]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/terminal-util.c
Merge pull request #2054 from keszybz/nss-link-less-2
[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 assert(tty);
730
731 return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
732 }
733
734 int fd_columns(int fd) {
735 struct winsize ws = {};
736
737 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
738 return -errno;
739
740 if (ws.ws_col <= 0)
741 return -EIO;
742
743 return ws.ws_col;
744 }
745
746 unsigned columns(void) {
747 const char *e;
748 int c;
749
750 if (_likely_(cached_columns > 0))
751 return cached_columns;
752
753 c = 0;
754 e = getenv("COLUMNS");
755 if (e)
756 (void) safe_atoi(e, &c);
757
758 if (c <= 0)
759 c = fd_columns(STDOUT_FILENO);
760
761 if (c <= 0)
762 c = 80;
763
764 cached_columns = c;
765 return cached_columns;
766 }
767
768 int fd_lines(int fd) {
769 struct winsize ws = {};
770
771 if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
772 return -errno;
773
774 if (ws.ws_row <= 0)
775 return -EIO;
776
777 return ws.ws_row;
778 }
779
780 unsigned lines(void) {
781 const char *e;
782 int l;
783
784 if (_likely_(cached_lines > 0))
785 return cached_lines;
786
787 l = 0;
788 e = getenv("LINES");
789 if (e)
790 (void) safe_atoi(e, &l);
791
792 if (l <= 0)
793 l = fd_lines(STDOUT_FILENO);
794
795 if (l <= 0)
796 l = 24;
797
798 cached_lines = l;
799 return cached_lines;
800 }
801
802 /* intended to be used as a SIGWINCH sighandler */
803 void columns_lines_cache_reset(int signum) {
804 cached_columns = 0;
805 cached_lines = 0;
806 }
807
808 bool on_tty(void) {
809 static int cached_on_tty = -1;
810
811 if (_unlikely_(cached_on_tty < 0))
812 cached_on_tty = isatty(STDOUT_FILENO) > 0;
813
814 return cached_on_tty;
815 }
816
817 int make_stdio(int fd) {
818 int r, s, t;
819
820 assert(fd >= 0);
821
822 r = dup2(fd, STDIN_FILENO);
823 s = dup2(fd, STDOUT_FILENO);
824 t = dup2(fd, STDERR_FILENO);
825
826 if (fd >= 3)
827 safe_close(fd);
828
829 if (r < 0 || s < 0 || t < 0)
830 return -errno;
831
832 /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
833 * dup2() was a NOP and the bit hence possibly set. */
834 fd_cloexec(STDIN_FILENO, false);
835 fd_cloexec(STDOUT_FILENO, false);
836 fd_cloexec(STDERR_FILENO, false);
837
838 return 0;
839 }
840
841 int make_null_stdio(void) {
842 int null_fd;
843
844 null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
845 if (null_fd < 0)
846 return -errno;
847
848 return make_stdio(null_fd);
849 }
850
851 int getttyname_malloc(int fd, char **ret) {
852 size_t l = 100;
853 int r;
854
855 assert(fd >= 0);
856 assert(ret);
857
858 for (;;) {
859 char path[l];
860
861 r = ttyname_r(fd, path, sizeof(path));
862 if (r == 0) {
863 const char *p;
864 char *c;
865
866 p = startswith(path, "/dev/");
867 c = strdup(p ?: path);
868 if (!c)
869 return -ENOMEM;
870
871 *ret = c;
872 return 0;
873 }
874
875 if (r != ERANGE)
876 return -r;
877
878 l *= 2;
879 }
880
881 return 0;
882 }
883
884 int getttyname_harder(int fd, char **r) {
885 int k;
886 char *s = NULL;
887
888 k = getttyname_malloc(fd, &s);
889 if (k < 0)
890 return k;
891
892 if (streq(s, "tty")) {
893 free(s);
894 return get_ctty(0, NULL, r);
895 }
896
897 *r = s;
898 return 0;
899 }
900
901 int get_ctty_devnr(pid_t pid, dev_t *d) {
902 int r;
903 _cleanup_free_ char *line = NULL;
904 const char *p;
905 unsigned long ttynr;
906
907 assert(pid >= 0);
908
909 p = procfs_file_alloca(pid, "stat");
910 r = read_one_line_file(p, &line);
911 if (r < 0)
912 return r;
913
914 p = strrchr(line, ')');
915 if (!p)
916 return -EIO;
917
918 p++;
919
920 if (sscanf(p, " "
921 "%*c " /* state */
922 "%*d " /* ppid */
923 "%*d " /* pgrp */
924 "%*d " /* session */
925 "%lu ", /* ttynr */
926 &ttynr) != 1)
927 return -EIO;
928
929 if (major(ttynr) == 0 && minor(ttynr) == 0)
930 return -ENXIO;
931
932 if (d)
933 *d = (dev_t) ttynr;
934
935 return 0;
936 }
937
938 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
939 char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
940 _cleanup_free_ char *s = NULL;
941 const char *p;
942 dev_t devnr;
943 int k;
944
945 assert(r);
946
947 k = get_ctty_devnr(pid, &devnr);
948 if (k < 0)
949 return k;
950
951 sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
952
953 k = readlink_malloc(fn, &s);
954 if (k < 0) {
955
956 if (k != -ENOENT)
957 return k;
958
959 /* This is an ugly hack */
960 if (major(devnr) == 136) {
961 if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
962 return -ENOMEM;
963 } else {
964 /* Probably something like the ptys which have no
965 * symlink in /dev/char. Let's return something
966 * vaguely useful. */
967
968 b = strdup(fn + 5);
969 if (!b)
970 return -ENOMEM;
971 }
972 } else {
973 if (startswith(s, "/dev/"))
974 p = s + 5;
975 else if (startswith(s, "../"))
976 p = s + 3;
977 else
978 p = s;
979
980 b = strdup(p);
981 if (!b)
982 return -ENOMEM;
983 }
984
985 *r = b;
986 if (_devnr)
987 *_devnr = devnr;
988
989 return 0;
990 }
991
992 int ptsname_malloc(int fd, char **ret) {
993 size_t l = 100;
994
995 assert(fd >= 0);
996 assert(ret);
997
998 for (;;) {
999 char *c;
1000
1001 c = new(char, l);
1002 if (!c)
1003 return -ENOMEM;
1004
1005 if (ptsname_r(fd, c, l) == 0) {
1006 *ret = c;
1007 return 0;
1008 }
1009 if (errno != ERANGE) {
1010 free(c);
1011 return -errno;
1012 }
1013
1014 free(c);
1015 l *= 2;
1016 }
1017 }
1018
1019 int ptsname_namespace(int pty, char **ret) {
1020 int no = -1, r;
1021
1022 /* Like ptsname(), but doesn't assume that the path is
1023 * accessible in the local namespace. */
1024
1025 r = ioctl(pty, TIOCGPTN, &no);
1026 if (r < 0)
1027 return -errno;
1028
1029 if (no < 0)
1030 return -EIO;
1031
1032 if (asprintf(ret, "/dev/pts/%i", no) < 0)
1033 return -ENOMEM;
1034
1035 return 0;
1036 }
1037
1038 int openpt_in_namespace(pid_t pid, int flags) {
1039 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1040 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1041 siginfo_t si;
1042 pid_t child;
1043 int r;
1044
1045 assert(pid > 0);
1046
1047 r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &usernsfd, &rootfd);
1048 if (r < 0)
1049 return r;
1050
1051 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
1052 return -errno;
1053
1054 child = fork();
1055 if (child < 0)
1056 return -errno;
1057
1058 if (child == 0) {
1059 int master;
1060
1061 pair[0] = safe_close(pair[0]);
1062
1063 r = namespace_enter(pidnsfd, mntnsfd, -1, usernsfd, rootfd);
1064 if (r < 0)
1065 _exit(EXIT_FAILURE);
1066
1067 master = posix_openpt(flags|O_NOCTTY|O_CLOEXEC);
1068 if (master < 0)
1069 _exit(EXIT_FAILURE);
1070
1071 if (unlockpt(master) < 0)
1072 _exit(EXIT_FAILURE);
1073
1074 if (send_one_fd(pair[1], master, 0) < 0)
1075 _exit(EXIT_FAILURE);
1076
1077 _exit(EXIT_SUCCESS);
1078 }
1079
1080 pair[1] = safe_close(pair[1]);
1081
1082 r = wait_for_terminate(child, &si);
1083 if (r < 0)
1084 return r;
1085 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
1086 return -EIO;
1087
1088 return receive_one_fd(pair[0], 0);
1089 }
1090
1091 int open_terminal_in_namespace(pid_t pid, const char *name, int mode) {
1092 _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, usernsfd = -1, rootfd = -1;
1093 _cleanup_close_pair_ int pair[2] = { -1, -1 };
1094 siginfo_t si;
1095 pid_t child;
1096 int r;
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 = open_terminal(name, mode|O_NOCTTY|O_CLOEXEC);
1119 if (master < 0)
1120 _exit(EXIT_FAILURE);
1121
1122 if (send_one_fd(pair[1], master, 0) < 0)
1123 _exit(EXIT_FAILURE);
1124
1125 _exit(EXIT_SUCCESS);
1126 }
1127
1128 pair[1] = safe_close(pair[1]);
1129
1130 r = wait_for_terminate(child, &si);
1131 if (r < 0)
1132 return r;
1133 if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
1134 return -EIO;
1135
1136 return receive_one_fd(pair[0], 0);
1137 }
1138
1139 bool colors_enabled(void) {
1140 const char *colors;
1141
1142 colors = getenv("SYSTEMD_COLORS");
1143 if (!colors) {
1144 if (streq_ptr(getenv("TERM"), "dumb"))
1145 return false;
1146 return on_tty();
1147 }
1148
1149 return parse_boolean(colors) != 0;
1150 }