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