1
//! [`tui::transport::Transport`] that drives the TUI runtime over a
2
//! russh channel.
3
//!
4
//! The bridge bridges three impedance mismatches:
5
//!
6
//! - **sync ↔ async.** `tui::run_loop` is sync; russh's
7
//!   `Handle::data` is async. We capture a `tokio::runtime::Handle`
8
//!   at construction and `block_on` from inside the spawned blocking
9
//!   task that runs the loop.
10
//! - **single byte stream ↔ ratatui frames + raw passthrough.** The
11
//!   ratatui `CrosstermBackend` writes ANSI cell escapes; chart
12
//!   code emits kitty graphics APC bytes that must reach the same
13
//!   stream but bypass ratatui's grid. We expose the second path via
14
//!   [`Transport::write_passthrough`] using a separate
15
//!   [`ChannelWriter`] clone so the two emit paths don't fight over
16
//!   the same buffer.
17
//! - **input from `Handler::data` ↔ blocking `Transport::poll`.** The
18
//!   handler shoves [`RawEvent`]s into an `mpsc` channel; the
19
//!   transport's `poll` blocks the runtime thread on `recv` with a
20
//!   tokio timeout via the captured runtime handle.
21

            
22
use crate::pty_backend::PtyBackend;
23
use crate::tui_channel::Geometry;
24
use ratatui::Terminal;
25
use ratatui::backend::Backend;
26
use russh::ChannelId;
27
use russh::server::Handle;
28
use std::io::{self, Write};
29
use std::time::Duration;
30
use tokio::sync::mpsc::Receiver;
31
use tokio::sync::watch;
32
use tui::transport::{MOUSE_DISABLE, MOUSE_ENABLE, RawEvent, Transport, failed_steps, warn_failed};
33

            
34
/// `std::io::Write` that forwards bytes to a russh channel via the
35
/// session's [`Handle`]. `flush` drives the async `Handle::data`
36
/// call from sync code by `block_on`-ing on the runtime captured at
37
/// construction.
38
pub struct ChannelWriter {
39
    handle: Handle,
40
    channel: ChannelId,
41
    runtime: tokio::runtime::Handle,
42
    buffer: Vec<u8>,
43
}
44

            
45
impl ChannelWriter {
46
26
    pub fn new(handle: Handle, channel: ChannelId, runtime: tokio::runtime::Handle) -> Self {
47
26
        Self {
48
26
            handle,
49
26
            channel,
50
26
            runtime,
51
26
            buffer: Vec::with_capacity(4096),
52
26
        }
53
26
    }
54

            
55
526
    fn drain_buffer(&mut self) -> io::Result<()> {
56
526
        if self.buffer.is_empty() {
57
234
            return Ok(());
58
292
        }
59
292
        let bytes = std::mem::take(&mut self.buffer);
60
292
        let result = self.runtime.block_on(self.handle.data(self.channel, bytes));
61
292
        match result {
62
269
            Ok(()) => Ok(()),
63
23
            Err(_) => Err(io::Error::new(
64
23
                io::ErrorKind::BrokenPipe,
65
23
                "ssh channel closed",
66
23
            )),
67
        }
68
526
    }
69
}
70

            
71
impl Write for ChannelWriter {
72
125497
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
73
125497
        self.buffer.extend_from_slice(buf);
74
125497
        Ok(buf.len())
75
125497
    }
76

            
77
526
    fn flush(&mut self) -> io::Result<()> {
78
526
        self.drain_buffer()
79
526
    }
80
}
81

            
82
/// SSH-side transport. Wraps a [`PtyBackend`] over a
83
/// [`ChannelWriter`] and dequeues input events the handler pushed
84
/// into the session's mpsc.
85
pub struct SshTransport {
86
    terminal: Terminal<PtyBackend<ChannelWriter>>,
87
    inputs: Receiver<RawEvent>,
88
    passthrough: ChannelWriter,
89
    handle: Handle,
90
    channel: ChannelId,
91
    runtime: tokio::runtime::Handle,
92
    term: Option<String>,
93
    geometry: watch::Receiver<Geometry>,
94
}
95

            
96
impl SshTransport {
97
    /// Build a transport bound to the given russh `channel` and
98
    /// `handle`. `term` is the terminal type the peer announced via
99
    /// `pty-req` (e.g. `xterm-kitty`); pass `None` if no PTY was
100
    /// requested.
101
    ///
102
    /// # Errors
103
    ///
104
    /// Returns `Err` if constructing the terminal fails or the initial
105
    /// backend clear cannot be written to the channel.
106
13
    pub fn new(
107
13
        handle: Handle,
108
13
        channel: ChannelId,
109
13
        runtime: tokio::runtime::Handle,
110
13
        inputs: Receiver<RawEvent>,
111
13
        term: Option<String>,
112
13
        geometry: watch::Receiver<Geometry>,
113
13
    ) -> io::Result<Self> {
114
13
        let backend_writer = ChannelWriter::new(handle.clone(), channel, runtime.clone());
115
13
        let mut passthrough = ChannelWriter::new(handle.clone(), channel, runtime.clone());
116
13
        let backend = PtyBackend::new(backend_writer, geometry.clone());
117
13
        let mut terminal = Terminal::new(backend)?;
118
        // Clear at the backend level (writes the `ESC[2J` clear sequence to the
119
        // channel). `Terminal::clear` would first call `get_cursor_position`,
120
        // which issues a DSR query and reads the reply from the controlling
121
        // tty — there is none over SSH/headless, so it fails with ENXIO.
122
13
        terminal.backend_mut().clear()?;
123
13
        passthrough.write_all(MOUSE_ENABLE)?;
124
13
        passthrough.flush()?;
125
13
        Ok(Self {
126
13
            terminal,
127
13
            inputs,
128
13
            passthrough,
129
13
            handle,
130
13
            channel,
131
13
            runtime,
132
13
            term,
133
13
            geometry,
134
13
        })
135
13
    }
136
}
137

            
138
// An ssh session must never save files on the server.
139
const _: () = assert!(!<SshTransport as Transport>::LOCAL_FILES);
140

            
141
/// Gives the client its terminal back: mouse reporting off, cursor shown, plain style. We
142
/// don't enter raw mode or the alternate screen on the client, so no more is needed. Every
143
/// step is tried whatever the ones before it did.
144
16
pub(crate) fn restore<W: Write>(out: &mut W) -> Vec<(&'static str, io::Error)> {
145
16
    failed_steps([
146
16
        ("mouse", out.write_all(MOUSE_DISABLE)),
147
16
        ("cursor", out.write_all(b"\x1b[?25h")),
148
16
        ("style", out.write_all(b"\x1b[0m\r\n")),
149
16
        ("flush", out.flush()),
150
16
    ])
151
16
}
152

            
153
/// Runs on quit, error and panic alike; the loop thread is a blocking one, so waiting on the
154
/// runtime is allowed here.
155
impl Drop for SshTransport {
156
13
    fn drop(&mut self) {
157
13
        warn_failed(restore(&mut self.passthrough));
158
13
        if self
159
13
            .runtime
160
13
            .block_on(self.handle.close(self.channel))
161
13
            .is_err()
162
        {
163
10
            tracing::warn!("closing the ssh channel failed");
164
3
        }
165
13
    }
166
}
167

            
168
impl Transport for SshTransport {
169
    type Backend = PtyBackend<ChannelWriter>;
170

            
171
474
    fn terminal_mut(&mut self) -> &mut Terminal<Self::Backend> {
172
474
        &mut self.terminal
173
474
    }
174

            
175
234
    fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>> {
176
234
        self.runtime.block_on(async {
177
234
            match tokio::time::timeout(timeout, self.inputs.recv()).await {
178
192
                Ok(Some(ev)) => Ok(Some(ev)),
179
8
                Ok(None) => Err(io::Error::new(
180
8
                    io::ErrorKind::UnexpectedEof,
181
8
                    "ssh channel closed",
182
8
                )),
183
34
                Err(_) => Ok(None),
184
            }
185
234
        })
186
234
    }
187

            
188
    fn write_passthrough(&mut self, bytes: &[u8]) -> io::Result<()> {
189
        self.passthrough.write_all(bytes)?;
190
        self.passthrough.flush()
191
    }
192

            
193
237
    fn client_term(&self) -> Option<&str> {
194
237
        self.term.as_deref()
195
237
    }
196

            
197
237
    fn cell_pixels(&self) -> (u16, u16) {
198
237
        self.geometry.borrow().cell_pixels()
199
237
    }
200
}