]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/terminal-util.c
terminal-util: modernize things with TAKE_PTR a bit
[thirdparty/systemd.git] / src / basic / terminal-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
288a74cc 2
11c3a366 3#include <errno.h>
07630cea 4#include <fcntl.h>
11c3a366 5#include <limits.h>
23b27b39
LP
6#include <linux/kd.h>
7#include <linux/tiocl.h>
8#include <linux/vt.h>
9#include <poll.h>
10#include <signal.h>
11c3a366
TA
11#include <stdarg.h>
12#include <stddef.h>
13#include <stdlib.h>
14#include <string.h>
15#include <sys/inotify.h>
23b27b39 16#include <sys/ioctl.h>
11c3a366
TA
17#include <sys/socket.h>
18#include <sys/sysmacros.h>
19#include <sys/time.h>
07630cea 20#include <sys/types.h>
23b27b39 21#include <sys/utsname.h>
288a74cc 22#include <termios.h>
07630cea 23#include <unistd.h>
288a74cc 24
b5efdb8a 25#include "alloc-util.h"
81f5e513 26#include "copy.h"
f8360f33 27#include "def.h"
acf553b0 28#include "env-util.h"
3ffd4af2 29#include "fd-util.h"
288a74cc 30#include "fileio.h"
f4f15635 31#include "fs-util.h"
c004493c 32#include "io-util.h"
93cc7779
TA
33#include "log.h"
34#include "macro.h"
0cb8e3d1 35#include "namespace-util.h"
6bedfcbb 36#include "parse-util.h"
c2b32159
LP
37#include "path-util.h"
38#include "proc-cmdline.h"
07630cea 39#include "process-util.h"
2583fbea 40#include "socket-util.h"
8fcde012 41#include "stat-util.h"
07630cea 42#include "string-util.h"
6af62124 43#include "strv.h"
3ffd4af2 44#include "terminal-util.h"
07630cea
LP
45#include "time-util.h"
46#include "util.h"
288a74cc
RC
47
48static volatile unsigned cached_columns = 0;
49static volatile unsigned cached_lines = 0;
50
c6063244
LP
51static volatile int cached_on_tty = -1;
52static volatile int cached_colors_enabled = -1;
53static volatile int cached_underline_enabled = -1;
54
288a74cc
RC
55int chvt(int vt) {
56 _cleanup_close_ int fd;
57
0295642d
LP
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
0a8b555c 61 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
62 if (fd < 0)
63 return -errno;
64
b9e74c39 65 if (vt <= 0) {
288a74cc
RC
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
83int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
715bcf36
LP
84 _cleanup_free_ char *line = NULL;
85 struct termios old_termios;
86 int r;
288a74cc
RC
87
88 assert(f);
89 assert(ret);
90
715bcf36 91 /* If this is a terminal, then switch canonical mode off, so that we can read a single character */
288a74cc 92 if (tcgetattr(fileno(f), &old_termios) >= 0) {
715bcf36 93 struct termios new_termios = old_termios;
288a74cc
RC
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) {
03a7dbea 100 char c;
288a74cc
RC
101
102 if (t != USEC_INFINITY) {
103 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
d3f9790c 104 (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios);
288a74cc
RC
105 return -ETIMEDOUT;
106 }
107 }
108
03a7dbea 109 r = safe_fgetc(f, &c);
d3f9790c 110 (void) tcsetattr(fileno(f), TCSADRAIN, &old_termios);
d3f9790c
LP
111 if (r < 0)
112 return r;
03a7dbea
LP
113 if (r == 0)
114 return -EIO;
288a74cc
RC
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
715bcf36 129 /* If this is not a terminal, then read a full line instead */
288a74cc 130
715bcf36
LP
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;
288a74cc
RC
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
3c670f89
FB
147#define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
148
149int ask_char(char *ret, const char *replies, const char *fmt, ...) {
288a74cc
RC
150 int r;
151
152 assert(ret);
153 assert(replies);
3c670f89 154 assert(fmt);
288a74cc
RC
155
156 for (;;) {
157 va_list ap;
158 char c;
159 bool need_nl = true;
160
7565bb98 161 if (colors_enabled())
1fc464f6 162 fputs(ANSI_HIGHLIGHT, stdout);
288a74cc 163
3c670f89
FB
164 putchar('\r');
165
166 va_start(ap, fmt);
167 vprintf(fmt, ap);
288a74cc
RC
168 va_end(ap);
169
7565bb98 170 if (colors_enabled())
1fc464f6 171 fputs(ANSI_NORMAL, stdout);
288a74cc
RC
172
173 fflush(stdout);
174
3c670f89 175 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
288a74cc
RC
176 if (r < 0) {
177
3c670f89
FB
178 if (r == -ETIMEDOUT)
179 continue;
180
288a74cc
RC
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
202int ask_string(char **ret, const char *text, ...) {
715bcf36
LP
203 int r;
204
288a74cc
RC
205 assert(ret);
206 assert(text);
207
208 for (;;) {
715bcf36 209 _cleanup_free_ char *line = NULL;
288a74cc
RC
210 va_list ap;
211
7565bb98 212 if (colors_enabled())
1fc464f6 213 fputs(ANSI_HIGHLIGHT, stdout);
288a74cc
RC
214
215 va_start(ap, text);
216 vprintf(text, ap);
217 va_end(ap);
218
7565bb98 219 if (colors_enabled())
1fc464f6 220 fputs(ANSI_NORMAL, stdout);
288a74cc
RC
221
222 fflush(stdout);
223
715bcf36
LP
224 r = read_line(stdin, LONG_LINE_MAX, &line);
225 if (r < 0)
226 return r;
227 if (r == 0)
228 return -EIO;
288a74cc 229
715bcf36
LP
230 if (!isempty(line)) {
231 *ret = TAKE_PTR(line);
288a74cc
RC
232 return 0;
233 }
234 }
235}
236
237int 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 */
7d927c9a 250 (void) ioctl(fd, TIOCNXCL);
288a74cc
RC
251
252 /* Switch to text mode */
253 if (switch_to_text)
7d927c9a 254 (void) ioctl(fd, KDSETMODE, KD_TEXT);
288a74cc 255
73e669e0 256 /* Set default keyboard mode */
c83f349c 257 (void) vt_reset_keyboard(fd);
288a74cc
RC
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
294finish:
295 /* Just in case, flush all crap out */
7d927c9a 296 (void) tcflush(fd, TCIOFLUSH);
288a74cc
RC
297
298 return r;
299}
300
301int reset_terminal(const char *name) {
302 _cleanup_close_ int fd = -1;
303
0a8b555c
LP
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);
288a74cc
RC
309 if (fd < 0)
310 return fd;
311
312 return reset_terminal_fd(fd, true);
313}
314
315int open_terminal(const char *name, int mode) {
288a74cc 316 unsigned c = 0;
87964ec7 317 int fd;
288a74cc
RC
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
35bdab77
LP
328 if (mode & O_CREAT)
329 return -EINVAL;
288a74cc
RC
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
87964ec7 347 if (isatty(fd) <= 0) {
288a74cc
RC
348 safe_close(fd);
349 return -ENOTTY;
350 }
351
352 return fd;
353}
354
355int acquire_terminal(
356 const char *name,
8854d795 357 AcquireTerminalFlags flags,
288a74cc
RC
358 usec_t timeout) {
359
8854d795
LP
360 _cleanup_close_ int notify = -1, fd = -1;
361 usec_t ts = USEC_INFINITY;
362 int r, wd = -1;
288a74cc
RC
363
364 assert(name);
8854d795 365 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
288a74cc 366
8854d795
LP
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.
288a74cc 369 *
8854d795
LP
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
f95dbcc2
ZJS
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
8854d795
LP
374 * probably should not do anyway.) */
375
376 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
288a74cc 377 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
8854d795
LP
378 if (notify < 0)
379 return -errno;
288a74cc
RC
380
381 wd = inotify_add_watch(notify, name, IN_CLOSE);
8854d795
LP
382 if (wd < 0)
383 return -errno;
384
385 if (timeout != USEC_INFINITY)
386 ts = now(CLOCK_MONOTONIC);
288a74cc
RC
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)
8854d795 398 return r;
288a74cc
RC
399 }
400
8854d795
LP
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 */
288a74cc
RC
403 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
404 if (fd < 0)
405 return fd;
406
8854d795 407 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
288a74cc
RC
408 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
409
410 /* First, try to get the tty */
8854d795
LP
411 r = ioctl(fd, TIOCSCTTY,
412 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
288a74cc 413
8854d795 414 /* Reset signal handler to old value */
288a74cc
RC
415 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
416
8854d795
LP
417 /* Success? Exit the loop now! */
418 if (r >= 0)
419 break;
288a74cc 420
8854d795
LP
421 /* Any failure besides -EPERM? Fail, regardless of the mode. */
422 if (r != -EPERM)
423 return r;
288a74cc 424
8854d795
LP
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. */
288a74cc
RC
428 break;
429
8854d795
LP
430 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
431 return r;
432
288a74cc 433 assert(notify >= 0);
8854d795 434 assert(wd >= 0);
288a74cc
RC
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
8854d795
LP
444 assert(ts != USEC_INFINITY);
445
288a74cc 446 n = now(CLOCK_MONOTONIC);
8854d795
LP
447 if (ts + timeout < n)
448 return -ETIMEDOUT;
288a74cc 449
f80da6f3 450 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
288a74cc 451 if (r < 0)
8854d795
LP
452 return r;
453 if (r == 0)
454 return -ETIMEDOUT;
288a74cc
RC
455 }
456
457 l = read(notify, &buffer, sizeof(buffer));
458 if (l < 0) {
3742095b 459 if (IN_SET(errno, EINTR, EAGAIN))
288a74cc
RC
460 continue;
461
8854d795 462 return -errno;
288a74cc
RC
463 }
464
465 FOREACH_INOTIFY_EVENT(e, buffer, l) {
8854d795
LP
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;
288a74cc
RC
471 }
472
473 break;
474 }
475
8854d795
LP
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. */
288a74cc
RC
478 fd = safe_close(fd);
479 }
480
c10d6bdb 481 return TAKE_FD(fd);
288a74cc
RC
482}
483
484int 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;
87964ec7 492 int r;
288a74cc 493
0a8b555c 494 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
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
87964ec7 502 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
288a74cc
RC
503
504 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
505
506 return r;
507}
508
509int 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
518int terminal_vhangup(const char *name) {
519 _cleanup_close_ int fd;
520
0a8b555c 521 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
522 if (fd < 0)
523 return fd;
524
525 return terminal_vhangup_fd(fd);
526}
527
528int vt_disallocate(const char *name) {
1ba23931 529 _cleanup_close_ int fd = -1;
27458ed6 530 const char *e, *n;
288a74cc 531 unsigned u;
1ba23931 532 int r;
288a74cc
RC
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
27458ed6
LP
538 e = path_startswith(name, "/dev/");
539 if (!e)
288a74cc
RC
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);
288a74cc
RC
555 return 0;
556 }
557
27458ed6
LP
558 n = startswith(e, "tty");
559 if (!n)
288a74cc
RC
560 return -EINVAL;
561
27458ed6 562 r = safe_atou(n, &u);
288a74cc
RC
563 if (r < 0)
564 return r;
565
566 if (u <= 0)
567 return -EINVAL;
568
569 /* Try to deallocate */
0a8b555c 570 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
571 if (fd < 0)
572 return fd;
573
574 r = ioctl(fd, VT_DISALLOCATE, u);
1ba23931 575 fd = safe_close(fd);
288a74cc
RC
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);
288a74cc
RC
594 return 0;
595}
596
288a74cc
RC
597int make_console_stdio(void) {
598 int fd, r;
599
600 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
601
8854d795 602 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
288a74cc
RC
603 if (fd < 0)
604 return log_error_errno(fd, "Failed to acquire terminal: %m");
605
3d18b167
LP
606 r = reset_terminal_fd(fd, true);
607 if (r < 0)
608 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
609
8bb2db73 610 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
288a74cc 611 if (r < 0)
8bb2db73 612 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
288a74cc 613
c6063244
LP
614 reset_terminal_feature_caches();
615
288a74cc
RC
616 return 0;
617}
618
288a74cc
RC
619bool tty_is_vc(const char *tty) {
620 assert(tty);
621
622 return vtnr_from_tty(tty) >= 0;
623}
624
625bool tty_is_console(const char *tty) {
626 assert(tty);
627
a119ec7c 628 return streq(skip_dev_prefix(tty), "console");
288a74cc
RC
629}
630
631int vtnr_from_tty(const char *tty) {
632 int i, r;
633
634 assert(tty);
635
a119ec7c 636 tty = skip_dev_prefix(tty);
288a74cc
RC
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
7b912648
LP
654 int resolve_dev_console(char **ret) {
655 _cleanup_free_ char *active = NULL;
288a74cc 656 char *tty;
7b912648 657 int r;
288a74cc 658
7b912648
LP
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) */
288a74cc
RC
663
664 if (path_is_read_only_fs("/sys") > 0)
7b912648 665 return -ENOMEDIUM;
288a74cc 666
7b912648
LP
667 r = read_one_line_file("/sys/class/tty/console/active", &active);
668 if (r < 0)
669 return r;
288a74cc 670
7b912648
LP
671 /* If multiple log outputs are configured the last one is what /dev/console points to */
672 tty = strrchr(active, ' ');
288a74cc
RC
673 if (tty)
674 tty++;
675 else
7b912648 676 tty = active;
288a74cc
RC
677
678 if (streq(tty, "tty0")) {
7b912648 679 active = mfree(active);
288a74cc
RC
680
681 /* Get the active VC (e.g. tty1) */
7b912648
LP
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
ae2a15bc
LP
689 if (tty == active)
690 *ret = TAKE_PTR(active);
691 else {
7b912648
LP
692 char *tmp;
693
694 tmp = strdup(tty);
695 if (!tmp)
696 return -ENOMEM;
697
698 *ret = tmp;
288a74cc
RC
699 }
700
7b912648 701 return 0;
288a74cc
RC
702}
703
bef41af2
LP
704int get_kernel_consoles(char ***ret) {
705 _cleanup_strv_free_ char **l = NULL;
6af62124 706 _cleanup_free_ char *line = NULL;
bef41af2 707 const char *p;
6af62124
WF
708 int r;
709
bef41af2
LP
710 assert(ret);
711
f95dbcc2 712 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
bef41af2
LP
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;
6af62124
WF
716
717 r = read_one_line_file("/sys/class/tty/console/active", &line);
718 if (r < 0)
719 return r;
720
bef41af2 721 p = line;
6af62124
WF
722 for (;;) {
723 _cleanup_free_ char *tty = NULL;
724 char *path;
725
bef41af2 726 r = extract_first_word(&p, &tty, NULL, 0);
6af62124
WF
727 if (r < 0)
728 return r;
729 if (r == 0)
730 break;
731
732 if (streq(tty, "tty0")) {
733 tty = mfree(tty);
734 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
735 if (r < 0)
736 return r;
737 }
738
739 path = strappend("/dev/", tty);
740 if (!path)
741 return -ENOMEM;
742
743 if (access(path, F_OK) < 0) {
744 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
745 free(path);
746 continue;
747 }
748
bef41af2 749 r = strv_consume(&l, path);
6af62124
WF
750 if (r < 0)
751 return r;
752 }
753
bef41af2 754 if (strv_isempty(l)) {
6af62124 755 log_debug("No devices found for system console");
bef41af2 756 goto fallback;
6af62124
WF
757 }
758
ae2a15bc 759 *ret = TAKE_PTR(l);
bef41af2
LP
760
761 return 0;
762
763fallback:
764 r = strv_extend(&l, "/dev/console");
765 if (r < 0)
766 return r;
767
ae2a15bc 768 *ret = TAKE_PTR(l);
bef41af2 769
6af62124
WF
770 return 0;
771}
772
288a74cc 773bool tty_is_vc_resolve(const char *tty) {
7b912648 774 _cleanup_free_ char *resolved = NULL;
288a74cc
RC
775
776 assert(tty);
777
a119ec7c 778 tty = skip_dev_prefix(tty);
288a74cc
RC
779
780 if (streq(tty, "console")) {
7b912648 781 if (resolve_dev_console(&resolved) < 0)
288a74cc 782 return false;
7b912648
LP
783
784 tty = resolved;
288a74cc
RC
785 }
786
787 return tty_is_vc(tty);
788}
789
790const char *default_term_for_tty(const char *tty) {
6af760f3 791 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
288a74cc
RC
792}
793
794int fd_columns(int fd) {
795 struct winsize ws = {};
796
797 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
798 return -errno;
799
800 if (ws.ws_col <= 0)
801 return -EIO;
802
803 return ws.ws_col;
804}
805
806unsigned columns(void) {
807 const char *e;
808 int c;
809
c6063244 810 if (cached_columns > 0)
288a74cc
RC
811 return cached_columns;
812
813 c = 0;
814 e = getenv("COLUMNS");
815 if (e)
816 (void) safe_atoi(e, &c);
817
d09a7135 818 if (c <= 0 || c > USHRT_MAX) {
288a74cc 819 c = fd_columns(STDOUT_FILENO);
d09a7135
LP
820 if (c <= 0)
821 c = 80;
822 }
288a74cc
RC
823
824 cached_columns = c;
825 return cached_columns;
826}
827
828int fd_lines(int fd) {
829 struct winsize ws = {};
830
831 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
832 return -errno;
833
834 if (ws.ws_row <= 0)
835 return -EIO;
836
837 return ws.ws_row;
838}
839
840unsigned lines(void) {
841 const char *e;
842 int l;
843
c6063244 844 if (cached_lines > 0)
288a74cc
RC
845 return cached_lines;
846
847 l = 0;
848 e = getenv("LINES");
849 if (e)
850 (void) safe_atoi(e, &l);
851
d09a7135 852 if (l <= 0 || l > USHRT_MAX) {
288a74cc 853 l = fd_lines(STDOUT_FILENO);
d09a7135
LP
854 if (l <= 0)
855 l = 24;
856 }
288a74cc
RC
857
858 cached_lines = l;
859 return cached_lines;
860}
861
862/* intended to be used as a SIGWINCH sighandler */
863void columns_lines_cache_reset(int signum) {
864 cached_columns = 0;
865 cached_lines = 0;
866}
867
c6063244
LP
868void reset_terminal_feature_caches(void) {
869 cached_columns = 0;
870 cached_lines = 0;
871
872 cached_colors_enabled = -1;
873 cached_underline_enabled = -1;
874 cached_on_tty = -1;
875}
288a74cc 876
c6063244 877bool on_tty(void) {
8cd0356e
LP
878
879 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
880 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
881 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
882 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
883 * terminal functionality when outputting stuff, even if the input is piped to us. */
884
c6063244 885 if (cached_on_tty < 0)
8cd0356e
LP
886 cached_on_tty =
887 isatty(STDOUT_FILENO) > 0 &&
888 isatty(STDERR_FILENO) > 0;
288a74cc
RC
889
890 return cached_on_tty;
891}
892
288a74cc 893int getttyname_malloc(int fd, char **ret) {
30222f4b 894 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
288a74cc
RC
895 int r;
896
897 assert(fd >= 0);
898 assert(ret);
899
30222f4b
ZJS
900 r = ttyname_r(fd, path, sizeof path); /* positive error */
901 assert(r >= 0);
902 if (r == ERANGE)
903 return -ENAMETOOLONG;
904 if (r > 0)
905 return -r;
288a74cc 906
30222f4b
ZJS
907 c = strdup(skip_dev_prefix(path));
908 if (!c)
909 return -ENOMEM;
288a74cc 910
30222f4b 911 *ret = c;
288a74cc
RC
912 return 0;
913}
914
f171decd
LP
915int getttyname_harder(int fd, char **ret) {
916 _cleanup_free_ char *s = NULL;
917 int r;
288a74cc 918
f171decd
LP
919 r = getttyname_malloc(fd, &s);
920 if (r < 0)
921 return r;
288a74cc 922
f171decd
LP
923 if (streq(s, "tty"))
924 return get_ctty(0, NULL, ret);
288a74cc 925
f171decd 926 *ret = TAKE_PTR(s);
288a74cc
RC
927 return 0;
928}
929
930int get_ctty_devnr(pid_t pid, dev_t *d) {
931 int r;
932 _cleanup_free_ char *line = NULL;
933 const char *p;
934 unsigned long ttynr;
935
936 assert(pid >= 0);
937
938 p = procfs_file_alloca(pid, "stat");
939 r = read_one_line_file(p, &line);
940 if (r < 0)
941 return r;
942
943 p = strrchr(line, ')');
944 if (!p)
945 return -EIO;
946
947 p++;
948
949 if (sscanf(p, " "
950 "%*c " /* state */
951 "%*d " /* ppid */
952 "%*d " /* pgrp */
953 "%*d " /* session */
954 "%lu ", /* ttynr */
955 &ttynr) != 1)
956 return -EIO;
957
958 if (major(ttynr) == 0 && minor(ttynr) == 0)
cfeaa44a 959 return -ENXIO;
288a74cc
RC
960
961 if (d)
962 *d = (dev_t) ttynr;
963
964 return 0;
965}
966
54b22b26
LP
967int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
968 _cleanup_free_ char *fn = NULL, *b = NULL;
288a74cc 969 dev_t devnr;
54b22b26 970 int r;
288a74cc 971
54b22b26
LP
972 r = get_ctty_devnr(pid, &devnr);
973 if (r < 0)
974 return r;
288a74cc 975
54b22b26
LP
976 r = device_path_make_canonical(S_IFCHR, devnr, &fn);
977 if (r < 0) {
978 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
979 return r;
288a74cc 980
288a74cc 981 if (major(devnr) == 136) {
54b22b26
LP
982 /* This is an ugly hack: PTY devices are not listed in /dev/char/, as they don't follow the
983 * Linux device model. This means we have no nice way to match them up against their actual
984 * device node. Let's hence do the check by the fixed, assigned major number. Normally we try
985 * to avoid such fixed major/minor matches, but there appears to nother nice way to handle
986 * this. */
987
288a74cc
RC
988 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
989 return -ENOMEM;
990 } else {
54b22b26
LP
991 /* Probably something similar to the ptys which have no symlink in /dev/char/. Let's return
992 * something vaguely useful. */
288a74cc 993
54b22b26
LP
994 r = device_path_make_major_minor(S_IFCHR, devnr, &fn);
995 if (r < 0)
996 return r;
288a74cc 997 }
54b22b26 998 }
288a74cc 999
54b22b26
LP
1000 if (!b) {
1001 const char *w;
1002
1003 w = path_startswith(fn, "/dev/");
1004 if (w) {
1005 b = strdup(w);
1006 if (!b)
1007 return -ENOMEM;
1008 } else
1009 b = TAKE_PTR(fn);
288a74cc
RC
1010 }
1011
54b22b26
LP
1012 if (ret)
1013 *ret = TAKE_PTR(b);
1014
1015 if (ret_devnr)
1016 *ret_devnr = devnr;
288a74cc
RC
1017
1018 return 0;
1019}
a07c35c3 1020
66cb2fde
LP
1021int ptsname_malloc(int fd, char **ret) {
1022 size_t l = 100;
1023
1024 assert(fd >= 0);
1025 assert(ret);
1026
1027 for (;;) {
1028 char *c;
1029
1030 c = new(char, l);
1031 if (!c)
1032 return -ENOMEM;
1033
1034 if (ptsname_r(fd, c, l) == 0) {
1035 *ret = c;
1036 return 0;
1037 }
1038 if (errno != ERANGE) {
1039 free(c);
1040 return -errno;
1041 }
1042
1043 free(c);
1044 l *= 2;
1045 }
1046}
1047
a07c35c3
LP
1048int ptsname_namespace(int pty, char **ret) {
1049 int no = -1, r;
1050
1051 /* Like ptsname(), but doesn't assume that the path is
1052 * accessible in the local namespace. */
1053
1054 r = ioctl(pty, TIOCGPTN, &no);
1055 if (r < 0)
1056 return -errno;
1057
1058 if (no < 0)
1059 return -EIO;
1060
1061 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1062 return -ENOMEM;
1063
1064 return 0;
1065}
66cb2fde
LP
1066
1067int openpt_in_namespace(pid_t pid, int flags) {
1068 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1069 _cleanup_close_pair_ int pair[2] = { -1, -1 };
66cb2fde
LP
1070 pid_t child;
1071 int r;
1072
1073 assert(pid > 0);
1074
1075 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1076 if (r < 0)
1077 return r;
1078
1079 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1080 return -errno;
1081
1edcb6a9
LP
1082 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1083 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
4c253ed1
LP
1084 if (r < 0)
1085 return r;
1086 if (r == 0) {
66cb2fde
LP
1087 int master;
1088
1089 pair[0] = safe_close(pair[0]);
1090
66cb2fde
LP
1091 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1092 if (master < 0)
1093 _exit(EXIT_FAILURE);
1094
1095 if (unlockpt(master) < 0)
1096 _exit(EXIT_FAILURE);
1097
1098 if (send_one_fd(pair[1], master, 0) < 0)
1099 _exit(EXIT_FAILURE);
1100
1101 _exit(EXIT_SUCCESS);
1102 }
1103
1104 pair[1] = safe_close(pair[1]);
1105
1edcb6a9 1106 r = wait_for_terminate_and_check("(sd-openptns)", child, 0);
66cb2fde
LP
1107 if (r < 0)
1108 return r;
2e87a1fd 1109 if (r != EXIT_SUCCESS)
66cb2fde
LP
1110 return -EIO;
1111
1112 return receive_one_fd(pair[0], 0);
1113}
40e1f4ea
LP
1114
1115int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1116 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1117 _cleanup_close_pair_ int pair[2] = { -1, -1 };
40e1f4ea
LP
1118 pid_t child;
1119 int r;
1120
1121 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1122 if (r < 0)
1123 return r;
1124
1125 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1126 return -errno;
1127
1edcb6a9
LP
1128 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG,
1129 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
4c253ed1
LP
1130 if (r < 0)
1131 return r;
1132 if (r == 0) {
40e1f4ea
LP
1133 int master;
1134
1135 pair[0] = safe_close(pair[0]);
1136
40e1f4ea
LP
1137 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1138 if (master < 0)
1139 _exit(EXIT_FAILURE);
1140
1141 if (send_one_fd(pair[1], master, 0) < 0)
1142 _exit(EXIT_FAILURE);
1143
1144 _exit(EXIT_SUCCESS);
1145 }
1146
1147 pair[1] = safe_close(pair[1]);
1148
1edcb6a9 1149 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
40e1f4ea
LP
1150 if (r < 0)
1151 return r;
2e87a1fd 1152 if (r != EXIT_SUCCESS)
40e1f4ea
LP
1153 return -EIO;
1154
1155 return receive_one_fd(pair[0], 0);
1156}
40c9fe4c 1157
158fbf76 1158static bool getenv_terminal_is_dumb(void) {
ac96418b
LP
1159 const char *e;
1160
ac96418b
LP
1161 e = getenv("TERM");
1162 if (!e)
1163 return true;
1164
1165 return streq(e, "dumb");
1166}
1167
158fbf76
ZJS
1168bool terminal_is_dumb(void) {
1169 if (!on_tty())
1170 return true;
1171
1172 return getenv_terminal_is_dumb();
1173}
1174
40c9fe4c 1175bool colors_enabled(void) {
40c9fe4c 1176
0295642d 1177 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
f95dbcc2 1178 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
0295642d
LP
1179 * 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
1180 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1181 * continously due to fear of SAK, and hence things are a bit weird. */
1182
c6063244 1183 if (cached_colors_enabled < 0) {
acf553b0 1184 int val;
ae5b3958 1185
acf553b0
ZJS
1186 val = getenv_bool("SYSTEMD_COLORS");
1187 if (val >= 0)
c6063244 1188 cached_colors_enabled = val;
df0ff127 1189 else if (getpid_cached() == 1)
158fbf76 1190 /* PID1 outputs to the console without holding it open all the time */
c6063244 1191 cached_colors_enabled = !getenv_terminal_is_dumb();
ae5b3958 1192 else
c6063244 1193 cached_colors_enabled = !terminal_is_dumb();
40c9fe4c
JS
1194 }
1195
c6063244 1196 return cached_colors_enabled;
40c9fe4c 1197}
c83f349c 1198
c2b32159
LP
1199bool dev_console_colors_enabled(void) {
1200 _cleanup_free_ char *s = NULL;
1201 int b;
1202
1203 /* Returns true if we assume that color is supported on /dev/console.
1204 *
1205 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
f95dbcc2
ZJS
1206 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1207 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
c2b32159
LP
1208 * colors_enabled() operates. */
1209
1210 b = getenv_bool("SYSTEMD_COLORS");
1211 if (b >= 0)
1212 return b;
1213
1214 if (getenv_for_pid(1, "TERM", &s) <= 0)
1215 (void) proc_cmdline_get_key("TERM", 0, &s);
1216
1217 return !streq_ptr(s, "dumb");
1218}
1219
526664f6 1220bool underline_enabled(void) {
526664f6 1221
c6063244 1222 if (cached_underline_enabled < 0) {
526664f6
LP
1223
1224 /* The Linux console doesn't support underlining, turn it off, but only there. */
1225
c6063244
LP
1226 if (colors_enabled())
1227 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
526664f6 1228 else
c6063244 1229 cached_underline_enabled = false;
526664f6
LP
1230 }
1231
c6063244 1232 return cached_underline_enabled;
526664f6
LP
1233}
1234
c83f349c
LP
1235int vt_default_utf8(void) {
1236 _cleanup_free_ char *b = NULL;
1237 int r;
1238
1239 /* Read the default VT UTF8 setting from the kernel */
1240
1241 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1242 if (r < 0)
1243 return r;
1244
1245 return parse_boolean(b);
1246}
1247
1248int vt_reset_keyboard(int fd) {
1249 int kb;
1250
1251 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1252 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1253
1254 if (ioctl(fd, KDSKBMODE, kb) < 0)
1255 return -errno;
1256
1257 return 0;
1258}
6179ede1
FB
1259
1260int vt_restore(int fd) {
1261 static const struct vt_mode mode = {
1262 .mode = VT_AUTO,
1263 };
1264 int r, q = 0;
1265
1266 r = ioctl(fd, KDSETMODE, KD_TEXT);
1267 if (r < 0)
1268 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1269
1270 r = vt_reset_keyboard(fd);
1271 if (r < 0) {
1272 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1273 if (q >= 0)
1274 q = r;
1275 }
1276
1277 r = ioctl(fd, VT_SETMODE, &mode);
1278 if (r < 0) {
1279 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1280 if (q >= 0)
1281 q = -errno;
1282 }
1283
1284 r = fchown(fd, 0, (gid_t) -1);
1285 if (r < 0) {
1286 log_debug_errno(errno, "Failed to chown VT, ignoring: %m");
1287 if (q >= 0)
1288 q = -errno;
1289 }
1290
1291 return q;
1292}
27dafac9
FB
1293
1294int vt_release(int fd, bool restore) {
1295 assert(fd >= 0);
1296
1297 /* This function releases the VT by acknowledging the VT-switch signal
1298 * sent by the kernel and optionally reset the VT in text and auto
1299 * VT-switching modes. */
1300
1301 if (ioctl(fd, VT_RELDISP, 1) < 0)
1302 return -errno;
1303
1304 if (restore)
1305 return vt_restore(fd);
1306
1307 return 0;
1308}