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