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