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;
11
12use anyhow::{Context, Result, bail};
13use oxdock_core::{Field, HostModule, OxDockFn, OxDockType, RecordSchema, StepCtx, TypeTag, Value};
14use oxdock_func_macro::oxdock_func;
15use oxdock_net_plugin::{
16    AcquiredListener, EndpointKey, EndpointRegistry, ServiceTarget, SocketRequirement,
17    acquire_listener, no_cli_mapping, parse_virtual_endpoint, resolve_service_target,
18};
19use oxdock_pipe::PipeHandle;
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/// Block until the queue yields an authenticated session (or teardown).
36/// Shared by `SSH_DEQUEUE` and the `SSH_ACCEPT` wrapper. No timeout:
37/// a waiter parks in the queue condvar while a bridge thread parks on
38/// the task hub; on hub fire the bridge pokes the queue awake and the
39/// waiter ends with `Cancelled`. One transient thread per call, spent
40/// only on wakeups, never on ticks.
41fn dequeue_session<P: ProcessManager>(
42    cx: &StepCtx<P>,
43    queue: &Arc<SessionQueue>,
44    func: &str,
45) -> Result<PendingSession> {
46    let hub = cx.cancel_hub();
47    let bridge_queue = Arc::clone(queue);
48    let bridge_hub = Arc::clone(&hub);
49    let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
50    std::thread::scope(|scope| {
51        let bridge = scope.spawn(move || {
52            // Rendezvous: read the sequence, then signal, then park,
53            // so the release below can never land before the wait.
54            let seen = bridge_hub.sequence();
55            let _ = started_tx.send(());
56            let (cancelled, _) = bridge_hub.wait(seen);
57            if cancelled {
58                bridge_queue.poke();
59            }
60        });
61        let result = loop {
62            if hub.is_cancelled() || cx.is_cancelled() {
63                break Err(anyhow::anyhow!("{func}: task cancelled"));
64            }
65            match queue.try_pop() {
66                Dequeue::Session(session) => break Ok(session),
67                Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
68                Dequeue::Empty | Dequeue::Cancelled => {}
69            }
70            match queue.wait_blocking(&hub) {
71                Dequeue::Session(session) => break Ok(session),
72                Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
73                Dequeue::Cancelled | Dequeue::Empty => {}
74            }
75        };
76        // Release the bridge (rendezvous first so the poke cannot
77        // land before its wait, then poke, never cancel: the dequeue
78        // may have ended cleanly) and join it: no thread outlives the
79        // call.
80        let _ = started_rx.recv();
81        hub.poke();
82        let _ = bridge.join();
83        result
84    })
85}
86
87/// Dequeue one authenticated session for routing before any byte
88/// pumping starts. Must run inside `ASYNC`.
89///
90/// The server sends first: the client side never EOFs its input, so a
91/// synthetic reply cannot race teardown.
92///
93#[oxdock_func(
94    returns = TypeTag::Record(dequeue_result_fields()),
95    summary = "Dequeue one SSH session with its metadata."
96)]
97#[example(
98    name = "route one session",
99    code = r###"
100    IMPORT [STD, SSH]
101    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})
102
103    # Serve: dequeue one session and pump a synthetic reply.
104    LET $in: PIPE
105    LET $out: PIPE
106    LET $w: HANDLE = ASYNC {
107        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
108        ASSERT_EQ $sess.username "u"
109        SSH_PUMP_CHANNEL($sess.session, $in, $out)
110    }
111
112    # Connect a client to the server.
113    LET $cin: PIPE
114    LET $cout: PIPE
115    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }
116
117    # Close both inputs: each pump observes EOF, half-closes, and every
118    # task returns with no cancellation.
119    WITH_IO [stdout=$cin] ECHO "client-hello"
120    WITH_IO [stdout=$in] ECHO "server-greeting"
121    LET $cDone: MAP<ANY> = AWAIT $c
122    ASSERT_EQ $cDone.closed true
123    AWAIT $w
124    SSH_CLOSE($m.server)
125    "###
126)]
127fn ssh_dequeue<P: ProcessManager>(
128    cx: &mut StepCtx<P>,
129    /// Server handle from `SSH_SERVE`.
130    server: SshServerTag,
131) -> Result<Value> {
132    if !cx.is_async_task() {
133        bail!(
134            "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
135        );
136    }
137    let state = Arc::clone(server.state());
138    let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
139    let command = session.exec_command.clone().unwrap_or_default();
140    let username = session.username.clone().unwrap_or_default();
141    let addr = session
142        .peer_addr
143        .map(|addr| addr.to_string())
144        .unwrap_or_default();
145    let tag = SshSessionTag::new(
146        session.exec_command,
147        session.username,
148        session.peer_addr,
149        session.pty_size,
150        session.up_rx,
151        session.down_tx,
152    );
153    let mut map = BTreeMap::new();
154    map.insert(
155        "session".to_string(),
156        Value::mint_heap(SshSessionTag::descriptor(), tag),
157    );
158    map.insert("command".to_string(), Value::string(command));
159    map.insert("username".to_string(), Value::string(username));
160    map.insert("addr".to_string(), Value::string(addr));
161    Ok(Value::map(map))
162}
163
164/// Spin up an SSH server on a runner-mapped service. Unmapped and
165/// memory services bail: SSH needs a TCP socket.
166/// `options` takes required `username`/`password` STRINGs plus the
167/// optional `key_path` STRING (workspace-relative Ed25519 file,
168/// load-or-create; blank keeps the ephemeral key) and the optional
169/// `idle_timeout` DURATION (quiet-connection kill, default 5m; zero
170/// disables it for persistent sessions).
171#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
172#[example(
173    name = "serve and close",
174    code = r###"
175    IMPORT [STD, SSH]
176    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
177    ASSERT_EQ $m.virtual "doc-ssh-serve"
178    SSH_CLOSE($m.server)
179    "###
180)]
181fn ssh_serve<P: ProcessManager>(
182    cx: &mut StepCtx<P>,
183    /// Service name to serve; the runner maps it with -p/--listen.
184    bind: String,
185    /// Server credentials and host key.
186    #[options(
187        "username: STRING",
188        "password: STRING",
189        "key_path?: STRING",
190        "idle_timeout?: DURATION|STRING"
191    )]
192    options: BTreeMap<String, Value>,
193) -> Result<Value> {
194    let map = &options;
195    let username = match map.get("username") {
196        Some(value) => {
197            let text = value.as_str().expect("check_options verified STRING");
198            if text.trim().is_empty() {
199                bail!("SSH_SERVE option 'username' must not be empty");
200            }
201            text.to_string()
202        }
203        None => bail!("SSH_SERVE option 'username' is required"),
204    };
205    let password = match map.get("password") {
206        Some(value) => {
207            let text = value.as_str().expect("check_options verified STRING");
208            if text.trim().is_empty() {
209                bail!("SSH_SERVE option 'password' must not be empty");
210            }
211            text.to_string()
212        }
213        None => bail!("SSH_SERVE option 'password' is required"),
214    };
215    let key_path = match map.get("key_path") {
216        Some(value) => {
217            let text = value.as_str().expect("check_options verified STRING");
218            if text.trim().is_empty() {
219                None
220            } else {
221                Some(text.to_string())
222            }
223        }
224        None => None,
225    };
226    // Idle kill override: absent keeps the default, zero disables the
227    // timeout entirely (persistent sessions must opt out explicitly).
228    let idle_timeout = match map.get("idle_timeout") {
229        Some(value) => {
230            // `check_options` verified `DURATION|STRING`; narrow directly.
231            let timeout = if let Some(duration) = value.as_duration() {
232                duration
233            } else {
234                let text = value
235                    .as_str()
236                    .expect("check_options verified DURATION|STRING");
237                oxdock_parser::command::parse_duration(text).with_context(|| {
238                    format!("SSH_SERVE option 'idle_timeout' must be a duration, got {text:?}")
239                })?
240            };
241            (!timeout.is_zero()).then_some(timeout)
242        }
243        None => Some(crate::runtime::DEFAULT_INACTIVITY_TIMEOUT),
244    };
245    let registry = cx
246        .module_state::<EndpointRegistry>("SSH")
247        .expect("SSH module registers its endpoint registry as module state");
248    let endpoint = parse_serve_endpoint(&bind)?;
249    let key = EndpointKey::tcp(endpoint);
250    let (acquired, registry) = acquire_listener(
251        &registry,
252        &key,
253        "SSH_SERVE",
254        SocketRequirement::SocketRequired,
255    )?;
256    let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
257        Some(key) => key,
258        None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
259            .context("generate ephemeral Ed25519 host key")?,
260    };
261    let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
262    let id = format!("ssh-{pid}-{id}", pid = std::process::id());
263    let queue = Arc::new(SessionQueue::new());
264    let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
265    let (local_addr, addr_text, thread) = match acquired {
266        AcquiredListener::Tcp { listener, addr } => {
267            // The runtime owns a clone; the slot keeps the backlog socket.
268            let owned = listener
269                .try_clone()
270                .context("SSH_SERVE cannot clone its listener")?;
271            let thread_queue = Arc::clone(&queue);
272            let thread_user = username.clone();
273            let thread_pass = password.clone();
274            let thread = std::thread::Builder::new()
275                .name(id.clone())
276                .spawn(move || {
277                    crate::runtime::serve(
278                        owned,
279                        host_key,
280                        thread_user,
281                        thread_pass,
282                        thread_queue,
283                        shutdown_rx,
284                        idle_timeout,
285                    )
286                })
287                .context("SSH_SERVE cannot spawn the server thread")?;
288            (addr, addr.to_string(), Some(thread))
289        }
290        AcquiredListener::Memory => {
291            // Unreachable: `SocketRequired` already bailed; same text.
292            drop(shutdown_rx);
293            return Err(no_cli_mapping("SSH_SERVE", &key.endpoint));
294        }
295        AcquiredListener::Offline => {
296            // No thread: dropping the receiver makes shutdown a no-op.
297            drop(shutdown_rx);
298            (
299                std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
300                key.endpoint.to_string(),
301                None,
302            )
303        }
304    };
305    let state = Arc::new(ServerState::new(crate::state::ServerConfig {
306        id,
307        local_addr,
308        addr_text: addr_text.clone(),
309        queue,
310        shutdown_tx,
311        thread,
312        registry: Arc::clone(&registry),
313        endpoint: key.clone(),
314    }));
315    let mut map = BTreeMap::new();
316    map.insert(
317        "server".to_string(),
318        Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
319    );
320    map.insert("addr".to_string(), Value::string(addr_text));
321    map.insert("username".to_string(), Value::string(username));
322    map.insert("password".to_string(), Value::string(password));
323    map.insert(
324        "virtual".to_string(),
325        Value::string(key.endpoint.to_string()),
326    );
327    Ok(Value::map(map))
328}
329
330/// `SSH_DEQUEUE` + `SSH_PUMP_CHANNEL` in one call, for worker loops
331/// that need no pre-pump inspection. Must run inside `ASYNC`.
332///
333/// The server sends first: the client side never EOFs its input, so
334/// the reply cannot race teardown.
335///
336#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
337    name: "closed".to_string(),
338    ty: TypeTag::Bool,
339    docs: "True when the session closed cleanly.",
340    optional: false,
341}, Field {
342    name: "command".to_string(),
343    ty: TypeTag::String,
344    docs: "Executed command, empty for shells.",
345    optional: false,
346}])), summary = "Accept one SSH session into pipes.")]
347#[example(
348    name = "accept and close",
349    code = r###"
350    IMPORT [STD, SSH]
351    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
352    LET $in: PIPE
353    LET $out: PIPE
354    LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
355    LET $cin: PIPE
356    LET $cout: PIPE
357    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
358
359    # Close both inputs: each pump observes EOF, half-closes, and both
360    # tasks return their result maps with no cancellation.
361    WITH_IO [stdout=$cin] ECHO "client-hello"
362    WITH_IO [stdout=$in] ECHO "server-greeting"
363    LET $done: MAP<ANY> = AWAIT $acc
364    ASSERT_EQ $done.closed true
365    ASSERT_CONTAINS $done "command"
366    LET $cDone: MAP<ANY> = AWAIT $c
367    ASSERT_EQ $cDone.closed true
368    SSH_CLOSE($m.server)
369    "###
370)]
371fn ssh_accept<P: ProcessManager>(
372    cx: &mut StepCtx<P>,
373    /// Server handle from `SSH_SERVE`.
374    server: SshServerTag,
375    /// Pipe carrying bytes consumed by the wire side.
376    in_pipe: PipeHandle,
377    /// Pipe carrying bytes produced by the wire side.
378    out_pipe: PipeHandle,
379) -> Result<Value> {
380    if !cx.is_async_task() {
381        bail!(
382            "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
383        );
384    }
385    let in_pipe = Value::pipe_handle(in_pipe);
386    let out_pipe = Value::pipe_handle(out_pipe);
387    let state = Arc::clone(server.state());
388    let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
389    pump_session(
390        cx,
391        &in_pipe,
392        &out_pipe,
393        session.up_rx,
394        session.down_tx,
395        true,
396    )?;
397    let mut map = BTreeMap::new();
398    map.insert("closed".to_string(), Value::bool(true));
399    map.insert(
400        "command".to_string(),
401        Value::string(session.exec_command.unwrap_or_default()),
402    );
403    Ok(Value::map(map))
404}
405
406/// Pump a dequeued session through explicit pipes until the channel
407/// closes. Must run inside `ASYNC`. Pump ends take once: a second
408/// pump bails instead of splitting bytes.
409///
410#[oxdock_func(
411    returns = TypeTag::Record(std::sync::Arc::from([Field {
412        name: "closed".to_string(),
413        ty: TypeTag::Bool,
414        docs: "True when the session closed cleanly.",
415        optional: false,
416    }])),
417    summary = "Pump a dequeued SSH session through pipes."
418)]
419#[example(
420    name = "pump a session",
421    code = r###"
422    IMPORT [STD, SSH]
423    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
424    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
425    LET $cin: PIPE
426    LET $cout: PIPE
427    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
428    WITH_IO [stdout=$cin] ECHO "client-hello"
429    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
430    LET $sin: PIPE
431    LET $sout: PIPE
432    LET $p: HANDLE = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
433    WITH_IO [stdout=$sin] ECHO "server-greeting"
434    LET $cDone: MAP<ANY> = AWAIT $c
435    ASSERT_EQ $cDone.closed true
436    LET $pDone: MAP<ANY> = AWAIT $p
437    ASSERT_EQ $pDone.closed true
438    SSH_CLOSE($m.server)
439    "###
440)]
441fn ssh_pump_channel<P: ProcessManager>(
442    cx: &mut StepCtx<P>,
443    /// Session handle from `SSH_DEQUEUE` (pump ends take once).
444    session: SshSessionTag,
445    /// Pipe carrying bytes consumed by the wire side.
446    in_pipe: PipeHandle,
447    /// Pipe carrying bytes produced by the wire side.
448    out_pipe: PipeHandle,
449) -> Result<Value> {
450    if !cx.is_async_task() {
451        bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
452    }
453    let in_pipe = Value::pipe_handle(in_pipe);
454    let out_pipe = Value::pipe_handle(out_pipe);
455    let (up_rx, down_tx) = session.take_pump_ends()?;
456    // Release the control sender when the pump ends (pass or fail):
457    // the wire writer must observe the drain and close then, not when
458    // the last session clone drops long after.
459    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
460    session.finish_pump();
461    pump?;
462    let mut map = BTreeMap::new();
463    map.insert("closed".to_string(), Value::bool(true));
464    Ok(Value::map(map))
465}
466
467/// Report the session's exit status to the client (RFC 4254 6.10),
468/// ahead of the channel close. Survives the take-once pump ends, so
469/// call it before the pump drains. `SSH_PTY_RUN` reports by itself;
470/// this covers other legs (`RUN`, synthetic replies).
471#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
472#[example(
473    name = "report exit status",
474    code = r###"
475    IMPORT [STD, SSH]
476    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
477    LET $srv: HANDLE = ASYNC {
478        LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
479        LET $sin: PIPE
480        LET $sout: PIPE
481        LET $p: HANDLE = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
482        SSH_SEND_EXIT_STATUS($sess.session, 3)
483        WITH_IO [stdout=$sin] ECHO "server-greeting"
484        AWAIT $p
485    }
486    LET $cin: PIPE
487    LET $cout: PIPE
488    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
489    # Close the client input: its pump observes EOF and half-closes, so
490    # both pumps drain instead of idling on an empty pipe.
491    WITH_IO [stdout=$cin] ECHO "client-hello"
492    LET $cDone: MAP<ANY> = AWAIT $c
493    ASSERT_EQ $cDone.closed true
494    ASSERT_EQ $cDone.exit_status 3
495    AWAIT $srv
496    SSH_CLOSE($m.server)
497    "###
498)]
499fn ssh_send_exit_status<P: ProcessManager>(
500    cx: &mut StepCtx<P>,
501    /// Session handle from `SSH_DEQUEUE`.
502    session: SshSessionTag,
503    /// Exit status to report (0 to 4294967295).
504    code: i64,
505) -> Result<Value> {
506    let _ = cx;
507    if code < 0 {
508        bail!("SSH_SEND_EXIT_STATUS code must not be negative: {code}");
509    }
510    let code = u32::try_from(code)
511        .map_err(|_| anyhow::anyhow!("SSH_SEND_EXIT_STATUS code out of range: {code}"))?;
512    session.send_exit_status(code)?;
513    Ok(Value::bool(true))
514}
515
516/// Shut a server down and join its runtime thread (bounded).
517/// Idempotent.
518///
519#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
520#[example(
521    name = "shut down",
522    code = r###"
523    IMPORT [STD, SSH]
524    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
525    LET $ok: BOOL = SSH_CLOSE($m.server)
526    ASSERT_EQ $ok true
527    "###
528)]
529fn ssh_close<P: ProcessManager>(
530    cx: &mut StepCtx<P>,
531    /// Server handle from `SSH_SERVE`.
532    server: SshServerTag,
533) -> Result<Value> {
534    let _ = cx;
535    let state = Arc::clone(server.state());
536    state.request_shutdown();
537    Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
538}
539
540/// Open an SSH client session and pump its shell channel through
541/// explicit pipes until it closes. Must run inside `ASYNC`, beside
542/// the pump tasks. Under `--offline` the dial bails before any
543/// socket work. The result MAP carries `exit_status`, or -1 when the
544/// server sent none.
545#[oxdock_func(returns = TypeTag::Map, summary = "Open an SSH client session into pipes.")]
546#[example(
547    name = "connect and close",
548    code = r###"
549    IMPORT [STD, SSH]
550    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
551    LET $in: PIPE
552    LET $out: PIPE
553    LET $acc: HANDLE = ASYNC { SSH_ACCEPT($m.server, $in, $out) }
554    LET $cin: PIPE
555    LET $cout: PIPE
556    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
557
558    # Close both inputs: each pump observes EOF, half-closes, and both
559    # tasks return their result maps with no cancellation.
560    WITH_IO [stdout=$cin] ECHO "client-hello"
561    WITH_IO [stdout=$in] ECHO "server-greeting"
562    LET $done: MAP<ANY> = AWAIT $c
563    ASSERT_EQ $done.closed true
564    LET $adone: MAP<ANY> = AWAIT $acc
565    ASSERT_EQ $adone.closed true
566    SSH_CLOSE($m.server)
567    "###
568)]
569fn ssh_connect<P: ProcessManager>(
570    cx: &mut StepCtx<P>,
571    /// Dial target: a service name resolved through runner mappings.
572    target: String,
573    /// Inner credentials for the SSH session.
574    username: String,
575    /// Inner credentials for the SSH session.
576    password: String,
577    /// Pipe carrying bytes consumed by the wire side.
578    in_pipe: PipeHandle,
579    /// Pipe carrying bytes produced by the wire side.
580    out_pipe: PipeHandle,
581) -> Result<Value> {
582    if !cx.is_async_task() {
583        bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
584    }
585    // Registry travels as module state.
586    let registry = cx
587        .module_state::<EndpointRegistry>("SSH")
588        .expect("SSH module registers its endpoint registry as module state");
589    let in_pipe = Value::pipe_handle(in_pipe);
590    let out_pipe = Value::pipe_handle(out_pipe);
591    if registry.is_offline() {
592        bail!("SSH_CONNECT failed: engine running in --offline mode");
593    }
594    if username.is_empty() {
595        bail!("SSH_CONNECT username must not be empty");
596    }
597    // Symbolic only: physical shapes already failed in the parser.
598    let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
599    let key = EndpointKey::tcp(endpoint);
600    let addr = match resolve_service_target(
601        &registry,
602        &key,
603        "SSH_CONNECT",
604        SocketRequirement::SocketRequired,
605    )? {
606        ServiceTarget::Tcp(addr) => addr,
607        // Unreachable: the shared resolver already bailed; same text.
608        ServiceTarget::Memory => {
609            return Err(no_cli_mapping("SSH_CONNECT", &key.endpoint));
610        }
611    };
612    let runtime = connect_runtime()?;
613    let session = runtime
614        .block_on(connect_session(&addr, &username, &password))
615        .context("SSH_CONNECT failed")?;
616    let crate::runtime::OutboundSession {
617        up_rx,
618        down_tx,
619        exit_status,
620        wire_done,
621        handle,
622        ..
623    } = session;
624    // Client linger: the reply and the exit-status arrive after the
625    // client's own stdin EOF, so never cut the output wait short.
626    let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
627    let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
628    pump?;
629    // Joined after disconnect: a post-EOF status records before this read.
630    let _ = runtime.block_on(wire_done);
631    let mut map = BTreeMap::new();
632    map.insert("closed".to_string(), Value::bool(true));
633    let status = exit_status
634        .lock()
635        .map(|slot| slot.map(i64::from))
636        .unwrap_or(None);
637    map.insert("exit_status".to_string(), Value::int(status.unwrap_or(-1)));
638    Ok(Value::map(map))
639}
640
641/// Copy one pipe into another until EOF, then close the target.
642/// Either task placement works, as long as the other end is live.
643///
644#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
645#[example(
646    name = "copy",
647    code = r###"
648    # Closing the source ends the copy: the count proves the bytes moved.
649    IMPORT [STD, SSH]
650    LET $in: PIPE
651    WITH_IO [stdout=$in] ECHO "pump-me"
652    LET $out: PIPE
653    LET $n: INT = SSH_PUMP($in, $out)
654    ASSERT_EQ $n 8
655    WITH_IO [stdin=$out] READ_LINE $got
656    ASSERT_EQ $got "pump-me"
657    "###
658)]
659fn ssh_pump<P: ProcessManager>(
660    cx: &mut StepCtx<P>,
661    /// Source pipe to drain.
662    from_pipe: PipeHandle,
663    /// Target pipe receiving the bytes (closed at EOF).
664    to_pipe: PipeHandle,
665) -> Result<Value> {
666    let from_pipe = Value::pipe_handle(from_pipe);
667    let to_pipe = Value::pipe_handle(to_pipe);
668    let cancel = AtomicBool::new(false);
669    let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
670    Ok(Value::int(total))
671}
672
673/// Run `argv` under a local pseudo-terminal and pump it through
674/// explicit pipes until the child exits. Must run inside `ASYNC`.
675/// Returns the INT exit code.
676///
677/// `rows`/`cols` seed the initial size when positive, else the
678/// session's requested size (24x80 default). Outer window-changes
679/// resize live; each session owns its cell.
680///
681/// The code also reports as the wire `exit-status` at child exit, so
682/// stock clients see the real code instead of 255.
683///
684/// Every session opens cleared and homed, like Win32-OpenSSH, so the
685/// child renders onto a known blank screen.
686///
687/// Windows joining follows MSVCRT rules, so CRT programs parse back
688/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
689/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
690/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
691///
692/// Stdin arrives untranslated. Consoles submit on CR, so a DSL line
693/// bound for a console child ends with `\r`. Real terminals already
694/// send CR for Enter.
695///
696/// Environment is exactly the script environment like `RUN`:
697/// block-scoped `ENV` (such as the session's `SSH_USER` / `SSH_CLIENT` /
698/// `SSH_SERVER` / `SSH_COMMAND` relay) reaches the child; host names
699/// arrive only through `INHERIT_ENV`, including `TERM` for terminal
700/// definitions. The working directory comes from the script.
701///
702#[oxdock_func(
703    returns = TypeTag::Int,
704    summary = "Run a command under a sized local terminal into pipes."
705)]
706#[example(
707    name = "run under a terminal",
708    code = r###"
709    IMPORT [STD, SSH]
710    INHERIT_ENV [PATH]
711    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
712    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
713    LET $cin: PIPE
714    LET $cout: PIPE
715    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
716    WITH_IO [stdout=$cin] ECHO "client-hello"
717    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
718
719    # The client task only proved the session live: cancel it before the
720    # terminal run, so no two pumps share the session.
721    CANCEL $c
722    LET $pin: PIPE
723    LET $pout: PIPE
724    # Assert on the whole pipe: terminal streams carry setup noise ahead
725    # of child output, so line reads are version-dependent.
726    [family:unix] {
727        LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
728        LET $code: INT = AWAIT $t
729        ASSERT_EQ $code 0
730        ASSERT_CONTAINS $pout "pty-hi"
731    }
732    [family:windows] {
733        LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
734        LET $code: INT = AWAIT $t
735        ASSERT_EQ $code 0
736        ASSERT_CONTAINS $pout "pty-hi"
737    }
738    SSH_CLOSE($m.server)
739    "###
740)]
741fn ssh_pty_run<P: ProcessManager>(
742    cx: &mut StepCtx<P>,
743    /// Session handle from `SSH_DEQUEUE`.
744    session: SshSessionTag,
745    /// Program and arguments to run.
746    argv: Vec<String>,
747    /// Terminal rows when positive, session size otherwise.
748    rows: i64,
749    /// Terminal columns when positive, session size otherwise.
750    cols: i64,
751    /// Pipe carrying bytes consumed by the child.
752    in_pipe: PipeHandle,
753    /// Pipe carrying bytes produced by the child.
754    out_pipe: PipeHandle,
755) -> Result<Value> {
756    if !cx.is_async_task() {
757        bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
758    }
759    let in_pipe = Value::pipe_handle(in_pipe);
760    let out_pipe = Value::pipe_handle(out_pipe);
761    let initial = if rows > 0 && cols > 0 {
762        crate::state::PtySize::new(rows as u32, cols as u32)
763    } else {
764        session.pty_size()
765    };
766    // Best effort: an unpumped session has no reader. Owned clone:
767    // the reaper runs detached, so the callback must be `'static`.
768    let session_report = session.clone();
769    let report = move |code: u32| {
770        let _ = session_report.send_exit_status(code);
771    };
772    let code = crate::pty::pump_pty_session(
773        cx,
774        &argv,
775        initial,
776        &session.pty_size_handle(),
777        &in_pipe,
778        &out_pipe,
779        Some(std::sync::Arc::new(report)),
780    )?;
781    Ok(Value::int(code))
782}
783
784/// Run `argv` directly (no terminal) and pump it through explicit pipes
785/// until the child exits. Must run inside `ASYNC`. Returns the INT exit
786/// code (-1 when the child died by signal).
787///
788/// Bytes travel untouched: no init sequence, no newline translation, no
789/// setup handshake. This is the binary-safe leg `scp`-style protocols
790/// need; `SSH_PTY_RUN` owns the interactive side instead.
791///
792/// The code reports as the wire `exit-status` at child exit, so stock
793/// clients see the real code instead of 255. Signaled children report
794/// nothing: clients observe the close without a status.
795///
796/// Stdin EOF closes the child's stdin, so stdin-driven children like
797/// `cat` exit on their own. Standard output and error ride separate
798/// pipes: diagnostics must never pollute the byte stream.
799///
800/// Environment is exactly the script environment like `RUN`:
801/// block-scoped `ENV` reaches the child; host names arrive only through
802/// `INHERIT_ENV`. The working directory comes from the script.
803///
804/// Windows joining follows MSVCRT rules, so CRT programs parse back
805/// exactly `argv`. `cmd /c` is the exception (its tail is a command,
806/// not `argv`): route command text via `ENV SSH_COMMAND="..."` with
807/// `["cmd", "/c", "%SSH_COMMAND%"]` instead.
808#[oxdock_func(
809    returns = TypeTag::Int,
810    summary = "Run a command with piped stdio into explicit pipes."
811)]
812#[example(
813    name = "run with piped stdio",
814    code = r###"
815    IMPORT [STD, SSH]
816    INHERIT_ENV [PATH]
817    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
818    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
819    LET $cin: PIPE
820    LET $cout: PIPE
821    LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
822    WITH_IO [stdout=$cin] ECHO "client-hello"
823    LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
824
825    # The client task only proved the session live: cancel it before the
826    # run, so no two pumps share the session.
827    CANCEL $c
828    LET $pin: PIPE
829    LET $pout: PIPE
830    LET $perr: PIPE
831    LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
832    [family:windows] {
833        $argv = ["cmd", "/c", "echo run-hi"]
834    }
835    LET $t: HANDLE = ASYNC { SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
836    LET $code: INT = AWAIT $t
837    ASSERT_EQ $code 0
838    ASSERT_CONTAINS $pout "run-hi"
839    SSH_CLOSE($m.server)
840    "###
841)]
842fn ssh_run<P: ProcessManager>(
843    cx: &mut StepCtx<P>,
844    /// Session handle from `SSH_DEQUEUE`.
845    session: SshSessionTag,
846    /// Program and arguments to run.
847    argv: Vec<String>,
848    /// Pipe carrying bytes consumed by the child on stdin.
849    in_pipe: PipeHandle,
850    /// Pipe carrying bytes produced by the child on stdout.
851    out_pipe: PipeHandle,
852    /// Pipe carrying bytes produced by the child on stderr.
853    err_pipe: PipeHandle,
854) -> Result<Value> {
855    if !cx.is_async_task() {
856        bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
857    }
858    let in_pipe = Value::pipe_handle(in_pipe);
859    let out_pipe = Value::pipe_handle(out_pipe);
860    let err_pipe = Value::pipe_handle(err_pipe);
861    // Best effort: an unpumped session has no reader. Owned clone:
862    // the reaper runs detached, so the callback must be `'static`.
863    let session_report = session.clone();
864    let report = move |code: u32| {
865        let _ = session_report.send_exit_status(code);
866    };
867    let code = crate::run::pump_run_session(
868        cx,
869        &argv,
870        &in_pipe,
871        &out_pipe,
872        &err_pipe,
873        Some(std::sync::Arc::new(report)),
874    )?;
875    Ok(Value::int(code))
876}
877
878/// Run one argv vector on a remote host over SSH and collect the
879/// result. Stateless by design: every call carries its target,
880/// credentials, and argv, holds no session, and returns one MAP with
881/// `exit`, `stdout`, `stderr`, `truncated`, and `timed_out`. A retry
882/// after a dropped channel repeats the same bytes, so idempotent
883/// commands make retries boring.
884///
885/// The argv never becomes a shell string in script hands: it joins
886/// once here through `shell_words::join`, the same vetted
887/// implementation behind `SHELL_SPLIT_ARGS`/`SHELL_JOIN_ARGS` and the
888/// remote plugins. Quoting `$HOME`, backticks, and redirects arrive as
889/// literal arguments because no layer between the caller and this join
890/// re-parses them.
891///
892/// Output caps apply while reading: past `max_bytes` per stream the
893/// buffers stop growing but the drain continues, so a flood still
894/// learns its exit status and reports `truncated`. A timeout kills
895/// the wait and returns whatever arrived with `timed_out`. `exit` is
896/// -1 when the server never sent a status.
897#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
898#[example(
899    name = "exec collects remote output",
900    code = r###"
901    # The server side answers exec with a local run: dequeue the
902    # session, split the joined command back into argv, run it, and
903    # pump the child output into the channel. The exit status rides
904    # the wire through the session report.
905    IMPORT [STD, SSH]
906    INHERIT_ENV [PATH]
907    LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
908    LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
909    LET $runner: HANDLE = ASYNC {
910        LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
911        LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
912        LET $wire: PIPE
913        LET $drain: PIPE
914        LET $pump: HANDLE = ASYNC { SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
915        LET $pin: PIPE
916        LET $pout: PIPE
917        LET $perr: PIPE
918        LET $run: HANDLE = ASYNC { SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
919        LET $n: INT = SSH_PUMP($pout, $wire)
920        LET $code: INT = AWAIT $run
921        LET $pDone: MAP<ANY> = AWAIT $pump
922        ASSERT_EQ $code 0
923    }
924
925    # One call, one MAP: argv in, collected streams out.
926    [family:unix] {
927        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
928        ASSERT_EQ $res.timed_out false
929        ASSERT_EQ $res.exit 0
930        ASSERT_CONTAINS $res.stdout "exec-hi"
931    }
932    [family:windows] {
933        LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
934        ASSERT_EQ $res.timed_out false
935        ASSERT_EQ $res.exit 0
936        ASSERT_CONTAINS $res.stdout "exec-hi"
937    }
938    AWAIT $runner
939    SSH_CLOSE($m.server)
940    "###
941)]
942fn ssh_exec<P: ProcessManager>(
943    cx: &mut StepCtx<P>,
944    /// Dial target: a service name resolved through runner mappings.
945    target: String,
946    /// Inner credentials for the SSH session.
947    username: String,
948    /// Inner credentials for the SSH session.
949    password: String,
950    /// Program and arguments to run remotely; joined once, by the
951    /// plugin, with POSIX shell quoting.
952    argv: Vec<String>,
953    /// `timeout` DURATION|STRING (default 60s) and `max_bytes` INT
954    /// (default 8 MiB per stream).
955    #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
956    options: BTreeMap<String, Value>,
957) -> Result<Value> {
958    if argv.is_empty() {
959        bail!("SSH_EXEC needs at least a program");
960    }
961    if username.is_empty() {
962        bail!("SSH_EXEC username must not be empty");
963    }
964    let registry = cx
965        .module_state::<EndpointRegistry>("SSH")
966        .expect("SSH module registers its endpoint registry as module state");
967    if registry.is_offline() {
968        bail!("SSH_EXEC failed: engine running in --offline mode");
969    }
970    // Symbolic only: physical shapes already failed in the parser.
971    let endpoint = parse_virtual_endpoint(&target, "SSH_EXEC")?;
972    let key = EndpointKey::tcp(endpoint);
973    let addr = match resolve_service_target(
974        &registry,
975        &key,
976        "SSH_EXEC",
977        SocketRequirement::SocketRequired,
978    )? {
979        ServiceTarget::Tcp(addr) => addr,
980        // Unreachable: the shared resolver already bailed; same text.
981        ServiceTarget::Memory => {
982            return Err(no_cli_mapping("SSH_EXEC", &key.endpoint));
983        }
984    };
985    let timeout = match options.get("timeout") {
986        None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
987        Some(value) => {
988            // `check_options` verified `DURATION|STRING`; narrow directly.
989            let timeout = if let Some(duration) = value.as_duration() {
990                duration
991            } else {
992                let text = value
993                    .as_str()
994                    .expect("check_options verified DURATION|STRING");
995                oxdock_parser::command::parse_duration(text).with_context(|| {
996                    format!("SSH_EXEC option 'timeout' must be a duration, got {text:?}")
997                })?
998            };
999            if timeout.is_zero() {
1000                bail!("SSH_EXEC option 'timeout' must be positive");
1001            }
1002            timeout
1003        }
1004    };
1005    let max_bytes = match options.get("max_bytes") {
1006        None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1007        Some(value) => {
1008            let bytes = value.as_i64().expect("check_options verified INT");
1009            if bytes <= 0 {
1010                bail!("SSH_EXEC option 'max_bytes' must be positive");
1011            }
1012            bytes as usize
1013        }
1014    };
1015    // The single shell encoding in the pipeline: argv becomes one
1016    // string here, and only here.
1017    let command = shell_words::join(&argv).into_bytes();
1018    let runtime = connect_runtime()?;
1019    let outcome = runtime
1020        .block_on(crate::runtime::run_remote_exec(
1021            &addr, &username, &password, command, timeout, max_bytes,
1022        ))
1023        .context("SSH_EXEC failed")?;
1024    let mut map = BTreeMap::new();
1025    map.insert("exit".to_string(), Value::int(outcome.exit.unwrap_or(-1)));
1026    map.insert(
1027        "stdout".to_string(),
1028        Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1029    );
1030    map.insert(
1031        "stderr".to_string(),
1032        Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1033    );
1034    map.insert("truncated".to_string(), Value::bool(outcome.truncated));
1035    map.insert("timed_out".to_string(), Value::bool(outcome.timed_out));
1036    Ok(Value::map(map))
1037}
1038
1039/// Field table backing the `SSH_SERVE_INFO` schema and return tag.
1040fn serve_result_fields() -> Arc<[Field]> {
1041    Arc::from(vec![
1042        Field {
1043            name: "server".to_string(),
1044            ty: TypeTag::Custom(SshServerTag::descriptor()),
1045            docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1046            optional: false,
1047        },
1048        Field {
1049            name: "addr".to_string(),
1050            ty: TypeTag::String,
1051            docs: "Bound socket address (`ip:port`) of the server.",
1052            optional: false,
1053        },
1054        Field {
1055            name: "username".to_string(),
1056            ty: TypeTag::String,
1057            docs: "Configured username.",
1058            optional: false,
1059        },
1060        Field {
1061            name: "password".to_string(),
1062            ty: TypeTag::String,
1063            docs: "Configured password.",
1064            optional: false,
1065        },
1066        Field {
1067            name: "virtual".to_string(),
1068            ty: TypeTag::String,
1069            docs: "Virtual endpoint echo of the claimed slot.",
1070            optional: false,
1071        },
1072    ])
1073}
1074
1075/// Field table backing the `SSH_DEQUEUE_INFO` schema and return tag.
1076fn dequeue_result_fields() -> Arc<[Field]> {
1077    Arc::from(vec![
1078        Field {
1079            name: "session".to_string(),
1080            ty: TypeTag::Custom(SshSessionTag::descriptor()),
1081            docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1082            optional: false,
1083        },
1084        Field {
1085            name: "command".to_string(),
1086            ty: TypeTag::String,
1087            docs: "Executed command, empty for shells.",
1088            optional: false,
1089        },
1090        Field {
1091            name: "username".to_string(),
1092            ty: TypeTag::String,
1093            docs: "Authenticated username, empty when unset.",
1094            optional: false,
1095        },
1096        Field {
1097            name: "addr".to_string(),
1098            ty: TypeTag::String,
1099            docs: "Peer address, empty when unset.",
1100            optional: false,
1101        },
1102    ])
1103}
1104
1105/// The `SSH` host module: virtual-endpoint server plus client, bridged
1106/// to DSL pipes. Generic over the process manager like every host module.
1107pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1108    module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1109}
1110
1111/// The `SSH` host module resolving through `registry`: the registry
1112/// travels as module state (`HostModule::with_state`) for bodies to
1113/// fetch from `cx`, so every entry stays `#[oxdock_func]`. Everything
1114/// else reaches the same registry through its `SSH_SERVER` handle. A
1115/// pre-run service check rides along: every service the steps name must
1116/// be fully bound before execution starts.
1117pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1118    let check = registry.pre_run_check("SSH");
1119    HostModule {
1120        name: "SSH".to_string(),
1121        funcs: vec![
1122            SshServe::registration(),
1123            SshAccept::registration(),
1124            SshDequeue::registration(),
1125            SshPumpChannel::registration(),
1126            SshSendExitStatus::registration(),
1127            SshClose::registration(),
1128            SshConnect::registration(),
1129            SshExec::registration(),
1130            SshPump::registration(),
1131            SshPtyRun::registration(),
1132            SshRun::registration(),
1133        ],
1134        types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1135        record_schemas: vec![
1136            RecordSchema {
1137                name: "SSH_SERVE_INFO",
1138                fields: serve_result_fields(),
1139            },
1140            RecordSchema {
1141                name: "SSH_DEQUEUE_INFO",
1142                fields: dequeue_result_fields(),
1143            },
1144        ],
1145        states: Vec::new(),
1146    }
1147    .with_state(registry)
1148    .with_state(Arc::new(check))
1149}