oxdock-ssh-plugin 0.46.0-alpha

Ephemeral user-space SSH server and client for OxDock scripts, bridged to stdio pipelines through the Engine facade.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Server lifetime state: session queue, shutdown teardown, handle Drop.
//!
//! There is deliberately no global registry: every `SSH_SERVER` DSL value
//! carries an `Arc<ServerState>`, so server lifetime follows handle
//! lifetime. When the last handle drops, [`ServerState::drop`] signals the
//! runtime thread and wakes every waiter; nothing leaks.

use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use bytes::Bytes;
use tokio::sync::mpsc;

/// How long `SSH_CLOSE` waits for the runtime thread before detaching it.
pub const CLOSE_JOIN_TIMEOUT: Duration = Duration::from_secs(5);

/// Bounded handoff depth between the russh runtime and sync pump threads.
/// Bounds memory under a slow consumer; the async side applies SSH
/// backpressure instead of growing a queue.
pub const CHANNEL_CAPACITY: usize = 64;

/// One direction of the pump-to-wire handoff.
#[derive(Debug)]
pub enum DownMsg {
    Data(Bytes),
    Eof,
    /// Server-to-client `exit-status` request (RFC 4254 section 6.10).
    /// Queued FIFO like every other message, so bytes sent before it
    /// still flush first. The wire writer sends the request, then keeps
    /// serving the queue: `Eof` and close still follow from the pump.
    ExitStatus(u32),
}

/// Wire bytes toward the DSL pipes. `Eof` is a half-close: no more bytes
/// will arrive, but the channel itself stays open until the pump drains
/// and tears down. Queued before any later messages (FIFO), so bytes
/// sent before the EOF still flush first.
#[derive(Debug)]
pub enum UpMsg {
    Data(Bytes),
    Eof,
}

/// A freshly authenticated channel waiting for an `SSH_DEQUEUE` call.
/// The wire-writer task is already spawned; the pump side of the queue
/// pairs it with explicit DSL pipes.
#[derive(Debug)]
pub struct PendingSession {
    /// Command from an `exec` request, if the client used one.
    pub exec_command: Option<String>,
    /// Authenticated username, captured at auth time.
    pub username: Option<String>,
    /// Peer socket address, captured at connection time.
    pub peer_addr: Option<SocketAddr>,
    /// Terminal dimensions for this connection's channels: the handler
    /// records pty and window-change requests here, and the session's pty
    /// pump polls it. Owned per connection, never shared across guests.
    pub pty_size: SharedPtySize,
    /// Wire bytes toward the DSL pipes. Bounded ([`CHANNEL_CAPACITY`]):
    /// the async sender applies SSH backpressure instead of growing a
    /// queue. Closed by the wire side when the channel goes away, so the
    /// pump observes the end by drain.
    pub up_rx: mpsc::Receiver<UpMsg>,
    /// DSL bytes toward the wire. The pump sends [`DownMsg::Eof`] on
    /// stdin EOF, then drops the sender.
    pub down_tx: mpsc::Sender<DownMsg>,
}

/// Dequeue state shared between the russh runtime thread (producers) and
/// `SSH_ACCEPT` worker threads (consumers).
#[derive(Debug)]
pub struct QueueState {
    sessions: VecDeque<PendingSession>,
    shutdown: bool,
}

/// Dequeue outcome for one wait.
pub enum Dequeue {
    Session(PendingSession),
    Shutdown,
    /// Task cancelled while parked: the cancel bridge poked the queue
    /// awake and the hub reads cancelled.
    Cancelled,
    /// Nothing queued right now (`try_pop` only; blocking waits never
    /// return this).
    Empty,
}

/// Multi-consumer session queue: any number of concurrent `SSH_ACCEPT`
/// calls pop distinct sessions FIFO.
#[derive(Debug)]
pub struct SessionQueue {
    state: Mutex<QueueState>,
    cvar: Condvar,
}

impl SessionQueue {
    pub fn new() -> Self {
        Self {
            state: Mutex::new(QueueState {
                sessions: VecDeque::new(),
                shutdown: false,
            }),
            cvar: Condvar::new(),
        }
    }

    /// Enqueue an authenticated session from the runtime thread.
    /// Never blocks, never holds the lock across an await.
    pub fn push(&self, session: PendingSession) {
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if guard.shutdown {
            return;
        }
        guard.sessions.push_back(session);
        self.cvar.notify_one();
    }

    /// Signal teardown and wake every waiter. Poison-tolerant and
    /// non-blocking: safe to call from `Drop`.
    pub fn signal_shutdown(&self) {
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        guard.shutdown = true;
        self.cvar.notify_all();
    }

    /// Non-blocking dequeue attempt.
    pub fn try_pop(&self) -> Dequeue {
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        if let Some(session) = guard.sessions.pop_front() {
            Dequeue::Session(session)
        } else if guard.shutdown {
            Dequeue::Shutdown
        } else {
            Dequeue::Empty
        }
    }

    /// Block until a session arrives, the server shuts down, or the
    /// hub reads cancelled. No timeout: the caller pokes the queue
    /// awake on cancel (see `dequeue_session`), the predicate observes
    /// the hub, and the waiter ends. Spurious wakes re-check.
    pub fn wait_blocking(&self, hub: &oxdock_process::CancelHub) -> Dequeue {
        let mut guard = self
            .state
            .lock()
            .unwrap_or_else(|poison| poison.into_inner());
        guard = self
            .cvar
            .wait_while(guard, |state| {
                state.sessions.is_empty() && !state.shutdown && !hub.is_cancelled()
            })
            .unwrap_or_else(|poison| poison.into_inner());
        if let Some(session) = guard.sessions.pop_front() {
            Dequeue::Session(session)
        } else if hub.is_cancelled() {
            Dequeue::Cancelled
        } else {
            Dequeue::Shutdown
        }
    }

    /// Wake every waiter without shutting down. The cancel bridge in
    /// `dequeue_session` calls this when the task cancels so a waiter
    /// parked with no traffic still ends, then re-checks cancellation.
    pub fn poke(&self) {
        self.cvar.notify_all();
    }
}

impl Default for SessionQueue {
    fn default() -> Self {
        Self::new()
    }
}

/// Shutdown signal from the DSL-visible handle to the runtime thread.
#[derive(Debug)]
pub enum ShutdownSignal {
    Close,
}

/// Terminal dimensions for one connection's channels, requested by the
/// outer client. Each connection owns its cell (minted in `new_client`,
/// attached to the session at announce), so concurrent guests never see
/// each other's sizes. Zero rows/cols (clients that report none) clamp to
/// the 24x80 default at apply time, never stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PtySize {
    pub rows: u16,
    pub cols: u16,
}

impl PtySize {
    pub fn new(rows: u32, cols: u32) -> Self {
        Self {
            rows: rows.try_into().unwrap_or(u16::MAX),
            cols: cols.try_into().unwrap_or(u16::MAX),
        }
    }

    /// Kernel-ready size: zeros fall back to 24x80 since a 0x0 pty
    /// breaks fullscreen apps (they lay out for a nonexistent screen).
    pub fn effective(&self) -> (u16, u16) {
        (
            if self.rows == 0 { 24 } else { self.rows },
            if self.cols == 0 { 80 } else { self.cols },
        )
    }
}

impl Default for PtySize {
    fn default() -> Self {
        Self { rows: 24, cols: 80 }
    }
}

/// Shareable terminal-size cell: one instance per connection, held by
/// the russh handler (writer: pty and window-change requests) and the
/// dequeued session (reader: the session's pty pump polls it).
///
/// The sequence number distinguishes "outer requested this" from "nobody
/// asked yet": a pump that opened on explicit dimensions must not have
/// them clobbered by a stale default on its first poll.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PtySizeStamp {
    pub size: PtySize,
    pub(crate) seq: u64,
}

impl PtySizeStamp {
    fn bump(&mut self, size: PtySize) {
        self.size = size;
        self.seq = self.seq.wrapping_add(1);
    }
}

pub type SharedPtySize = Arc<SizeCell>;

/// Shareable terminal-size cell: one instance per connection, held by
/// the connection handler (writer) and the session's pty pump. The
/// condvar lets a resize watcher sleep until a window-change lands
/// instead of polling the sequence.
#[derive(Debug)]
pub struct SizeCell {
    stamp: Mutex<PtySizeStamp>,
    changed: Condvar,
}

/// Fresh size cell at the default dimensions, sequence zero.
pub fn shared_pty_size() -> SharedPtySize {
    Arc::new(SizeCell {
        stamp: Mutex::new(PtySizeStamp {
            size: PtySize::default(),
            seq: 0,
        }),
        changed: Condvar::new(),
    })
}

/// Record dimensions on a shared cell (poison-tolerant) and wake its
/// resize watcher. Notifies under the stamp lock: the watcher holds
/// the same lock across its check-to-sleep transition, so the notify
/// can never slip between the check and the sleep.
pub fn set_shared_pty_size(cell: &SharedPtySize, size: PtySize) {
    if let Ok(mut slot) = cell.stamp.lock() {
        slot.bump(size);
        cell.changed.notify_all();
    }
}

/// Snapshot a shared cell with its sequence (poison-tolerant).
pub fn snapshot_pty_size(cell: &SharedPtySize) -> PtySizeStamp {
    cell.stamp
        .lock()
        .map(|slot| *slot)
        .unwrap_or_else(|poison| *poison.into_inner())
}

/// Wake the cell's watcher without recording a size: teardown retires
/// the resize watcher this way, so no watcher outlives its session.
/// Notifies under the stamp lock, same lost-wakeup reasoning as
/// [`set_shared_pty_size`].
pub fn poke_size(cell: &SharedPtySize) {
    if let Ok(slot) = cell.stamp.lock() {
        cell.changed.notify_all();
        drop(slot);
    }
}

/// Sleep until the cell's sequence moves past `seen` (window-change
/// arrived) or `stop` reads true (teardown). Returns the fresh
/// snapshot; the caller re-checks `stop` to tell the two apart.
pub fn wait_size_changed(cell: &SharedPtySize, seen: u64, stop: &AtomicBool) -> PtySizeStamp {
    let mut slot = cell
        .stamp
        .lock()
        .unwrap_or_else(|poison| poison.into_inner());
    while slot.seq == seen && !stop.load(Ordering::SeqCst) {
        slot = cell
            .changed
            .wait(slot)
            .unwrap_or_else(|poison| poison.into_inner());
    }
    *slot
}

/// Lifetime state behind one `SSH_SERVER` value.
#[derive(Debug)]
pub struct ServerState {
    id: String,
    local_addr: SocketAddr,
    /// Display/MAP address text: the physical bind for socket servers, the
    /// virtual endpoint echo when socketless (`--offline`).
    addr_text: String,
    queue: Arc<SessionQueue>,
    /// Signal to the runtime thread. `None` once consumed by `SSH_CLOSE`.
    /// Plain std channel: `Sender` is `Send + Sync` and `send` never blocks.
    shutdown_tx: Mutex<Option<std::sync::mpsc::Sender<ShutdownSignal>>>,
    /// Runtime thread handle, taken by `SSH_CLOSE` for a bounded join.
    /// Dropped (detached) if the handle value dies first; the thread then
    /// self-reaps when sessions drain. `None` for socketless servers,
    /// which spawn no thread.
    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
    /// The endpoint this server was acquired for, plus the registry
    /// holding its slot: close/drop frees the slot for re-serve loops.
    registry: Arc<oxdock_net_plugin::EndpointRegistry>,
    endpoint: oxdock_net_plugin::EndpointKey,
}

/// Construction bundle for [`ServerState::new`]: identity, runtime
/// halves, and endpoint bookkeeping in one argument (stays under the
/// argument-count lint as the surface grows).
///
/// [`ServerState::new`]: ServerState::new
pub struct ServerConfig {
    pub id: String,
    pub local_addr: SocketAddr,
    pub addr_text: String,
    pub queue: Arc<SessionQueue>,
    pub shutdown_tx: std::sync::mpsc::Sender<ShutdownSignal>,
    pub thread: Option<std::thread::JoinHandle<()>>,
    pub registry: Arc<oxdock_net_plugin::EndpointRegistry>,
    pub endpoint: oxdock_net_plugin::EndpointKey,
}

impl ServerState {
    pub fn new(config: ServerConfig) -> Self {
        Self {
            id: config.id,
            local_addr: config.local_addr,
            addr_text: config.addr_text,
            queue: config.queue,
            shutdown_tx: Mutex::new(Some(config.shutdown_tx)),
            thread: Mutex::new(config.thread),
            registry: config.registry,
            endpoint: config.endpoint,
        }
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn local_addr(&self) -> SocketAddr {
        self.local_addr
    }

    /// Address text for display and result MAPs: the physical bind for
    /// socket servers, the virtual endpoint echo when socketless.
    pub fn addr_text(&self) -> &str {
        &self.addr_text
    }

    pub fn queue(&self) -> &Arc<SessionQueue> {
        &self.queue
    }

    /// Best-effort shutdown: wake queue waiters, nudge the runtime
    /// thread, and free the registry slot. Shared by `SSH_CLOSE` and
    /// `Drop`; never blocks, never joins.
    pub fn request_shutdown(&self) {
        self.queue.signal_shutdown();
        if let Ok(mut slot) = self.shutdown_tx.lock()
            && let Some(tx) = slot.take()
        {
            let _ = tx.send(ShutdownSignal::Close);
        }
        self.registry.release(&self.endpoint);
    }

    /// Bounded join of the runtime thread. Returns true when the thread
    /// exited within `timeout`; on timeout the thread is detached and
    /// self-reaps once sessions drain.
    pub fn join_thread(&self, timeout: Duration) -> bool {
        let handle = self
            .thread
            .lock()
            .map(|mut slot| slot.take())
            .unwrap_or(None);
        let Some(handle) = handle else {
            return true;
        };
        let deadline = Instant::now() + timeout;
        loop {
            if handle.is_finished() {
                let _ = handle.join();
                return true;
            }
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
}

impl Drop for ServerState {
    fn drop(&mut self) {
        self.request_shutdown();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pending_pair() -> (PendingSession, mpsc::Sender<DownMsg>) {
        let (_up_tx, up_rx) = mpsc::channel(CHANNEL_CAPACITY);
        let (down_tx, _down_rx) = mpsc::channel(1);
        let session = PendingSession {
            exec_command: None,
            username: None,
            peer_addr: None,
            pty_size: shared_pty_size(),
            up_rx,
            down_tx: down_tx.clone(),
        };
        (session, down_tx)
    }

    #[test]
    fn shutdown_wakes_empty_waiter() {
        // No timeout anymore: the waiter parks in a blocking wait and
        // the shutdown signal wakes it.
        let queue = SessionQueue::new();
        let hub = oxdock_process::CancelHub::new();
        std::thread::scope(|scope| {
            let waiter = scope.spawn(|| queue.wait_blocking(&hub));
            std::thread::sleep(Duration::from_millis(50));
            queue.signal_shutdown();
            assert!(matches!(
                waiter.join().expect("waiter joins"),
                Dequeue::Shutdown
            ));
        });
    }

    #[test]
    fn cancel_wakes_empty_waiter() {
        // The dequeue cancel bridge: hub fires, queue poked, waiter
        // ends with Cancelled instead of hanging.
        let queue = SessionQueue::new();
        let hub = oxdock_process::CancelHub::new();
        std::thread::scope(|scope| {
            let waiter = scope.spawn(|| queue.wait_blocking(&hub));
            std::thread::sleep(Duration::from_millis(50));
            hub.mark_cancelled();
            queue.poke();
            assert!(matches!(
                waiter.join().expect("waiter joins"),
                Dequeue::Cancelled
            ));
        });
    }

    #[test]
    fn size_change_wakes_watcher() {
        let cell = shared_pty_size();
        let seen = snapshot_pty_size(&cell).seq;
        let stop = AtomicBool::new(false);
        std::thread::scope(|scope| {
            let watcher = scope.spawn(|| wait_size_changed(&cell, seen, &stop));
            std::thread::sleep(Duration::from_millis(50));
            set_shared_pty_size(&cell, PtySize::new(40, 120));
            let snapshot = watcher.join().expect("watcher joins");
            assert_eq!(snapshot.size, PtySize::new(40, 120));
            assert_ne!(snapshot.seq, seen);
        });
    }

    #[test]
    fn fifo_ordering() {
        let queue = SessionQueue::new();
        let (first, _) = pending_pair();
        let (second, _) = pending_pair();
        queue.push(first);
        queue.push(second);
        assert!(matches!(queue.try_pop(), Dequeue::Session(_)));
        assert!(matches!(queue.try_pop(), Dequeue::Session(_)));
        assert!(matches!(queue.try_pop(), Dequeue::Empty));
    }

    #[test]
    fn push_after_shutdown_dropped() {
        let queue = SessionQueue::new();
        queue.signal_shutdown();
        let (session, _) = pending_pair();
        queue.push(session);
        assert!(matches!(queue.try_pop(), Dequeue::Shutdown));
    }
}