]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
76d6d1a20c9e011ae5c1c14a2e1ac3549c2319d8
[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 int r;
204
205 assert(ret);
206 assert(text);
207
208 for (;;) {
209 _cleanup_free_ char *line = NULL;
210 va_list ap;
211
212 if (colors_enabled())
213 fputs(ANSI_HIGHLIGHT, stdout);
214
215 va_start(ap, text);
216 vprintf(text, ap);
217 va_end(ap);
218
219 if (colors_enabled())
220 fputs(ANSI_NORMAL, stdout);
221
222 fflush(stdout);
223
224 r = read_line(stdin, LONG_LINE_MAX, &line);
225 if (r < 0)
226 return r;
227 if (r == 0)
228 return -EIO;
229
230 if (!isempty(line)) {
231 *ret = TAKE_PTR(line);
232 return 0;
233 }
234 }
235 }
236
237 int reset_terminal_fd(int fd, bool switch_to_text) {
238 struct termios termios;
239 int r = 0;
240
241 /* Set terminal to some sane defaults */
242
243 assert(fd >= 0);
244
245 /* We leave locked terminal attributes untouched, so that
246 * Plymouth may set whatever it wants to set, and we don't
247 * interfere with that. */
248
249 /* Disable exclusive mode, just in case */
250 (void) ioctl(fd, TIOCNXCL);
251
252 /* Switch to text mode */
253 if (switch_to_text)
254 (void) ioctl(fd, KDSETMODE, KD_TEXT);
255
256 /* Set default keyboard mode */
257 (void) vt_reset_keyboard(fd);
258
259 if (tcgetattr(fd, &termios) < 0) {
260 r = -errno;
261 goto finish;
262 }
263
264 /* We only reset the stuff that matters to the software. How
265 * hardware is set up we don't touch assuming that somebody
266 * else will do that for us */
267
268 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
269 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
270 termios.c_oflag |= ONLCR;
271 termios.c_cflag |= CREAD;
272 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
273
274 termios.c_cc[VINTR] = 03; /* ^C */
275 termios.c_cc[VQUIT] = 034; /* ^\ */
276 termios.c_cc[VERASE] = 0177;
277 termios.c_cc[VKILL] = 025; /* ^X */
278 termios.c_cc[VEOF] = 04; /* ^D */
279 termios.c_cc[VSTART] = 021; /* ^Q */
280 termios.c_cc[VSTOP] = 023; /* ^S */
281 termios.c_cc[VSUSP] = 032; /* ^Z */
282 termios.c_cc[VLNEXT] = 026; /* ^V */
283 termios.c_cc[VWERASE] = 027; /* ^W */
284 termios.c_cc[VREPRINT] = 022; /* ^R */
285 termios.c_cc[VEOL] = 0;
286 termios.c_cc[VEOL2] = 0;
287
288 termios.c_cc[VTIME] = 0;
289 termios.c_cc[VMIN] = 1;
290
291 if (tcsetattr(fd, TCSANOW, &termios) < 0)
292 r = -errno;
293
294 finish:
295 /* Just in case, flush all crap out */
296 (void) tcflush(fd, TCIOFLUSH);
297
298 return r;
299 }
300
301 int reset_terminal(const char *name) {
302 _cleanup_close_ int fd = -1;
303
304 /* We open the terminal with O_NONBLOCK here, to ensure we
305 * don't block on carrier if this is a terminal with carrier
306 * configured. */
307
308 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
309 if (fd < 0)
310 return fd;
311
312 return reset_terminal_fd(fd, true);
313 }
314
315 int open_terminal(const char *name, int mode) {
316 unsigned c = 0;
317 int fd;
318
319 /*
320 * If a TTY is in the process of being closed opening it might
321 * cause EIO. This is horribly awful, but unlikely to be
322 * changed in the kernel. Hence we work around this problem by
323 * retrying a couple of times.
324 *
325 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
326 */
327
328 if (mode & O_CREAT)
329 return -EINVAL;
330
331 for (;;) {
332 fd = open(name, mode, 0);
333 if (fd >= 0)
334 break;
335
336 if (errno != EIO)
337 return -errno;
338
339 /* Max 1s in total */
340 if (c >= 20)
341 return -errno;
342
343 usleep(50 * USEC_PER_MSEC);
344 c++;
345 }
346
347 if (isatty(fd) <= 0) {
348 safe_close(fd);
349 return -ENOTTY;
350 }
351
352 return 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 = now(CLOCK_MONOTONIC);
447 if (ts + timeout < n)
448 return -ETIMEDOUT;
449
450 r = fd_wait_for_event(notify, POLLIN, ts + 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;
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 _cleanup_close_ int fd = -1;
530 const char *e, *n;
531 unsigned u;
532 int r;
533
534 /* Deallocate the VT if possible. If not possible
535 * (i.e. because it is the active one), at least clear it
536 * entirely (including the scrollback buffer) */
537
538 e = path_startswith(name, "/dev/");
539 if (!e)
540 return -EINVAL;
541
542 if (!tty_is_vc(name)) {
543 /* So this is not a VT. I guess we cannot deallocate
544 * it then. But let's at least clear the screen */
545
546 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
547 if (fd < 0)
548 return fd;
549
550 loop_write(fd,
551 "\033[r" /* clear scrolling region */
552 "\033[H" /* move home */
553 "\033[2J", /* clear screen */
554 10, false);
555 return 0;
556 }
557
558 n = startswith(e, "tty");
559 if (!n)
560 return -EINVAL;
561
562 r = safe_atou(n, &u);
563 if (r < 0)
564 return r;
565
566 if (u <= 0)
567 return -EINVAL;
568
569 /* Try to deallocate */
570 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
571 if (fd < 0)
572 return fd;
573
574 r = ioctl(fd, VT_DISALLOCATE, u);
575 fd = safe_close(fd);
576
577 if (r >= 0)
578 return 0;
579
580 if (errno != EBUSY)
581 return -errno;
582
583 /* Couldn't deallocate, so let's clear it fully with
584 * scrollback */
585 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
586 if (fd < 0)
587 return fd;
588
589 loop_write(fd,
590 "\033[r" /* clear scrolling region */
591 "\033[H" /* move home */
592 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
593 10, false);
594 return 0;
595 }
596
597 int make_console_stdio(void) {
598 int fd, r;
599
600 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
601
602 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
603 if (fd < 0)
604 return log_error_errno(fd, "Failed to acquire terminal: %m");
605
606 r = reset_terminal_fd(fd, true);
607 if (r < 0)
608 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
609
610 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
611 if (r < 0)
612 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
613
614 reset_terminal_feature_caches();
615
616 return 0;
617 }
618
619 bool tty_is_vc(const char *tty) {
620 assert(tty);
621
622 return vtnr_from_tty(tty) >= 0;
623 }
624
625 bool tty_is_console(const char *tty) {
626 assert(tty);
627
628 return streq(skip_dev_prefix(tty), "console");
629 }
630
631 int vtnr_from_tty(const char *tty) {
632 int i, r;
633
634 assert(tty);
635
636 tty = skip_dev_prefix(tty);
637
638 if (!startswith(tty, "tty") )
639 return -EINVAL;
640
641 if (tty[3] < '0' || tty[3] > '9')
642 return -EINVAL;
643
644 r = safe_atoi(tty+3, &i);
645 if (r < 0)
646 return r;
647
648 if (i < 0 || i > 63)
649 return -EINVAL;
650
651 return i;
652 }
653
654 int resolve_dev_console(char **ret) {
655 _cleanup_free_ char *active = NULL;
656 char *tty;
657 int r;
658
659 assert(ret);
660
661 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
662 * sign for container setups) */
663
664 if (path_is_read_only_fs("/sys") > 0)
665 return -ENOMEDIUM;
666
667 r = read_one_line_file("/sys/class/tty/console/active", &active);
668 if (r < 0)
669 return r;
670
671 /* If multiple log outputs are configured the last one is what /dev/console points to */
672 tty = strrchr(active, ' ');
673 if (tty)
674 tty++;
675 else
676 tty = active;
677
678 if (streq(tty, "tty0")) {
679 active = mfree(active);
680
681 /* Get the active VC (e.g. tty1) */
682 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
683 if (r < 0)
684 return r;
685
686 tty = active;
687 }
688
689 if (tty == active)
690 *ret = TAKE_PTR(active);
691 else {
692 char *tmp;
693
694 tmp = strdup(tty);
695 if (!tmp)
696 return -ENOMEM;
697
698 *ret = tmp;
699 }
700
701 return 0;
702 }
703
704 int get_kernel_consoles(char ***ret) {
705 _cleanup_strv_free_ char **l = NULL;
706 _cleanup_free_ char *line = NULL;
707 const char *p;
708 int r;
709
710 assert(ret);
711
712 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
713 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
714 if (path_is_read_only_fs("/sys") > 0)
715 goto fallback;
716
717 r = read_one_line_file("/sys/class/tty/console/active", &line);
718 if (r < 0)
719 return r;
720
721 p = line;
722 for (;;) {
723 _cleanup_free_ char *tty = NULL, *path = NULL;
724
725 r = extract_first_word(&p, &tty, NULL, 0);
726 if (r < 0)
727 return r;
728 if (r == 0)
729 break;
730
731 if (streq(tty, "tty0")) {
732 tty = mfree(tty);
733 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
734 if (r < 0)
735 return r;
736 }
737
738 path = path_join("/dev", tty);
739 if (!path)
740 return -ENOMEM;
741
742 if (access(path, F_OK) < 0) {
743 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
744 continue;
745 }
746
747 r = strv_consume(&l, TAKE_PTR(path));
748 if (r < 0)
749 return r;
750 }
751
752 if (strv_isempty(l)) {
753 log_debug("No devices found for system console");
754 goto fallback;
755 }
756
757 *ret = TAKE_PTR(l);
758
759 return 0;
760
761 fallback:
762 r = strv_extend(&l, "/dev/console");
763 if (r < 0)
764 return r;
765
766 *ret = TAKE_PTR(l);
767
768 return 0;
769 }
770
771 bool tty_is_vc_resolve(const char *tty) {
772 _cleanup_free_ char *resolved = NULL;
773
774 assert(tty);
775
776 tty = skip_dev_prefix(tty);
777
778 if (streq(tty, "console")) {
779 if (resolve_dev_console(&resolved) < 0)
780 return false;
781
782 tty = resolved;
783 }
784
785 return tty_is_vc(tty);
786 }
787
788 const char *default_term_for_tty(const char *tty) {
789 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
790 }
791
792 int fd_columns(int fd) {
793 struct winsize ws = {};
794
795 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
796 return -errno;
797
798 if (ws.ws_col <= 0)
799 return -EIO;
800
801 return ws.ws_col;
802 }
803
804 unsigned columns(void) {
805 const char *e;
806 int c;
807
808 if (cached_columns > 0)
809 return cached_columns;
810
811 c = 0;
812 e = getenv("COLUMNS");
813 if (e)
814 (void) safe_atoi(e, &c);
815
816 if (c <= 0 || c > USHRT_MAX) {
817 c = fd_columns(STDOUT_FILENO);
818 if (c <= 0)
819 c = 80;
820 }
821
822 cached_columns = c;
823 return cached_columns;
824 }
825
826 int fd_lines(int fd) {
827 struct winsize ws = {};
828
829 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
830 return -errno;
831
832 if (ws.ws_row <= 0)
833 return -EIO;
834
835 return ws.ws_row;
836 }
837
838 unsigned lines(void) {
839 const char *e;
840 int l;
841
842 if (cached_lines > 0)
843 return cached_lines;
844
845 l = 0;
846 e = getenv("LINES");
847 if (e)
848 (void) safe_atoi(e, &l);
849
850 if (l <= 0 || l > USHRT_MAX) {
851 l = fd_lines(STDOUT_FILENO);
852 if (l <= 0)
853 l = 24;
854 }
855
856 cached_lines = l;
857 return cached_lines;
858 }
859
860 /* intended to be used as a SIGWINCH sighandler */
861 void columns_lines_cache_reset(int signum) {
862 cached_columns = 0;
863 cached_lines = 0;
864 }
865
866 void reset_terminal_feature_caches(void) {
867 cached_columns = 0;
868 cached_lines = 0;
869
870 cached_colors_enabled = -1;
871 cached_underline_enabled = -1;
872 cached_on_tty = -1;
873 }
874
875 bool on_tty(void) {
876
877 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
878 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
879 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
880 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
881 * terminal functionality when outputting stuff, even if the input is piped to us. */
882
883 if (cached_on_tty < 0)
884 cached_on_tty =
885 isatty(STDOUT_FILENO) > 0 &&
886 isatty(STDERR_FILENO) > 0;
887
888 return cached_on_tty;
889 }
890
891 int getttyname_malloc(int fd, char **ret) {
892 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
893 int r;
894
895 assert(fd >= 0);
896 assert(ret);
897
898 r = ttyname_r(fd, path, sizeof path); /* positive error */
899 assert(r >= 0);
900 if (r == ERANGE)
901 return -ENAMETOOLONG;
902 if (r > 0)
903 return -r;
904
905 c = strdup(skip_dev_prefix(path));
906 if (!c)
907 return -ENOMEM;
908
909 *ret = c;
910 return 0;
911 }
912
913 int getttyname_harder(int fd, char **ret) {
914 _cleanup_free_ char *s = NULL;
915 int r;
916
917 r = getttyname_malloc(fd, &s);
918 if (r < 0)
919 return r;
920
921 if (streq(s, "tty"))
922 return get_ctty(0, NULL, ret);
923
924 *ret = TAKE_PTR(s);
925 return 0;
926 }
927
928 int get_ctty_devnr(pid_t pid, dev_t *d) {
929 int r;
930 _cleanup_free_ char *line = NULL;
931 const char *p;
932 unsigned long ttynr;
933
934 assert(pid >= 0);
935
936 p = procfs_file_alloca(pid, "stat");
937 r = read_one_line_file(p, &line);
938 if (r < 0)
939 return r;
940
941 p = strrchr(line, ')');
942 if (!p)
943 return -EIO;
944
945 p++;
946
947 if (sscanf(p, " "
948 "%*c " /* state */
949 "%*d " /* ppid */
950 "%*d " /* pgrp */
951 "%*d " /* session */
952 "%lu ", /* ttynr */
953 &ttynr) != 1)
954 return -EIO;
955
956 if (major(ttynr) == 0 && minor(ttynr) == 0)
957 return -ENXIO;
958
959 if (d)
960 *d = (dev_t) ttynr;
961
962 return 0;
963 }
964
965 int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
966 _cleanup_free_ char *fn = NULL, *b = NULL;
967 dev_t devnr;
968 int r;
969
970 r = get_ctty_devnr(pid, &devnr);
971 if (r < 0)
972 return r;
973
974 r = device_path_make_canonical(S_IFCHR, devnr, &fn);
975 if (r < 0) {
976 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
977 return r;
978
979 if (major(devnr) == 136) {
980 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
981 * Linux device model. This means we have no nice way to match them up against their actual
982 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
983 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
984 * this. */
985
986 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
987 return -ENOMEM;
988 } else {
989 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
990 * something vaguely useful. */
991
992 r = device_path_make_major_minor(S_IFCHR, devnr, &fn);
993 if (r < 0)
994 return r;
995 }
996 }
997
998 if (!b) {
999 const char *w;
1000
1001 w = path_startswith(fn, "/dev/");
1002 if (w) {
1003 b = strdup(w);
1004 if (!b)
1005 return -ENOMEM;
1006 } else
1007 b = TAKE_PTR(fn);
1008 }
1009
1010 if (ret)
1011 *ret = TAKE_PTR(b);
1012
1013 if (ret_devnr)
1014 *ret_devnr = devnr;
1015
1016 return 0;
1017 }
1018
1019 int ptsname_malloc(int fd, char **ret) {
1020 size_t l = 100;
1021
1022 assert(fd >= 0);
1023 assert(ret);
1024
1025 for (;;) {
1026 char *c;
1027
1028 c = new(char, l);
1029 if (!c)
1030 return -ENOMEM;
1031
1032 if (ptsname_r(fd, c, l) == 0) {
1033 *ret = c;
1034 return 0;
1035 }
1036 if (errno != ERANGE) {
1037 free(c);
1038 return -errno;
1039 }
1040
1041 free(c);
1042
1043 if (l > SIZE_MAX / 2)
1044 return -ENOMEM;
1045
1046 l *= 2;
1047 }
1048 }
1049
1050 int openpt_allocate(int flags, char **ret_slave) {
1051 _cleanup_close_ int fd = -1;
1052 _cleanup_free_ char *p = NULL;
1053 int r;
1054
1055 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1056 if (fd < 0)
1057 return -errno;
1058
1059 if (ret_slave) {
1060 r = ptsname_malloc(fd, &p);
1061 if (r < 0)
1062 return r;
1063
1064 if (!path_startswith(p, "/dev/pts/"))
1065 return -EINVAL;
1066 }
1067
1068 if (unlockpt(fd) < 0)
1069 return -errno;
1070
1071 if (ret_slave)
1072 *ret_slave = TAKE_PTR(p);
1073
1074 return TAKE_FD(fd);
1075 }
1076
1077 static int ptsname_namespace(int pty, char **ret) {
1078 int no = -1, r;
1079
1080 /* Like ptsname(), but doesn't assume that the path is
1081 * accessible in the local namespace. */
1082
1083 r = ioctl(pty, TIOCGPTN, &no);
1084 if (r < 0)
1085 return -errno;
1086
1087 if (no < 0)
1088 return -EIO;
1089
1090 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1091 return -ENOMEM;
1092
1093 return 0;
1094 }
1095
1096 int openpt_allocate_in_namespace(pid_t pid, int flags, char **ret_slave) {
1097 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1, fd = -1;
1098 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1099 pid_t child;
1100 int r;
1101
1102 assert(pid > 0);
1103
1104 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1105 if (r < 0)
1106 return r;
1107
1108 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1109 return -errno;
1110
1111 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1112 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1113 if (r < 0)
1114 return r;
1115 if (r == 0) {
1116 pair[0] = safe_close(pair[0]);
1117
1118 fd = openpt_allocate(flags, NULL);
1119 if (fd < 0)
1120 _exit(EXIT_FAILURE);
1121
1122 if (send_one_fd(pair[1], fd, 0) < 0)
1123 _exit(EXIT_FAILURE);
1124
1125 _exit(EXIT_SUCCESS);
1126 }
1127
1128 pair[1] = safe_close(pair[1]);
1129
1130 r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
1131 if (r < 0)
1132 return r;
1133 if (r != EXIT_SUCCESS)
1134 return -EIO;
1135
1136 fd = receive_one_fd(pair[0], 0);
1137 if (fd < 0)
1138 return fd;
1139
1140 if (ret_slave) {
1141 r = ptsname_namespace(fd, ret_slave);
1142 if (r < 0)
1143 return r;
1144 }
1145
1146 return TAKE_FD(fd);
1147 }
1148
1149 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1150 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1151 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1152 pid_t child;
1153 int r;
1154
1155 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1156 if (r < 0)
1157 return r;
1158
1159 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1160 return -errno;
1161
1162 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1163 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
1164 if (r < 0)
1165 return r;
1166 if (r == 0) {
1167 int master;
1168
1169 pair[0] = safe_close(pair[0]);
1170
1171 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1172 if (master < 0)
1173 _exit(EXIT_FAILURE);
1174
1175 if (send_one_fd(pair[1], master, 0) < 0)
1176 _exit(EXIT_FAILURE);
1177
1178 _exit(EXIT_SUCCESS);
1179 }
1180
1181 pair[1] = safe_close(pair[1]);
1182
1183 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
1184 if (r < 0)
1185 return r;
1186 if (r != EXIT_SUCCESS)
1187 return -EIO;
1188
1189 return receive_one_fd(pair[0], 0);
1190 }
1191
1192 static bool getenv_terminal_is_dumb(void) {
1193 const char *e;
1194
1195 e = getenv("TERM");
1196 if (!e)
1197 return true;
1198
1199 return streq(e, "dumb");
1200 }
1201
1202 bool terminal_is_dumb(void) {
1203 if (!on_tty())
1204 return true;
1205
1206 return getenv_terminal_is_dumb();
1207 }
1208
1209 bool colors_enabled(void) {
1210
1211 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1212 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1213 * 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
1214 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1215 * continuously due to fear of SAK, and hence things are a bit weird. */
1216
1217 if (cached_colors_enabled < 0) {
1218 int val;
1219
1220 val = getenv_bool("SYSTEMD_COLORS");
1221 if (val >= 0)
1222 cached_colors_enabled = val;
1223 else if (getpid_cached() == 1)
1224 /* PID1 outputs to the console without holding it open all the time */
1225 cached_colors_enabled = !getenv_terminal_is_dumb();
1226 else
1227 cached_colors_enabled = !terminal_is_dumb();
1228 }
1229
1230 return cached_colors_enabled;
1231 }
1232
1233 bool dev_console_colors_enabled(void) {
1234 _cleanup_free_ char *s = NULL;
1235 int b;
1236
1237 /* Returns true if we assume that color is supported on /dev/console.
1238 *
1239 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1240 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1241 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1242 * colors_enabled() operates. */
1243
1244 b = getenv_bool("SYSTEMD_COLORS");
1245 if (b >= 0)
1246 return b;
1247
1248 if (getenv_for_pid(1, "TERM", &s) <= 0)
1249 (void) proc_cmdline_get_key("TERM", 0, &s);
1250
1251 return !streq_ptr(s, "dumb");
1252 }
1253
1254 bool underline_enabled(void) {
1255
1256 if (cached_underline_enabled < 0) {
1257
1258 /* The Linux console doesn't support underlining, turn it off, but only there. */
1259
1260 if (colors_enabled())
1261 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1262 else
1263 cached_underline_enabled = false;
1264 }
1265
1266 return cached_underline_enabled;
1267 }
1268
1269 int vt_default_utf8(void) {
1270 _cleanup_free_ char *b = NULL;
1271 int r;
1272
1273 /* Read the default VT UTF8 setting from the kernel */
1274
1275 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1276 if (r < 0)
1277 return r;
1278
1279 return parse_boolean(b);
1280 }
1281
1282 int vt_verify_kbmode(int fd) {
1283 int curr_mode;
1284
1285 /*
1286 * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.
1287 * Otherwise we would (likely) interfere with X11's processing of the
1288 * key events.
1289 *
1290 * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
1291 */
1292
1293 if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)
1294 return -errno;
1295
1296 return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;
1297 }
1298
1299 int vt_reset_keyboard(int fd) {
1300 int kb, r;
1301
1302 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1303 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1304
1305 r = vt_verify_kbmode(fd);
1306 if (r == -EBUSY) {
1307 log_debug_errno(r, "Keyboard is not in XLATE or UNICODE mode, not resetting: %m");
1308 return 0;
1309 } else if (r < 0)
1310 return r;
1311
1312 if (ioctl(fd, KDSKBMODE, kb) < 0)
1313 return -errno;
1314
1315 return 0;
1316 }
1317
1318 int vt_restore(int fd) {
1319 static const struct vt_mode mode = {
1320 .mode = VT_AUTO,
1321 };
1322 int r, q = 0;
1323
1324 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
1325 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1326
1327 r = vt_reset_keyboard(fd);
1328 if (r < 0) {
1329 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1330 if (q >= 0)
1331 q = r;
1332 }
1333
1334 if (ioctl(fd, VT_SETMODE, &mode) < 0) {
1335 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1336 if (q >= 0)
1337 q = -errno;
1338 }
1339
1340 r = fchmod_and_chown(fd, TTY_MODE, 0, (gid_t) -1);
1341 if (r < 0) {
1342 log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m");
1343 if (q >= 0)
1344 q = r;
1345 }
1346
1347 return q;
1348 }
1349
1350 int vt_release(int fd, bool restore) {
1351 assert(fd >= 0);
1352
1353 /* This function releases the VT by acknowledging the VT-switch signal
1354 * sent by the kernel and optionally reset the VT in text and auto
1355 * VT-switching modes. */
1356
1357 if (ioctl(fd, VT_RELDISP, 1) < 0)
1358 return -errno;
1359
1360 if (restore)
1361 return vt_restore(fd);
1362
1363 return 0;
1364 }
1365
1366 void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
1367 /* Note that this will initialize output variables only when there's something to output.
1368 * The caller must pre-initalize to "" or NULL as appropriate. */
1369
1370 if (priority <= LOG_ERR) {
1371 if (on)
1372 *on = ANSI_HIGHLIGHT_RED;
1373 if (off)
1374 *off = ANSI_NORMAL;
1375 if (highlight)
1376 *highlight = ANSI_HIGHLIGHT;
1377
1378 } else if (priority <= LOG_WARNING) {
1379 if (on)
1380 *on = ANSI_HIGHLIGHT_YELLOW;
1381 if (off)
1382 *off = ANSI_NORMAL;
1383 if (highlight)
1384 *highlight = ANSI_HIGHLIGHT;
1385
1386 } else if (priority <= LOG_NOTICE) {
1387 if (on)
1388 *on = ANSI_HIGHLIGHT;
1389 if (off)
1390 *off = ANSI_NORMAL;
1391 if (highlight)
1392 *highlight = ANSI_HIGHLIGHT_RED;
1393
1394 } else if (priority >= LOG_DEBUG) {
1395 if (on)
1396 *on = ANSI_GREY;
1397 if (off)
1398 *off = ANSI_NORMAL;
1399 if (highlight)
1400 *highlight = ANSI_HIGHLIGHT_RED;
1401 }
1402 }