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