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