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}
72
73/// Handle to one dequeued SSH session instance.
74///
75/// Cloning the value shares the session; metadata reads never consume.
76/// Display shows id and peer only: the command string may carry secrets.
77#[oxdock_type(name = "SSH_SESSION")]
78#[derive(Debug, Clone)]
79pub struct SshSessionTag {
80    inner: Arc<SshSessionInner>,
81}
82
83impl SshSessionTag {
84    pub fn new(
85        command: Option<String>,
86        username: Option<String>,
87        peer_addr: Option<SocketAddr>,
88        pty_size: crate::state::SharedPtySize,
89        up_rx: mpsc::Receiver<UpMsg>,
90        down_tx: mpsc::Sender<DownMsg>,
91    ) -> Self {
92        Self {
93            inner: Arc::new(SshSessionInner {
94                id: SESSION_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
95                command,
96                username,
97                peer_addr,
98                pty_size,
99                up_rx: Mutex::new(Some(up_rx)),
100                down_tx: Mutex::new(Some(down_tx)),
101            }),
102        }
103    }
104
105    pub fn command(&self) -> Option<String> {
106        self.inner.command.clone()
107    }
108
109    pub fn username(&self) -> Option<String> {
110        self.inner.username.clone()
111    }
112
113    pub fn peer_addr(&self) -> Option<SocketAddr> {
114        self.inner.peer_addr
115    }
116
117    /// Snapshot this session's terminal dimensions.
118    pub fn pty_size(&self) -> crate::state::PtySize {
119        crate::state::snapshot_pty_size(&self.inner.pty_size).size
120    }
121
122    /// Shareable handle to this session's size cell, for its pty pump.
123    pub fn pty_size_handle(&self) -> crate::state::SharedPtySize {
124        Arc::clone(&self.inner.pty_size)
125    }
126
127    /// Take the pump ends for `SSH_PUMP_CHANNEL`. A second pump on the
128    /// same session bails instead of splitting bytes across pumps. The
129    /// check runs before either take so a failed pump mutates nothing.
130    pub fn take_pump_ends(&self) -> Result<(mpsc::Receiver<UpMsg>, mpsc::Sender<DownMsg>)> {
131        let mut up = self.inner.up_rx.lock().unwrap_or_else(|p| p.into_inner());
132        let mut down = self.inner.down_tx.lock().unwrap_or_else(|p| p.into_inner());
133        if up.is_none() || down.is_none() {
134            bail!("SSH session already pumped");
135        }
136        Ok((up.take().unwrap(), down.take().unwrap()))
137    }
138}
139
140impl PartialEq for SshSessionTag {
141    fn eq(&self, other: &Self) -> bool {
142        self.inner.id == other.inner.id
143    }
144}
145
146impl fmt::Display for SshSessionTag {
147    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148        let peer = self
149            .inner
150            .peer_addr
151            .map(|addr| addr.to_string())
152            .unwrap_or_default();
153        match &self.inner.username {
154            Some(user) => write!(
155                formatter,
156                "SSH_SESSION(sess-{} {}@{})",
157                self.inner.id, user, peer
158            ),
159            None => write!(formatter, "SSH_SESSION(sess-{} {})", self.inner.id, peer),
160        }
161    }
162}