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