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