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 FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration, NativeFn, OxDockFn, OxDockType,
16 StepCtx, Value,
17};
18use oxdock_func_macro::oxdock_func;
19use oxdock_net_plugin::{AcquiredListener, EndpointKey, EndpointRegistry, acquire_listener};
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
35const DEQUEUE_TICK: Duration = Duration::from_millis(10);
37
38fn server_state(value: &Value, func: &str) -> Result<Arc<ServerState>> {
40 let Some(tag) = value.read_heap::<SshServerTag>(SshServerTag::descriptor()) else {
41 bail!(
42 "{func} expects an SSH_SERVER value, got {}",
43 value.type_name()
44 );
45 };
46 Ok(Arc::clone(tag.state()))
47}
48
49fn session_tag(value: &Value, func: &str) -> Result<SshSessionTag> {
51 let Some(tag) = value.read_heap::<SshSessionTag>(SshSessionTag::descriptor()) else {
52 bail!(
53 "{func} expects an SSH_SESSION value, got {}",
54 value.type_name()
55 );
56 };
57 Ok(tag.clone())
58}
59
60fn dequeue_session<P: ProcessManager>(
63 cx: &StepCtx<P>,
64 queue: &Arc<SessionQueue>,
65 func: &str,
66) -> Result<PendingSession> {
67 loop {
68 match queue.try_pop() {
69 Dequeue::Session(session) => return Ok(session),
70 Dequeue::Shutdown => bail!("{func}: server is closed"),
71 Dequeue::Empty => {}
72 }
73 match queue.wait_for_session(DEQUEUE_TICK) {
74 Dequeue::Session(session) => return Ok(session),
75 Dequeue::Shutdown => bail!("{func}: server is closed"),
76 Dequeue::Empty => {}
77 }
78 if cx.is_cancelled() {
79 bail!("{func}: task cancelled");
80 }
81 }
82}
83
84#[oxdock_func(
135 returns = "MAP",
136 summary = "Dequeue one SSH session with its metadata."
137)]
138fn ssh_dequeue<P: ProcessManager>(cx: &mut StepCtx<P>, server: Value) -> Result<Value> {
139 if !cx.is_async_task() {
140 bail!(
141 "SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
142 );
143 }
144 let state = server_state(&server, "SSH_DEQUEUE")?;
145 let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
146 let command = session.exec_command.clone().unwrap_or_default();
147 let username = session.username.clone().unwrap_or_default();
148 let addr = session
149 .peer_addr
150 .map(|addr| addr.to_string())
151 .unwrap_or_default();
152 let tag = SshSessionTag::new(
153 session.exec_command,
154 session.username,
155 session.peer_addr,
156 session.pty_size,
157 session.up_rx,
158 session.down_tx,
159 );
160 let mut map = BTreeMap::new();
161 map.insert(
162 "session".to_string(),
163 Value::mint_heap(SshSessionTag::descriptor(), tag),
164 );
165 map.insert("command".to_string(), Value::string(command));
166 map.insert("username".to_string(), Value::string(username));
167 map.insert("addr".to_string(), Value::string(addr));
168 Ok(Value::map(map))
169}
170
171fn argv_list(value: &Value, func: &str) -> Result<Vec<String>> {
173 let Some(items) = value.as_list() else {
174 bail!("{func} argv must be a LIST of strings");
175 };
176 if items.is_empty() {
177 bail!("{func} argv must not be empty");
178 }
179 items
180 .iter()
181 .map(|item| {
182 item.as_str().map(str::to_string).ok_or_else(|| {
183 anyhow::anyhow!("{func} argv must be strings, got {}", item.type_name())
184 })
185 })
186 .collect()
187}
188
189fn serve_options(options: &Value) -> Result<&BTreeMap<String, Value>> {
192 options.as_map().ok_or_else(|| {
193 anyhow::anyhow!(
194 "SSH_SERVE options must be a MAP, got {}",
195 options.type_name()
196 )
197 })
198}
199
200fn required_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<String> {
204 let Some(value) = map.get(key) else {
205 bail!("{func} option '{key}' is required");
206 };
207 let Some(s) = value.as_str() else {
208 bail!(
209 "{func} option '{key}' must be a STRING, got {}",
210 value.type_name()
211 );
212 };
213 if s.trim().is_empty() {
214 bail!("{func} option '{key}' must not be empty");
215 }
216 Ok(s.to_string())
217}
218
219fn optional_string(map: &BTreeMap<String, Value>, func: &str, key: &str) -> Result<Option<String>> {
222 let Some(value) = map.get(key) else {
223 return Ok(None);
224 };
225 let Some(s) = value.as_str() else {
226 bail!(
227 "{func} option '{key}' must be a STRING, got {}",
228 value.type_name()
229 );
230 };
231 let trimmed = s.trim();
232 if trimmed.is_empty() {
233 return Ok(None);
234 }
235 Ok(Some(s.to_string()))
236}
237
238fn ssh_serve<P: ProcessManager>(
253 cx: &mut StepCtx<P>,
254 registry: &Arc<EndpointRegistry>,
255 bind: String,
256 options: Value,
257) -> Result<Value> {
258 let map = serve_options(&options)?;
259 for key in map.keys() {
260 if key != "username" && key != "password" && key != "key_path" {
261 bail!("SSH_SERVE() unknown option '{key}' (expected: username, password, key_path)");
262 }
263 }
264 let username = required_string(map, "SSH_SERVE", "username")?;
265 let password = required_string(map, "SSH_SERVE", "password")?;
266 let key_path = optional_string(map, "SSH_SERVE", "key_path")?;
267 let endpoint = parse_serve_endpoint(&bind)?;
268 let key = EndpointKey::tcp(endpoint);
269 let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
270 let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
271 Some(key) => key,
272 None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
273 .context("generate ephemeral Ed25519 host key")?,
274 };
275 let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
276 let id = format!("ssh-{pid}-{id}", pid = std::process::id());
277 let queue = Arc::new(SessionQueue::new());
278 let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
279 let (local_addr, addr_text, thread) = match acquired {
280 AcquiredListener::Tcp { listener, addr } => {
281 let owned = listener
284 .try_clone()
285 .context("SSH_SERVE cannot clone its listener")?;
286 let thread_queue = Arc::clone(&queue);
287 let thread_user = username.clone();
288 let thread_pass = password.clone();
289 let thread = std::thread::Builder::new()
290 .name(id.clone())
291 .spawn(move || {
292 crate::runtime::serve(
293 owned,
294 host_key,
295 thread_user,
296 thread_pass,
297 thread_queue,
298 shutdown_rx,
299 )
300 })
301 .context("SSH_SERVE cannot spawn the server thread")?;
302 (addr, addr.to_string(), Some(thread))
303 }
304 AcquiredListener::Memory => {
305 drop(shutdown_rx);
306 bail!(
307 "SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
308 )
309 }
310 AcquiredListener::Offline => {
311 drop(shutdown_rx);
316 (
317 std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
318 key.endpoint.to_string(),
319 None,
320 )
321 }
322 };
323 let state = Arc::new(ServerState::new(crate::state::ServerConfig {
324 id,
325 local_addr,
326 addr_text: addr_text.clone(),
327 queue,
328 shutdown_tx,
329 thread,
330 registry: Arc::clone(®istry),
331 endpoint: key.clone(),
332 }));
333 let mut map = BTreeMap::new();
334 map.insert(
335 "server".to_string(),
336 Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
337 );
338 map.insert("addr".to_string(), Value::string(addr_text));
339 map.insert("username".to_string(), Value::string(username));
340 map.insert("password".to_string(), Value::string(password));
341 map.insert(
342 "virtual".to_string(),
343 Value::string(key.endpoint.to_string()),
344 );
345 Ok(Value::map(map))
346}
347
348#[oxdock_func(returns = "MAP", summary = "Accept one SSH session into pipes.")]
392fn ssh_accept<P: ProcessManager>(
393 cx: &mut StepCtx<P>,
394 server: Value,
395 in_pipe: Value,
396 out_pipe: Value,
397) -> Result<Value> {
398 if !cx.is_async_task() {
399 bail!(
400 "SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
401 );
402 }
403 let state = server_state(&server, "SSH_ACCEPT")?;
404 let cancel = AtomicBool::new(false);
405 let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
406 pump_session(
407 cx,
408 &in_pipe,
409 &out_pipe,
410 session.up_rx,
411 session.down_tx,
412 &cancel,
413 )?;
414 let mut map = BTreeMap::new();
415 map.insert("closed".to_string(), Value::bool(true));
416 map.insert(
417 "command".to_string(),
418 Value::string(session.exec_command.unwrap_or_default()),
419 );
420 Ok(Value::map(map))
421}
422
423#[oxdock_func(
428 returns = "MAP",
429 summary = "Pump a dequeued SSH session through pipes."
430)]
431fn ssh_pump_channel<P: ProcessManager>(
432 cx: &mut StepCtx<P>,
433 session: Value,
434 in_pipe: Value,
435 out_pipe: Value,
436) -> Result<Value> {
437 if !cx.is_async_task() {
438 bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
439 }
440 let tag = session_tag(&session, "SSH_PUMP_CHANNEL")?;
441 let (up_rx, down_tx) = tag.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 = "BOOL", summary = "Shut down an SSH server.")]
452fn ssh_close<P: ProcessManager>(cx: &mut StepCtx<P>, server: Value) -> Result<Value> {
453 let _ = cx;
454 let state = server_state(&server, "SSH_CLOSE")?;
455 state.request_shutdown();
456 Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
457}
458
459fn ssh_connect<P: ProcessManager>(
468 cx: &mut StepCtx<P>,
469 registry: &Arc<EndpointRegistry>,
470 target: String,
471 username: String,
472 password: String,
473 in_pipe: Value,
474 out_pipe: Value,
475) -> Result<Value> {
476 if !cx.is_async_task() {
477 bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
478 }
479 if registry.is_offline() {
481 bail!("SSH_CONNECT failed: engine running in --offline mode");
482 }
483 if username.is_empty() {
484 bail!("SSH_CONNECT username must not be empty");
485 }
486 let addr = crate::validate::resolve_connect_addr(registry, &target)?;
487 let runtime = connect_runtime()?;
488 let session = runtime
489 .block_on(connect_session(&addr, &username, &password))
490 .context("SSH_CONNECT failed")?;
491 let crate::runtime::OutboundSession {
492 up_rx,
493 down_tx,
494 handle,
495 ..
496 } = session;
497 let cancel = AtomicBool::new(false);
498 let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
499 let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
500 pump?;
501 let mut map = BTreeMap::new();
502 map.insert("closed".to_string(), Value::bool(true));
503 Ok(Value::map(map))
504}
505
506#[oxdock_func(returns = "INT", summary = "Copy one pipe into another until EOF.")]
510fn ssh_pump<P: ProcessManager>(
511 cx: &mut StepCtx<P>,
512 from_pipe: Value,
513 to_pipe: Value,
514) -> Result<Value> {
515 let cancel = AtomicBool::new(false);
516 let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
517 Ok(Value::int(total))
518}
519
520#[oxdock_func(
532 returns = "INT",
533 summary = "Run a command under a sized local terminal into pipes."
534)]
535fn ssh_pty_run<P: ProcessManager>(
536 cx: &mut StepCtx<P>,
537 session: Value,
538 argv: Value,
539 rows: i64,
540 cols: i64,
541 in_pipe: Value,
542 out_pipe: Value,
543) -> Result<Value> {
544 if !cx.is_async_task() {
545 bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
546 }
547 let tag = session_tag(&session, "SSH_PTY_RUN")?;
548 let argv = argv_list(&argv, "SSH_PTY_RUN")?;
549 let initial = if rows > 0 && cols > 0 {
550 crate::state::PtySize::new(rows as u32, cols as u32)
551 } else {
552 tag.pty_size()
553 };
554 let cancel = AtomicBool::new(false);
555 let code = crate::pty::pump_pty_session(
556 cx,
557 &argv,
558 initial,
559 &tag.pty_size_handle(),
560 &in_pipe,
561 &out_pipe,
562 &cancel,
563 )?;
564 Ok(Value::int(code))
565}
566
567pub fn module_with<P: ProcessManager>() -> HostModule<P> {
570 module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
571}
572
573pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
578 HostModule {
579 name: "SSH".to_string(),
580 funcs: vec![
581 ssh_serve_registration(Arc::clone(®istry)),
582 SshAccept::registration(),
583 SshDequeue::registration(),
584 SshPumpChannel::registration(),
585 SshClose::registration(),
586 ssh_connect_registration(registry),
587 SshPump::registration(),
588 SshPtyRun::registration(),
589 ],
590 types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
591 }
592}
593
594fn ssh_serve_registration<P: ProcessManager>(
598 registry: Arc<EndpointRegistry>,
599) -> HostRegistration<P> {
600 let func: NativeFn<P> = Arc::new(move |cx, values| {
601 if values.len() != 2 {
602 bail!("SSH_SERVE() expects 2 argument(s), got {}", values.len());
603 }
604 let mut values = values.into_iter();
605 let bind = match values.next().expect("arity checked above").as_str() {
606 Some(s) => s.to_string(),
607 None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
608 };
609 let options = values.next().expect("arity checked above");
610 ssh_serve(cx, ®istry, bind, options)
611 });
612 HostRegistration::Stateful {
613 name: "SSH_SERVE".to_string(),
614 meta: FuncMeta {
615 name: "SSH_SERVE".to_string(),
616 module: String::new(),
618 kind: FuncKind::HostCtx,
619 params: Some(vec![
620 FuncParam {
621 name: "bind".to_string(),
622 param_type: Some("STRING".to_string()),
623 },
624 FuncParam {
625 name: "options".to_string(),
626 param_type: None,
627 },
628 ]),
629 returns: Some("MAP".to_string()),
630 rpn: false,
631 summary: "Serve SSH on a virtual service endpoint.",
632 docs: "Serve SSH on a virtual service endpoint.",
633 },
634 func,
635 }
636}
637
638fn ssh_connect_registration<P: ProcessManager>(
641 registry: Arc<EndpointRegistry>,
642) -> HostRegistration<P> {
643 let func: NativeFn<P> = Arc::new(move |cx, values| {
644 if values.len() != 5 {
645 bail!("SSH_CONNECT() expects 5 argument(s), got {}", values.len());
646 }
647 let mut values = values.into_iter();
648 let target = match values.next().expect("arity checked above").as_str() {
649 Some(s) => s.to_string(),
650 None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
651 };
652 let username = match values.next().expect("arity checked above").as_str() {
653 Some(s) => s.to_string(),
654 None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
655 };
656 let password = match values.next().expect("arity checked above").as_str() {
657 Some(s) => s.to_string(),
658 None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
659 };
660 let in_pipe = values.next().expect("arity checked above");
661 let out_pipe = values.next().expect("arity checked above");
662 ssh_connect(cx, ®istry, target, username, password, in_pipe, out_pipe)
663 });
664 HostRegistration::Stateful {
665 name: "SSH_CONNECT".to_string(),
666 meta: FuncMeta {
667 name: "SSH_CONNECT".to_string(),
668 module: String::new(),
670 kind: FuncKind::HostCtx,
671 params: Some(vec![
672 FuncParam {
673 name: "target".to_string(),
674 param_type: Some("STRING".to_string()),
675 },
676 FuncParam {
677 name: "username".to_string(),
678 param_type: Some("STRING".to_string()),
679 },
680 FuncParam {
681 name: "password".to_string(),
682 param_type: Some("STRING".to_string()),
683 },
684 FuncParam {
685 name: "in_pipe".to_string(),
686 param_type: None,
687 },
688 FuncParam {
689 name: "out_pipe".to_string(),
690 param_type: None,
691 },
692 ]),
693 returns: Some("MAP".to_string()),
694 rpn: false,
695 summary: "Open an SSH client session into pipes.",
696 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.",
697 },
698 func,
699 }
700}