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