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