1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <limits.h>
6 #include <signal.h>
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/epoll.h>
12 #include <sys/ioctl.h>
13 #include <sys/time.h>
14 #include <termios.h>
15 #include <unistd.h>
16
17 #include "sd-event.h"
18
19 #include "alloc-util.h"
20 #include "errno-util.h"
21 #include "fd-util.h"
22 #include "log.h"
23 #include "macro.h"
24 #include "ptyfwd.h"
25 #include "terminal-util.h"
26 #include "time-util.h"
27
28 struct PTYForward {
29 sd_event *event;
30
31 int input_fd;
32 int output_fd;
33 int master;
34
35 PTYForwardFlags flags;
36
37 sd_event_source *stdin_event_source;
38 sd_event_source *stdout_event_source;
39 sd_event_source *master_event_source;
40
41 sd_event_source *sigwinch_event_source;
42
43 struct termios saved_stdin_attr;
44 struct termios saved_stdout_attr;
45
46 bool close_input_fd:1;
47 bool close_output_fd:1;
48
49 bool saved_stdin:1;
50 bool saved_stdout:1;
51
52 bool stdin_readable:1;
53 bool stdin_hangup:1;
54 bool stdout_writable:1;
55 bool stdout_hangup:1;
56 bool master_readable:1;
57 bool master_writable:1;
58 bool master_hangup:1;
59
60 bool read_from_master:1;
61
62 bool done:1;
63 bool drain:1;
64
65 bool last_char_set:1;
66 char last_char;
67
68 char in_buffer[LINE_MAX], out_buffer[LINE_MAX];
69 size_t in_buffer_full, out_buffer_full;
70
71 usec_t escape_timestamp;
72 unsigned escape_counter;
73
74 PTYForwardHandler handler;
75 void *userdata;
76 };
77
78 #define ESCAPE_USEC (1*USEC_PER_SEC)
79
pty_forward_disconnect(PTYForward * f)80 static void pty_forward_disconnect(PTYForward *f) {
81
82 if (!f)
83 return;
84
85 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
86 f->stdout_event_source = sd_event_source_unref(f->stdout_event_source);
87
88 f->master_event_source = sd_event_source_unref(f->master_event_source);
89 f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source);
90 f->event = sd_event_unref(f->event);
91
92 if (f->output_fd >= 0) {
93 if (f->saved_stdout)
94 (void) tcsetattr(f->output_fd, TCSANOW, &f->saved_stdout_attr);
95
96 /* STDIN/STDOUT should not be non-blocking normally, so let's reset it */
97 (void) fd_nonblock(f->output_fd, false);
98 if (f->close_output_fd)
99 f->output_fd = safe_close(f->output_fd);
100 }
101
102 if (f->input_fd >= 0) {
103 if (f->saved_stdin)
104 (void) tcsetattr(f->input_fd, TCSANOW, &f->saved_stdin_attr);
105
106 (void) fd_nonblock(f->input_fd, false);
107 if (f->close_input_fd)
108 f->input_fd = safe_close(f->input_fd);
109 }
110
111 f->saved_stdout = f->saved_stdin = false;
112 }
113
pty_forward_done(PTYForward * f,int rcode)114 static int pty_forward_done(PTYForward *f, int rcode) {
115 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
116 assert(f);
117
118 if (f->done)
119 return 0;
120
121 e = sd_event_ref(f->event);
122
123 f->done = true;
124 pty_forward_disconnect(f);
125
126 if (f->handler)
127 return f->handler(f, rcode, f->userdata);
128 else
129 return sd_event_exit(e, rcode < 0 ? EXIT_FAILURE : rcode);
130 }
131
look_for_escape(PTYForward * f,const char * buffer,size_t n)132 static bool look_for_escape(PTYForward *f, const char *buffer, size_t n) {
133 const char *p;
134
135 assert(f);
136 assert(buffer);
137 assert(n > 0);
138
139 for (p = buffer; p < buffer + n; p++) {
140
141 /* Check for ^] */
142 if (*p == 0x1D) {
143 usec_t nw = now(CLOCK_MONOTONIC);
144
145 if (f->escape_counter == 0 || nw > f->escape_timestamp + ESCAPE_USEC) {
146 f->escape_timestamp = nw;
147 f->escape_counter = 1;
148 } else {
149 (f->escape_counter)++;
150
151 if (f->escape_counter >= 3)
152 return true;
153 }
154 } else {
155 f->escape_timestamp = 0;
156 f->escape_counter = 0;
157 }
158 }
159
160 return false;
161 }
162
ignore_vhangup(PTYForward * f)163 static bool ignore_vhangup(PTYForward *f) {
164 assert(f);
165
166 if (f->flags & PTY_FORWARD_IGNORE_VHANGUP)
167 return true;
168
169 if ((f->flags & PTY_FORWARD_IGNORE_INITIAL_VHANGUP) && !f->read_from_master)
170 return true;
171
172 return false;
173 }
174
drained(PTYForward * f)175 static bool drained(PTYForward *f) {
176 int q = 0;
177
178 assert(f);
179
180 if (f->out_buffer_full > 0)
181 return false;
182
183 if (f->master_readable)
184 return false;
185
186 if (ioctl(f->master, TIOCINQ, &q) < 0)
187 log_debug_errno(errno, "TIOCINQ failed on master: %m");
188 else if (q > 0)
189 return false;
190
191 if (ioctl(f->master, TIOCOUTQ, &q) < 0)
192 log_debug_errno(errno, "TIOCOUTQ failed on master: %m");
193 else if (q > 0)
194 return false;
195
196 return true;
197 }
198
shovel(PTYForward * f)199 static int shovel(PTYForward *f) {
200 ssize_t k;
201
202 assert(f);
203
204 while ((f->stdin_readable && f->in_buffer_full <= 0) ||
205 (f->master_writable && f->in_buffer_full > 0) ||
206 (f->master_readable && f->out_buffer_full <= 0) ||
207 (f->stdout_writable && f->out_buffer_full > 0)) {
208
209 if (f->stdin_readable && f->in_buffer_full < LINE_MAX) {
210
211 k = read(f->input_fd, f->in_buffer + f->in_buffer_full, LINE_MAX - f->in_buffer_full);
212 if (k < 0) {
213
214 if (errno == EAGAIN)
215 f->stdin_readable = false;
216 else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) {
217 f->stdin_readable = false;
218 f->stdin_hangup = true;
219
220 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
221 } else {
222 log_error_errno(errno, "read(): %m");
223 return pty_forward_done(f, -errno);
224 }
225 } else if (k == 0) {
226 /* EOF on stdin */
227 f->stdin_readable = false;
228 f->stdin_hangup = true;
229
230 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
231 } else {
232 /* Check if ^] has been pressed three times within one second. If we get this we quite
233 * immediately. */
234 if (look_for_escape(f, f->in_buffer + f->in_buffer_full, k))
235 return pty_forward_done(f, -ECANCELED);
236
237 f->in_buffer_full += (size_t) k;
238 }
239 }
240
241 if (f->master_writable && f->in_buffer_full > 0) {
242
243 k = write(f->master, f->in_buffer, f->in_buffer_full);
244 if (k < 0) {
245
246 if (IN_SET(errno, EAGAIN, EIO))
247 f->master_writable = false;
248 else if (IN_SET(errno, EPIPE, ECONNRESET)) {
249 f->master_writable = f->master_readable = false;
250 f->master_hangup = true;
251
252 f->master_event_source = sd_event_source_unref(f->master_event_source);
253 } else {
254 log_error_errno(errno, "write(): %m");
255 return pty_forward_done(f, -errno);
256 }
257 } else {
258 assert(f->in_buffer_full >= (size_t) k);
259 memmove(f->in_buffer, f->in_buffer + k, f->in_buffer_full - k);
260 f->in_buffer_full -= k;
261 }
262 }
263
264 if (f->master_readable && f->out_buffer_full < LINE_MAX) {
265
266 k = read(f->master, f->out_buffer + f->out_buffer_full, LINE_MAX - f->out_buffer_full);
267 if (k < 0) {
268
269 /* Note that EIO on the master device
270 * might be caused by vhangup() or
271 * temporary closing of everything on
272 * the other side, we treat it like
273 * EAGAIN here and try again, unless
274 * ignore_vhangup is off. */
275
276 if (errno == EAGAIN || (errno == EIO && ignore_vhangup(f)))
277 f->master_readable = false;
278 else if (IN_SET(errno, EPIPE, ECONNRESET, EIO)) {
279 f->master_readable = f->master_writable = false;
280 f->master_hangup = true;
281
282 f->master_event_source = sd_event_source_unref(f->master_event_source);
283 } else {
284 log_error_errno(errno, "read(): %m");
285 return pty_forward_done(f, -errno);
286 }
287 } else {
288 f->read_from_master = true;
289 f->out_buffer_full += (size_t) k;
290 }
291 }
292
293 if (f->stdout_writable && f->out_buffer_full > 0) {
294
295 k = write(f->output_fd, f->out_buffer, f->out_buffer_full);
296 if (k < 0) {
297
298 if (errno == EAGAIN)
299 f->stdout_writable = false;
300 else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) {
301 f->stdout_writable = false;
302 f->stdout_hangup = true;
303 f->stdout_event_source = sd_event_source_unref(f->stdout_event_source);
304 } else {
305 log_error_errno(errno, "write(): %m");
306 return pty_forward_done(f, -errno);
307 }
308
309 } else {
310
311 if (k > 0) {
312 f->last_char = f->out_buffer[k-1];
313 f->last_char_set = true;
314 }
315
316 assert(f->out_buffer_full >= (size_t) k);
317 memmove(f->out_buffer, f->out_buffer + k, f->out_buffer_full - k);
318 f->out_buffer_full -= k;
319 }
320 }
321 }
322
323 if (f->stdin_hangup || f->stdout_hangup || f->master_hangup) {
324 /* Exit the loop if any side hung up and if there's
325 * nothing more to write or nothing we could write. */
326
327 if ((f->out_buffer_full <= 0 || f->stdout_hangup) &&
328 (f->in_buffer_full <= 0 || f->master_hangup))
329 return pty_forward_done(f, 0);
330 }
331
332 /* If we were asked to drain, and there's nothing more to handle from the master, then call the callback
333 * too. */
334 if (f->drain && drained(f))
335 return pty_forward_done(f, 0);
336
337 return 0;
338 }
339
on_master_event(sd_event_source * e,int fd,uint32_t revents,void * userdata)340 static int on_master_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
341 PTYForward *f = userdata;
342
343 assert(f);
344 assert(e);
345 assert(e == f->master_event_source);
346 assert(fd >= 0);
347 assert(fd == f->master);
348
349 if (revents & (EPOLLIN|EPOLLHUP))
350 f->master_readable = true;
351
352 if (revents & (EPOLLOUT|EPOLLHUP))
353 f->master_writable = true;
354
355 return shovel(f);
356 }
357
on_stdin_event(sd_event_source * e,int fd,uint32_t revents,void * userdata)358 static int on_stdin_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
359 PTYForward *f = userdata;
360
361 assert(f);
362 assert(e);
363 assert(e == f->stdin_event_source);
364 assert(fd >= 0);
365 assert(fd == f->input_fd);
366
367 if (revents & (EPOLLIN|EPOLLHUP))
368 f->stdin_readable = true;
369
370 return shovel(f);
371 }
372
on_stdout_event(sd_event_source * e,int fd,uint32_t revents,void * userdata)373 static int on_stdout_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
374 PTYForward *f = userdata;
375
376 assert(f);
377 assert(e);
378 assert(e == f->stdout_event_source);
379 assert(fd >= 0);
380 assert(fd == f->output_fd);
381
382 if (revents & (EPOLLOUT|EPOLLHUP))
383 f->stdout_writable = true;
384
385 return shovel(f);
386 }
387
on_sigwinch_event(sd_event_source * e,const struct signalfd_siginfo * si,void * userdata)388 static int on_sigwinch_event(sd_event_source *e, const struct signalfd_siginfo *si, void *userdata) {
389 PTYForward *f = userdata;
390 struct winsize ws;
391
392 assert(f);
393 assert(e);
394 assert(e == f->sigwinch_event_source);
395
396 /* The window size changed, let's forward that. */
397 if (ioctl(f->output_fd, TIOCGWINSZ, &ws) >= 0)
398 (void) ioctl(f->master, TIOCSWINSZ, &ws);
399
400 return 0;
401 }
402
pty_forward_new(sd_event * event,int master,PTYForwardFlags flags,PTYForward ** ret)403 int pty_forward_new(
404 sd_event *event,
405 int master,
406 PTYForwardFlags flags,
407 PTYForward **ret) {
408
409 _cleanup_(pty_forward_freep) PTYForward *f = NULL;
410 struct winsize ws;
411 int r;
412
413 f = new(PTYForward, 1);
414 if (!f)
415 return -ENOMEM;
416
417 *f = (struct PTYForward) {
418 .flags = flags,
419 .master = -1,
420 .input_fd = -1,
421 .output_fd = -1,
422 };
423
424 if (event)
425 f->event = sd_event_ref(event);
426 else {
427 r = sd_event_default(&f->event);
428 if (r < 0)
429 return r;
430 }
431
432 if (FLAGS_SET(flags, PTY_FORWARD_READ_ONLY))
433 f->output_fd = STDOUT_FILENO;
434 else {
435 /* If we shall be invoked in interactive mode, let's switch on non-blocking mode, so that we
436 * never end up staving one direction while we block on the other. However, let's be careful
437 * here and not turn on O_NONBLOCK for stdin/stdout directly, but of re-opened copies of
438 * them. This has two advantages: when we are killed abruptly the stdin/stdout fds won't be
439 * left in O_NONBLOCK state for the next process using them. In addition, if some process
440 * running in the background wants to continue writing to our stdout it can do so without
441 * being confused by O_NONBLOCK. */
442
443 f->input_fd = fd_reopen(STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
444 if (f->input_fd < 0) {
445 /* Handle failures gracefully, after all certain fd types cannot be reopened
446 * (sockets, …) */
447 log_debug_errno(f->input_fd, "Failed to reopen stdin, using original fd: %m");
448
449 r = fd_nonblock(STDIN_FILENO, true);
450 if (r < 0)
451 return r;
452
453 f->input_fd = STDIN_FILENO;
454 } else
455 f->close_input_fd = true;
456
457 f->output_fd = fd_reopen(STDOUT_FILENO, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
458 if (f->output_fd < 0) {
459 log_debug_errno(f->output_fd, "Failed to reopen stdout, using original fd: %m");
460
461 r = fd_nonblock(STDOUT_FILENO, true);
462 if (r < 0)
463 return r;
464
465 f->output_fd = STDOUT_FILENO;
466 } else
467 f->close_output_fd = true;
468 }
469
470 r = fd_nonblock(master, true);
471 if (r < 0)
472 return r;
473
474 f->master = master;
475
476 if (ioctl(f->output_fd, TIOCGWINSZ, &ws) < 0)
477 /* If we can't get the resolution from the output fd, then use our internal, regular width/height,
478 * i.e. something derived from $COLUMNS and $LINES if set. */
479 ws = (struct winsize) {
480 .ws_row = lines(),
481 .ws_col = columns(),
482 };
483
484 (void) ioctl(master, TIOCSWINSZ, &ws);
485
486 if (!(flags & PTY_FORWARD_READ_ONLY)) {
487 assert(f->input_fd >= 0);
488
489 if (tcgetattr(f->input_fd, &f->saved_stdin_attr) >= 0) {
490 struct termios raw_stdin_attr;
491
492 f->saved_stdin = true;
493
494 raw_stdin_attr = f->saved_stdin_attr;
495 cfmakeraw(&raw_stdin_attr);
496 raw_stdin_attr.c_oflag = f->saved_stdin_attr.c_oflag;
497 tcsetattr(f->input_fd, TCSANOW, &raw_stdin_attr);
498 }
499
500 if (tcgetattr(f->output_fd, &f->saved_stdout_attr) >= 0) {
501 struct termios raw_stdout_attr;
502
503 f->saved_stdout = true;
504
505 raw_stdout_attr = f->saved_stdout_attr;
506 cfmakeraw(&raw_stdout_attr);
507 raw_stdout_attr.c_iflag = f->saved_stdout_attr.c_iflag;
508 raw_stdout_attr.c_lflag = f->saved_stdout_attr.c_lflag;
509 tcsetattr(f->output_fd, TCSANOW, &raw_stdout_attr);
510 }
511
512 r = sd_event_add_io(f->event, &f->stdin_event_source, f->input_fd, EPOLLIN|EPOLLET, on_stdin_event, f);
513 if (r < 0 && r != -EPERM)
514 return r;
515
516 if (r >= 0)
517 (void) sd_event_source_set_description(f->stdin_event_source, "ptyfwd-stdin");
518 }
519
520 r = sd_event_add_io(f->event, &f->stdout_event_source, f->output_fd, EPOLLOUT|EPOLLET, on_stdout_event, f);
521 if (r == -EPERM)
522 /* stdout without epoll support. Likely redirected to regular file. */
523 f->stdout_writable = true;
524 else if (r < 0)
525 return r;
526 else
527 (void) sd_event_source_set_description(f->stdout_event_source, "ptyfwd-stdout");
528
529 r = sd_event_add_io(f->event, &f->master_event_source, master, EPOLLIN|EPOLLOUT|EPOLLET, on_master_event, f);
530 if (r < 0)
531 return r;
532
533 (void) sd_event_source_set_description(f->master_event_source, "ptyfwd-master");
534
535 r = sd_event_add_signal(f->event, &f->sigwinch_event_source, SIGWINCH, on_sigwinch_event, f);
536 if (r < 0)
537 return r;
538
539 (void) sd_event_source_set_description(f->sigwinch_event_source, "ptyfwd-sigwinch");
540
541 *ret = TAKE_PTR(f);
542
543 return 0;
544 }
545
pty_forward_free(PTYForward * f)546 PTYForward *pty_forward_free(PTYForward *f) {
547 pty_forward_disconnect(f);
548 return mfree(f);
549 }
550
pty_forward_get_last_char(PTYForward * f,char * ch)551 int pty_forward_get_last_char(PTYForward *f, char *ch) {
552 assert(f);
553 assert(ch);
554
555 if (!f->last_char_set)
556 return -ENXIO;
557
558 *ch = f->last_char;
559 return 0;
560 }
561
pty_forward_set_ignore_vhangup(PTYForward * f,bool b)562 int pty_forward_set_ignore_vhangup(PTYForward *f, bool b) {
563 int r;
564
565 assert(f);
566
567 if (!!(f->flags & PTY_FORWARD_IGNORE_VHANGUP) == b)
568 return 0;
569
570 SET_FLAG(f->flags, PTY_FORWARD_IGNORE_VHANGUP, b);
571
572 if (!ignore_vhangup(f)) {
573
574 /* We shall now react to vhangup()s? Let's check
575 * immediately if we might be in one */
576
577 f->master_readable = true;
578 r = shovel(f);
579 if (r < 0)
580 return r;
581 }
582
583 return 0;
584 }
585
pty_forward_get_ignore_vhangup(PTYForward * f)586 bool pty_forward_get_ignore_vhangup(PTYForward *f) {
587 assert(f);
588
589 return !!(f->flags & PTY_FORWARD_IGNORE_VHANGUP);
590 }
591
pty_forward_is_done(PTYForward * f)592 bool pty_forward_is_done(PTYForward *f) {
593 assert(f);
594
595 return f->done;
596 }
597
pty_forward_set_handler(PTYForward * f,PTYForwardHandler cb,void * userdata)598 void pty_forward_set_handler(PTYForward *f, PTYForwardHandler cb, void *userdata) {
599 assert(f);
600
601 f->handler = cb;
602 f->userdata = userdata;
603 }
604
pty_forward_drain(PTYForward * f)605 bool pty_forward_drain(PTYForward *f) {
606 assert(f);
607
608 /* Starts draining the forwarder. Specifically:
609 *
610 * - Returns true if there are no unprocessed bytes from the pty, false otherwise
611 *
612 * - Makes sure the handler function is called the next time the number of unprocessed bytes hits zero
613 */
614
615 f->drain = true;
616 return drained(f);
617 }
618
pty_forward_set_priority(PTYForward * f,int64_t priority)619 int pty_forward_set_priority(PTYForward *f, int64_t priority) {
620 int r;
621 assert(f);
622
623 if (f->stdin_event_source) {
624 r = sd_event_source_set_priority(f->stdin_event_source, priority);
625 if (r < 0)
626 return r;
627 }
628
629 r = sd_event_source_set_priority(f->stdout_event_source, priority);
630 if (r < 0)
631 return r;
632
633 r = sd_event_source_set_priority(f->master_event_source, priority);
634 if (r < 0)
635 return r;
636
637 r = sd_event_source_set_priority(f->sigwinch_event_source, priority);
638 if (r < 0)
639 return r;
640
641 return 0;
642 }
643
pty_forward_set_width_height(PTYForward * f,unsigned width,unsigned height)644 int pty_forward_set_width_height(PTYForward *f, unsigned width, unsigned height) {
645 struct winsize ws;
646
647 assert(f);
648
649 if (width == UINT_MAX && height == UINT_MAX)
650 return 0; /* noop */
651
652 if (width != UINT_MAX &&
653 (width == 0 || width > USHRT_MAX))
654 return -ERANGE;
655
656 if (height != UINT_MAX &&
657 (height == 0 || height > USHRT_MAX))
658 return -ERANGE;
659
660 if (width == UINT_MAX || height == UINT_MAX) {
661 if (ioctl(f->master, TIOCGWINSZ, &ws) < 0)
662 return -errno;
663
664 if (width != UINT_MAX)
665 ws.ws_col = width;
666 if (height != UINT_MAX)
667 ws.ws_row = height;
668 } else
669 ws = (struct winsize) {
670 .ws_row = height,
671 .ws_col = width,
672 };
673
674 if (ioctl(f->master, TIOCSWINSZ, &ws) < 0)
675 return -errno;
676
677 /* Make sure we ignore SIGWINCH window size events from now on */
678 f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source);
679
680 return 0;
681 }
682