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