Debian Codegraph @

src/shared/ptyfwd.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <signal.h>
5 #include <string.h>
6 #include <sys/ioctl.h>
7 #include <termios.h>
8 #include <unistd.h>
9
10 #include "sd-event.h"
11
12 #include "alloc-util.h"
13 #include "ansi-color.h"
14 #include "env-util.h"
15 #include "errno-util.h"
16 #include "extract-word.h"
17 #include "fd-util.h"
18 #include "glyph-util.h"
19 #include "hostname-setup.h"
20 #include "io-util.h"
21 #include "log.h"
22 #include "pretty-print.h"
23 #include "ptyfwd.h"
24 #include "stat-util.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "terminal-util.h"
28 #include "time-util.h"
29
30 typedef enum AnsiColorState {
31 ANSI_COLOR_STATE_TEXT,
32 ANSI_COLOR_STATE_ESC,
33 ANSI_COLOR_STATE_CSI_SEQUENCE,
34 ANSI_COLOR_STATE_OSC_SEQUENCE,
35 ANSI_COLOR_STATE_OSC_SEQUENCE_TERMINATING,
36 _ANSI_COLOR_STATE_MAX,
37 _ANSI_COLOR_STATE_INVALID = -EINVAL,
38 } AnsiColorState;
39
40 #define ANSI_SEQUENCE_LENGTH_MAX 192U
41 #define ANSI_SEQUENCE_WINDOW_TITLE_MAX 128U
42
43 assert_cc(ANSI_SEQUENCE_LENGTH_MAX > ANSI_SEQUENCE_WINDOW_TITLE_MAX);
44
45 /* We don't list SIGHUP here because that's what you get when your tty has a hangup, and if we do we'll close
46 * the pty too which already generates a hangup, and thus a SIGHUP, which means we'd generate SIGHUP twice,
47 * once by us, and once by the kernel. */
48 const int pty_forward_signals[N_PTY_FORWARD_SIGNALS] = { SIGTERM, SIGINT, SIGQUIT, SIGTSTP, SIGCONT, SIGUSR1, SIGUSR2 };
49
50 struct PTYForward {
51 sd_event *event;
52
53 int input_fd;
54 int output_fd;
55 int master;
56
57 PTYForwardFlags flags;
58
59 sd_event_source *stdin_event_source;
60 sd_event_source *stdout_event_source;
61 sd_event_source *master_event_source;
62 sd_event_source *sigwinch_event_source;
63 sd_event_source *exit_event_source;
64 sd_event_source *defer_event_source;
65
66 struct termios saved_stdin_attr;
67 struct termios saved_stdout_attr;
68
69 bool close_input_fd:1;
70 bool close_output_fd:1;
71
72 bool saved_stdin:1;
73 bool saved_stdout:1;
74
75 bool stdin_readable:1;
76 bool stdin_hangup:1;
77 bool stdout_writable:1;
78 bool stdout_hangup:1;
79 bool master_readable:1;
80 bool master_writable:1;
81 bool master_hangup:1;
82
83 bool read_from_master:1;
84
85 bool done:1;
86 bool drain:1;
87
88 bool last_char_set:1;
89 char last_char;
90 char last_char_safe;
91
92 char in_buffer[LINE_MAX], *out_buffer;
93 size_t out_buffer_size;
94 size_t in_buffer_full, out_buffer_full;
95 size_t out_buffer_write_len; /* The length of the output in the buffer except for the trailing
96 * truncated OSC, CSI, or some (but not all) ESC sequence. */
97
98 usec_t escape_timestamp;
99 unsigned escape_counter;
100
101 PTYForwardHangupHandler hangup_handler;
102 void *hangup_userdata;
103 PTYForwardHotkeyHandler hotkey_handler;
104 void *hotkey_userdata;
105
106 char *background_color;
107 AnsiColorState ansi_color_state;
108 char *csi_sequence;
109 char *osc_sequence;
110
111 char *title; /* Window title to show by default */
112 char *title_prefix; /* If terminal client overrides window title, prefix this string */
113 };
114
115 #define ESCAPE_USEC (1*USEC_PER_SEC)
116
117 static void pty_forward_disconnect(PTYForward *f) {
118
119 if (!f)
120 return;
121
122 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
123 f->stdout_event_source = sd_event_source_unref(f->stdout_event_source);
124 f->master_event_source = sd_event_source_unref(f->master_event_source);
125 f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source);
126 f->exit_event_source = sd_event_source_unref(f->exit_event_source);
127 f->defer_event_source = sd_event_source_unref(f->defer_event_source);
128 f->event = sd_event_unref(f->event);
129
130 if (f->output_fd >= 0) {
131 if (f->saved_stdout)
132 (void) tcsetattr(f->output_fd, TCSANOW, &f->saved_stdout_attr);
133
134 if (f->last_char_set && f->last_char != '\n') {
135 const char *s;
136
137 if (isatty_safe(f->output_fd) && f->last_char != '\r')
138 s = "\r\n";
139 else
140 s = "\n";
141 (void) loop_write(f->output_fd, s, SIZE_MAX);
142
143 f->last_char_set = true;
144 f->last_char = '\n';
145 }
146
147 if (colors_enabled()) {
148 if (f->title)
149 (void) loop_write(f->output_fd, ANSI_WINDOW_TITLE_POP, SIZE_MAX);
150
151 terminal_reset_ansi_seq(f->output_fd);
152 }
153
154 /* STDIN/STDOUT should not be non-blocking normally, so let's reset it */
155 (void) fd_nonblock(f->output_fd, false);
156
157 if (f->close_output_fd)
158 f->output_fd = safe_close(f->output_fd);
159 }
160
161 if (f->input_fd >= 0) {
162 if (f->saved_stdin)
163 (void) tcsetattr(f->input_fd, TCSANOW, &f->saved_stdin_attr);
164
165 (void) fd_nonblock(f->input_fd, false);
166 if (f->close_input_fd)
167 f->input_fd = safe_close(f->input_fd);
168 }
169
170 f->saved_stdout = f->saved_stdin = false;
171
172 f->out_buffer = mfree(f->out_buffer);
173 f->out_buffer_size = 0;
174 f->out_buffer_full = 0;
175 f->out_buffer_write_len = 0;
176 f->in_buffer_full = 0;
177
178 f->csi_sequence = mfree(f->csi_sequence);
179 f->osc_sequence = mfree(f->osc_sequence);
180 f->ansi_color_state = _ANSI_COLOR_STATE_INVALID;
181 }
182
183 static int pty_forward_done(PTYForward *f, int rcode) {
184 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
185 assert(f);
186
187 if (f->done)
188 return 0;
189
190 e = sd_event_ref(f->event);
191
192 f->done = true;
193 pty_forward_disconnect(f);
194
195 if (f->hangup_handler)
196 return f->hangup_handler(f, rcode, f->hangup_userdata);
197
198 return sd_event_exit(e, rcode < 0 ? EXIT_FAILURE : rcode);
199 }
200
201 typedef enum RequestOperation {
202 REQUEST_NOP,
203 REQUEST_EXIT,
204 REQUEST_HOTKEY_BASE,
205 REQUEST_HOTKEY_A = REQUEST_HOTKEY_BASE + 'a',
206 REQUEST_HOTKEY_Z = REQUEST_HOTKEY_BASE + 'z',
207 _REQUEST_OPERATION_MAX,
208 _REQUEST_OPERATION_INVALID = -EINVAL,
209 } RequestOperation;
210
211 static RequestOperation look_for_escape(PTYForward *f, const char *buffer, size_t n) {
212 assert(f);
213 assert(buffer);
214 assert(n > 0);
215
216 for (const char *p = buffer; p < buffer + n; p++) {
217
218 switch (*p) {
219
220 case 0x1D: { /* Check for ^] */
221 usec_t nw = now(CLOCK_MONOTONIC);
222
223 if (f->escape_counter == 0 || nw > usec_add(f->escape_timestamp, ESCAPE_USEC)) {
224 f->escape_timestamp = nw;
225 f->escape_counter = 1;
226 } else {
227 f->escape_counter++;
228
229 if (f->escape_counter >= 3)
230 return REQUEST_EXIT;
231 }
232
233 break;
234 }
235
236 case 'a'...'z':
237 if (f->escape_counter == 2 &&
238 now(CLOCK_MONOTONIC) <= usec_add(f->escape_timestamp, ESCAPE_USEC)) {
239 f->escape_timestamp = 0;
240 f->escape_counter = 0;
241 return REQUEST_HOTKEY_BASE + *p;
242 }
243
244 _fallthrough_;
245
246 default:
247 f->escape_timestamp = 0;
248 f->escape_counter = 0;
249 }
250 }
251
252 return REQUEST_NOP;
253 }
254
255 static bool drained(PTYForward *f) {
256 int q = 0;
257
258 assert(f);
259
260 if (f->done)
261 return true;
262
263 if (f->out_buffer_full > 0)
264 return false;
265
266 if (f->master_readable)
267 return false;
268
269 if (ioctl(f->master, TIOCINQ, &q) < 0)
270 log_debug_errno(errno, "TIOCINQ failed on master: %m");
271 else if (q > 0)
272 return false;
273
274 if (ioctl(f->master, TIOCOUTQ, &q) < 0)
275 log_debug_errno(errno, "TIOCOUTQ failed on master: %m");
276 else if (q > 0)
277 return false;
278
279 return true;
280 }
281
282 static char* background_color_sequence(PTYForward *f) {
283 assert(f);
284 assert(f->background_color);
285
286 return strjoin("\x1B[", f->background_color, "m");
287 }
288
289 static int insert_string(PTYForward *f, size_t offset, const char *s) {
290 assert(f);
291 assert(offset <= f->out_buffer_full);
292 assert(s);
293
294 size_t l = strlen(s);
295 assert(l <= INT_MAX); /* Make sure we can still return this */
296
297 void *p = realloc(f->out_buffer, MAX(f->out_buffer_full + l, (size_t) LINE_MAX));
298 if (!p)
299 return -ENOMEM;
300
301 f->out_buffer = p;
302 f->out_buffer_size = MALLOC_SIZEOF_SAFE(f->out_buffer);
303
304 memmove(f->out_buffer + offset + l, f->out_buffer + offset, f->out_buffer_full - offset);
305 memcpy(f->out_buffer + offset, s, l);
306 f->out_buffer_full += l;
307
308 return (int) l;
309 }
310
311 static int insert_background_color(PTYForward *f, size_t offset) {
312 _cleanup_free_ char *s = NULL;
313
314 assert(f);
315
316 if (FLAGS_SET(f->flags, PTY_FORWARD_DUMB_TERMINAL))
317 return 0;
318
319 if (!f->background_color)
320 return 0;
321
322 if (!shall_tint_background())
323 return 0;
324
325 s = background_color_sequence(f);
326 if (!s)
327 return -ENOMEM;
328
329 return insert_string(f, offset, s);
330 }
331
332 static int is_csi_background_reset_sequence(const char *seq) {
333 enum {
334 COLOR_TOKEN_NO,
335 COLOR_TOKEN_START,
336 COLOR_TOKEN_8BIT,
337 COLOR_TOKEN_24BIT_R,
338 COLOR_TOKEN_24BIT_G,
339 COLOR_TOKEN_24BIT_B,
340 } token_state = COLOR_TOKEN_NO;
341
342 bool b = false;
343 int r;
344
345 assert(seq);
346
347 /* This parses CSI "m" sequences, and determines if they reset the background color. If so returns
348 * 1. This can then be used to insert another sequence that sets the color to the desired
349 * replacement. */
350
351 for (;;) {
352 _cleanup_free_ char *token = NULL;
353
354 r = extract_first_word(&seq, &token, ";", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
355 if (r < 0)
356 return r;
357 if (r == 0)
358 break;
359
360 switch (token_state) {
361
362 case COLOR_TOKEN_NO:
363
364 if (STR_IN_SET(token, "", "0", "00", "49"))
365 b = true; /* These tokens set the background back to normal */
366 else if (STR_IN_SET(token, "40", "41", "42", "43", "44", "45", "46", "47", "48"))
367 b = false; /* And these tokens set them to something other than normal */
368
369 if (STR_IN_SET(token, "38", "48", "58"))
370 token_state = COLOR_TOKEN_START; /* These tokens mean an 8bit or 24bit color will follow */
371 break;
372
373 case COLOR_TOKEN_START:
374
375 if (STR_IN_SET(token, "5", "05"))
376 token_state = COLOR_TOKEN_8BIT; /* 8bit color */
377 else if (STR_IN_SET(token, "2", "02"))
378 token_state = COLOR_TOKEN_24BIT_R; /* 24bit color */
379 else
380 token_state = COLOR_TOKEN_NO; /* something weird? */
381 break;
382
383 case COLOR_TOKEN_24BIT_R:
384 token_state = COLOR_TOKEN_24BIT_G;
385 break;
386
387 case COLOR_TOKEN_24BIT_G:
388 token_state = COLOR_TOKEN_24BIT_B;
389 break;
390
391 case COLOR_TOKEN_8BIT:
392 case COLOR_TOKEN_24BIT_B:
393 token_state = COLOR_TOKEN_NO;
394 break;
395 }
396 }
397
398 return b;
399 }
400
401 static int insert_background_fix(PTYForward *f, size_t offset) {
402 assert(f);
403
404 if (FLAGS_SET(f->flags, PTY_FORWARD_DUMB_TERMINAL))
405 return 0;
406
407 if (!f->background_color)
408 return 0;
409
410 if (!shall_tint_background())
411 return 0;
412
413 if (!is_csi_background_reset_sequence(strempty(f->csi_sequence)))
414 return 0;
415
416 _cleanup_free_ char *s = NULL;
417 s = strjoin(";", f->background_color);
418 if (!s)
419 return -ENOMEM;
420
421 return insert_string(f, offset, s);
422 }
423
424 bool shall_set_terminal_title(void) {
425 static int cache = -1;
426
427 if (cache >= 0)
428 return cache;
429
430 cache = getenv_bool("SYSTEMD_ADJUST_TERMINAL_TITLE");
431 if (cache == -ENXIO)
432 return (cache = true);
433 if (cache < 0)
434 log_debug_errno(cache, "Failed to parse $SYSTEMD_ADJUST_TERMINAL_TITLE, leaving terminal title setting enabled: %m");
435
436 return cache != 0;
437 }
438
439 static int insert_window_title_fix(PTYForward *f, size_t offset) {
440 assert(f);
441
442 if (FLAGS_SET(f->flags, PTY_FORWARD_DUMB_TERMINAL))
443 return 0;
444
445 if (!f->title_prefix)
446 return 0;
447
448 if (!f->osc_sequence)
449 return 0;
450
451 const char *t = startswith(f->osc_sequence, "0;"); /* Set window title OSC sequence */
452 if (!t)
453 return 0;
454
455 _cleanup_free_ char *joined = strjoin(ANSI_OSC "0;", f->title_prefix, t, ANSI_ST);
456 if (!joined)
457 return -ENOMEM;
458
459 return insert_string(f, offset, joined);
460 }
461
462 static int pty_forward_ansi_process(PTYForward *f, size_t offset) {
463 int r;
464
465 assert(f);
466 assert(offset <= f->out_buffer_full);
467
468 for (size_t i = offset; i < f->out_buffer_full; i++) {
469 char c = f->out_buffer[i];
470
471 switch (f->ansi_color_state) {
472
473 case ANSI_COLOR_STATE_TEXT:
474 if (IN_SET(c, '\n', '\r')) {
475 /* Immediately after a newline (ASCII 10) or carriage return (ASCII 13) insert an
476 * ANSI sequence set the background color back. */
477 r = insert_background_color(f, i+1);
478 if (r < 0)
479 return r;
480 i += r;
481 f->last_char_safe = c;
482 } else if (c == 0x1B) /* ESC */
483 f->ansi_color_state = ANSI_COLOR_STATE_ESC;
484 else if (!char_is_cc(c))
485 f->last_char_safe = c;
486 break;
487
488 case ANSI_COLOR_STATE_ESC:
489
490 if (c == '[')
491 f->ansi_color_state = ANSI_COLOR_STATE_CSI_SEQUENCE;
492 else if (c == ']')
493 f->ansi_color_state = ANSI_COLOR_STATE_OSC_SEQUENCE;
494 else if (c == 'c') {
495 /* "Full reset" aka "Reset to initial state" */
496 r = insert_background_color(f, i+1);
497 if (r < 0)
498 return r;
499
500 i += r;
501 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
502 } else
503 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
504 break;
505
506 case ANSI_COLOR_STATE_CSI_SEQUENCE:
507
508 if (c >= 0x20 && c <= 0x3F) {
509 /* If this is a "parameter" or "intermediary" byte (i.e. ranges 0x20…0x2F and
510 * 0x30…0x3F) then we are still in the CSI sequence */
511
512 if (strlen_ptr(f->csi_sequence) >= ANSI_SEQUENCE_LENGTH_MAX) {
513 /* Safety check: lets not accept unbounded CSI sequences */
514
515 f->csi_sequence = mfree(f->csi_sequence);
516 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
517 } else if (!strextend(&f->csi_sequence, CHAR_TO_STR(c)))
518 return -ENOMEM;
519 } else {
520 /* Otherwise, the CSI sequence is over */
521
522 if (c == 'p' && streq_ptr(f->csi_sequence, "!")) {
523
524 /* CSI ! p → "Soft Reset", let's immediately fix our bg color again */
525 r = insert_background_color(f, i+1);
526 if (r < 0)
527 return r;
528
529 i += r;
530 } else if (c == 'm') {
531 /* This is an "SGR" (Select Graphic Rendition) sequence. Patch in our background color. */
532 r = insert_background_fix(f, i);
533 if (r < 0)
534 return r;
535
536 i += r;
537 }
538
539 f->csi_sequence = mfree(f->csi_sequence);
540 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
541 }
542 break;
543
544 case ANSI_COLOR_STATE_OSC_SEQUENCE:
545
546 if ((uint8_t) c >= ' ') {
547 if (strlen_ptr(f->osc_sequence) >= ANSI_SEQUENCE_LENGTH_MAX) {
548 /* Safety check: lets not accept unbounded OSC sequences */
549 f->osc_sequence = mfree(f->osc_sequence);
550 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
551 } else if (!strextend(&f->osc_sequence, CHAR_TO_STR(c)))
552 return -ENOMEM;
553 } else if (c == '\x07') {
554 /* Otherwise, the OSC sequence is over
555 *
556 * There are three documented ways to end an OSC sequence:
557 * 1. BEL aka ^G aka \x07
558 * 2. \x9c
559 * 3. \x1b\x5c
560 * Note that we do not support \x9c here, because that's also a valid UTF8
561 * codepoint, and that would create ambiguity. Various terminal emulators
562 * similar do not support it. */
563
564 r = insert_window_title_fix(f, i+1);
565 if (r < 0)
566 return r;
567 i += r;
568
569 f->osc_sequence = mfree(f->osc_sequence);
570 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
571 } else if (c == '\x1b')
572 /* See the comment above. */
573 f->ansi_color_state = ANSI_COLOR_STATE_OSC_SEQUENCE_TERMINATING;
574 else {
575 /* Unexpected or unsupported OSC sequence. */
576 f->osc_sequence = mfree(f->osc_sequence);
577 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
578 }
579 break;
580
581 case ANSI_COLOR_STATE_OSC_SEQUENCE_TERMINATING:
582 if (c == '\x5c') {
583 r = insert_window_title_fix(f, i+1);
584 if (r < 0)
585 return r;
586 i += r;
587 }
588
589 f->osc_sequence = mfree(f->osc_sequence);
590 f->ansi_color_state = ANSI_COLOR_STATE_TEXT;
591 break;
592
593 default:
594 assert_not_reached();
595 }
596
597 if (f->ansi_color_state == ANSI_COLOR_STATE_TEXT)
598 f->out_buffer_write_len = i + 1;
599 }
600
601 return 0;
602 }
603
604 static int do_shovel(PTYForward *f) {
605 ssize_t k;
606 int r;
607
608 assert(f);
609
610 if (f->out_buffer_size == 0 && !FLAGS_SET(f->flags, PTY_FORWARD_DUMB_TERMINAL)) {
611 /* If the output hasn't been allocated yet, we are at the beginning of the first
612 * shovelling. Hence, possibly send some initial ANSI sequences. But do so only if we are
613 * talking to an actual TTY. */
614
615 if (f->background_color && shall_tint_background()) {
616 /* Erase the first line when we start */
617 f->out_buffer = background_color_sequence(f);
618 if (!f->out_buffer)
619 return log_oom();
620
621 if (!strextend(&f->out_buffer, ANSI_ERASE_TO_END_OF_LINE))
622 return log_oom();
623 }
624
625 if (f->title) {
626 if (!strextend(&f->out_buffer,
627 ANSI_WINDOW_TITLE_PUSH
628 ANSI_OSC "2;", f->title, ANSI_ST))
629 return log_oom();
630 }
631
632 if (f->out_buffer) {
633 f->out_buffer_full = f->out_buffer_write_len = strlen(f->out_buffer);
634 f->out_buffer_size = MALLOC_SIZEOF_SAFE(f->out_buffer);
635 }
636 }
637
638 if (f->out_buffer_size < LINE_MAX) {
639 /* Make sure we always have room for at least one "line" */
640 void *p = realloc(f->out_buffer, LINE_MAX);
641 if (!p)
642 return log_oom();
643
644 f->out_buffer = p;
645 f->out_buffer_size = MALLOC_SIZEOF_SAFE(p);
646 }
647
648 for (;;) {
649 bool did_something = false;
650
651 if (f->stdin_readable && f->in_buffer_full < LINE_MAX) {
652
653 k = read(f->input_fd, f->in_buffer + f->in_buffer_full, LINE_MAX - f->in_buffer_full);
654 if (k < 0) {
655
656 if (errno == EAGAIN)
657 f->stdin_readable = false;
658 else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) {
659 f->stdin_readable = false;
660 f->stdin_hangup = true;
661
662 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
663 } else
664 return log_error_errno(errno, "Failed to read from pty input fd: %m");
665 } else if (k == 0) {
666 /* EOF on stdin */
667 f->stdin_readable = false;
668 f->stdin_hangup = true;
669
670 f->stdin_event_source = sd_event_source_unref(f->stdin_event_source);
671 } else {
672 if (!FLAGS_SET(f->flags, PTY_FORWARD_TRANSPARENT)) {
673 /* Check if ^] has been pressed three times within one second. If we get this we quit
674 * immediately. */
675 RequestOperation q = look_for_escape(f, f->in_buffer + f->in_buffer_full, k);
676 f->in_buffer_full += (size_t) k;
677 if (q < 0)
678 return q;
679 if (q == REQUEST_EXIT)
680 return -ECANCELED;
681 if (q >= REQUEST_HOTKEY_A && q <= REQUEST_HOTKEY_Z && f->hotkey_handler) {
682 r = f->hotkey_handler(f, q - REQUEST_HOTKEY_BASE, f->hotkey_userdata);
683 if (r < 0)
684 return r;
685 }
686 } else
687 f->in_buffer_full += (size_t) k;
688 }
689
690 did_something = true;
691 }
692
693 if (f->master_writable && f->in_buffer_full > 0) {
694
695 k = write(f->master, f->in_buffer, f->in_buffer_full);
696 if (k < 0) {
697
698 if (IN_SET(errno, EAGAIN, EIO))
699 f->master_writable = false;
700 else if (IN_SET(errno, EPIPE, ECONNRESET)) {
701 f->master_writable = f->master_readable = false;
702 f->master_hangup = true;
703
704 f->master_event_source = sd_event_source_unref(f->master_event_source);
705 } else
706 return log_error_errno(errno, "write(): %m");
707 } else {
708 assert(f->in_buffer_full >= (size_t) k);
709 memmove(f->in_buffer, f->in_buffer + k, f->in_buffer_full - k);
710 f->in_buffer_full -= k;
711 }
712
713 did_something = true;
714 }
715
716 if (f->master_readable && f->out_buffer_full < MIN(f->out_buffer_size, (size_t) LINE_MAX)) {
717
718 k = read(f->master, f->out_buffer + f->out_buffer_full, f->out_buffer_size - f->out_buffer_full);
719 if (k < 0) {
720
721 /* Note that EIO on the master device might be caused by vhangup() or
722 * temporary closing of everything on the other side, we treat it like EAGAIN
723 * here and try again, unless vhangup() is honored. */
724
725 if (errno == EAGAIN || (errno == EIO && !pty_forward_vhangup_honored(f)))
726 f->master_readable = false;
727 else if (IN_SET(errno, EPIPE, ECONNRESET, EIO)) {
728 f->master_readable = f->master_writable = false;
729 f->master_hangup = true;
730
731 f->master_event_source = sd_event_source_unref(f->master_event_source);
732 } else
733 return log_error_errno(errno, "Failed to read from pty master fd: %m");
734 } else {
735 f->read_from_master = true;
736 size_t scan_index = f->out_buffer_full;
737 f->out_buffer_full += (size_t) k;
738
739 r = pty_forward_ansi_process(f, scan_index);
740 if (r < 0)
741 return log_error_errno(r, "Failed to scan for ANSI sequences: %m");
742 }
743
744 did_something = true;
745 }
746
747 if (f->stdout_writable && f->out_buffer_write_len > 0) {
748 assert(f->out_buffer_write_len <= f->out_buffer_full);
749
750 k = write(f->output_fd, f->out_buffer, f->out_buffer_write_len);
751 if (k < 0) {
752
753 if (errno == EAGAIN)
754 f->stdout_writable = false;
755 else if (errno == EIO || ERRNO_IS_DISCONNECT(errno)) {
756 f->stdout_writable = false;
757 f->stdout_hangup = true;
758 f->stdout_event_source = sd_event_source_unref(f->stdout_event_source);
759 } else
760 return log_error_errno(errno, "Failed to write to pty output fd: %m");
761
762 } else {
763
764 if (k > 0 && f->last_char_safe != '\0') {
765 if ((size_t) k == f->out_buffer_write_len)
766 /* If we wrote all, then save the last safe character. */
767 f->last_char = f->last_char_safe;
768 else
769 /* If we wrote partially, then tentatively save the last written character.
770 * Hopefully, we will write more in the next loop. */
771 f->last_char = f->out_buffer[k-1];
772
773 f->last_char_set = true;
774 }
775
776 assert(f->out_buffer_write_len >= (size_t) k);
777 memmove(f->out_buffer, f->out_buffer + k, f->out_buffer_full - k);
778 f->out_buffer_full -= k;
779 f->out_buffer_write_len -= k;
780 }
781
782 did_something = true;
783 }
784
785 if (!did_something)
786 break;
787 }
788
789 return 0;
790 }
791
792 static int shovel(PTYForward *f) {
793 int r;
794
795 assert(f);
796
797 r = do_shovel(f);
798 if (r < 0)
799 return pty_forward_done(f, r);
800
801 if (f->stdin_hangup || f->stdout_hangup || f->master_hangup) {
802 /* Exit the loop if any side hung up and if there's
803 * nothing more to write or nothing we could write. */
804
805 if ((f->out_buffer_write_len <= 0 || f->stdout_hangup) &&
806 (f->in_buffer_full <= 0 || f->master_hangup))
807 return pty_forward_done(f, 0);
808 }
809
810 /* If we were asked to drain, and there's nothing more to handle from the master, then call the callback
811 * too. */
812 if (f->drain && drained(f))
813 return pty_forward_done(f, 0);
814
815 return 0;
816 }
817
818 static int shovel_force(PTYForward *f) {
819 assert(f);
820
821 if (!f->master_hangup)
822 f->master_writable = f->master_readable = true;
823 if (!f->stdin_hangup && f->input_fd >= 0)
824 f->stdin_readable = true;
825 if (!f->stdout_hangup)
826 f->stdout_writable = true;
827
828 return shovel(f);
829 }
830
831 static int on_master_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
832 PTYForward *f = ASSERT_PTR(userdata);
833
834 assert(e);
835 assert(e == f->master_event_source);
836 assert(fd >= 0);
837 assert(fd == f->master);
838
839 if (revents & (EPOLLIN|EPOLLHUP))
840 f->master_readable = true;
841
842 if (revents & (EPOLLOUT|EPOLLHUP))
843 f->master_writable = true;
844
845 return shovel(f);
846 }
847
848 static int on_stdin_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
849 PTYForward *f = ASSERT_PTR(userdata);
850
851 assert(e);
852 assert(e == f->stdin_event_source);
853 assert(fd >= 0);
854 assert(fd == f->input_fd);
855
856 if (revents & (EPOLLIN|EPOLLHUP))
857 f->stdin_readable = true;
858
859 return shovel(f);
860 }
861
862 static int on_stdout_event(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
863 PTYForward *f = ASSERT_PTR(userdata);
864
865 assert(e);
866 assert(e == f->stdout_event_source);
867 assert(fd >= 0);
868 assert(fd == f->output_fd);
869
870 if (revents & (EPOLLOUT|EPOLLHUP))
871 f->stdout_writable = true;
872
873 return shovel(f);
874 }
875
876 static int on_sigwinch_event(sd_event_source *e, const struct signalfd_siginfo *si, void *userdata) {
877 PTYForward *f = ASSERT_PTR(userdata);
878 struct winsize ws;
879
880 assert(e);
881 assert(e == f->sigwinch_event_source);
882
883 /* The window size changed, let's forward that. */
884 if (ioctl(f->output_fd, TIOCGWINSZ, &ws) >= 0)
885 (void) ioctl(f->master, TIOCSWINSZ, &ws);
886
887 return 0;
888 }
889
890 static int on_exit_event(sd_event_source *e, void *userdata) {
891 PTYForward *f = ASSERT_PTR(userdata);
892 int r;
893
894 assert(e);
895 assert(e == f->exit_event_source);
896
897 if (!pty_forward_drain(f)) {
898 /* If not drained, try to drain the buffer. */
899 r = shovel_force(f);
900 if (r < 0)
901 return r;
902 }
903
904 return pty_forward_done(f, 0);
905 }
906
907 static int on_defer_event(sd_event_source *s, void *userdata) {
908 PTYForward *f = ASSERT_PTR(userdata);
909 return shovel_force(f);
910 }
911
912 static int pty_forward_add_defer(PTYForward *f) {
913 assert(f);
914
915 if (f->done)
916 return 0;
917
918 if (f->defer_event_source)
919 return sd_event_source_set_enabled(f->defer_event_source, SD_EVENT_ONESHOT);
920
921 return sd_event_add_defer(f->event, &f->defer_event_source, on_defer_event, f);
922 }
923
924 int pty_forward_new(
925 sd_event *event,
926 int master,
927 PTYForwardFlags flags,
928 PTYForward **ret) {
929
930 _cleanup_(pty_forward_freep) PTYForward *f = NULL;
931 struct winsize ws;
932 int r;
933
934 assert(master >= 0);
935 assert(ret);
936
937 if (!FLAGS_SET(flags, PTY_FORWARD_READ_ONLY)) {
938 /* If stdin isn't actually opened for reading, or refers to the read end of a pipe (or
939 * socket) whose peer has already hung up, then there's nothing for us to forward — imply
940 * read-only mode. */
941 r = RET_NERRNO(fcntl(STDIN_FILENO, F_GETFL));
942 if (r < 0 && r != -EBADF)
943 return log_debug_errno(errno, "Failed to query stdin flags: %m");
944 if (r == -EBADF || (r & O_ACCMODE_STRICT) == O_WRONLY)
945 flags |= PTY_FORWARD_READ_ONLY;
946 else {
947 r = pipe_eof(STDIN_FILENO);
948 if (r < 0)
949 log_debug_errno(r, "Failed to check whether stdin is at EOF, ignoring: %m");
950 else if (r > 0)
951 flags |= PTY_FORWARD_READ_ONLY;
952 }
953 }
954
955 f = new(PTYForward, 1);
956 if (!f)
957 return -ENOMEM;
958
959 *f = (PTYForward) {
960 .flags = flags,
961 .master = -EBADF,
962 .input_fd = -EBADF,
963 .output_fd = -EBADF,
964 };
965
966 if (event)
967 f->event = sd_event_ref(event);
968 else {
969 r = sd_event_default(&f->event);
970 if (r < 0)
971 return r;
972 }
973
974 if (FLAGS_SET(flags, PTY_FORWARD_READ_ONLY))
975 f->output_fd = STDOUT_FILENO;
976 else {
977 /* If we shall be invoked in interactive mode, let's switch on non-blocking mode, so that we
978 * never end up staving one direction while we block on the other. However, let's be careful
979 * here and not turn on O_NONBLOCK for stdin/stdout directly, but of reopened copies of
980 * them. This has two advantages: when we are killed abruptly the stdin/stdout fds won't be
981 * left in O_NONBLOCK state for the next process using them. In addition, if some process
982 * running in the background wants to continue writing to our stdout it can do so without
983 * being confused by O_NONBLOCK.
984 * We keep O_APPEND (if present) on the output FD and (try to) keep current file position on
985 * both input and output FD (principle of least surprise).
986 */
987
988 f->input_fd = fd_reopen_propagate_append_and_position(
989 STDIN_FILENO, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
990 if (f->input_fd < 0) {
991 /* Handle failures gracefully, after all certain fd types cannot be reopened
992 * (sockets, …) */
993 log_debug_errno(f->input_fd, "Failed to reopen stdin, using original fd: %m");
994
995 r = fd_nonblock(STDIN_FILENO, true);
996 if (r < 0)
997 return r;
998
999 f->input_fd = STDIN_FILENO;
1000 } else
1001 f->close_input_fd = true;
1002
1003 f->output_fd = fd_reopen_propagate_append_and_position(
1004 STDOUT_FILENO, O_WRONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
1005 if (f->output_fd < 0) {
1006 log_debug_errno(f->output_fd, "Failed to reopen stdout, using original fd: %m");
1007
1008 r = fd_nonblock(STDOUT_FILENO, true);
1009 if (r < 0)
1010 return r;
1011
1012 f->output_fd = STDOUT_FILENO;
1013 } else
1014 f->close_output_fd = true;
1015 }
1016
1017 r = fd_nonblock(master, true);
1018 if (r < 0)
1019 return r;
1020
1021 f->master = master;
1022
1023 /* Disable color/window title setting unless we talk to a good TTY */
1024 if (!isatty_safe(f->output_fd) || get_color_mode() == COLOR_OFF)
1025 f->flags |= PTY_FORWARD_DUMB_TERMINAL;
1026
1027 if (ioctl(f->output_fd, TIOCGWINSZ, &ws) < 0)
1028 /* If we can't get the resolution from the output fd, then use our internal, regular width/height,
1029 * i.e. something derived from $COLUMNS and $LINES if set. */
1030 ws = (struct winsize) {
1031 .ws_row = lines(),
1032 .ws_col = columns(),
1033 };
1034
1035 (void) ioctl(master, TIOCSWINSZ, &ws);
1036
1037 if (!FLAGS_SET(flags, PTY_FORWARD_READ_ONLY)) {
1038 bool same;
1039
1040 assert(f->input_fd >= 0);
1041
1042 r = fd_inode_same(f->input_fd, f->output_fd);
1043 if (r < 0)
1044 return r;
1045 same = r > 0;
1046
1047 if (tcgetattr(f->input_fd, &f->saved_stdin_attr) >= 0) {
1048 struct termios raw_stdin_attr;
1049
1050 f->saved_stdin = true;
1051
1052 raw_stdin_attr = f->saved_stdin_attr;
1053 cfmakeraw(&raw_stdin_attr);
1054
1055 if (!same)
1056 raw_stdin_attr.c_oflag = f->saved_stdin_attr.c_oflag;
1057
1058 (void) tcsetattr(f->input_fd, TCSANOW, &raw_stdin_attr);
1059 }
1060
1061 if (!same && tcgetattr(f->output_fd, &f->saved_stdout_attr) >= 0) {
1062 struct termios raw_stdout_attr;
1063
1064 f->saved_stdout = true;
1065
1066 raw_stdout_attr = f->saved_stdout_attr;
1067 cfmakeraw(&raw_stdout_attr);
1068 raw_stdout_attr.c_iflag = f->saved_stdout_attr.c_iflag;
1069 raw_stdout_attr.c_lflag = f->saved_stdout_attr.c_lflag;
1070 (void) tcsetattr(f->output_fd, TCSANOW, &raw_stdout_attr);
1071 }
1072
1073 r = sd_event_add_io(f->event, &f->stdin_event_source, f->input_fd, EPOLLIN|EPOLLET, on_stdin_event, f);
1074 if (r < 0 && r != -EPERM)
1075 return r;
1076
1077 if (r >= 0)
1078 (void) sd_event_source_set_description(f->stdin_event_source, "ptyfwd-stdin");
1079 }
1080
1081 r = sd_event_add_io(f->event, &f->stdout_event_source, f->output_fd, EPOLLOUT|EPOLLET, on_stdout_event, f);
1082 if (r == -EPERM)
1083 /* stdout without epoll support. Likely redirected to regular file. */
1084 f->stdout_writable = true;
1085 else if (r < 0)
1086 return r;
1087 else
1088 (void) sd_event_source_set_description(f->stdout_event_source, "ptyfwd-stdout");
1089
1090 r = sd_event_add_io(f->event, &f->master_event_source, master, EPOLLIN|EPOLLOUT|EPOLLET, on_master_event, f);
1091 if (r < 0)
1092 return r;
1093
1094 (void) sd_event_source_set_description(f->master_event_source, "ptyfwd-master");
1095
1096 r = sd_event_add_signal(f->event, &f->sigwinch_event_source, SIGWINCH|SD_EVENT_SIGNAL_PROCMASK, on_sigwinch_event, f);
1097 if (r < 0)
1098 return r;
1099
1100 (void) sd_event_source_set_description(f->sigwinch_event_source, "ptyfwd-sigwinch");
1101
1102 r = sd_event_add_exit(f->event, &f->exit_event_source, on_exit_event, f);
1103 if (r < 0)
1104 return r;
1105
1106 (void) sd_event_source_set_description(f->exit_event_source, "ptyfwd-exit");
1107
1108 *ret = TAKE_PTR(f);
1109
1110 return 0;
1111 }
1112
1113 PTYForward* pty_forward_free(PTYForward *f) {
1114 if (!f)
1115 return NULL;
1116
1117 pty_forward_disconnect(f);
1118 free(f->background_color);
1119 free(f->title);
1120 free(f->title_prefix);
1121
1122 return mfree(f);
1123 }
1124
1125 int pty_forward_honor_vhangup(PTYForward *f) {
1126 assert(f);
1127
1128 if ((f->flags & (PTY_FORWARD_IGNORE_VHANGUP | PTY_FORWARD_IGNORE_INITIAL_VHANGUP)) == 0)
1129 return 0; /* nothing changed. */
1130
1131 f->flags &= ~(PTY_FORWARD_IGNORE_VHANGUP | PTY_FORWARD_IGNORE_INITIAL_VHANGUP);
1132
1133 if (f->master_hangup)
1134 return 0;
1135
1136 /* We shall now react to vhangup()s? Let's check if we might be in one. */
1137 return pty_forward_add_defer(f);
1138 }
1139
1140 bool pty_forward_vhangup_honored(const PTYForward *f) {
1141 assert(f);
1142
1143 if (FLAGS_SET(f->flags, PTY_FORWARD_IGNORE_VHANGUP))
1144 return false;
1145
1146 if (FLAGS_SET(f->flags, PTY_FORWARD_IGNORE_INITIAL_VHANGUP) && !f->read_from_master)
1147 return false;
1148
1149 return true;
1150 }
1151
1152 void pty_forward_set_hangup_handler(PTYForward *f, PTYForwardHangupHandler cb, void *userdata) {
1153 assert(f);
1154
1155 f->hangup_handler = cb;
1156 f->hangup_userdata = userdata;
1157 }
1158
1159 void pty_forward_set_hotkey_handler(PTYForward *f, PTYForwardHotkeyHandler cb, void *userdata) {
1160 assert(f);
1161
1162 f->hotkey_handler = cb;
1163 f->hotkey_userdata = userdata;
1164 }
1165
1166 int pty_forward_drain(PTYForward *f) {
1167 assert(f);
1168
1169 /* Starts draining the forwarder. This makes sure the handler function is called the next time the
1170 * number of unprocessed bytes hits zero. */
1171
1172 f->drain = true;
1173 return pty_forward_add_defer(f);
1174 }
1175
1176 int pty_forward_set_priority(PTYForward *f, int64_t priority) {
1177 int r;
1178
1179 assert(f);
1180
1181 if (f->stdin_event_source) {
1182 r = sd_event_source_set_priority(f->stdin_event_source, priority);
1183 if (r < 0)
1184 return r;
1185 }
1186
1187 r = sd_event_source_set_priority(f->stdout_event_source, priority);
1188 if (r < 0)
1189 return r;
1190
1191 r = sd_event_source_set_priority(f->master_event_source, priority);
1192 if (r < 0)
1193 return r;
1194
1195 r = sd_event_source_set_priority(f->sigwinch_event_source, priority);
1196 if (r < 0)
1197 return r;
1198
1199 return 0;
1200 }
1201
1202 int pty_forward_set_width_height(PTYForward *f, unsigned width, unsigned height) {
1203 struct winsize ws;
1204
1205 assert(f);
1206
1207 if (width == UINT_MAX && height == UINT_MAX)
1208 return 0; /* noop */
1209
1210 if (width != UINT_MAX &&
1211 (width == 0 || width > USHRT_MAX))
1212 return -ERANGE;
1213
1214 if (height != UINT_MAX &&
1215 (height == 0 || height > USHRT_MAX))
1216 return -ERANGE;
1217
1218 if (width == UINT_MAX || height == UINT_MAX) {
1219 if (ioctl(f->master, TIOCGWINSZ, &ws) < 0)
1220 return -errno;
1221
1222 if (width != UINT_MAX)
1223 ws.ws_col = width;
1224 if (height != UINT_MAX)
1225 ws.ws_row = height;
1226 } else
1227 ws = (struct winsize) {
1228 .ws_row = height,
1229 .ws_col = width,
1230 };
1231
1232 if (ioctl(f->master, TIOCSWINSZ, &ws) < 0)
1233 return -errno;
1234
1235 /* Make sure we ignore SIGWINCH window size events from now on */
1236 f->sigwinch_event_source = sd_event_source_unref(f->sigwinch_event_source);
1237
1238 return 0;
1239 }
1240
1241 int pty_forward_set_background_color(PTYForward *f, const char *color) {
1242 assert(f);
1243
1244 return free_and_strdup(&f->background_color, color);
1245 }
1246
1247 int pty_forward_set_title(PTYForward *f, const char *title) {
1248 assert(f);
1249
1250 /* Refuse accepting a title when we already started shoveling */
1251 if (f->out_buffer_size > 0)
1252 return -EBUSY;
1253
1254 if (!title) {
1255 f->title = mfree(f->title);
1256 return 0;
1257 }
1258
1259 /* Truncate the title to 128 chars, since some terminal emulators really don't like overly long ANSI
1260 * sequences */
1261 _cleanup_free_ char *ellipsized = ellipsize(title, ANSI_SEQUENCE_WINDOW_TITLE_MAX, 66);
1262 if (!ellipsized)
1263 return -ENOMEM;
1264
1265 return free_and_replace(f->title, ellipsized);
1266 }
1267
1268 int pty_forward_set_titlef(PTYForward *f, const char *format, ...) {
1269 _cleanup_free_ char *title = NULL;
1270 va_list ap;
1271 int r;
1272
1273 assert(f);
1274 assert(format);
1275
1276 if (f->out_buffer_size > 0)
1277 return -EBUSY;
1278
1279 va_start(ap, format);
1280 r = vasprintf(&title, format, ap);
1281 va_end(ap);
1282 if (r < 0)
1283 return -ENOMEM;
1284
1285 return pty_forward_set_title(f, title);
1286 }
1287
1288 int pty_forward_set_title_prefix(PTYForward *f, const char *title_prefix) {
1289 assert(f);
1290
1291 return free_and_strdup(&f->title_prefix, title_prefix);
1292 }
1293
1294 int pty_forward_set_window_title(
1295 PTYForward *f,
1296 Glyph circle, /* e.g. GLYPH_GREEN_CIRCLE */
1297 const char *hostname, /* Can be NULL, and obtained by gethostname_strict() in that case. */
1298 char * const *msg) {
1299
1300 _cleanup_free_ char *hn = NULL, *dot = NULL, *joined = NULL;
1301 int r;
1302
1303 assert(f);
1304
1305 if (!shall_set_terminal_title())
1306 return 0;
1307
1308 if (!hostname) {
1309 (void) gethostname_strict(&hn);
1310 hostname = hn;
1311 }
1312
1313 if (circle >= 0 && emoji_enabled()) {
1314 dot = strjoin(glyph(circle), " ");
1315 if (!dot)
1316 return -ENOMEM;
1317 }
1318
1319 joined = strv_join(msg, " ");
1320 if (!joined)
1321 return -ENOMEM;
1322
1323 r = pty_forward_set_titlef(f, "%s%s%s%s", strempty(dot), joined, hostname ? " on " : "", strempty(hostname));
1324 if (r < 0)
1325 return r;
1326
1327 if (dot) {
1328 r = pty_forward_set_title_prefix(f, dot);
1329 if (r < 0)
1330 return r;
1331 }
1332
1333 return 0;
1334 }