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