]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
terminal-util: add extra validity checks that we operate on a TTY before doing so
[thirdparty/systemd.git] / src / basic / terminal-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <linux/kd.h>
7 #include <linux/tiocl.h>
8 #include <linux/vt.h>
9 #include <poll.h>
10 #include <signal.h>
11 #include <stdarg.h>
12 #include <stddef.h>
13 #include <stdlib.h>
14 #include <sys/inotify.h>
15 #include <sys/ioctl.h>
16 #include <sys/sysmacros.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/utsname.h>
20 #include <termios.h>
21 #include <unistd.h>
22
23 #include "alloc-util.h"
24 #include "copy.h"
25 #include "def.h"
26 #include "env-util.h"
27 #include "fd-util.h"
28 #include "fileio.h"
29 #include "fs-util.h"
30 #include "io-util.h"
31 #include "log.h"
32 #include "macro.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"
41 #include "strv.h"
42 #include "terminal-util.h"
43 #include "time-util.h"
44 #include "user-util.h"
45 #include "util.h"
46
47 static volatile unsigned cached_columns = 0;
48 static volatile unsigned cached_lines = 0;
49
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;
53
54 int chvt(int vt) {
55 _cleanup_close_ int fd = -1;
56
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. */
59
60 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
61 if (fd < 0)
62 return -errno;
63
64 if (vt <= 0) {
65 int tiocl[2] = {
66 TIOCL_GETKMSGREDIRECT,
67 0
68 };
69
70 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
71 return -errno;
72
73 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
74 }
75
76 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
77 return -errno;
78
79 return 0;
80 }
81
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;
85 int r, fd;
86
87 assert(f);
88 assert(ret);
89
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
92 * nicely.) */
93 fd = fileno(f);
94 if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
95 struct termios new_termios = old_termios;
96
97 new_termios.c_lflag &= ~ICANON;
98 new_termios.c_cc[VMIN] = 1;
99 new_termios.c_cc[VTIME] = 0;
100
101 if (tcsetattr(fd, TCSADRAIN, &new_termios) >= 0) {
102 char c;
103
104 if (t != USEC_INFINITY) {
105 if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
106 (void) tcsetattr(fd, TCSADRAIN, &old_termios);
107 return -ETIMEDOUT;
108 }
109 }
110
111 r = safe_fgetc(f, &c);
112 (void) tcsetattr(fd, TCSADRAIN, &old_termios);
113 if (r < 0)
114 return r;
115 if (r == 0)
116 return -EIO;
117
118 if (need_nl)
119 *need_nl = c != '\n';
120
121 *ret = c;
122 return 0;
123 }
124 }
125
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 */
131
132 if (fd_wait_for_event(fd, POLLIN, t) <= 0)
133 return -ETIMEDOUT;
134 }
135
136 /* If this is not a terminal, then read a full line instead */
137
138 r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
139 if (r < 0)
140 return r;
141 if (r == 0)
142 return -EIO;
143
144 if (strlen(line) != 1)
145 return -EBADMSG;
146
147 if (need_nl)
148 *need_nl = false;
149
150 *ret = line[0];
151 return 0;
152 }
153
154 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
155
156 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
157 int r;
158
159 assert(ret);
160 assert(replies);
161 assert(fmt);
162
163 for (;;) {
164 va_list ap;
165 char c;
166 bool need_nl = true;
167
168 fputs(ansi_highlight(), stdout);
169
170 putchar('\r');
171
172 va_start(ap, fmt);
173 vprintf(fmt, ap);
174 va_end(ap);
175
176 fputs(ansi_normal(), stdout);
177
178 fflush(stdout);
179
180 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
181 if (r < 0) {
182
183 if (r == -ETIMEDOUT)
184 continue;
185
186 if (r == -EBADMSG) {
187 puts("Bad input, please try again.");
188 continue;
189 }
190
191 putchar('\n');
192 return r;
193 }
194
195 if (need_nl)
196 putchar('\n');
197
198 if (strchr(replies, c)) {
199 *ret = c;
200 return 0;
201 }
202
203 puts("Read unexpected character, please try again.");
204 }
205 }
206
207 int ask_string(char **ret, const char *text, ...) {
208 _cleanup_free_ char *line = NULL;
209 va_list ap;
210 int r;
211
212 assert(ret);
213 assert(text);
214
215 fputs(ansi_highlight(), stdout);
216
217 va_start(ap, text);
218 vprintf(text, ap);
219 va_end(ap);
220
221 fputs(ansi_normal(), stdout);
222
223 fflush(stdout);
224
225 r = read_line(stdin, LONG_LINE_MAX, &line);
226 if (r < 0)
227 return r;
228 if (r == 0)
229 return -EIO;
230
231 *ret = TAKE_PTR(line);
232 return 0;
233 }
234
235 int reset_terminal_fd(int fd, bool switch_to_text) {
236 struct termios termios;
237 int r = 0;
238
239 /* Set terminal to some sane defaults */
240
241 assert(fd >= 0);
242
243 if (isatty(fd) < 1)
244 return log_debug_errno(errno, "Asked to reset a terminal that actually isn't a terminal: %m");
245
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. */
248
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");
252
253 /* Switch to text mode */
254 if (switch_to_text)
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");
257
258
259 /* Set default keyboard mode */
260 (void) vt_reset_keyboard(fd);
261
262 if (tcgetattr(fd, &termios) < 0) {
263 r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
264 goto finish;
265 }
266
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 */
270
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;
276
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;
290
291 termios.c_cc[VTIME] = 0;
292 termios.c_cc[VMIN] = 1;
293
294 if (tcsetattr(fd, TCSANOW, &termios) < 0)
295 r = -errno;
296
297 finish:
298 /* Just in case, flush all crap out */
299 (void) tcflush(fd, TCIOFLUSH);
300
301 return r;
302 }
303
304 int reset_terminal(const char *name) {
305 _cleanup_close_ int fd = -1;
306
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
309 * configured. */
310
311 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
312 if (fd < 0)
313 return fd;
314
315 return reset_terminal_fd(fd, true);
316 }
317
318 int open_terminal(const char *name, int mode) {
319 unsigned c = 0;
320 int fd;
321
322 /*
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.
327 *
328 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
329 */
330
331 if (mode & O_CREAT)
332 return -EINVAL;
333
334 for (;;) {
335 fd = open(name, mode, 0);
336 if (fd >= 0)
337 break;
338
339 if (errno != EIO)
340 return -errno;
341
342 /* Max 1s in total */
343 if (c >= 20)
344 return -errno;
345
346 usleep(50 * USEC_PER_MSEC);
347 c++;
348 }
349
350 if (isatty(fd) <= 0) {
351 safe_close(fd);
352 return -ENOTTY;
353 }
354
355 return fd;
356 }
357
358 int acquire_terminal(
359 const char *name,
360 AcquireTerminalFlags flags,
361 usec_t timeout) {
362
363 _cleanup_close_ int notify = -1, fd = -1;
364 usec_t ts = USEC_INFINITY;
365 int r, wd = -1;
366
367 assert(name);
368 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
369
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.
372 *
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.) */
378
379 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
380 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
381 if (notify < 0)
382 return -errno;
383
384 wd = inotify_add_watch(notify, name, IN_CLOSE);
385 if (wd < 0)
386 return -errno;
387
388 if (timeout != USEC_INFINITY)
389 ts = now(CLOCK_MONOTONIC);
390 }
391
392 for (;;) {
393 struct sigaction sa_old, sa_new = {
394 .sa_handler = SIG_IGN,
395 .sa_flags = SA_RESTART,
396 };
397
398 if (notify >= 0) {
399 r = flush_fd(notify);
400 if (r < 0)
401 return r;
402 }
403
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);
407 if (fd < 0)
408 return fd;
409
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);
412
413 /* First, try to get the tty */
414 r = ioctl(fd, TIOCSCTTY,
415 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
416
417 /* Reset signal handler to old value */
418 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
419
420 /* Success? Exit the loop now! */
421 if (r >= 0)
422 break;
423
424 /* Any failure besides -EPERM? Fail, regardless of the mode. */
425 if (r != -EPERM)
426 return r;
427
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. */
431 break;
432
433 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
434 return r;
435
436 assert(notify >= 0);
437 assert(wd >= 0);
438
439 for (;;) {
440 union inotify_event_buffer buffer;
441 struct inotify_event *e;
442 ssize_t l;
443
444 if (timeout != USEC_INFINITY) {
445 usec_t n;
446
447 assert(ts != USEC_INFINITY);
448
449 n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
450 if (n >= timeout)
451 return -ETIMEDOUT;
452
453 r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
454 if (r < 0)
455 return r;
456 if (r == 0)
457 return -ETIMEDOUT;
458 }
459
460 l = read(notify, &buffer, sizeof(buffer));
461 if (l < 0) {
462 if (IN_SET(errno, EINTR, EAGAIN))
463 continue;
464
465 return -errno;
466 }
467
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. */
470 break;
471
472 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
473 return -EIO;
474 }
475
476 break;
477 }
478
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. */
481 fd = safe_close(fd);
482 }
483
484 return TAKE_FD(fd);
485 }
486
487 int release_terminal(void) {
488 static const struct sigaction sa_new = {
489 .sa_handler = SIG_IGN,
490 .sa_flags = SA_RESTART,
491 };
492
493 _cleanup_close_ int fd = -1;
494 struct sigaction sa_old;
495 int r;
496
497 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
498 if (fd < 0)
499 return -errno;
500
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);
504
505 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
506
507 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
508
509 return r;
510 }
511
512 int terminal_vhangup_fd(int fd) {
513 assert(fd >= 0);
514
515 if (ioctl(fd, TIOCVHANGUP) < 0)
516 return -errno;
517
518 return 0;
519 }
520
521 int terminal_vhangup(const char *name) {
522 _cleanup_close_ int fd = -1;
523
524 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
525 if (fd < 0)
526 return fd;
527
528 return terminal_vhangup_fd(fd);
529 }
530
531 int vt_disallocate(const char *name) {
532 const char *e;
533 int r;
534
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). */
538
539 e = path_startswith(name, "/dev/");
540 if (!e)
541 return -EINVAL;
542
543 if (tty_is_vc(name)) {
544 _cleanup_close_ int fd = -1;
545 unsigned u;
546 const char *n;
547
548 n = startswith(e, "tty");
549 if (!n)
550 return -EINVAL;
551
552 r = safe_atou(n, &u);
553 if (r < 0)
554 return r;
555
556 if (u <= 0)
557 return -EINVAL;
558
559 /* Try to deallocate */
560 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
561 if (fd < 0)
562 return fd;
563
564 r = ioctl(fd, VT_DISALLOCATE, u);
565 if (r >= 0)
566 return 0;
567 if (errno != EBUSY)
568 return -errno;
569 }
570
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. */
573
574 _cleanup_close_ int fd2 = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
575 if (fd2 < 0)
576 return fd2;
577
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 */
582 10, false);
583 return 0;
584 }
585
586 int make_console_stdio(void) {
587 int fd, r;
588
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. */
592
593 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
594 if (fd < 0) {
595 log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
596
597 r = make_null_stdio();
598 if (r < 0)
599 return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
600
601 } else {
602 r = reset_terminal_fd(fd, true);
603 if (r < 0)
604 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
605
606 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
607 if (r < 0)
608 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
609 }
610
611 reset_terminal_feature_caches();
612 return 0;
613 }
614
615 bool tty_is_vc(const char *tty) {
616 assert(tty);
617
618 return vtnr_from_tty(tty) >= 0;
619 }
620
621 bool tty_is_console(const char *tty) {
622 assert(tty);
623
624 return streq(skip_dev_prefix(tty), "console");
625 }
626
627 int vtnr_from_tty(const char *tty) {
628 int i, r;
629
630 assert(tty);
631
632 tty = skip_dev_prefix(tty);
633
634 if (!startswith(tty, "tty") )
635 return -EINVAL;
636
637 if (tty[3] < '0' || tty[3] > '9')
638 return -EINVAL;
639
640 r = safe_atoi(tty+3, &i);
641 if (r < 0)
642 return r;
643
644 if (i < 0 || i > 63)
645 return -EINVAL;
646
647 return i;
648 }
649
650 int resolve_dev_console(char **ret) {
651 _cleanup_free_ char *active = NULL;
652 char *tty;
653 int r;
654
655 assert(ret);
656
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) */
659
660 if (path_is_read_only_fs("/sys") > 0)
661 return -ENOMEDIUM;
662
663 r = read_one_line_file("/sys/class/tty/console/active", &active);
664 if (r < 0)
665 return r;
666
667 /* If multiple log outputs are configured the last one is what /dev/console points to */
668 tty = strrchr(active, ' ');
669 if (tty)
670 tty++;
671 else
672 tty = active;
673
674 if (streq(tty, "tty0")) {
675 active = mfree(active);
676
677 /* Get the active VC (e.g. tty1) */
678 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
679 if (r < 0)
680 return r;
681
682 tty = active;
683 }
684
685 if (tty == active)
686 *ret = TAKE_PTR(active);
687 else {
688 char *tmp;
689
690 tmp = strdup(tty);
691 if (!tmp)
692 return -ENOMEM;
693
694 *ret = tmp;
695 }
696
697 return 0;
698 }
699
700 int get_kernel_consoles(char ***ret) {
701 _cleanup_strv_free_ char **l = NULL;
702 _cleanup_free_ char *line = NULL;
703 const char *p;
704 int r;
705
706 assert(ret);
707
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)
711 goto fallback;
712
713 r = read_one_line_file("/sys/class/tty/console/active", &line);
714 if (r < 0)
715 return r;
716
717 p = line;
718 for (;;) {
719 _cleanup_free_ char *tty = NULL, *path = NULL;
720
721 r = extract_first_word(&p, &tty, NULL, 0);
722 if (r < 0)
723 return r;
724 if (r == 0)
725 break;
726
727 if (streq(tty, "tty0")) {
728 tty = mfree(tty);
729 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
730 if (r < 0)
731 return r;
732 }
733
734 path = path_join("/dev", tty);
735 if (!path)
736 return -ENOMEM;
737
738 if (access(path, F_OK) < 0) {
739 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
740 continue;
741 }
742
743 r = strv_consume(&l, TAKE_PTR(path));
744 if (r < 0)
745 return r;
746 }
747
748 if (strv_isempty(l)) {
749 log_debug("No devices found for system console");
750 goto fallback;
751 }
752
753 *ret = TAKE_PTR(l);
754
755 return 0;
756
757 fallback:
758 r = strv_extend(&l, "/dev/console");
759 if (r < 0)
760 return r;
761
762 *ret = TAKE_PTR(l);
763
764 return 0;
765 }
766
767 bool tty_is_vc_resolve(const char *tty) {
768 _cleanup_free_ char *resolved = NULL;
769
770 assert(tty);
771
772 tty = skip_dev_prefix(tty);
773
774 if (streq(tty, "console")) {
775 if (resolve_dev_console(&resolved) < 0)
776 return false;
777
778 tty = resolved;
779 }
780
781 return tty_is_vc(tty);
782 }
783
784 const char *default_term_for_tty(const char *tty) {
785 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
786 }
787
788 int fd_columns(int fd) {
789 struct winsize ws = {};
790
791 if (fd < 0)
792 return -EBADF;
793
794 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
795 return -errno;
796
797 if (ws.ws_col <= 0)
798 return -EIO;
799
800 return ws.ws_col;
801 }
802
803 unsigned columns(void) {
804 const char *e;
805 int c;
806
807 if (cached_columns > 0)
808 return cached_columns;
809
810 c = 0;
811 e = getenv("COLUMNS");
812 if (e)
813 (void) safe_atoi(e, &c);
814
815 if (c <= 0 || c > USHRT_MAX) {
816 c = fd_columns(STDOUT_FILENO);
817 if (c <= 0)
818 c = 80;
819 }
820
821 cached_columns = c;
822 return cached_columns;
823 }
824
825 int fd_lines(int fd) {
826 struct winsize ws = {};
827
828 if (fd < 0)
829 return -EBADF;
830
831 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
832 return -errno;
833
834 if (ws.ws_row <= 0)
835 return -EIO;
836
837 return ws.ws_row;
838 }
839
840 unsigned lines(void) {
841 const char *e;
842 int l;
843
844 if (cached_lines > 0)
845 return cached_lines;
846
847 l = 0;
848 e = getenv("LINES");
849 if (e)
850 (void) safe_atoi(e, &l);
851
852 if (l <= 0 || l > USHRT_MAX) {
853 l = fd_lines(STDOUT_FILENO);
854 if (l <= 0)
855 l = 24;
856 }
857
858 cached_lines = l;
859 return cached_lines;
860 }
861
862 /* intended to be used as a SIGWINCH sighandler */
863 void columns_lines_cache_reset(int signum) {
864 cached_columns = 0;
865 cached_lines = 0;
866 }
867
868 void reset_terminal_feature_caches(void) {
869 cached_columns = 0;
870 cached_lines = 0;
871
872 cached_color_mode = _COLOR_INVALID;
873 cached_underline_enabled = -1;
874 cached_on_tty = -1;
875 }
876
877 bool on_tty(void) {
878
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. */
884
885 if (cached_on_tty < 0)
886 cached_on_tty =
887 isatty(STDOUT_FILENO) > 0 &&
888 isatty(STDERR_FILENO) > 0;
889
890 return cached_on_tty;
891 }
892
893 int getttyname_malloc(int fd, char **ret) {
894 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
895 int r;
896
897 assert(fd >= 0);
898 assert(ret);
899
900 r = ttyname_r(fd, path, sizeof path); /* positive error */
901 assert(r >= 0);
902 if (r == ERANGE)
903 return -ENAMETOOLONG;
904 if (r > 0)
905 return -r;
906
907 c = strdup(skip_dev_prefix(path));
908 if (!c)
909 return -ENOMEM;
910
911 *ret = c;
912 return 0;
913 }
914
915 int getttyname_harder(int fd, char **ret) {
916 _cleanup_free_ char *s = NULL;
917 int r;
918
919 r = getttyname_malloc(fd, &s);
920 if (r < 0)
921 return r;
922
923 if (streq(s, "tty"))
924 return get_ctty(0, NULL, ret);
925
926 *ret = TAKE_PTR(s);
927 return 0;
928 }
929
930 int get_ctty_devnr(pid_t pid, dev_t *d) {
931 int r;
932 _cleanup_free_ char *line = NULL;
933 const char *p;
934 unsigned long ttynr;
935
936 assert(pid >= 0);
937
938 p = procfs_file_alloca(pid, "stat");
939 r = read_one_line_file(p, &line);
940 if (r < 0)
941 return r;
942
943 p = strrchr(line, ')');
944 if (!p)
945 return -EIO;
946
947 p++;
948
949 if (sscanf(p, " "
950 "%*c " /* state */
951 "%*d " /* ppid */
952 "%*d " /* pgrp */
953 "%*d " /* session */
954 "%lu ", /* ttynr */
955 &ttynr) != 1)
956 return -EIO;
957
958 if (major(ttynr) == 0 && minor(ttynr) == 0)
959 return -ENXIO;
960
961 if (d)
962 *d = (dev_t) ttynr;
963
964 return 0;
965 }
966
967 int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
968 _cleanup_free_ char *fn = NULL, *b = NULL;
969 dev_t devnr;
970 int r;
971
972 r = get_ctty_devnr(pid, &devnr);
973 if (r < 0)
974 return r;
975
976 r = device_path_make_canonical(S_IFCHR, devnr, &fn);
977 if (r < 0) {
978 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
979 return r;
980
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
986 * this. */
987
988 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
989 return -ENOMEM;
990 } else {
991 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
992 * something vaguely useful. */
993
994 r = device_path_make_major_minor(S_IFCHR, devnr, &fn);
995 if (r < 0)
996 return r;
997 }
998 }
999
1000 if (!b) {
1001 const char *w;
1002
1003 w = path_startswith(fn, "/dev/");
1004 if (w) {
1005 b = strdup(w);
1006 if (!b)
1007 return -ENOMEM;
1008 } else
1009 b = TAKE_PTR(fn);
1010 }
1011
1012 if (ret)
1013 *ret = TAKE_PTR(b);
1014
1015 if (ret_devnr)
1016 *ret_devnr = devnr;
1017
1018 return 0;
1019 }
1020
1021 int ptsname_malloc(int fd, char **ret) {
1022 size_t l = 100;
1023
1024 assert(fd >= 0);
1025 assert(ret);
1026
1027 for (;;) {
1028 char *c;
1029
1030 c = new(char, l);
1031 if (!c)
1032 return -ENOMEM;
1033
1034 if (ptsname_r(fd, c, l) == 0) {
1035 *ret = c;
1036 return 0;
1037 }
1038 if (errno != ERANGE) {
1039 free(c);
1040 return -errno;
1041 }
1042
1043 free(c);
1044
1045 if (l > SIZE_MAX / 2)
1046 return -ENOMEM;
1047
1048 l *= 2;
1049 }
1050 }
1051
1052 int openpt_allocate(int flags, char **ret_slave) {
1053 _cleanup_close_ int fd = -1;
1054 _cleanup_free_ char *p = NULL;
1055 int r;
1056
1057 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1058 if (fd < 0)
1059 return -errno;
1060
1061 if (ret_slave) {
1062 r = ptsname_malloc(fd, &p);
1063 if (r < 0)
1064 return r;
1065
1066 if (!path_startswith(p, "/dev/pts/"))
1067 return -EINVAL;
1068 }
1069
1070 if (unlockpt(fd) < 0)
1071 return -errno;
1072
1073 if (ret_slave)
1074 *ret_slave = TAKE_PTR(p);
1075
1076 return TAKE_FD(fd);
1077 }
1078
1079 static int ptsname_namespace(int pty, char **ret) {
1080 int no = -1, r;
1081
1082 /* Like ptsname(), but doesn't assume that the path is
1083 * accessible in the local namespace. */
1084
1085 r = ioctl(pty, TIOCGPTN, &no);
1086 if (r < 0)
1087 return -errno;
1088
1089 if (no < 0)
1090 return -EIO;
1091
1092 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1093 return -ENOMEM;
1094
1095 return 0;
1096 }
1097
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 };
1101 pid_t child;
1102 int r;
1103
1104 assert(pid > 0);
1105
1106 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1107 if (r < 0)
1108 return r;
1109
1110 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1111 return -errno;
1112
1113 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1114 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1115 if (r < 0)
1116 return r;
1117 if (r == 0) {
1118 pair[0] = safe_close(pair[0]);
1119
1120 fd = openpt_allocate(flags, NULL);
1121 if (fd < 0)
1122 _exit(EXIT_FAILURE);
1123
1124 if (send_one_fd(pair[1], fd, 0) < 0)
1125 _exit(EXIT_FAILURE);
1126
1127 _exit(EXIT_SUCCESS);
1128 }
1129
1130 pair[1] = safe_close(pair[1]);
1131
1132 r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
1133 if (r < 0)
1134 return r;
1135 if (r != EXIT_SUCCESS)
1136 return -EIO;
1137
1138 fd = receive_one_fd(pair[0], 0);
1139 if (fd < 0)
1140 return fd;
1141
1142 if (ret_slave) {
1143 r = ptsname_namespace(fd, ret_slave);
1144 if (r < 0)
1145 return r;
1146 }
1147
1148 return TAKE_FD(fd);
1149 }
1150
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 };
1154 pid_t child;
1155 int r;
1156
1157 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1158 if (r < 0)
1159 return r;
1160
1161 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1162 return -errno;
1163
1164 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1165 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1166 if (r < 0)
1167 return r;
1168 if (r == 0) {
1169 int master;
1170
1171 pair[0] = safe_close(pair[0]);
1172
1173 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1174 if (master < 0)
1175 _exit(EXIT_FAILURE);
1176
1177 if (send_one_fd(pair[1], master, 0) < 0)
1178 _exit(EXIT_FAILURE);
1179
1180 _exit(EXIT_SUCCESS);
1181 }
1182
1183 pair[1] = safe_close(pair[1]);
1184
1185 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
1186 if (r < 0)
1187 return r;
1188 if (r != EXIT_SUCCESS)
1189 return -EIO;
1190
1191 return receive_one_fd(pair[0], 0);
1192 }
1193
1194 static bool getenv_terminal_is_dumb(void) {
1195 const char *e;
1196
1197 e = getenv("TERM");
1198 if (!e)
1199 return true;
1200
1201 return streq(e, "dumb");
1202 }
1203
1204 bool terminal_is_dumb(void) {
1205 if (!on_tty())
1206 return true;
1207
1208 return getenv_terminal_is_dumb();
1209 }
1210
1211 static ColorMode parse_systemd_colors(void) {
1212 const char *e;
1213 int r;
1214
1215 e = getenv("SYSTEMD_COLORS");
1216 if (!e)
1217 return _COLOR_INVALID;
1218 if (streq(e, "16"))
1219 return COLOR_16;
1220 if (streq(e, "256"))
1221 return COLOR_256;
1222 r = parse_boolean(e);
1223 if (r >= 0)
1224 return r > 0 ? COLOR_ON : COLOR_OFF;
1225 return _COLOR_INVALID;
1226 }
1227
1228 ColorMode get_color_mode(void) {
1229
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. */
1237 ColorMode m;
1238
1239 if (cached_color_mode < 0) {
1240 m = parse_systemd_colors();
1241 if (m >= 0)
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;
1246
1247 else if (getpid_cached() == 1)
1248 /* PID1 outputs to the console without holding it open all the time.
1249 *
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;
1257 else
1258 cached_color_mode = terminal_is_dumb() ? COLOR_OFF : COLOR_256;
1259 }
1260
1261 return cached_color_mode;
1262 }
1263
1264 bool dev_console_colors_enabled(void) {
1265 _cleanup_free_ char *s = NULL;
1266 ColorMode m;
1267
1268 /* Returns true if we assume that color is supported on /dev/console.
1269 *
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. */
1274
1275 m = parse_systemd_colors();
1276 if (m >= 0)
1277 return m;
1278
1279 if (getenv("NO_COLOR"))
1280 return false;
1281
1282 if (getenv_for_pid(1, "TERM", &s) <= 0)
1283 (void) proc_cmdline_get_key("TERM", 0, &s);
1284
1285 return !streq_ptr(s, "dumb");
1286 }
1287
1288 bool underline_enabled(void) {
1289
1290 if (cached_underline_enabled < 0) {
1291
1292 /* The Linux console doesn't support underlining, turn it off, but only there. */
1293
1294 if (colors_enabled())
1295 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1296 else
1297 cached_underline_enabled = false;
1298 }
1299
1300 return cached_underline_enabled;
1301 }
1302
1303 int vt_default_utf8(void) {
1304 _cleanup_free_ char *b = NULL;
1305 int r;
1306
1307 /* Read the default VT UTF8 setting from the kernel */
1308
1309 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1310 if (r < 0)
1311 return r;
1312
1313 return parse_boolean(b);
1314 }
1315
1316 int vt_reset_keyboard(int fd) {
1317 int kb;
1318
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;
1321
1322 if (ioctl(fd, KDSKBMODE, kb) < 0)
1323 return -errno;
1324
1325 return 0;
1326 }
1327
1328 int vt_restore(int fd) {
1329 static const struct vt_mode mode = {
1330 .mode = VT_AUTO,
1331 };
1332 int r, q = 0;
1333
1334 if (isatty(fd) < 1)
1335 return log_debug_errno(errno, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1336
1337 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
1338 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1339
1340 r = vt_reset_keyboard(fd);
1341 if (r < 0) {
1342 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1343 if (q >= 0)
1344 q = r;
1345 }
1346
1347 if (ioctl(fd, VT_SETMODE, &mode) < 0) {
1348 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1349 if (q >= 0)
1350 q = -errno;
1351 }
1352
1353 r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
1354 if (r < 0) {
1355 log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m");
1356 if (q >= 0)
1357 q = r;
1358 }
1359
1360 return q;
1361 }
1362
1363 int vt_release(int fd, bool restore) {
1364 assert(fd >= 0);
1365
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. */
1369
1370 if (isatty(fd) < 1)
1371 return log_debug_errno(errno, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1372
1373 if (ioctl(fd, VT_RELDISP, 1) < 0)
1374 return -errno;
1375
1376 if (restore)
1377 return vt_restore(fd);
1378
1379 return 0;
1380 }
1381
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. */
1385
1386 if (priority <= LOG_ERR) {
1387 if (on)
1388 *on = ansi_highlight_red();
1389 if (off)
1390 *off = ansi_normal();
1391 if (highlight)
1392 *highlight = ansi_highlight();
1393
1394 } else if (priority <= LOG_WARNING) {
1395 if (on)
1396 *on = ansi_highlight_yellow();
1397 if (off)
1398 *off = ansi_normal();
1399 if (highlight)
1400 *highlight = ansi_highlight();
1401
1402 } else if (priority <= LOG_NOTICE) {
1403 if (on)
1404 *on = ansi_highlight();
1405 if (off)
1406 *off = ansi_normal();
1407 if (highlight)
1408 *highlight = ansi_highlight_red();
1409
1410 } else if (priority >= LOG_DEBUG) {
1411 if (on)
1412 *on = ansi_grey();
1413 if (off)
1414 *off = ansi_normal();
1415 if (highlight)
1416 *highlight = ansi_highlight_red();
1417 }
1418 }