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