]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
basic: move acquire_data_fd() and fd_duplicate_data_fd() to new data-fd-util.c
[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 "def.h"
25 #include "env-util.h"
26 #include "fd-util.h"
27 #include "fileio.h"
28 #include "fs-util.h"
29 #include "io-util.h"
30 #include "log.h"
31 #include "macro.h"
32 #include "namespace-util.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "proc-cmdline.h"
36 #include "process-util.h"
37 #include "socket-util.h"
38 #include "stat-util.h"
39 #include "stdio-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 _cleanup_close_ int fd = -1;
320 unsigned c = 0;
321
322 /*
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
325 * times.
326 *
327 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
328 */
329
330 if (mode & O_CREAT)
331 return -EINVAL;
332
333 for (;;) {
334 fd = open(name, mode, 0);
335 if (fd >= 0)
336 break;
337
338 if (errno != EIO)
339 return -errno;
340
341 /* Max 1s in total */
342 if (c >= 20)
343 return -errno;
344
345 (void) usleep(50 * USEC_PER_MSEC);
346 c++;
347 }
348
349 if (isatty(fd) < 1)
350 return negative_errno();
351
352 return TAKE_FD(fd);
353 }
354
355 int acquire_terminal(
356 const char *name,
357 AcquireTerminalFlags flags,
358 usec_t timeout) {
359
360 _cleanup_close_ int notify = -1, fd = -1;
361 usec_t ts = USEC_INFINITY;
362 int r, wd = -1;
363
364 assert(name);
365 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
366
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.
369 *
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.) */
375
376 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
377 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
378 if (notify < 0)
379 return -errno;
380
381 wd = inotify_add_watch(notify, name, IN_CLOSE);
382 if (wd < 0)
383 return -errno;
384
385 if (timeout != USEC_INFINITY)
386 ts = now(CLOCK_MONOTONIC);
387 }
388
389 for (;;) {
390 struct sigaction sa_old, sa_new = {
391 .sa_handler = SIG_IGN,
392 .sa_flags = SA_RESTART,
393 };
394
395 if (notify >= 0) {
396 r = flush_fd(notify);
397 if (r < 0)
398 return r;
399 }
400
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);
404 if (fd < 0)
405 return fd;
406
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);
409
410 /* First, try to get the tty */
411 r = ioctl(fd, TIOCSCTTY,
412 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
413
414 /* Reset signal handler to old value */
415 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
416
417 /* Success? Exit the loop now! */
418 if (r >= 0)
419 break;
420
421 /* Any failure besides -EPERM? Fail, regardless of the mode. */
422 if (r != -EPERM)
423 return r;
424
425 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
426 * into a success. Note that EPERM is also returned if we
427 * already are the owner of the TTY. */
428 break;
429
430 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
431 return r;
432
433 assert(notify >= 0);
434 assert(wd >= 0);
435
436 for (;;) {
437 union inotify_event_buffer buffer;
438 struct inotify_event *e;
439 ssize_t l;
440
441 if (timeout != USEC_INFINITY) {
442 usec_t n;
443
444 assert(ts != USEC_INFINITY);
445
446 n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
447 if (n >= timeout)
448 return -ETIMEDOUT;
449
450 r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
451 if (r < 0)
452 return r;
453 if (r == 0)
454 return -ETIMEDOUT;
455 }
456
457 l = read(notify, &buffer, sizeof(buffer));
458 if (l < 0) {
459 if (IN_SET(errno, EINTR, EAGAIN))
460 continue;
461
462 return -errno;
463 }
464
465 FOREACH_INOTIFY_EVENT(e, buffer, l) {
466 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
467 break;
468
469 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
470 return -EIO;
471 }
472
473 break;
474 }
475
476 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
477 * we do this after sleeping, so that we don't enter an endless loop. */
478 fd = safe_close(fd);
479 }
480
481 return TAKE_FD(fd);
482 }
483
484 int release_terminal(void) {
485 static const struct sigaction sa_new = {
486 .sa_handler = SIG_IGN,
487 .sa_flags = SA_RESTART,
488 };
489
490 _cleanup_close_ int fd = -1;
491 struct sigaction sa_old;
492 int r;
493
494 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
495 if (fd < 0)
496 return -errno;
497
498 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
499 * by our own TIOCNOTTY */
500 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
501
502 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
503
504 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
505
506 return r;
507 }
508
509 int terminal_vhangup_fd(int fd) {
510 assert(fd >= 0);
511
512 if (ioctl(fd, TIOCVHANGUP) < 0)
513 return -errno;
514
515 return 0;
516 }
517
518 int terminal_vhangup(const char *name) {
519 _cleanup_close_ int fd = -1;
520
521 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
522 if (fd < 0)
523 return fd;
524
525 return terminal_vhangup_fd(fd);
526 }
527
528 int vt_disallocate(const char *name) {
529 const char *e;
530 int r;
531
532 /* Deallocate the VT if possible. If not possible
533 * (i.e. because it is the active one), at least clear it
534 * entirely (including the scrollback buffer). */
535
536 e = path_startswith(name, "/dev/");
537 if (!e)
538 return -EINVAL;
539
540 if (tty_is_vc(name)) {
541 _cleanup_close_ int fd = -1;
542 unsigned u;
543 const char *n;
544
545 n = startswith(e, "tty");
546 if (!n)
547 return -EINVAL;
548
549 r = safe_atou(n, &u);
550 if (r < 0)
551 return r;
552
553 if (u <= 0)
554 return -EINVAL;
555
556 /* Try to deallocate */
557 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
558 if (fd < 0)
559 return fd;
560
561 r = ioctl(fd, VT_DISALLOCATE, u);
562 if (r >= 0)
563 return 0;
564 if (errno != EBUSY)
565 return -errno;
566 }
567
568 /* So this is not a VT (in which case we cannot deallocate it),
569 * or we failed to deallocate. Let's at least clear the screen. */
570
571 _cleanup_close_ int fd2 = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
572 if (fd2 < 0)
573 return fd2;
574
575 (void) loop_write(fd2,
576 "\033[r" /* clear scrolling region */
577 "\033[H" /* move home */
578 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
579 10, false);
580 return 0;
581 }
582
583 int make_console_stdio(void) {
584 int fd, r;
585
586 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
587 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
588 * is specified on the kernel command line. */
589
590 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
591 if (fd < 0) {
592 log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
593
594 r = make_null_stdio();
595 if (r < 0)
596 return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
597
598 } else {
599 r = reset_terminal_fd(fd, true);
600 if (r < 0)
601 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
602
603 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
604 if (r < 0)
605 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
606 }
607
608 reset_terminal_feature_caches();
609 return 0;
610 }
611
612 bool tty_is_vc(const char *tty) {
613 assert(tty);
614
615 return vtnr_from_tty(tty) >= 0;
616 }
617
618 bool tty_is_console(const char *tty) {
619 assert(tty);
620
621 return streq(skip_dev_prefix(tty), "console");
622 }
623
624 int vtnr_from_tty(const char *tty) {
625 int i, r;
626
627 assert(tty);
628
629 tty = skip_dev_prefix(tty);
630
631 if (!startswith(tty, "tty") )
632 return -EINVAL;
633
634 if (tty[3] < '0' || tty[3] > '9')
635 return -EINVAL;
636
637 r = safe_atoi(tty+3, &i);
638 if (r < 0)
639 return r;
640
641 if (i < 0 || i > 63)
642 return -EINVAL;
643
644 return i;
645 }
646
647 int resolve_dev_console(char **ret) {
648 _cleanup_free_ char *active = NULL;
649 char *tty;
650 int r;
651
652 assert(ret);
653
654 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
655 * sign for container setups) */
656
657 if (path_is_read_only_fs("/sys") > 0)
658 return -ENOMEDIUM;
659
660 r = read_one_line_file("/sys/class/tty/console/active", &active);
661 if (r < 0)
662 return r;
663
664 /* If multiple log outputs are configured the last one is what /dev/console points to */
665 tty = strrchr(active, ' ');
666 if (tty)
667 tty++;
668 else
669 tty = active;
670
671 if (streq(tty, "tty0")) {
672 active = mfree(active);
673
674 /* Get the active VC (e.g. tty1) */
675 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
676 if (r < 0)
677 return r;
678
679 tty = active;
680 }
681
682 if (tty == active)
683 *ret = TAKE_PTR(active);
684 else {
685 char *tmp;
686
687 tmp = strdup(tty);
688 if (!tmp)
689 return -ENOMEM;
690
691 *ret = tmp;
692 }
693
694 return 0;
695 }
696
697 int get_kernel_consoles(char ***ret) {
698 _cleanup_strv_free_ char **l = NULL;
699 _cleanup_free_ char *line = NULL;
700 const char *p;
701 int r;
702
703 assert(ret);
704
705 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
706 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
707 if (path_is_read_only_fs("/sys") > 0)
708 goto fallback;
709
710 r = read_one_line_file("/sys/class/tty/console/active", &line);
711 if (r < 0)
712 return r;
713
714 p = line;
715 for (;;) {
716 _cleanup_free_ char *tty = NULL, *path = NULL;
717
718 r = extract_first_word(&p, &tty, NULL, 0);
719 if (r < 0)
720 return r;
721 if (r == 0)
722 break;
723
724 if (streq(tty, "tty0")) {
725 tty = mfree(tty);
726 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
727 if (r < 0)
728 return r;
729 }
730
731 path = path_join("/dev", tty);
732 if (!path)
733 return -ENOMEM;
734
735 if (access(path, F_OK) < 0) {
736 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
737 continue;
738 }
739
740 r = strv_consume(&l, TAKE_PTR(path));
741 if (r < 0)
742 return r;
743 }
744
745 if (strv_isempty(l)) {
746 log_debug("No devices found for system console");
747 goto fallback;
748 }
749
750 *ret = TAKE_PTR(l);
751
752 return 0;
753
754 fallback:
755 r = strv_extend(&l, "/dev/console");
756 if (r < 0)
757 return r;
758
759 *ret = TAKE_PTR(l);
760
761 return 0;
762 }
763
764 bool tty_is_vc_resolve(const char *tty) {
765 _cleanup_free_ char *resolved = NULL;
766
767 assert(tty);
768
769 tty = skip_dev_prefix(tty);
770
771 if (streq(tty, "console")) {
772 if (resolve_dev_console(&resolved) < 0)
773 return false;
774
775 tty = resolved;
776 }
777
778 return tty_is_vc(tty);
779 }
780
781 const char *default_term_for_tty(const char *tty) {
782 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
783 }
784
785 int fd_columns(int fd) {
786 struct winsize ws = {};
787
788 if (fd < 0)
789 return -EBADF;
790
791 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
792 return -errno;
793
794 if (ws.ws_col <= 0)
795 return -EIO;
796
797 return ws.ws_col;
798 }
799
800 unsigned columns(void) {
801 const char *e;
802 int c;
803
804 if (cached_columns > 0)
805 return cached_columns;
806
807 c = 0;
808 e = getenv("COLUMNS");
809 if (e)
810 (void) safe_atoi(e, &c);
811
812 if (c <= 0 || c > USHRT_MAX) {
813 c = fd_columns(STDOUT_FILENO);
814 if (c <= 0)
815 c = 80;
816 }
817
818 cached_columns = c;
819 return cached_columns;
820 }
821
822 int fd_lines(int fd) {
823 struct winsize ws = {};
824
825 if (fd < 0)
826 return -EBADF;
827
828 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
829 return -errno;
830
831 if (ws.ws_row <= 0)
832 return -EIO;
833
834 return ws.ws_row;
835 }
836
837 unsigned lines(void) {
838 const char *e;
839 int l;
840
841 if (cached_lines > 0)
842 return cached_lines;
843
844 l = 0;
845 e = getenv("LINES");
846 if (e)
847 (void) safe_atoi(e, &l);
848
849 if (l <= 0 || l > USHRT_MAX) {
850 l = fd_lines(STDOUT_FILENO);
851 if (l <= 0)
852 l = 24;
853 }
854
855 cached_lines = l;
856 return cached_lines;
857 }
858
859 /* intended to be used as a SIGWINCH sighandler */
860 void columns_lines_cache_reset(int signum) {
861 cached_columns = 0;
862 cached_lines = 0;
863 }
864
865 void reset_terminal_feature_caches(void) {
866 cached_columns = 0;
867 cached_lines = 0;
868
869 cached_color_mode = _COLOR_INVALID;
870 cached_underline_enabled = -1;
871 cached_on_tty = -1;
872 }
873
874 bool on_tty(void) {
875
876 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
877 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
878 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
879 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
880 * terminal functionality when outputting stuff, even if the input is piped to us. */
881
882 if (cached_on_tty < 0)
883 cached_on_tty =
884 isatty(STDOUT_FILENO) > 0 &&
885 isatty(STDERR_FILENO) > 0;
886
887 return cached_on_tty;
888 }
889
890 int getttyname_malloc(int fd, char **ret) {
891 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
892 int r;
893
894 assert(fd >= 0);
895 assert(ret);
896
897 r = ttyname_r(fd, path, sizeof path); /* positive error */
898 assert(r >= 0);
899 if (r == ERANGE)
900 return -ENAMETOOLONG;
901 if (r > 0)
902 return -r;
903
904 c = strdup(skip_dev_prefix(path));
905 if (!c)
906 return -ENOMEM;
907
908 *ret = c;
909 return 0;
910 }
911
912 int getttyname_harder(int fd, char **ret) {
913 _cleanup_free_ char *s = NULL;
914 int r;
915
916 r = getttyname_malloc(fd, &s);
917 if (r < 0)
918 return r;
919
920 if (streq(s, "tty"))
921 return get_ctty(0, NULL, ret);
922
923 *ret = TAKE_PTR(s);
924 return 0;
925 }
926
927 int get_ctty_devnr(pid_t pid, dev_t *d) {
928 int r;
929 _cleanup_free_ char *line = NULL;
930 const char *p;
931 unsigned long ttynr;
932
933 assert(pid >= 0);
934
935 p = procfs_file_alloca(pid, "stat");
936 r = read_one_line_file(p, &line);
937 if (r < 0)
938 return r;
939
940 p = strrchr(line, ')');
941 if (!p)
942 return -EIO;
943
944 p++;
945
946 if (sscanf(p, " "
947 "%*c " /* state */
948 "%*d " /* ppid */
949 "%*d " /* pgrp */
950 "%*d " /* session */
951 "%lu ", /* ttynr */
952 &ttynr) != 1)
953 return -EIO;
954
955 if (major(ttynr) == 0 && minor(ttynr) == 0)
956 return -ENXIO;
957
958 if (d)
959 *d = (dev_t) ttynr;
960
961 return 0;
962 }
963
964 int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
965 char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
966 _cleanup_free_ char *buf = NULL;
967 const char *fn = NULL, *w;
968 dev_t devnr;
969 int r;
970
971 r = get_ctty_devnr(pid, &devnr);
972 if (r < 0)
973 return r;
974
975 r = device_path_make_canonical(S_IFCHR, devnr, &buf);
976 if (r < 0) {
977 struct stat st;
978
979 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
980 return r;
981
982 /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
983 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
984 * assume this is a PTY for a moment, and check if the device node this would then map to in
985 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
986 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
987 * the minor number of the pty. */
988 xsprintf(pty, "/dev/pts/%u", minor(devnr));
989
990 if (stat(pty, &st) < 0) {
991 if (errno != ENOENT)
992 return -errno;
993
994 } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
995 fn = pty;
996
997 if (!fn) {
998 /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
999 * symlink in /dev/char/. Let's return something vaguely useful. */
1000 r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
1001 if (r < 0)
1002 return r;
1003
1004 fn = buf;
1005 }
1006 } else
1007 fn = buf;
1008
1009 w = path_startswith(fn, "/dev/");
1010 if (!w)
1011 return -EINVAL;
1012
1013 if (ret) {
1014 _cleanup_free_ char *b = NULL;
1015
1016 b = strdup(w);
1017 if (!b)
1018 return -ENOMEM;
1019
1020 *ret = TAKE_PTR(b);
1021 }
1022
1023 if (ret_devnr)
1024 *ret_devnr = devnr;
1025
1026 return 0;
1027 }
1028
1029 int ptsname_malloc(int fd, char **ret) {
1030 size_t l = 100;
1031
1032 assert(fd >= 0);
1033 assert(ret);
1034
1035 for (;;) {
1036 char *c;
1037
1038 c = new(char, l);
1039 if (!c)
1040 return -ENOMEM;
1041
1042 if (ptsname_r(fd, c, l) == 0) {
1043 *ret = c;
1044 return 0;
1045 }
1046 if (errno != ERANGE) {
1047 free(c);
1048 return -errno;
1049 }
1050
1051 free(c);
1052
1053 if (l > SIZE_MAX / 2)
1054 return -ENOMEM;
1055
1056 l *= 2;
1057 }
1058 }
1059
1060 int openpt_allocate(int flags, char **ret_slave) {
1061 _cleanup_close_ int fd = -1;
1062 _cleanup_free_ char *p = NULL;
1063 int r;
1064
1065 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1066 if (fd < 0)
1067 return -errno;
1068
1069 if (ret_slave) {
1070 r = ptsname_malloc(fd, &p);
1071 if (r < 0)
1072 return r;
1073
1074 if (!path_startswith(p, "/dev/pts/"))
1075 return -EINVAL;
1076 }
1077
1078 if (unlockpt(fd) < 0)
1079 return -errno;
1080
1081 if (ret_slave)
1082 *ret_slave = TAKE_PTR(p);
1083
1084 return TAKE_FD(fd);
1085 }
1086
1087 static int ptsname_namespace(int pty, char **ret) {
1088 int no = -1, r;
1089
1090 /* Like ptsname(), but doesn't assume that the path is
1091 * accessible in the local namespace. */
1092
1093 r = ioctl(pty, TIOCGPTN, &no);
1094 if (r < 0)
1095 return -errno;
1096
1097 if (no < 0)
1098 return -EIO;
1099
1100 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1101 return -ENOMEM;
1102
1103 return 0;
1104 }
1105
1106 int openpt_allocate_in_namespace(pid_t pid, int flags, char **ret_slave) {
1107 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1, fd = -1;
1108 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1109 pid_t child;
1110 int r;
1111
1112 assert(pid > 0);
1113
1114 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1115 if (r < 0)
1116 return r;
1117
1118 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1119 return -errno;
1120
1121 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1122 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1123 if (r < 0)
1124 return r;
1125 if (r == 0) {
1126 pair[0] = safe_close(pair[0]);
1127
1128 fd = openpt_allocate(flags, NULL);
1129 if (fd < 0)
1130 _exit(EXIT_FAILURE);
1131
1132 if (send_one_fd(pair[1], fd, 0) < 0)
1133 _exit(EXIT_FAILURE);
1134
1135 _exit(EXIT_SUCCESS);
1136 }
1137
1138 pair[1] = safe_close(pair[1]);
1139
1140 r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
1141 if (r < 0)
1142 return r;
1143 if (r != EXIT_SUCCESS)
1144 return -EIO;
1145
1146 fd = receive_one_fd(pair[0], 0);
1147 if (fd < 0)
1148 return fd;
1149
1150 if (ret_slave) {
1151 r = ptsname_namespace(fd, ret_slave);
1152 if (r < 0)
1153 return r;
1154 }
1155
1156 return TAKE_FD(fd);
1157 }
1158
1159 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1160 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1161 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1162 pid_t child;
1163 int r;
1164
1165 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1166 if (r < 0)
1167 return r;
1168
1169 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1170 return -errno;
1171
1172 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1173 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1174 if (r < 0)
1175 return r;
1176 if (r == 0) {
1177 int master;
1178
1179 pair[0] = safe_close(pair[0]);
1180
1181 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1182 if (master < 0)
1183 _exit(EXIT_FAILURE);
1184
1185 if (send_one_fd(pair[1], master, 0) < 0)
1186 _exit(EXIT_FAILURE);
1187
1188 _exit(EXIT_SUCCESS);
1189 }
1190
1191 pair[1] = safe_close(pair[1]);
1192
1193 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
1194 if (r < 0)
1195 return r;
1196 if (r != EXIT_SUCCESS)
1197 return -EIO;
1198
1199 return receive_one_fd(pair[0], 0);
1200 }
1201
1202 static bool getenv_terminal_is_dumb(void) {
1203 const char *e;
1204
1205 e = getenv("TERM");
1206 if (!e)
1207 return true;
1208
1209 return streq(e, "dumb");
1210 }
1211
1212 bool terminal_is_dumb(void) {
1213 if (!on_tty())
1214 return true;
1215
1216 return getenv_terminal_is_dumb();
1217 }
1218
1219 static ColorMode parse_systemd_colors(void) {
1220 const char *e;
1221 int r;
1222
1223 e = getenv("SYSTEMD_COLORS");
1224 if (!e)
1225 return _COLOR_INVALID;
1226 if (streq(e, "16"))
1227 return COLOR_16;
1228 if (streq(e, "256"))
1229 return COLOR_256;
1230 r = parse_boolean(e);
1231 if (r >= 0)
1232 return r > 0 ? COLOR_ON : COLOR_OFF;
1233 return _COLOR_INVALID;
1234 }
1235
1236 ColorMode get_color_mode(void) {
1237
1238 /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1239 * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors and COLOR_ON for unrestricted
1240 * color output. For that we check $SYSTEMD_COLORS first (which is the explicit way to
1241 * 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
1242 * 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
1243 * check whether we are connected to a TTY, because we don't keep /dev/console open continuously due to fear
1244 * of SAK, and hence things are a bit weird. */
1245 ColorMode m;
1246
1247 if (cached_color_mode < 0) {
1248 m = parse_systemd_colors();
1249 if (m >= 0)
1250 cached_color_mode = m;
1251 else if (getenv("NO_COLOR"))
1252 /* We only check for the presence of the variable; value is ignored. */
1253 cached_color_mode = COLOR_OFF;
1254
1255 else if (getpid_cached() == 1)
1256 /* PID1 outputs to the console without holding it open all the time.
1257 *
1258 * Note that the Linux console can only display 16 colors. We still enable 256 color
1259 * mode even for PID1 output though (which typically goes to the Linux console),
1260 * since the Linux console is able to parse the 256 color sequences and automatically
1261 * map them to the closest color in the 16 color palette (since kernel 3.16). Doing
1262 * 256 colors is nice for people who invoke systemd in a container or via a serial
1263 * link or such, and use a true 256 color terminal to do so. */
1264 cached_color_mode = getenv_terminal_is_dumb() ? COLOR_OFF : COLOR_256;
1265 else
1266 cached_color_mode = terminal_is_dumb() ? COLOR_OFF : COLOR_256;
1267 }
1268
1269 return cached_color_mode;
1270 }
1271
1272 bool dev_console_colors_enabled(void) {
1273 _cleanup_free_ char *s = NULL;
1274 ColorMode m;
1275
1276 /* Returns true if we assume that color is supported on /dev/console.
1277 *
1278 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1279 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1280 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1281 * colors_enabled() operates. */
1282
1283 m = parse_systemd_colors();
1284 if (m >= 0)
1285 return m;
1286
1287 if (getenv("NO_COLOR"))
1288 return false;
1289
1290 if (getenv_for_pid(1, "TERM", &s) <= 0)
1291 (void) proc_cmdline_get_key("TERM", 0, &s);
1292
1293 return !streq_ptr(s, "dumb");
1294 }
1295
1296 bool underline_enabled(void) {
1297
1298 if (cached_underline_enabled < 0) {
1299
1300 /* The Linux console doesn't support underlining, turn it off, but only there. */
1301
1302 if (colors_enabled())
1303 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1304 else
1305 cached_underline_enabled = false;
1306 }
1307
1308 return cached_underline_enabled;
1309 }
1310
1311 int vt_default_utf8(void) {
1312 _cleanup_free_ char *b = NULL;
1313 int r;
1314
1315 /* Read the default VT UTF8 setting from the kernel */
1316
1317 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1318 if (r < 0)
1319 return r;
1320
1321 return parse_boolean(b);
1322 }
1323
1324 int vt_reset_keyboard(int fd) {
1325 int kb;
1326
1327 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1328 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1329
1330 if (ioctl(fd, KDSKBMODE, kb) < 0)
1331 return -errno;
1332
1333 return 0;
1334 }
1335
1336 int vt_restore(int fd) {
1337 static const struct vt_mode mode = {
1338 .mode = VT_AUTO,
1339 };
1340 int r, q = 0;
1341
1342 if (isatty(fd) < 1)
1343 return log_debug_errno(errno, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1344
1345 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
1346 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1347
1348 r = vt_reset_keyboard(fd);
1349 if (r < 0) {
1350 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1351 if (q >= 0)
1352 q = r;
1353 }
1354
1355 if (ioctl(fd, VT_SETMODE, &mode) < 0) {
1356 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1357 if (q >= 0)
1358 q = -errno;
1359 }
1360
1361 r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
1362 if (r < 0) {
1363 log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m");
1364 if (q >= 0)
1365 q = r;
1366 }
1367
1368 return q;
1369 }
1370
1371 int vt_release(int fd, bool restore) {
1372 assert(fd >= 0);
1373
1374 /* This function releases the VT by acknowledging the VT-switch signal
1375 * sent by the kernel and optionally reset the VT in text and auto
1376 * VT-switching modes. */
1377
1378 if (isatty(fd) < 1)
1379 return log_debug_errno(errno, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1380
1381 if (ioctl(fd, VT_RELDISP, 1) < 0)
1382 return -errno;
1383
1384 if (restore)
1385 return vt_restore(fd);
1386
1387 return 0;
1388 }
1389
1390 void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
1391 /* Note that this will initialize output variables only when there's something to output.
1392 * The caller must pre-initialize to "" or NULL as appropriate. */
1393
1394 if (priority <= LOG_ERR) {
1395 if (on)
1396 *on = ansi_highlight_red();
1397 if (off)
1398 *off = ansi_normal();
1399 if (highlight)
1400 *highlight = ansi_highlight();
1401
1402 } else if (priority <= LOG_WARNING) {
1403 if (on)
1404 *on = ansi_highlight_yellow();
1405 if (off)
1406 *off = ansi_normal();
1407 if (highlight)
1408 *highlight = ansi_highlight();
1409
1410 } else if (priority <= LOG_NOTICE) {
1411 if (on)
1412 *on = ansi_highlight();
1413 if (off)
1414 *off = ansi_normal();
1415 if (highlight)
1416 *highlight = ansi_highlight_red();
1417
1418 } else if (priority >= LOG_DEBUG) {
1419 if (on)
1420 *on = ansi_grey();
1421 if (off)
1422 *off = ansi_normal();
1423 if (highlight)
1424 *highlight = ansi_highlight_red();
1425 }
1426 }