]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
Revert "Move verify_vc_kbmode() to terminal-util.c as vt_verify_kbmode()"
[thirdparty/systemd.git] / src / basic / terminal-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 <string.h>
15 #include <sys/inotify.h>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
18 #include <sys/sysmacros.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/utsname.h>
22 #include <termios.h>
23 #include <unistd.h>
24
25 #include "alloc-util.h"
26 #include "copy.h"
27 #include "def.h"
28 #include "env-util.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "io-util.h"
33 #include "log.h"
34 #include "macro.h"
35 #include "namespace-util.h"
36 #include "parse-util.h"
37 #include "path-util.h"
38 #include "proc-cmdline.h"
39 #include "process-util.h"
40 #include "socket-util.h"
41 #include "stat-util.h"
42 #include "string-util.h"
43 #include "strv.h"
44 #include "terminal-util.h"
45 #include "time-util.h"
46 #include "util.h"
47
48 static volatile unsigned cached_columns = 0;
49 static volatile unsigned cached_lines = 0;
50
51 static volatile int cached_on_tty = -1;
52 static volatile int cached_colors_enabled = -1;
53 static volatile int cached_underline_enabled = -1;
54
55 int chvt(int vt) {
56 _cleanup_close_ int fd;
57
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. */
60
61 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
62 if (fd < 0)
63 return -errno;
64
65 if (vt <= 0) {
66 int tiocl[2] = {
67 TIOCL_GETKMSGREDIRECT,
68 0
69 };
70
71 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
72 return -errno;
73
74 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
75 }
76
77 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
78 return -errno;
79
80 return 0;
81 }
82
83 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
84 _cleanup_free_ char *line = NULL;
85 struct termios old_termios;
86 int r;
87
88 assert(f);
89 assert(ret);
90
91 /* If this is a terminal, then switch canonical mode off, so that we can read a single character */
92 if (tcgetattr(fileno(f), &old_termios) >= 0) {
93 struct termios new_termios = old_termios;
94
95 new_termios.c_lflag &= ~ICANON;
96 new_termios.c_cc[VMIN] = 1;
97 new_termios.c_cc[VTIME] = 0;
98
99 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
100 char c;
101
102 if (t != USEC_INFINITY) {
103 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
104 (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios);
105 return -ETIMEDOUT;
106 }
107 }
108
109 r = safe_fgetc(f, &c);
110 (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios);
111 if (r < 0)
112 return r;
113 if (r == 0)
114 return -EIO;
115
116 if (need_nl)
117 *need_nl = c != '\n';
118
119 *ret = c;
120 return 0;
121 }
122 }
123
124 if (t != USEC_INFINITY) {
125 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
126 return -ETIMEDOUT;
127 }
128
129 /* If this is not a terminal, then read a full line instead */
130
131 r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
132 if (r < 0)
133 return r;
134 if (r == 0)
135 return -EIO;
136
137 if (strlen(line) != 1)
138 return -EBADMSG;
139
140 if (need_nl)
141 *need_nl = false;
142
143 *ret = line[0];
144 return 0;
145 }
146
147 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
148
149 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
150 int r;
151
152 assert(ret);
153 assert(replies);
154 assert(fmt);
155
156 for (;;) {
157 va_list ap;
158 char c;
159 bool need_nl = true;
160
161 if (colors_enabled())
162 fputs(ANSI_HIGHLIGHT, stdout);
163
164 putchar('\r');
165
166 va_start(ap, fmt);
167 vprintf(fmt, ap);
168 va_end(ap);
169
170 if (colors_enabled())
171 fputs(ANSI_NORMAL, stdout);
172
173 fflush(stdout);
174
175 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
176 if (r < 0) {
177
178 if (r == -ETIMEDOUT)
179 continue;
180
181 if (r == -EBADMSG) {
182 puts("Bad input, please try again.");
183 continue;
184 }
185
186 putchar('\n');
187 return r;
188 }
189
190 if (need_nl)
191 putchar('\n');
192
193 if (strchr(replies, c)) {
194 *ret = c;
195 return 0;
196 }
197
198 puts("Read unexpected character, please try again.");
199 }
200 }
201
202 int ask_string(char **ret, const char *text, ...) {
203 _cleanup_free_ char *line = NULL;
204 va_list ap;
205 int r;
206
207 assert(ret);
208 assert(text);
209
210 if (colors_enabled())
211 fputs(ANSI_HIGHLIGHT, stdout);
212
213 va_start(ap, text);
214 vprintf(text, ap);
215 va_end(ap);
216
217 if (colors_enabled())
218 fputs(ANSI_NORMAL, stdout);
219
220 fflush(stdout);
221
222 r = read_line(stdin, LONG_LINE_MAX, &line);
223 if (r < 0)
224 return r;
225 if (r == 0)
226 return -EIO;
227
228 *ret = TAKE_PTR(line);
229 return 0;
230 }
231
232 int reset_terminal_fd(int fd, bool switch_to_text) {
233 struct termios termios;
234 int r = 0;
235
236 /* Set terminal to some sane defaults */
237
238 assert(fd >= 0);
239
240 /* We leave locked terminal attributes untouched, so that
241 * Plymouth may set whatever it wants to set, and we don't
242 * interfere with that. */
243
244 /* Disable exclusive mode, just in case */
245 (void) ioctl(fd, TIOCNXCL);
246
247 /* Switch to text mode */
248 if (switch_to_text)
249 (void) ioctl(fd, KDSETMODE, KD_TEXT);
250
251 /* Set default keyboard mode */
252 (void) vt_reset_keyboard(fd);
253
254 if (tcgetattr(fd, &termios) < 0) {
255 r = -errno;
256 goto finish;
257 }
258
259 /* We only reset the stuff that matters to the software. How
260 * hardware is set up we don't touch assuming that somebody
261 * else will do that for us */
262
263 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
264 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
265 termios.c_oflag |= ONLCR;
266 termios.c_cflag |= CREAD;
267 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
268
269 termios.c_cc[VINTR] = 03; /* ^C */
270 termios.c_cc[VQUIT] = 034; /* ^\ */
271 termios.c_cc[VERASE] = 0177;
272 termios.c_cc[VKILL] = 025; /* ^X */
273 termios.c_cc[VEOF] = 04; /* ^D */
274 termios.c_cc[VSTART] = 021; /* ^Q */
275 termios.c_cc[VSTOP] = 023; /* ^S */
276 termios.c_cc[VSUSP] = 032; /* ^Z */
277 termios.c_cc[VLNEXT] = 026; /* ^V */
278 termios.c_cc[VWERASE] = 027; /* ^W */
279 termios.c_cc[VREPRINT] = 022; /* ^R */
280 termios.c_cc[VEOL] = 0;
281 termios.c_cc[VEOL2] = 0;
282
283 termios.c_cc[VTIME] = 0;
284 termios.c_cc[VMIN] = 1;
285
286 if (tcsetattr(fd, TCSANOW, &termios) < 0)
287 r = -errno;
288
289 finish:
290 /* Just in case, flush all crap out */
291 (void) tcflush(fd, TCIOFLUSH);
292
293 return r;
294 }
295
296 int reset_terminal(const char *name) {
297 _cleanup_close_ int fd = -1;
298
299 /* We open the terminal with O_NONBLOCK here, to ensure we
300 * don't block on carrier if this is a terminal with carrier
301 * configured. */
302
303 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
304 if (fd < 0)
305 return fd;
306
307 return reset_terminal_fd(fd, true);
308 }
309
310 int open_terminal(const char *name, int mode) {
311 unsigned c = 0;
312 int fd;
313
314 /*
315 * If a TTY is in the process of being closed opening it might
316 * cause EIO. This is horribly awful, but unlikely to be
317 * changed in the kernel. Hence we work around this problem by
318 * retrying a couple of times.
319 *
320 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
321 */
322
323 if (mode & O_CREAT)
324 return -EINVAL;
325
326 for (;;) {
327 fd = open(name, mode, 0);
328 if (fd >= 0)
329 break;
330
331 if (errno != EIO)
332 return -errno;
333
334 /* Max 1s in total */
335 if (c >= 20)
336 return -errno;
337
338 usleep(50 * USEC_PER_MSEC);
339 c++;
340 }
341
342 if (isatty(fd) <= 0) {
343 safe_close(fd);
344 return -ENOTTY;
345 }
346
347 return fd;
348 }
349
350 int acquire_terminal(
351 const char *name,
352 AcquireTerminalFlags flags,
353 usec_t timeout) {
354
355 _cleanup_close_ int notify = -1, fd = -1;
356 usec_t ts = USEC_INFINITY;
357 int r, wd = -1;
358
359 assert(name);
360 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
361
362 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
363 * acquire it, so that we don't lose any event.
364 *
365 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
366 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
367 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
368 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
369 * probably should not do anyway.) */
370
371 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
372 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
373 if (notify < 0)
374 return -errno;
375
376 wd = inotify_add_watch(notify, name, IN_CLOSE);
377 if (wd < 0)
378 return -errno;
379
380 if (timeout != USEC_INFINITY)
381 ts = now(CLOCK_MONOTONIC);
382 }
383
384 for (;;) {
385 struct sigaction sa_old, sa_new = {
386 .sa_handler = SIG_IGN,
387 .sa_flags = SA_RESTART,
388 };
389
390 if (notify >= 0) {
391 r = flush_fd(notify);
392 if (r < 0)
393 return r;
394 }
395
396 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
397 * to figure out if we successfully became the controlling process of the tty */
398 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
399 if (fd < 0)
400 return fd;
401
402 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
403 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
404
405 /* First, try to get the tty */
406 r = ioctl(fd, TIOCSCTTY,
407 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
408
409 /* Reset signal handler to old value */
410 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
411
412 /* Success? Exit the loop now! */
413 if (r >= 0)
414 break;
415
416 /* Any failure besides -EPERM? Fail, regardless of the mode. */
417 if (r != -EPERM)
418 return r;
419
420 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
421 * into a success. Note that EPERM is also returned if we
422 * already are the owner of the TTY. */
423 break;
424
425 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
426 return r;
427
428 assert(notify >= 0);
429 assert(wd >= 0);
430
431 for (;;) {
432 union inotify_event_buffer buffer;
433 struct inotify_event *e;
434 ssize_t l;
435
436 if (timeout != USEC_INFINITY) {
437 usec_t n;
438
439 assert(ts != USEC_INFINITY);
440
441 n = now(CLOCK_MONOTONIC);
442 if (ts + timeout < n)
443 return -ETIMEDOUT;
444
445 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
446 if (r < 0)
447 return r;
448 if (r == 0)
449 return -ETIMEDOUT;
450 }
451
452 l = read(notify, &buffer, sizeof(buffer));
453 if (l < 0) {
454 if (IN_SET(errno, EINTR, EAGAIN))
455 continue;
456
457 return -errno;
458 }
459
460 FOREACH_INOTIFY_EVENT(e, buffer, l) {
461 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
462 break;
463
464 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
465 return -EIO;
466 }
467
468 break;
469 }
470
471 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
472 * we do this after sleeping, so that we don't enter an endless loop. */
473 fd = safe_close(fd);
474 }
475
476 return TAKE_FD(fd);
477 }
478
479 int release_terminal(void) {
480 static const struct sigaction sa_new = {
481 .sa_handler = SIG_IGN,
482 .sa_flags = SA_RESTART,
483 };
484
485 _cleanup_close_ int fd = -1;
486 struct sigaction sa_old;
487 int r;
488
489 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
490 if (fd < 0)
491 return -errno;
492
493 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
494 * by our own TIOCNOTTY */
495 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
496
497 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
498
499 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
500
501 return r;
502 }
503
504 int terminal_vhangup_fd(int fd) {
505 assert(fd >= 0);
506
507 if (ioctl(fd, TIOCVHANGUP) < 0)
508 return -errno;
509
510 return 0;
511 }
512
513 int terminal_vhangup(const char *name) {
514 _cleanup_close_ int fd;
515
516 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
517 if (fd < 0)
518 return fd;
519
520 return terminal_vhangup_fd(fd);
521 }
522
523 int vt_disallocate(const char *name) {
524 const char *e;
525 int r;
526
527 /* Deallocate the VT if possible. If not possible
528 * (i.e. because it is the active one), at least clear it
529 * entirely (including the scrollback buffer). */
530
531 e = path_startswith(name, "/dev/");
532 if (!e)
533 return -EINVAL;
534
535 if (tty_is_vc(name)) {
536 _cleanup_close_ int fd = -1;
537 unsigned u;
538 const char *n;
539
540 n = startswith(e, "tty");
541 if (!n)
542 return -EINVAL;
543
544 r = safe_atou(n, &u);
545 if (r < 0)
546 return r;
547
548 if (u <= 0)
549 return -EINVAL;
550
551 /* Try to deallocate */
552 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
553 if (fd < 0)
554 return fd;
555
556 r = ioctl(fd, VT_DISALLOCATE, u);
557 if (r >= 0)
558 return 0;
559 if (errno != EBUSY)
560 return -errno;
561 }
562
563 /* So this is not a VT (in which case we cannot deallocate it),
564 * or we failed to deallocate. Let's at least clear the screen. */
565
566 _cleanup_close_ int fd2 = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
567 if (fd2 < 0)
568 return fd2;
569
570 (void) loop_write(fd2,
571 "\033[r" /* clear scrolling region */
572 "\033[H" /* move home */
573 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
574 10, false);
575 return 0;
576 }
577
578 int make_console_stdio(void) {
579 int fd, r;
580
581 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
582
583 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
584 if (fd < 0)
585 return log_error_errno(fd, "Failed to acquire terminal: %m");
586
587 r = reset_terminal_fd(fd, true);
588 if (r < 0)
589 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
590
591 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
592 if (r < 0)
593 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
594
595 reset_terminal_feature_caches();
596
597 return 0;
598 }
599
600 bool tty_is_vc(const char *tty) {
601 assert(tty);
602
603 return vtnr_from_tty(tty) >= 0;
604 }
605
606 bool tty_is_console(const char *tty) {
607 assert(tty);
608
609 return streq(skip_dev_prefix(tty), "console");
610 }
611
612 int vtnr_from_tty(const char *tty) {
613 int i, r;
614
615 assert(tty);
616
617 tty = skip_dev_prefix(tty);
618
619 if (!startswith(tty, "tty") )
620 return -EINVAL;
621
622 if (tty[3] < '0' || tty[3] > '9')
623 return -EINVAL;
624
625 r = safe_atoi(tty+3, &i);
626 if (r < 0)
627 return r;
628
629 if (i < 0 || i > 63)
630 return -EINVAL;
631
632 return i;
633 }
634
635 int resolve_dev_console(char **ret) {
636 _cleanup_free_ char *active = NULL;
637 char *tty;
638 int r;
639
640 assert(ret);
641
642 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
643 * sign for container setups) */
644
645 if (path_is_read_only_fs("/sys") > 0)
646 return -ENOMEDIUM;
647
648 r = read_one_line_file("/sys/class/tty/console/active", &active);
649 if (r < 0)
650 return r;
651
652 /* If multiple log outputs are configured the last one is what /dev/console points to */
653 tty = strrchr(active, ' ');
654 if (tty)
655 tty++;
656 else
657 tty = active;
658
659 if (streq(tty, "tty0")) {
660 active = mfree(active);
661
662 /* Get the active VC (e.g. tty1) */
663 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
664 if (r < 0)
665 return r;
666
667 tty = active;
668 }
669
670 if (tty == active)
671 *ret = TAKE_PTR(active);
672 else {
673 char *tmp;
674
675 tmp = strdup(tty);
676 if (!tmp)
677 return -ENOMEM;
678
679 *ret = tmp;
680 }
681
682 return 0;
683 }
684
685 int get_kernel_consoles(char ***ret) {
686 _cleanup_strv_free_ char **l = NULL;
687 _cleanup_free_ char *line = NULL;
688 const char *p;
689 int r;
690
691 assert(ret);
692
693 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
694 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
695 if (path_is_read_only_fs("/sys") > 0)
696 goto fallback;
697
698 r = read_one_line_file("/sys/class/tty/console/active", &line);
699 if (r < 0)
700 return r;
701
702 p = line;
703 for (;;) {
704 _cleanup_free_ char *tty = NULL, *path = NULL;
705
706 r = extract_first_word(&p, &tty, NULL, 0);
707 if (r < 0)
708 return r;
709 if (r == 0)
710 break;
711
712 if (streq(tty, "tty0")) {
713 tty = mfree(tty);
714 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
715 if (r < 0)
716 return r;
717 }
718
719 path = path_join("/dev", tty);
720 if (!path)
721 return -ENOMEM;
722
723 if (access(path, F_OK) < 0) {
724 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
725 continue;
726 }
727
728 r = strv_consume(&l, TAKE_PTR(path));
729 if (r < 0)
730 return r;
731 }
732
733 if (strv_isempty(l)) {
734 log_debug("No devices found for system console");
735 goto fallback;
736 }
737
738 *ret = TAKE_PTR(l);
739
740 return 0;
741
742 fallback:
743 r = strv_extend(&l, "/dev/console");
744 if (r < 0)
745 return r;
746
747 *ret = TAKE_PTR(l);
748
749 return 0;
750 }
751
752 bool tty_is_vc_resolve(const char *tty) {
753 _cleanup_free_ char *resolved = NULL;
754
755 assert(tty);
756
757 tty = skip_dev_prefix(tty);
758
759 if (streq(tty, "console")) {
760 if (resolve_dev_console(&resolved) < 0)
761 return false;
762
763 tty = resolved;
764 }
765
766 return tty_is_vc(tty);
767 }
768
769 const char *default_term_for_tty(const char *tty) {
770 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
771 }
772
773 int fd_columns(int fd) {
774 struct winsize ws = {};
775
776 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
777 return -errno;
778
779 if (ws.ws_col <= 0)
780 return -EIO;
781
782 return ws.ws_col;
783 }
784
785 unsigned columns(void) {
786 const char *e;
787 int c;
788
789 if (cached_columns > 0)
790 return cached_columns;
791
792 c = 0;
793 e = getenv("COLUMNS");
794 if (e)
795 (void) safe_atoi(e, &c);
796
797 if (c <= 0 || c > USHRT_MAX) {
798 c = fd_columns(STDOUT_FILENO);
799 if (c <= 0)
800 c = 80;
801 }
802
803 cached_columns = c;
804 return cached_columns;
805 }
806
807 int fd_lines(int fd) {
808 struct winsize ws = {};
809
810 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
811 return -errno;
812
813 if (ws.ws_row <= 0)
814 return -EIO;
815
816 return ws.ws_row;
817 }
818
819 unsigned lines(void) {
820 const char *e;
821 int l;
822
823 if (cached_lines > 0)
824 return cached_lines;
825
826 l = 0;
827 e = getenv("LINES");
828 if (e)
829 (void) safe_atoi(e, &l);
830
831 if (l <= 0 || l > USHRT_MAX) {
832 l = fd_lines(STDOUT_FILENO);
833 if (l <= 0)
834 l = 24;
835 }
836
837 cached_lines = l;
838 return cached_lines;
839 }
840
841 /* intended to be used as a SIGWINCH sighandler */
842 void columns_lines_cache_reset(int signum) {
843 cached_columns = 0;
844 cached_lines = 0;
845 }
846
847 void reset_terminal_feature_caches(void) {
848 cached_columns = 0;
849 cached_lines = 0;
850
851 cached_colors_enabled = -1;
852 cached_underline_enabled = -1;
853 cached_on_tty = -1;
854 }
855
856 bool on_tty(void) {
857
858 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
859 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
860 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
861 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
862 * terminal functionality when outputting stuff, even if the input is piped to us. */
863
864 if (cached_on_tty < 0)
865 cached_on_tty =
866 isatty(STDOUT_FILENO) > 0 &&
867 isatty(STDERR_FILENO) > 0;
868
869 return cached_on_tty;
870 }
871
872 int getttyname_malloc(int fd, char **ret) {
873 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
874 int r;
875
876 assert(fd >= 0);
877 assert(ret);
878
879 r = ttyname_r(fd, path, sizeof path); /* positive error */
880 assert(r >= 0);
881 if (r == ERANGE)
882 return -ENAMETOOLONG;
883 if (r > 0)
884 return -r;
885
886 c = strdup(skip_dev_prefix(path));
887 if (!c)
888 return -ENOMEM;
889
890 *ret = c;
891 return 0;
892 }
893
894 int getttyname_harder(int fd, char **ret) {
895 _cleanup_free_ char *s = NULL;
896 int r;
897
898 r = getttyname_malloc(fd, &s);
899 if (r < 0)
900 return r;
901
902 if (streq(s, "tty"))
903 return get_ctty(0, NULL, ret);
904
905 *ret = TAKE_PTR(s);
906 return 0;
907 }
908
909 int get_ctty_devnr(pid_t pid, dev_t *d) {
910 int r;
911 _cleanup_free_ char *line = NULL;
912 const char *p;
913 unsigned long ttynr;
914
915 assert(pid >= 0);
916
917 p = procfs_file_alloca(pid, "stat");
918 r = read_one_line_file(p, &line);
919 if (r < 0)
920 return r;
921
922 p = strrchr(line, ')');
923 if (!p)
924 return -EIO;
925
926 p++;
927
928 if (sscanf(p, " "
929 "%*c " /* state */
930 "%*d " /* ppid */
931 "%*d " /* pgrp */
932 "%*d " /* session */
933 "%lu ", /* ttynr */
934 &ttynr) != 1)
935 return -EIO;
936
937 if (major(ttynr) == 0 && minor(ttynr) == 0)
938 return -ENXIO;
939
940 if (d)
941 *d = (dev_t) ttynr;
942
943 return 0;
944 }
945
946 int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
947 _cleanup_free_ char *fn = NULL, *b = NULL;
948 dev_t devnr;
949 int r;
950
951 r = get_ctty_devnr(pid, &devnr);
952 if (r < 0)
953 return r;
954
955 r = device_path_make_canonical(S_IFCHR, devnr, &fn);
956 if (r < 0) {
957 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
958 return r;
959
960 if (major(devnr) == 136) {
961 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
962 * Linux device model. This means we have no nice way to match them up against their actual
963 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
964 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
965 * this. */
966
967 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
968 return -ENOMEM;
969 } else {
970 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
971 * something vaguely useful. */
972
973 r = device_path_make_major_minor(S_IFCHR, devnr, &fn);
974 if (r < 0)
975 return r;
976 }
977 }
978
979 if (!b) {
980 const char *w;
981
982 w = path_startswith(fn, "/dev/");
983 if (w) {
984 b = strdup(w);
985 if (!b)
986 return -ENOMEM;
987 } else
988 b = TAKE_PTR(fn);
989 }
990
991 if (ret)
992 *ret = TAKE_PTR(b);
993
994 if (ret_devnr)
995 *ret_devnr = devnr;
996
997 return 0;
998 }
999
1000 int ptsname_malloc(int fd, char **ret) {
1001 size_t l = 100;
1002
1003 assert(fd >= 0);
1004 assert(ret);
1005
1006 for (;;) {
1007 char *c;
1008
1009 c = new(char, l);
1010 if (!c)
1011 return -ENOMEM;
1012
1013 if (ptsname_r(fd, c, l) == 0) {
1014 *ret = c;
1015 return 0;
1016 }
1017 if (errno != ERANGE) {
1018 free(c);
1019 return -errno;
1020 }
1021
1022 free(c);
1023
1024 if (l > SIZE_MAX / 2)
1025 return -ENOMEM;
1026
1027 l *= 2;
1028 }
1029 }
1030
1031 int openpt_allocate(int flags, char **ret_slave) {
1032 _cleanup_close_ int fd = -1;
1033 _cleanup_free_ char *p = NULL;
1034 int r;
1035
1036 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1037 if (fd < 0)
1038 return -errno;
1039
1040 if (ret_slave) {
1041 r = ptsname_malloc(fd, &p);
1042 if (r < 0)
1043 return r;
1044
1045 if (!path_startswith(p, "/dev/pts/"))
1046 return -EINVAL;
1047 }
1048
1049 if (unlockpt(fd) < 0)
1050 return -errno;
1051
1052 if (ret_slave)
1053 *ret_slave = TAKE_PTR(p);
1054
1055 return TAKE_FD(fd);
1056 }
1057
1058 static int ptsname_namespace(int pty, char **ret) {
1059 int no = -1, r;
1060
1061 /* Like ptsname(), but doesn't assume that the path is
1062 * accessible in the local namespace. */
1063
1064 r = ioctl(pty, TIOCGPTN, &no);
1065 if (r < 0)
1066 return -errno;
1067
1068 if (no < 0)
1069 return -EIO;
1070
1071 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1072 return -ENOMEM;
1073
1074 return 0;
1075 }
1076
1077 int openpt_allocate_in_namespace(pid_t pid, int flags, char **ret_slave) {
1078 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1, fd = -1;
1079 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1080 pid_t child;
1081 int r;
1082
1083 assert(pid > 0);
1084
1085 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1086 if (r < 0)
1087 return r;
1088
1089 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1090 return -errno;
1091
1092 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1093 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1094 if (r < 0)
1095 return r;
1096 if (r == 0) {
1097 pair[0] = safe_close(pair[0]);
1098
1099 fd = openpt_allocate(flags, NULL);
1100 if (fd < 0)
1101 _exit(EXIT_FAILURE);
1102
1103 if (send_one_fd(pair[1], fd, 0) < 0)
1104 _exit(EXIT_FAILURE);
1105
1106 _exit(EXIT_SUCCESS);
1107 }
1108
1109 pair[1] = safe_close(pair[1]);
1110
1111 r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
1112 if (r < 0)
1113 return r;
1114 if (r != EXIT_SUCCESS)
1115 return -EIO;
1116
1117 fd = receive_one_fd(pair[0], 0);
1118 if (fd < 0)
1119 return fd;
1120
1121 if (ret_slave) {
1122 r = ptsname_namespace(fd, ret_slave);
1123 if (r < 0)
1124 return r;
1125 }
1126
1127 return TAKE_FD(fd);
1128 }
1129
1130 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1131 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1132 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1133 pid_t child;
1134 int r;
1135
1136 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1137 if (r < 0)
1138 return r;
1139
1140 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1141 return -errno;
1142
1143 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1144 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1145 if (r < 0)
1146 return r;
1147 if (r == 0) {
1148 int master;
1149
1150 pair[0] = safe_close(pair[0]);
1151
1152 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1153 if (master < 0)
1154 _exit(EXIT_FAILURE);
1155
1156 if (send_one_fd(pair[1], master, 0) < 0)
1157 _exit(EXIT_FAILURE);
1158
1159 _exit(EXIT_SUCCESS);
1160 }
1161
1162 pair[1] = safe_close(pair[1]);
1163
1164 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
1165 if (r < 0)
1166 return r;
1167 if (r != EXIT_SUCCESS)
1168 return -EIO;
1169
1170 return receive_one_fd(pair[0], 0);
1171 }
1172
1173 static bool getenv_terminal_is_dumb(void) {
1174 const char *e;
1175
1176 e = getenv("TERM");
1177 if (!e)
1178 return true;
1179
1180 return streq(e, "dumb");
1181 }
1182
1183 bool terminal_is_dumb(void) {
1184 if (!on_tty())
1185 return true;
1186
1187 return getenv_terminal_is_dumb();
1188 }
1189
1190 bool colors_enabled(void) {
1191
1192 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1193 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1194 * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if
1195 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1196 * continuously due to fear of SAK, and hence things are a bit weird. */
1197
1198 if (cached_colors_enabled < 0) {
1199 int val;
1200
1201 val = getenv_bool("SYSTEMD_COLORS");
1202 if (val >= 0)
1203 cached_colors_enabled = val;
1204 else if (getpid_cached() == 1)
1205 /* PID1 outputs to the console without holding it open all the time */
1206 cached_colors_enabled = !getenv_terminal_is_dumb();
1207 else
1208 cached_colors_enabled = !terminal_is_dumb();
1209 }
1210
1211 return cached_colors_enabled;
1212 }
1213
1214 bool dev_console_colors_enabled(void) {
1215 _cleanup_free_ char *s = NULL;
1216 int b;
1217
1218 /* Returns true if we assume that color is supported on /dev/console.
1219 *
1220 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1221 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1222 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1223 * colors_enabled() operates. */
1224
1225 b = getenv_bool("SYSTEMD_COLORS");
1226 if (b >= 0)
1227 return b;
1228
1229 if (getenv_for_pid(1, "TERM", &s) <= 0)
1230 (void) proc_cmdline_get_key("TERM", 0, &s);
1231
1232 return !streq_ptr(s, "dumb");
1233 }
1234
1235 bool underline_enabled(void) {
1236
1237 if (cached_underline_enabled < 0) {
1238
1239 /* The Linux console doesn't support underlining, turn it off, but only there. */
1240
1241 if (colors_enabled())
1242 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1243 else
1244 cached_underline_enabled = false;
1245 }
1246
1247 return cached_underline_enabled;
1248 }
1249
1250 int vt_default_utf8(void) {
1251 _cleanup_free_ char *b = NULL;
1252 int r;
1253
1254 /* Read the default VT UTF8 setting from the kernel */
1255
1256 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1257 if (r < 0)
1258 return r;
1259
1260 return parse_boolean(b);
1261 }
1262
1263 int vt_reset_keyboard(int fd) {
1264 int kb;
1265
1266 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1267 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1268
1269 if (ioctl(fd, KDSKBMODE, kb) < 0)
1270 return -errno;
1271
1272 return 0;
1273 }
1274
1275 int vt_restore(int fd) {
1276 static const struct vt_mode mode = {
1277 .mode = VT_AUTO,
1278 };
1279 int r, q = 0;
1280
1281 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
1282 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1283
1284 r = vt_reset_keyboard(fd);
1285 if (r < 0) {
1286 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1287 if (q >= 0)
1288 q = r;
1289 }
1290
1291 if (ioctl(fd, VT_SETMODE, &mode) < 0) {
1292 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1293 if (q >= 0)
1294 q = -errno;
1295 }
1296
1297 r = fchmod_and_chown(fd, TTY_MODE, 0, (gid_t) -1);
1298 if (r < 0) {
1299 log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m");
1300 if (q >= 0)
1301 q = r;
1302 }
1303
1304 return q;
1305 }
1306
1307 int vt_release(int fd, bool restore) {
1308 assert(fd >= 0);
1309
1310 /* This function releases the VT by acknowledging the VT-switch signal
1311 * sent by the kernel and optionally reset the VT in text and auto
1312 * VT-switching modes. */
1313
1314 if (ioctl(fd, VT_RELDISP, 1) < 0)
1315 return -errno;
1316
1317 if (restore)
1318 return vt_restore(fd);
1319
1320 return 0;
1321 }
1322
1323 void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
1324 /* Note that this will initialize output variables only when there's something to output.
1325 * The caller must pre-initalize to "" or NULL as appropriate. */
1326
1327 if (priority <= LOG_ERR) {
1328 if (on)
1329 *on = ANSI_HIGHLIGHT_RED;
1330 if (off)
1331 *off = ANSI_NORMAL;
1332 if (highlight)
1333 *highlight = ANSI_HIGHLIGHT;
1334
1335 } else if (priority <= LOG_WARNING) {
1336 if (on)
1337 *on = ANSI_HIGHLIGHT_YELLOW;
1338 if (off)
1339 *off = ANSI_NORMAL;
1340 if (highlight)
1341 *highlight = ANSI_HIGHLIGHT;
1342
1343 } else if (priority <= LOG_NOTICE) {
1344 if (on)
1345 *on = ANSI_HIGHLIGHT;
1346 if (off)
1347 *off = ANSI_NORMAL;
1348 if (highlight)
1349 *highlight = ANSI_HIGHLIGHT_RED;
1350
1351 } else if (priority >= LOG_DEBUG) {
1352 if (on)
1353 *on = ANSI_GREY;
1354 if (off)
1355 *off = ANSI_NORMAL;
1356 if (highlight)
1357 *highlight = ANSI_HIGHLIGHT_RED;
1358 }
1359 }