]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
terminal-util: extra safety checks when parsing $COLUMNS or $LINES (#10314)
[thirdparty/systemd.git] / src / basic / terminal-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 <string.h>
15 #include <sys/inotify.h>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
18 #include <sys/sysmacros.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/utsname.h>
22 #include <termios.h>
23 #include <unistd.h>
24
25 #include "alloc-util.h"
26 #include "copy.h"
27 #include "def.h"
28 #include "env-util.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "io-util.h"
33 #include "log.h"
34 #include "macro.h"
35 #include "pager.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 "string-util.h"
43 #include "strv.h"
44 #include "terminal-util.h"
45 #include "time-util.h"
46 #include "util.h"
47
48 static volatile unsigned cached_columns = 0;
49 static volatile unsigned cached_lines = 0;
50
51 static volatile int cached_on_tty = -1;
52 static volatile int cached_colors_enabled = -1;
53 static volatile int cached_underline_enabled = -1;
54
55 int chvt(int vt) {
56 _cleanup_close_ int fd;
57
58 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
59 * if that's configured. */
60
61 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
62 if (fd < 0)
63 return -errno;
64
65 if (vt <= 0) {
66 int tiocl[2] = {
67 TIOCL_GETKMSGREDIRECT,
68 0
69 };
70
71 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
72 return -errno;
73
74 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
75 }
76
77 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
78 return -errno;
79
80 return 0;
81 }
82
83 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
84 struct termios old_termios, new_termios;
85 char c, line[LINE_MAX];
86
87 assert(f);
88 assert(ret);
89
90 if (tcgetattr(fileno(f), &old_termios) >= 0) {
91 new_termios = old_termios;
92
93 new_termios.c_lflag &= ~ICANON;
94 new_termios.c_cc[VMIN] = 1;
95 new_termios.c_cc[VTIME] = 0;
96
97 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
98 size_t k;
99
100 if (t != USEC_INFINITY) {
101 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
102 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
103 return -ETIMEDOUT;
104 }
105 }
106
107 k = fread(&c, 1, 1, f);
108
109 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
110
111 if (k <= 0)
112 return -EIO;
113
114 if (need_nl)
115 *need_nl = c != '\n';
116
117 *ret = c;
118 return 0;
119 }
120 }
121
122 if (t != USEC_INFINITY) {
123 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
124 return -ETIMEDOUT;
125 }
126
127 errno = 0;
128 if (!fgets(line, sizeof(line), f))
129 return errno > 0 ? -errno : -EIO;
130
131 truncate_nl(line);
132
133 if (strlen(line) != 1)
134 return -EBADMSG;
135
136 if (need_nl)
137 *need_nl = false;
138
139 *ret = line[0];
140 return 0;
141 }
142
143 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
144
145 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
146 int r;
147
148 assert(ret);
149 assert(replies);
150 assert(fmt);
151
152 for (;;) {
153 va_list ap;
154 char c;
155 bool need_nl = true;
156
157 if (colors_enabled())
158 fputs(ANSI_HIGHLIGHT, stdout);
159
160 putchar('\r');
161
162 va_start(ap, fmt);
163 vprintf(fmt, ap);
164 va_end(ap);
165
166 if (colors_enabled())
167 fputs(ANSI_NORMAL, stdout);
168
169 fflush(stdout);
170
171 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
172 if (r < 0) {
173
174 if (r == -ETIMEDOUT)
175 continue;
176
177 if (r == -EBADMSG) {
178 puts("Bad input, please try again.");
179 continue;
180 }
181
182 putchar('\n');
183 return r;
184 }
185
186 if (need_nl)
187 putchar('\n');
188
189 if (strchr(replies, c)) {
190 *ret = c;
191 return 0;
192 }
193
194 puts("Read unexpected character, please try again.");
195 }
196 }
197
198 int ask_string(char **ret, const char *text, ...) {
199 assert(ret);
200 assert(text);
201
202 for (;;) {
203 char line[LINE_MAX];
204 va_list ap;
205
206 if (colors_enabled())
207 fputs(ANSI_HIGHLIGHT, stdout);
208
209 va_start(ap, text);
210 vprintf(text, ap);
211 va_end(ap);
212
213 if (colors_enabled())
214 fputs(ANSI_NORMAL, stdout);
215
216 fflush(stdout);
217
218 errno = 0;
219 if (!fgets(line, sizeof(line), stdin))
220 return errno > 0 ? -errno : -EIO;
221
222 if (!endswith(line, "\n"))
223 putchar('\n');
224 else {
225 char *s;
226
227 if (isempty(line))
228 continue;
229
230 truncate_nl(line);
231 s = strdup(line);
232 if (!s)
233 return -ENOMEM;
234
235 *ret = s;
236 return 0;
237 }
238 }
239 }
240
241 int reset_terminal_fd(int fd, bool switch_to_text) {
242 struct termios termios;
243 int r = 0;
244
245 /* Set terminal to some sane defaults */
246
247 assert(fd >= 0);
248
249 /* We leave locked terminal attributes untouched, so that
250 * Plymouth may set whatever it wants to set, and we don't
251 * interfere with that. */
252
253 /* Disable exclusive mode, just in case */
254 (void) ioctl(fd, TIOCNXCL);
255
256 /* Switch to text mode */
257 if (switch_to_text)
258 (void) ioctl(fd, KDSETMODE, KD_TEXT);
259
260 /* Set default keyboard mode */
261 (void) vt_reset_keyboard(fd);
262
263 if (tcgetattr(fd, &termios) < 0) {
264 r = -errno;
265 goto finish;
266 }
267
268 /* We only reset the stuff that matters to the software. How
269 * hardware is set up we don't touch assuming that somebody
270 * else will do that for us */
271
272 termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
273 termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
274 termios.c_oflag |= ONLCR;
275 termios.c_cflag |= CREAD;
276 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
277
278 termios.c_cc[VINTR] = 03; /* ^C */
279 termios.c_cc[VQUIT] = 034; /* ^\ */
280 termios.c_cc[VERASE] = 0177;
281 termios.c_cc[VKILL] = 025; /* ^X */
282 termios.c_cc[VEOF] = 04; /* ^D */
283 termios.c_cc[VSTART] = 021; /* ^Q */
284 termios.c_cc[VSTOP] = 023; /* ^S */
285 termios.c_cc[VSUSP] = 032; /* ^Z */
286 termios.c_cc[VLNEXT] = 026; /* ^V */
287 termios.c_cc[VWERASE] = 027; /* ^W */
288 termios.c_cc[VREPRINT] = 022; /* ^R */
289 termios.c_cc[VEOL] = 0;
290 termios.c_cc[VEOL2] = 0;
291
292 termios.c_cc[VTIME] = 0;
293 termios.c_cc[VMIN] = 1;
294
295 if (tcsetattr(fd, TCSANOW, &termios) < 0)
296 r = -errno;
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 = -1;
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 unsigned c = 0;
321 int fd;
322
323 /*
324 * If a TTY is in the process of being closed opening it might
325 * cause EIO. This is horribly awful, but unlikely to be
326 * changed in the kernel. Hence we work around this problem by
327 * retrying a couple of times.
328 *
329 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
330 */
331
332 if (mode & O_CREAT)
333 return -EINVAL;
334
335 for (;;) {
336 fd = open(name, mode, 0);
337 if (fd >= 0)
338 break;
339
340 if (errno != EIO)
341 return -errno;
342
343 /* Max 1s in total */
344 if (c >= 20)
345 return -errno;
346
347 usleep(50 * USEC_PER_MSEC);
348 c++;
349 }
350
351 if (isatty(fd) <= 0) {
352 safe_close(fd);
353 return -ENOTTY;
354 }
355
356 return fd;
357 }
358
359 int acquire_terminal(
360 const char *name,
361 AcquireTerminalFlags flags,
362 usec_t timeout) {
363
364 _cleanup_close_ int notify = -1, fd = -1;
365 usec_t ts = USEC_INFINITY;
366 int r, wd = -1;
367
368 assert(name);
369 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
370
371 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
372 * acquire it, so that we don't lose any event.
373 *
374 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
375 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
376 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
377 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
378 * probably should not do anyway.) */
379
380 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
381 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
382 if (notify < 0)
383 return -errno;
384
385 wd = inotify_add_watch(notify, name, IN_CLOSE);
386 if (wd < 0)
387 return -errno;
388
389 if (timeout != USEC_INFINITY)
390 ts = now(CLOCK_MONOTONIC);
391 }
392
393 for (;;) {
394 struct sigaction sa_old, sa_new = {
395 .sa_handler = SIG_IGN,
396 .sa_flags = SA_RESTART,
397 };
398
399 if (notify >= 0) {
400 r = flush_fd(notify);
401 if (r < 0)
402 return r;
403 }
404
405 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
406 * to figure out if we successfully became the controlling process of the tty */
407 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
408 if (fd < 0)
409 return fd;
410
411 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
412 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
413
414 /* First, try to get the tty */
415 r = ioctl(fd, TIOCSCTTY,
416 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
417
418 /* Reset signal handler to old value */
419 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
420
421 /* Success? Exit the loop now! */
422 if (r >= 0)
423 break;
424
425 /* Any failure besides -EPERM? Fail, regardless of the mode. */
426 if (r != -EPERM)
427 return r;
428
429 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
430 * into a success. Note that EPERM is also returned if we
431 * already are the owner of the TTY. */
432 break;
433
434 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
435 return r;
436
437 assert(notify >= 0);
438 assert(wd >= 0);
439
440 for (;;) {
441 union inotify_event_buffer buffer;
442 struct inotify_event *e;
443 ssize_t l;
444
445 if (timeout != USEC_INFINITY) {
446 usec_t n;
447
448 assert(ts != USEC_INFINITY);
449
450 n = now(CLOCK_MONOTONIC);
451 if (ts + timeout < n)
452 return -ETIMEDOUT;
453
454 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
455 if (r < 0)
456 return r;
457 if (r == 0)
458 return -ETIMEDOUT;
459 }
460
461 l = read(notify, &buffer, sizeof(buffer));
462 if (l < 0) {
463 if (IN_SET(errno, EINTR, EAGAIN))
464 continue;
465
466 return -errno;
467 }
468
469 FOREACH_INOTIFY_EVENT(e, buffer, l) {
470 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
471 break;
472
473 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
474 return -EIO;
475 }
476
477 break;
478 }
479
480 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
481 * we do this after sleeping, so that we don't enter an endless loop. */
482 fd = safe_close(fd);
483 }
484
485 return TAKE_FD(fd);
486 }
487
488 int release_terminal(void) {
489 static const struct sigaction sa_new = {
490 .sa_handler = SIG_IGN,
491 .sa_flags = SA_RESTART,
492 };
493
494 _cleanup_close_ int fd = -1;
495 struct sigaction sa_old;
496 int r;
497
498 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
499 if (fd < 0)
500 return -errno;
501
502 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
503 * by our own TIOCNOTTY */
504 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
505
506 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
507
508 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
509
510 return r;
511 }
512
513 int terminal_vhangup_fd(int fd) {
514 assert(fd >= 0);
515
516 if (ioctl(fd, TIOCVHANGUP) < 0)
517 return -errno;
518
519 return 0;
520 }
521
522 int terminal_vhangup(const char *name) {
523 _cleanup_close_ int fd;
524
525 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
526 if (fd < 0)
527 return fd;
528
529 return terminal_vhangup_fd(fd);
530 }
531
532 int vt_disallocate(const char *name) {
533 _cleanup_close_ int fd = -1;
534 const char *e, *n;
535 unsigned u;
536 int r;
537
538 /* Deallocate the VT if possible. If not possible
539 * (i.e. because it is the active one), at least clear it
540 * entirely (including the scrollback buffer) */
541
542 e = path_startswith(name, "/dev/");
543 if (!e)
544 return -EINVAL;
545
546 if (!tty_is_vc(name)) {
547 /* So this is not a VT. I guess we cannot deallocate
548 * it then. But let's at least clear the screen */
549
550 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
551 if (fd < 0)
552 return fd;
553
554 loop_write(fd,
555 "\033[r" /* clear scrolling region */
556 "\033[H" /* move home */
557 "\033[2J", /* clear screen */
558 10, false);
559 return 0;
560 }
561
562 n = startswith(e, "tty");
563 if (!n)
564 return -EINVAL;
565
566 r = safe_atou(n, &u);
567 if (r < 0)
568 return r;
569
570 if (u <= 0)
571 return -EINVAL;
572
573 /* Try to deallocate */
574 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
575 if (fd < 0)
576 return fd;
577
578 r = ioctl(fd, VT_DISALLOCATE, u);
579 fd = safe_close(fd);
580
581 if (r >= 0)
582 return 0;
583
584 if (errno != EBUSY)
585 return -errno;
586
587 /* Couldn't deallocate, so let's clear it fully with
588 * scrollback */
589 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
590 if (fd < 0)
591 return fd;
592
593 loop_write(fd,
594 "\033[r" /* clear scrolling region */
595 "\033[H" /* move home */
596 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
597 10, false);
598 return 0;
599 }
600
601 int make_console_stdio(void) {
602 int fd, r;
603
604 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
605
606 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
607 if (fd < 0)
608 return log_error_errno(fd, "Failed to acquire terminal: %m");
609
610 r = reset_terminal_fd(fd, true);
611 if (r < 0)
612 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
613
614 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
615 if (r < 0)
616 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
617
618 reset_terminal_feature_caches();
619
620 return 0;
621 }
622
623 bool tty_is_vc(const char *tty) {
624 assert(tty);
625
626 return vtnr_from_tty(tty) >= 0;
627 }
628
629 bool tty_is_console(const char *tty) {
630 assert(tty);
631
632 return streq(skip_dev_prefix(tty), "console");
633 }
634
635 int vtnr_from_tty(const char *tty) {
636 int i, r;
637
638 assert(tty);
639
640 tty = skip_dev_prefix(tty);
641
642 if (!startswith(tty, "tty") )
643 return -EINVAL;
644
645 if (tty[3] < '0' || tty[3] > '9')
646 return -EINVAL;
647
648 r = safe_atoi(tty+3, &i);
649 if (r < 0)
650 return r;
651
652 if (i < 0 || i > 63)
653 return -EINVAL;
654
655 return i;
656 }
657
658 int resolve_dev_console(char **ret) {
659 _cleanup_free_ char *active = NULL;
660 char *tty;
661 int r;
662
663 assert(ret);
664
665 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
666 * sign for container setups) */
667
668 if (path_is_read_only_fs("/sys") > 0)
669 return -ENOMEDIUM;
670
671 r = read_one_line_file("/sys/class/tty/console/active", &active);
672 if (r < 0)
673 return r;
674
675 /* If multiple log outputs are configured the last one is what /dev/console points to */
676 tty = strrchr(active, ' ');
677 if (tty)
678 tty++;
679 else
680 tty = active;
681
682 if (streq(tty, "tty0")) {
683 active = mfree(active);
684
685 /* Get the active VC (e.g. tty1) */
686 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
687 if (r < 0)
688 return r;
689
690 tty = active;
691 }
692
693 if (tty == active)
694 *ret = TAKE_PTR(active);
695 else {
696 char *tmp;
697
698 tmp = strdup(tty);
699 if (!tmp)
700 return -ENOMEM;
701
702 *ret = tmp;
703 }
704
705 return 0;
706 }
707
708 int get_kernel_consoles(char ***ret) {
709 _cleanup_strv_free_ char **l = NULL;
710 _cleanup_free_ char *line = NULL;
711 const char *p;
712 int r;
713
714 assert(ret);
715
716 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
717 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
718 if (path_is_read_only_fs("/sys") > 0)
719 goto fallback;
720
721 r = read_one_line_file("/sys/class/tty/console/active", &line);
722 if (r < 0)
723 return r;
724
725 p = line;
726 for (;;) {
727 _cleanup_free_ char *tty = NULL;
728 char *path;
729
730 r = extract_first_word(&p, &tty, NULL, 0);
731 if (r < 0)
732 return r;
733 if (r == 0)
734 break;
735
736 if (streq(tty, "tty0")) {
737 tty = mfree(tty);
738 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
739 if (r < 0)
740 return r;
741 }
742
743 path = strappend("/dev/", tty);
744 if (!path)
745 return -ENOMEM;
746
747 if (access(path, F_OK) < 0) {
748 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
749 free(path);
750 continue;
751 }
752
753 r = strv_consume(&l, path);
754 if (r < 0)
755 return r;
756 }
757
758 if (strv_isempty(l)) {
759 log_debug("No devices found for system console");
760 goto fallback;
761 }
762
763 *ret = TAKE_PTR(l);
764
765 return 0;
766
767 fallback:
768 r = strv_extend(&l, "/dev/console");
769 if (r < 0)
770 return r;
771
772 *ret = TAKE_PTR(l);
773
774 return 0;
775 }
776
777 bool tty_is_vc_resolve(const char *tty) {
778 _cleanup_free_ char *resolved = NULL;
779
780 assert(tty);
781
782 tty = skip_dev_prefix(tty);
783
784 if (streq(tty, "console")) {
785 if (resolve_dev_console(&resolved) < 0)
786 return false;
787
788 tty = resolved;
789 }
790
791 return tty_is_vc(tty);
792 }
793
794 const char *default_term_for_tty(const char *tty) {
795 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
796 }
797
798 int fd_columns(int fd) {
799 struct winsize ws = {};
800
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
810 unsigned columns(void) {
811 const char *e;
812 int c;
813
814 if (cached_columns > 0)
815 return cached_columns;
816
817 c = 0;
818 e = getenv("COLUMNS");
819 if (e)
820 (void) safe_atoi(e, &c);
821
822 if (c <= 0 || c > USHRT_MAX) {
823 c = fd_columns(STDOUT_FILENO);
824 if (c <= 0)
825 c = 80;
826 }
827
828 cached_columns = c;
829 return cached_columns;
830 }
831
832 int fd_lines(int fd) {
833 struct winsize ws = {};
834
835 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
836 return -errno;
837
838 if (ws.ws_row <= 0)
839 return -EIO;
840
841 return ws.ws_row;
842 }
843
844 unsigned lines(void) {
845 const char *e;
846 int l;
847
848 if (cached_lines > 0)
849 return cached_lines;
850
851 l = 0;
852 e = getenv("LINES");
853 if (e)
854 (void) safe_atoi(e, &l);
855
856 if (l <= 0 || l > USHRT_MAX) {
857 l = fd_lines(STDOUT_FILENO);
858 if (l <= 0)
859 l = 24;
860 }
861
862 cached_lines = l;
863 return cached_lines;
864 }
865
866 /* intended to be used as a SIGWINCH sighandler */
867 void columns_lines_cache_reset(int signum) {
868 cached_columns = 0;
869 cached_lines = 0;
870 }
871
872 void reset_terminal_feature_caches(void) {
873 cached_columns = 0;
874 cached_lines = 0;
875
876 cached_colors_enabled = -1;
877 cached_underline_enabled = -1;
878 cached_on_tty = -1;
879 }
880
881 bool on_tty(void) {
882
883 /* We check both stdout and stderr, so that situations where pipes on the shell are used are reliably
884 * recognized, regardless if only the output or the errors are piped to some place. Since on_tty() is generally
885 * used to default to a safer, non-interactive, non-color mode of operation it's probably good to be defensive
886 * here, and check for both. Note that we don't check for STDIN_FILENO, because it should fine to use fancy
887 * terminal functionality when outputting stuff, even if the input is piped to us. */
888
889 if (cached_on_tty < 0)
890 cached_on_tty =
891 isatty(STDOUT_FILENO) > 0 &&
892 isatty(STDERR_FILENO) > 0;
893
894 return cached_on_tty;
895 }
896
897 int getttyname_malloc(int fd, char **ret) {
898 size_t l = 100;
899 int r;
900
901 assert(fd >= 0);
902 assert(ret);
903
904 for (;;) {
905 char path[l];
906
907 r = ttyname_r(fd, path, sizeof(path));
908 if (r == 0) {
909 char *c;
910
911 c = strdup(skip_dev_prefix(path));
912 if (!c)
913 return -ENOMEM;
914
915 *ret = c;
916 return 0;
917 }
918
919 if (r != ERANGE)
920 return -r;
921
922 l *= 2;
923 }
924
925 return 0;
926 }
927
928 int getttyname_harder(int fd, char **r) {
929 int k;
930 char *s = NULL;
931
932 k = getttyname_malloc(fd, &s);
933 if (k < 0)
934 return k;
935
936 if (streq(s, "tty")) {
937 free(s);
938 return get_ctty(0, NULL, r);
939 }
940
941 *r = s;
942 return 0;
943 }
944
945 int get_ctty_devnr(pid_t pid, dev_t *d) {
946 int r;
947 _cleanup_free_ char *line = NULL;
948 const char *p;
949 unsigned long ttynr;
950
951 assert(pid >= 0);
952
953 p = procfs_file_alloca(pid, "stat");
954 r = read_one_line_file(p, &line);
955 if (r < 0)
956 return r;
957
958 p = strrchr(line, ')');
959 if (!p)
960 return -EIO;
961
962 p++;
963
964 if (sscanf(p, " "
965 "%*c " /* state */
966 "%*d " /* ppid */
967 "%*d " /* pgrp */
968 "%*d " /* session */
969 "%lu ", /* ttynr */
970 &ttynr) != 1)
971 return -EIO;
972
973 if (major(ttynr) == 0 && minor(ttynr) == 0)
974 return -ENXIO;
975
976 if (d)
977 *d = (dev_t) ttynr;
978
979 return 0;
980 }
981
982 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
983 char fn[STRLEN("/dev/char/") + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
984 _cleanup_free_ char *s = NULL;
985 const char *p;
986 dev_t devnr;
987 int k;
988
989 assert(r);
990
991 k = get_ctty_devnr(pid, &devnr);
992 if (k < 0)
993 return k;
994
995 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
996
997 k = readlink_malloc(fn, &s);
998 if (k < 0) {
999
1000 if (k != -ENOENT)
1001 return k;
1002
1003 /* This is an ugly hack */
1004 if (major(devnr) == 136) {
1005 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
1006 return -ENOMEM;
1007 } else {
1008 /* Probably something like the ptys which have no
1009 * symlink in /dev/char. Let's return something
1010 * vaguely useful. */
1011
1012 b = strdup(fn + 5);
1013 if (!b)
1014 return -ENOMEM;
1015 }
1016 } else {
1017 if (startswith(s, "/dev/"))
1018 p = s + 5;
1019 else if (startswith(s, "../"))
1020 p = s + 3;
1021 else
1022 p = s;
1023
1024 b = strdup(p);
1025 if (!b)
1026 return -ENOMEM;
1027 }
1028
1029 *r = b;
1030 if (_devnr)
1031 *_devnr = devnr;
1032
1033 return 0;
1034 }
1035
1036 int ptsname_malloc(int fd, char **ret) {
1037 size_t l = 100;
1038
1039 assert(fd >= 0);
1040 assert(ret);
1041
1042 for (;;) {
1043 char *c;
1044
1045 c = new(char, l);
1046 if (!c)
1047 return -ENOMEM;
1048
1049 if (ptsname_r(fd, c, l) == 0) {
1050 *ret = c;
1051 return 0;
1052 }
1053 if (errno != ERANGE) {
1054 free(c);
1055 return -errno;
1056 }
1057
1058 free(c);
1059 l *= 2;
1060 }
1061 }
1062
1063 int ptsname_namespace(int pty, char **ret) {
1064 int no = -1, r;
1065
1066 /* Like ptsname(), but doesn't assume that the path is
1067 * accessible in the local namespace. */
1068
1069 r = ioctl(pty, TIOCGPTN, &no);
1070 if (r < 0)
1071 return -errno;
1072
1073 if (no < 0)
1074 return -EIO;
1075
1076 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1077 return -ENOMEM;
1078
1079 return 0;
1080 }
1081
1082 int openpt_in_namespace(pid_t pid, int flags) {
1083 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1084 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1085 pid_t child;
1086 int r;
1087
1088 assert(pid > 0);
1089
1090 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1091 if (r < 0)
1092 return r;
1093
1094 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1095 return -errno;
1096
1097 r = safe_fork("(sd-openpt)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1098 if (r < 0)
1099 return r;
1100 if (r == 0) {
1101 int master;
1102
1103 pair[0] = safe_close(pair[0]);
1104
1105 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1106 if (r < 0)
1107 _exit(EXIT_FAILURE);
1108
1109 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1110 if (master < 0)
1111 _exit(EXIT_FAILURE);
1112
1113 if (unlockpt(master) < 0)
1114 _exit(EXIT_FAILURE);
1115
1116 if (send_one_fd(pair[1], master, 0) < 0)
1117 _exit(EXIT_FAILURE);
1118
1119 _exit(EXIT_SUCCESS);
1120 }
1121
1122 pair[1] = safe_close(pair[1]);
1123
1124 r = wait_for_terminate_and_check("(sd-openpt)", child, 0);
1125 if (r < 0)
1126 return r;
1127 if (r != EXIT_SUCCESS)
1128 return -EIO;
1129
1130 return receive_one_fd(pair[0], 0);
1131 }
1132
1133 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1134 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1135 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1136 pid_t child;
1137 int r;
1138
1139 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1140 if (r < 0)
1141 return r;
1142
1143 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1144 return -errno;
1145
1146 r = safe_fork("(sd-terminal)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1147 if (r < 0)
1148 return r;
1149 if (r == 0) {
1150 int master;
1151
1152 pair[0] = safe_close(pair[0]);
1153
1154 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1155 if (r < 0)
1156 _exit(EXIT_FAILURE);
1157
1158 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1159 if (master < 0)
1160 _exit(EXIT_FAILURE);
1161
1162 if (send_one_fd(pair[1], master, 0) < 0)
1163 _exit(EXIT_FAILURE);
1164
1165 _exit(EXIT_SUCCESS);
1166 }
1167
1168 pair[1] = safe_close(pair[1]);
1169
1170 r = wait_for_terminate_and_check("(sd-terminal)", child, 0);
1171 if (r < 0)
1172 return r;
1173 if (r != EXIT_SUCCESS)
1174 return -EIO;
1175
1176 return receive_one_fd(pair[0], 0);
1177 }
1178
1179 static bool getenv_terminal_is_dumb(void) {
1180 const char *e;
1181
1182 e = getenv("TERM");
1183 if (!e)
1184 return true;
1185
1186 return streq(e, "dumb");
1187 }
1188
1189 bool terminal_is_dumb(void) {
1190 if (!on_tty())
1191 return true;
1192
1193 return getenv_terminal_is_dumb();
1194 }
1195
1196 bool colors_enabled(void) {
1197
1198 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1199 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1200 * TTY. And if we are on a TTY we turn it off if $TERM is set to "dumb". There's one special tweak though: if
1201 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1202 * continously due to fear of SAK, and hence things are a bit weird. */
1203
1204 if (cached_colors_enabled < 0) {
1205 int val;
1206
1207 val = getenv_bool("SYSTEMD_COLORS");
1208 if (val >= 0)
1209 cached_colors_enabled = val;
1210 else if (getpid_cached() == 1)
1211 /* PID1 outputs to the console without holding it open all the time */
1212 cached_colors_enabled = !getenv_terminal_is_dumb();
1213 else
1214 cached_colors_enabled = !terminal_is_dumb();
1215 }
1216
1217 return cached_colors_enabled;
1218 }
1219
1220 bool dev_console_colors_enabled(void) {
1221 _cleanup_free_ char *s = NULL;
1222 int b;
1223
1224 /* Returns true if we assume that color is supported on /dev/console.
1225 *
1226 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1227 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1228 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1229 * colors_enabled() operates. */
1230
1231 b = getenv_bool("SYSTEMD_COLORS");
1232 if (b >= 0)
1233 return b;
1234
1235 if (getenv_for_pid(1, "TERM", &s) <= 0)
1236 (void) proc_cmdline_get_key("TERM", 0, &s);
1237
1238 return !streq_ptr(s, "dumb");
1239 }
1240
1241 bool underline_enabled(void) {
1242
1243 if (cached_underline_enabled < 0) {
1244
1245 /* The Linux console doesn't support underlining, turn it off, but only there. */
1246
1247 if (colors_enabled())
1248 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1249 else
1250 cached_underline_enabled = false;
1251 }
1252
1253 return cached_underline_enabled;
1254 }
1255
1256 int vt_default_utf8(void) {
1257 _cleanup_free_ char *b = NULL;
1258 int r;
1259
1260 /* Read the default VT UTF8 setting from the kernel */
1261
1262 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1263 if (r < 0)
1264 return r;
1265
1266 return parse_boolean(b);
1267 }
1268
1269 int vt_reset_keyboard(int fd) {
1270 int kb;
1271
1272 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1273 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1274
1275 if (ioctl(fd, KDSKBMODE, kb) < 0)
1276 return -errno;
1277
1278 return 0;
1279 }
1280
1281 static bool urlify_enabled(void) {
1282 static int cached_urlify_enabled = -1;
1283
1284 /* Unfortunately 'less' doesn't support links like this yet 😭, hence let's disable this as long as there's a
1285 * pager in effect. Let's drop this check as soon as less got fixed a and enough time passed so that it's safe
1286 * to assume that a link-enabled 'less' version has hit most installations. */
1287
1288 if (cached_urlify_enabled < 0) {
1289 int val;
1290
1291 val = getenv_bool("SYSTEMD_URLIFY");
1292 if (val >= 0)
1293 cached_urlify_enabled = val;
1294 else
1295 cached_urlify_enabled = colors_enabled() && !pager_have();
1296 }
1297
1298 return cached_urlify_enabled;
1299 }
1300
1301 int terminal_urlify(const char *url, const char *text, char **ret) {
1302 char *n;
1303
1304 assert(url);
1305
1306 /* Takes an URL and a pretty string and formats it as clickable link for the terminal. See
1307 * https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda for details. */
1308
1309 if (isempty(text))
1310 text = url;
1311
1312 if (urlify_enabled())
1313 n = strjoin("\x1B]8;;", url, "\a", text, "\x1B]8;;\a");
1314 else
1315 n = strdup(text);
1316 if (!n)
1317 return -ENOMEM;
1318
1319 *ret = n;
1320 return 0;
1321 }
1322
1323 int terminal_urlify_path(const char *path, const char *text, char **ret) {
1324 _cleanup_free_ char *absolute = NULL;
1325 struct utsname u;
1326 const char *url;
1327 int r;
1328
1329 assert(path);
1330
1331 /* Much like terminal_urlify() above, but takes a file system path as input
1332 * and turns it into a proper file:// URL first. */
1333
1334 if (isempty(path))
1335 return -EINVAL;
1336
1337 if (isempty(text))
1338 text = path;
1339
1340 if (!urlify_enabled()) {
1341 char *n;
1342
1343 n = strdup(text);
1344 if (!n)
1345 return -ENOMEM;
1346
1347 *ret = n;
1348 return 0;
1349 }
1350
1351 if (uname(&u) < 0)
1352 return -errno;
1353
1354 if (!path_is_absolute(path)) {
1355 r = path_make_absolute_cwd(path, &absolute);
1356 if (r < 0)
1357 return r;
1358
1359 path = absolute;
1360 }
1361
1362 /* As suggested by https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda, let's include the local
1363 * hostname here. Note that we don't use gethostname_malloc() or gethostname_strict() since we are interested
1364 * in the raw string the kernel has set, whatever it may be, under the assumption that terminals are not overly
1365 * careful with validating the strings either. */
1366
1367 url = strjoina("file://", u.nodename, path);
1368
1369 return terminal_urlify(url, text, ret);
1370 }
1371
1372 int terminal_urlify_man(const char *page, const char *section, char **ret) {
1373 const char *url, *text;
1374
1375 url = strjoina("man:", page, "(", section, ")");
1376 text = strjoina(page, "(", section, ") man page");
1377
1378 return terminal_urlify(url, text, ret);
1379 }
1380
1381 static int cat_file(const char *filename, bool newline) {
1382 _cleanup_fclose_ FILE *f = NULL;
1383 _cleanup_free_ char *urlified = NULL;
1384 int r;
1385
1386 f = fopen(filename, "re");
1387 if (!f)
1388 return -errno;
1389
1390 r = terminal_urlify_path(filename, NULL, &urlified);
1391 if (r < 0)
1392 return r;
1393
1394 printf("%s%s# %s%s\n",
1395 newline ? "\n" : "",
1396 ansi_highlight_blue(),
1397 urlified,
1398 ansi_normal());
1399 fflush(stdout);
1400
1401 for (;;) {
1402 _cleanup_free_ char *line = NULL;
1403
1404 r = read_line(f, LONG_LINE_MAX, &line);
1405 if (r < 0)
1406 return log_error_errno(r, "Failed to read \"%s\": %m", filename);
1407 if (r == 0)
1408 break;
1409
1410 puts(line);
1411 }
1412
1413 return 0;
1414 }
1415
1416 int cat_files(const char *file, char **dropins, CatFlags flags) {
1417 char **path;
1418 int r;
1419
1420 if (file) {
1421 r = cat_file(file, false);
1422 if (r == -ENOENT && (flags & CAT_FLAGS_MAIN_FILE_OPTIONAL))
1423 printf("%s# config file %s not found%s\n",
1424 ansi_highlight_magenta(),
1425 file,
1426 ansi_normal());
1427 else if (r < 0)
1428 return log_warning_errno(r, "Failed to cat %s: %m", file);
1429 }
1430
1431 STRV_FOREACH(path, dropins) {
1432 r = cat_file(*path, file || path != dropins);
1433 if (r < 0)
1434 return log_warning_errno(r, "Failed to cat %s: %m", *path);
1435 }
1436
1437 return 0;
1438 }
1439
1440 void print_separator(void) {
1441
1442 /* Outputs a separator line that resolves to whitespace when copied from the terminal. We do that by outputting
1443 * one line filled with spaces with ANSI underline set, followed by a second (empty) line. */
1444
1445 if (underline_enabled()) {
1446 size_t i, c;
1447
1448 c = columns();
1449
1450 flockfile(stdout);
1451 fputs_unlocked(ANSI_UNDERLINE, stdout);
1452
1453 for (i = 0; i < c; i++)
1454 fputc_unlocked(' ', stdout);
1455
1456 fputs_unlocked(ANSI_NORMAL "\n\n", stdout);
1457 funlockfile(stdout);
1458 } else
1459 fputs("\n\n", stdout);
1460 }