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