Skip to main content

oxdock_ssh_plugin/
funcs.rs

1//! The `SSH` host module: `SERVE`, `ACCEPT` / `DEQUEUE` + `PUMP_CHANNEL`,
2//! `CLOSE`, `CONNECT`, `PUMP`.
3//!
4//! Pipe direction convention (fixed for every func): `out_pipe` carries
5//! bytes produced by the wire side (the DSL reads them), `in_pipe`
6//! carries bytes consumed by the wire side (the DSL writes them).
7
8use std::collections::BTreeMap;
9use std::sync::atomic::AtomicBool;
10use std::sync::{Arc, OnceLock};
11use std::time::Duration;
12
13use anyhow::{Context, Result, bail};
14use oxdock_core::{
15    Field, FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration, NativeFn, OxDockFn,
16    OxDockType, ParamOption, RecordSchema, StepCtx, TypeTag, Value,
17};
18use oxdock_func_macro::oxdock_func;
19use oxdock_net_plugin::{AcquiredListener, EndpointKey, EndpointRegistry, acquire_listener};
20use oxdock_pipe::PipeHandle;
21use oxdock_process::ProcessManager;
22use russh::keys::{Algorithm, PrivateKey};
23
24use crate::bridge::{pump_pipe_to_pipe, pump_session};
25use crate::keys::load_or_create_host_key;
26use crate::runtime::{connect_runtime, connect_session};
27use crate::state::{
28    CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
29};
30use crate::types::{SshServerTag, SshSessionTag};
31use crate::validate::parse_serve_endpoint;
32
33/// Unique server ids per process.
34static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
35
36/// Dequeue tick: shutdown and cancellation surface within a few ticks.
37const DEQUEUE_TICK: Duration = Duration::from_millis(10);
38
39/// Block until the queue yields an authenticated session (or teardown).
40/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper.
41fn dequeue_session<P: ProcessManager>(
42    cx: &StepCtx<P>,
43    queue: &Arc<SessionQueue>,
44    func: &str,
45) -> Result<PendingSession> {
46    loop {
47        match queue.try_pop() {
48            Dequeue::Session(session) => return Ok(session),
49            Dequeue::Shutdown => bail!("{func}: server is closed"),
50            Dequeue::Empty => {}
51        }
52        match queue.wait_for_session(DEQUEUE_TICK) {
53            Dequeue::Session(session) => return Ok(session),
54            Dequeue::Shutdown => bail!("{func}: server is closed"),
55            Dequeue::Empty => {}
56        }
57        if cx.is_cancelled() {
58            bail!("{func}: task cancelled");
59        }
60    }
61}
62
63/// Dequeue one authenticated session and expose its metadata before any
64/// byte pumping starts, so scripts can route on the requested command or
65/// client identity. Must run inside `ASYNC`. Returns a MAP with
66/// `session` (SSH_SESSION), `command` (STRING, empty for shells),
67/// `username` and `addr` (STRINGs, empty when unknown).
68///
69/// Routing shape: compare the dequeued command against known commands,
70/// build a fresh pipe pair per session, and pump a synthetic reply with
71/// `SSH_PUMP_CHANNEL`. The server sends first: the client side never
72/// EOFs its input, so the reply cannot race teardown. This complete
73/// program runs end to end under the docs conformance suite.
74///
75/// ```oxdock
76/// IMPORT [STD, SSH]
77/// LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-demo", {username: "u", password: "p"})
78///
79/// # Serve: dequeue one session and pump a synthetic reply.
80/// LET $in: PIPE
81/// LET $out: PIPE
82/// LET $w: HANDLE = ASYNC {
83///     LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
84///     ASSERT_CONTAINS $sess "session"
85///     ASSERT_CONTAINS $sess "command"
86///     ASSERT_CONTAINS $sess "username"
87///     ASSERT_CONTAINS $sess "addr"
88///     ASSERT_EQ $sess.username "u"
89///     SSH_PUMP_CHANNEL($sess.session, $in, $out)
90/// }
91///
92/// # Connect a client to the server.
93/// LET $cin: PIPE
94/// LET $cout: PIPE
95/// LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-demo", "u", "p", $cin, $cout) }
96///
97/// # Greet through the server pipe and wait for delivery.
98/// WITH_IO [stdout=$in] ECHO "server-greeting"
99/// LET $info: MAP<ANY> = INSPECT($cout)
100/// LET $empty: BOOL = $info.buffer_bytes == 0
101/// WHILE $empty {
102///     SLEEP 100ms
103///     $info = INSPECT($cout)
104///     $empty = $info.buffer_bytes == 0
105/// }
106/// ASSERT_CONTAINS $cout "server-greeting"
107///
108/// # Shut everything down.
109/// AWAIT $w
110/// CANCEL $c
111/// SSH_CLOSE($m.server)
112/// ```
113///
114#[oxdock_func(
115    returns = TypeTag::Record(dequeue_result_fields()),
116    summary = "Dequeue one SSH session with its metadata."
117)]
118fn ssh_dequeue<P: ProcessManager>(
119    cx: &mut StepCtx<P>,
120    /// Server handle from `SSH_SERVE`.
121    server: SshServerTag,
122) -> Result<Value> {
123    if !cx.is_async_task() {
124        bail!(
125            "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
126        );
127    }
128    let state = Arc::clone(server.state());
129    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
130    let command = session.exec_command.clone().unwrap_or_default();
131    let username = session.username.clone().unwrap_or_default();
132    let addr = session
133        .peer_addr
134        .map(|addr| addr.to_string())
135        .unwrap_or_default();
136    let tag = SshSessionTag::new(
137        session.exec_command,
138        session.username,
139        session.peer_addr,
140        session.pty_size,
141        session.up_rx,
142        session.down_tx,
143    );
144    let mut map = BTreeMap::new();
145    map.insert(
146        "session".to_string(),
147        Value::mint_heap(SshSessionTag::descriptor(), tag),
148    );
149    map.insert("command".to_string(), Value::string(command));
150    map.insert("username".to_string(), Value::string(username));
151    map.insert("addr".to_string(), Value::string(addr));
152    Ok(Value::map(map))
153}
154
155/// Read a required STRING key from the options MAP. Missing, non-string,
156/// or blank binds bail naming the key: a server without credentials is
157/// meaningless, so there is no default.
158fn required_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<String> {
159    let Some(value) = map.get(key) else {
160        bail!("{func} option '{key}' is required");
161    };
162    let Some(s) = value.as_str() else {
163        bail!(
164            "{func} option '{key}' must be a STRING, got {}",
165            value.type_name()
166        );
167    };
168    if s.trim().is_empty() {
169        bail!("{func} option '{key}' must not be empty");
170    }
171    Ok(s.to_string())
172}
173
174/// Read an optional STRING key from the options MAP. Missing, empty, or
175/// whitespace-only binds `None`; present non-strings bail.
176fn optional_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<Option<String>> {
177    let Some(value) = map.get(key) else {
178        return Ok(None);
179    };
180    let Some(s) = value.as_str() else {
181        bail!(
182            "{func} option '{key}' must be a STRING, got {}",
183            value.type_name()
184        );
185    };
186    let trimmed = s.trim();
187    if trimmed.is_empty() {
188        return Ok(None);
189    }
190    Ok(Some(s.to_string()))
191}
192
193/// Spin up an SSH server on a virtual service endpoint with the given
194/// credentials. `bind` is a logical port (`"2251"`) or service name:
195/// physical binds in-script are rejected, `0` is reserved for the CLI
196/// outer mapping. `options` is a MAP with required `username`/`password`
197/// STRINGs (a server without credentials is meaningless, so blanks bail)
198/// and the optional `key_path` STRING (workspace-relative OpenSSH Ed25519
199/// file, load-or-create; a leading `/` anchors to the workspace root like
200/// WRITE, and escapes still bail; absent or blank keeps the ephemeral
201/// in-memory key).
202/// SERVE options, shared by the registration metadata and the runtime
203/// key check: one source for the keys scripts may pass, so
204/// documentation and enforcement cannot drift apart.
205static SSH_SERVE_OPTIONS: &[ParamOption] = &[
206    ParamOption {
207        name: "username",
208        value: TypeTag::String,
209        required: true,
210        default: None,
211    },
212    ParamOption {
213        name: "password",
214        value: TypeTag::String,
215        required: true,
216        default: None,
217    },
218    ParamOption {
219        name: "key_path",
220        value: TypeTag::String,
221        required: false,
222        default: None,
223    },
224];
225
226/// Non-blocking: returns a MAP with `server` (SSH_SERVER),
227/// `addr` (STRING: the physical bind, or the virtual endpoint echo when
228/// socketless), `username` and `password` (STRINGs), and `virtual`
229/// (STRING echo). Memory services bail: SSH needs a TCP socket, so map
230/// the name with `-p`/`--listen`.
231fn ssh_serve<P: ProcessManager>(
232    cx: &mut StepCtx<P>,
233    registry: &Arc<EndpointRegistry>,
234    bind: String,
235    options: BTreeMap<String, Value>,
236) -> Result<Value> {
237    let map = &options;
238    oxdock_core::check_options(map, SSH_SERVE_OPTIONS, "SSH_SERVE")?;
239    let username = required_string(map, "SSH_SERVE", "username")?;
240    let password = required_string(map, "SSH_SERVE", "password")?;
241    let key_path = optional_string(map, "SSH_SERVE", "key_path")?;
242    let endpoint = parse_serve_endpoint(&bind)?;
243    let key = EndpointKey::tcp(endpoint);
244    let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
245    let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
246        Some(key) => key,
247        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
248            .context("generate ephemeral Ed25519 host key")?,
249    };
250    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
251    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
252    let queue = Arc::new(SessionQueue::new());
253    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
254    let (local_addr, addr_text, thread) = match acquired {
255        AcquiredListener::Tcp { listener, addr } => {
256            // The slot keeps the shared backlog socket; the runtime owns
257            // its own clone.
258            let owned = listener
259                .try_clone()
260                .context("SSH_SERVE cannot clone its listener")?;
261            let thread_queue = Arc::clone(&queue);
262            let thread_user = username.clone();
263            let thread_pass = password.clone();
264            let thread = std::thread::Builder::new()
265                .name(id.clone())
266                .spawn(move || {
267                    crate::runtime::serve(
268                        owned,
269                        host_key,
270                        thread_user,
271                        thread_pass,
272                        thread_queue,
273                        shutdown_rx,
274                    )
275                })
276                .context("SSH_SERVE cannot spawn the server thread")?;
277            (addr, addr.to_string(), Some(thread))
278        }
279        AcquiredListener::Memory => {
280            drop(shutdown_rx);
281            bail!(
282                "SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
283            )
284        }
285        AcquiredListener::Offline => {
286            // Socketless servers spawn no thread: DEQUEUE waits on the
287            // queue until close (test drivers push sessions via the
288            // queue). Dropping the receiver makes later shutdown sends a
289            // silent no-op.
290            drop(shutdown_rx);
291            (
292                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
293                key.endpoint.to_string(),
294                None,
295            )
296        }
297    };
298    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
299        id,
300        local_addr,
301        addr_text: addr_text.clone(),
302        queue,
303        shutdown_tx,
304        thread,
305        registry: Arc::clone(&registry),
306        endpoint: key.clone(),
307    }));
308    let mut map = BTreeMap::new();
309    map.insert(
310        "server".to_string(),
311        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
312    );
313    map.insert("addr".to_string(), Value::string(addr_text));
314    map.insert("username".to_string(), Value::string(username));
315    map.insert("password".to_string(), Value::string(password));
316    map.insert(
317        "virtual".to_string(),
318        Value::string(key.endpoint.to_string()),
319    );
320    Ok(Value::map(map))
321}
322
323/// Accept the next authenticated session and pump it through explicit
324/// pipes until the channel closes. Must run inside `ASYNC`. Returns a
325/// MAP with `closed` (BOOL) and `command` (STRING, empty for shells).
326/// Thin wrapper over `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` for worker loops
327/// that need no pre-pump inspection; use those directly to route on
328/// session metadata first. Returns a MAP with `closed` (BOOL) and
329/// `command` (STRING, empty for shells); the example below asserts both
330/// keys on the awaited result. The server sends first: the client side
331/// never EOFs its input, so the reply cannot race teardown. This
332/// complete program runs end to end under the docs conformance suite.
333///
334/// ```oxdock
335/// IMPORT [STD, SSH]
336/// LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-demo", {username: "u", password: "p"})
337///
338/// # Accept one session into fresh pipes.
339/// LET $in: PIPE
340/// LET $out: PIPE
341/// LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
342///
343/// # Connect a client to the server.
344/// LET $cin: PIPE
345/// LET $cout: PIPE
346/// LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-demo", "u", "p", $cin, $cout) }
347///
348/// # Greet through the server pipe and wait for delivery.
349/// WITH_IO [stdout=$in] ECHO "server-greeting"
350/// LET $info: MAP<ANY> = INSPECT($cout)
351/// LET $empty: BOOL = $info.buffer_bytes == 0
352/// WHILE $empty {
353///     SLEEP 100ms
354///     $info = INSPECT($cout)
355///     $empty = $info.buffer_bytes == 0
356/// }
357/// ASSERT_CONTAINS $cout "server-greeting"
358///
359/// # The awaited result carries both keys; then shut down.
360/// LET $done: MAP<ANY> = AWAIT $acc
361/// ASSERT_EQ $done.closed true
362/// ASSERT_CONTAINS $done "command"
363/// CANCEL $c
364/// SSH_CLOSE($m.server)
365/// ```
366///
367#[oxdock_func(returns = TypeTag::Record(&[Field {
368    name: "closed",
369    ty: TypeTag::Bool,
370    docs: "True when the session closed cleanly.",
371    optional: false,
372}]), summary = "Accept one SSH session into pipes.")]
373fn ssh_accept<P: ProcessManager>(
374    cx: &mut StepCtx<P>,
375    /// Server handle from `SSH_SERVE`.
376    server: SshServerTag,
377    /// Pipe carrying bytes consumed by the wire side.
378    in_pipe: PipeHandle,
379    /// Pipe carrying bytes produced by the wire side.
380    out_pipe: PipeHandle,
381) -> Result<Value> {
382    if !cx.is_async_task() {
383        bail!(
384            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
385        );
386    }
387    // Downstream pumps take `&Value`: re-wrap the extracted handles so
388    // every helper below keeps its Value-based shape.
389    let in_pipe = Value::pipe_handle(in_pipe);
390    let out_pipe = Value::pipe_handle(out_pipe);
391    let state = Arc::clone(server.state());
392    let cancel = AtomicBool::new(false);
393    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
394    pump_session(
395        cx,
396        &in_pipe,
397        &out_pipe,
398        session.up_rx,
399        session.down_tx,
400        &cancel,
401    )?;
402    let mut map = BTreeMap::new();
403    map.insert("closed".to_string(), Value::bool(true));
404    map.insert(
405        "command".to_string(),
406        Value::string(session.exec_command.unwrap_or_default()),
407    );
408    Ok(Value::map(map))
409}
410
411/// Pump a dequeued session between explicit DSL pipes until the channel
412/// closes. Must run inside `ASYNC`. The session ends are take-once: a
413/// second pump on the same session bails instead of splitting bytes.
414/// Returns a MAP with `closed` (BOOL).
415///
416#[oxdock_func(
417    returns = TypeTag::Record(&[Field {
418        name: "closed",
419        ty: TypeTag::Bool,
420        docs: "True when the session closed cleanly.",
421        optional: false,
422    }]),
423    summary = "Pump a dequeued SSH session through pipes."
424)]
425fn ssh_pump_channel<P: ProcessManager>(
426    cx: &mut StepCtx<P>,
427    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
428    session: SshSessionTag,
429    /// Pipe carrying bytes consumed by the wire side.
430    in_pipe: PipeHandle,
431    /// Pipe carrying bytes produced by the wire side.
432    out_pipe: PipeHandle,
433) -> Result<Value> {
434    if !cx.is_async_task() {
435        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
436    }
437    // Downstream pumps take `&Value`: re-wrap the extracted handles so
438    // every helper below keeps its Value-based shape.
439    let in_pipe = Value::pipe_handle(in_pipe);
440    let out_pipe = Value::pipe_handle(out_pipe);
441    let (up_rx, down_tx) = session.take_pump_ends()?;
442    let cancel = AtomicBool::new(false);
443    pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
444    let mut map = BTreeMap::new();
445    map.insert("closed".to_string(), Value::bool(true));
446    Ok(Value::map(map))
447}
448
449/// Shut a server down and join its runtime thread (bounded). Idempotent:
450/// returns BOOL true when no thread remains.
451///
452#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
453fn ssh_close<P: ProcessManager>(
454    cx: &mut StepCtx<P>,
455    /// Server handle from `SSH_SERVE`.
456    server: SshServerTag,
457) -> Result<Value> {
458    let _ = cx;
459    let state = Arc::clone(server.state());
460    state.request_shutdown();
461    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
462}
463
464/// Connect to an SSH server with distinct inner credentials and pump the
465/// shell channel through explicit pipes until it closes. Must run inside
466/// `ASYNC`, concurrently with the `SSH_PUMP` tasks (never before them).
467/// `target` is a logical port (`"2251"`: CLI-mapped address or loopback
468/// default), a service name (CLI-mapped address only; unmapped names are
469/// memory services and SSH needs TCP), a served address (`$m.addr`), or
470/// a `host:port` dial. Under `--offline` the dial bails before any DNS
471/// or socket work. Returns a MAP with `closed` (BOOL).
472fn ssh_connect<P: ProcessManager>(
473    cx: &mut StepCtx<P>,
474    registry: &Arc<EndpointRegistry>,
475    target: String,
476    username: String,
477    password: String,
478    in_pipe: Value,
479    out_pipe: Value,
480) -> Result<Value> {
481    if !cx.is_async_task() {
482        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
483    }
484    // Sandbox gate first: offline runs open no OS sockets.
485    if registry.is_offline() {
486        bail!("SSH_CONNECT failed: engine running in --offline mode");
487    }
488    if username.is_empty() {
489        bail!("SSH_CONNECT username must not be empty");
490    }
491    let addr = crate::validate::resolve_connect_addr(registry, &target)?;
492    let runtime = connect_runtime()?;
493    let session = runtime
494        .block_on(connect_session(&addr, &username, &password))
495        .context("SSH_CONNECT failed")?;
496    let crate::runtime::OutboundSession {
497        up_rx,
498        down_tx,
499        handle,
500        ..
501    } = session;
502    let cancel = AtomicBool::new(false);
503    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
504    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
505    pump?;
506    let mut map = BTreeMap::new();
507    map.insert("closed".to_string(), Value::bool(true));
508    Ok(Value::map(map))
509}
510
511/// Copy one pipe into another until EOF, then close the target.
512/// Returns the INT byte count. Either task placement works, as long as
513/// the other end is live (usually an `ASYNC` task).
514///
515#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
516fn ssh_pump<P: ProcessManager>(
517    cx: &mut StepCtx<P>,
518    /// Source pipe to drain.
519    from_pipe: PipeHandle,
520    /// Target pipe receiving the bytes (closed at EOF).
521    to_pipe: PipeHandle,
522) -> Result<Value> {
523    // `pump_pipe_to_pipe` takes `&Value`: re-wrap the extracted
524    // handles so the bridge keeps its Value-based shape.
525    let from_pipe = Value::pipe_handle(from_pipe);
526    let to_pipe = Value::pipe_handle(to_pipe);
527    let cancel = AtomicBool::new(false);
528    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
529    Ok(Value::int(total))
530}
531
532/// Run `argv` under a local pseudo-terminal sized from the dequeued
533/// session and pump it through explicit pipes until the child exits.
534/// `rows`/`cols` seed the initial size when positive; non-positive falls
535/// back to the session's requested size (the outer pty request, 24x80
536/// default). Outer window-change requests resize this session's terminal
537/// live; every session owns its size cell, so concurrent guests never
538/// observe each other. Must run inside `ASYNC`. Returns the INT exit
539/// code. Environment is inherited from the host process and layered with
540/// the script environment like `RUN`: block-scoped `ENV` (such as the
541/// session's `SSH_USER` / `SSH_CLIENT` / `SSH_SERVER` / `SSH_COMMAND`
542/// relay) reaches the child; the working directory comes from the script.
543///
544#[oxdock_func(
545    returns = TypeTag::Int,
546    summary = "Run a command under a sized local terminal into pipes."
547)]
548fn ssh_pty_run<P: ProcessManager>(
549    cx: &mut StepCtx<P>,
550    /// Session handle from `SSH_DEQUEUE`.
551    session: SshSessionTag,
552    /// Program and arguments to run.
553    argv: Vec<String>,
554    /// Terminal rows when positive, session size otherwise.
555    rows: i64,
556    /// Terminal columns when positive, session size otherwise.
557    cols: i64,
558    /// Pipe carrying bytes consumed by the child.
559    in_pipe: PipeHandle,
560    /// Pipe carrying bytes produced by the child.
561    out_pipe: PipeHandle,
562) -> Result<Value> {
563    if !cx.is_async_task() {
564        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
565    }
566    // `pump_pty_session` takes `&Value` pipes: re-wrap the extracted
567    // handles so the bridge keeps its Value-based shape.
568    let in_pipe = Value::pipe_handle(in_pipe);
569    let out_pipe = Value::pipe_handle(out_pipe);
570    let initial = if rows > 0 && cols > 0 {
571        crate::state::PtySize::new(rows as u32, cols as u32)
572    } else {
573        session.pty_size()
574    };
575    let cancel = AtomicBool::new(false);
576    let code = crate::pty::pump_pty_session(
577        cx,
578        &argv,
579        initial,
580        &session.pty_size_handle(),
581        &in_pipe,
582        &out_pipe,
583        &cancel,
584    )?;
585    Ok(Value::int(code))
586}
587
588/// Field table for the `SSH_SERVE` result bundle, backing the
589/// `SSH_SERVE_INFO` schema and the `SSH_SERVE` return tag: one source
590/// for the shape the host mints, so introspection, enforcement, and
591/// documentation cannot drift apart.
592fn serve_result_fields() -> &'static [Field] {
593    static FIELDS: OnceLock<Vec<Field>> = OnceLock::new();
594    FIELDS.get_or_init(|| {
595        vec![
596            Field {
597                name: "server",
598                ty: TypeTag::Custom(SshServerTag::descriptor()),
599                docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
600                optional: false,
601            },
602            Field {
603                name: "addr",
604                ty: TypeTag::String,
605                docs: "Bound socket address (`ip:port`) of the server.",
606                optional: false,
607            },
608            Field {
609                name: "username",
610                ty: TypeTag::String,
611                docs: "Configured username.",
612                optional: false,
613            },
614            Field {
615                name: "password",
616                ty: TypeTag::String,
617                docs: "Configured password.",
618                optional: false,
619            },
620            Field {
621                name: "virtual",
622                ty: TypeTag::String,
623                docs: "Virtual endpoint echo of the claimed slot.",
624                optional: false,
625            },
626        ]
627    })
628}
629
630/// Field table for the `SSH_DEQUEUE` result bundle, backing the
631/// `SSH_DEQUEUE_INFO` schema and the `SSH_DEQUEUE` return tag.
632fn dequeue_result_fields() -> &'static [Field] {
633    static FIELDS: OnceLock<Vec<Field>> = OnceLock::new();
634    FIELDS.get_or_init(|| {
635        vec![
636            Field {
637                name: "session",
638                ty: TypeTag::Custom(SshSessionTag::descriptor()),
639                docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
640                optional: false,
641            },
642            Field {
643                name: "command",
644                ty: TypeTag::String,
645                docs: "Executed command, empty for shells.",
646                optional: false,
647            },
648            Field {
649                name: "username",
650                ty: TypeTag::String,
651                docs: "Authenticated username, empty when unset.",
652                optional: false,
653            },
654            Field {
655                name: "addr",
656                ty: TypeTag::String,
657                docs: "Peer address, empty when unset.",
658                optional: false,
659            },
660        ]
661    })
662}
663
664/// The `SSH` host module: virtual-endpoint server plus client, bridged
665/// to DSL pipes. Generic over the process manager like every host module.
666pub fn module_with<P: ProcessManager>() -> HostModule<P> {
667    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
668}
669
670/// The `SSH` host module resolving through `registry`: `SSH_SERVE` and
671/// `SSH_CONNECT` close over it (hand-built entries; the `#[oxdock_func]`
672/// macro only generates closers-over-nothing). Everything else reaches
673/// the same registry through its `SSH_SERVER` handle.
674pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
675    HostModule {
676        name: "SSH".to_string(),
677        funcs: vec![
678            ssh_serve_registration(Arc::clone(&registry)),
679            SshAccept::registration(),
680            SshDequeue::registration(),
681            SshPumpChannel::registration(),
682            SshClose::registration(),
683            ssh_connect_registration(registry),
684            SshPump::registration(),
685            SshPtyRun::registration(),
686        ],
687        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
688        record_schemas: vec![
689            RecordSchema {
690                name: "SSH_SERVE_INFO",
691                fields: serve_result_fields(),
692            },
693            RecordSchema {
694                name: "SSH_DEQUEUE_INFO",
695                fields: dequeue_result_fields(),
696            },
697        ],
698    }
699}
700
701/// Hand-built `SSH_SERVE` entry: same shape the macro would emit (arity
702/// check, `STRING`/`Value` unpacking, metadata), plus the captured
703/// registry threaded into [`ssh_serve`].
704fn ssh_serve_registration<P: ProcessManager>(
705    registry: Arc<EndpointRegistry>,
706) -> HostRegistration<P> {
707    // One params vector feeds both the metadata and the arity check,
708    // so the two can never disagree: add a parameter once, here.
709    let params = vec![
710        FuncParam {
711            name: "bind".to_string(),
712            param_type: Some(TypeTag::String),
713            allowed: None,
714            docs: "Virtual service endpoint to serve (logical port or service name).",
715            options: None,
716            optional: false,
717        },
718        FuncParam {
719            name: "options".to_string(),
720            param_type: Some(TypeTag::Map),
721            allowed: None,
722            docs: "Server credentials and host key.",
723            options: Some(SSH_SERVE_OPTIONS),
724            optional: false,
725        },
726    ];
727    let arity = params.len();
728    let func: NativeFn<P> = Arc::new(move |cx, values| {
729        if values.len() != arity {
730            bail!(
731                "SSH_SERVE() expects {arity} argument(s), got {}",
732                values.len()
733            );
734        }
735        let mut values = values.into_iter();
736        let bind = match values.next().expect("arity checked above").as_str() {
737            Some(s) => s.to_string(),
738            None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
739        };
740        let options_value = values.next().expect("arity checked above");
741        let options = match options_value.as_map() {
742            Some(map) => map.clone(),
743            None => bail!(
744                "SSH_SERVE() argument `$options` must be a MAP, got {}",
745                options_value.type_name()
746            ),
747        };
748        ssh_serve(cx, &registry, bind, options)
749    });
750    HostRegistration::Stateful {
751        name: "SSH_SERVE".to_string(),
752        meta: FuncMeta {
753            name: "SSH_SERVE".to_string(),
754            // Assigned at registration, like the macro's markers.
755            module: String::new(),
756            kind: FuncKind::HostCtx,
757            params: Some(params),
758            returns: Some(TypeTag::Record(serve_result_fields())),
759            rpn: false,
760            summary: "Serve SSH on a virtual service endpoint.",
761            docs: "Serve SSH on a virtual service endpoint.",
762        },
763        func,
764    }
765}
766
767/// Hand-built `SSH_CONNECT` entry: same shape the macro would emit, plus
768/// the captured registry threaded into [`ssh_connect`].
769fn ssh_connect_registration<P: ProcessManager>(
770    registry: Arc<EndpointRegistry>,
771) -> HostRegistration<P> {
772    // One params vector feeds both the metadata and the arity check,
773    // so the two can never disagree: add a parameter once, here.
774    let params = vec![
775        FuncParam {
776            name: "target".to_string(),
777            param_type: Some(TypeTag::String),
778            allowed: None,
779            docs: "Dial target: logical port, service name, served address, or `host:port`.",
780            options: None,
781            optional: false,
782        },
783        FuncParam {
784            name: "username".to_string(),
785            param_type: Some(TypeTag::String),
786            allowed: None,
787            docs: "Inner credentials for the SSH session.",
788            options: None,
789            optional: false,
790        },
791        FuncParam {
792            name: "password".to_string(),
793            param_type: Some(TypeTag::String),
794            allowed: None,
795            docs: "Inner credentials for the SSH session.",
796            options: None,
797            optional: false,
798        },
799        FuncParam {
800            name: "in_pipe".to_string(),
801            param_type: Some(TypeTag::Pipe),
802            allowed: None,
803            docs: "Pipe carrying bytes consumed by the wire side.",
804            options: None,
805            optional: false,
806        },
807        FuncParam {
808            name: "out_pipe".to_string(),
809            param_type: Some(TypeTag::Pipe),
810            allowed: None,
811            docs: "Pipe carrying bytes produced by the wire side.",
812            options: None,
813            optional: false,
814        },
815    ];
816    let arity = params.len();
817    let func: NativeFn<P> = Arc::new(move |cx, values| {
818        if values.len() != arity {
819            bail!(
820                "SSH_CONNECT() expects {arity} argument(s), got {}",
821                values.len()
822            );
823        }
824        let mut values = values.into_iter();
825        let target = match values.next().expect("arity checked above").as_str() {
826            Some(s) => s.to_string(),
827            None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
828        };
829        let username = match values.next().expect("arity checked above").as_str() {
830            Some(s) => s.to_string(),
831            None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
832        };
833        let password = match values.next().expect("arity checked above").as_str() {
834            Some(s) => s.to_string(),
835            None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
836        };
837        let in_pipe = values.next().expect("arity checked above");
838        if in_pipe.as_pipe_handle().is_none() {
839            bail!(
840                "SSH_CONNECT() argument `$in_pipe` must be a PIPE, got {}",
841                in_pipe.type_name()
842            );
843        }
844        let out_pipe = values.next().expect("arity checked above");
845        if out_pipe.as_pipe_handle().is_none() {
846            bail!(
847                "SSH_CONNECT() argument `$out_pipe` must be a PIPE, got {}",
848                out_pipe.type_name()
849            );
850        }
851        ssh_connect(cx, &registry, target, username, password, in_pipe, out_pipe)
852    });
853    HostRegistration::Stateful {
854        name: "SSH_CONNECT".to_string(),
855        meta: FuncMeta {
856            name: "SSH_CONNECT".to_string(),
857            // Assigned at registration, like the macro's markers.
858            module: String::new(),
859            kind: FuncKind::HostCtx,
860            params: Some(params),
861            returns: Some(TypeTag::Map),
862            rpn: false,
863            summary: "Open an SSH client session into pipes.",
864            docs: "Open an SSH client session into pipes. Target shapes: a logical port (CLI-mapped address or loopback default), a service name (CLI-mapped address only), a served address, or a host:port dial.",
865        },
866        func,
867    }
868}