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