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(
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: SshSessionTag,
745 argv: Vec<String>,
747 rows: i64,
749 cols: i64,
751 in_pipe: PipeHandle,
753 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 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#[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 [family:unix] {
832 LET $t: HANDLE = ASYNC { SSH_RUN($sess.session, ["sh", "-c", "echo run-hi"], $pin, $pout, $perr) }
833 LET $code: INT = AWAIT $t
834 ASSERT_EQ $code 0
835 ASSERT_CONTAINS $pout "run-hi"
836 }
837 [family:windows] {
838 LET $t: HANDLE = ASYNC { SSH_RUN($sess.session, ["cmd", "/c", "echo run-hi"], $pin, $pout, $perr) }
839 LET $code: INT = AWAIT $t
840 ASSERT_EQ $code 0
841 ASSERT_CONTAINS $pout "run-hi"
842 }
843 SSH_CLOSE($m.server)
844 "###
845)]
846fn ssh_run<P: ProcessManager>(
847 cx: &mut StepCtx<P>,
848 session: SshSessionTag,
850 argv: Vec<String>,
852 in_pipe: PipeHandle,
854 out_pipe: PipeHandle,
856 err_pipe: PipeHandle,
858) -> Result<Value> {
859 if !cx.is_async_task() {
860 bail!("SSH_RUN requires ASYNC: run it in its own task beside the session pump task");
861 }
862 let in_pipe = Value::pipe_handle(in_pipe);
863 let out_pipe = Value::pipe_handle(out_pipe);
864 let err_pipe = Value::pipe_handle(err_pipe);
865 let session_report = session.clone();
868 let report = move |code: u32| {
869 let _ = session_report.send_exit_status(code);
870 };
871 let code = crate::run::pump_run_session(
872 cx,
873 &argv,
874 &in_pipe,
875 &out_pipe,
876 &err_pipe,
877 Some(std::sync::Arc::new(report)),
878 )?;
879 Ok(Value::int(code))
880}
881
882fn serve_result_fields() -> Arc<[Field]> {
884 Arc::from(vec![
885 Field {
886 name: "server".to_string(),
887 ty: TypeTag::Custom(SshServerTag::descriptor()),
888 docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
889 optional: false,
890 },
891 Field {
892 name: "addr".to_string(),
893 ty: TypeTag::String,
894 docs: "Bound socket address (`ip:port`) of the server.",
895 optional: false,
896 },
897 Field {
898 name: "username".to_string(),
899 ty: TypeTag::String,
900 docs: "Configured username.",
901 optional: false,
902 },
903 Field {
904 name: "password".to_string(),
905 ty: TypeTag::String,
906 docs: "Configured password.",
907 optional: false,
908 },
909 Field {
910 name: "virtual".to_string(),
911 ty: TypeTag::String,
912 docs: "Virtual endpoint echo of the claimed slot.",
913 optional: false,
914 },
915 ])
916}
917
918fn dequeue_result_fields() -> Arc<[Field]> {
920 Arc::from(vec![
921 Field {
922 name: "session".to_string(),
923 ty: TypeTag::Custom(SshSessionTag::descriptor()),
924 docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
925 optional: false,
926 },
927 Field {
928 name: "command".to_string(),
929 ty: TypeTag::String,
930 docs: "Executed command, empty for shells.",
931 optional: false,
932 },
933 Field {
934 name: "username".to_string(),
935 ty: TypeTag::String,
936 docs: "Authenticated username, empty when unset.",
937 optional: false,
938 },
939 Field {
940 name: "addr".to_string(),
941 ty: TypeTag::String,
942 docs: "Peer address, empty when unset.",
943 optional: false,
944 },
945 ])
946}
947
948pub fn module_with<P: ProcessManager>() -> HostModule<P> {
951 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
952}
953
954pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
961 let check = registry.pre_run_check("SSH");
962 HostModule {
963 name: "SSH".to_string(),
964 funcs: vec![
965 SshServe::registration(),
966 SshAccept::registration(),
967 SshDequeue::registration(),
968 SshPumpChannel::registration(),
969 SshSendExitStatus::registration(),
970 SshClose::registration(),
971 SshConnect::registration(),
972 SshPump::registration(),
973 SshPtyRun::registration(),
974 SshRun::registration(),
975 ],
976 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
977 record_schemas: vec![
978 RecordSchema {
979 name: "SSH_SERVE_INFO",
980 fields: serve_result_fields(),
981 },
982 RecordSchema {
983 name: "SSH_DEQUEUE_INFO",
984 fields: dequeue_result_fields(),
985 },
986 ],
987 states: Vec::new(),
988 }
989 .with_state(registry)
990 .with_state(Arc::new(check))
991}