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