1use std::collections::BTreeMap;
9use std::sync::atomic::AtomicBool;
10use std::sync::{Arc, OnceLock};
11use std::time::Duration;
12
13use anyhow::{Context, Result, bail};
14use oxdock_core::{
15 Field, FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration, NativeFn, OxDockFn,
16 OxDockType, ParamOption, RecordSchema, StepCtx, TypeTag, Value,
17};
18use oxdock_func_macro::oxdock_func;
19use oxdock_net_plugin::{AcquiredListener, EndpointKey, EndpointRegistry, acquire_listener};
20use oxdock_pipe::PipeHandle;
21use oxdock_process::ProcessManager;
22use russh::keys::{Algorithm, PrivateKey};
23
24use crate::bridge::{pump_pipe_to_pipe, pump_session};
25use crate::keys::load_or_create_host_key;
26use crate::runtime::{connect_runtime, connect_session};
27use crate::state::{
28 CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
29};
30use crate::types::{SshServerTag, SshSessionTag};
31use crate::validate::parse_serve_endpoint;
32
33static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
35
36const DEQUEUE_TICK: Duration = Duration::from_millis(10);
38
39fn dequeue_session<P: ProcessManager>(
42 cx: &StepCtx<P>,
43 queue: &Arc<SessionQueue>,
44 func: &str,
45) -> Result<PendingSession> {
46 loop {
47 match queue.try_pop() {
48 Dequeue::Session(session) => return Ok(session),
49 Dequeue::Shutdown => bail!("{func}: server is closed"),
50 Dequeue::Empty => {}
51 }
52 match queue.wait_for_session(DEQUEUE_TICK) {
53 Dequeue::Session(session) => return Ok(session),
54 Dequeue::Shutdown => bail!("{func}: server is closed"),
55 Dequeue::Empty => {}
56 }
57 if cx.is_cancelled() {
58 bail!("{func}: task cancelled");
59 }
60 }
61}
62
63#[oxdock_func(
115 returns = TypeTag::Record(dequeue_result_fields()),
116 summary = "Dequeue one SSH session with its metadata."
117)]
118fn ssh_dequeue<P: ProcessManager>(
119 cx: &mut StepCtx<P>,
120 server: SshServerTag,
122) -> Result<Value> {
123 if !cx.is_async_task() {
124 bail!(
125 "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
126 );
127 }
128 let state = Arc::clone(server.state());
129 let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
130 let command = session.exec_command.clone().unwrap_or_default();
131 let username = session.username.clone().unwrap_or_default();
132 let addr = session
133 .peer_addr
134 .map(|addr| addr.to_string())
135 .unwrap_or_default();
136 let tag = SshSessionTag::new(
137 session.exec_command,
138 session.username,
139 session.peer_addr,
140 session.pty_size,
141 session.up_rx,
142 session.down_tx,
143 );
144 let mut map = BTreeMap::new();
145 map.insert(
146 "session".to_string(),
147 Value::mint_heap(SshSessionTag::descriptor(), tag),
148 );
149 map.insert("command".to_string(), Value::string(command));
150 map.insert("username".to_string(), Value::string(username));
151 map.insert("addr".to_string(), Value::string(addr));
152 Ok(Value::map(map))
153}
154
155fn required_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<String> {
159 let Some(value) = map.get(key) else {
160 bail!("{func} option '{key}' is required");
161 };
162 let Some(s) = value.as_str() else {
163 bail!(
164 "{func} option '{key}' must be a STRING, got {}",
165 value.type_name()
166 );
167 };
168 if s.trim().is_empty() {
169 bail!("{func} option '{key}' must not be empty");
170 }
171 Ok(s.to_string())
172}
173
174fn optional_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<Option<String>> {
177 let Some(value) = map.get(key) else {
178 return Ok(None);
179 };
180 let Some(s) = value.as_str() else {
181 bail!(
182 "{func} option '{key}' must be a STRING, got {}",
183 value.type_name()
184 );
185 };
186 let trimmed = s.trim();
187 if trimmed.is_empty() {
188 return Ok(None);
189 }
190 Ok(Some(s.to_string()))
191}
192
193static SSH_SERVE_OPTIONS: &[ParamOption] = &[
206 ParamOption {
207 name: "username",
208 value: TypeTag::String,
209 required: true,
210 default: None,
211 },
212 ParamOption {
213 name: "password",
214 value: TypeTag::String,
215 required: true,
216 default: None,
217 },
218 ParamOption {
219 name: "key_path",
220 value: TypeTag::String,
221 required: false,
222 default: None,
223 },
224];
225
226fn ssh_serve<P: ProcessManager>(
232 cx: &mut StepCtx<P>,
233 registry: &Arc<EndpointRegistry>,
234 bind: String,
235 options: BTreeMap<String, Value>,
236) -> Result<Value> {
237 let map = &options;
238 oxdock_core::check_options(map, SSH_SERVE_OPTIONS, "SSH_SERVE")?;
239 let username = required_string(map, "SSH_SERVE", "username")?;
240 let password = required_string(map, "SSH_SERVE", "password")?;
241 let key_path = optional_string(map, "SSH_SERVE", "key_path")?;
242 let endpoint = parse_serve_endpoint(&bind)?;
243 let key = EndpointKey::tcp(endpoint);
244 let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
245 let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
246 Some(key) => key,
247 None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
248 .context("generate ephemeral Ed25519 host key")?,
249 };
250 let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
251 let id = format!("ssh-{pid}-{id}", pid = std::process::id());
252 let queue = Arc::new(SessionQueue::new());
253 let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
254 let (local_addr, addr_text, thread) = match acquired {
255 AcquiredListener::Tcp { listener, addr } => {
256 let owned = listener
259 .try_clone()
260 .context("SSH_SERVE cannot clone its listener")?;
261 let thread_queue = Arc::clone(&queue);
262 let thread_user = username.clone();
263 let thread_pass = password.clone();
264 let thread = std::thread::Builder::new()
265 .name(id.clone())
266 .spawn(move || {
267 crate::runtime::serve(
268 owned,
269 host_key,
270 thread_user,
271 thread_pass,
272 thread_queue,
273 shutdown_rx,
274 )
275 })
276 .context("SSH_SERVE cannot spawn the server thread")?;
277 (addr, addr.to_string(), Some(thread))
278 }
279 AcquiredListener::Memory => {
280 drop(shutdown_rx);
281 bail!(
282 "SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
283 )
284 }
285 AcquiredListener::Offline => {
286 drop(shutdown_rx);
291 (
292 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
293 key.endpoint.to_string(),
294 None,
295 )
296 }
297 };
298 let state = Arc::new(ServerState::new(crate::state::ServerConfig {
299 id,
300 local_addr,
301 addr_text: addr_text.clone(),
302 queue,
303 shutdown_tx,
304 thread,
305 registry: Arc::clone(®istry),
306 endpoint: key.clone(),
307 }));
308 let mut map = BTreeMap::new();
309 map.insert(
310 "server".to_string(),
311 Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
312 );
313 map.insert("addr".to_string(), Value::string(addr_text));
314 map.insert("username".to_string(), Value::string(username));
315 map.insert("password".to_string(), Value::string(password));
316 map.insert(
317 "virtual".to_string(),
318 Value::string(key.endpoint.to_string()),
319 );
320 Ok(Value::map(map))
321}
322
323#[oxdock_func(returns = TypeTag::Record(&[Field {
368 name: "closed",
369 ty: TypeTag::Bool,
370 docs: "True when the session closed cleanly.",
371 optional: false,
372}]), summary = "Accept one SSH session into pipes.")]
373fn ssh_accept<P: ProcessManager>(
374 cx: &mut StepCtx<P>,
375 server: SshServerTag,
377 in_pipe: PipeHandle,
379 out_pipe: PipeHandle,
381) -> Result<Value> {
382 if !cx.is_async_task() {
383 bail!(
384 "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
385 );
386 }
387 let in_pipe = Value::pipe_handle(in_pipe);
390 let out_pipe = Value::pipe_handle(out_pipe);
391 let state = Arc::clone(server.state());
392 let cancel = AtomicBool::new(false);
393 let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
394 pump_session(
395 cx,
396 &in_pipe,
397 &out_pipe,
398 session.up_rx,
399 session.down_tx,
400 &cancel,
401 )?;
402 let mut map = BTreeMap::new();
403 map.insert("closed".to_string(), Value::bool(true));
404 map.insert(
405 "command".to_string(),
406 Value::string(session.exec_command.unwrap_or_default()),
407 );
408 Ok(Value::map(map))
409}
410
411#[oxdock_func(
417 returns = TypeTag::Record(&[Field {
418 name: "closed",
419 ty: TypeTag::Bool,
420 docs: "True when the session closed cleanly.",
421 optional: false,
422 }]),
423 summary = "Pump a dequeued SSH session through pipes."
424)]
425fn ssh_pump_channel<P: ProcessManager>(
426 cx: &mut StepCtx<P>,
427 session: SshSessionTag,
429 in_pipe: PipeHandle,
431 out_pipe: PipeHandle,
433) -> Result<Value> {
434 if !cx.is_async_task() {
435 bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
436 }
437 let in_pipe = Value::pipe_handle(in_pipe);
440 let out_pipe = Value::pipe_handle(out_pipe);
441 let (up_rx, down_tx) = session.take_pump_ends()?;
442 let cancel = AtomicBool::new(false);
443 pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
444 let mut map = BTreeMap::new();
445 map.insert("closed".to_string(), Value::bool(true));
446 Ok(Value::map(map))
447}
448
449#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
453fn ssh_close<P: ProcessManager>(
454 cx: &mut StepCtx<P>,
455 server: SshServerTag,
457) -> Result<Value> {
458 let _ = cx;
459 let state = Arc::clone(server.state());
460 state.request_shutdown();
461 Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
462}
463
464fn ssh_connect<P: ProcessManager>(
473 cx: &mut StepCtx<P>,
474 registry: &Arc<EndpointRegistry>,
475 target: String,
476 username: String,
477 password: String,
478 in_pipe: Value,
479 out_pipe: Value,
480) -> Result<Value> {
481 if !cx.is_async_task() {
482 bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
483 }
484 if registry.is_offline() {
486 bail!("SSH_CONNECT failed: engine running in --offline mode");
487 }
488 if username.is_empty() {
489 bail!("SSH_CONNECT username must not be empty");
490 }
491 let addr = crate::validate::resolve_connect_addr(registry, &target)?;
492 let runtime = connect_runtime()?;
493 let session = runtime
494 .block_on(connect_session(&addr, &username, &password))
495 .context("SSH_CONNECT failed")?;
496 let crate::runtime::OutboundSession {
497 up_rx,
498 down_tx,
499 handle,
500 ..
501 } = session;
502 let cancel = AtomicBool::new(false);
503 let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
504 let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
505 pump?;
506 let mut map = BTreeMap::new();
507 map.insert("closed".to_string(), Value::bool(true));
508 Ok(Value::map(map))
509}
510
511#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
516fn ssh_pump<P: ProcessManager>(
517 cx: &mut StepCtx<P>,
518 from_pipe: PipeHandle,
520 to_pipe: PipeHandle,
522) -> Result<Value> {
523 let from_pipe = Value::pipe_handle(from_pipe);
526 let to_pipe = Value::pipe_handle(to_pipe);
527 let cancel = AtomicBool::new(false);
528 let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
529 Ok(Value::int(total))
530}
531
532#[oxdock_func(
545 returns = TypeTag::Int,
546 summary = "Run a command under a sized local terminal into pipes."
547)]
548fn ssh_pty_run<P: ProcessManager>(
549 cx: &mut StepCtx<P>,
550 session: SshSessionTag,
552 argv: Vec<String>,
554 rows: i64,
556 cols: i64,
558 in_pipe: PipeHandle,
560 out_pipe: PipeHandle,
562) -> Result<Value> {
563 if !cx.is_async_task() {
564 bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
565 }
566 let in_pipe = Value::pipe_handle(in_pipe);
569 let out_pipe = Value::pipe_handle(out_pipe);
570 let initial = if rows > 0 && cols > 0 {
571 crate::state::PtySize::new(rows as u32, cols as u32)
572 } else {
573 session.pty_size()
574 };
575 let cancel = AtomicBool::new(false);
576 let code = crate::pty::pump_pty_session(
577 cx,
578 &argv,
579 initial,
580 &session.pty_size_handle(),
581 &in_pipe,
582 &out_pipe,
583 &cancel,
584 )?;
585 Ok(Value::int(code))
586}
587
588fn serve_result_fields() -> &'static [Field] {
593 static FIELDS: OnceLock<Vec<Field>> = OnceLock::new();
594 FIELDS.get_or_init(|| {
595 vec![
596 Field {
597 name: "server",
598 ty: TypeTag::Custom(SshServerTag::descriptor()),
599 docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
600 optional: false,
601 },
602 Field {
603 name: "addr",
604 ty: TypeTag::String,
605 docs: "Bound socket address (`ip:port`) of the server.",
606 optional: false,
607 },
608 Field {
609 name: "username",
610 ty: TypeTag::String,
611 docs: "Configured username.",
612 optional: false,
613 },
614 Field {
615 name: "password",
616 ty: TypeTag::String,
617 docs: "Configured password.",
618 optional: false,
619 },
620 Field {
621 name: "virtual",
622 ty: TypeTag::String,
623 docs: "Virtual endpoint echo of the claimed slot.",
624 optional: false,
625 },
626 ]
627 })
628}
629
630fn dequeue_result_fields() -> &'static [Field] {
633 static FIELDS: OnceLock<Vec<Field>> = OnceLock::new();
634 FIELDS.get_or_init(|| {
635 vec![
636 Field {
637 name: "session",
638 ty: TypeTag::Custom(SshSessionTag::descriptor()),
639 docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
640 optional: false,
641 },
642 Field {
643 name: "command",
644 ty: TypeTag::String,
645 docs: "Executed command, empty for shells.",
646 optional: false,
647 },
648 Field {
649 name: "username",
650 ty: TypeTag::String,
651 docs: "Authenticated username, empty when unset.",
652 optional: false,
653 },
654 Field {
655 name: "addr",
656 ty: TypeTag::String,
657 docs: "Peer address, empty when unset.",
658 optional: false,
659 },
660 ]
661 })
662}
663
664pub fn module_with<P: ProcessManager>() -> HostModule<P> {
667 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
668}
669
670pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
675 HostModule {
676 name: "SSH".to_string(),
677 funcs: vec![
678 ssh_serve_registration(Arc::clone(®istry)),
679 SshAccept::registration(),
680 SshDequeue::registration(),
681 SshPumpChannel::registration(),
682 SshClose::registration(),
683 ssh_connect_registration(registry),
684 SshPump::registration(),
685 SshPtyRun::registration(),
686 ],
687 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
688 record_schemas: vec![
689 RecordSchema {
690 name: "SSH_SERVE_INFO",
691 fields: serve_result_fields(),
692 },
693 RecordSchema {
694 name: "SSH_DEQUEUE_INFO",
695 fields: dequeue_result_fields(),
696 },
697 ],
698 }
699}
700
701fn ssh_serve_registration<P: ProcessManager>(
705 registry: Arc<EndpointRegistry>,
706) -> HostRegistration<P> {
707 let params = vec![
710 FuncParam {
711 name: "bind".to_string(),
712 param_type: Some(TypeTag::String),
713 allowed: None,
714 docs: "Virtual service endpoint to serve (logical port or service name).",
715 options: None,
716 optional: false,
717 },
718 FuncParam {
719 name: "options".to_string(),
720 param_type: Some(TypeTag::Map),
721 allowed: None,
722 docs: "Server credentials and host key.",
723 options: Some(SSH_SERVE_OPTIONS),
724 optional: false,
725 },
726 ];
727 let arity = params.len();
728 let func: NativeFn<P> = Arc::new(move |cx, values| {
729 if values.len() != arity {
730 bail!(
731 "SSH_SERVE() expects {arity} argument(s), got {}",
732 values.len()
733 );
734 }
735 let mut values = values.into_iter();
736 let bind = match values.next().expect("arity checked above").as_str() {
737 Some(s) => s.to_string(),
738 None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
739 };
740 let options_value = values.next().expect("arity checked above");
741 let options = match options_value.as_map() {
742 Some(map) => map.clone(),
743 None => bail!(
744 "SSH_SERVE() argument `$options` must be a MAP, got {}",
745 options_value.type_name()
746 ),
747 };
748 ssh_serve(cx, ®istry, bind, options)
749 });
750 HostRegistration::Stateful {
751 name: "SSH_SERVE".to_string(),
752 meta: FuncMeta {
753 name: "SSH_SERVE".to_string(),
754 module: String::new(),
756 kind: FuncKind::HostCtx,
757 params: Some(params),
758 returns: Some(TypeTag::Record(serve_result_fields())),
759 rpn: false,
760 summary: "Serve SSH on a virtual service endpoint.",
761 docs: "Serve SSH on a virtual service endpoint.",
762 },
763 func,
764 }
765}
766
767fn ssh_connect_registration<P: ProcessManager>(
770 registry: Arc<EndpointRegistry>,
771) -> HostRegistration<P> {
772 let params = vec![
775 FuncParam {
776 name: "target".to_string(),
777 param_type: Some(TypeTag::String),
778 allowed: None,
779 docs: "Dial target: logical port, service name, served address, or `host:port`.",
780 options: None,
781 optional: false,
782 },
783 FuncParam {
784 name: "username".to_string(),
785 param_type: Some(TypeTag::String),
786 allowed: None,
787 docs: "Inner credentials for the SSH session.",
788 options: None,
789 optional: false,
790 },
791 FuncParam {
792 name: "password".to_string(),
793 param_type: Some(TypeTag::String),
794 allowed: None,
795 docs: "Inner credentials for the SSH session.",
796 options: None,
797 optional: false,
798 },
799 FuncParam {
800 name: "in_pipe".to_string(),
801 param_type: Some(TypeTag::Pipe),
802 allowed: None,
803 docs: "Pipe carrying bytes consumed by the wire side.",
804 options: None,
805 optional: false,
806 },
807 FuncParam {
808 name: "out_pipe".to_string(),
809 param_type: Some(TypeTag::Pipe),
810 allowed: None,
811 docs: "Pipe carrying bytes produced by the wire side.",
812 options: None,
813 optional: false,
814 },
815 ];
816 let arity = params.len();
817 let func: NativeFn<P> = Arc::new(move |cx, values| {
818 if values.len() != arity {
819 bail!(
820 "SSH_CONNECT() expects {arity} argument(s), got {}",
821 values.len()
822 );
823 }
824 let mut values = values.into_iter();
825 let target = match values.next().expect("arity checked above").as_str() {
826 Some(s) => s.to_string(),
827 None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
828 };
829 let username = match values.next().expect("arity checked above").as_str() {
830 Some(s) => s.to_string(),
831 None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
832 };
833 let password = match values.next().expect("arity checked above").as_str() {
834 Some(s) => s.to_string(),
835 None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
836 };
837 let in_pipe = values.next().expect("arity checked above");
838 if in_pipe.as_pipe_handle().is_none() {
839 bail!(
840 "SSH_CONNECT() argument `$in_pipe` must be a PIPE, got {}",
841 in_pipe.type_name()
842 );
843 }
844 let out_pipe = values.next().expect("arity checked above");
845 if out_pipe.as_pipe_handle().is_none() {
846 bail!(
847 "SSH_CONNECT() argument `$out_pipe` must be a PIPE, got {}",
848 out_pipe.type_name()
849 );
850 }
851 ssh_connect(cx, ®istry, target, username, password, in_pipe, out_pipe)
852 });
853 HostRegistration::Stateful {
854 name: "SSH_CONNECT".to_string(),
855 meta: FuncMeta {
856 name: "SSH_CONNECT".to_string(),
857 module: String::new(),
859 kind: FuncKind::HostCtx,
860 params: Some(params),
861 returns: Some(TypeTag::Map),
862 rpn: false,
863 summary: "Open an SSH client session into pipes.",
864 docs: "Open an SSH client session into pipes. Target shapes: a logical port (CLI-mapped address or loopback default), a service name (CLI-mapped address only), a served address, or a host:port dial.",
865 },
866 func,
867 }
868}