1use std::collections::BTreeMap;
9use std::sync::Arc;
10use std::sync::atomic::AtomicBool;
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, check_value_at,
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
155static SSH_SERVE_OPTIONS: &[ParamOption] = &[
168 ParamOption {
169 name: "username",
170 value: TypeTag::String,
171 required: true,
172 default: None,
173 },
174 ParamOption {
175 name: "password",
176 value: TypeTag::String,
177 required: true,
178 default: None,
179 },
180 ParamOption {
181 name: "key_path",
182 value: TypeTag::String,
183 required: false,
184 default: None,
185 },
186];
187
188fn ssh_serve<P: ProcessManager>(
194 cx: &mut StepCtx<P>,
195 registry: &Arc<EndpointRegistry>,
196 bind: String,
197 options: BTreeMap<String, Value>,
198) -> Result<Value> {
199 let map = &options;
200 oxdock_core::check_options(map, SSH_SERVE_OPTIONS, "SSH_SERVE")?;
201 let username = match map.get("username") {
205 Some(value) => {
206 check_value_at(&TypeTag::String, value, "SSH_SERVE option 'username'")?;
207 let text = value.as_str().expect("check_value_at verified STRING");
208 if text.trim().is_empty() {
209 bail!("SSH_SERVE option 'username' must not be empty");
210 }
211 text.to_string()
212 }
213 None => bail!("SSH_SERVE option 'username' is required"),
214 };
215 let password = match map.get("password") {
216 Some(value) => {
217 check_value_at(&TypeTag::String, value, "SSH_SERVE option 'password'")?;
218 let text = value.as_str().expect("check_value_at verified STRING");
219 if text.trim().is_empty() {
220 bail!("SSH_SERVE option 'password' must not be empty");
221 }
222 text.to_string()
223 }
224 None => bail!("SSH_SERVE option 'password' is required"),
225 };
226 let key_path = match map.get("key_path") {
227 Some(value) => {
228 check_value_at(&TypeTag::String, value, "SSH_SERVE option 'key_path'")?;
229 let text = value.as_str().expect("check_value_at verified STRING");
230 if text.trim().is_empty() {
231 None
232 } else {
233 Some(text.to_string())
234 }
235 }
236 None => None,
237 };
238 let endpoint = parse_serve_endpoint(&bind)?;
239 let key = EndpointKey::tcp(endpoint);
240 let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
241 let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
242 Some(key) => key,
243 None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
244 .context("generate ephemeral Ed25519 host key")?,
245 };
246 let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
247 let id = format!("ssh-{pid}-{id}", pid = std::process::id());
248 let queue = Arc::new(SessionQueue::new());
249 let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
250 let (local_addr, addr_text, thread) = match acquired {
251 AcquiredListener::Tcp { listener, addr } => {
252 let owned = listener
255 .try_clone()
256 .context("SSH_SERVE cannot clone its listener")?;
257 let thread_queue = Arc::clone(&queue);
258 let thread_user = username.clone();
259 let thread_pass = password.clone();
260 let thread = std::thread::Builder::new()
261 .name(id.clone())
262 .spawn(move || {
263 crate::runtime::serve(
264 owned,
265 host_key,
266 thread_user,
267 thread_pass,
268 thread_queue,
269 shutdown_rx,
270 )
271 })
272 .context("SSH_SERVE cannot spawn the server thread")?;
273 (addr, addr.to_string(), Some(thread))
274 }
275 AcquiredListener::Memory => {
276 drop(shutdown_rx);
277 bail!(
278 "SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
279 )
280 }
281 AcquiredListener::Offline => {
282 drop(shutdown_rx);
287 (
288 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
289 key.endpoint.to_string(),
290 None,
291 )
292 }
293 };
294 let state = Arc::new(ServerState::new(crate::state::ServerConfig {
295 id,
296 local_addr,
297 addr_text: addr_text.clone(),
298 queue,
299 shutdown_tx,
300 thread,
301 registry: Arc::clone(®istry),
302 endpoint: key.clone(),
303 }));
304 let mut map = BTreeMap::new();
305 map.insert(
306 "server".to_string(),
307 Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
308 );
309 map.insert("addr".to_string(), Value::string(addr_text));
310 map.insert("username".to_string(), Value::string(username));
311 map.insert("password".to_string(), Value::string(password));
312 map.insert(
313 "virtual".to_string(),
314 Value::string(key.endpoint.to_string()),
315 );
316 Ok(Value::map(map))
317}
318
319#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
364 name: "closed".to_string(),
365 ty: TypeTag::Bool,
366 docs: "True when the session closed cleanly.",
367 optional: false,
368}, Field {
369 name: "command".to_string(),
370 ty: TypeTag::String,
371 docs: "Executed command, empty for shells.",
372 optional: false,
373}])), summary = "Accept one SSH session into pipes.")]
374fn ssh_accept<P: ProcessManager>(
375 cx: &mut StepCtx<P>,
376 server: SshServerTag,
378 in_pipe: PipeHandle,
380 out_pipe: PipeHandle,
382) -> Result<Value> {
383 if !cx.is_async_task() {
384 bail!(
385 "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
386 );
387 }
388 let in_pipe = Value::pipe_handle(in_pipe);
391 let out_pipe = Value::pipe_handle(out_pipe);
392 let state = Arc::clone(server.state());
393 let cancel = AtomicBool::new(false);
394 let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
395 pump_session(
396 cx,
397 &in_pipe,
398 &out_pipe,
399 session.up_rx,
400 session.down_tx,
401 &cancel,
402 )?;
403 let mut map = BTreeMap::new();
404 map.insert("closed".to_string(), Value::bool(true));
405 map.insert(
406 "command".to_string(),
407 Value::string(session.exec_command.unwrap_or_default()),
408 );
409 Ok(Value::map(map))
410}
411
412#[oxdock_func(
418 returns = TypeTag::Record(std::sync::Arc::from([Field {
419 name: "closed".to_string(),
420 ty: TypeTag::Bool,
421 docs: "True when the session closed cleanly.",
422 optional: false,
423 }])),
424 summary = "Pump a dequeued SSH session through pipes."
425)]
426fn ssh_pump_channel<P: ProcessManager>(
427 cx: &mut StepCtx<P>,
428 session: SshSessionTag,
430 in_pipe: PipeHandle,
432 out_pipe: PipeHandle,
434) -> Result<Value> {
435 if !cx.is_async_task() {
436 bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
437 }
438 let in_pipe = Value::pipe_handle(in_pipe);
441 let out_pipe = Value::pipe_handle(out_pipe);
442 let (up_rx, down_tx) = session.take_pump_ends()?;
443 let cancel = AtomicBool::new(false);
444 pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
445 let mut map = BTreeMap::new();
446 map.insert("closed".to_string(), Value::bool(true));
447 Ok(Value::map(map))
448}
449
450#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
454fn ssh_close<P: ProcessManager>(
455 cx: &mut StepCtx<P>,
456 server: SshServerTag,
458) -> Result<Value> {
459 let _ = cx;
460 let state = Arc::clone(server.state());
461 state.request_shutdown();
462 Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
463}
464
465fn ssh_connect<P: ProcessManager>(
474 cx: &mut StepCtx<P>,
475 registry: &Arc<EndpointRegistry>,
476 target: String,
477 username: String,
478 password: String,
479 in_pipe: Value,
480 out_pipe: Value,
481) -> Result<Value> {
482 if !cx.is_async_task() {
483 bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
484 }
485 if registry.is_offline() {
487 bail!("SSH_CONNECT failed: engine running in --offline mode");
488 }
489 if username.is_empty() {
490 bail!("SSH_CONNECT username must not be empty");
491 }
492 let addr = crate::validate::resolve_connect_addr(registry, &target)?;
493 let runtime = connect_runtime()?;
494 let session = runtime
495 .block_on(connect_session(&addr, &username, &password))
496 .context("SSH_CONNECT failed")?;
497 let crate::runtime::OutboundSession {
498 up_rx,
499 down_tx,
500 handle,
501 ..
502 } = session;
503 let cancel = AtomicBool::new(false);
504 let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
505 let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
506 pump?;
507 let mut map = BTreeMap::new();
508 map.insert("closed".to_string(), Value::bool(true));
509 Ok(Value::map(map))
510}
511
512#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
517fn ssh_pump<P: ProcessManager>(
518 cx: &mut StepCtx<P>,
519 from_pipe: PipeHandle,
521 to_pipe: PipeHandle,
523) -> Result<Value> {
524 let from_pipe = Value::pipe_handle(from_pipe);
527 let to_pipe = Value::pipe_handle(to_pipe);
528 let cancel = AtomicBool::new(false);
529 let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
530 Ok(Value::int(total))
531}
532
533#[oxdock_func(
546 returns = TypeTag::Int,
547 summary = "Run a command under a sized local terminal into pipes."
548)]
549fn ssh_pty_run<P: ProcessManager>(
550 cx: &mut StepCtx<P>,
551 session: SshSessionTag,
553 argv: Vec<String>,
555 rows: i64,
557 cols: i64,
559 in_pipe: PipeHandle,
561 out_pipe: PipeHandle,
563) -> Result<Value> {
564 if !cx.is_async_task() {
565 bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
566 }
567 let in_pipe = Value::pipe_handle(in_pipe);
570 let out_pipe = Value::pipe_handle(out_pipe);
571 let initial = if rows > 0 && cols > 0 {
572 crate::state::PtySize::new(rows as u32, cols as u32)
573 } else {
574 session.pty_size()
575 };
576 let cancel = AtomicBool::new(false);
577 let code = crate::pty::pump_pty_session(
578 cx,
579 &argv,
580 initial,
581 &session.pty_size_handle(),
582 &in_pipe,
583 &out_pipe,
584 &cancel,
585 )?;
586 Ok(Value::int(code))
587}
588
589fn serve_result_fields() -> Arc<[Field]> {
594 Arc::from(vec![
595 Field {
596 name: "server".to_string(),
597 ty: TypeTag::Custom(SshServerTag::descriptor()),
598 docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
599 optional: false,
600 },
601 Field {
602 name: "addr".to_string(),
603 ty: TypeTag::String,
604 docs: "Bound socket address (`ip:port`) of the server.",
605 optional: false,
606 },
607 Field {
608 name: "username".to_string(),
609 ty: TypeTag::String,
610 docs: "Configured username.",
611 optional: false,
612 },
613 Field {
614 name: "password".to_string(),
615 ty: TypeTag::String,
616 docs: "Configured password.",
617 optional: false,
618 },
619 Field {
620 name: "virtual".to_string(),
621 ty: TypeTag::String,
622 docs: "Virtual endpoint echo of the claimed slot.",
623 optional: false,
624 },
625 ])
626}
627
628fn dequeue_result_fields() -> Arc<[Field]> {
631 Arc::from(vec![
632 Field {
633 name: "session".to_string(),
634 ty: TypeTag::Custom(SshSessionTag::descriptor()),
635 docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
636 optional: false,
637 },
638 Field {
639 name: "command".to_string(),
640 ty: TypeTag::String,
641 docs: "Executed command, empty for shells.",
642 optional: false,
643 },
644 Field {
645 name: "username".to_string(),
646 ty: TypeTag::String,
647 docs: "Authenticated username, empty when unset.",
648 optional: false,
649 },
650 Field {
651 name: "addr".to_string(),
652 ty: TypeTag::String,
653 docs: "Peer address, empty when unset.",
654 optional: false,
655 },
656 ])
657}
658
659pub fn module_with<P: ProcessManager>() -> HostModule<P> {
662 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
663}
664
665pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
670 HostModule {
671 name: "SSH".to_string(),
672 funcs: vec![
673 ssh_serve_registration(Arc::clone(®istry)),
674 SshAccept::registration(),
675 SshDequeue::registration(),
676 SshPumpChannel::registration(),
677 SshClose::registration(),
678 ssh_connect_registration(registry),
679 SshPump::registration(),
680 SshPtyRun::registration(),
681 ],
682 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
683 record_schemas: vec![
684 RecordSchema {
685 name: "SSH_SERVE_INFO",
686 fields: serve_result_fields(),
687 },
688 RecordSchema {
689 name: "SSH_DEQUEUE_INFO",
690 fields: dequeue_result_fields(),
691 },
692 ],
693 }
694}
695
696fn ssh_serve_registration<P: ProcessManager>(
700 registry: Arc<EndpointRegistry>,
701) -> HostRegistration<P> {
702 let params = vec![
705 FuncParam {
706 name: "bind".to_string(),
707 param_type: Some(TypeTag::String),
708 allowed: None,
709 docs: "Virtual service endpoint to serve (logical port or service name).",
710 options: None,
711 optional: false,
712 },
713 FuncParam {
714 name: "options".to_string(),
715 param_type: Some(TypeTag::Map),
716 allowed: None,
717 docs: "Server credentials and host key.",
718 options: Some(SSH_SERVE_OPTIONS),
719 optional: false,
720 },
721 ];
722 let arity = params.len();
723 let func: NativeFn<P> = Arc::new(move |cx, values| {
724 if values.len() != arity {
725 bail!(
726 "SSH_SERVE() expects {arity} argument(s), got {}",
727 values.len()
728 );
729 }
730 let mut values = values.into_iter();
731 let bind = match values.next().expect("arity checked above").as_str() {
732 Some(s) => s.to_string(),
733 None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
734 };
735 let options_value = values.next().expect("arity checked above");
736 let options = match options_value.as_map() {
737 Some(map) => map.clone(),
738 None => bail!(
739 "SSH_SERVE() argument `$options` must be a MAP, got {}",
740 options_value.type_name()
741 ),
742 };
743 ssh_serve(cx, ®istry, bind, options)
744 });
745 HostRegistration::Stateful {
746 name: "SSH_SERVE".to_string(),
747 meta: FuncMeta {
748 name: "SSH_SERVE".to_string(),
749 module: String::new(),
751 kind: FuncKind::HostCtx,
752 params: Some(params),
753 returns: Some(TypeTag::Record(serve_result_fields())),
754 rpn: false,
755 summary: "Serve SSH on a virtual service endpoint.",
756 docs: "Serve SSH on a virtual service endpoint.",
757 },
758 func,
759 }
760}
761
762fn ssh_connect_registration<P: ProcessManager>(
765 registry: Arc<EndpointRegistry>,
766) -> HostRegistration<P> {
767 let params = vec![
770 FuncParam {
771 name: "target".to_string(),
772 param_type: Some(TypeTag::String),
773 allowed: None,
774 docs: "Dial target: logical port, service name, served address, or `host:port`.",
775 options: None,
776 optional: false,
777 },
778 FuncParam {
779 name: "username".to_string(),
780 param_type: Some(TypeTag::String),
781 allowed: None,
782 docs: "Inner credentials for the SSH session.",
783 options: None,
784 optional: false,
785 },
786 FuncParam {
787 name: "password".to_string(),
788 param_type: Some(TypeTag::String),
789 allowed: None,
790 docs: "Inner credentials for the SSH session.",
791 options: None,
792 optional: false,
793 },
794 FuncParam {
795 name: "in_pipe".to_string(),
796 param_type: Some(TypeTag::Pipe),
797 allowed: None,
798 docs: "Pipe carrying bytes consumed by the wire side.",
799 options: None,
800 optional: false,
801 },
802 FuncParam {
803 name: "out_pipe".to_string(),
804 param_type: Some(TypeTag::Pipe),
805 allowed: None,
806 docs: "Pipe carrying bytes produced by the wire side.",
807 options: None,
808 optional: false,
809 },
810 ];
811 let arity = params.len();
812 let func: NativeFn<P> = Arc::new(move |cx, values| {
813 if values.len() != arity {
814 bail!(
815 "SSH_CONNECT() expects {arity} argument(s), got {}",
816 values.len()
817 );
818 }
819 let mut values = values.into_iter();
820 let target = match values.next().expect("arity checked above").as_str() {
821 Some(s) => s.to_string(),
822 None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
823 };
824 let username = match values.next().expect("arity checked above").as_str() {
825 Some(s) => s.to_string(),
826 None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
827 };
828 let password = match values.next().expect("arity checked above").as_str() {
829 Some(s) => s.to_string(),
830 None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
831 };
832 let in_pipe = values.next().expect("arity checked above");
833 if in_pipe.as_pipe_handle().is_none() {
834 bail!(
835 "SSH_CONNECT() argument `$in_pipe` must be a PIPE, got {}",
836 in_pipe.type_name()
837 );
838 }
839 let out_pipe = values.next().expect("arity checked above");
840 if out_pipe.as_pipe_handle().is_none() {
841 bail!(
842 "SSH_CONNECT() argument `$out_pipe` must be a PIPE, got {}",
843 out_pipe.type_name()
844 );
845 }
846 ssh_connect(cx, ®istry, target, username, password, in_pipe, out_pipe)
847 });
848 HostRegistration::Stateful {
849 name: "SSH_CONNECT".to_string(),
850 meta: FuncMeta {
851 name: "SSH_CONNECT".to_string(),
852 module: String::new(),
854 kind: FuncKind::HostCtx,
855 params: Some(params),
856 returns: Some(TypeTag::Map),
857 rpn: false,
858 summary: "Open an SSH client session into pipes.",
859 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.",
860 },
861 func,
862 }
863}