]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
Merge pull request #8417 from brauner/2018-03-09/add_bind_mount_fallback_to_private_d...
[thirdparty/systemd.git] / src / basic / terminal-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <limits.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/socket.h>
17 #include <sys/sysmacros.h>
18 #include <sys/time.h>
19 #include <linux/kd.h>
20 #include <linux/tiocl.h>
21 #include <linux/vt.h>
22 #include <poll.h>
23 #include <signal.h>
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
26 #include <termios.h>
27 #include <unistd.h>
28
29 #include "alloc-util.h"
30 #include "env-util.h"
31 #include "fd-util.h"
32 #include "fileio.h"
33 #include "fs-util.h"
34 #include "io-util.h"
35 #include "log.h"
36 #include "macro.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "proc-cmdline.h"
40 #include "process-util.h"
41 #include "socket-util.h"
42 #include "stat-util.h"
43 #include "string-util.h"
44 #include "strv.h"
45 #include "terminal-util.h"
46 #include "time-util.h"
47 #include "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_colors_enabled = -1;
54 static volatile int cached_underline_enabled = -1;
55
56 int chvt(int vt) {
57 _cleanup_close_ int fd;
58
59 /* Switch to the specified vt number. If the VT is specified <= 0 switch to the VT the kernel log messages go,
60 * if that's configured. */
61
62 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
63 if (fd < 0)
64 return -errno;
65
66 if (vt <= 0) {
67 int tiocl[2] = {
68 TIOCL_GETKMSGREDIRECT,
69 0
70 };
71
72 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
73 return -errno;
74
75 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
76 }
77
78 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
79 return -errno;
80
81 return 0;
82 }
83
84 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
85 struct termios old_termios, new_termios;
86 char c, line[LINE_MAX];
87
88 assert(f);
89 assert(ret);
90
91 if (tcgetattr(fileno(f), &old_termios) >= 0) {
92 new_termios = old_termios;
93
94 new_termios.c_lflag &= ~ICANON;
95 new_termios.c_cc[VMIN] = 1;
96 new_termios.c_cc[VTIME] = 0;
97
98 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
99 size_t k;
100
101 if (t != USEC_INFINITY) {
102 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
103 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
104 return -ETIMEDOUT;
105 }
106 }
107
108 k = fread(&c, 1, 1, f);
109
110 tcsetattr(fileno(f), TCSADRAIN, &old_termios);
111
112 if (k <= 0)
113 return -EIO;
114
115 if (need_nl)
116 *need_nl = c != '\n';
117
118 *ret = c;
119 return 0;
120 }
121 }
122
123 if (t != USEC_INFINITY) {
124 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
125 return -ETIMEDOUT;
126 }
127
128 errno = 0;
129 if (!fgets(line, sizeof(line), f))
130 return errno > 0 ? -errno : -EIO;
131
132 truncate_nl(line);
133
134 if (strlen(line) != 1)
135 return -EBADMSG;
136
137 if (need_nl)
138 *need_nl = false;
139
140 *ret = line[0];
141 return 0;
142 }
143
144 #define DEFAULT_ASK_REFRESH_USEC (2*USEC_PER_SEC)
145
146 int ask_char(char *ret, const char *replies, const char *fmt, ...) {
147 int r;
148
149 assert(ret);
150 assert(replies);
151 assert(fmt);
152
153 for (;;) {
154 va_list ap;
155 char c;
156 bool need_nl = true;
157
158 if (colors_enabled())
159 fputs(ANSI_HIGHLIGHT, stdout);
160
161 putchar('\r');
162
163 va_start(ap, fmt);
164 vprintf(fmt, ap);
165 va_end(ap);
166
167 if (colors_enabled())
168 fputs(ANSI_NORMAL, stdout);
169
170 fflush(stdout);
171
172 r = read_one_char(stdin, &c, DEFAULT_ASK_REFRESH_USEC, &need_nl);
173 if (r < 0) {
174
175 if (r == -ETIMEDOUT)
176 continue;
177
178 if (r == -EBADMSG) {
179 puts("Bad input, please try again.");
180 continue;
181 }
182
183 putchar('\n');
184 return r;
185 }
186
187 if (need_nl)
188 putchar('\n');
189
190 if (strchr(replies, c)) {
191 *ret = c;
192 return 0;
193 }
194
195 puts("Read unexpected character, please try again.");
196 }
197 }
198
199 int ask_string(char **ret, const char *text, ...) {
200 assert(ret);
201 assert(text);
202
203 for (;;) {
204 char line[LINE_MAX];
205 va_list ap;
206
207 if (colors_enabled())
208 fputs(ANSI_HIGHLIGHT, stdout);
209
210 va_start(ap, text);
211 vprintf(text, ap);
212 va_end(ap);
213
214 if (colors_enabled())
215 fputs(ANSI_NORMAL, stdout);
216
217 fflush(stdout);
218
219 errno = 0;
220 if (!fgets(line, sizeof(line), stdin))
221 return errno > 0 ? -errno : -EIO;
222
223 if (!endswith(line, "\n"))
224 putchar('\n');
225 else {
226 char *s;
227
228 if (isempty(line))
229 continue;
230
231 truncate_nl(line);
232 s = strdup(line);
233 if (!s)
234 return -ENOMEM;
235
236 *ret = s;
237 return 0;
238 }
239 }
240 }
241
242 int reset_terminal_fd(int fd, bool switch_to_text) {
243 struct termios termios;
244 int r = 0;
245
246 /* Set terminal to some sane defaults */
247
248 assert(fd >= 0);
249
250 /* We leave locked terminal attributes untouched, so that
251 * Plymouth may set whatever it wants to set, and we don't
252 * interfere with that. */
253
254 /* Disable exclusive mode, just in case */
255 (void) ioctl(fd, TIOCNXCL);
256
257 /* Switch to text mode */
258 if (switch_to_text)
259 (void) ioctl(fd, KDSETMODE, KD_TEXT);
260
261 /* Set default keyboard mode */
262 (void) vt_reset_keyboard(fd);
263
264 if (tcgetattr(fd, &termios) < 0) {
265 r = -errno;
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;
276 termios.c_cflag |= CREAD;
277 termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | 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 if (tcsetattr(fd, TCSANOW, &termios) < 0)
297 r = -errno;
298
299 finish:
300 /* Just in case, flush all crap out */
301 (void) tcflush(fd, TCIOFLUSH);
302
303 return r;
304 }
305
306 int reset_terminal(const char *name) {
307 _cleanup_close_ int fd = -1;
308
309 /* We open the terminal with O_NONBLOCK here, to ensure we
310 * don't block on carrier if this is a terminal with carrier
311 * configured. */
312
313 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
314 if (fd < 0)
315 return fd;
316
317 return reset_terminal_fd(fd, true);
318 }
319
320 int open_terminal(const char *name, int mode) {
321 unsigned c = 0;
322 int fd;
323
324 /*
325 * If a TTY is in the process of being closed opening it might
326 * cause EIO. This is horribly awful, but unlikely to be
327 * changed in the kernel. Hence we work around this problem by
328 * retrying a couple of times.
329 *
330 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
331 */
332
333 if (mode & O_CREAT)
334 return -EINVAL;
335
336 for (;;) {
337 fd = open(name, mode, 0);
338 if (fd >= 0)
339 break;
340
341 if (errno != EIO)
342 return -errno;
343
344 /* Max 1s in total */
345 if (c >= 20)
346 return -errno;
347
348 usleep(50 * USEC_PER_MSEC);
349 c++;
350 }
351
352 if (isatty(fd) <= 0) {
353 safe_close(fd);
354 return -ENOTTY;
355 }
356
357 return fd;
358 }
359
360 int acquire_terminal(
361 const char *name,
362 AcquireTerminalFlags flags,
363 usec_t timeout) {
364
365 _cleanup_close_ int notify = -1, fd = -1;
366 usec_t ts = USEC_INFINITY;
367 int r, wd = -1;
368
369 assert(name);
370 assert(IN_SET(flags & ~ACQUIRE_TERMINAL_PERMISSIVE, ACQUIRE_TERMINAL_TRY, ACQUIRE_TERMINAL_FORCE, ACQUIRE_TERMINAL_WAIT));
371
372 /* We use inotify to be notified when the tty is closed. We create the watch before checking if we can actually
373 * acquire it, so that we don't lose any event.
374 *
375 * Note: strictly speaking this actually watches for the device being closed, it does *not* really watch
376 * whether a tty loses its controlling process. However, unless some rogue process uses TIOCNOTTY on /dev/tty
377 * *after* closing its tty otherwise this will not become a problem. As long as the administrator makes sure to
378 * not configure any service on the same tty as an untrusted user this should not be a problem. (Which they
379 * probably should not do anyway.) */
380
381 if ((flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_WAIT) {
382 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
383 if (notify < 0)
384 return -errno;
385
386 wd = inotify_add_watch(notify, name, IN_CLOSE);
387 if (wd < 0)
388 return -errno;
389
390 if (timeout != USEC_INFINITY)
391 ts = now(CLOCK_MONOTONIC);
392 }
393
394 for (;;) {
395 struct sigaction sa_old, sa_new = {
396 .sa_handler = SIG_IGN,
397 .sa_flags = SA_RESTART,
398 };
399
400 if (notify >= 0) {
401 r = flush_fd(notify);
402 if (r < 0)
403 return r;
404 }
405
406 /* We pass here O_NOCTTY only so that we can check the return value TIOCSCTTY and have a reliable way
407 * to figure out if we successfully became the controlling process of the tty */
408 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
409 if (fd < 0)
410 return fd;
411
412 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed if we already own the tty. */
413 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
414
415 /* First, try to get the tty */
416 r = ioctl(fd, TIOCSCTTY,
417 (flags & ~ACQUIRE_TERMINAL_PERMISSIVE) == ACQUIRE_TERMINAL_FORCE) < 0 ? -errno : 0;
418
419 /* Reset signal handler to old value */
420 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
421
422 /* Success? Exit the loop now! */
423 if (r >= 0)
424 break;
425
426 /* Any failure besides -EPERM? Fail, regardless of the mode. */
427 if (r != -EPERM)
428 return r;
429
430 if (flags & ACQUIRE_TERMINAL_PERMISSIVE) /* If we are in permissive mode, then EPERM is fine, turn this
431 * into a success. Note that EPERM is also returned if we
432 * already are the owner of the TTY. */
433 break;
434
435 if (flags != ACQUIRE_TERMINAL_WAIT) /* If we are in TRY or FORCE mode, then propagate EPERM as EPERM */
436 return r;
437
438 assert(notify >= 0);
439 assert(wd >= 0);
440
441 for (;;) {
442 union inotify_event_buffer buffer;
443 struct inotify_event *e;
444 ssize_t l;
445
446 if (timeout != USEC_INFINITY) {
447 usec_t n;
448
449 assert(ts != USEC_INFINITY);
450
451 n = now(CLOCK_MONOTONIC);
452 if (ts + timeout < n)
453 return -ETIMEDOUT;
454
455 r = fd_wait_for_event(notify, POLLIN, ts + timeout - n);
456 if (r < 0)
457 return r;
458 if (r == 0)
459 return -ETIMEDOUT;
460 }
461
462 l = read(notify, &buffer, sizeof(buffer));
463 if (l < 0) {
464 if (IN_SET(errno, EINTR, EAGAIN))
465 continue;
466
467 return -errno;
468 }
469
470 FOREACH_INOTIFY_EVENT(e, buffer, l) {
471 if (e->mask & IN_Q_OVERFLOW) /* If we hit an inotify queue overflow, simply check if the terminal is up for grabs now. */
472 break;
473
474 if (e->wd != wd || !(e->mask & IN_CLOSE)) /* Safety checks */
475 return -EIO;
476 }
477
478 break;
479 }
480
481 /* We close the tty fd here since if the old session ended our handle will be dead. It's important that
482 * we do this after sleeping, so that we don't enter an endless loop. */
483 fd = safe_close(fd);
484 }
485
486 return TAKE_FD(fd);
487 }
488
489 int release_terminal(void) {
490 static const struct sigaction sa_new = {
491 .sa_handler = SIG_IGN,
492 .sa_flags = SA_RESTART,
493 };
494
495 _cleanup_close_ int fd = -1;
496 struct sigaction sa_old;
497 int r;
498
499 fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
500 if (fd < 0)
501 return -errno;
502
503 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
504 * by our own TIOCNOTTY */
505 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
506
507 r = ioctl(fd, TIOCNOTTY) < 0 ? -errno : 0;
508
509 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
510
511 return r;
512 }
513
514 int terminal_vhangup_fd(int fd) {
515 assert(fd >= 0);
516
517 if (ioctl(fd, TIOCVHANGUP) < 0)
518 return -errno;
519
520 return 0;
521 }
522
523 int terminal_vhangup(const char *name) {
524 _cleanup_close_ int fd;
525
526 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
527 if (fd < 0)
528 return fd;
529
530 return terminal_vhangup_fd(fd);
531 }
532
533 int vt_disallocate(const char *name) {
534 _cleanup_close_ int fd = -1;
535 const char *e, *n;
536 unsigned u;
537 int r;
538
539 /* Deallocate the VT if possible. If not possible
540 * (i.e. because it is the active one), at least clear it
541 * entirely (including the scrollback buffer) */
542
543 e = path_startswith(name, "/dev/");
544 if (!e)
545 return -EINVAL;
546
547 if (!tty_is_vc(name)) {
548 /* So this is not a VT. I guess we cannot deallocate
549 * it then. But let's at least clear the screen */
550
551 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
552 if (fd < 0)
553 return fd;
554
555 loop_write(fd,
556 "\033[r" /* clear scrolling region */
557 "\033[H" /* move home */
558 "\033[2J", /* clear screen */
559 10, false);
560 return 0;
561 }
562
563 n = startswith(e, "tty");
564 if (!n)
565 return -EINVAL;
566
567 r = safe_atou(n, &u);
568 if (r < 0)
569 return r;
570
571 if (u <= 0)
572 return -EINVAL;
573
574 /* Try to deallocate */
575 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
576 if (fd < 0)
577 return fd;
578
579 r = ioctl(fd, VT_DISALLOCATE, u);
580 fd = safe_close(fd);
581
582 if (r >= 0)
583 return 0;
584
585 if (errno != EBUSY)
586 return -errno;
587
588 /* Couldn't deallocate, so let's clear it fully with
589 * scrollback */
590 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
591 if (fd < 0)
592 return fd;
593
594 loop_write(fd,
595 "\033[r" /* clear scrolling region */
596 "\033[H" /* move home */
597 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
598 10, false);
599 return 0;
600 }
601
602 int make_console_stdio(void) {
603 int fd, r;
604
605 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
606
607 fd = acquire_terminal("/dev/console", ACQUIRE_TERMINAL_FORCE|ACQUIRE_TERMINAL_PERMISSIVE, USEC_INFINITY);
608 if (fd < 0)
609 return log_error_errno(fd, "Failed to acquire terminal: %m");
610
611 r = reset_terminal_fd(fd, true);
612 if (r < 0)
613 log_warning_errno(r, "Failed to reset terminal, ignoring: %m");
614
615 r = rearrange_stdio(fd, fd, fd); /* This invalidates 'fd' both on success and on failure. */
616 if (r < 0)
617 return log_error_errno(r, "Failed to make terminal stdin/stdout/stderr: %m");
618
619 reset_terminal_feature_caches();
620
621 return 0;
622 }
623
624 bool tty_is_vc(const char *tty) {
625 assert(tty);
626
627 return vtnr_from_tty(tty) >= 0;
628 }
629
630 bool tty_is_console(const char *tty) {
631 assert(tty);
632
633 return streq(skip_dev_prefix(tty), "console");
634 }
635
636 int vtnr_from_tty(const char *tty) {
637 int i, r;
638
639 assert(tty);
640
641 tty = skip_dev_prefix(tty);
642
643 if (!startswith(tty, "tty") )
644 return -EINVAL;
645
646 if (tty[3] < '0' || tty[3] > '9')
647 return -EINVAL;
648
649 r = safe_atoi(tty+3, &i);
650 if (r < 0)
651 return r;
652
653 if (i < 0 || i > 63)
654 return -EINVAL;
655
656 return i;
657 }
658
659 int resolve_dev_console(char **ret) {
660 _cleanup_free_ char *active = NULL;
661 char *tty;
662 int r;
663
664 assert(ret);
665
666 /* Resolve where /dev/console is pointing to, if /sys is actually ours (i.e. not read-only-mounted which is a
667 * sign for container setups) */
668
669 if (path_is_read_only_fs("/sys") > 0)
670 return -ENOMEDIUM;
671
672 r = read_one_line_file("/sys/class/tty/console/active", &active);
673 if (r < 0)
674 return r;
675
676 /* If multiple log outputs are configured the last one is what /dev/console points to */
677 tty = strrchr(active, ' ');
678 if (tty)
679 tty++;
680 else
681 tty = active;
682
683 if (streq(tty, "tty0")) {
684 active = mfree(active);
685
686 /* Get the active VC (e.g. tty1) */
687 r = read_one_line_file("/sys/class/tty/tty0/active", &active);
688 if (r < 0)
689 return r;
690
691 tty = active;
692 }
693
694 if (tty == active)
695 *ret = TAKE_PTR(active);
696 else {
697 char *tmp;
698
699 tmp = strdup(tty);
700 if (!tmp)
701 return -ENOMEM;
702
703 *ret = tmp;
704 }
705
706 return 0;
707 }
708
709 int get_kernel_consoles(char ***ret) {
710 _cleanup_strv_free_ char **l = NULL;
711 _cleanup_free_ char *line = NULL;
712 const char *p;
713 int r;
714
715 assert(ret);
716
717 /* If /sys is mounted read-only this means we are running in some kind of container environment. In that
718 * case /sys would reflect the host system, not us, hence ignore the data we can read from it. */
719 if (path_is_read_only_fs("/sys") > 0)
720 goto fallback;
721
722 r = read_one_line_file("/sys/class/tty/console/active", &line);
723 if (r < 0)
724 return r;
725
726 p = line;
727 for (;;) {
728 _cleanup_free_ char *tty = NULL;
729 char *path;
730
731 r = extract_first_word(&p, &tty, NULL, 0);
732 if (r < 0)
733 return r;
734 if (r == 0)
735 break;
736
737 if (streq(tty, "tty0")) {
738 tty = mfree(tty);
739 r = read_one_line_file("/sys/class/tty/tty0/active", &tty);
740 if (r < 0)
741 return r;
742 }
743
744 path = strappend("/dev/", tty);
745 if (!path)
746 return -ENOMEM;
747
748 if (access(path, F_OK) < 0) {
749 log_debug_errno(errno, "Console device %s is not accessible, skipping: %m", path);
750 free(path);
751 continue;
752 }
753
754 r = strv_consume(&l, path);
755 if (r < 0)
756 return r;
757 }
758
759 if (strv_isempty(l)) {
760 log_debug("No devices found for system console");
761 goto fallback;
762 }
763
764 *ret = TAKE_PTR(l);
765
766 return 0;
767
768 fallback:
769 r = strv_extend(&l, "/dev/console");
770 if (r < 0)
771 return r;
772
773 *ret = TAKE_PTR(l);
774
775 return 0;
776 }
777
778 bool tty_is_vc_resolve(const char *tty) {
779 _cleanup_free_ char *resolved = NULL;
780
781 assert(tty);
782
783 tty = skip_dev_prefix(tty);
784
785 if (streq(tty, "console")) {
786 if (resolve_dev_console(&resolved) < 0)
787 return false;
788
789 tty = resolved;
790 }
791
792 return tty_is_vc(tty);
793 }
794
795 const char *default_term_for_tty(const char *tty) {
796 return tty && tty_is_vc_resolve(tty) ? "linux" : "vt220";
797 }
798
799 int fd_columns(int fd) {
800 struct winsize ws = {};
801
802 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
803 return -errno;
804
805 if (ws.ws_col <= 0)
806 return -EIO;
807
808 return ws.ws_col;
809 }
810
811 unsigned columns(void) {
812 const char *e;
813 int c;
814
815 if (cached_columns > 0)
816 return cached_columns;
817
818 c = 0;
819 e = getenv("COLUMNS");
820 if (e)
821 (void) safe_atoi(e, &c);
822
823 if (c <= 0)
824 c = fd_columns(STDOUT_FILENO);
825
826 if (c <= 0)
827 c = 80;
828
829 cached_columns = c;
830 return cached_columns;
831 }
832
833 int fd_lines(int fd) {
834 struct winsize ws = {};
835
836 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
837 return -errno;
838
839 if (ws.ws_row <= 0)
840 return -EIO;
841
842 return ws.ws_row;
843 }
844
845 unsigned lines(void) {
846 const char *e;
847 int l;
848
849 if (cached_lines > 0)
850 return cached_lines;
851
852 l = 0;
853 e = getenv("LINES");
854 if (e)
855 (void) safe_atoi(e, &l);
856
857 if (l <= 0)
858 l = fd_lines(STDOUT_FILENO);
859
860 if (l <= 0)
861 l = 24;
862
863 cached_lines = l;
864 return cached_lines;
865 }
866
867 /* intended to be used as a SIGWINCH sighandler */
868 void columns_lines_cache_reset(int signum) {
869 cached_columns = 0;
870 cached_lines = 0;
871 }
872
873 void reset_terminal_feature_caches(void) {
874 cached_columns = 0;
875 cached_lines = 0;
876
877 cached_colors_enabled = -1;
878 cached_underline_enabled = -1;
879 cached_on_tty = -1;
880 }
881
882 bool on_tty(void) {
883 if (cached_on_tty < 0)
884 cached_on_tty = isatty(STDOUT_FILENO) > 0;
885
886 return cached_on_tty;
887 }
888
889 int getttyname_malloc(int fd, char **ret) {
890 size_t l = 100;
891 int r;
892
893 assert(fd >= 0);
894 assert(ret);
895
896 for (;;) {
897 char path[l];
898
899 r = ttyname_r(fd, path, sizeof(path));
900 if (r == 0) {
901 char *c;
902
903 c = strdup(skip_dev_prefix(path));
904 if (!c)
905 return -ENOMEM;
906
907 *ret = c;
908 return 0;
909 }
910
911 if (r != ERANGE)
912 return -r;
913
914 l *= 2;
915 }
916
917 return 0;
918 }
919
920 int getttyname_harder(int fd, char **r) {
921 int k;
922 char *s = NULL;
923
924 k = getttyname_malloc(fd, &s);
925 if (k < 0)
926 return k;
927
928 if (streq(s, "tty")) {
929 free(s);
930 return get_ctty(0, NULL, r);
931 }
932
933 *r = s;
934 return 0;
935 }
936
937 int get_ctty_devnr(pid_t pid, dev_t *d) {
938 int r;
939 _cleanup_free_ char *line = NULL;
940 const char *p;
941 unsigned long ttynr;
942
943 assert(pid >= 0);
944
945 p = procfs_file_alloca(pid, "stat");
946 r = read_one_line_file(p, &line);
947 if (r < 0)
948 return r;
949
950 p = strrchr(line, ')');
951 if (!p)
952 return -EIO;
953
954 p++;
955
956 if (sscanf(p, " "
957 "%*c " /* state */
958 "%*d " /* ppid */
959 "%*d " /* pgrp */
960 "%*d " /* session */
961 "%lu ", /* ttynr */
962 &ttynr) != 1)
963 return -EIO;
964
965 if (major(ttynr) == 0 && minor(ttynr) == 0)
966 return -ENXIO;
967
968 if (d)
969 *d = (dev_t) ttynr;
970
971 return 0;
972 }
973
974 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
975 char fn[STRLEN("/dev/char/") + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
976 _cleanup_free_ char *s = NULL;
977 const char *p;
978 dev_t devnr;
979 int k;
980
981 assert(r);
982
983 k = get_ctty_devnr(pid, &devnr);
984 if (k < 0)
985 return k;
986
987 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
988
989 k = readlink_malloc(fn, &s);
990 if (k < 0) {
991
992 if (k != -ENOENT)
993 return k;
994
995 /* This is an ugly hack */
996 if (major(devnr) == 136) {
997 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
998 return -ENOMEM;
999 } else {
1000 /* Probably something like the ptys which have no
1001 * symlink in /dev/char. Let's return something
1002 * vaguely useful. */
1003
1004 b = strdup(fn + 5);
1005 if (!b)
1006 return -ENOMEM;
1007 }
1008 } else {
1009 if (startswith(s, "/dev/"))
1010 p = s + 5;
1011 else if (startswith(s, "../"))
1012 p = s + 3;
1013 else
1014 p = s;
1015
1016 b = strdup(p);
1017 if (!b)
1018 return -ENOMEM;
1019 }
1020
1021 *r = b;
1022 if (_devnr)
1023 *_devnr = devnr;
1024
1025 return 0;
1026 }
1027
1028 int ptsname_malloc(int fd, char **ret) {
1029 size_t l = 100;
1030
1031 assert(fd >= 0);
1032 assert(ret);
1033
1034 for (;;) {
1035 char *c;
1036
1037 c = new(char, l);
1038 if (!c)
1039 return -ENOMEM;
1040
1041 if (ptsname_r(fd, c, l) == 0) {
1042 *ret = c;
1043 return 0;
1044 }
1045 if (errno != ERANGE) {
1046 free(c);
1047 return -errno;
1048 }
1049
1050 free(c);
1051 l *= 2;
1052 }
1053 }
1054
1055 int ptsname_namespace(int pty, char **ret) {
1056 int no = -1, r;
1057
1058 /* Like ptsname(), but doesn't assume that the path is
1059 * accessible in the local namespace. */
1060
1061 r = ioctl(pty, TIOCGPTN, &no);
1062 if (r < 0)
1063 return -errno;
1064
1065 if (no < 0)
1066 return -EIO;
1067
1068 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1069 return -ENOMEM;
1070
1071 return 0;
1072 }
1073
1074 int openpt_in_namespace(pid_t pid, int flags) {
1075 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1076 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1077 pid_t child;
1078 int r;
1079
1080 assert(pid > 0);
1081
1082 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1083 if (r < 0)
1084 return r;
1085
1086 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1087 return -errno;
1088
1089 r = safe_fork("(sd-openpt)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1090 if (r < 0)
1091 return r;
1092 if (r == 0) {
1093 int master;
1094
1095 pair[0] = safe_close(pair[0]);
1096
1097 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1098 if (r < 0)
1099 _exit(EXIT_FAILURE);
1100
1101 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1102 if (master < 0)
1103 _exit(EXIT_FAILURE);
1104
1105 if (unlockpt(master) < 0)
1106 _exit(EXIT_FAILURE);
1107
1108 if (send_one_fd(pair[1], master, 0) < 0)
1109 _exit(EXIT_FAILURE);
1110
1111 _exit(EXIT_SUCCESS);
1112 }
1113
1114 pair[1] = safe_close(pair[1]);
1115
1116 r = wait_for_terminate_and_check("(sd-openpt)", child, 0);
1117 if (r < 0)
1118 return r;
1119 if (r != EXIT_SUCCESS)
1120 return -EIO;
1121
1122 return receive_one_fd(pair[0], 0);
1123 }
1124
1125 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1126 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1127 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1128 pid_t child;
1129 int r;
1130
1131 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1132 if (r < 0)
1133 return r;
1134
1135 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1136 return -errno;
1137
1138 r = safe_fork("(sd-terminal)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &child);
1139 if (r < 0)
1140 return r;
1141 if (r == 0) {
1142 int master;
1143
1144 pair[0] = safe_close(pair[0]);
1145
1146 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1147 if (r < 0)
1148 _exit(EXIT_FAILURE);
1149
1150 master = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1151 if (master < 0)
1152 _exit(EXIT_FAILURE);
1153
1154 if (send_one_fd(pair[1], master, 0) < 0)
1155 _exit(EXIT_FAILURE);
1156
1157 _exit(EXIT_SUCCESS);
1158 }
1159
1160 pair[1] = safe_close(pair[1]);
1161
1162 r = wait_for_terminate_and_check("(sd-terminal)", child, 0);
1163 if (r < 0)
1164 return r;
1165 if (r != EXIT_SUCCESS)
1166 return -EIO;
1167
1168 return receive_one_fd(pair[0], 0);
1169 }
1170
1171 static bool getenv_terminal_is_dumb(void) {
1172 const char *e;
1173
1174 e = getenv("TERM");
1175 if (!e)
1176 return true;
1177
1178 return streq(e, "dumb");
1179 }
1180
1181 bool terminal_is_dumb(void) {
1182 if (!on_tty())
1183 return true;
1184
1185 return getenv_terminal_is_dumb();
1186 }
1187
1188 bool colors_enabled(void) {
1189
1190 /* Returns true if colors are considered supported on our stdout. For that we check $SYSTEMD_COLORS first
1191 * (which is the explicit way to turn colors on/off). If that didn't work we turn colors off unless we are on a
1192 * 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
1193 * we are PID 1 then we do not check whether we are connected to a TTY, because we don't keep /dev/console open
1194 * continously due to fear of SAK, and hence things are a bit weird. */
1195
1196 if (cached_colors_enabled < 0) {
1197 int val;
1198
1199 val = getenv_bool("SYSTEMD_COLORS");
1200 if (val >= 0)
1201 cached_colors_enabled = val;
1202 else if (getpid_cached() == 1)
1203 /* PID1 outputs to the console without holding it open all the time */
1204 cached_colors_enabled = !getenv_terminal_is_dumb();
1205 else
1206 cached_colors_enabled = !terminal_is_dumb();
1207 }
1208
1209 return cached_colors_enabled;
1210 }
1211
1212 bool dev_console_colors_enabled(void) {
1213 _cleanup_free_ char *s = NULL;
1214 int b;
1215
1216 /* Returns true if we assume that color is supported on /dev/console.
1217 *
1218 * For that we first check if we explicitly got told to use colors or not, by checking $SYSTEMD_COLORS. If that
1219 * isn't set we check whether PID 1 has $TERM set, and if not, whether TERM is set on the kernel command
1220 * line. If we find $TERM set we assume color if it's not set to "dumb", similarly to how regular
1221 * colors_enabled() operates. */
1222
1223 b = getenv_bool("SYSTEMD_COLORS");
1224 if (b >= 0)
1225 return b;
1226
1227 if (getenv_for_pid(1, "TERM", &s) <= 0)
1228 (void) proc_cmdline_get_key("TERM", 0, &s);
1229
1230 return !streq_ptr(s, "dumb");
1231 }
1232
1233 bool underline_enabled(void) {
1234
1235 if (cached_underline_enabled < 0) {
1236
1237 /* The Linux console doesn't support underlining, turn it off, but only there. */
1238
1239 if (colors_enabled())
1240 cached_underline_enabled = !streq_ptr(getenv("TERM"), "linux");
1241 else
1242 cached_underline_enabled = false;
1243 }
1244
1245 return cached_underline_enabled;
1246 }
1247
1248 int vt_default_utf8(void) {
1249 _cleanup_free_ char *b = NULL;
1250 int r;
1251
1252 /* Read the default VT UTF8 setting from the kernel */
1253
1254 r = read_one_line_file("/sys/module/vt/parameters/default_utf8", &b);
1255 if (r < 0)
1256 return r;
1257
1258 return parse_boolean(b);
1259 }
1260
1261 int vt_reset_keyboard(int fd) {
1262 int kb;
1263
1264 /* If we can't read the default, then default to unicode. It's 2017 after all. */
1265 kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
1266
1267 if (ioctl(fd, KDSKBMODE, kb) < 0)
1268 return -errno;
1269
1270 return 0;
1271 }