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