Skip to main content

oxdock_ssh_plugin/
types.rs

1//! The `SSH_SERVER` opaque handle type.
2//!
3//! The value carries shared server lifetime state and nothing secret:
4//! credentials live only on the runtime thread. Display and Debug
5//! redact everything but the id and address.
6
7use std::fmt;
8use std::net::SocketAddr;
9use std::sync::{Arc, Mutex};
10
11use oxdock_diagnostics::DiagnosticResult;
12
13use crate::diagnostics as ssh_diag;
14use oxdock_func_macro::oxdock_type;
15use tokio::sync::mpsc;
16
17use crate::state::{DownMsg, ServerState, UpMsg};
18
19/// Handle to one ephemeral SSH server instance.
20///
21/// Cloning the value shares the server; dropping the last clone
22/// signals shutdown.
23#[oxdock_type(name = "SSH_SERVER")]
24#[derive(Debug, Clone)]
25pub struct SshServerTag {
26    state: Arc<ServerState>,
27}
28
29impl SshServerTag {
30    pub fn new(state: Arc<ServerState>) -> Self {
31        Self { state }
32    }
33
34    pub fn state(&self) -> &Arc<ServerState> {
35        &self.state
36    }
37}
38
39impl PartialEq for SshServerTag {
40    fn eq(&self, other: &Self) -> bool {
41        self.state.id() == other.state.id()
42    }
43}
44
45impl fmt::Display for SshServerTag {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(
48            formatter,
49            "SSH_SERVER({}, {})",
50            self.state.id(),
51            self.state.addr_text()
52        )
53    }
54}
55
56/// Unique session ids per process.
57static SESSION_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
58
59/// Shareable half of one dequeued session: metadata, the session's
60/// terminal-size cell, plus take-once pump ends. Cloning shares the
61/// session; pumping consumes the ends.
62#[derive(Debug)]
63struct SshSessionInner {
64    id: u64,
65    command: Option<String>,
66    username: Option<String>,
67    peer_addr: Option<SocketAddr>,
68    /// This session's size cell, shared with its connection handler
69    /// (writer) and its pty pump (reader). Never shared across sessions.
70    pty_size: crate::state::SharedPtySize,
71    up_rx: Mutex<Option<mpsc::Receiver<UpMsg>>>,
72    down_tx: Mutex<Option<mpsc::Sender<DownMsg>>>,
73    /// Control sender for the wire `exit-status`, kept across pumps:
74    /// a clone of `down_tx` held back at construction, so
75    /// `SSH_SEND_EXIT_STATUS` can queue the request even while a byte
76    /// pump owns the main ends. Released when the pump finishes (see
77    /// `finish_pump`): the wire writer must observe the drain and close
78    /// the channel then, not when the last session clone drops (long
79    /// after, on an accept loop holding the session). Dies with the
80    /// last session clone for sessions that never pump.
81    control_tx: Mutex<Option<mpsc::Sender<DownMsg>>>,
82}
83
84/// Handle to one dequeued SSH session instance.
85///
86/// Cloning the value shares the session; metadata reads never consume.
87/// Display shows id and peer only: the command string may carry secrets.
88#[oxdock_type(name = "SSH_SESSION")]
89#[derive(Debug, Clone)]
90pub struct SshSessionTag {
91    inner: Arc<SshSessionInner>,
92}
93
94impl SshSessionTag {
95    pub fn new(
96        command: Option<String>,
97        username: Option<String>,
98        peer_addr: Option<SocketAddr>,
99        pty_size: crate::state::SharedPtySize,
100        up_rx: mpsc::Receiver<UpMsg>,
101        down_tx: mpsc::Sender<DownMsg>,
102    ) -> Self {
103        Self {
104            inner: Arc::new(SshSessionInner {
105                id: SESSION_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
106                command,
107                username,
108                peer_addr,
109                pty_size,
110                up_rx: Mutex::new(Some(up_rx)),
111                down_tx: Mutex::new(Some(down_tx.clone())),
112                control_tx: Mutex::new(Some(down_tx)),
113            }),
114        }
115    }
116
117    /// Queue an `exit-status` request for the client. Usable before the
118    /// pump finishes; after that it bails, so a late send fails loudly
119    /// instead of hanging a client that already saw the close. Never
120    /// blocks: a saturated queue means the wire side is wedged behind
121    /// network backpressure, and parking the reporter on it would stall
122    /// teardown behind a dead network. That failure also bails loudly.
123    pub fn send_exit_status(&self, code: u32) -> DiagnosticResult<()> {
124        let slot = self
125            .inner
126            .control_tx
127            .lock()
128            .unwrap_or_else(|p| p.into_inner());
129        let Some(tx) = slot.as_ref() else {
130            return Err(ssh_diag::session_pump_already_finished());
131        };
132        tx.try_send(crate::state::DownMsg::ExitStatus(code))
133            .map_err(|err| match err {
134                tokio::sync::mpsc::error::TrySendError::Full(_) => {
135                    ssh_diag::session_wire_queue_saturated()
136                }
137                tokio::sync::mpsc::error::TrySendError::Closed(_) => {
138                    ssh_diag::session_wire_writer_gone()
139                }
140            })?;
141        Ok(())
142    }
143
144    /// Release the control sender once the byte pump finishes. The wire
145    /// writer then observes the drain and closes the channel promptly,
146    /// even while the script still holds the session. Idempotent.
147    pub fn finish_pump(&self) {
148        self.inner
149            .control_tx
150            .lock()
151            .unwrap_or_else(|poison| poison.into_inner())
152            .take();
153    }
154
155    pub fn command(&self) -> Option<String> {
156        self.inner.command.clone()
157    }
158
159    pub fn username(&self) -> Option<String> {
160        self.inner.username.clone()
161    }
162
163    pub fn peer_addr(&self) -> Option<SocketAddr> {
164        self.inner.peer_addr
165    }
166
167    /// Snapshot this session's terminal dimensions.
168    pub fn pty_size(&self) -> crate::state::PtySize {
169        crate::state::snapshot_pty_size(&self.inner.pty_size).size
170    }
171
172    /// Shareable handle to this session's size cell, for its pty pump.
173    pub fn pty_size_handle(&self) -> crate::state::SharedPtySize {
174        Arc::clone(&self.inner.pty_size)
175    }
176
177    /// Take the pump ends for `SSH_PUMP_CHANNEL`. A second pump on the
178    /// same session bails instead of splitting bytes across pumps. The
179    /// check runs before either take so a failed pump mutates nothing.
180    pub fn take_pump_ends(
181        &self,
182    ) -> DiagnosticResult<(mpsc::Receiver<UpMsg>, mpsc::Sender<DownMsg>)> {
183        let mut up = self.inner.up_rx.lock().unwrap_or_else(|p| p.into_inner());
184        let mut down = self.inner.down_tx.lock().unwrap_or_else(|p| p.into_inner());
185        if up.is_none() || down.is_none() {
186            return Err(ssh_diag::session_already_pumped());
187        }
188        Ok((up.take().unwrap(), down.take().unwrap()))
189    }
190}
191
192impl PartialEq for SshSessionTag {
193    fn eq(&self, other: &Self) -> bool {
194        self.inner.id == other.inner.id
195    }
196}
197
198impl fmt::Display for SshSessionTag {
199    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
200        let peer = self
201            .inner
202            .peer_addr
203            .map(|addr| addr.to_string())
204            .unwrap_or_default();
205        match &self.inner.username {
206            Some(user) => write!(
207                formatter,
208                "SSH_SESSION(sess-{} {}@{})",
209                self.inner.id, user, peer
210            ),
211            None => write!(formatter, "SSH_SESSION(sess-{} {})", self.inner.id, peer),
212        }
213    }
214}