]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/terminal.c
github: Update for main branch
[mirror_lxc.git] / src / lxc / terminal.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "config.h"
4
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <pthread.h>
8 #include <signal.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <sys/epoll.h>
12 #include <sys/types.h>
13 #include <termios.h>
14 #include <unistd.h>
15
16 #include "lxc.h"
17
18 #include "af_unix.h"
19 #include "caps.h"
20 #include "commands.h"
21 #include "conf.h"
22 #include "log.h"
23 #include "lxclock.h"
24 #include "mainloop.h"
25 #include "memory_utils.h"
26 #include "open_utils.h"
27 #include "start.h"
28 #include "syscall_wrappers.h"
29 #include "terminal.h"
30 #include "utils.h"
31
32 #if HAVE_OPENPTY
33 #include <pty.h>
34 #else
35 #include "openpty.h"
36 #endif
37
38 #define LXC_TERMINAL_BUFFER_SIZE 1024
39
40 lxc_log_define(terminal, lxc);
41
42 void lxc_terminal_winsz(int srcfd, int dstfd)
43 {
44 int ret;
45 struct winsize wsz;
46
47 if (!isatty(srcfd))
48 return;
49
50 ret = ioctl(srcfd, TIOCGWINSZ, &wsz);
51 if (ret < 0) {
52 WARN("Failed to get window size");
53 return;
54 }
55
56 ret = ioctl(dstfd, TIOCSWINSZ, &wsz);
57 if (ret < 0)
58 WARN("Failed to set window size");
59 else
60 DEBUG("Set window size to %d columns and %d rows", wsz.ws_col,
61 wsz.ws_row);
62
63 return;
64 }
65
66 static void lxc_terminal_winch(struct lxc_terminal_state *ts)
67 {
68 lxc_terminal_winsz(ts->stdinfd, ts->ptxfd);
69 }
70
71 int lxc_terminal_signalfd_cb(int fd, uint32_t events, void *cbdata,
72 struct lxc_async_descr *descr)
73 {
74 ssize_t ret;
75 struct signalfd_siginfo siginfo;
76 struct lxc_terminal_state *ts = cbdata;
77
78 ret = lxc_read_nointr(fd, &siginfo, sizeof(siginfo));
79 if (ret < 0 || (size_t)ret < sizeof(siginfo)) {
80 ERROR("Failed to read signal info");
81 return LXC_MAINLOOP_ERROR;
82 }
83
84 if (siginfo.ssi_signo == SIGTERM) {
85 DEBUG("Received SIGTERM. Detaching from the terminal");
86 return LXC_MAINLOOP_CLOSE;
87 }
88
89 if (siginfo.ssi_signo == SIGWINCH)
90 lxc_terminal_winch(ts);
91
92 return LXC_MAINLOOP_CONTINUE;
93 }
94
95 struct lxc_terminal_state *lxc_terminal_signal_init(int srcfd, int dstfd)
96 {
97 __do_close int signal_fd = -EBADF;
98 __do_free struct lxc_terminal_state *ts = NULL;
99 int ret;
100 sigset_t mask;
101
102 ts = malloc(sizeof(*ts));
103 if (!ts)
104 return NULL;
105
106 memset(ts, 0, sizeof(*ts));
107 ts->stdinfd = srcfd;
108 ts->ptxfd = dstfd;
109 ts->sigfd = -1;
110
111 ret = sigemptyset(&mask);
112 if (ret < 0) {
113 SYSERROR("Failed to initialize an empty signal set");
114 return NULL;
115 }
116
117 if (isatty(srcfd)) {
118 ret = sigaddset(&mask, SIGWINCH);
119 if (ret < 0)
120 SYSNOTICE("Failed to add SIGWINCH to signal set");
121 } else {
122 INFO("fd %d does not refer to a tty device", srcfd);
123 }
124
125 /* Exit the mainloop cleanly on SIGTERM. */
126 ret = sigaddset(&mask, SIGTERM);
127 if (ret < 0) {
128 SYSERROR("Failed to add SIGWINCH to signal set");
129 return NULL;
130 }
131
132 ret = pthread_sigmask(SIG_BLOCK, &mask, &ts->oldmask);
133 if (ret < 0) {
134 WARN("Failed to block signals");
135 return NULL;
136 }
137
138 signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
139 if (signal_fd < 0) {
140 WARN("Failed to create signal fd");
141 (void)pthread_sigmask(SIG_SETMASK, &ts->oldmask, NULL);
142 return NULL;
143 }
144 ts->sigfd = move_fd(signal_fd);
145 TRACE("Created signal fd %d", ts->sigfd);
146
147 return move_ptr(ts);
148 }
149
150 int lxc_terminal_signal_sigmask_safe_blocked(struct lxc_terminal *terminal)
151 {
152 struct lxc_terminal_state *state = terminal->tty_state;
153
154 if (!state)
155 return 0;
156
157 return pthread_sigmask(SIG_SETMASK, &state->oldmask, NULL);
158 }
159
160 /**
161 * lxc_terminal_signal_fini: uninstall signal handler
162 *
163 * @terminal: terminal instance
164 *
165 * Restore the saved signal handler that was in effect at the time
166 * lxc_terminal_signal_init() was called.
167 */
168 static void lxc_terminal_signal_fini(struct lxc_terminal *terminal)
169 {
170 struct lxc_terminal_state *state = terminal->tty_state;
171
172 if (!terminal->tty_state)
173 return;
174
175 state = terminal->tty_state;
176 if (state->sigfd >= 0) {
177 close(state->sigfd);
178
179 if (pthread_sigmask(SIG_SETMASK, &state->oldmask, NULL) < 0)
180 SYSWARN("Failed to restore signal mask");
181 }
182
183 free(terminal->tty_state);
184 terminal->tty_state = NULL;
185 }
186
187 static int lxc_terminal_truncate_log_file(struct lxc_terminal *terminal)
188 {
189 /* be very certain things are kosher */
190 if (!terminal->log_path || terminal->log_fd < 0)
191 return -EBADF;
192
193 return lxc_unpriv(ftruncate(terminal->log_fd, 0));
194 }
195
196 static int lxc_terminal_rotate_log_file(struct lxc_terminal *terminal)
197 {
198 __do_free char *tmp = NULL;
199 int ret;
200 size_t len;
201
202 if (!terminal->log_path || terminal->log_rotate == 0)
203 return -EOPNOTSUPP;
204
205 /* be very certain things are kosher */
206 if (terminal->log_fd < 0)
207 return -EBADF;
208
209 len = strlen(terminal->log_path) + sizeof(".1");
210 tmp = must_realloc(NULL, len);
211
212 ret = strnprintf(tmp, len, "%s.1", terminal->log_path);
213 if (ret < 0)
214 return -EFBIG;
215
216 close(terminal->log_fd);
217 terminal->log_fd = -1;
218 ret = lxc_unpriv(rename(terminal->log_path, tmp));
219 if (ret < 0)
220 return ret;
221
222 return lxc_terminal_create_log_file(terminal);
223 }
224
225 static int lxc_terminal_write_log_file(struct lxc_terminal *terminal, char *buf,
226 int bytes_read)
227 {
228 int ret;
229 struct stat st;
230 int64_t space_left = -1;
231
232 if (terminal->log_fd < 0)
233 return 0;
234
235 /* A log size <= 0 means that there's no limit on the size of the log
236 * file at which point we simply ignore whether the log is supposed to
237 * be rotated or not.
238 */
239 if (terminal->log_size <= 0)
240 return lxc_write_nointr(terminal->log_fd, buf, bytes_read);
241
242 /* Get current size of the log file. */
243 ret = fstat(terminal->log_fd, &st);
244 if (ret < 0) {
245 SYSERROR("Failed to stat the terminal log file descriptor");
246 return -1;
247 }
248
249 /* handle non-regular files */
250 if ((st.st_mode & S_IFMT) != S_IFREG) {
251 /* This isn't a regular file. so rotating the file seems a
252 * dangerous thing to do, size limits are also very
253 * questionable. Let's not risk anything and tell the user that
254 * they're requesting us to do weird stuff.
255 */
256 if (terminal->log_rotate > 0 || terminal->log_size > 0)
257 return -EINVAL;
258
259 /* I mean, sure log wherever you want to. */
260 return lxc_write_nointr(terminal->log_fd, buf, bytes_read);
261 }
262
263 space_left = terminal->log_size - st.st_size;
264
265 /* User doesn't want to rotate the log file and there's no more space
266 * left so simply truncate it.
267 */
268 if (space_left <= 0 && terminal->log_rotate <= 0) {
269 ret = lxc_terminal_truncate_log_file(terminal);
270 if (ret < 0)
271 return ret;
272
273 if ((uint64_t)bytes_read <= terminal->log_size)
274 return lxc_write_nointr(terminal->log_fd, buf, bytes_read);
275
276 /* Write as much as we can into the buffer and loose the rest. */
277 return lxc_write_nointr(terminal->log_fd, buf, terminal->log_size);
278 }
279
280 /* There's enough space left. */
281 if (bytes_read <= space_left)
282 return lxc_write_nointr(terminal->log_fd, buf, bytes_read);
283
284 /* There's not enough space left but at least write as much as we can
285 * into the old log file.
286 */
287 ret = lxc_write_nointr(terminal->log_fd, buf, space_left);
288 if (ret < 0)
289 return -1;
290
291 /* Calculate how many bytes we still need to write. */
292 bytes_read -= space_left;
293
294 /* There'd be more to write but we aren't instructed to rotate the log
295 * file so simply return. There's no error on our side here.
296 */
297 if (terminal->log_rotate > 0)
298 ret = lxc_terminal_rotate_log_file(terminal);
299 else
300 ret = lxc_terminal_truncate_log_file(terminal);
301 if (ret < 0)
302 return ret;
303
304 if (terminal->log_size < (uint64_t)bytes_read) {
305 /* Well, this is unfortunate because it means that there is more
306 * to write than the user has granted us space. There are
307 * multiple ways to handle this but let's use the simplest one:
308 * write as much as we can, tell the user that there was more
309 * stuff to write and move on.
310 * Note that this scenario shouldn't actually happen with the
311 * standard pty-based terminal that LXC allocates since it will
312 * be switched into raw mode. In raw mode only 1 byte at a time
313 * should be read and written.
314 */
315 WARN("Size of terminal log file is smaller than the bytes to write");
316 ret = lxc_write_nointr(terminal->log_fd, buf, terminal->log_size);
317 if (ret < 0)
318 return -1;
319 bytes_read -= ret;
320 return bytes_read;
321 }
322
323 /* Yay, we made it. */
324 ret = lxc_write_nointr(terminal->log_fd, buf, bytes_read);
325 if (ret < 0)
326 return -1;
327 bytes_read -= ret;
328 return bytes_read;
329 }
330
331 static int lxc_terminal_ptx_io(struct lxc_terminal *terminal)
332 {
333 char buf[LXC_TERMINAL_BUFFER_SIZE];
334 int r, w, w_log, w_rbuf;
335
336 w = r = lxc_read_nointr(terminal->ptx, buf, sizeof(buf));
337 if (r <= 0) {
338 if (errno == EWOULDBLOCK)
339 return 0;
340
341 return -1;
342 }
343 w_rbuf = w_log = 0;
344 /* write to peer first */
345 if (terminal->peer >= 0)
346 w = lxc_write_nointr(terminal->peer, buf, r);
347
348 /* write to terminal ringbuffer */
349 if (terminal->buffer_size > 0)
350 w_rbuf = lxc_ringbuf_write(&terminal->ringbuf, buf, r);
351
352 /* write to terminal log */
353 if (terminal->log_fd >= 0)
354 w_log = lxc_terminal_write_log_file(terminal, buf, r);
355
356 if (w != r)
357 WARN("Short write on terminal r:%d != w:%d", r, w);
358
359 if (w_rbuf < 0) {
360 errno = -w_rbuf;
361 SYSTRACE("Failed to write %d bytes to terminal ringbuffer", r);
362 }
363
364 if (w_log < 0)
365 TRACE("Failed to write %d bytes to terminal log", r);
366
367 return 0;
368 }
369
370 static int lxc_terminal_peer_io(struct lxc_terminal *terminal)
371 {
372 char buf[LXC_TERMINAL_BUFFER_SIZE];
373 int r, w;
374
375 w = r = lxc_read_nointr(terminal->peer, buf, sizeof(buf));
376 if (r <= 0) {
377 if (errno == EWOULDBLOCK)
378 return 0;
379
380 return -1;
381 }
382
383 w = lxc_write_nointr(terminal->ptx, buf, r);
384 if (w != r)
385 WARN("Short write on terminal r:%d != w:%d", r, w);
386
387 return 0;
388 }
389
390 static int lxc_terminal_ptx_io_handler(int fd, uint32_t events, void *data,
391 struct lxc_async_descr *descr)
392 {
393 struct lxc_terminal *terminal = data;
394 int ret;
395
396 ret = lxc_terminal_ptx_io(data);
397 if (ret < 0)
398 return log_info(LXC_MAINLOOP_CLOSE,
399 "Terminal client on fd %d has exited",
400 terminal->ptx);
401
402 return LXC_MAINLOOP_CONTINUE;
403 }
404
405 static int lxc_terminal_peer_io_handler(int fd, uint32_t events, void *data,
406 struct lxc_async_descr *descr)
407 {
408 struct lxc_terminal *terminal = data;
409 int ret;
410
411 ret = lxc_terminal_peer_io(data);
412 if (ret < 0)
413 return log_info(LXC_MAINLOOP_CLOSE,
414 "Terminal client on fd %d has exited",
415 terminal->peer);
416
417 return LXC_MAINLOOP_CONTINUE;
418 }
419
420 static int lxc_terminal_mainloop_add_peer(struct lxc_terminal *terminal)
421 {
422 int ret;
423
424 if (terminal->peer >= 0) {
425 if (fd_make_nonblocking(terminal->peer))
426 return log_error_errno(-1, errno, "Failed to make terminal peer fd non-blocking");
427
428 ret = lxc_mainloop_add_handler(terminal->descr, terminal->peer,
429 lxc_terminal_peer_io_handler,
430 default_cleanup_handler,
431 terminal, "lxc_terminal_peer_io_handler");
432 if (ret < 0) {
433 WARN("Failed to add terminal peer handler to mainloop");
434 return -1;
435 }
436 }
437
438 if (!terminal->tty_state || terminal->tty_state->sigfd < 0)
439 return 0;
440
441 ret = lxc_mainloop_add_handler(terminal->descr,
442 terminal->tty_state->sigfd,
443 lxc_terminal_signalfd_cb,
444 default_cleanup_handler,
445 terminal->tty_state,
446 "lxc_terminal_signalfd_cb");
447 if (ret < 0) {
448 WARN("Failed to add signal handler to mainloop");
449 return -1;
450 }
451
452 return 0;
453 }
454
455 int lxc_terminal_mainloop_add(struct lxc_async_descr *descr,
456 struct lxc_terminal *terminal)
457 {
458 int ret;
459
460 if (terminal->ptx < 0) {
461 INFO("Terminal is not initialized");
462 return 0;
463 }
464
465 if (fd_make_nonblocking(terminal->ptx))
466 return log_error_errno(-1, errno, "Failed to make terminal ptx fd non-blocking");
467
468 ret = lxc_mainloop_add_handler(descr, terminal->ptx,
469 lxc_terminal_ptx_io_handler,
470 default_cleanup_handler,
471 terminal, "lxc_terminal_ptx_io_handler");
472 if (ret < 0) {
473 ERROR("Failed to add handler for terminal ptx fd %d to mainloop", terminal->ptx);
474 return -1;
475 }
476
477 /* We cache the descr so that we can add an fd to it when someone
478 * does attach to it in lxc_terminal_allocate().
479 */
480 terminal->descr = descr;
481
482 return lxc_terminal_mainloop_add_peer(terminal);
483 }
484
485 int lxc_setup_tios(int fd, struct termios *oldtios)
486 {
487 int ret;
488 struct termios newtios;
489
490 if (!isatty(fd)) {
491 ERROR("File descriptor %d does not refer to a terminal", fd);
492 return -1;
493 }
494
495 /* Get current termios. */
496 ret = tcgetattr(fd, oldtios);
497 if (ret < 0) {
498 SYSERROR("Failed to get current terminal settings");
499 return -1;
500 }
501
502 /* ensure we don't end up in an endless loop:
503 * The kernel might fire SIGTTOU while an
504 * ioctl() in tcsetattr() is executed. When the ioctl()
505 * is resumed and retries, the signal handler interrupts it again.
506 */
507 signal (SIGTTIN, SIG_IGN);
508 signal (SIGTTOU, SIG_IGN);
509
510 newtios = *oldtios;
511
512 /* We use the same settings that ssh does. */
513 newtios.c_iflag |= IGNPAR;
514 newtios.c_iflag &= ~(ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF);
515 #ifdef IUCLC
516 newtios.c_iflag &= ~IUCLC;
517 #endif
518 newtios.c_lflag &= ~(TOSTOP | ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL);
519 #ifdef IEXTEN
520 newtios.c_lflag &= ~IEXTEN;
521 #endif
522 newtios.c_oflag |= ONLCR;
523 newtios.c_oflag |= OPOST;
524 newtios.c_cc[VMIN] = 1;
525 newtios.c_cc[VTIME] = 0;
526
527 /* Set new attributes. */
528 ret = tcsetattr(fd, TCSAFLUSH, &newtios);
529 if (ret < 0) {
530 ERROR("Failed to set new terminal settings");
531 return -1;
532 }
533
534 return 0;
535 }
536
537 static void lxc_terminal_peer_proxy_free(struct lxc_terminal *terminal)
538 {
539 lxc_terminal_signal_fini(terminal);
540
541 close(terminal->proxy.ptx);
542 terminal->proxy.ptx = -1;
543
544 close(terminal->proxy.pty);
545 terminal->proxy.pty = -1;
546
547 terminal->proxy.busy = -1;
548
549 terminal->proxy.name[0] = '\0';
550
551 terminal->peer = -1;
552 }
553
554 static int lxc_terminal_peer_proxy_alloc(struct lxc_terminal *terminal,
555 int sockfd)
556 {
557 int ret;
558 struct termios oldtermio;
559 struct lxc_terminal_state *ts;
560
561 if (terminal->ptx < 0) {
562 ERROR("Terminal not set up");
563 return -1;
564 }
565
566 if (terminal->proxy.busy != -1 || terminal->peer != -1) {
567 NOTICE("Terminal already in use");
568 return -1;
569 }
570
571 if (terminal->tty_state) {
572 ERROR("Terminal has already been initialized");
573 return -1;
574 }
575
576 /* This is the proxy terminal that will be given to the client, and
577 * that the real terminal ptx will send to / recv from.
578 */
579 ret = openpty(&terminal->proxy.ptx, &terminal->proxy.pty, NULL,
580 NULL, NULL);
581 if (ret < 0) {
582 SYSERROR("Failed to open proxy terminal");
583 return -1;
584 }
585
586 ret = ttyname_r(terminal->proxy.pty, terminal->proxy.name,
587 sizeof(terminal->proxy.name));
588 if (ret < 0) {
589 SYSERROR("Failed to retrieve name of proxy terminal pty");
590 goto on_error;
591 }
592
593 ret = lxc_fd_cloexec(terminal->proxy.ptx, true);
594 if (ret < 0) {
595 SYSERROR("Failed to set FD_CLOEXEC flag on proxy terminal ptx");
596 goto on_error;
597 }
598
599 ret = lxc_fd_cloexec(terminal->proxy.pty, true);
600 if (ret < 0) {
601 SYSERROR("Failed to set FD_CLOEXEC flag on proxy terminal pty");
602 goto on_error;
603 }
604
605 ret = lxc_setup_tios(terminal->proxy.pty, &oldtermio);
606 if (ret < 0)
607 goto on_error;
608
609 ts = lxc_terminal_signal_init(terminal->proxy.ptx, terminal->ptx);
610 if (!ts)
611 goto on_error;
612
613 terminal->tty_state = ts;
614 terminal->peer = terminal->proxy.pty;
615 terminal->proxy.busy = sockfd;
616 ret = lxc_terminal_mainloop_add_peer(terminal);
617 if (ret < 0)
618 goto on_error;
619
620 NOTICE("Opened proxy terminal with ptx fd %d and pty fd %d",
621 terminal->proxy.ptx, terminal->proxy.pty);
622 return 0;
623
624 on_error:
625 lxc_terminal_peer_proxy_free(terminal);
626 return -1;
627 }
628
629 int lxc_terminal_allocate(struct lxc_conf *conf, int sockfd, int *ttyreq)
630 {
631 size_t ttynum;
632 int ptxfd = -1;
633 struct lxc_tty_info *ttys = &conf->ttys;
634 struct lxc_terminal *terminal = &conf->console;
635
636 if (*ttyreq == 0) {
637 int ret;
638
639 ret = lxc_terminal_peer_proxy_alloc(terminal, sockfd);
640 if (ret < 0)
641 goto out;
642
643 ptxfd = terminal->proxy.ptx;
644 goto out;
645 }
646
647 if (*ttyreq > 0) {
648 if ((size_t)*ttyreq > ttys->max)
649 goto out;
650
651 if (ttys->tty[*ttyreq - 1].busy >= 0)
652 goto out;
653
654 /* The requested tty is available. */
655 ttynum = *ttyreq;
656 goto out_tty;
657 }
658
659 /* Search for next available tty, fixup index tty1 => [0]. */
660 for (ttynum = 1; ttynum <= ttys->max && ttys->tty[ttynum - 1].busy >= 0; ttynum++) {
661 ;
662 }
663
664 /* We didn't find any available slot for tty. */
665 if (ttynum > ttys->max)
666 goto out;
667
668 *ttyreq = (int)ttynum;
669
670 out_tty:
671 ttys->tty[ttynum - 1].busy = sockfd;
672 ptxfd = ttys->tty[ttynum - 1].ptx;
673
674 out:
675 return ptxfd;
676 }
677
678 void lxc_terminal_free(struct lxc_conf *conf, int fd)
679 {
680 struct lxc_tty_info *ttys = &conf->ttys;
681 struct lxc_terminal *terminal = &conf->console;
682
683 for (size_t i = 0; i < ttys->max; i++)
684 if (ttys->tty[i].busy == fd)
685 ttys->tty[i].busy = -1;
686
687 if (terminal->proxy.busy != fd)
688 return;
689
690 lxc_mainloop_del_handler(terminal->descr, terminal->proxy.pty);
691 lxc_terminal_peer_proxy_free(terminal);
692 }
693
694 static int lxc_terminal_peer_default(struct lxc_terminal *terminal)
695 {
696 struct lxc_terminal_state *ts;
697 const char *path;
698 int ret = 0;
699
700 if (terminal->path)
701 path = terminal->path;
702 else
703 path = "/dev/tty";
704
705 terminal->peer = lxc_unpriv(open(path, O_RDWR | O_CLOEXEC));
706 if (terminal->peer < 0) {
707 if (!terminal->path) {
708 errno = ENODEV;
709 SYSDEBUG("The process does not have a controlling terminal");
710 goto on_succes;
711 }
712
713 SYSERROR("Failed to open proxy terminal \"%s\"", path);
714 return -ENOTTY;
715 }
716 DEBUG("Using terminal \"%s\" as proxy", path);
717
718 if (!isatty(terminal->peer)) {
719 ERROR("File descriptor for \"%s\" does not refer to a terminal", path);
720 goto on_error_free_tios;
721 }
722
723 ts = lxc_terminal_signal_init(terminal->peer, terminal->ptx);
724 terminal->tty_state = ts;
725 if (!ts) {
726 WARN("Failed to install signal handler");
727 goto on_error_free_tios;
728 }
729
730 lxc_terminal_winsz(terminal->peer, terminal->ptx);
731
732 terminal->tios = malloc(sizeof(*terminal->tios));
733 if (!terminal->tios)
734 goto on_error_free_tios;
735
736 ret = lxc_setup_tios(terminal->peer, terminal->tios);
737 if (ret < 0)
738 goto on_error_close_peer;
739 else
740 goto on_succes;
741
742 on_error_free_tios:
743 free(terminal->tios);
744 terminal->tios = NULL;
745
746 on_error_close_peer:
747 close(terminal->peer);
748 terminal->peer = -1;
749 ret = -ENOTTY;
750
751 on_succes:
752 return ret;
753 }
754
755 int lxc_terminal_write_ringbuffer(struct lxc_terminal *terminal)
756 {
757 char *r_addr;
758 ssize_t ret;
759 uint64_t used;
760 struct lxc_ringbuf *buf = &terminal->ringbuf;
761
762 /* There's not log file where we can dump the ringbuffer to. */
763 if (terminal->log_fd < 0)
764 return 0;
765
766 used = lxc_ringbuf_used(buf);
767 if (used == 0)
768 return 0;
769
770 ret = lxc_terminal_truncate_log_file(terminal);
771 if (ret < 0)
772 return ret;
773
774 /* Write as much as we can without exceeding the limit. */
775 if (terminal->log_size < used)
776 used = terminal->log_size;
777
778 r_addr = lxc_ringbuf_get_read_addr(buf);
779 ret = lxc_write_nointr(terminal->log_fd, r_addr, used);
780 if (ret < 0)
781 return -EIO;
782
783 return 0;
784 }
785
786 void lxc_terminal_delete(struct lxc_terminal *terminal)
787 {
788 int ret;
789
790 ret = lxc_terminal_write_ringbuffer(terminal);
791 if (ret < 0)
792 WARN("Failed to write terminal log to disk");
793
794 if (terminal->tios && terminal->peer >= 0) {
795 ret = tcsetattr(terminal->peer, TCSAFLUSH, terminal->tios);
796 if (ret < 0)
797 SYSWARN("Failed to set old terminal settings");
798 }
799 free(terminal->tios);
800 terminal->tios = NULL;
801
802 if (terminal->peer >= 0)
803 close(terminal->peer);
804 terminal->peer = -1;
805
806 if (terminal->ptx >= 0)
807 close(terminal->ptx);
808 terminal->ptx = -1;
809
810 if (terminal->pty >= 0)
811 close(terminal->pty);
812 terminal->pty = -1;
813
814 terminal->pty_nr = -1;
815
816 if (terminal->log_fd >= 0)
817 close(terminal->log_fd);
818 terminal->log_fd = -1;
819 }
820
821 /**
822 * Note that this function needs to run before the mainloop starts. Since we
823 * register a handler for the terminal's ptxfd when we create the mainloop
824 * the terminal handler needs to see an allocated ringbuffer.
825 */
826 static int lxc_terminal_create_ringbuf(struct lxc_terminal *terminal)
827 {
828 int ret;
829 struct lxc_ringbuf *buf = &terminal->ringbuf;
830 uint64_t size = terminal->buffer_size;
831
832 /* no ringbuffer previously allocated and no ringbuffer requested */
833 if (!buf->addr && size <= 0)
834 return 0;
835
836 /* ringbuffer allocated but no new ringbuffer requested */
837 if (buf->addr && size <= 0) {
838 lxc_ringbuf_release(buf);
839 buf->addr = NULL;
840 buf->r_off = 0;
841 buf->w_off = 0;
842 buf->size = 0;
843 TRACE("Deallocated terminal ringbuffer");
844 return 0;
845 }
846
847 if (size <= 0)
848 return 0;
849
850 /* check wether the requested size for the ringbuffer has changed */
851 if (buf->addr && buf->size != size) {
852 TRACE("Terminal ringbuffer size changed from %" PRIu64
853 " to %" PRIu64 " bytes. Deallocating terminal ringbuffer",
854 buf->size, size);
855 lxc_ringbuf_release(buf);
856 }
857
858 ret = lxc_ringbuf_create(buf, size);
859 if (ret < 0) {
860 ERROR("Failed to setup %" PRIu64 " byte terminal ringbuffer", size);
861 return -1;
862 }
863
864 TRACE("Allocated %" PRIu64 " byte terminal ringbuffer", size);
865 return 0;
866 }
867
868 /**
869 * This is the terminal log file. Please note that the terminal log file is
870 * (implementation wise not content wise) independent of the terminal ringbuffer.
871 */
872 int lxc_terminal_create_log_file(struct lxc_terminal *terminal)
873 {
874 if (!terminal->log_path)
875 return 0;
876
877 terminal->log_fd = lxc_unpriv(open(terminal->log_path, O_CLOEXEC | O_RDWR | O_CREAT | O_APPEND, 0600));
878 if (terminal->log_fd < 0) {
879 SYSERROR("Failed to open terminal log file \"%s\"", terminal->log_path);
880 return -1;
881 }
882
883 DEBUG("Using \"%s\" as terminal log file", terminal->log_path);
884 return 0;
885 }
886
887 static int lxc_terminal_map_ids(struct lxc_conf *c, struct lxc_terminal *terminal)
888 {
889 int ret;
890
891 if (list_empty(&c->id_map))
892 return 0;
893
894 if (is_empty_string(terminal->name) && terminal->pty < 0)
895 return 0;
896
897 if (terminal->pty >= 0)
898 ret = userns_exec_mapped_root(NULL, terminal->pty, c);
899 else
900 ret = userns_exec_mapped_root(terminal->name, -EBADF, c);
901 if (ret < 0)
902 return log_error(-1, "Failed to chown terminal %d(%s)", terminal->pty,
903 !is_empty_string(terminal->name) ? terminal->name : "(null)");
904
905 TRACE("Chowned terminal %d(%s)", terminal->pty,
906 !is_empty_string(terminal->name) ? terminal->name : "(null)");
907
908 return 0;
909 }
910
911 static int lxc_terminal_create_foreign(struct lxc_conf *conf, struct lxc_terminal *terminal)
912 {
913 int ret;
914
915 ret = openpty(&terminal->ptx, &terminal->pty, NULL, NULL, NULL);
916 if (ret < 0) {
917 SYSERROR("Failed to open terminal");
918 return -1;
919 }
920
921 ret = lxc_terminal_map_ids(conf, terminal);
922 if (ret < 0) {
923 SYSERROR("Failed to change ownership of terminal multiplexer device");
924 goto err;
925 }
926
927 ret = ttyname_r(terminal->pty, terminal->name, sizeof(terminal->name));
928 if (ret < 0) {
929 SYSERROR("Failed to retrieve name of terminal pty");
930 goto err;
931 }
932
933 ret = lxc_fd_cloexec(terminal->ptx, true);
934 if (ret < 0) {
935 SYSERROR("Failed to set FD_CLOEXEC flag on terminal ptx");
936 goto err;
937 }
938
939 ret = lxc_fd_cloexec(terminal->pty, true);
940 if (ret < 0) {
941 SYSERROR("Failed to set FD_CLOEXEC flag on terminal pty");
942 goto err;
943 }
944
945 ret = lxc_terminal_peer_default(terminal);
946 if (ret < 0) {
947 ERROR("Failed to allocate proxy terminal");
948 goto err;
949 }
950
951 return 0;
952
953 err:
954 lxc_terminal_delete(terminal);
955 return -ENODEV;
956 }
957
958 int lxc_devpts_terminal(int devpts_fd, int *ret_ptx, int *ret_pty,
959 int *ret_pty_nr, bool require_tiocgptpeer)
960 {
961 __do_close int fd_devpts = -EBADF, fd_ptx = -EBADF,
962 fd_opath_pty = -EBADF, fd_pty = -EBADF;
963 int pty_nr = -1;
964 int ret;
965
966 /*
967 * When we aren't told what devpts instance to allocate from we assume
968 * it is the one in the caller's mount namespace.
969 * This poses a slight complication, a lot of distros will change
970 * permissions on /dev/ptmx so it can be opened by unprivileged users
971 * but will not change permissions on /dev/pts/ptmx itself. In
972 * addition, /dev/ptmx can either be a symlink, a bind-mount, or a
973 * separate device node. So we need to allow for fairly lax lookup.
974 */
975 if (devpts_fd < 0)
976 fd_ptx = open_at(-EBADF, "/dev/ptmx", PROTECT_OPEN_RW & ~O_NOFOLLOW,
977 PROTECT_LOOKUP_ABSOLUTE_XDEV_SYMLINKS, 0);
978 else
979 fd_ptx = open_beneath(devpts_fd, "ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC);
980 if (fd_ptx < 0) {
981 if (errno == ENOSPC)
982 return systrace("Exceeded number of allocatable terminals");
983
984 return syswarn("Failed to open terminal multiplexer device");
985 }
986
987 if (devpts_fd < 0) {
988 fd_devpts = open_at(-EBADF, "/dev/pts", PROTECT_OPATH_DIRECTORY,
989 PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
990 if (fd_devpts < 0)
991 return syswarn("Failed to open devpts instance");
992
993 if (!same_device(fd_devpts, "ptmx", fd_ptx, ""))
994 return syswarn("The acquired ptmx devices don't match");
995 devpts_fd = fd_devpts;
996 }
997
998 ret = unlockpt(fd_ptx);
999 if (ret < 0)
1000 return syswarn_set(-ENODEV, "Failed to unlock multiplexer device device");
1001
1002 fd_pty = ioctl(fd_ptx, TIOCGPTPEER, O_RDWR | O_NOCTTY | O_CLOEXEC);
1003 if (fd_pty < 0) {
1004 switch (errno) {
1005 case ENOTTY:
1006 SYSTRACE("Pure fd-based terminal allocation not possible");
1007 break;
1008 case ENOSPC:
1009 SYSTRACE("Exceeded number of allocatable terminals");
1010 break;
1011 default:
1012 SYSWARN("Failed to allocate new pty device");
1013 return -errno;
1014 }
1015
1016 /* The caller tells us that they trust the devpts instance. */
1017 if (require_tiocgptpeer)
1018 return ret_errno(ENODEV);
1019 }
1020
1021 ret = ioctl(fd_ptx, TIOCGPTN, &pty_nr);
1022 if (ret)
1023 return syswarn_set(-ENODEV, "Failed to retrieve name of terminal pty");
1024
1025 if (fd_pty < 0) {
1026 /*
1027 * If we end up it means that TIOCGPTPEER isn't supported but
1028 * the caller told us they trust the devpts instance so we use
1029 * the pty nr to open the pty side.
1030 */
1031 fd_pty = open_at(devpts_fd, fdstr(pty_nr), PROTECT_OPEN_RW,
1032 PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1033 if (fd_pty < 0)
1034 return syswarn_set(-ENODEV, "Failed to open terminal pty fd by path %d/%d",
1035 devpts_fd, pty_nr);
1036 } else {
1037 fd_opath_pty = open_at(devpts_fd, fdstr(pty_nr), PROTECT_OPATH_FILE,
1038 PROTECT_LOOKUP_ABSOLUTE_XDEV, 0);
1039 if (fd_opath_pty < 0)
1040 return syswarn_set(-ENODEV, "Failed to open terminal pty fd by path %d/%d",
1041 devpts_fd, pty_nr);
1042
1043 if (!same_file_lax(fd_pty, fd_opath_pty))
1044 return syswarn_set(-ENODEV, "Terminal file descriptor changed");
1045 }
1046
1047 *ret_ptx = move_fd(fd_ptx);
1048 *ret_pty = move_fd(fd_pty);
1049 *ret_pty_nr = pty_nr;
1050 return 0;
1051 }
1052
1053 int lxc_terminal_parent(struct lxc_conf *conf)
1054 {
1055 struct lxc_terminal *console = &conf->console;
1056 int ret;
1057
1058 if (!wants_console(&conf->console))
1059 return 0;
1060
1061 /* Allocate console from the container's devpts. */
1062 if (conf->pty_max > 1)
1063 return 0;
1064
1065 /* Allocate console for the container from the host's devpts. */
1066 ret = lxc_devpts_terminal(-EBADF, &console->ptx, &console->pty,
1067 &console->pty_nr, false);
1068 if (ret < 0)
1069 return syserror("Failed to allocate console");
1070
1071 ret = strnprintf(console->name, sizeof(console->name),
1072 "/dev/pts/%d", console->pty_nr);
1073 if (ret < 0)
1074 return syserror("Failed to create console path");
1075
1076 return lxc_terminal_map_ids(conf, &conf->console);
1077 }
1078
1079 static int lxc_terminal_create_native(const char *name, const char *lxcpath,
1080 struct lxc_terminal *terminal)
1081 {
1082 __do_close int devpts_fd = -EBADF;
1083 int ret;
1084
1085 devpts_fd = lxc_cmd_get_devpts_fd(name, lxcpath);
1086 if (devpts_fd < 0)
1087 return sysinfo("Failed to receive devpts fd");
1088
1089 ret = lxc_devpts_terminal(devpts_fd, &terminal->ptx, &terminal->pty,
1090 &terminal->pty_nr, true);
1091 if (ret < 0)
1092 return ret;
1093
1094 ret = strnprintf(terminal->name, sizeof(terminal->name),
1095 "/dev/pts/%d", terminal->pty_nr);
1096 if (ret < 0)
1097 return syserror("Failed to create path");
1098
1099 ret = lxc_terminal_peer_default(terminal);
1100 if (ret < 0) {
1101 lxc_terminal_delete(terminal);
1102 return syswarn_set(-ENODEV, "Failed to allocate proxy terminal");
1103 }
1104
1105 return 0;
1106 }
1107
1108 int lxc_terminal_create(const char *name, const char *lxcpath,
1109 struct lxc_conf *conf, struct lxc_terminal *terminal)
1110 {
1111 if (!lxc_terminal_create_native(name, lxcpath, terminal))
1112 return 0;
1113
1114 return lxc_terminal_create_foreign(conf, terminal);
1115 }
1116
1117 int lxc_terminal_setup(struct lxc_conf *conf)
1118 {
1119 int ret;
1120 struct lxc_terminal *terminal = &conf->console;
1121
1122 if (terminal->path && strequal(terminal->path, "none"))
1123 return log_info(0, "No terminal requested");
1124
1125 ret = lxc_terminal_peer_default(terminal);
1126 if (ret < 0)
1127 goto err;
1128
1129 ret = lxc_terminal_create_log_file(terminal);
1130 if (ret < 0)
1131 goto err;
1132
1133 ret = lxc_terminal_create_ringbuf(terminal);
1134 if (ret < 0)
1135 goto err;
1136
1137 return 0;
1138
1139 err:
1140 lxc_terminal_delete(terminal);
1141 return -ENODEV;
1142 }
1143
1144 static bool __terminal_dup2(int duplicate, int original)
1145 {
1146 int ret;
1147
1148 if (!isatty(original))
1149 return true;
1150
1151 ret = dup2(duplicate, original);
1152 if (ret < 0) {
1153 SYSERROR("Failed to dup2(%d, %d)", duplicate, original);
1154 return false;
1155 }
1156
1157 return true;
1158 }
1159
1160 int lxc_terminal_set_stdfds(int fd)
1161 {
1162 int i;
1163
1164 if (fd < 0)
1165 return 0;
1166
1167 for (i = 0; i < 3; i++)
1168 if (!__terminal_dup2(fd, (int[]){STDIN_FILENO, STDOUT_FILENO,
1169 STDERR_FILENO}[i]))
1170 return -1;
1171
1172 return 0;
1173 }
1174
1175 int lxc_terminal_stdin_cb(int fd, uint32_t events, void *cbdata,
1176 struct lxc_async_descr *descr)
1177 {
1178 int ret;
1179 char c;
1180 struct lxc_terminal_state *ts = cbdata;
1181
1182 if (fd != ts->stdinfd)
1183 return LXC_MAINLOOP_CLOSE;
1184
1185 ret = lxc_read_nointr(ts->stdinfd, &c, 1);
1186 if (ret <= 0)
1187 return LXC_MAINLOOP_CLOSE;
1188
1189 if (ts->escape >= 1) {
1190 /* we want to exit the terminal with Ctrl+a q */
1191 if (c == ts->escape && !ts->saw_escape) {
1192 ts->saw_escape = 1;
1193 return LXC_MAINLOOP_CONTINUE;
1194 }
1195
1196 if (c == 'q' && ts->saw_escape)
1197 return LXC_MAINLOOP_CLOSE;
1198
1199 ts->saw_escape = 0;
1200 }
1201
1202 ret = lxc_write_nointr(ts->ptxfd, &c, 1);
1203 if (ret <= 0)
1204 return LXC_MAINLOOP_CLOSE;
1205
1206 return LXC_MAINLOOP_CONTINUE;
1207 }
1208
1209 int lxc_terminal_ptx_cb(int fd, uint32_t events, void *cbdata,
1210 struct lxc_async_descr *descr)
1211 {
1212 int r, w;
1213 char buf[LXC_TERMINAL_BUFFER_SIZE];
1214 struct lxc_terminal_state *ts = cbdata;
1215
1216 if (fd != ts->ptxfd)
1217 return LXC_MAINLOOP_CLOSE;
1218
1219 r = lxc_read_nointr(fd, buf, sizeof(buf));
1220 if (r <= 0)
1221 return LXC_MAINLOOP_CLOSE;
1222
1223 w = lxc_write_nointr(ts->stdoutfd, buf, r);
1224 if (w <= 0 || w != r)
1225 return LXC_MAINLOOP_CLOSE;
1226
1227 return LXC_MAINLOOP_CONTINUE;
1228 }
1229
1230 int lxc_terminal_getfd(struct lxc_container *c, int *ttynum, int *ptxfd)
1231 {
1232 return lxc_cmd_get_tty_fd(c->name, ttynum, ptxfd, c->config_path);
1233 }
1234
1235 int lxc_console(struct lxc_container *c, int ttynum,
1236 int stdinfd, int stdoutfd, int stderrfd,
1237 int escape)
1238 {
1239 int ptxfd, ret, ttyfd;
1240 struct lxc_async_descr descr;
1241 struct termios oldtios;
1242 struct lxc_terminal_state *ts;
1243 struct lxc_terminal terminal = {
1244 .tty_state = NULL,
1245 };
1246 int istty = 0;
1247
1248 ttyfd = lxc_cmd_get_tty_fd(c->name, &ttynum, &ptxfd, c->config_path);
1249 if (ttyfd < 0)
1250 return -1;
1251
1252 ret = setsid();
1253 if (ret < 0)
1254 TRACE("Process is already group leader");
1255
1256 ts = lxc_terminal_signal_init(stdinfd, ptxfd);
1257 if (!ts) {
1258 ret = -1;
1259 goto close_fds;
1260 }
1261 terminal.tty_state = ts;
1262 ts->escape = escape;
1263 ts->stdoutfd = stdoutfd;
1264
1265 istty = isatty(stdinfd);
1266 if (istty) {
1267 lxc_terminal_winsz(stdinfd, ptxfd);
1268 lxc_terminal_winsz(ts->stdinfd, ts->ptxfd);
1269 } else {
1270 INFO("File descriptor %d does not refer to a terminal", stdinfd);
1271 }
1272
1273 ret = lxc_mainloop_open(&descr);
1274 if (ret) {
1275 ERROR("Failed to create mainloop");
1276 goto sigwinch_fini;
1277 }
1278
1279 if (ts->sigfd != -1) {
1280 ret = lxc_mainloop_add_handler(&descr, ts->sigfd,
1281 lxc_terminal_signalfd_cb,
1282 default_cleanup_handler,
1283 ts, "lxc_terminal_signalfd_cb");
1284 if (ret < 0) {
1285 ERROR("Failed to add signal handler to mainloop");
1286 goto close_mainloop;
1287 }
1288 }
1289
1290 ret = lxc_mainloop_add_handler(&descr, ts->stdinfd,
1291 lxc_terminal_stdin_cb,
1292 default_cleanup_handler,
1293 ts, "lxc_terminal_stdin_cb");
1294 if (ret < 0) {
1295 ERROR("Failed to add stdin handler");
1296 goto close_mainloop;
1297 }
1298
1299 ret = lxc_mainloop_add_handler(&descr, ts->ptxfd,
1300 lxc_terminal_ptx_cb,
1301 default_cleanup_handler,
1302 ts, "lxc_terminal_ptx_cb");
1303 if (ret < 0) {
1304 ERROR("Failed to add ptx handler");
1305 goto close_mainloop;
1306 }
1307
1308 if (ts->escape >= 1) {
1309 fprintf(stderr,
1310 "\n"
1311 "Connected to tty %1$d\n"
1312 "Type <Ctrl+%2$c q> to exit the console, "
1313 "<Ctrl+%2$c Ctrl+%2$c> to enter Ctrl+%2$c itself\n",
1314 ttynum, 'a' + escape - 1);
1315 }
1316
1317 if (istty) {
1318 ret = lxc_setup_tios(stdinfd, &oldtios);
1319 if (ret < 0)
1320 goto close_mainloop;
1321 }
1322
1323 ret = lxc_mainloop(&descr, -1);
1324 if (ret < 0) {
1325 ERROR("The mainloop returned an error");
1326 goto restore_tios;
1327 }
1328
1329 ret = 0;
1330
1331 restore_tios:
1332 if (istty) {
1333 istty = tcsetattr(stdinfd, TCSAFLUSH, &oldtios);
1334 if (istty < 0)
1335 SYSWARN("Failed to restore terminal properties");
1336 }
1337
1338 close_mainloop:
1339 lxc_mainloop_close(&descr);
1340
1341 sigwinch_fini:
1342 lxc_terminal_signal_fini(&terminal);
1343
1344 close_fds:
1345 close(ptxfd);
1346 close(ttyfd);
1347
1348 return ret;
1349 }
1350
1351 int lxc_make_controlling_terminal(int fd)
1352 {
1353 int ret;
1354
1355 setsid();
1356
1357 ret = ioctl(fd, TIOCSCTTY, (char *)NULL);
1358 if (ret < 0)
1359 return -1;
1360
1361 return 0;
1362 }
1363
1364 int lxc_terminal_prepare_login(int fd)
1365 {
1366 int ret;
1367
1368 ret = lxc_make_controlling_terminal(fd);
1369 if (ret < 0)
1370 return -1;
1371
1372 ret = lxc_terminal_set_stdfds(fd);
1373 if (ret < 0)
1374 return -1;
1375
1376 if (fd > STDERR_FILENO)
1377 close(fd);
1378
1379 return 0;
1380 }
1381
1382 void lxc_terminal_info_init(struct lxc_terminal_info *terminal)
1383 {
1384 terminal->name[0] = '\0';
1385 terminal->ptx = -EBADF;
1386 terminal->pty = -EBADF;
1387 terminal->busy = -1;
1388 terminal->pty_nr = -1;
1389 }
1390
1391 void lxc_terminal_init(struct lxc_terminal *terminal)
1392 {
1393 memset(terminal, 0, sizeof(*terminal));
1394 terminal->pty_nr = -1;
1395 terminal->pty = -EBADF;
1396 terminal->ptx = -EBADF;
1397 terminal->peer = -EBADF;
1398 terminal->log_fd = -EBADF;
1399 lxc_terminal_info_init(&terminal->proxy);
1400 }
1401
1402 void lxc_terminal_conf_free(struct lxc_terminal *terminal)
1403 {
1404 free(terminal->log_path);
1405 free(terminal->path);
1406 if (terminal->buffer_size > 0 && terminal->ringbuf.addr)
1407 lxc_ringbuf_release(&terminal->ringbuf);
1408 lxc_terminal_signal_fini(terminal);
1409 }