1use 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
32const FIELD_CLOSED: &str = "closed";
36const FIELD_COMMAND: &str = "command";
37const FIELD_EXIT_STATUS: &str = "exit_status";
38const FIELD_SERVER: &str = "server";
39const FIELD_ADDR: &str = "addr";
40const FIELD_USERNAME: &str = "username";
41const FIELD_PASSWORD: &str = "password";
42const FIELD_VIRTUAL: &str = "virtual";
43const FIELD_SESSION: &str = "session";
44const FIELD_EXIT: &str = "exit";
45const FIELD_TRUNCATED: &str = "truncated";
46const FIELD_TIMED_OUT: &str = "timed_out";
47
48const OPT_KEY_PATH: &str = "key_path";
52const OPT_IDLE_TIMEOUT: &str = "idle_timeout";
53const OPT_TIMEOUT: &str = "timeout";
54const OPT_MAX_BYTES: &str = "max_bytes";
55
56static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
58
59fn dequeue_session<P: ProcessManager>(
66 cx: &StepCtx<P>,
67 queue: &Arc<SessionQueue>,
68 func: &str,
69) -> Result<PendingSession> {
70 let hub = cx.cancel_hub();
71 let bridge_queue = Arc::clone(queue);
72 let bridge_hub = Arc::clone(&hub);
73 let (started_tx, started_rx) = std::sync::mpsc::channel::<()>();
74 std::thread::scope(|scope| {
75 let bridge = scope.spawn(move || {
76 let seen = bridge_hub.sequence();
79 let _ = started_tx.send(());
80 let (cancelled, _) = bridge_hub.wait(seen);
81 if cancelled {
82 bridge_queue.poke();
83 }
84 });
85 let result = loop {
86 if hub.is_cancelled() || cx.is_cancelled() {
87 break Err(anyhow::anyhow!("{func}: task cancelled"));
88 }
89 match queue.try_pop() {
90 Dequeue::Session(session) => break Ok(session),
91 Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
92 Dequeue::Empty | Dequeue::Cancelled => {}
93 }
94 match queue.wait_blocking(&hub) {
95 Dequeue::Session(session) => break Ok(session),
96 Dequeue::Shutdown => break Err(anyhow::anyhow!("{func}: server is closed")),
97 Dequeue::Cancelled | Dequeue::Empty => {}
98 }
99 };
100 let _ = started_rx.recv();
105 hub.poke();
106 let _ = bridge.join();
107 result
108 })
109}
110
111#[oxdock_func(
118 returns = TypeTag::Record(dequeue_result_fields()),
119 summary = "Dequeue one SSH session with its metadata."
120)]
121#[example(
122 name = "route one session",
123 code = r###"
124 IMPORT [STD, SSH]
125 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-route", {username: "u", password: "p"})
126
127 # Serve: dequeue one session and pump a synthetic reply.
128 LET $in: PIPE
129 LET $out: PIPE
130 LET $w: HANDLE<VOID> = ASYNC {
131 LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
132 ASSERT_EQ $sess.username "u"
133 SSH_PUMP_CHANNEL($sess.session, $in, $out)
134 }
135
136 # Connect a client to the server.
137 LET $cin: PIPE
138 LET $cout: PIPE
139 LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-route", "u", "p", $cin, $cout) }
140
141 # Close both inputs: each pump observes EOF, half-closes, and every
142 # task returns with no cancellation.
143 WITH_IO [stdout=$cin] ECHO "client-hello"
144 WITH_IO [stdout=$in] ECHO "server-greeting"
145 LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
146 ASSERT_EQ $cDone.closed true
147 AWAIT $w
148 SSH_CLOSE($m.server)
149 "###
150)]
151fn ssh_dequeue<P: ProcessManager>(
152 cx: &mut StepCtx<P>,
153 server: SshServerTag,
155) -> Result<Value> {
156 if !cx.is_async_task() {
157 bail!(
158 "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE<T> = ASYNC {{ SSH_DEQUEUE($server.server) }}"
159 );
160 }
161 let state = Arc::clone(server.state());
162 let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
163 let command = session.exec_command.clone().unwrap_or_default();
164 let username = session.username.clone().unwrap_or_default();
165 let addr = session
166 .peer_addr
167 .map(|addr| addr.to_string())
168 .unwrap_or_default();
169 let tag = SshSessionTag::new(
170 session.exec_command,
171 session.username,
172 session.peer_addr,
173 session.pty_size,
174 session.up_rx,
175 session.down_tx,
176 );
177 let mut map = BTreeMap::new();
178 map.insert(
179 "session".to_string(),
180 Value::mint_heap(SshSessionTag::descriptor(), tag),
181 );
182 map.insert(FIELD_COMMAND.to_string(), Value::string(command));
183 map.insert(FIELD_USERNAME.to_string(), Value::string(username));
184 map.insert(FIELD_ADDR.to_string(), Value::string(addr));
185 Ok(Value::map(map))
186}
187
188#[oxdock_func(returns = TypeTag::Record(serve_result_fields()), summary = "Serve SSH on a virtual service endpoint.")]
196#[example(
197 name = "serve and close",
198 code = r###"
199 IMPORT [STD, SSH]
200 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-serve", {username: "u", password: "p"})
201 ASSERT_EQ $m.virtual "doc-ssh-serve"
202 SSH_CLOSE($m.server)
203 "###
204)]
205fn ssh_serve<P: ProcessManager>(
206 cx: &mut StepCtx<P>,
207 bind: String,
209 #[options(
211 "username: STRING",
212 "password: STRING",
213 "key_path?: STRING",
214 "idle_timeout?: DURATION|STRING"
215 )]
216 options: BTreeMap<String, Value>,
217) -> Result<Value> {
218 let map = &options;
219 let username = match map.get(FIELD_USERNAME) {
220 Some(value) => {
221 let text = value.as_str().expect("check_options verified STRING");
222 if text.trim().is_empty() {
223 bail!("SSH_SERVE option '{FIELD_USERNAME}' must not be empty");
224 }
225 text.to_string()
226 }
227 None => bail!("SSH_SERVE option '{FIELD_USERNAME}' is required"),
228 };
229 let password = match map.get(FIELD_PASSWORD) {
230 Some(value) => {
231 let text = value.as_str().expect("check_options verified STRING");
232 if text.trim().is_empty() {
233 bail!("SSH_SERVE option '{FIELD_PASSWORD}' must not be empty");
234 }
235 text.to_string()
236 }
237 None => bail!("SSH_SERVE option '{FIELD_PASSWORD}' is required"),
238 };
239 let key_path = match map.get(OPT_KEY_PATH) {
240 Some(value) => {
241 let text = value.as_str().expect("check_options verified STRING");
242 if text.trim().is_empty() {
243 None
244 } else {
245 Some(text.to_string())
246 }
247 }
248 None => None,
249 };
250 let idle_timeout = match map.get(OPT_IDLE_TIMEOUT) {
253 Some(value) => {
254 let timeout = if let Some(duration) = value.as_duration() {
256 duration
257 } else {
258 let text = value
259 .as_str()
260 .expect("check_options verified DURATION|STRING");
261 oxdock_parser::command::parse_duration(text).with_context(|| {
262 format!(
263 "SSH_SERVE option '{OPT_IDLE_TIMEOUT}' must be a duration, got {text:?}"
264 )
265 })?
266 };
267 (!timeout.is_zero()).then_some(timeout)
268 }
269 None => Some(crate::runtime::DEFAULT_INACTIVITY_TIMEOUT),
270 };
271 let registry = cx
272 .module_state::<EndpointRegistry>("SSH")
273 .expect("SSH module registers its endpoint registry as module state");
274 let endpoint = parse_serve_endpoint(&bind)?;
275 let key = EndpointKey::tcp(endpoint);
276 let (acquired, registry) = acquire_listener(
277 ®istry,
278 &key,
279 "SSH_SERVE",
280 SocketRequirement::SocketRequired,
281 )?;
282 let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
283 Some(key) => key,
284 None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
285 .context("generate ephemeral Ed25519 host key")?,
286 };
287 let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
288 let id = format!("ssh-{pid}-{id}", pid = std::process::id());
289 let queue = Arc::new(SessionQueue::new());
290 let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
291 let (local_addr, addr_text, thread) = match acquired {
292 AcquiredListener::Tcp { listener, addr } => {
293 let owned = listener
295 .try_clone()
296 .context("SSH_SERVE cannot clone its listener")?;
297 let thread_queue = Arc::clone(&queue);
298 let thread_user = username.clone();
299 let thread_pass = password.clone();
300 let thread = std::thread::Builder::new()
301 .name(id.clone())
302 .spawn(move || {
303 crate::runtime::serve(
304 owned,
305 host_key,
306 thread_user,
307 thread_pass,
308 thread_queue,
309 shutdown_rx,
310 idle_timeout,
311 )
312 })
313 .context("SSH_SERVE cannot spawn the server thread")?;
314 (addr, addr.to_string(), Some(thread))
315 }
316 AcquiredListener::Memory => {
317 drop(shutdown_rx);
319 return Err(no_cli_mapping("SSH_SERVE", &key.endpoint));
320 }
321 AcquiredListener::Offline => {
322 drop(shutdown_rx);
324 (
325 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
326 key.endpoint.to_string(),
327 None,
328 )
329 }
330 };
331 let state = Arc::new(ServerState::new(crate::state::ServerConfig {
332 id,
333 local_addr,
334 addr_text: addr_text.clone(),
335 queue,
336 shutdown_tx,
337 thread,
338 registry: Arc::clone(®istry),
339 endpoint: key.clone(),
340 }));
341 let mut map = BTreeMap::new();
342 map.insert(
343 "server".to_string(),
344 Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
345 );
346 map.insert(FIELD_ADDR.to_string(), Value::string(addr_text));
347 map.insert(FIELD_USERNAME.to_string(), Value::string(username));
348 map.insert(FIELD_PASSWORD.to_string(), Value::string(password));
349 map.insert(
350 "virtual".to_string(),
351 Value::string(key.endpoint.to_string()),
352 );
353 Ok(Value::map(map))
354}
355
356#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
363 name: FIELD_CLOSED.to_string(),
364 ty: TypeTag::Bool,
365 docs: "True when the session closed cleanly.",
366 optional: false,
367 default: None,
368}, Field {
369 name: FIELD_COMMAND.to_string(),
370 ty: TypeTag::String,
371 docs: "Executed command, empty for shells.",
372 optional: false,
373 default: None,
374}])), summary = "Accept one SSH session into pipes.")]
375#[example(
376 name = "accept and close",
377 code = r###"
378 IMPORT [STD, SSH]
379 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-accept", {username: "u", password: "p"})
380 LET $in: PIPE
381 LET $out: PIPE
382 LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
383 LET $cin: PIPE
384 LET $cout: PIPE
385 LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-accept", "u", "p", $cin, $cout) }
386
387 # Close both inputs: each pump observes EOF, half-closes, and both
388 # tasks return their result maps with no cancellation.
389 WITH_IO [stdout=$cin] ECHO "client-hello"
390 WITH_IO [stdout=$in] ECHO "server-greeting"
391 LET $done: MAP<ANY> = AWAIT $acc
392 ASSERT_EQ $done.closed true
393 ASSERT_CONTAINS $done "command"
394 LET $cDone: MAP<ANY> = AWAIT $c
395 ASSERT_EQ $cDone.closed true
396 SSH_CLOSE($m.server)
397 "###
398)]
399fn ssh_accept<P: ProcessManager>(
400 cx: &mut StepCtx<P>,
401 server: SshServerTag,
403 in_pipe: PipeHandle,
405 out_pipe: PipeHandle,
407) -> Result<Value> {
408 if !cx.is_async_task() {
409 bail!(
410 "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE<T> = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
411 );
412 }
413 let in_pipe = Value::pipe_handle(in_pipe);
414 let out_pipe = Value::pipe_handle(out_pipe);
415 let state = Arc::clone(server.state());
416 let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
417 pump_session(
418 cx,
419 &in_pipe,
420 &out_pipe,
421 session.up_rx,
422 session.down_tx,
423 true,
424 )?;
425 let mut map = BTreeMap::new();
426 map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
427 map.insert(
428 "command".to_string(),
429 Value::string(session.exec_command.unwrap_or_default()),
430 );
431 Ok(Value::map(map))
432}
433
434#[oxdock_func(
439 returns = TypeTag::Record(std::sync::Arc::from([Field {
440 name: FIELD_CLOSED.to_string(),
441 ty: TypeTag::Bool,
442 docs: "True when the session closed cleanly.",
443 optional: false,
444 default: None,
445 }])),
446 summary = "Pump a dequeued SSH session through pipes."
447)]
448#[example(
449 name = "pump a session",
450 code = r###"
451 IMPORT [STD, SSH]
452 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pump", {username: "u", password: "p"})
453 LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
454 LET $cin: PIPE
455 LET $cout: PIPE
456 LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-pump", "u", "p", $cin, $cout) }
457 WITH_IO [stdout=$cin] ECHO "client-hello"
458 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
459 LET $sin: PIPE
460 LET $sout: PIPE
461 LET $p: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
462 WITH_IO [stdout=$sin] ECHO "server-greeting"
463 LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
464 ASSERT_EQ $cDone.closed true
465 LET $pDone: MAP<ANY> = AWAIT $p
466 ASSERT_EQ $pDone.closed true
467 SSH_CLOSE($m.server)
468 "###
469)]
470fn ssh_pump_channel<P: ProcessManager>(
471 cx: &mut StepCtx<P>,
472 session: SshSessionTag,
474 in_pipe: PipeHandle,
476 out_pipe: PipeHandle,
478) -> Result<Value> {
479 if !cx.is_async_task() {
480 bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
481 }
482 let in_pipe = Value::pipe_handle(in_pipe);
483 let out_pipe = Value::pipe_handle(out_pipe);
484 let (up_rx, down_tx) = session.take_pump_ends()?;
485 let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, true);
489 session.finish_pump();
490 pump?;
491 let mut map = BTreeMap::new();
492 map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
493 Ok(Value::map(map))
494}
495
496#[oxdock_func(returns = TypeTag::Bool, summary = "Send the session exit status to the client.")]
501#[example(
502 name = "report exit status",
503 code = r###"
504 IMPORT [STD, SSH]
505 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exit-status", {username: "u", password: "p"})
506 LET $srv: HANDLE<VOID> = ASYNC {
507 LET $sess: SSH_DEQUEUE_INFO = SSH_DEQUEUE($m.server)
508 LET $sin: PIPE
509 LET $sout: PIPE
510 LET $p: HANDLE<VOID> = ASYNC { SSH_PUMP_CHANNEL($sess.session, $sin, $sout) }
511 SSH_SEND_EXIT_STATUS($sess.session, 3)
512 WITH_IO [stdout=$sin] ECHO "server-greeting"
513 AWAIT $p
514 }
515 LET $cin: PIPE
516 LET $cout: PIPE
517 LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-exit-status", "u", "p", $cin, $cout) }
518 # Close the client input: its pump observes EOF and half-closes, so
519 # both pumps drain instead of idling on an empty pipe.
520 WITH_IO [stdout=$cin] ECHO "client-hello"
521 LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
522 ASSERT_EQ $cDone.closed true
523 ASSERT_EQ $cDone.exit_status 3
524 AWAIT $srv
525 SSH_CLOSE($m.server)
526 "###
527)]
528fn ssh_send_exit_status<P: ProcessManager>(
529 cx: &mut StepCtx<P>,
530 session: SshSessionTag,
532 code: i64,
534) -> Result<Value> {
535 let _ = cx;
536 if code < 0 {
537 bail!("SSH_SEND_EXIT_STATUS code must not be negative: {code}");
538 }
539 let code = u32::try_from(code)
540 .map_err(|_| anyhow::anyhow!("SSH_SEND_EXIT_STATUS code out of range: {code}"))?;
541 session.send_exit_status(code)?;
542 Ok(Value::bool(true))
543}
544
545#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
549#[example(
550 name = "shut down",
551 code = r###"
552 IMPORT [STD, SSH]
553 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-close", {username: "u", password: "p"})
554 LET $ok: BOOL = SSH_CLOSE($m.server)
555 ASSERT_EQ $ok true
556 "###
557)]
558fn ssh_close<P: ProcessManager>(
559 cx: &mut StepCtx<P>,
560 server: SshServerTag,
562) -> Result<Value> {
563 let _ = cx;
564 let state = Arc::clone(server.state());
565 state.request_shutdown();
566 Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
567}
568
569#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
575 name: FIELD_CLOSED.to_string(),
576 ty: TypeTag::Bool,
577 docs: "True when the session closed cleanly.",
578 optional: false,
579 default: None,
580}, Field {
581 name: FIELD_EXIT_STATUS.to_string(),
582 ty: TypeTag::Int,
583 docs: "Remote exit status, or -1 when none arrived.",
584 optional: false,
585 default: None,
586}])), summary = "Open an SSH client session into pipes.")]
587#[example(
588 name = "connect and close",
589 code = r###"
590 IMPORT [STD, SSH]
591 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-connect", {username: "u", password: "p"})
592 LET $in: PIPE
593 LET $out: PIPE
594 LET $acc: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_ACCEPT($m.server, $in, $out) }
595 LET $cin: PIPE
596 LET $cout: PIPE
597 LET $c: HANDLE<MAP<closed: BOOL, exit_status: INT>> = ASYNC { RETURN SSH_CONNECT("doc-ssh-connect", "u", "p", $cin, $cout) }
598
599 # Close both inputs: each pump observes EOF, half-closes, and both
600 # tasks return their result maps with no cancellation.
601 WITH_IO [stdout=$cin] ECHO "client-hello"
602 WITH_IO [stdout=$in] ECHO "server-greeting"
603 LET $cDone: MAP<closed: BOOL, exit_status: INT> = AWAIT $c
604 ASSERT_EQ $cDone.closed true
605 LET $adone: MAP<ANY> = AWAIT $acc
606 ASSERT_EQ $adone.closed true
607 SSH_CLOSE($m.server)
608 "###
609)]
610fn ssh_connect<P: ProcessManager>(
611 cx: &mut StepCtx<P>,
612 target: String,
614 username: String,
616 password: String,
618 in_pipe: PipeHandle,
620 out_pipe: PipeHandle,
622) -> Result<Value> {
623 if !cx.is_async_task() {
624 bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
625 }
626 let registry = cx
628 .module_state::<EndpointRegistry>("SSH")
629 .expect("SSH module registers its endpoint registry as module state");
630 let in_pipe = Value::pipe_handle(in_pipe);
631 let out_pipe = Value::pipe_handle(out_pipe);
632 if registry.is_offline() {
633 bail!("SSH_CONNECT failed: engine running in --offline mode");
634 }
635 if username.is_empty() {
636 bail!("SSH_CONNECT username must not be empty");
637 }
638 let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
640 let key = EndpointKey::tcp(endpoint);
641 let addr = match resolve_service_target(
642 ®istry,
643 &key,
644 "SSH_CONNECT",
645 SocketRequirement::SocketRequired,
646 )? {
647 ServiceTarget::Tcp(addr) => addr,
648 ServiceTarget::Memory => {
650 return Err(no_cli_mapping("SSH_CONNECT", &key.endpoint));
651 }
652 };
653 let runtime = connect_runtime()?;
654 let session = runtime
655 .block_on(connect_session(&addr, &username, &password))
656 .context("SSH_CONNECT failed")?;
657 let crate::runtime::OutboundSession {
658 up_rx,
659 down_tx,
660 exit_status,
661 wire_done,
662 handle,
663 ..
664 } = session;
665 let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, false);
668 let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
669 pump?;
670 let _ = runtime.block_on(wire_done);
672 let mut map = BTreeMap::new();
673 map.insert(FIELD_CLOSED.to_string(), Value::bool(true));
674 let status = exit_status
675 .lock()
676 .map(|slot| slot.map(i64::from))
677 .unwrap_or(None);
678 map.insert(
679 FIELD_EXIT_STATUS.to_string(),
680 Value::int(status.unwrap_or(-1)),
681 );
682 Ok(Value::map(map))
683}
684
685#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
689#[example(
690 name = "copy",
691 code = r###"
692 # Closing the source ends the copy: the count proves the bytes moved.
693 IMPORT [STD, SSH]
694 LET $in: PIPE
695 WITH_IO [stdout=$in] ECHO "pump-me"
696 LET $out: PIPE
697 LET $n: INT = SSH_PUMP($in, $out)
698 ASSERT_EQ $n 8
699 WITH_IO [stdin=$out] READ_LINE $got
700 ASSERT_EQ $got "pump-me"
701 "###
702)]
703fn ssh_pump<P: ProcessManager>(
704 cx: &mut StepCtx<P>,
705 from_pipe: PipeHandle,
707 to_pipe: PipeHandle,
709) -> Result<Value> {
710 let from_pipe = Value::pipe_handle(from_pipe);
711 let to_pipe = Value::pipe_handle(to_pipe);
712 let cancel = AtomicBool::new(false);
713 let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
714 Ok(Value::int(total))
715}
716
717#[oxdock_func(
760 returns = TypeTag::Int,
761 summary = "Run a command under a sized local terminal into pipes."
762)]
763#[example(
764 name = "run under a terminal",
765 code = r###"
766 IMPORT [STD, SSH]
767 INHERIT_ENV [PATH]
768 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
769 LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
770 LET $cin: PIPE
771 LET $cout: PIPE
772 LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
773 WITH_IO [stdout=$cin] ECHO "client-hello"
774 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
775
776 # The client task only proved the session live: cancel it before the
777 # terminal run, so no two pumps share the session.
778 CANCEL $c
779 LET $pin: PIPE
780 LET $pout: PIPE
781 # Assert on the whole pipe: terminal streams carry setup noise ahead
782 # of child output, so line reads are version-dependent.
783 [family:unix] {
784 LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
785 LET $code: INT = AWAIT $t
786 ASSERT_EQ $code 0
787 ASSERT_CONTAINS $pout "pty-hi"
788 }
789 [family:windows] {
790 LET $t: HANDLE<INT> = ASYNC { RETURN SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
791 LET $code: INT = AWAIT $t
792 ASSERT_EQ $code 0
793 ASSERT_CONTAINS $pout "pty-hi"
794 }
795 SSH_CLOSE($m.server)
796 "###
797)]
798fn ssh_pty_run<P: ProcessManager>(
799 cx: &mut StepCtx<P>,
800 session: SshSessionTag,
802 argv: Vec<String>,
804 rows: i64,
806 cols: i64,
808 in_pipe: PipeHandle,
810 out_pipe: PipeHandle,
812) -> Result<Value> {
813 if !cx.is_async_task() {
814 bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
815 }
816 let in_pipe = Value::pipe_handle(in_pipe);
817 let out_pipe = Value::pipe_handle(out_pipe);
818 let initial = if rows > 0 && cols > 0 {
819 crate::state::PtySize::new(rows as u32, cols as u32)
820 } else {
821 session.pty_size()
822 };
823 let session_report = session.clone();
826 let report = move |code: u32| {
827 let _ = session_report.send_exit_status(code);
828 };
829 let code = crate::pty::pump_pty_session(
830 cx,
831 &argv,
832 initial,
833 &session.pty_size_handle(),
834 &in_pipe,
835 &out_pipe,
836 Some(std::sync::Arc::new(report)),
837 )?;
838 Ok(Value::int(code))
839}
840
841#[oxdock_func(
866 returns = TypeTag::Int,
867 summary = "Run a command with piped stdio into explicit pipes."
868)]
869#[example(
870 name = "run with piped stdio",
871 code = r###"
872 IMPORT [STD, SSH]
873 INHERIT_ENV [PATH]
874 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
875 LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
876 LET $cin: PIPE
877 LET $cout: PIPE
878 LET $c: HANDLE<VOID> = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
879 WITH_IO [stdout=$cin] ECHO "client-hello"
880 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
881
882 # The client task only proved the session live: cancel it before the
883 # run, so no two pumps share the session.
884 CANCEL $c
885 LET $pin: PIPE
886 LET $pout: PIPE
887 LET $perr: PIPE
888 LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
889 [family:windows] {
890 $argv = ["cmd", "/c", "echo run-hi"]
891 }
892 LET $t: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
893 LET $code: INT = AWAIT $t
894 ASSERT_EQ $code 0
895 ASSERT_CONTAINS $pout "run-hi"
896 SSH_CLOSE($m.server)
897 "###
898)]
899fn ssh_run<P: ProcessManager>(
900 cx: &mut StepCtx<P>,
901 session: SshSessionTag,
903 argv: Vec<String>,
905 in_pipe: PipeHandle,
907 out_pipe: PipeHandle,
909 err_pipe: PipeHandle,
911) -> Result<Value> {
912 if !cx.is_async_task() {
913 bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
914 }
915 let in_pipe = Value::pipe_handle(in_pipe);
916 let out_pipe = Value::pipe_handle(out_pipe);
917 let err_pipe = Value::pipe_handle(err_pipe);
918 let session_report = session.clone();
921 let report = move |code: u32| {
922 let _ = session_report.send_exit_status(code);
923 };
924 let code = crate::run::pump_run_session(
925 cx,
926 &argv,
927 &in_pipe,
928 &out_pipe,
929 &err_pipe,
930 Some(std::sync::Arc::new(report)),
931 )?;
932 Ok(Value::int(code))
933}
934
935#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
955#[example(
956 name = "exec collects remote output",
957 code = r###"
958 # The server side answers exec with a local run: dequeue the
959 # session, split the joined command back into argv, run it, and
960 # pump the child output into the channel. The exit status rides
961 # the wire through the session report.
962 IMPORT [STD, SSH]
963 INHERIT_ENV [PATH]
964 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
965 LET $d: HANDLE<SSH_DEQUEUE_INFO> = ASYNC { RETURN SSH_DEQUEUE($m.server) }
966 LET $runner: HANDLE<VOID> = ASYNC {
967 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
968 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
969 LET $wire: PIPE
970 LET $drain: PIPE
971 LET $pump: HANDLE<MAP<ANY>> = ASYNC { RETURN SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
972 LET $pin: PIPE
973 LET $pout: PIPE
974 LET $perr: PIPE
975 LET $run: HANDLE<INT> = ASYNC { RETURN SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
976 LET $n: INT = SSH_PUMP($pout, $wire)
977 LET $code: INT = AWAIT $run
978 LET $pDone: MAP<ANY> = AWAIT $pump
979 ASSERT_EQ $code 0
980 }
981
982 # One call, one MAP: argv in, collected streams out.
983 [family:unix] {
984 LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
985 ASSERT_EQ $res.timed_out false
986 ASSERT_EQ $res.exit 0
987 ASSERT_CONTAINS $res.stdout "exec-hi"
988 }
989 [family:windows] {
990 LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
991 ASSERT_EQ $res.timed_out false
992 ASSERT_EQ $res.exit 0
993 ASSERT_CONTAINS $res.stdout "exec-hi"
994 }
995 AWAIT $runner
996 SSH_CLOSE($m.server)
997 "###
998)]
999fn ssh_exec<P: ProcessManager>(
1000 cx: &mut StepCtx<P>,
1001 target: String,
1003 username: String,
1005 password: String,
1007 argv: Vec<String>,
1010 #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
1013 options: BTreeMap<String, Value>,
1014) -> Result<Value> {
1015 if argv.is_empty() {
1016 bail!("SSH_EXEC needs at least a program");
1017 }
1018 if username.is_empty() {
1019 bail!("SSH_EXEC username must not be empty");
1020 }
1021 let registry = cx
1022 .module_state::<EndpointRegistry>("SSH")
1023 .expect("SSH module registers its endpoint registry as module state");
1024 if registry.is_offline() {
1025 bail!("SSH_EXEC failed: engine running in --offline mode");
1026 }
1027 let endpoint = parse_virtual_endpoint(&target, "SSH_EXEC")?;
1029 let key = EndpointKey::tcp(endpoint);
1030 let addr = match resolve_service_target(
1031 ®istry,
1032 &key,
1033 "SSH_EXEC",
1034 SocketRequirement::SocketRequired,
1035 )? {
1036 ServiceTarget::Tcp(addr) => addr,
1037 ServiceTarget::Memory => {
1039 return Err(no_cli_mapping("SSH_EXEC", &key.endpoint));
1040 }
1041 };
1042 let timeout = match options.get(OPT_TIMEOUT) {
1043 None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
1044 Some(value) => {
1045 let timeout = if let Some(duration) = value.as_duration() {
1047 duration
1048 } else {
1049 let text = value
1050 .as_str()
1051 .expect("check_options verified DURATION|STRING");
1052 oxdock_parser::command::parse_duration(text).with_context(|| {
1053 format!("SSH_EXEC option '{OPT_TIMEOUT}' must be a duration, got {text:?}")
1054 })?
1055 };
1056 if timeout.is_zero() {
1057 bail!("SSH_EXEC option '{OPT_TIMEOUT}' must be positive");
1058 }
1059 timeout
1060 }
1061 };
1062 let max_bytes = match options.get(OPT_MAX_BYTES) {
1063 None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1064 Some(value) => {
1065 let bytes = value.as_i64().expect("check_options verified INT");
1066 if bytes <= 0 {
1067 bail!("SSH_EXEC option '{OPT_MAX_BYTES}' must be positive");
1068 }
1069 bytes as usize
1070 }
1071 };
1072 let command = shell_words::join(&argv).into_bytes();
1075 let runtime = connect_runtime()?;
1076 let outcome = runtime
1077 .block_on(crate::runtime::run_remote_exec(
1078 &addr, &username, &password, command, timeout, max_bytes,
1079 ))
1080 .context("SSH_EXEC failed")?;
1081 let mut map = BTreeMap::new();
1082 map.insert(
1083 FIELD_EXIT.to_string(),
1084 Value::int(outcome.exit.unwrap_or(-1)),
1085 );
1086 map.insert(
1087 "stdout".to_string(),
1088 Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1089 );
1090 map.insert(
1091 "stderr".to_string(),
1092 Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1093 );
1094 map.insert(FIELD_TRUNCATED.to_string(), Value::bool(outcome.truncated));
1095 map.insert(FIELD_TIMED_OUT.to_string(), Value::bool(outcome.timed_out));
1096 Ok(Value::map(map))
1097}
1098
1099#[oxdock_func(pure, returns = TypeTag::String)]
1107#[example(
1108 name = "mint and serve",
1109 code = r###"
1110 IMPORT [STD, SSH]
1111
1112 # Fresh draws mint 64 hex chars with no committed secret.
1113 LET $pass: STRING = SSH_GENERATE_PASSWORD()
1114 LET $len: INT = LEN($pass)
1115 ASSERT_EQ $len 64
1116
1117 # The minted value serves directly as a server password.
1118 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
1119 SSH_CLOSE($m.server)
1120 "###
1121)]
1122fn ssh_generate_password() -> Result<Value> {
1123 Ok(Value::string(crate::generate_password()))
1124}
1125
1126fn serve_result_fields() -> Arc<[Field]> {
1128 Arc::from(vec![
1129 Field {
1130 name: FIELD_SERVER.to_string(),
1131 ty: TypeTag::Custom(SshServerTag::descriptor()),
1132 docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1133 optional: false,
1134 default: None,
1135 },
1136 Field {
1137 name: FIELD_ADDR.to_string(),
1138 ty: TypeTag::String,
1139 docs: "Bound socket address (`ip:port`) of the server.",
1140 optional: false,
1141 default: None,
1142 },
1143 Field {
1144 name: FIELD_USERNAME.to_string(),
1145 ty: TypeTag::String,
1146 docs: "Configured username.",
1147 optional: false,
1148 default: None,
1149 },
1150 Field {
1151 name: FIELD_PASSWORD.to_string(),
1152 ty: TypeTag::String,
1153 docs: "Configured password.",
1154 optional: false,
1155 default: None,
1156 },
1157 Field {
1158 name: FIELD_VIRTUAL.to_string(),
1159 ty: TypeTag::String,
1160 docs: "Virtual endpoint echo of the claimed slot.",
1161 optional: false,
1162 default: None,
1163 },
1164 ])
1165}
1166
1167fn dequeue_result_fields() -> Arc<[Field]> {
1169 Arc::from(vec![
1170 Field {
1171 name: FIELD_SESSION.to_string(),
1172 ty: TypeTag::Custom(SshSessionTag::descriptor()),
1173 docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1174 optional: false,
1175 default: None,
1176 },
1177 Field {
1178 name: FIELD_COMMAND.to_string(),
1179 ty: TypeTag::String,
1180 docs: "Executed command, empty for shells.",
1181 optional: false,
1182 default: None,
1183 },
1184 Field {
1185 name: FIELD_USERNAME.to_string(),
1186 ty: TypeTag::String,
1187 docs: "Authenticated username, empty when unset.",
1188 optional: false,
1189 default: None,
1190 },
1191 Field {
1192 name: FIELD_ADDR.to_string(),
1193 ty: TypeTag::String,
1194 docs: "Peer address, empty when unset.",
1195 optional: false,
1196 default: None,
1197 },
1198 ])
1199}
1200
1201pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1204 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1205}
1206
1207pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1214 let check = registry.pre_run_check("SSH");
1215 HostModule {
1216 name: "SSH".to_string(),
1217 funcs: vec![
1218 SshServe::registration(),
1219 SshAccept::registration(),
1220 SshDequeue::registration(),
1221 SshPumpChannel::registration(),
1222 SshSendExitStatus::registration(),
1223 SshClose::registration(),
1224 SshConnect::registration(),
1225 SshExec::registration(),
1226 SshPump::registration(),
1227 SshPtyRun::registration(),
1228 SshRun::registration(),
1229 SshGeneratePassword::registration(),
1230 ],
1231 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1232 record_schemas: vec![
1233 RecordSchema {
1234 name: "SSH_SERVE_INFO",
1235 fields: serve_result_fields(),
1236 },
1237 RecordSchema {
1238 name: "SSH_DEQUEUE_INFO",
1239 fields: dequeue_result_fields(),
1240 },
1241 ],
1242 states: Vec::new(),
1243 }
1244 .with_state(registry)
1245 .with_state(Arc::new(check))
1246}