Debian Codegraph @

src/basic/terminal-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/kd.h>
5 #include <linux/magic.h>
6 #include <linux/tiocl.h>
7 #include <linux/vt.h>
8 #include <poll.h>
9 #include <signal.h>
10 #include <stdlib.h>
11 #include <sys/inotify.h>
12 #include <sys/ioctl.h>
13 #include <sys/sysmacros.h>
14 #include <termios.h>
15 #include <time.h>
16 #include <unistd.h>
17
18 #include "alloc-util.h"
19 #include "ansi-color.h"
20 #include "chase.h"
21 #include "devnum-util.h"
22 #include "errno-util.h"
23 #include "extract-word.h"
24 #include "fd-util.h"
25 #include "fileio.h"
26 #include "fs-util.h"
27 #include "hexdecoct.h"
28 #include "inotify-util.h"
29 #include "io-util.h"
30 #include "log.h"
31 #include "namespace-util.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "pidref.h"
35 #include "proc-cmdline.h"
36 #include "process-util.h"
37 #include "signal-util.h"
38 #include "socket-util.h"
39 #include "stat-util.h"
40 #include "stdio-util.h"
41 #include "string-util.h"
42 #include "strv.h"
43 #include "terminal-util.h"
44 #include "time-util.h"
45 #include "utf8.h"
46
47 /* How much to wait when reading/writing ANSI sequences from/to the console */
48 #define CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC (333 * USEC_PER_MSEC)
49
50 static volatile unsigned cached_columns = 0;
51 static volatile unsigned cached_lines = 0;
52
53 static volatile int cached_on_tty = -1;
54 static volatile int cached_on_dev_null = -1;
55
56 bool isatty_safe(int fd) {
57 assert(fd >= 0);
58
59 if (isatty(fd))
60 return true;
61
62 /* Linux/glibc returns EIO for hung up TTY on isatty(). Which is wrong, the thing doesn't stop being
63 * a TTY after all, just because it is temporarily hung up. Let's work around this here, until this
64 * is fixed in glibc. See: https://sourceware.org/bugzilla/show_bug.cgi?id=32103 */
65 if (errno == EIO)
66 return true;
67
68 /* Be resilient if we're working on stdio, since they're set up by parent process. */
69 assert(errno != EBADF || IN_SET(fd, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO));
70
71 return false;
72 }
73
74 int chvt(int vt) {
75 _cleanup_close_ int fd = -EBADF;
76
77 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
78 * if that's configured. */
79
80 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
81 if (fd < 0)
82 return fd;
83
84 if (vt <= 0) {
85 int tiocl[2] = {
86 TIOCL_GETKMSGREDIRECT,
87 0
88 };
89
90 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
91 return -errno;
92
93 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
94 }
95
96 return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
97 }
98
99 int read_one_char(FILE *f, char *ret, usec_t t, bool echo, bool *need_nl) {
100 _cleanup_free_ char *line = NULL;
101 struct termios old_termios;
102 int r, fd;
103
104 assert(ret);
105
106 if (!f)
107 f = stdin;
108
109 /* If this is a terminal, then switch canonical mode off, so that we can read a single
110 * character. (Note that fmemopen() streams do not have an fd associated with them, let's handle that
111 * nicely.) If 'echo' is false we'll also disable ECHO mode so that the pressed key is not made
112 * visible to the user. */
113 fd = fileno(f);
114 if (fd >= 0 && tcgetattr(fd, &old_termios) >= 0) {
115 struct termios new_termios = old_termios;
116
117 new_termios.c_lflag &= ~(ICANON|(echo ? 0 : ECHO));
118 new_termios.c_cc[VMIN] = 1;
119 new_termios.c_cc[VTIME] = 0;
120
121 if (tcsetattr(fd, TCSANOW, &new_termios) >= 0) {
122 char c;
123
124 if (t != USEC_INFINITY) {
125 if (fd_wait_for_event(fd, POLLIN, t) <= 0) {
126 (void) tcsetattr(fd, TCSANOW, &old_termios);
127 return -ETIMEDOUT;
128 }
129 }
130
131 r = safe_fgetc(f, &c);
132 (void) tcsetattr(fd, TCSANOW, &old_termios);
133 if (r < 0)
134 return r;
135 if (r == 0)
136 return -EIO;
137
138 if (need_nl)
139 *need_nl = c != '\n';
140
141 *ret = c;
142 return 0;
143 }
144 }
145
146 if (t != USEC_INFINITY && fd >= 0) {
147 /* Let's wait the specified amount of time for input. When we have no fd we skip this, under
148 * the assumption that this is an fmemopen() stream or so where waiting doesn't make sense
149 * anyway, as the data is either already in the stream or cannot possible be placed there
150 * while we access the stream */
151
152 if (fd_wait_for_event(fd, POLLIN, t) <= 0)
153 return -ETIMEDOUT;
154 }
155
156 /* If this is not a terminal, then read a full line instead */
157
158 r = read_line(f, 16, &line); /* longer than necessary, to eat up UTF-8 chars/vt100 key sequences */
159 if (r < 0)
160 return r;
161 if (r == 0)
162 return -EIO;
163
164 if (strlen(line) != 1)
165 return -EBADMSG;
166
167 if (need_nl)
168 *need_nl = false;
169
170 *ret = line[0];
171 return 0;
172 }
173
174 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
175
176 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
177 int r;
178
179 assert(ret);
180 assert(replies);
181 assert(fmt);
182
183 for (;;) {
184 va_list ap;
185 char c;
186 bool need_nl = true;
187
188 fputs(ansi_highlight(), stdout);
189
190 putchar('\r');
191
192 va_start(ap, fmt);
193 vprintf(fmt, ap);
194 va_end(ap);
195
196 fputs(ansi_normal(), stdout);
197
198 fflush(stdout);
199
200 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, /* echo= */ true, &need_nl);
201 if (r < 0) {
202
203 if (r == -ETIMEDOUT)
204 continue;
205
206 if (r == -EBADMSG) {
207 puts("Bad input, please try again.");
208 continue;
209 }
210
211 putchar('\n');
212 return r;
213 }
214
215 if (need_nl)
216 putchar('\n');
217
218 if (strchr(replies, c)) {
219 *ret = c;
220 return 0;
221 }
222
223 puts("Read unexpected character, please try again.");
224 }
225 }
226
227 typedef enum CompletionResult{
228 COMPLETION_ALREADY, /* the input string is already complete */
229 COMPLETION_FULL, /* completed the input string to be complete now */
230 COMPLETION_PARTIAL, /* completed the input string so that is still incomplete */
231 COMPLETION_NONE, /* found no matching completion */
232 _COMPLETION_RESULT_MAX,
233 _COMPLETION_RESULT_INVALID = -EINVAL,
234 _COMPLETION_RESULT_ERRNO_MAX = -ERRNO_MAX,
235 } CompletionResult;
236
237 static CompletionResult pick_completion(const char *string, char *const*completions, char **ret) {
238 _cleanup_free_ char *found = NULL;
239 bool partial = false;
240
241 string = strempty(string);
242
243 STRV_FOREACH(c, completions) {
244
245 /* Ignore entries that are not actually completions */
246 if (!startswith(*c, string))
247 continue;
248
249 /* Store first completion that matches */
250 if (!found) {
251 found = strdup(*c);
252 if (!found)
253 return -ENOMEM;
254
255 continue;
256 }
257
258 /* If there's another completion that works truncate the one we already found by common
259 * prefix */
260 size_t n = str_common_prefix(found, *c);
261 if (n == SIZE_MAX)
262 continue;
263
264 found[n] = 0;
265 partial = true;
266 }
267
268 *ret = TAKE_PTR(found);
269
270 if (!*ret)
271 return COMPLETION_NONE;
272 if (partial)
273 return COMPLETION_PARTIAL;
274
275 return streq(string, *ret) ? COMPLETION_ALREADY : COMPLETION_FULL;
276 }
277
278 static void clear_by_backspace(size_t n) {
279 /* Erase the specified number of character cells backwards on the terminal */
280 for (size_t i = 0; i < n; i++)
281 fputs("\b \b", stdout);
282 }
283
284 int ask_string_full(
285 char **ret,
286 const char *prefill,
287 GetCompletionsCallback get_completions,
288 void *userdata,
289 const char *text, ...) {
290
291 va_list ap;
292 int r;
293
294 assert(ret);
295 assert(text);
296
297 _cleanup_free_ char *string = NULL;
298 size_t n = 0;
299
300 if (prefill) {
301 /* Prefill query with explicit data if specified */
302
303 string = strdup(prefill);
304 if (!string)
305 return -ENOMEM;
306
307 n = strlen(string);
308
309 } else if (get_completions) {
310 /* Otherwise, figure out what string to preselect the query with */
311 _cleanup_strv_free_ char **completions = NULL;
312 r = get_completions("", GET_COMPLETIONS_PRESELECT, &completions, userdata);
313 if (r < 0)
314 return r;
315
316 CompletionResult cr = pick_completion(string, completions, &string);
317 if (cr < 0)
318 return cr;
319
320 n = strlen_ptr(string);
321 }
322
323 /* Output the prompt */
324 fputs(ansi_highlight(), stdout);
325 va_start(ap, text);
326 vprintf(text, ap);
327 va_end(ap);
328 fputs(ansi_normal(), stdout);
329 if (string)
330 fputs(string, stdout);
331 fflush(stdout);
332
333 /* Do interactive logic only if stdin + stdout are connected to the same place. And yes, we could use
334 * STDIN_FILENO and STDOUT_FILENO here, but let's be overly correct for once, after all libc allows
335 * swapping out stdin/stdout. */
336 int fd_input = fileno(stdin);
337 int fd_output = fileno(stdout);
338 struct termios old_termios = TERMIOS_NULL;
339 CLEANUP_TERMIOS_RESET(fd_input, old_termios);
340
341 if (fd_input < 0 || fd_output < 0 || same_fd(fd_input, fd_output) <= 0)
342 goto fallback;
343
344 /* Try to disable echo, which also tells us if this even is a terminal */
345 if (tcgetattr(fd_input, &old_termios) < 0) {
346 old_termios = TERMIOS_NULL;
347 goto fallback;
348 }
349
350 struct termios new_termios = old_termios;
351 termios_disable_echo(&new_termios);
352 if (tcsetattr(fd_input, TCSANOW, &new_termios) < 0)
353 return -errno;
354
355 for (;;) {
356 int c = fgetc(stdin);
357
358 /* On EOF or NUL, end the request, don't output anything anymore */
359 if (IN_SET(c, EOF, 0))
360 break;
361
362 /* On Return also end the request, but make this visible */
363 if (IN_SET(c, '\n', '\r')) {
364 fputc('\n', stdout);
365 break;
366 }
367
368 if (c == '\t') {
369 /* Tab */
370
371 _cleanup_strv_free_ char **completions = NULL;
372 if (get_completions) {
373 r = get_completions(string, /* flags= */ 0, &completions, userdata);
374 if (r < 0)
375 return r;
376 }
377
378 _cleanup_free_ char *new_string = NULL;
379 CompletionResult cr = pick_completion(string, completions, &new_string);
380 if (cr < 0)
381 return cr;
382 if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_FULL)) {
383 /* Output the new suffix we learned */
384 fputs(ASSERT_PTR(startswith(new_string, strempty(string))), stdout);
385
386 /* And update the whole string */
387 free_and_replace(string, new_string);
388 n = strlen(string);
389 }
390 if (cr == COMPLETION_NONE)
391 fputc('\a', stdout); /* BEL */
392
393 if (IN_SET(cr, COMPLETION_PARTIAL, COMPLETION_ALREADY)) {
394 /* If this worked only partially, or if the user hit TAB even though we were
395 * complete already, then show the remaining options (in the latter case just
396 * the one). */
397 fputc('\n', stdout);
398
399 _cleanup_strv_free_ char **filtered = strv_filter_prefix(completions, string);
400 if (!filtered)
401 return -ENOMEM;
402
403 r = show_menu(filtered,
404 /* n_columns= */ SIZE_MAX,
405 /* column_width= */ SIZE_MAX,
406 /* ellipsize_percentage= */ 0,
407 /* grey_prefix= */ string,
408 /* with_numbers= */ false);
409 if (r < 0)
410 return r;
411
412 /* Show the prompt again */
413 fputs(ansi_highlight(), stdout);
414 va_start(ap, text);
415 vprintf(text, ap);
416 va_end(ap);
417 fputs(ansi_normal(), stdout);
418 fputs(string, stdout);
419 }
420
421 } else if (IN_SET(c, '\b', 127)) {
422 /* Backspace */
423
424 if (n == 0)
425 fputc('\a', stdout); /* BEL */
426 else {
427 size_t m = utf8_last_length(string, n);
428
429 char *e = string + n - m;
430 clear_by_backspace(utf8_console_width(e));
431
432 *e = 0;
433 n -= m;
434 }
435
436 } else if (c == 21) {
437 /* Ctrl-u → erase all input */
438
439 clear_by_backspace(utf8_console_width(string));
440 if (string)
441 string[n = 0] = 0;
442 else
443 assert(n == 0);
444
445 } else if (c == 4) {
446 /* Ctrl-d → cancel this field input */
447
448 return -ECANCELED;
449
450 } else if (char_is_cc(c) || n >= LINE_MAX)
451 /* refuse control characters and too long strings */
452 fputc('\a', stdout); /* BEL */
453 else {
454 /* Regular char */
455
456 if (!GREEDY_REALLOC(string, n+2))
457 return -ENOMEM;
458
459 string[n++] = (char) c;
460 string[n] = 0;
461
462 fputc(c, stdout);
463 }
464
465 fflush(stdout);
466 }
467
468 if (!string) {
469 string = strdup("");
470 if (!string)
471 return -ENOMEM;
472 }
473
474 *ret = TAKE_PTR(string);
475 return 0;
476
477 fallback:
478 /* A simple fallback without TTY magic */
479 string = mfree(string);
480 r = read_line(stdin, LONG_LINE_MAX, &string);
481 if (r < 0)
482 return r;
483 if (r == 0)
484 return -EIO;
485
486 *ret = TAKE_PTR(string);
487 return 0;
488 }
489
490 bool any_key_to_proceed(void) {
491
492 /* Insert a new line here as well as to when the user inputs, as this is also used during the boot up
493 * sequence when status messages may be interleaved with the current program output. This ensures
494 * that the status messages aren't appended on the same line as this message. */
495
496 fputc('\n', stdout);
497 fputs(ansi_highlight_magenta(), stdout);
498 fputs("-- Press any key to proceed --", stdout);
499 fputs(ansi_normal(), stdout);
500 fputc('\n', stdout);
501 fflush(stdout);
502
503 char key = 0;
504 (void) read_one_char(stdin, &key, USEC_INFINITY, /* echo= */ false, /* need_nl= */ NULL);
505
506 fputc('\n', stdout);
507 fflush(stdout);
508
509 return key != 'q';
510 }
511
512 static size_t widest_list_element(char *const*l) {
513 size_t w = 0;
514
515 /* Returns the largest console width of all elements in 'l' */
516
517 STRV_FOREACH(i, l)
518 w = MAX(w, utf8_console_width(*i));
519
520 return w;
521 }
522
523 int show_menu(char **x,
524 size_t n_columns,
525 size_t column_width,
526 unsigned ellipsize_percentage,
527 const char *grey_prefix,
528 bool with_numbers) {
529
530 assert(n_columns > 0);
531
532 if (n_columns == SIZE_MAX)
533 n_columns = 3;
534
535 if (column_width == SIZE_MAX) {
536 size_t widest = widest_list_element(x);
537
538 /* If not specified, derive column width from screen width */
539 size_t column_max = (columns()-1) / n_columns;
540
541 /* Subtract room for numbers */
542 if (with_numbers && column_max > 6)
543 column_max -= 6;
544
545 /* If columns would get too tight let's make this a linear list instead. */
546 if (column_max < 10 && widest > 10) {
547 n_columns = 1;
548 column_max = columns()-1;
549
550 if (with_numbers && column_max > 6)
551 column_max -= 6;
552 }
553
554 column_width = CLAMP(widest+1, 10U, column_max);
555 }
556
557 size_t n = strv_length(x);
558 size_t per_column = DIV_ROUND_UP(n, n_columns);
559
560 size_t break_lines = lines();
561 if (break_lines > 2)
562 break_lines--;
563
564 /* The first page gets two extra lines, since we want to show
565 * a title */
566 size_t break_modulo = break_lines;
567 if (break_modulo > 3)
568 break_modulo -= 3;
569
570 for (size_t i = 0; i < per_column; i++) {
571
572 for (size_t j = 0; j < n_columns; j++) {
573 _cleanup_free_ char *e = NULL;
574
575 if (j * per_column + i >= n)
576 break;
577
578 e = ellipsize(x[j * per_column + i], column_width, ellipsize_percentage);
579 if (!e)
580 return -ENOMEM;
581
582 if (with_numbers)
583 printf("%s%4zu)%s ",
584 ansi_grey(),
585 j * per_column + i + 1,
586 ansi_normal());
587
588 if (grey_prefix && startswith(e, grey_prefix)) {
589 size_t k = MIN(strlen(grey_prefix), column_width);
590 printf("%s%.*s%s",
591 ansi_grey(),
592 (int) k, e,
593 ansi_normal());
594 printf("%-*s",
595 (int) (column_width - k), e+k);
596 } else
597 printf("%-*s", (int) column_width, e);
598 }
599
600 putchar('\n');
601
602 /* on the first screen we reserve 2 extra lines for the title */
603 if (i % break_lines == break_modulo)
604 if (!any_key_to_proceed())
605 return 0;
606 }
607
608 return 0;
609 }
610
611 int open_terminal(const char *name, int mode) {
612 _cleanup_close_ int fd = -EBADF;
613
614 /*
615 * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
616 * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
617 * times.
618 *
619 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
620 */
621
622 assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
623
624 for (unsigned c = 0;; c++) {
625 fd = open(name, mode, 0);
626 if (fd >= 0)
627 break;
628
629 if (errno != EIO)
630 return -errno;
631
632 /* Max 1s in total */
633 if (c >= 20)
634 return -EIO;
635
636 (void) usleep_safe(50 * USEC_PER_MSEC);
637 }
638
639 if (!isatty_safe(fd))
640 return -ENOTTY;
641
642 return TAKE_FD(fd);
643 }
644
645 int acquire_terminal(
646 const char *name,
647 AcquireTerminalFlags flags,
648 usec_t timeout) {
649
650 _cleanup_close_ int notify = -EBADF, fd = -EBADF;
651 usec_t ts = USEC_INFINITY;
652 int r, wd = -1;
653
654 assert(name);
655
656 AcquireTerminalFlags mode = flags & _ACQUIRE_TERMINAL_MODE_MASK;
657 assert(IN_SET(mode, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
658 assert(mode == ACQUIRE_TERMINAL_WAIT || !FLAGS_SET(flags, ACQUIRE_TERMINAL_WATCH_SIGTERM));
659
660 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
661 * acquire it, so that we don't lose any event.
662 *
663 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
664 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
665 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
666 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
667 * probably should not do anyway.) */
668
669 if (mode == ACQUIRE_TERMINAL_WAIT) {
670 notify = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
671 if (notify < 0)
672 return -errno;
673
674 wd = inotify_add_watch(notify, name, IN_CLOSE);
675 if (wd < 0)
676 return -errno;
677
678 if (timeout != USEC_INFINITY)
679 ts = now(CLOCK_MONOTONIC);
680 }
681
682 /* If we are called with ACQUIRE_TERMINAL_WATCH_SIGTERM we'll unblock SIGTERM during ppoll() temporarily */
683 sigset_t poll_ss;
684 assert_se(sigprocmask(SIG_SETMASK, /* newset= */ NULL, &poll_ss) >= 0);
685 if (flags & ACQUIRE_TERMINAL_WATCH_SIGTERM) {
686 assert_se(sigismember(&poll_ss, SIGTERM) > 0);
687 assert_se(sigdelset(&poll_ss, SIGTERM) >= 0);
688 }
689
690 for (;;) {
691 if (notify >= 0) {
692 r = flush_fd(notify);
693 if (r < 0)
694 return r;
695 }
696
697 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
698 * to figure out if we successfully became the controlling process of the tty */
699 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
700 if (fd < 0)
701 return fd;
702
703 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
704 struct sigaction sa_old;
705 assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
706
707 /* First, try to get the tty */
708 r = RET_NERRNO(ioctl(fd, TIOCSCTTY, mode == ACQUIRE_TERMINAL_FORCE));
709
710 /* Reset signal handler to old value */
711 assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
712
713 /* Success? Exit the loop now! */
714 if (r >= 0)
715 break;
716
717 /* Any failure besides -EPERM? Fail, regardless of the mode. */
718 if (r != -EPERM)
719 return r;
720
721 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
722 * into a success. Note that EPERM is also returned if we
723 * already are the owner of the TTY. */
724 break;
725
726 if (mode != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
727 return r;
728
729 assert(notify >= 0);
730 assert(wd >= 0);
731
732 for (;;) {
733 usec_t left;
734 if (timeout == USEC_INFINITY)
735 left = USEC_INFINITY;
736 else {
737 assert(ts != USEC_INFINITY);
738
739 usec_t n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
740 if (n >= timeout)
741 return -ETIMEDOUT;
742
743 left = timeout - n;
744 }
745
746 r = ppoll_usec_full(
747 &(struct pollfd) {
748 .fd = notify,
749 .events = POLLIN,
750 },
751 /* n_fds= */ 1,
752 left,
753 &poll_ss);
754 if (r < 0)
755 return r;
756 if (r == 0)
757 return -ETIMEDOUT;
758
759 union inotify_event_buffer buffer;
760 ssize_t l;
761 l = read(notify, &buffer, sizeof(buffer));
762 if (l < 0) {
763 if (ERRNO_IS_TRANSIENT(errno))
764 continue;
765
766 return -errno;
767 }
768
769 FOREACH_INOTIFY_EVENT(e, buffer, l) {
770 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
771 break;
772
773 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
774 return -EIO;
775 }
776
777 break;
778 }
779
780 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
781 * we do this after sleeping, so that we don't enter an endless loop. */
782 fd = safe_close(fd);
783 }
784
785 return TAKE_FD(fd);
786 }
787
788 int release_terminal(void) {
789 _cleanup_close_ int fd = -EBADF;
790 int r;
791
792 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
793 if (fd < 0)
794 return -errno;
795
796 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
797 * by our own TIOCNOTTY */
798 struct sigaction sa_old;
799 assert_se(sigaction(SIGHUP, &sigaction_ignore, &sa_old) >= 0);
800
801 r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
802
803 assert_se(sigaction(SIGHUP, &sa_old, NULL) >= 0);
804
805 return r;
806 }
807
808 int terminal_new_session(void) {
809
810 /* Make us the new session leader, and set stdin tty to be our controlling terminal.
811 *
812 * Why stdin? Well, the ctty logic is relevant for signal delivery mostly, i.e. if people hit C-c
813 * or the line is hung up. Such events are basically just a form of input, via a side channel
814 * (that side channel being signal delivery, i.e. SIGINT, SIGHUP et al). Hence we focus on input,
815 * not output here. */
816
817 if (!isatty_safe(STDIN_FILENO))
818 return -ENXIO;
819
820 (void) setsid();
821 return RET_NERRNO(ioctl(STDIN_FILENO, TIOCSCTTY, 0));
822 }
823
824 void terminal_detach_session(void) {
825 (void) setsid();
826 (void) release_terminal();
827 }
828
829 int terminal_vhangup_fd(int fd) {
830 assert(fd >= 0);
831 return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
832 }
833
834 int terminal_vhangup(const char *tty) {
835 _cleanup_close_ int fd = -EBADF;
836
837 assert(tty);
838
839 fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC);
840 if (fd < 0)
841 return fd;
842
843 return terminal_vhangup_fd(fd);
844 }
845
846 int vt_disallocate(const char *tty_path) {
847 assert(tty_path);
848
849 /* Deallocate the VT if possible. If not possible (i.e. because it is the active one), at least clear
850 * it entirely (including the scrollback buffer). */
851
852 int ttynr = vtnr_from_tty(tty_path);
853 if (ttynr > 0) {
854 _cleanup_close_ int fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
855 if (fd < 0)
856 return fd;
857
858 /* Try to deallocate */
859 if (ioctl(fd, VT_DISALLOCATE, ttynr) >= 0)
860 return 0;
861 if (errno != EBUSY)
862 return -errno;
863 }
864
865 /* So this is not a VT (in which case we cannot deallocate it), or we failed to deallocate. Let's at
866 * least clear the screen. */
867
868 _cleanup_close_ int fd2 = open_terminal(tty_path, O_WRONLY|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
869 if (fd2 < 0)
870 return fd2;
871
872 return loop_write_full(fd2,
873 "\033[r" /* clear scrolling region */
874 "\033[H" /* move home */
875 "\033[3J" /* clear screen including scrollback, requires Linux 2.6.40 */
876 "\033c", /* reset to initial state */
877 SIZE_MAX,
878 CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
879 }
880
881 static int vt_default_utf8(void) {
882 /* Read the default VT UTF8 setting from the kernel */
883 return read_boolean_file("/sys/module/vt/parameters/default_utf8");
884 }
885
886 static int vt_reset_keyboard(int fd) {
887 int r, kb;
888
889 assert(fd >= 0);
890
891 /* If we can't read the default, then default to Unicode. It's 2024 after all. */
892 r = vt_default_utf8();
893 if (r < 0)
894 log_debug_errno(r, "Failed to determine kernel VT UTF-8 mode, assuming enabled: %m");
895
896 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
897 return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
898 }
899
900 static int terminal_reset_ioctl(int fd, bool switch_to_text) {
901 struct termios termios;
902 int r;
903
904 /* Set terminal to some sane defaults */
905
906 assert(fd >= 0);
907
908 /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
909 * and we don't interfere with that. */
910
911 /* Disable exclusive mode, just in case */
912 if (ioctl(fd, TIOCNXCL) < 0)
913 log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
914
915 /* Switch to text mode */
916 if (switch_to_text)
917 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
918 log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
919
920 /* Set default keyboard mode */
921 r = vt_reset_keyboard(fd);
922 if (r < 0)
923 log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
924
925 if (tcgetattr(fd, &termios) < 0) {
926 r = log_debug_errno(errno, "Failed to get terminal parameters: %m");
927 goto finish;
928 }
929
930 /* We only reset the stuff that matters to the software. How
931 * hardware is set up we don't touch assuming that somebody
932 * else will do that for us */
933
934 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
935 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
936 termios.c_oflag |= ONLCR | OPOST;
937 termios.c_cflag |= CREAD;
938 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOKE;
939
940 termios.c_cc[VINTR] = 03; /* ^C */
941 termios.c_cc[VQUIT] = 034; /* ^\ */
942 termios.c_cc[VERASE] = 0177;
943 termios.c_cc[VKILL] = 025; /* ^X */
944 termios.c_cc[VEOF] = 04; /* ^D */
945 termios.c_cc[VSTART] = 021; /* ^Q */
946 termios.c_cc[VSTOP] = 023; /* ^S */
947 termios.c_cc[VSUSP] = 032; /* ^Z */
948 termios.c_cc[VLNEXT] = 026; /* ^V */
949 termios.c_cc[VWERASE] = 027; /* ^W */
950 termios.c_cc[VREPRINT] = 022; /* ^R */
951 termios.c_cc[VEOL] = 0;
952 termios.c_cc[VEOL2] = 0;
953
954 termios.c_cc[VTIME] = 0;
955 termios.c_cc[VMIN] = 1;
956
957 r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
958 if (r < 0)
959 log_debug_errno(r, "Failed to set terminal parameters: %m");
960
961 finish:
962 /* Just in case, flush all crap out */
963 (void) tcflush(fd, TCIOFLUSH);
964
965 return r;
966 }
967
968 int terminal_reset_ansi_seq(int fd) {
969 _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
970 int r;
971
972 assert(fd >= 0);
973
974 if (getenv_terminal_is_dumb())
975 return 0;
976
977 r = fd_nonblock(fd, true);
978 if (r < 0)
979 return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
980 if (r > 0)
981 nonblock_reset = fd;
982
983 r = loop_write_full(fd,
984 "\033[!p" /* soft terminal reset */
985 ANSI_OSC "104" ANSI_ST /* reset color palette via OSC 104 */
986 ANSI_NORMAL /* reset colors */
987 "\033[?7h" /* enable line-wrapping */
988 "\033[1G" /* place cursor at beginning of current line */
989 "\033[0J", /* erase till end of screen */
990 SIZE_MAX,
991 CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
992 if (r < 0)
993 log_debug_errno(r, "Failed to reset terminal through ANSI sequences: %m");
994
995 return r;
996 }
997
998 void reset_dev_console_fd(int fd, bool switch_to_text) {
999 int r;
1000
1001 assert(fd >= 0);
1002
1003 _cleanup_close_ int lock_fd = lock_dev_console();
1004 if (lock_fd < 0)
1005 log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
1006
1007 r = terminal_reset_ioctl(fd, switch_to_text);
1008 if (r < 0)
1009 log_warning_errno(r, "Failed to reset /dev/console, ignoring: %m");
1010
1011 unsigned rows, cols;
1012 r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
1013 if (r < 0)
1014 log_warning_errno(r, "Failed to get /dev/console size, ignoring: %m");
1015 else if (r > 0) {
1016 r = terminal_set_size_fd(fd, NULL, rows, cols);
1017 if (r < 0)
1018 log_warning_errno(r, "Failed to set configured terminal size on /dev/console, ignoring: %m");
1019 } else
1020 (void) terminal_fix_size(fd, fd);
1021
1022 r = terminal_reset_ansi_seq(fd);
1023 if (r < 0)
1024 log_warning_errno(r, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
1025 }
1026
1027 int lock_dev_console(void) {
1028 _cleanup_close_ int fd = -EBADF;
1029 int r;
1030
1031 /* NB: We do not use O_NOFOLLOW here, because some container managers might place a symlink to some
1032 * pty in /dev/console, in which case it should be fine to lock the target TTY. */
1033 fd = open_terminal("/dev/console", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1034 if (fd < 0)
1035 return fd;
1036
1037 r = lock_generic(fd, LOCK_BSD, LOCK_EX);
1038 if (r < 0)
1039 return r;
1040
1041 return TAKE_FD(fd);
1042 }
1043
1044 int make_console_stdio(void) {
1045 int fd, r;
1046
1047 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
1048 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
1049 * is specified on the kernel command line. */
1050
1051 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
1052 if (fd < 0) {
1053 log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
1054
1055 r = make_null_stdio();
1056 if (r < 0)
1057 return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
1058
1059 } else {
1060 reset_dev_console_fd(fd, /* switch_to_text= */ true);
1061
1062 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
1063 if (r < 0)
1064 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
1065 }
1066
1067 reset_terminal_feature_caches();
1068 return 0;
1069 }
1070
1071 static int vtnr_from_tty_raw(const char *tty, unsigned *ret) {
1072 assert(tty);
1073
1074 tty = skip_dev_prefix(tty);
1075
1076 const char *e = startswith(tty, "tty");
1077 if (!e)
1078 return -EINVAL;
1079
1080 return safe_atou(e, ret);
1081 }
1082
1083 int vtnr_from_tty(const char *tty) {
1084 unsigned u;
1085 int r;
1086
1087 assert(tty);
1088
1089 r = vtnr_from_tty_raw(tty, &u);
1090 if (r < 0)
1091 return r;
1092 if (!vtnr_is_valid(u))
1093 return -ERANGE;
1094
1095 return (int) u;
1096 }
1097
1098 bool tty_is_vc(const char *tty) {
1099 assert(tty);
1100
1101 /* NB: for >= 0 values no range check is conducted here, on the assumption that the caller will
1102 * either extract vtnr through vtnr_from_tty() later where ERANGE would be reported, or doesn't care
1103 * about whether it's strictly valid, but only asking "does this fall into the vt category?", for which
1104 * "yes" seems to be a better answer. */
1105
1106 return vtnr_from_tty_raw(tty, /* ret= */ NULL) >= 0;
1107 }
1108
1109 bool tty_is_console(const char *tty) {
1110 assert(tty);
1111
1112 return streq(skip_dev_prefix(tty), "console");
1113 }
1114
1115 int resolve_dev_console(char **ret) {
1116 int r;
1117
1118 assert(ret);
1119
1120 /* Resolve where /dev/console is pointing to. If /dev/console is a symlink (like in container
1121 * managers), we'll just resolve the symlink. If it's a real device node, we'll use if
1122 * /sys/class/tty/tty0/active, but only if /sys/ is actually ours (i.e. not read-only-mounted which
1123 * is a sign for container setups). */
1124
1125 _cleanup_free_ char *chased = NULL;
1126 r = chase("/dev/console", /* root= */ NULL, /* flags= */ 0, &chased, /* ret_fd= */ NULL);
1127 if (r < 0)
1128 return r;
1129 if (!path_equal(chased, "/dev/console")) {
1130 *ret = TAKE_PTR(chased);
1131 return 0;
1132 }
1133
1134 r = path_is_read_only_fs("/sys");
1135 if (r < 0)
1136 return r;
1137 if (r > 0)
1138 return -ENOMEDIUM;
1139
1140 _cleanup_free_ char *active = NULL;
1141 r = read_one_line_file("/sys/class/tty/console/active", &active);
1142 if (r < 0)
1143 return r;
1144 if (r == 0)
1145 return -ENXIO;
1146
1147 /* If multiple log outputs are configured the last one is what /dev/console points to */
1148 const char *tty = strrchr(active, ' ');
1149 if (tty)
1150 tty++;
1151 else
1152 tty = active;
1153
1154 if (streq(tty, "tty0")) {
1155 active = mfree(active);
1156
1157 /* Get the active VC (e.g. tty1) */
1158 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
1159 if (r < 0)
1160 return r;
1161 if (r == 0)
1162 return -ENXIO;
1163
1164 tty = active;
1165 }
1166
1167 _cleanup_free_ char *path = NULL;
1168 path = path_join("/dev", tty);
1169 if (!path)
1170 return -ENOMEM;
1171
1172 *ret = TAKE_PTR(path);
1173 return 0;
1174 }
1175
1176 int get_kernel_consoles(char ***ret) {
1177 _cleanup_strv_free_ char **l = NULL;
1178 _cleanup_free_ char *line = NULL;
1179 int r;
1180
1181 assert(ret);
1182
1183 /* If /sys/ is mounted read-only this means we are running in some kind of container environment.
1184 * In that case /sys/ would reflect the host system, not us, hence ignore the data we can read from it. */
1185 if (path_is_read_only_fs("/sys") > 0)
1186 goto fallback;
1187
1188 r = read_one_line_file("/sys/class/tty/console/active", &line);
1189 if (r < 0)
1190 return r;
1191
1192 for (const char *p = line;;) {
1193 _cleanup_free_ char *tty = NULL, *path = NULL;
1194
1195 r = extract_first_word(&p, &tty, NULL, 0);
1196 if (r < 0)
1197 return r;
1198 if (r == 0)
1199 break;
1200
1201 if (streq(tty, "tty0")) {
1202 tty = mfree(tty);
1203 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
1204 if (r < 0)
1205 return r;
1206 if (r == 0) {
1207 log_debug("No VT active, skipping /dev/tty0.");
1208 continue;
1209 }
1210 }
1211
1212 path = path_join("/dev", tty);
1213 if (!path)
1214 return -ENOMEM;
1215
1216 if (access(path, F_OK) < 0) {
1217 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
1218 continue;
1219 }
1220
1221 r = strv_consume(&l, TAKE_PTR(path));
1222 if (r < 0)
1223 return r;
1224 }
1225
1226 if (strv_isempty(l)) {
1227 log_debug("No devices found for system console");
1228 goto fallback;
1229 }
1230
1231 *ret = TAKE_PTR(l);
1232 return strv_length(*ret);
1233
1234 fallback:
1235 r = strv_extend(&l, "/dev/console");
1236 if (r < 0)
1237 return r;
1238
1239 *ret = TAKE_PTR(l);
1240 return 0;
1241 }
1242
1243 bool tty_is_vc_resolve(const char *tty) {
1244 _cleanup_free_ char *resolved = NULL;
1245
1246 assert(tty);
1247
1248 if (streq(skip_dev_prefix(tty), "console")) {
1249 if (resolve_dev_console(&resolved) < 0)
1250 return false;
1251
1252 tty = resolved;
1253 }
1254
1255 return tty_is_vc(tty);
1256 }
1257
1258 int fd_columns(int fd) {
1259 struct winsize ws = {};
1260
1261 if (fd < 0)
1262 return -EBADF;
1263
1264 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1265 return -errno;
1266
1267 if (ws.ws_col <= 0)
1268 return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
1269
1270 return ws.ws_col;
1271 }
1272
1273 int getenv_columns(void) {
1274 int r;
1275
1276 const char *e = getenv("COLUMNS");
1277 if (!e)
1278 return -ENXIO;
1279
1280 unsigned c;
1281 r = safe_atou_bounded(e, 1, USHRT_MAX, &c);
1282 if (r < 0)
1283 return r;
1284
1285 return (int) c;
1286 }
1287
1288 unsigned columns(void) {
1289
1290 if (cached_columns > 0)
1291 return cached_columns;
1292
1293 int c = getenv_columns();
1294 if (c < 0) {
1295 c = fd_columns(STDOUT_FILENO);
1296 if (c < 0)
1297 c = 80;
1298 }
1299
1300 assert(c > 0);
1301
1302 cached_columns = c;
1303 return cached_columns;
1304 }
1305
1306 int fd_lines(int fd) {
1307 struct winsize ws = {};
1308
1309 if (fd < 0)
1310 return -EBADF;
1311
1312 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1313 return -errno;
1314
1315 if (ws.ws_row <= 0)
1316 return -ENODATA; /* some tty types come up with invalid row/column initially, return a recognizable error for that */
1317
1318 return ws.ws_row;
1319 }
1320
1321 unsigned lines(void) {
1322 const char *e;
1323 int l;
1324
1325 if (cached_lines > 0)
1326 return cached_lines;
1327
1328 l = 0;
1329 e = getenv("LINES");
1330 if (e)
1331 (void) safe_atoi(e, &l);
1332
1333 if (l <= 0 || l > USHRT_MAX) {
1334 l = fd_lines(STDOUT_FILENO);
1335 if (l <= 0)
1336 l = 24;
1337 }
1338
1339 cached_lines = l;
1340 return cached_lines;
1341 }
1342
1343 int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
1344 struct winsize ws;
1345
1346 assert(fd >= 0);
1347
1348 if (!ident)
1349 ident = "TTY";
1350
1351 if (rows == UINT_MAX && cols == UINT_MAX)
1352 return 0;
1353
1354 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
1355 return log_debug_errno(errno,
1356 "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
1357 ident);
1358
1359 if (rows == UINT_MAX)
1360 rows = ws.ws_row;
1361 else if (rows > USHRT_MAX)
1362 rows = USHRT_MAX;
1363
1364 if (cols == UINT_MAX)
1365 cols = ws.ws_col;
1366 else if (cols > USHRT_MAX)
1367 cols = USHRT_MAX;
1368
1369 if (rows == ws.ws_row && cols == ws.ws_col)
1370 return 0;
1371
1372 ws.ws_row = rows;
1373 ws.ws_col = cols;
1374
1375 if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
1376 return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident);
1377
1378 return 0;
1379 }
1380
1381 int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
1382 _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
1383 unsigned rows = UINT_MAX, cols = UINT_MAX;
1384 int r;
1385
1386 assert(tty);
1387
1388 if (!ret_rows && !ret_cols)
1389 return 0;
1390
1391 tty = skip_dev_prefix(tty);
1392 if (path_startswith(tty, "pts/"))
1393 return -EMEDIUMTYPE;
1394 if (!in_charset(tty, ALPHANUMERICAL))
1395 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
1396 "TTY name '%s' contains non-alphanumeric characters, not searching kernel cmdline for size.", tty);
1397
1398 rowskey = strjoin("systemd.tty.rows.", tty);
1399 if (!rowskey)
1400 return -ENOMEM;
1401
1402 colskey = strjoin("systemd.tty.columns.", tty);
1403 if (!colskey)
1404 return -ENOMEM;
1405
1406 r = proc_cmdline_get_key_many(/* flags= */ 0,
1407 rowskey, &rowsvalue,
1408 colskey, &colsvalue);
1409 if (r < 0)
1410 return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
1411
1412 if (rowsvalue) {
1413 r = safe_atou(rowsvalue, &rows);
1414 if (r < 0)
1415 return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
1416 }
1417
1418 if (colsvalue) {
1419 r = safe_atou(colsvalue, &cols);
1420 if (r < 0)
1421 return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
1422 }
1423
1424 if (ret_rows)
1425 *ret_rows = rows;
1426 if (ret_cols)
1427 *ret_cols = cols;
1428
1429 return rows != UINT_MAX || cols != UINT_MAX;
1430 }
1431
1432 /* intended to be used as a SIGWINCH sighandler */
1433 void columns_lines_cache_reset(int signum) {
1434 cached_columns = 0;
1435 cached_lines = 0;
1436 }
1437
1438 void reset_terminal_feature_caches(void) {
1439 cached_columns = 0;
1440 cached_lines = 0;
1441
1442 cached_on_tty = -1;
1443 cached_on_dev_null = -1;
1444
1445 reset_ansi_feature_caches();
1446 }
1447
1448 bool on_tty(void) {
1449
1450 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
1451 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
1452 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
1453 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
1454 * terminal functionality when outputting stuff, even if the input is piped to us. */
1455
1456 if (cached_on_tty < 0)
1457 cached_on_tty =
1458 isatty_safe(STDOUT_FILENO) &&
1459 isatty_safe(STDERR_FILENO);
1460
1461 return cached_on_tty;
1462 }
1463
1464 int getttyname_malloc(int fd, char **ret) {
1465 char path[PATH_MAX]; /* PATH_MAX is counted *with* the trailing NUL byte */
1466 int r;
1467
1468 assert(fd >= 0);
1469 assert(ret);
1470
1471 r = ttyname_r(fd, path, sizeof path); /* positive error */
1472 assert(r >= 0);
1473 if (r == ERANGE)
1474 return -ENAMETOOLONG;
1475 if (r > 0)
1476 return -r;
1477
1478 return strdup_to(ret, skip_dev_prefix(path));
1479 }
1480
1481 int getttyname_harder(int fd, char **ret) {
1482 _cleanup_free_ char *s = NULL;
1483 int r;
1484
1485 assert(ret);
1486
1487 r = getttyname_malloc(fd, &s);
1488 if (r < 0)
1489 return r;
1490
1491 if (streq(s, "tty"))
1492 return get_ctty(0, NULL, ret);
1493
1494 *ret = TAKE_PTR(s);
1495 return 0;
1496 }
1497
1498 int get_ctty_devnr(pid_t pid, dev_t *ret) {
1499 _cleanup_free_ char *line = NULL;
1500 unsigned long ttynr;
1501 const char *p;
1502 int r;
1503
1504 assert(pid >= 0);
1505
1506 p = procfs_file_alloca(pid, "stat");
1507 r = read_one_line_file(p, &line);
1508 if (r < 0)
1509 return r;
1510
1511 p = strrchr(line, ')');
1512 if (!p)
1513 return -EIO;
1514
1515 p++;
1516
1517 if (sscanf(p, " "
1518 "%*c " /* state */
1519 "%*d " /* ppid */
1520 "%*d " /* pgrp */
1521 "%*d " /* session */
1522 "%lu ", /* ttynr */
1523 &ttynr) != 1)
1524 return -EIO;
1525
1526 if (devnum_is_zero(ttynr))
1527 return -ENXIO;
1528
1529 if (ret)
1530 *ret = (dev_t) ttynr;
1531
1532 return 0;
1533 }
1534
1535 int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
1536 char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
1537 _cleanup_free_ char *buf = NULL;
1538 const char *fn = NULL, *w;
1539 dev_t devnr;
1540 int r;
1541
1542 r = get_ctty_devnr(pid, &devnr);
1543 if (r < 0)
1544 return r;
1545
1546 r = device_path_make_canonical(S_IFCHR, devnr, &buf);
1547 if (r < 0) {
1548 struct stat st;
1549
1550 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
1551 return r;
1552
1553 /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
1554 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
1555 * assume this is a PTY for a moment, and check if the device node this would then map to in
1556 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
1557 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
1558 * the minor number of the pty. */
1559 xsprintf(pty, "/dev/pts/%u", minor(devnr));
1560
1561 if (stat(pty, &st) < 0) {
1562 if (errno != ENOENT)
1563 return -errno;
1564
1565 } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
1566 fn = pty;
1567
1568 if (!fn) {
1569 /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1570 * symlink in /dev/char/. Let's return something vaguely useful. */
1571 r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
1572 if (r < 0)
1573 return r;
1574
1575 fn = buf;
1576 }
1577 } else
1578 fn = buf;
1579
1580 w = path_startswith(fn, "/dev/");
1581 if (!w)
1582 return -EINVAL;
1583
1584 if (ret) {
1585 r = strdup_to(ret, w);
1586 if (r < 0)
1587 return r;
1588 }
1589
1590 if (ret_devnr)
1591 *ret_devnr = devnr;
1592
1593 return 0;
1594 }
1595
1596 int ptsname_malloc(int fd, char **ret) {
1597 assert(fd >= 0);
1598 assert(ret);
1599
1600 for (size_t l = 50;;) {
1601 _cleanup_free_ char *c = NULL;
1602
1603 c = new(char, l);
1604 if (!c)
1605 return -ENOMEM;
1606
1607 if (ptsname_r(fd, c, l) >= 0) {
1608 *ret = TAKE_PTR(c);
1609 return 0;
1610 }
1611 if (errno != ERANGE)
1612 return -errno;
1613
1614 if (!MUL_ASSIGN_SAFE(&l, 2))
1615 return -ENOMEM;
1616 }
1617 }
1618
1619 int openpt_allocate(int flags, char **ret_peer_path) {
1620 _cleanup_close_ int fd = -EBADF;
1621 int r;
1622
1623 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1624 if (fd < 0)
1625 return -errno;
1626
1627 _cleanup_free_ char *p = NULL;
1628 if (ret_peer_path) {
1629 r = ptsname_malloc(fd, &p);
1630 if (r < 0)
1631 return r;
1632
1633 if (!path_startswith(p, "/dev/pts/"))
1634 return -EINVAL;
1635 }
1636
1637 if (unlockpt(fd) < 0)
1638 return -errno;
1639
1640 if (ret_peer_path)
1641 *ret_peer_path = TAKE_PTR(p);
1642
1643 return TAKE_FD(fd);
1644 }
1645
1646 static int ptsname_namespace(int pty, char **ret) {
1647 int no = -1;
1648
1649 assert(pty >= 0);
1650 assert(ret);
1651
1652 /* Like ptsname(), but doesn't assume that the path is
1653 * accessible in the local namespace. */
1654
1655 if (ioctl(pty, TIOCGPTN, &no) < 0)
1656 return -errno;
1657
1658 if (no < 0)
1659 return -EIO;
1660
1661 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1662 return -ENOMEM;
1663
1664 return 0;
1665 }
1666
1667 int openpt_allocate_in_namespace(
1668 const PidRef *pidref,
1669 int flags,
1670 char **ret_peer_path) {
1671
1672 _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
1673 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
1674 int r;
1675
1676 r = pidref_namespace_open(pidref, &pidnsfd, &mntnsfd, /* ret_netns_fd= */ NULL, &usernsfd, &rootfd);
1677 if (r < 0)
1678 return log_debug_errno(r, "Failed to open namespaces of PID "PID_FMT": %m", pidref->pid);
1679
1680 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair) < 0)
1681 return -errno;
1682
1683 r = namespace_fork(
1684 "(sd-openptns)",
1685 "(sd-openpt)",
1686 FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_WAIT,
1687 pidnsfd,
1688 mntnsfd,
1689 /* netns_fd= */ -EBADF,
1690 usernsfd,
1691 rootfd,
1692 /* ret= */ NULL);
1693 if (r < 0)
1694 return r;
1695 if (r == 0) {
1696 pair[0] = safe_close(pair[0]);
1697
1698 fd = openpt_allocate(flags, /* ret_peer_path= */ NULL);
1699 if (fd < 0)
1700 _exit(EXIT_FAILURE);
1701
1702 if (send_one_fd(pair[1], fd, 0) < 0)
1703 _exit(EXIT_FAILURE);
1704
1705 _exit(EXIT_SUCCESS);
1706 }
1707
1708 pair[1] = safe_close(pair[1]);
1709
1710 fd = receive_one_fd(pair[0], 0);
1711 if (fd < 0)
1712 return fd;
1713
1714 if (ret_peer_path) {
1715 r = ptsname_namespace(fd, ret_peer_path);
1716 if (r < 0)
1717 return r;
1718 }
1719
1720 return TAKE_FD(fd);
1721 }
1722
1723 static bool on_dev_null(void) {
1724 struct stat dst, ost, est;
1725
1726 if (cached_on_dev_null >= 0)
1727 return cached_on_dev_null;
1728
1729 if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
1730 cached_on_dev_null = false;
1731 else
1732 cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
1733
1734 return cached_on_dev_null;
1735 }
1736
1737 bool term_env_valid(const char *term) {
1738 /* Checks if the specified $TERM value is suitable for propagation, i.e. is not empty, not set to
1739 * "unknown" (as is common in CI), and only contains characters valid in terminal type names.
1740 * Valid $TERM values are things like "xterm-256color", "linux", "screen.xterm-256color", i.e.
1741 * alphanumeric characters, hyphens, underscores, dots, and plus signs. */
1742 return !isempty(term) &&
1743 !streq(term, "unknown") &&
1744 in_charset(term, ALPHANUMERICAL "-_+.");
1745 }
1746
1747 bool getenv_terminal_is_dumb(void) {
1748 const char *e;
1749
1750 e = getenv("TERM");
1751 if (!e)
1752 return true;
1753
1754 return streq(e, "dumb");
1755 }
1756
1757 bool terminal_is_dumb(void) {
1758 if (!on_tty() && !on_dev_null())
1759 return true;
1760
1761 return getenv_terminal_is_dumb();
1762 }
1763
1764 bool dev_console_colors_enabled(void) {
1765 _cleanup_free_ char *s = NULL;
1766 ColorMode m;
1767
1768 /* Returns true if we assume that color is supported on /dev/console.
1769 *
1770 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1771 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1772 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1773 * colors_enabled() operates. */
1774
1775 m = parse_systemd_colors();
1776 if (m >= 0)
1777 return m;
1778
1779 if (getenv("NO_COLOR"))
1780 return false;
1781
1782 if (getenv_for_pid(1, "TERM", &s) <= 0)
1783 (void) proc_cmdline_get_key("TERM", 0, &s);
1784
1785 return !streq_ptr(s, "dumb");
1786 }
1787
1788 int vt_restore(int fd) {
1789
1790 static const struct vt_mode mode = {
1791 .mode = VT_AUTO,
1792 };
1793
1794 int r, ret = 0;
1795
1796 assert(fd >= 0);
1797
1798 if (!isatty_safe(fd))
1799 return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to restore the VT for an fd that does not refer to a terminal.");
1800
1801 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
1802 RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT to text mode, ignoring: %m"));
1803
1804 r = vt_reset_keyboard(fd);
1805 if (r < 0)
1806 RET_GATHER(ret, log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m"));
1807
1808 if (ioctl(fd, VT_SETMODE, &mode) < 0)
1809 RET_GATHER(ret, log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m"));
1810
1811 r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
1812 if (r < 0)
1813 RET_GATHER(ret, log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m"));
1814
1815 return ret;
1816 }
1817
1818 int vt_release(int fd, bool restore) {
1819 assert(fd >= 0);
1820
1821 /* This function releases the VT by acknowledging the VT-switch signal
1822 * sent by the kernel and optionally reset the VT in text and auto
1823 * VT-switching modes. */
1824
1825 if (!isatty_safe(fd))
1826 return log_debug_errno(SYNTHETIC_ERRNO(ENOTTY), "Asked to release the VT for an fd that does not refer to a terminal.");
1827
1828 if (ioctl(fd, VT_RELDISP, 1) < 0)
1829 return -errno;
1830
1831 if (restore)
1832 return vt_restore(fd);
1833
1834 return 0;
1835 }
1836
1837 void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
1838 /* Note that this will initialize output variables only when there's something to output.
1839 * The caller must pre-initialize to "" or NULL as appropriate. */
1840
1841 if (priority <= LOG_ERR) {
1842 if (on)
1843 *on = ansi_highlight_red();
1844 if (off)
1845 *off = ansi_normal();
1846 if (highlight)
1847 *highlight = ansi_highlight();
1848
1849 } else if (priority <= LOG_WARNING) {
1850 if (on)
1851 *on = ansi_highlight_yellow();
1852 if (off)
1853 *off = ansi_normal();
1854 if (highlight)
1855 *highlight = ansi_highlight();
1856
1857 } else if (priority <= LOG_NOTICE) {
1858 if (on)
1859 *on = ansi_highlight();
1860 if (off)
1861 *off = ansi_normal();
1862 if (highlight)
1863 *highlight = ansi_highlight_red();
1864
1865 } else if (priority >= LOG_DEBUG) {
1866 if (on)
1867 *on = ansi_grey();
1868 if (off)
1869 *off = ansi_normal();
1870 if (highlight)
1871 *highlight = ansi_highlight_red();
1872 }
1873 }
1874
1875 int terminal_set_cursor_position(int fd, unsigned row, unsigned column) {
1876 assert(fd >= 0);
1877
1878 char cursor_position[STRLEN("\x1B[" ";" "H") + DECIMAL_STR_MAX(unsigned) * 2 + 1];
1879 xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
1880
1881 return loop_write(fd, cursor_position, SIZE_MAX);
1882 }
1883
1884 static int terminal_verify_same(int input_fd, int output_fd) {
1885 int r;
1886
1887 assert(input_fd >= 0);
1888 assert(output_fd >= 0);
1889
1890 /* Validates that the specified fds reference the same TTY */
1891
1892 if (input_fd != output_fd) {
1893 struct stat sti;
1894 if (fstat(input_fd, &sti) < 0)
1895 return -errno;
1896
1897 r = stat_verify_char(&sti); /* TTYs are character devices */
1898 if (r < 0)
1899 return r;
1900
1901 struct stat sto;
1902 if (fstat(output_fd, &sto) < 0)
1903 return -errno;
1904
1905 r = stat_verify_char(&sto);
1906 if (r < 0)
1907 return r;
1908
1909 if (sti.st_rdev != sto.st_rdev)
1910 return -ENOLINK;
1911 }
1912
1913 if (!isatty_safe(input_fd)) /* The check above was just for char device, but now let's ensure it's actually a tty */
1914 return -ENOTTY;
1915
1916 return 0;
1917 }
1918
1919 typedef enum CursorPositionState {
1920 CURSOR_TEXT,
1921 CURSOR_ESCAPE,
1922 CURSOR_ROW,
1923 CURSOR_COLUMN,
1924 } CursorPositionState;
1925
1926 typedef struct CursorPositionContext {
1927 CursorPositionState state;
1928 unsigned row, column;
1929 } CursorPositionContext;
1930
1931 static int scan_cursor_position_response(
1932 CursorPositionContext *context,
1933 const char *buf,
1934 size_t size,
1935 size_t *ret_processed) {
1936
1937 assert(context);
1938 assert(buf);
1939 assert(ret_processed);
1940
1941 for (size_t i = 0; i < size; i++) {
1942 char c = buf[i];
1943
1944 switch (context->state) {
1945
1946 case CURSOR_TEXT:
1947 context->state = c == '\x1B' ? CURSOR_ESCAPE : CURSOR_TEXT;
1948 break;
1949
1950 case CURSOR_ESCAPE:
1951 context->state = c == '[' ? CURSOR_ROW : CURSOR_TEXT;
1952 break;
1953
1954 case CURSOR_ROW:
1955 if (c == ';')
1956 context->state = context->row > 0 ? CURSOR_COLUMN : CURSOR_TEXT;
1957 else {
1958 int d = undecchar(c);
1959
1960 /* We read a decimal character, let's suffix it to the number we so far read,
1961 * but let's do an overflow check first. */
1962 if (d < 0 || context->row > (UINT_MAX-d)/10)
1963 context->state = CURSOR_TEXT;
1964 else
1965 context->row = context->row * 10 + d;
1966 }
1967 break;
1968
1969 case CURSOR_COLUMN:
1970 if (c == 'R') {
1971 if (context->column > 0) {
1972 *ret_processed = i + 1;
1973 return 1; /* success! */
1974 }
1975
1976 context->state = CURSOR_TEXT;
1977 } else {
1978 int d = undecchar(c);
1979
1980 /* As above, add the decimal character to our column number */
1981 if (d < 0 || context->column > (UINT_MAX-d)/10)
1982 context->state = CURSOR_TEXT;
1983 else
1984 context->column = context->column * 10 + d;
1985 }
1986
1987 break;
1988 }
1989
1990 /* Reset any positions we might have picked up */
1991 if (IN_SET(context->state, CURSOR_TEXT, CURSOR_ESCAPE))
1992 context->row = context->column = 0;
1993 }
1994
1995 *ret_processed = size;
1996 return 0; /* all good, but not enough data yet */
1997 }
1998
1999 int terminal_get_cursor_position(
2000 int input_fd,
2001 int output_fd,
2002 unsigned *ret_row,
2003 unsigned *ret_column) {
2004
2005 _cleanup_close_ int nonblock_input_fd = -EBADF;
2006 int r;
2007
2008 assert(input_fd >= 0);
2009 assert(output_fd >= 0);
2010
2011 if (getenv_terminal_is_dumb())
2012 return -EOPNOTSUPP;
2013
2014 r = terminal_verify_same(input_fd, output_fd);
2015 if (r < 0)
2016 return log_debug_errno(r, "Called with distinct input/output fds: %m");
2017
2018 /* Failure to reset the terminal is ignored here and in similar cases below.
2019 * We already have our result; if cleanup fails it doesn't change the validity of the result. */
2020 struct termios old_termios = TERMIOS_NULL;
2021 CLEANUP_TERMIOS_RESET(input_fd, old_termios);
2022
2023 if (tcgetattr(input_fd, &old_termios) < 0)
2024 return log_debug_errno(errno, "Failed to get terminal settings: %m");
2025
2026 struct termios new_termios = old_termios;
2027 termios_disable_echo(&new_termios);
2028
2029 if (tcsetattr(input_fd, TCSANOW, &new_termios) < 0)
2030 return log_debug_errno(errno, "Failed to set new terminal settings: %m");
2031
2032 /* Request cursor position (DSR/CPR) */
2033 r = loop_write(output_fd, "\x1B[6n", SIZE_MAX);
2034 if (r < 0)
2035 return r;
2036
2037 /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read() should someone
2038 * else process the POLLIN. */
2039
2040 nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2041 if (r < 0)
2042 return r;
2043
2044 usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2045 char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
2046 size_t buf_full = 0;
2047 CursorPositionContext context = {};
2048
2049 for (bool first = true;; first = false) {
2050 if (buf_full == 0) {
2051 usec_t n = now(CLOCK_MONOTONIC);
2052 if (n >= end)
2053 return -EOPNOTSUPP;
2054
2055 r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
2056 if (r < 0)
2057 return r;
2058 if (r == 0)
2059 return -EOPNOTSUPP;
2060
2061 /* On the first try, read multiple characters, i.e. the shortest valid
2062 * reply. Afterwards read byte-wise, since we don't want to read too much, and
2063 * unnecessarily drop too many characters from the input queue. */
2064 ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
2065 if (l < 0) {
2066 if (errno == EAGAIN)
2067 continue;
2068
2069 return -errno;
2070 }
2071
2072 assert((size_t) l <= sizeof(buf));
2073 buf_full = l;
2074 }
2075
2076 size_t processed;
2077 r = scan_cursor_position_response(&context, buf, buf_full, &processed);
2078 if (r < 0)
2079 return r;
2080
2081 assert(processed <= buf_full);
2082 buf_full -= processed;
2083 memmove(buf, buf + processed, buf_full);
2084
2085 if (r > 0) {
2086 /* Superficial validity check */
2087 if (context.row >= 32766 || context.column >= 32766)
2088 return -ENODATA;
2089
2090 if (ret_row)
2091 *ret_row = context.row;
2092 if (ret_column)
2093 *ret_column = context.column;
2094
2095 return 0;
2096 }
2097 }
2098 }
2099
2100 int terminal_reset_defensive(int fd, TerminalResetFlags flags) {
2101 int r = 0;
2102
2103 assert(fd >= 0);
2104 assert(!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ|TERMINAL_RESET_FORCE_ANSI_SEQ));
2105
2106 /* Resets the terminal comprehensively, i.e. via both ioctl()s and via ANSI sequences, but do so only
2107 * if $TERM is unset or set to "dumb" */
2108
2109 if (!isatty_safe(fd))
2110 return -ENOTTY;
2111
2112 RET_GATHER(r, terminal_reset_ioctl(fd, FLAGS_SET(flags, TERMINAL_RESET_SWITCH_TO_TEXT)));
2113
2114 if (!FLAGS_SET(flags, TERMINAL_RESET_AVOID_ANSI_SEQ) &&
2115 (FLAGS_SET(flags, TERMINAL_RESET_FORCE_ANSI_SEQ) || !getenv_terminal_is_dumb()))
2116 RET_GATHER(r, terminal_reset_ansi_seq(fd));
2117
2118 return r;
2119 }
2120
2121 int terminal_reset_defensive_locked(int fd, TerminalResetFlags flags) {
2122 assert(fd >= 0);
2123
2124 _cleanup_close_ int lock_fd = lock_dev_console();
2125 if (lock_fd < 0)
2126 log_debug_errno(lock_fd, "Failed to acquire lock for /dev/console, ignoring: %m");
2127
2128 return terminal_reset_defensive(fd, flags);
2129 }
2130
2131 void termios_disable_echo(struct termios *termios) {
2132 assert(termios);
2133
2134 termios->c_lflag &= ~(ICANON|ECHO);
2135 termios->c_cc[VMIN] = 1;
2136 termios->c_cc[VTIME] = 0;
2137 }
2138
2139 static bool termios_is_null(const struct termios *t) {
2140 if (!t)
2141 return true;
2142
2143 return t->c_iflag == UINT_MAX &&
2144 t->c_oflag == UINT_MAX &&
2145 t->c_cflag == UINT_MAX &&
2146 t->c_lflag == UINT_MAX;
2147 }
2148
2149 void termios_reset(const TermiosResetContext *c) {
2150 assert(c);
2151
2152 PROTECT_ERRNO;
2153
2154 if (c->fd && *c->fd >= 0 && !termios_is_null(c->termios))
2155 (void) tcsetattr(*c->fd, TCSANOW, c->termios);
2156 }
2157
2158 typedef enum BackgroundColorState {
2159 BACKGROUND_TEXT,
2160 BACKGROUND_ESCAPE,
2161 BACKGROUND_BRACKET,
2162 BACKGROUND_FIRST_ONE,
2163 BACKGROUND_SECOND_ONE,
2164 BACKGROUND_SEMICOLON,
2165 BACKGROUND_R,
2166 BACKGROUND_G,
2167 BACKGROUND_B,
2168 BACKGROUND_RED,
2169 BACKGROUND_GREEN,
2170 BACKGROUND_BLUE,
2171 BACKGROUND_STRING_TERMINATOR,
2172 } BackgroundColorState;
2173
2174 typedef struct BackgroundColorContext {
2175 BackgroundColorState state;
2176 uint32_t red, green, blue;
2177 unsigned red_bits, green_bits, blue_bits;
2178 } BackgroundColorContext;
2179
2180 static int scan_background_color_response(
2181 BackgroundColorContext *context,
2182 const char *buf,
2183 size_t size,
2184 size_t *ret_processed) {
2185
2186 assert(context);
2187 assert(buf);
2188 assert(ret_processed);
2189
2190 for (size_t i = 0; i < size; i++) {
2191 char c = buf[i];
2192
2193 switch (context->state) {
2194
2195 case BACKGROUND_TEXT:
2196 context->state = c == '\x1B' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
2197 break;
2198
2199 case BACKGROUND_ESCAPE:
2200 context->state = c == ']' ? BACKGROUND_BRACKET : BACKGROUND_TEXT;
2201 break;
2202
2203 case BACKGROUND_BRACKET:
2204 context->state = c == '1' ? BACKGROUND_FIRST_ONE : BACKGROUND_TEXT;
2205 break;
2206
2207 case BACKGROUND_FIRST_ONE:
2208 context->state = c == '1' ? BACKGROUND_SECOND_ONE : BACKGROUND_TEXT;
2209 break;
2210
2211 case BACKGROUND_SECOND_ONE:
2212 context->state = c == ';' ? BACKGROUND_SEMICOLON : BACKGROUND_TEXT;
2213 break;
2214
2215 case BACKGROUND_SEMICOLON:
2216 context->state = c == 'r' ? BACKGROUND_R : BACKGROUND_TEXT;
2217 break;
2218
2219 case BACKGROUND_R:
2220 context->state = c == 'g' ? BACKGROUND_G : BACKGROUND_TEXT;
2221 break;
2222
2223 case BACKGROUND_G:
2224 context->state = c == 'b' ? BACKGROUND_B : BACKGROUND_TEXT;
2225 break;
2226
2227 case BACKGROUND_B:
2228 context->state = c == ':' ? BACKGROUND_RED : BACKGROUND_TEXT;
2229 break;
2230
2231 case BACKGROUND_RED:
2232 if (c == '/')
2233 context->state = context->red_bits > 0 ? BACKGROUND_GREEN : BACKGROUND_TEXT;
2234 else {
2235 int d = unhexchar(c);
2236 if (d < 0 || context->red_bits >= sizeof(context->red)*8)
2237 context->state = BACKGROUND_TEXT;
2238 else {
2239 context->red = (context->red << 4) | d;
2240 context->red_bits += 4;
2241 }
2242 }
2243 break;
2244
2245 case BACKGROUND_GREEN:
2246 if (c == '/')
2247 context->state = context->green_bits > 0 ? BACKGROUND_BLUE : BACKGROUND_TEXT;
2248 else {
2249 int d = unhexchar(c);
2250 if (d < 0 || context->green_bits >= sizeof(context->green)*8)
2251 context->state = BACKGROUND_TEXT;
2252 else {
2253 context->green = (context->green << 4) | d;
2254 context->green_bits += 4;
2255 }
2256 }
2257 break;
2258
2259 case BACKGROUND_BLUE:
2260 if (c == '\x07') {
2261 if (context->blue_bits > 0) {
2262 *ret_processed = i + 1;
2263 return 1; /* success! */
2264 }
2265
2266 context->state = BACKGROUND_TEXT;
2267 } else if (c == '\x1b')
2268 context->state = context->blue_bits > 0 ? BACKGROUND_STRING_TERMINATOR : BACKGROUND_TEXT;
2269 else {
2270 int d = unhexchar(c);
2271 if (d < 0 || context->blue_bits >= sizeof(context->blue)*8)
2272 context->state = BACKGROUND_TEXT;
2273 else {
2274 context->blue = (context->blue << 4) | d;
2275 context->blue_bits += 4;
2276 }
2277 }
2278 break;
2279
2280 case BACKGROUND_STRING_TERMINATOR:
2281 if (c == '\\') {
2282 *ret_processed = i + 1;
2283 return 1; /* success! */
2284 }
2285
2286 context->state = c == ']' ? BACKGROUND_ESCAPE : BACKGROUND_TEXT;
2287 break;
2288
2289 }
2290
2291 /* Reset any colors we might have picked up */
2292 if (IN_SET(context->state, BACKGROUND_TEXT, BACKGROUND_ESCAPE)) {
2293 /* reset color */
2294 context->red = context->green = context->blue = 0;
2295 context->red_bits = context->green_bits = context->blue_bits = 0;
2296 }
2297 }
2298
2299 *ret_processed = size;
2300 return 0; /* all good, but not enough data yet */
2301 }
2302
2303 int get_default_background_color(double *ret_red, double *ret_green, double *ret_blue) {
2304 int r;
2305
2306 assert(ret_red);
2307 assert(ret_green);
2308 assert(ret_blue);
2309
2310 if (!colors_enabled())
2311 return -EOPNOTSUPP;
2312
2313 r = terminal_verify_same(STDIN_FILENO, STDOUT_FILENO);
2314 if (r < 0)
2315 return r;
2316
2317 if (streq_ptr(getenv("TERM"), "linux")) {
2318 /* Linux console is black */
2319 *ret_red = *ret_green = *ret_blue = 0.0;
2320 return 0;
2321 }
2322
2323 /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2324 * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2325 _cleanup_close_ int nonblock_input_fd = r = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2326 if (r < 0)
2327 return r;
2328
2329 struct termios old_termios = TERMIOS_NULL;
2330 CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
2331
2332 if (tcgetattr(nonblock_input_fd, &old_termios) < 0)
2333 return -errno;
2334
2335 struct termios new_termios = old_termios;
2336 termios_disable_echo(&new_termios);
2337
2338 if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
2339 return -errno;
2340
2341 r = loop_write(STDOUT_FILENO, ANSI_OSC "11;?" ANSI_ST, SIZE_MAX);
2342 if (r < 0)
2343 return r;
2344
2345 usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2346 char buf[STRLEN(ANSI_OSC "11;rgb:0/0/0" ANSI_ST)]; /* shortest possible reply */
2347 size_t buf_full = 0;
2348 BackgroundColorContext context = {};
2349
2350 for (bool first = true;; first = false) {
2351 if (buf_full == 0) {
2352 usec_t n = now(CLOCK_MONOTONIC);
2353 if (n >= end)
2354 return -EOPNOTSUPP;
2355
2356 r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
2357 if (r < 0)
2358 return r;
2359 if (r == 0)
2360 return -EOPNOTSUPP;
2361
2362 /* On the first try, read multiple characters, i.e. the shortest valid
2363 * reply. Afterwards read byte-wise, since we don't want to read too much, and
2364 * unnecessarily drop too many characters from the input queue. */
2365 ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
2366 if (l < 0) {
2367 if (errno == EAGAIN)
2368 continue;
2369 return -errno;
2370 }
2371
2372 assert((size_t) l <= sizeof(buf));
2373 buf_full = l;
2374 }
2375
2376 size_t processed;
2377 r = scan_background_color_response(&context, buf, buf_full, &processed);
2378 if (r < 0)
2379 return r;
2380
2381 assert(processed <= buf_full);
2382 buf_full -= processed;
2383 memmove(buf, buf + processed, buf_full);
2384
2385 if (r > 0) {
2386 assert(context.red_bits > 0);
2387 *ret_red = (double) context.red / ((UINT64_C(1) << context.red_bits) - 1);
2388 assert(context.green_bits > 0);
2389 *ret_green = (double) context.green / ((UINT64_C(1) << context.green_bits) - 1);
2390 assert(context.blue_bits > 0);
2391 *ret_blue = (double) context.blue / ((UINT64_C(1) << context.blue_bits) - 1);
2392 return 0;
2393 }
2394 }
2395 }
2396
2397 /* Determine terminal dimensions by means of ANSI sequences: save the cursor via DECSC, position it far
2398 * to the bottom right (clamped to actual terminal dimensions), read back via DSR where we ended up, and
2399 * restore cursor via DECRC. Only needs a single DSR round-trip, and always restores the cursor regardless
2400 * of whether the response is received.
2401 *
2402 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
2403 static int terminal_query_size_by_dsr(
2404 int nonblock_input_fd,
2405 int output_fd,
2406 unsigned *ret_rows,
2407 unsigned *ret_columns) {
2408
2409 int r;
2410
2411 assert(nonblock_input_fd >= 0);
2412 assert(output_fd >= 0);
2413
2414 /* Use DECSC/DECRC to save/restore cursor instead of querying position via DSR. This way the cursor
2415 * is always restored — even on timeout — and we only need one DSR response instead of two. */
2416 r = loop_write_full(output_fd,
2417 "\x1B" "7" /* DECSC: save cursor position */
2418 "\x1B[32766;32766H" /* CUP: position cursor far to the right and to the bottom, staying within 16bit signed range */
2419 "\x1B[6n" /* DSR: request cursor position (CPR) */
2420 "\x1B" "8", /* DECRC: restore cursor position */
2421 SIZE_MAX,
2422 CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2423 if (r < 0)
2424 return r;
2425
2426 usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2427 char buf[STRLEN("\x1B[1;1R")]; /* The shortest valid reply possible */
2428 size_t buf_full = 0;
2429 CursorPositionContext context = {};
2430
2431 for (bool first = true;; first = false) {
2432 if (buf_full == 0) {
2433 usec_t n = now(CLOCK_MONOTONIC);
2434 if (n >= end)
2435 return -EOPNOTSUPP;
2436
2437 r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
2438 if (r < 0)
2439 return r;
2440 if (r == 0)
2441 return -EOPNOTSUPP;
2442
2443 /* On the first try, read multiple characters, i.e. the shortest valid
2444 * reply. Afterwards read byte-wise, since we don't want to read too much, and
2445 * unnecessarily drop too many characters from the input queue. */
2446 ssize_t l = read(nonblock_input_fd, buf, first ? sizeof(buf) : 1);
2447 if (l < 0) {
2448 if (errno == EAGAIN)
2449 continue;
2450
2451 return -errno;
2452 }
2453
2454 assert((size_t) l <= sizeof(buf));
2455 buf_full = l;
2456 }
2457
2458 size_t processed;
2459 r = scan_cursor_position_response(&context, buf, buf_full, &processed);
2460 if (r < 0)
2461 return r;
2462
2463 assert(processed <= buf_full);
2464 buf_full -= processed;
2465 memmove(buf, buf + processed, buf_full);
2466
2467 if (r > 0) {
2468 /* Superficial validity checks (no particular reason to check for < 4, it's
2469 * just a way to look for unreasonably small values) */
2470 if (context.row < 4 || context.column < 4 || context.row >= 32766 || context.column >= 32766)
2471 return -ENODATA;
2472
2473 if (ret_rows)
2474 *ret_rows = context.row;
2475 if (ret_columns)
2476 *ret_columns = context.column;
2477
2478 return 0;
2479 }
2480 }
2481 }
2482
2483 /* Common setup for ANSI terminal queries: validate the fds, open a non-blocking input fd, and configure
2484 * termios with echo and canonical mode disabled. Caller must restore termios and close the fd when done. */
2485 static int terminal_prepare_query(
2486 int input_fd,
2487 int output_fd,
2488 int *ret_nonblock_fd,
2489 struct termios *ret_saved_termios) {
2490
2491 int r;
2492
2493 assert(input_fd >= 0);
2494 assert(output_fd >= 0);
2495 assert(ret_nonblock_fd);
2496 assert(ret_saved_termios);
2497
2498 /* Use getenv_terminal_is_dumb() instead of terminal_is_dumb() here since we operate on an
2499 * explicitly passed fd, not on stdio. terminal_is_dumb() additionally checks on_tty() which
2500 * tests whether *stderr* is a tty — that's irrelevant when we're querying a directly opened
2501 * terminal such as /dev/console. */
2502 if (getenv_terminal_is_dumb())
2503 return -EOPNOTSUPP;
2504
2505 r = terminal_verify_same(input_fd, output_fd);
2506 if (r < 0)
2507 return log_debug_errno(r, "Called with distinct input/output fds: %m");
2508
2509 /* Open a 2nd input fd, in non-blocking mode, so that we won't ever hang in read()
2510 * should someone else process the POLLIN. Do all subsequent operations on the new fd. */
2511 _cleanup_close_ int nonblock_input_fd = r = fd_reopen(input_fd, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2512 if (r < 0)
2513 return r;
2514
2515 if (tcgetattr(nonblock_input_fd, ret_saved_termios) < 0)
2516 return log_debug_errno(errno, "Failed to get terminal settings: %m");
2517
2518 struct termios new_termios = *ret_saved_termios;
2519 termios_disable_echo(&new_termios);
2520
2521 if (tcsetattr(nonblock_input_fd, TCSANOW, &new_termios) < 0)
2522 return log_debug_errno(errno, "Failed to set new terminal settings: %m");
2523
2524 *ret_nonblock_fd = TAKE_FD(nonblock_input_fd);
2525 return 0;
2526 }
2527
2528 /*
2529 * See https://terminalguide.namepad.de/seq/csi_st-18/,
2530 * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_.
2531 */
2532 #define CSI18_Q "\x1B[18t" /* Report the size of the text area in characters */
2533 #define CSI18_Rp "\x1B[8;" /* Reply prefix */
2534 #define CSI18_R0 CSI18_Rp "1;1t" /* Shortest reply */
2535 #define CSI18_R1 CSI18_Rp "32766;32766t" /* Longest reply */
2536
2537 static int scan_text_area_size_response(
2538 const char *buf,
2539 size_t size,
2540 unsigned *ret_rows,
2541 unsigned *ret_columns) {
2542
2543 assert(buf);
2544 assert(ret_rows);
2545 assert(ret_columns);
2546
2547 /* Check if we have enough space for the shortest possible answer. */
2548 if (size < STRLEN(CSI18_R0))
2549 return -EAGAIN;
2550
2551 /* Check if the terminating sequence is present */
2552 if (buf[size - 1] != 't')
2553 return -EAGAIN;
2554
2555 unsigned short rows, columns;
2556 if (sscanf(buf, CSI18_Rp "%hu;%hut", &rows, &columns) != 2)
2557 return -EINVAL;
2558
2559 *ret_rows = rows;
2560 *ret_columns = columns;
2561 return 0;
2562 }
2563
2564 /* Determine terminal dimensions by means of an ANSI CSI 18 sequence.
2565 *
2566 * Caller must have already opened a non-blocking input fd and configured termios (echo/icanon off). */
2567 static int terminal_query_size_by_csi18(
2568 int nonblock_input_fd,
2569 int output_fd,
2570 unsigned *ret_rows,
2571 unsigned *ret_columns) {
2572
2573 int r;
2574
2575 assert(nonblock_input_fd >= 0);
2576 assert(output_fd >= 0);
2577
2578 r = loop_write_full(output_fd, CSI18_Q, SIZE_MAX, CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2579 if (r < 0)
2580 return r;
2581
2582 usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2583 char buf[STRLEN(CSI18_R1)];
2584 size_t bytes = 0;
2585
2586 for (;;) {
2587 usec_t n = now(CLOCK_MONOTONIC);
2588 if (n >= end)
2589 return -EOPNOTSUPP;
2590
2591 r = fd_wait_for_event(nonblock_input_fd, POLLIN, usec_sub_unsigned(end, n));
2592 if (r < 0)
2593 return r;
2594 if (r == 0)
2595 return -EOPNOTSUPP;
2596
2597 /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2598 * read byte by byte, since we don't want to read too much and drop characters from the input
2599 * queue. */
2600 ssize_t l = read(nonblock_input_fd, buf + bytes, bytes == 0 ? STRLEN(CSI18_R0) : 1);
2601 if (l < 0) {
2602 if (errno == EAGAIN)
2603 continue;
2604 return -errno;
2605 }
2606
2607 assert((size_t) l <= sizeof(buf) - bytes);
2608 bytes += l;
2609
2610 r = scan_text_area_size_response(buf, bytes, ret_rows, ret_columns);
2611 if (r != -EAGAIN)
2612 return r;
2613
2614 if (bytes == sizeof(buf))
2615 return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2616 * answer with a terminator in the allotted space. Something is
2617 * wrong, possibly some unrelated bytes got injected into the
2618 * answer. */
2619 }
2620 }
2621
2622 int terminal_get_size(
2623 int input_fd,
2624 int output_fd,
2625 unsigned *ret_rows,
2626 unsigned *ret_columns,
2627 bool try_dsr,
2628 bool try_csi18) {
2629
2630 _cleanup_close_ int nonblock_input_fd = -EBADF;
2631 struct termios old_termios = TERMIOS_NULL;
2632 CLEANUP_TERMIOS_RESET(nonblock_input_fd, old_termios);
2633 _cleanup_(nonblock_resetp) int nonblock_reset = -EBADF;
2634 int r;
2635
2636 assert(try_dsr || try_csi18);
2637
2638 r = terminal_prepare_query(input_fd, output_fd, &nonblock_input_fd, &old_termios);
2639 if (r < 0)
2640 return r;
2641
2642 /* Put the output fd in non-blocking mode with a write timeout, to avoid blocking indefinitely on
2643 * write if the terminal is not consuming data (e.g. serial console with flow control). */
2644 r = fd_nonblock(output_fd, true);
2645 if (r < 0)
2646 return log_debug_errno(r, "Failed to set terminal to non-blocking mode: %m");
2647 if (r > 0)
2648 nonblock_reset = output_fd;
2649
2650 /* Flush any stale input that might confuse the response parsers. */
2651 (void) tcflush(nonblock_input_fd, TCIFLUSH);
2652
2653 if (try_csi18) {
2654 r = terminal_query_size_by_csi18(nonblock_input_fd, output_fd, ret_rows, ret_columns);
2655 if (r >= 0)
2656 return r;
2657
2658 /* Query failed. Flush any outstanding input. */
2659 (void) tcflush(nonblock_input_fd, TCIFLUSH);
2660
2661 if (!IN_SET(r, -EOPNOTSUPP, -EINVAL))
2662 return r;
2663 }
2664
2665 if (try_dsr) {
2666 r = terminal_query_size_by_dsr(nonblock_input_fd, output_fd, ret_rows, ret_columns);
2667 if (r >= 0)
2668 return r;
2669
2670 /* Query failed. Flush any outstanding input. */
2671 (void) tcflush(nonblock_input_fd, TCIFLUSH);
2672 }
2673
2674 return r;
2675 }
2676
2677 int terminal_fix_size(int input_fd, int output_fd) {
2678 unsigned rows, columns;
2679 int r;
2680
2681 /* Tries to update the current terminal dimensions to the ones reported via ANSI sequences.
2682 *
2683 * Why bother with this? The ioctl() information is often incorrect on serial terminals (since
2684 * there's no handshake or protocol to determine the right dimensions in RS232), but since the ANSI
2685 * sequences are interpreted by the final terminal instead of an intermediary tty driver they should
2686 * be more accurate.
2687 */
2688
2689 struct winsize ws = {};
2690 if (ioctl(output_fd, TIOCGWINSZ, &ws) < 0)
2691 return log_debug_errno(errno, "Failed to query terminal dimensions, ignoring: %m");
2692
2693 r = terminal_get_size(input_fd, output_fd, &rows, &columns, /* try_dsr= */ true, /* try_csi18= */ true);
2694 if (r < 0)
2695 return log_debug_errno(r, "Failed to acquire terminal dimensions via ANSI sequences, not adjusting terminal dimensions: %m");
2696
2697 if (ws.ws_row == rows && ws.ws_col == columns) {
2698 log_debug("Terminal dimensions reported via ANSI sequences match currently set terminal dimensions, not changing.");
2699 return 0;
2700 }
2701
2702 ws.ws_col = columns;
2703 ws.ws_row = rows;
2704
2705 if (ioctl(output_fd, TIOCSWINSZ, &ws) < 0)
2706 return log_debug_errno(errno, "Failed to update terminal dimensions, ignoring: %m");
2707
2708 log_debug("Fixed terminal dimensions to %ux%u based on ANSI sequence information.", columns, rows);
2709 return 1;
2710 }
2711
2712 #define MAX_TERMINFO_LENGTH 64
2713 /* python -c 'print("".join(hex(ord(i))[2:] for i in "name").upper())' */
2714 #define DCS_TERMINFO_Q ANSI_DCS "+q" "6E616D65" ANSI_ST
2715 /* The answer is either 0+r… (invalid) or 1+r… (OK). */
2716 #define DCS_TERMINFO_R0 ANSI_DCS "0+r" ANSI_ST
2717 #define DCS_TERMINFO_R1 ANSI_DCS "1+r" "6E616D65" "=" /* This is followed by Pt ST. */
2718 assert_cc(STRLEN(DCS_TERMINFO_R0) <= STRLEN(DCS_TERMINFO_R1 ANSI_ST));
2719
2720 static int scan_terminfo_response(
2721 const char *buf,
2722 size_t size,
2723 char **ret_name) {
2724 int r;
2725
2726 assert(buf);
2727 assert(ret_name);
2728
2729 /* Check if we have enough space for the shortest possible answer. */
2730 if (size < STRLEN(DCS_TERMINFO_R0))
2731 return -EAGAIN;
2732
2733 /* Check if the terminating sequence is present */
2734 if (memcmp(buf + size - STRLEN(ANSI_ST), ANSI_ST, STRLEN(ANSI_ST)) != 0)
2735 return -EAGAIN;
2736
2737 if (size <= STRLEN(DCS_TERMINFO_R1 ANSI_ST))
2738 return -EINVAL; /* The answer is invalid or empty */
2739
2740 if (memcmp(buf, DCS_TERMINFO_R1, STRLEN(DCS_TERMINFO_R1)) != 0)
2741 return -EINVAL; /* The answer is not valid */
2742
2743 _cleanup_free_ void *dec = NULL;
2744 size_t dec_size;
2745 r = unhexmem_full(buf + STRLEN(DCS_TERMINFO_R1), size - STRLEN(DCS_TERMINFO_R1 ANSI_ST),
2746 /* secure= */ false,
2747 &dec, &dec_size);
2748 if (r < 0)
2749 return r;
2750
2751 assert(((const char *) dec)[dec_size] == '\0'); /* unhexmem appends NUL for our convenience */
2752 if (memchr(dec, '\0', dec_size) || string_has_cc(dec, NULL) || !filename_is_valid(dec))
2753 return -EUCLEAN;
2754
2755 *ret_name = TAKE_PTR(dec);
2756 return 0;
2757 }
2758
2759 int terminal_get_terminfo_by_dcs(int fd, char **ret_name) {
2760 int r;
2761
2762 assert(fd >= 0);
2763 assert(ret_name);
2764
2765 /* Note: fd must be in non-blocking read-write mode! */
2766
2767 struct termios old_termios = TERMIOS_NULL;
2768 CLEANUP_TERMIOS_RESET(fd, old_termios);
2769
2770 if (tcgetattr(fd, &old_termios) < 0)
2771 return -errno;
2772
2773 struct termios new_termios = old_termios;
2774 termios_disable_echo(&new_termios);
2775
2776 if (tcsetattr(fd, TCSANOW, &new_termios) < 0)
2777 return -errno;
2778
2779 r = loop_write(fd, DCS_TERMINFO_Q, SIZE_MAX);
2780 if (r < 0)
2781 return r;
2782
2783 usec_t end = usec_add(now(CLOCK_MONOTONIC), CONSOLE_ANSI_SEQUENCE_TIMEOUT_USEC);
2784 char buf[STRLEN(DCS_TERMINFO_R1) + MAX_TERMINFO_LENGTH + STRLEN(ANSI_ST)];
2785 size_t bytes = 0;
2786
2787 for (;;) {
2788 usec_t n = now(CLOCK_MONOTONIC);
2789 if (n >= end)
2790 return -EOPNOTSUPP;
2791
2792 r = fd_wait_for_event(fd, POLLIN, usec_sub_unsigned(end, n));
2793 if (r < 0)
2794 return r;
2795 if (r == 0)
2796 return -EOPNOTSUPP;
2797
2798 /* On the first read, read multiple characters, i.e. the shortest valid reply. Afterwards
2799 * read byte by byte, since we don't want to read too much and drop characters from the input
2800 * queue. */
2801 ssize_t l = read(fd, buf + bytes, bytes == 0 ? STRLEN(DCS_TERMINFO_R0) : 1);
2802 if (l < 0) {
2803 if (errno == EAGAIN)
2804 continue;
2805 return -errno;
2806 }
2807
2808 assert((size_t) l <= sizeof(buf) - bytes);
2809 bytes += l;
2810
2811 r = scan_terminfo_response(buf, bytes, ret_name);
2812 if (r != -EAGAIN)
2813 return r;
2814
2815 if (bytes == sizeof(buf))
2816 return -EOPNOTSUPP; /* The response has the right prefix, but we didn't find a valid
2817 * answer with a terminator in the allotted space. Something is
2818 * wrong, possibly some unrelated bytes got injected into the
2819 * answer. */
2820 }
2821 }
2822
2823 int have_terminfo_file(const char *name) {
2824 /* This is a heuristic check if we have the file, using the directory layout used on
2825 * current Linux systems. Checks for other layouts can be added later if appropriate. */
2826 int r;
2827
2828 assert(filename_is_valid(name));
2829
2830 _cleanup_free_ char *p = path_join("/usr/share/terminfo", CHAR_TO_STR(name[0]), name);
2831 if (!p)
2832 return log_oom_debug();
2833
2834 r = RET_NERRNO(access(p, F_OK));
2835 if (r == -ENOENT)
2836 return false;
2837 if (r < 0)
2838 return r;
2839 return true;
2840 }
2841
2842 int query_term_for_tty(const char *tty, char **ret_term) {
2843 _cleanup_free_ char *dcs_term = NULL;
2844 int r;
2845
2846 assert(tty);
2847 assert(ret_term);
2848
2849 if (tty_is_vc_resolve(tty))
2850 return strdup_to(ret_term, "linux");
2851
2852 /* Try to query the terminal implementation that we're on. This will not work in all
2853 * cases, which is fine, since this is intended to be used as a fallback. */
2854
2855 _cleanup_close_ int tty_fd = open_terminal(tty, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
2856 if (tty_fd < 0)
2857 return log_debug_errno(tty_fd, "Failed to open %s to query terminfo: %m", tty);
2858
2859 r = terminal_get_terminfo_by_dcs(tty_fd, &dcs_term);
2860 if (r < 0)
2861 return log_debug_errno(r, "Failed to query %s for terminfo: %m", tty);
2862
2863 r = have_terminfo_file(dcs_term);
2864 if (r < 0)
2865 return log_debug_errno(r, "Failed to look for terminfo %s: %m", dcs_term);
2866 if (r == 0)
2867 return log_info_errno(SYNTHETIC_ERRNO(ENODATA),
2868 "Terminfo %s not found for %s.", dcs_term, tty);
2869
2870 *ret_term = TAKE_PTR(dcs_term);
2871 return 0;
2872 }
2873
2874 int terminal_is_pty_fd(int fd) {
2875 int r;
2876
2877 assert(fd >= 0);
2878
2879 /* Returns true if we are looking at a pty, i.e. if it's backed by the /dev/pts/ file system */
2880
2881 if (!isatty_safe(fd))
2882 return false;
2883
2884 r = is_fs_type_at(fd, NULL, DEVPTS_SUPER_MAGIC);
2885 if (r != 0)
2886 return r;
2887
2888 /* The ptmx device is weird, it exists twice, once inside and once outside devpts. To detect the
2889 * latter case, let's fire off an ioctl() that only works on ptmx devices. */
2890
2891 int v;
2892 if (ioctl(fd, TIOCGPKT, &v) < 0) {
2893 if (ERRNO_IS_NOT_SUPPORTED(errno))
2894 return false;
2895
2896 return -errno;
2897 }
2898
2899 return true;
2900 }
2901
2902 int pty_open_peer(int fd, int mode) {
2903 assert(fd >= 0);
2904
2905 /* Opens the peer PTY using the new race-free TIOCGPTPEER ioctl() (kernel 4.13).
2906 *
2907 * This is safe to be called on TTYs from other namespaces. */
2908
2909 assert((mode & (O_CREAT|O_PATH|O_DIRECTORY|O_TMPFILE)) == 0);
2910
2911 /* This replicates the EIO retry logic of open_terminal() in a modified way. */
2912 for (unsigned c = 0;; c++) {
2913 int peer_fd = ioctl(fd, TIOCGPTPEER, mode);
2914 if (peer_fd >= 0)
2915 return peer_fd;
2916
2917 if (errno != EIO)
2918 return -errno;
2919
2920 /* Max 1s in total */
2921 if (c >= 20)
2922 return -EIO;
2923
2924 (void) usleep_safe(50 * USEC_PER_MSEC);
2925 }
2926 }