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