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