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