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
32static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
34
35fn 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 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 let _ = started_rx.recv();
81 hub.poke();
82 let _ = bridge.join();
83 result
84 })
85}
86
87#[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: 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#[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 bind: String,
185 #[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 let idle_timeout = match map.get("idle_timeout") {
229 Some(value) => {
230 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 ®istry,
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 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 drop(shutdown_rx);
293 return Err(no_cli_mapping("SSH_SERVE", &key.endpoint));
294 }
295 AcquiredListener::Offline => {
296 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(®istry),
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#[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: SshServerTag,
375 in_pipe: PipeHandle,
377 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#[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: SshSessionTag,
445 in_pipe: PipeHandle,
447 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 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#[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: SshSessionTag,
503 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#[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: 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#[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 target: String,
573 username: String,
575 password: String,
577 in_pipe: PipeHandle,
579 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 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 let endpoint = parse_virtual_endpoint(&target, "SSH_CONNECT")?;
599 let key = EndpointKey::tcp(endpoint);
600 let addr = match resolve_service_target(
601 ®istry,
602 &key,
603 "SSH_CONNECT",
604 SocketRequirement::SocketRequired,
605 )? {
606 ServiceTarget::Tcp(addr) => addr,
607 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 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 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#[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 from_pipe: PipeHandle,
663 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#[oxdock_func(
716 returns = TypeTag::Int,
717 summary = "Run a command under a sized local terminal into pipes."
718)]
719#[example(
720 name = "run under a terminal",
721 code = r###"
722 IMPORT [STD, SSH]
723 INHERIT_ENV [PATH]
724 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-pty", {username: "u", password: "p"})
725 LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
726 LET $cin: PIPE
727 LET $cout: PIPE
728 LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-pty", "u", "p", $cin, $cout) }
729 WITH_IO [stdout=$cin] ECHO "client-hello"
730 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
731
732 # The client task only proved the session live: cancel it before the
733 # terminal run, so no two pumps share the session.
734 CANCEL $c
735 LET $pin: PIPE
736 LET $pout: PIPE
737 # Assert on the whole pipe: terminal streams carry setup noise ahead
738 # of child output, so line reads are version-dependent.
739 [family:unix] {
740 LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["sh", "-c", "echo pty-hi"], 0, 0, $pin, $pout) }
741 LET $code: INT = AWAIT $t
742 ASSERT_EQ $code 0
743 ASSERT_CONTAINS $pout "pty-hi"
744 }
745 [family:windows] {
746 LET $t: HANDLE = ASYNC { SSH_PTY_RUN($sess.session, ["cmd", "/c", "echo pty-hi"], 0, 0, $pin, $pout) }
747 LET $code: INT = AWAIT $t
748 ASSERT_EQ $code 0
749 ASSERT_CONTAINS $pout "pty-hi"
750 }
751 SSH_CLOSE($m.server)
752 "###
753)]
754fn ssh_pty_run<P: ProcessManager>(
755 cx: &mut StepCtx<P>,
756 session: SshSessionTag,
758 argv: Vec<String>,
760 rows: i64,
762 cols: i64,
764 in_pipe: PipeHandle,
766 out_pipe: PipeHandle,
768) -> Result<Value> {
769 if !cx.is_async_task() {
770 bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
771 }
772 let in_pipe = Value::pipe_handle(in_pipe);
773 let out_pipe = Value::pipe_handle(out_pipe);
774 let initial = if rows > 0 && cols > 0 {
775 crate::state::PtySize::new(rows as u32, cols as u32)
776 } else {
777 session.pty_size()
778 };
779 let session_report = session.clone();
782 let report = move |code: u32| {
783 let _ = session_report.send_exit_status(code);
784 };
785 let code = crate::pty::pump_pty_session(
786 cx,
787 &argv,
788 initial,
789 &session.pty_size_handle(),
790 &in_pipe,
791 &out_pipe,
792 Some(std::sync::Arc::new(report)),
793 )?;
794 Ok(Value::int(code))
795}
796
797#[oxdock_func(
822 returns = TypeTag::Int,
823 summary = "Run a command with piped stdio into explicit pipes."
824)]
825#[example(
826 name = "run with piped stdio",
827 code = r###"
828 IMPORT [STD, SSH]
829 INHERIT_ENV [PATH]
830 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-run", {username: "u", password: "p"})
831 LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
832 LET $cin: PIPE
833 LET $cout: PIPE
834 LET $c: HANDLE = ASYNC { SSH_CONNECT("doc-ssh-run", "u", "p", $cin, $cout) }
835 WITH_IO [stdout=$cin] ECHO "client-hello"
836 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
837
838 # The client task only proved the session live: cancel it before the
839 # run, so no two pumps share the session.
840 CANCEL $c
841 LET $pin: PIPE
842 LET $pout: PIPE
843 LET $perr: PIPE
844 LET $argv: LIST<STRING> = ["sh", "-c", "echo run-hi"]
845 [family:windows] {
846 $argv = ["cmd", "/c", "echo run-hi"]
847 }
848 LET $t: HANDLE = ASYNC { SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
849 LET $code: INT = AWAIT $t
850 ASSERT_EQ $code 0
851 ASSERT_CONTAINS $pout "run-hi"
852 SSH_CLOSE($m.server)
853 "###
854)]
855fn ssh_run<P: ProcessManager>(
856 cx: &mut StepCtx<P>,
857 session: SshSessionTag,
859 argv: Vec<String>,
861 in_pipe: PipeHandle,
863 out_pipe: PipeHandle,
865 err_pipe: PipeHandle,
867) -> Result<Value> {
868 if !cx.is_async_task() {
869 bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
870 }
871 let in_pipe = Value::pipe_handle(in_pipe);
872 let out_pipe = Value::pipe_handle(out_pipe);
873 let err_pipe = Value::pipe_handle(err_pipe);
874 let session_report = session.clone();
877 let report = move |code: u32| {
878 let _ = session_report.send_exit_status(code);
879 };
880 let code = crate::run::pump_run_session(
881 cx,
882 &argv,
883 &in_pipe,
884 &out_pipe,
885 &err_pipe,
886 Some(std::sync::Arc::new(report)),
887 )?;
888 Ok(Value::int(code))
889}
890
891#[oxdock_func(returns = TypeTag::Map, summary = "Run argv on a remote host over SSH and collect the result.")]
911#[example(
912 name = "exec collects remote output",
913 code = r###"
914 # The server side answers exec with a local run: dequeue the
915 # session, split the joined command back into argv, run it, and
916 # pump the child output into the channel. The exit status rides
917 # the wire through the session report.
918 IMPORT [STD, SSH]
919 INHERIT_ENV [PATH]
920 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-exec", {username: "u", password: "p"})
921 LET $d: HANDLE = ASYNC { SSH_DEQUEUE($m.server) }
922 LET $runner: HANDLE = ASYNC {
923 LET $sess: SSH_DEQUEUE_INFO = AWAIT $d
924 LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS($sess.command)
925 LET $wire: PIPE
926 LET $drain: PIPE
927 LET $pump: HANDLE = ASYNC { SSH_PUMP_CHANNEL($sess.session, $wire, $drain) }
928 LET $pin: PIPE
929 LET $pout: PIPE
930 LET $perr: PIPE
931 LET $run: HANDLE = ASYNC { SSH_RUN($sess.session, $argv, $pin, $pout, $perr) }
932 LET $n: INT = SSH_PUMP($pout, $wire)
933 LET $code: INT = AWAIT $run
934 LET $pDone: MAP<ANY> = AWAIT $pump
935 ASSERT_EQ $code 0
936 }
937
938 # One call, one MAP: argv in, collected streams out.
939 [family:unix] {
940 LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["echo", "exec-hi"], {})
941 ASSERT_EQ $res.timed_out false
942 ASSERT_EQ $res.exit 0
943 ASSERT_CONTAINS $res.stdout "exec-hi"
944 }
945 [family:windows] {
946 LET $res: MAP<ANY> = SSH_EXEC("doc-ssh-exec", "u", "p", ["cmd", "/c", "echo exec-hi"], {})
947 ASSERT_EQ $res.timed_out false
948 ASSERT_EQ $res.exit 0
949 ASSERT_CONTAINS $res.stdout "exec-hi"
950 }
951 AWAIT $runner
952 SSH_CLOSE($m.server)
953 "###
954)]
955fn ssh_exec<P: ProcessManager>(
956 cx: &mut StepCtx<P>,
957 target: String,
959 username: String,
961 password: String,
963 argv: Vec<String>,
966 #[options("timeout?: DURATION|STRING", "max_bytes?: INT")]
969 options: BTreeMap<String, Value>,
970) -> Result<Value> {
971 if argv.is_empty() {
972 bail!("SSH_EXEC needs at least a program");
973 }
974 if username.is_empty() {
975 bail!("SSH_EXEC username must not be empty");
976 }
977 let registry = cx
978 .module_state::<EndpointRegistry>("SSH")
979 .expect("SSH module registers its endpoint registry as module state");
980 if registry.is_offline() {
981 bail!("SSH_EXEC failed: engine running in --offline mode");
982 }
983 let endpoint = parse_virtual_endpoint(&target, "SSH_EXEC")?;
985 let key = EndpointKey::tcp(endpoint);
986 let addr = match resolve_service_target(
987 ®istry,
988 &key,
989 "SSH_EXEC",
990 SocketRequirement::SocketRequired,
991 )? {
992 ServiceTarget::Tcp(addr) => addr,
993 ServiceTarget::Memory => {
995 return Err(no_cli_mapping("SSH_EXEC", &key.endpoint));
996 }
997 };
998 let timeout = match options.get("timeout") {
999 None => crate::runtime::DEFAULT_EXEC_TIMEOUT,
1000 Some(value) => {
1001 let timeout = if let Some(duration) = value.as_duration() {
1003 duration
1004 } else {
1005 let text = value
1006 .as_str()
1007 .expect("check_options verified DURATION|STRING");
1008 oxdock_parser::command::parse_duration(text).with_context(|| {
1009 format!("SSH_EXEC option 'timeout' must be a duration, got {text:?}")
1010 })?
1011 };
1012 if timeout.is_zero() {
1013 bail!("SSH_EXEC option 'timeout' must be positive");
1014 }
1015 timeout
1016 }
1017 };
1018 let max_bytes = match options.get("max_bytes") {
1019 None => crate::runtime::DEFAULT_EXEC_MAX_BYTES,
1020 Some(value) => {
1021 let bytes = value.as_i64().expect("check_options verified INT");
1022 if bytes <= 0 {
1023 bail!("SSH_EXEC option 'max_bytes' must be positive");
1024 }
1025 bytes as usize
1026 }
1027 };
1028 let command = shell_words::join(&argv).into_bytes();
1031 let runtime = connect_runtime()?;
1032 let outcome = runtime
1033 .block_on(crate::runtime::run_remote_exec(
1034 &addr, &username, &password, command, timeout, max_bytes,
1035 ))
1036 .context("SSH_EXEC failed")?;
1037 let mut map = BTreeMap::new();
1038 map.insert("exit".to_string(), Value::int(outcome.exit.unwrap_or(-1)));
1039 map.insert(
1040 "stdout".to_string(),
1041 Value::string(String::from_utf8_lossy(&outcome.stdout).into_owned()),
1042 );
1043 map.insert(
1044 "stderr".to_string(),
1045 Value::string(String::from_utf8_lossy(&outcome.stderr).into_owned()),
1046 );
1047 map.insert("truncated".to_string(), Value::bool(outcome.truncated));
1048 map.insert("timed_out".to_string(), Value::bool(outcome.timed_out));
1049 Ok(Value::map(map))
1050}
1051
1052#[oxdock_func(pure, returns = TypeTag::String)]
1060#[example(
1061 name = "mint and serve",
1062 code = r###"
1063 IMPORT [STD, SSH]
1064
1065 # Fresh draws mint 64 hex chars with no committed secret.
1066 LET $pass: STRING = SSH_GENERATE_PASSWORD()
1067 LET $len: INT = TEXT_LENGTH($pass)
1068 ASSERT_EQ $len 64
1069
1070 # The minted value serves directly as a server password.
1071 LET $m: SSH_SERVE_INFO = SSH_SERVE("doc-ssh-gen-pass", {username: "u", password: $pass})
1072 SSH_CLOSE($m.server)
1073 "###
1074)]
1075fn ssh_generate_password() -> Result<Value> {
1076 Ok(Value::string(crate::generate_password()))
1077}
1078
1079fn serve_result_fields() -> Arc<[Field]> {
1081 Arc::from(vec![
1082 Field {
1083 name: "server".to_string(),
1084 ty: TypeTag::Custom(SshServerTag::descriptor()),
1085 docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
1086 optional: false,
1087 },
1088 Field {
1089 name: "addr".to_string(),
1090 ty: TypeTag::String,
1091 docs: "Bound socket address (`ip:port`) of the server.",
1092 optional: false,
1093 },
1094 Field {
1095 name: "username".to_string(),
1096 ty: TypeTag::String,
1097 docs: "Configured username.",
1098 optional: false,
1099 },
1100 Field {
1101 name: "password".to_string(),
1102 ty: TypeTag::String,
1103 docs: "Configured password.",
1104 optional: false,
1105 },
1106 Field {
1107 name: "virtual".to_string(),
1108 ty: TypeTag::String,
1109 docs: "Virtual endpoint echo of the claimed slot.",
1110 optional: false,
1111 },
1112 ])
1113}
1114
1115fn dequeue_result_fields() -> Arc<[Field]> {
1117 Arc::from(vec![
1118 Field {
1119 name: "session".to_string(),
1120 ty: TypeTag::Custom(SshSessionTag::descriptor()),
1121 docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
1122 optional: false,
1123 },
1124 Field {
1125 name: "command".to_string(),
1126 ty: TypeTag::String,
1127 docs: "Executed command, empty for shells.",
1128 optional: false,
1129 },
1130 Field {
1131 name: "username".to_string(),
1132 ty: TypeTag::String,
1133 docs: "Authenticated username, empty when unset.",
1134 optional: false,
1135 },
1136 Field {
1137 name: "addr".to_string(),
1138 ty: TypeTag::String,
1139 docs: "Peer address, empty when unset.",
1140 optional: false,
1141 },
1142 ])
1143}
1144
1145pub fn module_with<P: ProcessManager>() -> HostModule<P> {
1148 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
1149}
1150
1151pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
1158 let check = registry.pre_run_check("SSH");
1159 HostModule {
1160 name: "SSH".to_string(),
1161 funcs: vec![
1162 SshServe::registration(),
1163 SshAccept::registration(),
1164 SshDequeue::registration(),
1165 SshPumpChannel::registration(),
1166 SshSendExitStatus::registration(),
1167 SshClose::registration(),
1168 SshConnect::registration(),
1169 SshExec::registration(),
1170 SshPump::registration(),
1171 SshPtyRun::registration(),
1172 SshRun::registration(),
1173 SshGeneratePassword::registration(),
1174 ],
1175 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
1176 record_schemas: vec![
1177 RecordSchema {
1178 name: "SSH_SERVE_INFO",
1179 fields: serve_result_fields(),
1180 },
1181 RecordSchema {
1182 name: "SSH_DEQUEUE_INFO",
1183 fields: dequeue_result_fields(),
1184 },
1185 ],
1186 states: Vec::new(),
1187 }
1188 .with_state(registry)
1189 .with_state(Arc::new(check))
1190}