]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/terminal-util.c
terminal-util: trivial modernizations for reset_terminal_fd()
[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;
197dd3a9 52static volatile int cached_on_dev_null = -1;
c4fea19a 53static volatile int cached_color_mode = _COLOR_INVALID;
c6063244
LP
54static volatile int cached_underline_enabled = -1;
55
288a74cc 56int chvt(int vt) {
254d1313 57 _cleanup_close_ int fd = -EBADF;
288a74cc 58
0295642d
LP
59 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
60 * if that's configured. */
61
0a8b555c 62 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
63 if (fd < 0)
64 return -errno;
65
b9e74c39 66 if (vt <= 0) {
288a74cc
RC
67 int tiocl[2] = {
68 TIOCL_GETKMSGREDIRECT,
69 0
70 };
71
72 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
73 return -errno;
74
75 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
76 }
77
7c248223 78 return RET_NERRNO(ioctl(fd, VT_ACTIVATE, vt));
288a74cc
RC
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;
68e4c637 236 int r;
288a74cc
RC
237
238 /* Set terminal to some sane defaults */
239
240 assert(fd >= 0);
241
e60a4a3c
LP
242 if (isatty(fd) < 1)
243 return log_debug_errno(errno, "Asked to reset a terminal that actually isn't a terminal: %m");
244
245 /* We leave locked terminal attributes untouched, so that Plymouth may set whatever it wants to set,
246 * and we don't interfere with that. */
288a74cc
RC
247
248 /* Disable exclusive mode, just in case */
7eaee902
LP
249 if (ioctl(fd, TIOCNXCL) < 0)
250 log_debug_errno(errno, "TIOCNXCL ioctl failed on TTY, ignoring: %m");
288a74cc
RC
251
252 /* Switch to text mode */
253 if (switch_to_text)
7eaee902
LP
254 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
255 log_debug_errno(errno, "KDSETMODE ioctl for switching to text mode failed on TTY, ignoring: %m");
256
288a74cc 257
73e669e0 258 /* Set default keyboard mode */
68e4c637
LP
259 r = vt_reset_keyboard(fd);
260 if (r < 0)
261 log_debug_errno(r, "Failed to reset VT keyboard, ignoring: %m");
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;
9fe26523 274 termios.c_oflag |= ONLCR | OPOST;
288a74cc
RC
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
68e4c637 295 r = RET_NERRNO(tcsetattr(fd, TCSANOW, &termios));
288a74cc
RC
296
297finish:
298 /* Just in case, flush all crap out */
7d927c9a 299 (void) tcflush(fd, TCIOFLUSH);
288a74cc
RC
300
301 return r;
302}
303
304int reset_terminal(const char *name) {
254d1313 305 _cleanup_close_ int fd = -EBADF;
288a74cc 306
0a8b555c
LP
307 /* We open the terminal with O_NONBLOCK here, to ensure we
308 * don't block on carrier if this is a terminal with carrier
309 * configured. */
310
311 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
312 if (fd < 0)
313 return fd;
314
315 return reset_terminal_fd(fd, true);
316}
317
318int open_terminal(const char *name, int mode) {
254d1313 319 _cleanup_close_ int fd = -EBADF;
288a74cc
RC
320 unsigned c = 0;
321
322 /*
4768529f
LP
323 * If a TTY is in the process of being closed opening it might cause EIO. This is horribly awful, but
324 * unlikely to be changed in the kernel. Hence we work around this problem by retrying a couple of
325 * times.
288a74cc
RC
326 *
327 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
328 */
329
35bdab77
LP
330 if (mode & O_CREAT)
331 return -EINVAL;
288a74cc
RC
332
333 for (;;) {
334 fd = open(name, mode, 0);
335 if (fd >= 0)
336 break;
337
338 if (errno != EIO)
339 return -errno;
340
341 /* Max 1s in total */
342 if (c >= 20)
343 return -errno;
344
4251512e 345 (void) usleep_safe(50 * USEC_PER_MSEC);
288a74cc
RC
346 c++;
347 }
348
4768529f
LP
349 if (isatty(fd) < 1)
350 return negative_errno();
288a74cc 351
4768529f 352 return TAKE_FD(fd);
288a74cc
RC
353}
354
355int acquire_terminal(
356 const char *name,
8854d795 357 AcquireTerminalFlags flags,
288a74cc
RC
358 usec_t timeout) {
359
254d1313 360 _cleanup_close_ int notify = -EBADF, fd = -EBADF;
8854d795
LP
361 usec_t ts = USEC_INFINITY;
362 int r, wd = -1;
288a74cc
RC
363
364 assert(name);
8854d795 365 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
288a74cc 366
8854d795
LP
367 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
368 * acquire it, so that we don't lose any event.
288a74cc 369 *
8854d795
LP
370 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
371 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
f95dbcc2
ZJS
372 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
373 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
8854d795
LP
374 * probably should not do anyway.) */
375
376 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
288a74cc 377 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
8854d795
LP
378 if (notify < 0)
379 return -errno;
288a74cc
RC
380
381 wd = inotify_add_watch(notify, name, IN_CLOSE);
8854d795
LP
382 if (wd < 0)
383 return -errno;
384
385 if (timeout != USEC_INFINITY)
386 ts = now(CLOCK_MONOTONIC);
288a74cc
RC
387 }
388
389 for (;;) {
390 struct sigaction sa_old, sa_new = {
391 .sa_handler = SIG_IGN,
392 .sa_flags = SA_RESTART,
393 };
394
395 if (notify >= 0) {
396 r = flush_fd(notify);
397 if (r < 0)
8854d795 398 return r;
288a74cc
RC
399 }
400
8854d795
LP
401 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
402 * to figure out if we successfully became the controlling process of the tty */
288a74cc
RC
403 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
404 if (fd < 0)
405 return fd;
406
8854d795 407 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
288a74cc
RC
408 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
409
410 /* First, try to get the tty */
7c248223 411 r = RET_NERRNO(ioctl(fd, TIOCSCTTY, (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE));
288a74cc 412
8854d795 413 /* Reset signal handler to old value */
288a74cc
RC
414 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
415
8854d795
LP
416 /* Success? Exit the loop now! */
417 if (r >= 0)
418 break;
288a74cc 419
8854d795
LP
420 /* Any failure besides -EPERM? Fail, regardless of the mode. */
421 if (r != -EPERM)
422 return r;
288a74cc 423
8854d795
LP
424 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
425 * into a success. Note that EPERM is also returned if we
426 * already are the owner of the TTY. */
288a74cc
RC
427 break;
428
8854d795
LP
429 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
430 return r;
431
288a74cc 432 assert(notify >= 0);
8854d795 433 assert(wd >= 0);
288a74cc
RC
434
435 for (;;) {
436 union inotify_event_buffer buffer;
288a74cc
RC
437 ssize_t l;
438
439 if (timeout != USEC_INFINITY) {
440 usec_t n;
441
8854d795
LP
442 assert(ts != USEC_INFINITY);
443
496db330
YW
444 n = usec_sub_unsigned(now(CLOCK_MONOTONIC), ts);
445 if (n >= timeout)
8854d795 446 return -ETIMEDOUT;
288a74cc 447
496db330 448 r = fd_wait_for_event(notify, POLLIN, usec_sub_unsigned(timeout, n));
288a74cc 449 if (r < 0)
8854d795
LP
450 return r;
451 if (r == 0)
452 return -ETIMEDOUT;
288a74cc
RC
453 }
454
455 l = read(notify, &buffer, sizeof(buffer));
456 if (l < 0) {
8add30a0 457 if (ERRNO_IS_TRANSIENT(errno))
288a74cc
RC
458 continue;
459
8854d795 460 return -errno;
288a74cc
RC
461 }
462
463 FOREACH_INOTIFY_EVENT(e, buffer, l) {
8854d795
LP
464 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
465 break;
466
467 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
468 return -EIO;
288a74cc
RC
469 }
470
471 break;
472 }
473
8854d795
LP
474 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
475 * we do this after sleeping, so that we don't enter an endless loop. */
288a74cc
RC
476 fd = safe_close(fd);
477 }
478
c10d6bdb 479 return TAKE_FD(fd);
288a74cc
RC
480}
481
482int release_terminal(void) {
483 static const struct sigaction sa_new = {
484 .sa_handler = SIG_IGN,
485 .sa_flags = SA_RESTART,
486 };
487
254d1313 488 _cleanup_close_ int fd = -EBADF;
288a74cc 489 struct sigaction sa_old;
87964ec7 490 int r;
288a74cc 491
0a8b555c 492 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
493 if (fd < 0)
494 return -errno;
495
496 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
497 * by our own TIOCNOTTY */
498 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
499
7c248223 500 r = RET_NERRNO(ioctl(fd, TIOCNOTTY));
288a74cc
RC
501
502 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
503
504 return r;
505}
506
507int terminal_vhangup_fd(int fd) {
508 assert(fd >= 0);
7c248223 509 return RET_NERRNO(ioctl(fd, TIOCVHANGUP));
288a74cc
RC
510}
511
512int terminal_vhangup(const char *name) {
254d1313 513 _cleanup_close_ int fd = -EBADF;
288a74cc 514
0a8b555c 515 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
288a74cc
RC
516 if (fd < 0)
517 return fd;
518
519 return terminal_vhangup_fd(fd);
520}
521
522int vt_disallocate(const char *name) {
ba5d26cc 523 const char *e;
1ba23931 524 int r;
288a74cc
RC
525
526 /* Deallocate the VT if possible. If not possible
527 * (i.e. because it is the active one), at least clear it
ba5d26cc 528 * entirely (including the scrollback buffer). */
288a74cc 529
27458ed6
LP
530 e = path_startswith(name, "/dev/");
531 if (!e)
288a74cc
RC
532 return -EINVAL;
533
ba5d26cc 534 if (tty_is_vc(name)) {
254d1313 535 _cleanup_close_ int fd = -EBADF;
ba5d26cc
ZJS
536 unsigned u;
537 const char *n;
288a74cc 538
ba5d26cc
ZJS
539 n = startswith(e, "tty");
540 if (!n)
541 return -EINVAL;
288a74cc 542
ba5d26cc
ZJS
543 r = safe_atou(n, &u);
544 if (r < 0)
545 return r;
288a74cc 546
ba5d26cc
ZJS
547 if (u <= 0)
548 return -EINVAL;
288a74cc 549
ba5d26cc
ZJS
550 /* Try to deallocate */
551 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
552 if (fd < 0)
553 return fd;
288a74cc 554
ba5d26cc
ZJS
555 r = ioctl(fd, VT_DISALLOCATE, u);
556 if (r >= 0)
557 return 0;
558 if (errno != EBUSY)
559 return -errno;
560 }
288a74cc 561
ba5d26cc
ZJS
562 /* So this is not a VT (in which case we cannot deallocate it),
563 * or we failed to deallocate. Let's at least clear the screen. */
288a74cc 564
ba5d26cc
ZJS
565 _cleanup_close_ int fd2 = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
566 if (fd2 < 0)
567 return fd2;
288a74cc 568
ba5d26cc
ZJS
569 (void) loop_write(fd2,
570 "\033[r" /* clear scrolling region */
571 "\033[H" /* move home */
572 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
e22c60a9 573 10);
288a74cc
RC
574 return 0;
575}
576
288a74cc
RC
577int make_console_stdio(void) {
578 int fd, r;
579
9281e703
LP
580 /* Make /dev/console the controlling terminal and stdin/stdout/stderr, if we can. If we can't use
581 * /dev/null instead. This is particularly useful if /dev/console is turned off, e.g. if console=null
582 * is specified on the kernel command line. */
288a74cc 583
8854d795 584 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
9281e703
LP
585 if (fd < 0) {
586 log_warning_errno(fd, "Failed to acquire terminal, using /dev/null stdin/stdout/stderr instead: %m");
288a74cc 587
9281e703
LP
588 r = make_null_stdio();
589 if (r < 0)
590 return log_error_errno(r, "Failed to make /dev/null stdin/stdout/stderr: %m");
3d18b167 591
9281e703 592 } else {
29f5a5ae
DDM
593 unsigned rows, cols;
594
102f36ef 595 r = reset_terminal_fd(fd, /* switch_to_text= */ true);
9281e703
LP
596 if (r < 0)
597 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
288a74cc 598
29f5a5ae
DDM
599 r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
600 if (r < 0)
601 log_warning_errno(r, "Failed to get terminal size, ignoring: %m");
602 else {
603 r = terminal_set_size_fd(fd, NULL, rows, cols);
604 if (r < 0)
605 log_warning_errno(r, "Failed to set terminal size, ignoring: %m");
606 }
607
9281e703
LP
608 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
609 if (r < 0)
610 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
611 }
c6063244 612
9281e703 613 reset_terminal_feature_caches();
288a74cc
RC
614 return 0;
615}
616
288a74cc
RC
617bool tty_is_vc(const char *tty) {
618 assert(tty);
619
620 return vtnr_from_tty(tty) >= 0;
621}
622
623bool tty_is_console(const char *tty) {
624 assert(tty);
625
a119ec7c 626 return streq(skip_dev_prefix(tty), "console");
288a74cc
RC
627}
628
629int vtnr_from_tty(const char *tty) {
630 int i, r;
631
632 assert(tty);
633
a119ec7c 634 tty = skip_dev_prefix(tty);
288a74cc
RC
635
636 if (!startswith(tty, "tty") )
637 return -EINVAL;
638
ff25d338 639 if (!ascii_isdigit(tty[3]))
288a74cc
RC
640 return -EINVAL;
641
642 r = safe_atoi(tty+3, &i);
643 if (r < 0)
644 return r;
645
646 if (i < 0 || i > 63)
647 return -EINVAL;
648
649 return i;
650}
651
7b912648
LP
652 int resolve_dev_console(char **ret) {
653 _cleanup_free_ char *active = NULL;
288a74cc 654 char *tty;
7b912648 655 int r;
288a74cc 656
7b912648
LP
657 assert(ret);
658
659 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
660 * sign for container setups) */
288a74cc
RC
661
662 if (path_is_read_only_fs("/sys") > 0)
7b912648 663 return -ENOMEDIUM;
288a74cc 664
7b912648
LP
665 r = read_one_line_file("/sys/class/tty/console/active", &active);
666 if (r < 0)
667 return r;
288a74cc 668
7b912648
LP
669 /* If multiple log outputs are configured the last one is what /dev/console points to */
670 tty = strrchr(active, ' ');
288a74cc
RC
671 if (tty)
672 tty++;
673 else
7b912648 674 tty = active;
288a74cc
RC
675
676 if (streq(tty, "tty0")) {
7b912648 677 active = mfree(active);
288a74cc
RC
678
679 /* Get the active VC (e.g. tty1) */
7b912648
LP
680 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
681 if (r < 0)
682 return r;
683
684 tty = active;
685 }
686
ae2a15bc
LP
687 if (tty == active)
688 *ret = TAKE_PTR(active);
689 else {
7b912648
LP
690 char *tmp;
691
692 tmp = strdup(tty);
693 if (!tmp)
694 return -ENOMEM;
695
696 *ret = tmp;
288a74cc
RC
697 }
698
7b912648 699 return 0;
288a74cc
RC
700}
701
bef41af2
LP
702int get_kernel_consoles(char ***ret) {
703 _cleanup_strv_free_ char **l = NULL;
6af62124 704 _cleanup_free_ char *line = NULL;
bef41af2 705 const char *p;
6af62124
WF
706 int r;
707
bef41af2
LP
708 assert(ret);
709
f95dbcc2 710 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
bef41af2
LP
711 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
712 if (path_is_read_only_fs("/sys") > 0)
713 goto fallback;
6af62124
WF
714
715 r = read_one_line_file("/sys/class/tty/console/active", &line);
716 if (r < 0)
717 return r;
718
bef41af2 719 p = line;
6af62124 720 for (;;) {
6abdec98 721 _cleanup_free_ char *tty = NULL, *path = NULL;
6af62124 722
bef41af2 723 r = extract_first_word(&p, &tty, NULL, 0);
6af62124
WF
724 if (r < 0)
725 return r;
726 if (r == 0)
727 break;
728
729 if (streq(tty, "tty0")) {
730 tty = mfree(tty);
731 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
732 if (r < 0)
733 return r;
734 }
735
6abdec98 736 path = path_join("/dev", tty);
6af62124
WF
737 if (!path)
738 return -ENOMEM;
739
740 if (access(path, F_OK) < 0) {
741 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
6af62124
WF
742 continue;
743 }
744
6abdec98 745 r = strv_consume(&l, TAKE_PTR(path));
6af62124
WF
746 if (r < 0)
747 return r;
748 }
749
bef41af2 750 if (strv_isempty(l)) {
6af62124 751 log_debug("No devices found for system console");
bef41af2 752 goto fallback;
6af62124
WF
753 }
754
ae2a15bc 755 *ret = TAKE_PTR(l);
bef41af2
LP
756
757 return 0;
758
759fallback:
760 r = strv_extend(&l, "/dev/console");
761 if (r < 0)
762 return r;
763
ae2a15bc 764 *ret = TAKE_PTR(l);
bef41af2 765
6af62124
WF
766 return 0;
767}
768
288a74cc 769bool tty_is_vc_resolve(const char *tty) {
7b912648 770 _cleanup_free_ char *resolved = NULL;
288a74cc
RC
771
772 assert(tty);
773
a119ec7c 774 tty = skip_dev_prefix(tty);
288a74cc
RC
775
776 if (streq(tty, "console")) {
7b912648 777 if (resolve_dev_console(&resolved) < 0)
288a74cc 778 return false;
7b912648
LP
779
780 tty = resolved;
288a74cc
RC
781 }
782
783 return tty_is_vc(tty);
784}
785
786const char *default_term_for_tty(const char *tty) {
6af760f3 787 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
288a74cc
RC
788}
789
790int fd_columns(int fd) {
791 struct winsize ws = {};
792
14f594b9
LP
793 if (fd < 0)
794 return -EBADF;
795
288a74cc
RC
796 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
797 return -errno;
798
799 if (ws.ws_col <= 0)
800 return -EIO;
801
802 return ws.ws_col;
803}
804
805unsigned columns(void) {
806 const char *e;
807 int c;
808
c6063244 809 if (cached_columns > 0)
288a74cc
RC
810 return cached_columns;
811
812 c = 0;
813 e = getenv("COLUMNS");
814 if (e)
815 (void) safe_atoi(e, &c);
816
d09a7135 817 if (c <= 0 || c > USHRT_MAX) {
288a74cc 818 c = fd_columns(STDOUT_FILENO);
d09a7135
LP
819 if (c <= 0)
820 c = 80;
821 }
288a74cc
RC
822
823 cached_columns = c;
824 return cached_columns;
825}
826
827int fd_lines(int fd) {
828 struct winsize ws = {};
829
14f594b9
LP
830 if (fd < 0)
831 return -EBADF;
832
288a74cc
RC
833 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
834 return -errno;
835
836 if (ws.ws_row <= 0)
837 return -EIO;
838
839 return ws.ws_row;
840}
841
842unsigned lines(void) {
843 const char *e;
844 int l;
845
c6063244 846 if (cached_lines > 0)
288a74cc
RC
847 return cached_lines;
848
849 l = 0;
850 e = getenv("LINES");
851 if (e)
852 (void) safe_atoi(e, &l);
853
d09a7135 854 if (l <= 0 || l > USHRT_MAX) {
288a74cc 855 l = fd_lines(STDOUT_FILENO);
d09a7135
LP
856 if (l <= 0)
857 l = 24;
858 }
288a74cc
RC
859
860 cached_lines = l;
861 return cached_lines;
862}
863
51462135
DDM
864int terminal_set_size_fd(int fd, const char *ident, unsigned rows, unsigned cols) {
865 struct winsize ws;
866
867 if (rows == UINT_MAX && cols == UINT_MAX)
868 return 0;
869
870 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
871 return log_debug_errno(errno,
872 "TIOCGWINSZ ioctl for getting %s size failed, not setting terminal size: %m",
873 ident ?: "TTY");
874
875 if (rows == UINT_MAX)
876 rows = ws.ws_row;
877 else if (rows > USHRT_MAX)
878 rows = USHRT_MAX;
879
880 if (cols == UINT_MAX)
881 cols = ws.ws_col;
882 else if (cols > USHRT_MAX)
883 cols = USHRT_MAX;
884
885 if (rows == ws.ws_row && cols == ws.ws_col)
886 return 0;
887
888 ws.ws_row = rows;
889 ws.ws_col = cols;
890
891 if (ioctl(fd, TIOCSWINSZ, &ws) < 0)
892 return log_debug_errno(errno, "TIOCSWINSZ ioctl for setting %s size failed: %m", ident ?: "TTY");
893
894 return 0;
895}
896
29f5a5ae
DDM
897int proc_cmdline_tty_size(const char *tty, unsigned *ret_rows, unsigned *ret_cols) {
898 _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
899 unsigned rows = UINT_MAX, cols = UINT_MAX;
900 int r;
901
902 assert(tty);
903
904 if (!ret_rows && !ret_cols)
905 return 0;
906
907 tty = skip_dev_prefix(tty);
908 if (!in_charset(tty, ALPHANUMERICAL))
909 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "%s contains non-alphanumeric characters", tty);
910
911 rowskey = strjoin("systemd.tty.rows.", tty);
912 if (!rowskey)
913 return -ENOMEM;
914
915 colskey = strjoin("systemd.tty.columns.", tty);
916 if (!colskey)
917 return -ENOMEM;
918
919 r = proc_cmdline_get_key_many(/* flags = */ 0,
920 rowskey, &rowsvalue,
921 colskey, &colsvalue);
922 if (r < 0)
923 return log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline: %m", tty);
924
925 if (rowsvalue) {
926 r = safe_atou(rowsvalue, &rows);
927 if (r < 0)
928 return log_debug_errno(r, "Failed to parse %s=%s: %m", rowskey, rowsvalue);
929 }
930
931 if (colsvalue) {
932 r = safe_atou(colsvalue, &cols);
933 if (r < 0)
934 return log_debug_errno(r, "Failed to parse %s=%s: %m", colskey, colsvalue);
935 }
936
937 if (ret_rows)
938 *ret_rows = rows;
939 if (ret_cols)
940 *ret_cols = cols;
941
942 return 0;
943}
944
288a74cc
RC
945/* intended to be used as a SIGWINCH sighandler */
946void columns_lines_cache_reset(int signum) {
947 cached_columns = 0;
948 cached_lines = 0;
949}
950
c6063244
LP
951void reset_terminal_feature_caches(void) {
952 cached_columns = 0;
953 cached_lines = 0;
954
c4fea19a 955 cached_color_mode = _COLOR_INVALID;
c6063244
LP
956 cached_underline_enabled = -1;
957 cached_on_tty = -1;
197dd3a9 958 cached_on_dev_null = -1;
c6063244 959}
288a74cc 960
c6063244 961bool on_tty(void) {
8cd0356e
LP
962
963 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
964 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
965 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
966 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
967 * terminal functionality when outputting stuff, even if the input is piped to us. */
968
c6063244 969 if (cached_on_tty < 0)
8cd0356e
LP
970 cached_on_tty =
971 isatty(STDOUT_FILENO) > 0 &&
972 isatty(STDERR_FILENO) > 0;
288a74cc
RC
973
974 return cached_on_tty;
975}
976
288a74cc 977int getttyname_malloc(int fd, char **ret) {
30222f4b 978 char path[PATH_MAX], *c; /* PATH_MAX is counted *with* the trailing NUL byte */
288a74cc
RC
979 int r;
980
981 assert(fd >= 0);
982 assert(ret);
983
30222f4b
ZJS
984 r = ttyname_r(fd, path, sizeof path); /* positive error */
985 assert(r >= 0);
986 if (r == ERANGE)
987 return -ENAMETOOLONG;
988 if (r > 0)
989 return -r;
288a74cc 990
30222f4b
ZJS
991 c = strdup(skip_dev_prefix(path));
992 if (!c)
993 return -ENOMEM;
288a74cc 994
30222f4b 995 *ret = c;
288a74cc
RC
996 return 0;
997}
998
f171decd
LP
999int getttyname_harder(int fd, char **ret) {
1000 _cleanup_free_ char *s = NULL;
1001 int r;
288a74cc 1002
f171decd
LP
1003 r = getttyname_malloc(fd, &s);
1004 if (r < 0)
1005 return r;
288a74cc 1006
f171decd
LP
1007 if (streq(s, "tty"))
1008 return get_ctty(0, NULL, ret);
288a74cc 1009
f171decd 1010 *ret = TAKE_PTR(s);
288a74cc
RC
1011 return 0;
1012}
1013
1014int get_ctty_devnr(pid_t pid, dev_t *d) {
1015 int r;
1016 _cleanup_free_ char *line = NULL;
1017 const char *p;
1018 unsigned long ttynr;
1019
1020 assert(pid >= 0);
1021
1022 p = procfs_file_alloca(pid, "stat");
1023 r = read_one_line_file(p, &line);
1024 if (r < 0)
1025 return r;
1026
1027 p = strrchr(line, ')');
1028 if (!p)
1029 return -EIO;
1030
1031 p++;
1032
1033 if (sscanf(p, " "
1034 "%*c " /* state */
1035 "%*d " /* ppid */
1036 "%*d " /* pgrp */
1037 "%*d " /* session */
1038 "%lu ", /* ttynr */
1039 &ttynr) != 1)
1040 return -EIO;
1041
d80e2a1e 1042 if (devnum_is_zero(ttynr))
cfeaa44a 1043 return -ENXIO;
288a74cc
RC
1044
1045 if (d)
1046 *d = (dev_t) ttynr;
1047
1048 return 0;
1049}
1050
54b22b26 1051int get_ctty(pid_t pid, dev_t *ret_devnr, char **ret) {
11f3c130
LP
1052 char pty[STRLEN("/dev/pts/") + DECIMAL_STR_MAX(dev_t) + 1];
1053 _cleanup_free_ char *buf = NULL;
1054 const char *fn = NULL, *w;
288a74cc 1055 dev_t devnr;
54b22b26 1056 int r;
288a74cc 1057
54b22b26
LP
1058 r = get_ctty_devnr(pid, &devnr);
1059 if (r < 0)
1060 return r;
288a74cc 1061
11f3c130 1062 r = device_path_make_canonical(S_IFCHR, devnr, &buf);
54b22b26 1063 if (r < 0) {
11f3c130
LP
1064 struct stat st;
1065
54b22b26
LP
1066 if (r != -ENOENT) /* No symlink for this in /dev/char/? */
1067 return r;
288a74cc 1068
11f3c130
LP
1069 /* Maybe this is PTY? PTY devices are not listed in /dev/char/, as they don't follow the
1070 * Linux device model and hence device_path_make_canonical() doesn't work for them. Let's
1071 * assume this is a PTY for a moment, and check if the device node this would then map to in
1072 * /dev/pts/ matches the one we are looking for. This way we don't have to hardcode the major
1073 * number (which is 136 btw), but we still rely on the fact that PTY numbers map directly to
1074 * the minor number of the pty. */
1075 xsprintf(pty, "/dev/pts/%u", minor(devnr));
1076
1077 if (stat(pty, &st) < 0) {
1078 if (errno != ENOENT)
1079 return -errno;
54b22b26 1080
11f3c130
LP
1081 } else if (S_ISCHR(st.st_mode) && devnr == st.st_rdev) /* Bingo! */
1082 fn = pty;
288a74cc 1083
11f3c130
LP
1084 if (!fn) {
1085 /* Doesn't exist, or not a PTY? Probably something similar to the PTYs which have no
1086 * symlink in /dev/char/. Let's return something vaguely useful. */
1087 r = device_path_make_major_minor(S_IFCHR, devnr, &buf);
54b22b26
LP
1088 if (r < 0)
1089 return r;
11f3c130
LP
1090
1091 fn = buf;
288a74cc 1092 }
11f3c130
LP
1093 } else
1094 fn = buf;
288a74cc 1095
11f3c130
LP
1096 w = path_startswith(fn, "/dev/");
1097 if (!w)
1098 return -EINVAL;
54b22b26 1099
11f3c130
LP
1100 if (ret) {
1101 _cleanup_free_ char *b = NULL;
1102
1103 b = strdup(w);
1104 if (!b)
1105 return -ENOMEM;
288a74cc 1106
54b22b26 1107 *ret = TAKE_PTR(b);
11f3c130 1108 }
54b22b26
LP
1109
1110 if (ret_devnr)
1111 *ret_devnr = devnr;
288a74cc
RC
1112
1113 return 0;
1114}
a07c35c3 1115
66cb2fde
LP
1116int ptsname_malloc(int fd, char **ret) {
1117 size_t l = 100;
1118
1119 assert(fd >= 0);
1120 assert(ret);
1121
1122 for (;;) {
1123 char *c;
1124
1125 c = new(char, l);
1126 if (!c)
1127 return -ENOMEM;
1128
1129 if (ptsname_r(fd, c, l) == 0) {
1130 *ret = c;
1131 return 0;
1132 }
1133 if (errno != ERANGE) {
1134 free(c);
1135 return -errno;
1136 }
1137
1138 free(c);
1fd4c4ed
LP
1139
1140 if (l > SIZE_MAX / 2)
1141 return -ENOMEM;
1142
66cb2fde
LP
1143 l *= 2;
1144 }
1145}
1146
ae1d13db 1147int openpt_allocate(int flags, char **ret_slave) {
254d1313 1148 _cleanup_close_ int fd = -EBADF;
ae1d13db
FB
1149 _cleanup_free_ char *p = NULL;
1150 int r;
1151
1152 fd = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1153 if (fd < 0)
1154 return -errno;
1155
1156 if (ret_slave) {
1157 r = ptsname_malloc(fd, &p);
1158 if (r < 0)
1159 return r;
1160
1161 if (!path_startswith(p, "/dev/pts/"))
1162 return -EINVAL;
1163 }
1164
1165 if (unlockpt(fd) < 0)
1166 return -errno;
1167
1168 if (ret_slave)
1169 *ret_slave = TAKE_PTR(p);
1170
1171 return TAKE_FD(fd);
1172}
1173
1174static int ptsname_namespace(int pty, char **ret) {
a07c35c3
LP
1175 int no = -1, r;
1176
1177 /* Like ptsname(), but doesn't assume that the path is
1178 * accessible in the local namespace. */
1179
1180 r = ioctl(pty, TIOCGPTN, &no);
1181 if (r < 0)
1182 return -errno;
1183
1184 if (no < 0)
1185 return -EIO;
1186
1187 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1188 return -ENOMEM;
1189
1190 return 0;
1191}
66cb2fde 1192
ae1d13db 1193int openpt_allocate_in_namespace(pid_t pid, int flags, char **ret_slave) {
254d1313 1194 _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF, fd = -EBADF;
71136404 1195 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
66cb2fde
LP
1196 pid_t child;
1197 int r;
1198
1199 assert(pid > 0);
1200
1201 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1202 if (r < 0)
1203 return r;
1204
1205 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1206 return -errno;
1207
e9ccae31 1208 r = namespace_fork("(sd-openptns)", "(sd-openpt)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL,
1edcb6a9 1209 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
4c253ed1
LP
1210 if (r < 0)
1211 return r;
1212 if (r == 0) {
66cb2fde
LP
1213 pair[0] = safe_close(pair[0]);
1214
ae1d13db
FB
1215 fd = openpt_allocate(flags, NULL);
1216 if (fd < 0)
66cb2fde
LP
1217 _exit(EXIT_FAILURE);
1218
ae1d13db 1219 if (send_one_fd(pair[1], fd, 0) < 0)
66cb2fde
LP
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-openptns)", child, 0);
66cb2fde
LP
1228 if (r < 0)
1229 return r;
2e87a1fd 1230 if (r != EXIT_SUCCESS)
66cb2fde
LP
1231 return -EIO;
1232
ae1d13db
FB
1233 fd = receive_one_fd(pair[0], 0);
1234 if (fd < 0)
1235 return fd;
1236
1237 if (ret_slave) {
1238 r = ptsname_namespace(fd, ret_slave);
1239 if (r < 0)
1240 return r;
1241 }
1242
1243 return TAKE_FD(fd);
66cb2fde 1244}
40e1f4ea
LP
1245
1246int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
254d1313 1247 _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF;
71136404 1248 _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
40e1f4ea
LP
1249 pid_t child;
1250 int r;
1251
1252 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1253 if (r < 0)
1254 return r;
1255
1256 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1257 return -errno;
1258
e9ccae31 1259 r = namespace_fork("(sd-terminalns)", "(sd-terminal)", NULL, 0, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL,
1edcb6a9 1260 pidnsfd, mntnsfd, -1, usernsfd, rootfd, &child);
4c253ed1
LP
1261 if (r < 0)
1262 return r;
1263 if (r == 0) {
40e1f4ea
LP
1264 int master;
1265
1266 pair[0] = safe_close(pair[0]);
1267
40e1f4ea
LP
1268 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1269 if (master < 0)
1270 _exit(EXIT_FAILURE);
1271
1272 if (send_one_fd(pair[1], master, 0) < 0)
1273 _exit(EXIT_FAILURE);
1274
1275 _exit(EXIT_SUCCESS);
1276 }
1277
1278 pair[1] = safe_close(pair[1]);
1279
1edcb6a9 1280 r = wait_for_terminate_and_check("(sd-terminalns)", child, 0);
40e1f4ea
LP
1281 if (r < 0)
1282 return r;
2e87a1fd 1283 if (r != EXIT_SUCCESS)
40e1f4ea
LP
1284 return -EIO;
1285
1286 return receive_one_fd(pair[0], 0);
1287}
40c9fe4c 1288
197dd3a9
DDM
1289static bool on_dev_null(void) {
1290 struct stat dst, ost, est;
1291
1292 if (cached_on_dev_null >= 0)
1293 return cached_on_dev_null;
1294
1295 if (stat("/dev/null", &dst) < 0 || fstat(STDOUT_FILENO, &ost) < 0 || fstat(STDERR_FILENO, &est) < 0)
1296 cached_on_dev_null = false;
1297 else
1298 cached_on_dev_null = stat_inode_same(&dst, &ost) && stat_inode_same(&dst, &est);
1299
1300 return cached_on_dev_null;
1301}
1302
158fbf76 1303static bool getenv_terminal_is_dumb(void) {
ac96418b
LP
1304 const char *e;
1305
ac96418b
LP
1306 e = getenv("TERM");
1307 if (!e)
1308 return true;
1309
1310 return streq(e, "dumb");
1311}
1312
158fbf76 1313bool terminal_is_dumb(void) {
197dd3a9 1314 if (!on_tty() && !on_dev_null())
158fbf76
ZJS
1315 return true;
1316
1317 return getenv_terminal_is_dumb();
1318}
1319
c4fea19a
MGR
1320static ColorMode parse_systemd_colors(void) {
1321 const char *e;
1322 int r;
ae5b3958 1323
c4fea19a
MGR
1324 e = getenv("SYSTEMD_COLORS");
1325 if (!e)
1326 return _COLOR_INVALID;
1327 if (streq(e, "16"))
1328 return COLOR_16;
1329 if (streq(e, "256"))
1330 return COLOR_256;
1331 r = parse_boolean(e);
1332 if (r >= 0)
1333 return r > 0 ? COLOR_ON : COLOR_OFF;
1334 return _COLOR_INVALID;
1335}
c484315b 1336
c4fea19a
MGR
1337ColorMode get_color_mode(void) {
1338
1339 /* Returns the mode used to choose output colors. The possible modes are COLOR_OFF for no colors,
1340 * COLOR_16 for only the base 16 ANSI colors, COLOR_256 for more colors and COLOR_ON for unrestricted
1341 * color output. For that we check $SYSTEMD_COLORS first (which is the explicit way to
1342 * 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
1343 * 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
1344 * check whether we are connected to a TTY, because we don't keep /dev/console open continuously due to fear
1345 * of SAK, and hence things are a bit weird. */
1346 ColorMode m;
1347
1348 if (cached_color_mode < 0) {
1349 m = parse_systemd_colors();
1350 if (m >= 0)
1351 cached_color_mode = m;
c484315b
ZJS
1352 else if (getenv("NO_COLOR"))
1353 /* We only check for the presence of the variable; value is ignored. */
c4fea19a 1354 cached_color_mode = COLOR_OFF;
c484315b 1355
34c2d32c 1356 else if (getpid_cached() == 1) {
c4fea19a 1357 /* PID1 outputs to the console without holding it open all the time.
ddbf9605
LP
1358 *
1359 * Note that the Linux console can only display 16 colors. We still enable 256 color
1360 * mode even for PID1 output though (which typically goes to the Linux console),
1361 * since the Linux console is able to parse the 256 color sequences and automatically
1362 * map them to the closest color in the 16 color palette (since kernel 3.16). Doing
1363 * 256 colors is nice for people who invoke systemd in a container or via a serial
1364 * link or such, and use a true 256 color terminal to do so. */
34c2d32c
ZJS
1365 if (getenv_terminal_is_dumb())
1366 cached_color_mode = COLOR_OFF;
1367 } else {
1368 if (terminal_is_dumb())
1369 cached_color_mode = COLOR_OFF;
1370 }
1371
1372 if (cached_color_mode < 0) {
1373 /* We failed to figure out any reason to *disable* colors.
1374 * Let's see how many colors we shall use. */
1375 if (STRPTR_IN_SET(getenv("COLORTERM"),
1376 "truecolor",
1377 "24bit"))
1378 cached_color_mode = COLOR_24BIT;
1379 else
1380 cached_color_mode = COLOR_256;
1381 }
40c9fe4c
JS
1382 }
1383
c4fea19a
MGR
1384 return cached_color_mode;
1385}
1386
c2b32159
LP
1387bool dev_console_colors_enabled(void) {
1388 _cleanup_free_ char *s = NULL;
c4fea19a 1389 ColorMode m;
c2b32159
LP
1390
1391 /* Returns true if we assume that color is supported on /dev/console.
1392 *
1393 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
f95dbcc2
ZJS
1394 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1395 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
c2b32159
LP
1396 * colors_enabled() operates. */
1397
c4fea19a
MGR
1398 m = parse_systemd_colors();
1399 if (m >= 0)
1400 return m;
c2b32159 1401
c484315b
ZJS
1402 if (getenv("NO_COLOR"))
1403 return false;
1404
c2b32159
LP
1405 if (getenv_for_pid(1, "TERM", &s) <= 0)
1406 (void) proc_cmdline_get_key("TERM", 0, &s);
1407
1408 return !streq_ptr(s, "dumb");
1409}
1410
526664f6 1411bool underline_enabled(void) {
526664f6 1412
c6063244 1413 if (cached_underline_enabled < 0) {
526664f6
LP
1414
1415 /* The Linux console doesn't support underlining, turn it off, but only there. */
1416
c6063244
LP
1417 if (colors_enabled())
1418 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
526664f6 1419 else
c6063244 1420 cached_underline_enabled = false;
526664f6
LP
1421 }
1422
c6063244 1423 return cached_underline_enabled;
526664f6
LP
1424}
1425
c83f349c
LP
1426int vt_default_utf8(void) {
1427 _cleanup_free_ char *b = NULL;
1428 int r;
1429
1430 /* Read the default VT UTF8 setting from the kernel */
1431
1432 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1433 if (r < 0)
1434 return r;
1435
1436 return parse_boolean(b);
1437}
1438
1439int vt_reset_keyboard(int fd) {
15bba613 1440 int kb;
c83f349c
LP
1441
1442 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1443 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1444
7c248223 1445 return RET_NERRNO(ioctl(fd, KDSKBMODE, kb));
c83f349c 1446}
6179ede1
FB
1447
1448int vt_restore(int fd) {
1449 static const struct vt_mode mode = {
1450 .mode = VT_AUTO,
1451 };
1452 int r, q = 0;
1453
e60a4a3c
LP
1454 if (isatty(fd) < 1)
1455 return log_debug_errno(errno, "Asked to restore the VT for an fd that does not refer to a terminal: %m");
1456
1802d5f2 1457 if (ioctl(fd, KDSETMODE, KD_TEXT) < 0)
6179ede1
FB
1458 q = log_debug_errno(errno, "Failed to set VT in text mode, ignoring: %m");
1459
1460 r = vt_reset_keyboard(fd);
1461 if (r < 0) {
1462 log_debug_errno(r, "Failed to reset keyboard mode, ignoring: %m");
1463 if (q >= 0)
1464 q = r;
1465 }
1466
1802d5f2 1467 if (ioctl(fd, VT_SETMODE, &mode) < 0) {
6179ede1
FB
1468 log_debug_errno(errno, "Failed to set VT_AUTO mode, ignoring: %m");
1469 if (q >= 0)
1470 q = -errno;
1471 }
1472
f5fbe71d 1473 r = fchmod_and_chown(fd, TTY_MODE, 0, GID_INVALID);
6179ede1 1474 if (r < 0) {
1802d5f2 1475 log_debug_errno(r, "Failed to chmod()/chown() VT, ignoring: %m");
6179ede1 1476 if (q >= 0)
1802d5f2 1477 q = r;
6179ede1
FB
1478 }
1479
1480 return q;
1481}
27dafac9
FB
1482
1483int vt_release(int fd, bool restore) {
1484 assert(fd >= 0);
1485
1486 /* This function releases the VT by acknowledging the VT-switch signal
1487 * sent by the kernel and optionally reset the VT in text and auto
1488 * VT-switching modes. */
1489
e60a4a3c
LP
1490 if (isatty(fd) < 1)
1491 return log_debug_errno(errno, "Asked to release the VT for an fd that does not refer to a terminal: %m");
1492
27dafac9
FB
1493 if (ioctl(fd, VT_RELDISP, 1) < 0)
1494 return -errno;
1495
1496 if (restore)
1497 return vt_restore(fd);
1498
1499 return 0;
1500}
37b8d2f6
ZJS
1501
1502void get_log_colors(int priority, const char **on, const char **off, const char **highlight) {
1503 /* Note that this will initialize output variables only when there's something to output.
5e2b0e1c 1504 * The caller must pre-initialize to "" or NULL as appropriate. */
37b8d2f6
ZJS
1505
1506 if (priority <= LOG_ERR) {
1507 if (on)
25e4608b 1508 *on = ansi_highlight_red();
37b8d2f6 1509 if (off)
bb146d23 1510 *off = ansi_normal();
37b8d2f6 1511 if (highlight)
bb146d23 1512 *highlight = ansi_highlight();
37b8d2f6 1513
0d0464d3
ZJS
1514 } else if (priority <= LOG_WARNING) {
1515 if (on)
25e4608b 1516 *on = ansi_highlight_yellow();
0d0464d3 1517 if (off)
bb146d23 1518 *off = ansi_normal();
0d0464d3 1519 if (highlight)
bb146d23 1520 *highlight = ansi_highlight();
0d0464d3 1521
37b8d2f6
ZJS
1522 } else if (priority <= LOG_NOTICE) {
1523 if (on)
bb146d23 1524 *on = ansi_highlight();
37b8d2f6 1525 if (off)
bb146d23 1526 *off = ansi_normal();
37b8d2f6 1527 if (highlight)
25e4608b 1528 *highlight = ansi_highlight_red();
37b8d2f6
ZJS
1529
1530 } else if (priority >= LOG_DEBUG) {
1531 if (on)
25e4608b 1532 *on = ansi_grey();
37b8d2f6 1533 if (off)
bb146d23 1534 *off = ansi_normal();
37b8d2f6 1535 if (highlight)
25e4608b 1536 *highlight = ansi_highlight_red();
37b8d2f6
ZJS
1537 }
1538}
fc7eb132
OJ
1539
1540int set_terminal_cursor_position(int fd, unsigned int row, unsigned int column) {
1541 int r;
1542 char cursor_position[STRLEN("\x1B[") + DECIMAL_STR_MAX(int) * 2 + STRLEN(";H") + 1];
1543
1544 assert(fd >= 0);
1545
1546 xsprintf(cursor_position, "\x1B[%u;%uH", row, column);
1547
e22c60a9 1548 r = loop_write(fd, cursor_position, SIZE_MAX);
fc7eb132
OJ
1549 if (r < 0)
1550 return log_warning_errno(r, "Failed to set cursor position, ignoring: %m");
1551
1552 return 0;
1553}