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