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::{Field, HostModule, OxDockFn, OxDockType, RecordSchema, StepCtx, TypeTag, Value};
15use oxdock_func_macro::oxdock_func;
16use oxdock_net_plugin::{
17    AcquiredListener, EndpointKey, EndpointRegistry, ServiceTarget, SocketRequirement,
18    acquire_listener, no_cli_mapping, parse_virtual_endpoint, resolve_service_target,
19};
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.
73///
74#[oxdock_func(
75    returns = TypeTag::Record(dequeue_result_fields()),
76    summary = "Dequeue one SSH session with its metadata."
77)]
78#[example(
79    name = "route one session",
80    code = r###"
81    IMPORT [STD, SSH]
82    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})
83
84    # Serve: dequeue one session and pump a synthetic reply.
85    LET $in: PIPE
86    LET $out: PIPE
87    LET $w: HANDLE = ASYNC {
88        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
89        ASSERT_EQ $sess.username "u"
90        SSH_PUMP_CHANNEL($sess.session, $in, $out)
91    }
92
93    # Connect a client to the server.
94    LET $cin: PIPE
95    LET $cout: PIPE
96    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }
97
98    # Close both inputs: each pump observes EOF, half-closes, and every
99    # task returns with no cancellation.
100    WITH_IO [stdout=$cin] ECHO "client-hello"
101    WITH_IO [stdout=$in] ECHO "server-greeting"
102    LET $cDone: MAP<ANY> = AWAIT $c
103    ASSERT_EQ $cDone.closed true
104    AWAIT $w
105    SSH_CLOSE($m.server)
106    "###
107)]
108fn ssh_dequeue<P: ProcessManager>(
109    cx: &mut StepCtx<P>,
110    /// Server handle from `SSH_SERVE`.
111    server: SshServerTag,
112) -> Result<Value> {
113    if !cx.is_async_task() {
114        bail!(
115            "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
116        );
117    }
118    let state = Arc::clone(server.state());
119    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
120    let command = session.exec_command.clone().unwrap_or_default();
121    let username = session.username.clone().unwrap_or_default();
122    let addr = session
123        .peer_addr
124        .map(|addr| addr.to_string())
125        .unwrap_or_default();
126    let tag = SshSessionTag::new(
127        session.exec_command,
128        session.username,
129        session.peer_addr,
130        session.pty_size,
131        session.up_rx,
132        session.down_tx,
133    );
134    let mut map = BTreeMap::new();
135    map.insert(
136        "session".to_string(),
137        Value::mint_heap(SshSessionTag::descriptor(), tag),
138    );
139    map.insert("command".to_string(), Value::string(command));
140    map.insert("username".to_string(), Value::string(username));
141    map.insert("addr".to_string(), Value::string(addr));
142    Ok(Value::map(map))
143}
144
145/// Spin up an SSH server on a runner-mapped service with the given
146/// credentials. `bind` is a service name; the runner maps it with
147/// `-p`/`--listen`, and unmapped services bail with the mapping hint
148/// (SSH needs a TCP socket, so there is no memory fallback).
149/// `options` is a MAP with required `username`/`password`
150/// STRINGs (a server without credentials is meaningless, so blanks bail)
151/// and the optional `key_path` STRING (workspace-relative OpenSSH Ed25519
152/// file, load-or-create; a leading `/` anchors to the workspace root like
153/// WRITE, and escapes still bail; absent or blank keeps the ephemeral
154/// in-memory key).
155/// Non-blocking: returns a MAP with `server` (SSH_SERVER),
156/// `addr` (STRING: the physical bind, or the virtual endpoint echo when
157/// socketless), `username` and `password` (STRINGs), and `virtual`
158/// (STRING echo). Unmapped and memory services bail with the CLI
159/// mapping hint: SSH needs a TCP socket, so map the name with
160/// `-p`/`--listen`.
161#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
162#[example(
163    name = "serve and close",
164    code = r###"
165    IMPORT [STD, SSH]
166    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
167    ASSERT_EQ $m.virtual "doc-ssh-serve"
168    SSH_CLOSE($m.server)
169    "###
170)]
171fn ssh_serve<P: ProcessManager>(
172    cx: &mut StepCtx<P>,
173    /// Service name to serve; the runner maps it with -p/--listen.
174    bind: String,
175    /// Server credentials and host key.
176    #[options("username: STRING", "password: STRING", "key_path?: STRING")]
177    options: BTreeMap<String, Value>,
178) -> Result<Value> {
179    let map = &options;
180    // Compositional reads: presence and blank stay domain errors (a
181    // server without credentials is meaningless, so there is no
182    // default); shapes already passed `check_options` in the wrapper.
183    let username = match map.get("username") {
184        Some(value) => {
185            let text = value.as_str().expect("check_options verified STRING");
186            if text.trim().is_empty() {
187                bail!("SSH_SERVE option 'username' must not be empty");
188            }
189            text.to_string()
190        }
191        None => bail!("SSH_SERVE option 'username' is required"),
192    };
193    let password = match map.get("password") {
194        Some(value) => {
195            let text = value.as_str().expect("check_options verified STRING");
196            if text.trim().is_empty() {
197                bail!("SSH_SERVE option 'password' must not be empty");
198            }
199            text.to_string()
200        }
201        None => bail!("SSH_SERVE option 'password' is required"),
202    };
203    let key_path = match map.get("key_path") {
204        Some(value) => {
205            let text = value.as_str().expect("check_options verified STRING");
206            if text.trim().is_empty() {
207                None
208            } else {
209                Some(text.to_string())
210            }
211        }
212        None => None,
213    };
214    let registry = cx
215        .module_state::<EndpointRegistry>("SSH")
216        .expect("SSH module registers its endpoint registry as module state");
217    let endpoint = parse_serve_endpoint(&bind)?;
218    let key = EndpointKey::tcp(endpoint);
219    let (acquired, registry) = acquire_listener(
220        &registry,
221        &key,
222        "SSH_SERVE",
223        SocketRequirement::SocketRequired,
224    )?;
225    let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
226        Some(key) => key,
227        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
228            .context("generate ephemeral Ed25519 host key")?,
229    };
230    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
231    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
232    let queue = Arc::new(SessionQueue::new());
233    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
234    let (local_addr, addr_text, thread) = match acquired {
235        AcquiredListener::Tcp { listener, addr } => {
236            // The slot keeps the shared backlog socket; the runtime owns
237            // its own clone.
238            let owned = listener
239                .try_clone()
240                .context("SSH_SERVE cannot clone its listener")?;
241            let thread_queue = Arc::clone(&queue);
242            let thread_user = username.clone();
243            let thread_pass = password.clone();
244            let thread = std::thread::Builder::new()
245                .name(id.clone())
246                .spawn(move || {
247                    crate::runtime::serve(
248                        owned,
249                        host_key,
250                        thread_user,
251                        thread_pass,
252                        thread_queue,
253                        shutdown_rx,
254                    )
255                })
256                .context("SSH_SERVE cannot spawn the server thread")?;
257            (addr, addr.to_string(), Some(thread))
258        }
259        AcquiredListener::Memory => {
260            // Defensive: `acquire_listener` with `SocketRequired` already
261            // bailed; the text still comes from the one shared helper.
262            drop(shutdown_rx);
263            return Err(no_cli_mapping("SSH_SERVE", &key.endpoint));
264        }
265        AcquiredListener::Offline => {
266            // Socketless servers spawn no thread: DEQUEUE waits on the
267            // queue until close (test drivers push sessions via the
268            // queue). Dropping the receiver makes later shutdown sends a
269            // silent no-op.
270            drop(shutdown_rx);
271            (
272                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
273                key.endpoint.to_string(),
274                None,
275            )
276        }
277    };
278    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
279        id,
280        local_addr,
281        addr_text: addr_text.clone(),
282        queue,
283        shutdown_tx,
284        thread,
285        registry: Arc::clone(&registry),
286        endpoint: key.clone(),
287    }));
288    let mut map = BTreeMap::new();
289    map.insert(
290        "server".to_string(),
291        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
292    );
293    map.insert("addr".to_string(), Value::string(addr_text));
294    map.insert("username".to_string(), Value::string(username));
295    map.insert("password".to_string(), Value::string(password));
296    map.insert(
297        "virtual".to_string(),
298        Value::string(key.endpoint.to_string()),
299    );
300    Ok(Value::map(map))
301}
302
303/// Accept the next authenticated session and pump it through explicit
304/// pipes until the channel closes. Must run inside `ASYNC`. Returns a
305/// MAP with `closed` (BOOL) and `command` (STRING, empty for shells).
306/// Thin wrapper over `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` for worker loops
307/// that need no pre-pump inspection; use those directly to route on
308/// session metadata first. Returns a MAP with `closed` (BOOL) and
309/// `command` (STRING, empty for shells); the example below asserts both
310/// keys on the awaited result. The server sends first: the client side
311/// never EOFs its input, so the reply cannot race teardown.
312///
313#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
314    name: "closed".to_string(),
315    ty: TypeTag::Bool,
316    docs: "True when the session closed cleanly.",
317    optional: false,
318}, Field {
319    name: "command".to_string(),
320    ty: TypeTag::String,
321    docs: "Executed command, empty for shells.",
322    optional: false,
323}])), summary = "Accept one SSH session into pipes.")]
324#[example(
325    name = "accept and close",
326    code = r###"
327    IMPORT [STD, SSH]
328    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
329    LET $in: PIPE
330    LET $out: PIPE
331    LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
332    LET $cin: PIPE
333    LET $cout: PIPE
334    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
335
336    # Close both inputs: each pump observes EOF, half-closes, and both
337    # tasks return their result maps with no cancellation.
338    WITH_IO [stdout=$cin] ECHO "client-hello"
339    WITH_IO [stdout=$in] ECHO "server-greeting"
340    LET $done: MAP<ANY> = AWAIT $acc
341    ASSERT_EQ $done.closed true
342    ASSERT_CONTAINS $done "command"
343    LET $cDone: MAP<ANY> = AWAIT $c
344    ASSERT_EQ $cDone.closed true
345    SSH_CLOSE($m.server)
346    "###
347)]
348fn ssh_accept<P: ProcessManager>(
349    cx: &mut StepCtx<P>,
350    /// Server handle from `SSH_SERVE`.
351    server: SshServerTag,
352    /// Pipe carrying bytes consumed by the wire side.
353    in_pipe: PipeHandle,
354    /// Pipe carrying bytes produced by the wire side.
355    out_pipe: PipeHandle,
356) -> Result<Value> {
357    if !cx.is_async_task() {
358        bail!(
359            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
360        );
361    }
362    // Downstream pumps take `&Value`: re-wrap the extracted handles so
363    // every helper below keeps its Value-based shape.
364    let in_pipe = Value::pipe_handle(in_pipe);
365    let out_pipe = Value::pipe_handle(out_pipe);
366    let state = Arc::clone(server.state());
367    let cancel = AtomicBool::new(false);
368    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
369    pump_session(
370        cx,
371        &in_pipe,
372        &out_pipe,
373        session.up_rx,
374        session.down_tx,
375        &cancel,
376    )?;
377    let mut map = BTreeMap::new();
378    map.insert("closed".to_string(), Value::bool(true));
379    map.insert(
380        "command".to_string(),
381        Value::string(session.exec_command.unwrap_or_default()),
382    );
383    Ok(Value::map(map))
384}
385
386/// Pump a dequeued session between explicit DSL pipes until the channel
387/// closes. Must run inside `ASYNC`. The session ends are take-once: a
388/// second pump on the same session bails instead of splitting bytes.
389/// Returns a MAP with `closed` (BOOL).
390///
391#[oxdock_func(
392    returns = TypeTag::Record(std::sync::Arc::from([Field {
393        name: "closed".to_string(),
394        ty: TypeTag::Bool,
395        docs: "True when the session closed cleanly.",
396        optional: false,
397    }])),
398    summary = "Pump a dequeued SSH session through pipes."
399)]
400#[example(
401    name = "pump a session",
402    code = r###"
403    IMPORT [STD, SSH]
404    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
405    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
406    LET $cin: PIPE
407    LET $cout: PIPE
408    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
409    WITH_IO [stdout=$cin] ECHO "client-hello"
410    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
411    LET $sin: PIPE
412    LET $sout: PIPE
413    LET $p: HANDLE = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
414    WITH_IO [stdout=$sin] ECHO "server-greeting"
415    LET $cDone: MAP<ANY> = AWAIT $c
416    ASSERT_EQ $cDone.closed true
417    LET $pDone: MAP<ANY> = AWAIT $p
418    ASSERT_EQ $pDone.closed true
419    SSH_CLOSE($m.server)
420    "###
421)]
422fn ssh_pump_channel<P: ProcessManager>(
423    cx: &mut StepCtx<P>,
424    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
425    session: SshSessionTag,
426    /// Pipe carrying bytes consumed by the wire side.
427    in_pipe: PipeHandle,
428    /// Pipe carrying bytes produced by the wire side.
429    out_pipe: PipeHandle,
430) -> Result<Value> {
431    if !cx.is_async_task() {
432        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
433    }
434    // Downstream pumps take `&Value`: re-wrap the extracted handles so
435    // every helper below keeps its Value-based shape.
436    let in_pipe = Value::pipe_handle(in_pipe);
437    let out_pipe = Value::pipe_handle(out_pipe);
438    let (up_rx, down_tx) = session.take_pump_ends()?;
439    let cancel = AtomicBool::new(false);
440    pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
441    let mut map = BTreeMap::new();
442    map.insert("closed".to_string(), Value::bool(true));
443    Ok(Value::map(map))
444}
445
446/// Shut a server down and join its runtime thread (bounded). Idempotent:
447/// returns BOOL true when no thread remains.
448///
449#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
450#[example(
451    name = "shut down",
452    code = r###"
453    IMPORT [STD, SSH]
454    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
455    LET $ok: BOOL = SSH_CLOSE($m.server)
456    ASSERT_EQ $ok true
457    "###
458)]
459fn ssh_close<P: ProcessManager>(
460    cx: &mut StepCtx<P>,
461    /// Server handle from `SSH_SERVE`.
462    server: SshServerTag,
463) -> Result<Value> {
464    let _ = cx;
465    let state = Arc::clone(server.state());
466    state.request_shutdown();
467    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
468}
469
470/// Connect to an SSH server with distinct inner credentials and pump the
471/// shell channel through explicit pipes until it closes. Must run inside
472/// `ASYNC`, concurrently with the `SSH_PUMP` tasks (never before them).
473/// `target` is a service name resolved through runner mappings: SSH
474/// needs a TCP socket, so unmapped services bail with the CLI mapping
475/// hint. Under `--offline` the dial bails before any socket work.
476/// Returns a MAP with `closed` (BOOL).
477#[oxdock_func(returns = TypeTag::Map, summary = "Open an SSH client session into pipes.")]
478#[example(
479    name = "connect and close",
480    code = r###"
481    IMPORT [STD, SSH]
482    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
483    LET $in: PIPE
484    LET $out: PIPE
485    LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
486    LET $cin: PIPE
487    LET $cout: PIPE
488    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
489
490    # Close both inputs: each pump observes EOF, half-closes, and both
491    # tasks return their result maps with no cancellation.
492    WITH_IO [stdout=$cin] ECHO "client-hello"
493    WITH_IO [stdout=$in] ECHO "server-greeting"
494    LET $done: MAP<ANY> = AWAIT $c
495    ASSERT_EQ $done.closed true
496    LET $adone: MAP<ANY> = AWAIT $acc
497    ASSERT_EQ $adone.closed true
498    SSH_CLOSE($m.server)
499    "###
500)]
501fn ssh_connect<P: ProcessManager>(
502    cx: &mut StepCtx<P>,
503    /// Dial target: a service name resolved through runner mappings.
504    target: String,
505    /// Inner credentials for the SSH session.
506    username: String,
507    /// Inner credentials for the SSH session.
508    password: String,
509    /// Pipe carrying bytes consumed by the wire side.
510    in_pipe: PipeHandle,
511    /// Pipe carrying bytes produced by the wire side.
512    out_pipe: PipeHandle,
513) -> Result<Value> {
514    if !cx.is_async_task() {
515        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
516    }
517    // Module-shared endpoint registry: stashed at registration, so
518    // this entry stays declarative with no captured closure.
519    let registry = cx
520        .module_state::<EndpointRegistry>("SSH")
521        .expect("SSH module registers its endpoint registry as module state");
522    // The session pump takes `&Value` pipes: re-wrap the extracted
523    // handles so the bridge keeps its Value-based shape.
524    let in_pipe = Value::pipe_handle(in_pipe);
525    let out_pipe = Value::pipe_handle(out_pipe);
526    // Sandbox gate first: offline runs open no OS sockets.
527    if registry.is_offline() {
528        bail!("SSH_CONNECT failed: engine running in --offline mode");
529    }
530    if username.is_empty() {
531        bail!("SSH_CONNECT username must not be empty");
532    }
533    // Strictly symbolic, resolved through the single shared resolver:
534    // served addresses and `host:port` shapes already failed in the
535    // parser below, so only runner-mapped services reach the dial.
536    let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
537    let key = EndpointKey::tcp(endpoint);
538    let addr = match resolve_service_target(
539        &registry,
540        &key,
541        "SSH_CONNECT",
542        SocketRequirement::SocketRequired,
543    )? {
544        ServiceTarget::Tcp(addr) => addr,
545        // Defensive: the shared resolver already bailed; same text.
546        ServiceTarget::Memory => {
547            return Err(no_cli_mapping("SSH_CONNECT", &key.endpoint));
548        }
549    };
550    let runtime = connect_runtime()?;
551    let session = runtime
552        .block_on(connect_session(&addr, &username, &password))
553        .context("SSH_CONNECT failed")?;
554    let crate::runtime::OutboundSession {
555        up_rx,
556        down_tx,
557        handle,
558        ..
559    } = session;
560    let cancel = AtomicBool::new(false);
561    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
562    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
563    pump?;
564    let mut map = BTreeMap::new();
565    map.insert("closed".to_string(), Value::bool(true));
566    Ok(Value::map(map))
567}
568
569/// Copy one pipe into another until EOF, then close the target.
570/// Returns the INT byte count. Either task placement works, as long as
571/// the other end is live (usually an `ASYNC` task).
572///
573#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
574#[example(
575    name = "copy",
576    code = r###"
577    # Closing the source ends the copy: the count proves the bytes moved.
578    IMPORT [STD, SSH]
579    LET $in: PIPE
580    WITH_IO [stdout=$in] ECHO "pump-me"
581    LET $out: PIPE
582    LET $n: INT = SSH_PUMP($in, $out)
583    ASSERT_EQ $n 8
584    WITH_IO [stdin=$out] READ_LINE $got
585    ASSERT_EQ $got "pump-me"
586    "###
587)]
588fn ssh_pump<P: ProcessManager>(
589    cx: &mut StepCtx<P>,
590    /// Source pipe to drain.
591    from_pipe: PipeHandle,
592    /// Target pipe receiving the bytes (closed at EOF).
593    to_pipe: PipeHandle,
594) -> Result<Value> {
595    // `pump_pipe_to_pipe` takes `&Value`: re-wrap the extracted
596    // handles so the bridge keeps its Value-based shape.
597    let from_pipe = Value::pipe_handle(from_pipe);
598    let to_pipe = Value::pipe_handle(to_pipe);
599    let cancel = AtomicBool::new(false);
600    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
601    Ok(Value::int(total))
602}
603
604/// Run `argv` under a local pseudo-terminal sized from the dequeued
605/// session and pump it through explicit pipes until the child exits.
606/// `rows`/`cols` seed the initial size when positive; non-positive falls
607/// back to the session's requested size (the outer pty request, 24x80
608/// default). Outer window-change requests resize this session's terminal
609/// live; every session owns its size cell, so concurrent guests never
610/// observe each other. Must run inside `ASYNC`. Returns the INT exit
611/// code. Environment is inherited from the host process and layered with
612/// the script environment like `RUN`: block-scoped `ENV` (such as the
613/// session's `SSH_USER` / `SSH_CLIENT` / `SSH_SERVER` / `SSH_COMMAND`
614/// relay) reaches the child; the working directory comes from the script.
615///
616#[oxdock_func(
617    returns = TypeTag::Int,
618    summary = "Run a command under a sized local terminal into pipes."
619)]
620#[example(
621    name = "run under a terminal",
622    code = r###"
623    IMPORT [STD, SSH]
624    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
625    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
626    LET $cin: PIPE
627    LET $cout: PIPE
628    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
629    WITH_IO [stdout=$cin] ECHO "client-hello"
630    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
631
632    # The client task only proved the session live: cancel it before the
633    # terminal run, so no two pumps share the session.
634    CANCEL $c
635    LET $pin: PIPE
636    LET $pout: PIPE
637    # Assert on the whole pipe: terminal streams carry setup noise ahead
638    # of child output, so line reads are version-dependent.
639    [family:unix] {
640        LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
641        LET $code: INT = AWAIT $t
642        ASSERT_EQ $code 0
643        ASSERT_CONTAINS $pout "pty-hi"
644    }
645    [family:windows] {
646        LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
647        LET $code: INT = AWAIT $t
648        ASSERT_EQ $code 0
649        ASSERT_CONTAINS $pout "pty-hi"
650    }
651    SSH_CLOSE($m.server)
652    "###
653)]
654fn ssh_pty_run<P: ProcessManager>(
655    cx: &mut StepCtx<P>,
656    /// Session handle from `SSH_DEQUEUE`.
657    session: SshSessionTag,
658    /// Program and arguments to run.
659    argv: Vec<String>,
660    /// Terminal rows when positive, session size otherwise.
661    rows: i64,
662    /// Terminal columns when positive, session size otherwise.
663    cols: i64,
664    /// Pipe carrying bytes consumed by the child.
665    in_pipe: PipeHandle,
666    /// Pipe carrying bytes produced by the child.
667    out_pipe: PipeHandle,
668) -> Result<Value> {
669    if !cx.is_async_task() {
670        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
671    }
672    // `pump_pty_session` takes `&Value` pipes: re-wrap the extracted
673    // handles so the bridge keeps its Value-based shape.
674    let in_pipe = Value::pipe_handle(in_pipe);
675    let out_pipe = Value::pipe_handle(out_pipe);
676    let initial = if rows > 0 && cols > 0 {
677        crate::state::PtySize::new(rows as u32, cols as u32)
678    } else {
679        session.pty_size()
680    };
681    let cancel = AtomicBool::new(false);
682    let code = crate::pty::pump_pty_session(
683        cx,
684        &argv,
685        initial,
686        &session.pty_size_handle(),
687        &in_pipe,
688        &out_pipe,
689        &cancel,
690    )?;
691    Ok(Value::int(code))
692}
693
694/// Field table for the `SSH_SERVE` result bundle, backing the
695/// `SSH_SERVE_INFO` schema and the `SSH_SERVE` return tag: one source
696/// for the shape the host mints, so introspection, enforcement, and
697/// documentation cannot drift apart.
698fn serve_result_fields() -> Arc<[Field]> {
699    Arc::from(vec![
700        Field {
701            name: "server".to_string(),
702            ty: TypeTag::Custom(SshServerTag::descriptor()),
703            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
704            optional: false,
705        },
706        Field {
707            name: "addr".to_string(),
708            ty: TypeTag::String,
709            docs: "Bound socket address (`ip:port`) of the server.",
710            optional: false,
711        },
712        Field {
713            name: "username".to_string(),
714            ty: TypeTag::String,
715            docs: "Configured username.",
716            optional: false,
717        },
718        Field {
719            name: "password".to_string(),
720            ty: TypeTag::String,
721            docs: "Configured password.",
722            optional: false,
723        },
724        Field {
725            name: "virtual".to_string(),
726            ty: TypeTag::String,
727            docs: "Virtual endpoint echo of the claimed slot.",
728            optional: false,
729        },
730    ])
731}
732
733/// Field table for the `SSH_DEQUEUE` result bundle, backing the
734/// `SSH_DEQUEUE_INFO` schema and the `SSH_DEQUEUE` return tag.
735fn dequeue_result_fields() -> Arc<[Field]> {
736    Arc::from(vec![
737        Field {
738            name: "session".to_string(),
739            ty: TypeTag::Custom(SshSessionTag::descriptor()),
740            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
741            optional: false,
742        },
743        Field {
744            name: "command".to_string(),
745            ty: TypeTag::String,
746            docs: "Executed command, empty for shells.",
747            optional: false,
748        },
749        Field {
750            name: "username".to_string(),
751            ty: TypeTag::String,
752            docs: "Authenticated username, empty when unset.",
753            optional: false,
754        },
755        Field {
756            name: "addr".to_string(),
757            ty: TypeTag::String,
758            docs: "Peer address, empty when unset.",
759            optional: false,
760        },
761    ])
762}
763
764/// The `SSH` host module: virtual-endpoint server plus client, bridged
765/// to DSL pipes. Generic over the process manager like every host module.
766pub fn module_with<P: ProcessManager>() -> HostModule<P> {
767    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
768}
769
770/// The `SSH` host module resolving through `registry`: the registry
771/// travels as module state (`HostModule::with_state`) for bodies to
772/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
773/// else reaches the same registry through its `SSH_SERVER` handle. A
774/// pre-run service check rides along: every service the steps name must
775/// be fully bound before execution starts.
776pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
777    let check = registry.pre_run_check("SSH");
778    HostModule {
779        name: "SSH".to_string(),
780        funcs: vec![
781            SshServe::registration(),
782            SshAccept::registration(),
783            SshDequeue::registration(),
784            SshPumpChannel::registration(),
785            SshClose::registration(),
786            SshConnect::registration(),
787            SshPump::registration(),
788            SshPtyRun::registration(),
789        ],
790        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
791        record_schemas: vec![
792            RecordSchema {
793                name: "SSH_SERVE_INFO",
794                fields: serve_result_fields(),
795            },
796            RecordSchema {
797                name: "SSH_DEQUEUE_INFO",
798                fields: dequeue_result_fields(),
799            },
800        ],
801        states: Vec::new(),
802    }
803    .with_state(registry)
804    .with_state(Arc::new(check))
805}