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