use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use oxdock_core::{
Field, FuncKind, FuncMeta, FuncParam, HostModule, HostRegistration, NativeFn, OxDockFn,
OxDockType, ParamOption, RecordSchema, StepCtx, TypeTag, Value, check_value_at,
};
use oxdock_func_macro::oxdock_func;
use oxdock_net_plugin::{AcquiredListener, EndpointKey, EndpointRegistry, acquire_listener};
use oxdock_pipe::PipeHandle;
use oxdock_process::ProcessManager;
use russh::keys::{Algorithm, PrivateKey};
use crate::bridge::{pump_pipe_to_pipe, pump_session};
use crate::keys::load_or_create_host_key;
use crate::runtime::{connect_runtime, connect_session};
use crate::state::{
CLOSE_JOIN_TIMEOUT, Dequeue, PendingSession, ServerState, SessionQueue, ShutdownSignal,
};
use crate::types::{SshServerTag, SshSessionTag};
use crate::validate::parse_serve_endpoint;
static SERVER_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
const DEQUEUE_TICK: Duration = Duration::from_millis(10);
fn dequeue_session<P: ProcessManager>(
cx: &StepCtx<P>,
queue: &Arc<SessionQueue>,
func: &str,
) -> Result<PendingSession> {
loop {
match queue.try_pop() {
Dequeue::Session(session) => return Ok(session),
Dequeue::Shutdown => bail!("{func}: server is closed"),
Dequeue::Empty => {}
}
match queue.wait_for_session(DEQUEUE_TICK) {
Dequeue::Session(session) => return Ok(session),
Dequeue::Shutdown => bail!("{func}: server is closed"),
Dequeue::Empty => {}
}
if cx.is_cancelled() {
bail!("{func}: task cancelled");
}
}
}
#[oxdock_func(
returns = TypeTag::Record(dequeue_result_fields()),
summary = "Dequeue one SSH session with its metadata."
)]
fn ssh_dequeue<P: ProcessManager>(
cx: &mut StepCtx<P>,
server: SshServerTag,
) -> Result<Value> {
if !cx.is_async_task() {
bail!(
"SSH_DEQUEUE requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_DEQUEUE($server.server) }}"
);
}
let state = Arc::clone(server.state());
let session = dequeue_session(cx, state.queue(), "SSH_DEQUEUE")?;
let command = session.exec_command.clone().unwrap_or_default();
let username = session.username.clone().unwrap_or_default();
let addr = session
.peer_addr
.map(|addr| addr.to_string())
.unwrap_or_default();
let tag = SshSessionTag::new(
session.exec_command,
session.username,
session.peer_addr,
session.pty_size,
session.up_rx,
session.down_tx,
);
let mut map = BTreeMap::new();
map.insert(
"session".to_string(),
Value::mint_heap(SshSessionTag::descriptor(), tag),
);
map.insert("command".to_string(), Value::string(command));
map.insert("username".to_string(), Value::string(username));
map.insert("addr".to_string(), Value::string(addr));
Ok(Value::map(map))
}
static SSH_SERVE_OPTIONS: &[ParamOption] = &[
ParamOption {
name: "username",
value: TypeTag::String,
required: true,
default: None,
},
ParamOption {
name: "password",
value: TypeTag::String,
required: true,
default: None,
},
ParamOption {
name: "key_path",
value: TypeTag::String,
required: false,
default: None,
},
];
fn ssh_serve<P: ProcessManager>(
cx: &mut StepCtx<P>,
registry: &Arc<EndpointRegistry>,
bind: String,
options: BTreeMap<String, Value>,
) -> Result<Value> {
let map = &options;
oxdock_core::check_options(map, SSH_SERVE_OPTIONS, "SSH_SERVE")?;
let username = match map.get("username") {
Some(value) => {
check_value_at(&TypeTag::String, value, "SSH_SERVE option 'username'")?;
let text = value.as_str().expect("check_value_at verified STRING");
if text.trim().is_empty() {
bail!("SSH_SERVE option 'username' must not be empty");
}
text.to_string()
}
None => bail!("SSH_SERVE option 'username' is required"),
};
let password = match map.get("password") {
Some(value) => {
check_value_at(&TypeTag::String, value, "SSH_SERVE option 'password'")?;
let text = value.as_str().expect("check_value_at verified STRING");
if text.trim().is_empty() {
bail!("SSH_SERVE option 'password' must not be empty");
}
text.to_string()
}
None => bail!("SSH_SERVE option 'password' is required"),
};
let key_path = match map.get("key_path") {
Some(value) => {
check_value_at(&TypeTag::String, value, "SSH_SERVE option 'key_path'")?;
let text = value.as_str().expect("check_value_at verified STRING");
if text.trim().is_empty() {
None
} else {
Some(text.to_string())
}
}
None => None,
};
let endpoint = parse_serve_endpoint(&bind)?;
let key = EndpointKey::tcp(endpoint);
let (acquired, registry) = acquire_listener(registry, &key, "SSH_SERVE")?;
let host_key = match load_or_create_host_key(cx, "SSH_SERVE", key_path)? {
Some(key) => key,
None => PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
.context("generate ephemeral Ed25519 host key")?,
};
let id = SERVER_IDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let id = format!("ssh-{pid}-{id}", pid = std::process::id());
let queue = Arc::new(SessionQueue::new());
let (shutdown_tx, shutdown_rx) = std::sync::mpsc::channel::<ShutdownSignal>();
let (local_addr, addr_text, thread) = match acquired {
AcquiredListener::Tcp { listener, addr } => {
let owned = listener
.try_clone()
.context("SSH_SERVE cannot clone its listener")?;
let thread_queue = Arc::clone(&queue);
let thread_user = username.clone();
let thread_pass = password.clone();
let thread = std::thread::Builder::new()
.name(id.clone())
.spawn(move || {
crate::runtime::serve(
owned,
host_key,
thread_user,
thread_pass,
thread_queue,
shutdown_rx,
)
})
.context("SSH_SERVE cannot spawn the server thread")?;
(addr, addr.to_string(), Some(thread))
}
AcquiredListener::Memory => {
drop(shutdown_rx);
bail!(
"SSH_SERVE: '{key}' is a memory service (SSH needs a TCP socket; map it with -p/--listen)"
)
}
AcquiredListener::Offline => {
drop(shutdown_rx);
(
std::net::SocketAddr::from(([0, 0, 0, 0], 0)),
key.endpoint.to_string(),
None,
)
}
};
let state = Arc::new(ServerState::new(crate::state::ServerConfig {
id,
local_addr,
addr_text: addr_text.clone(),
queue,
shutdown_tx,
thread,
registry: Arc::clone(®istry),
endpoint: key.clone(),
}));
let mut map = BTreeMap::new();
map.insert(
"server".to_string(),
Value::mint_heap(SshServerTag::descriptor(), SshServerTag::new(state)),
);
map.insert("addr".to_string(), Value::string(addr_text));
map.insert("username".to_string(), Value::string(username));
map.insert("password".to_string(), Value::string(password));
map.insert(
"virtual".to_string(),
Value::string(key.endpoint.to_string()),
);
Ok(Value::map(map))
}
#[oxdock_func(returns = TypeTag::Record(std::sync::Arc::from([Field {
name: "closed".to_string(),
ty: TypeTag::Bool,
docs: "True when the session closed cleanly.",
optional: false,
}, Field {
name: "command".to_string(),
ty: TypeTag::String,
docs: "Executed command, empty for shells.",
optional: false,
}])), summary = "Accept one SSH session into pipes.")]
fn ssh_accept<P: ProcessManager>(
cx: &mut StepCtx<P>,
server: SshServerTag,
in_pipe: PipeHandle,
out_pipe: PipeHandle,
) -> Result<Value> {
if !cx.is_async_task() {
bail!(
"SSH_ACCEPT requires ASYNC: wrap it as LET $t: HANDLE = ASYNC {{ SSH_ACCEPT($server, $in, $out) }}"
);
}
let in_pipe = Value::pipe_handle(in_pipe);
let out_pipe = Value::pipe_handle(out_pipe);
let state = Arc::clone(server.state());
let cancel = AtomicBool::new(false);
let session = dequeue_session(cx, state.queue(), "SSH_ACCEPT")?;
pump_session(
cx,
&in_pipe,
&out_pipe,
session.up_rx,
session.down_tx,
&cancel,
)?;
let mut map = BTreeMap::new();
map.insert("closed".to_string(), Value::bool(true));
map.insert(
"command".to_string(),
Value::string(session.exec_command.unwrap_or_default()),
);
Ok(Value::map(map))
}
#[oxdock_func(
returns = TypeTag::Record(std::sync::Arc::from([Field {
name: "closed".to_string(),
ty: TypeTag::Bool,
docs: "True when the session closed cleanly.",
optional: false,
}])),
summary = "Pump a dequeued SSH session through pipes."
)]
fn ssh_pump_channel<P: ProcessManager>(
cx: &mut StepCtx<P>,
session: SshSessionTag,
in_pipe: PipeHandle,
out_pipe: PipeHandle,
) -> Result<Value> {
if !cx.is_async_task() {
bail!("SSH_PUMP_CHANNEL requires ASYNC: pump it in its own task after SSH_DEQUEUE");
}
let in_pipe = Value::pipe_handle(in_pipe);
let out_pipe = Value::pipe_handle(out_pipe);
let (up_rx, down_tx) = session.take_pump_ends()?;
let cancel = AtomicBool::new(false);
pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel)?;
let mut map = BTreeMap::new();
map.insert("closed".to_string(), Value::bool(true));
Ok(Value::map(map))
}
#[oxdock_func(returns = TypeTag::Bool, summary = "Shut down an SSH server.")]
fn ssh_close<P: ProcessManager>(
cx: &mut StepCtx<P>,
server: SshServerTag,
) -> Result<Value> {
let _ = cx;
let state = Arc::clone(server.state());
state.request_shutdown();
Ok(Value::bool(state.join_thread(CLOSE_JOIN_TIMEOUT)))
}
fn ssh_connect<P: ProcessManager>(
cx: &mut StepCtx<P>,
registry: &Arc<EndpointRegistry>,
target: String,
username: String,
password: String,
in_pipe: Value,
out_pipe: Value,
) -> Result<Value> {
if !cx.is_async_task() {
bail!("SSH_CONNECT requires ASYNC: run it in its own task beside the SSH_PUMP tasks");
}
if registry.is_offline() {
bail!("SSH_CONNECT failed: engine running in --offline mode");
}
if username.is_empty() {
bail!("SSH_CONNECT username must not be empty");
}
let addr = crate::validate::resolve_connect_addr(registry, &target)?;
let runtime = connect_runtime()?;
let session = runtime
.block_on(connect_session(&addr, &username, &password))
.context("SSH_CONNECT failed")?;
let crate::runtime::OutboundSession {
up_rx,
down_tx,
handle,
..
} = session;
let cancel = AtomicBool::new(false);
let pump = pump_session(cx, &in_pipe, &out_pipe, up_rx, down_tx, &cancel);
let _ = runtime.block_on(handle.disconnect(russh::Disconnect::ByApplication, "", ""));
pump?;
let mut map = BTreeMap::new();
map.insert("closed".to_string(), Value::bool(true));
Ok(Value::map(map))
}
#[oxdock_func(returns = TypeTag::Int, summary = "Copy one pipe into another until EOF.")]
fn ssh_pump<P: ProcessManager>(
cx: &mut StepCtx<P>,
from_pipe: PipeHandle,
to_pipe: PipeHandle,
) -> Result<Value> {
let from_pipe = Value::pipe_handle(from_pipe);
let to_pipe = Value::pipe_handle(to_pipe);
let cancel = AtomicBool::new(false);
let total = pump_pipe_to_pipe(cx, &from_pipe, &to_pipe, &cancel)?;
Ok(Value::int(total))
}
#[oxdock_func(
returns = TypeTag::Int,
summary = "Run a command under a sized local terminal into pipes."
)]
fn ssh_pty_run<P: ProcessManager>(
cx: &mut StepCtx<P>,
session: SshSessionTag,
argv: Vec<String>,
rows: i64,
cols: i64,
in_pipe: PipeHandle,
out_pipe: PipeHandle,
) -> Result<Value> {
if !cx.is_async_task() {
bail!("SSH_PTY_RUN requires ASYNC: run it in its own task beside the session pump task");
}
let in_pipe = Value::pipe_handle(in_pipe);
let out_pipe = Value::pipe_handle(out_pipe);
let initial = if rows > 0 && cols > 0 {
crate::state::PtySize::new(rows as u32, cols as u32)
} else {
session.pty_size()
};
let cancel = AtomicBool::new(false);
let code = crate::pty::pump_pty_session(
cx,
&argv,
initial,
&session.pty_size_handle(),
&in_pipe,
&out_pipe,
&cancel,
)?;
Ok(Value::int(code))
}
fn serve_result_fields() -> Arc<[Field]> {
Arc::from(vec![
Field {
name: "server".to_string(),
ty: TypeTag::Custom(SshServerTag::descriptor()),
docs: "Server handle for `SSH_ACCEPT`, `SSH_DEQUEUE`, and `SSH_CLOSE`.",
optional: false,
},
Field {
name: "addr".to_string(),
ty: TypeTag::String,
docs: "Bound socket address (`ip:port`) of the server.",
optional: false,
},
Field {
name: "username".to_string(),
ty: TypeTag::String,
docs: "Configured username.",
optional: false,
},
Field {
name: "password".to_string(),
ty: TypeTag::String,
docs: "Configured password.",
optional: false,
},
Field {
name: "virtual".to_string(),
ty: TypeTag::String,
docs: "Virtual endpoint echo of the claimed slot.",
optional: false,
},
])
}
fn dequeue_result_fields() -> Arc<[Field]> {
Arc::from(vec![
Field {
name: "session".to_string(),
ty: TypeTag::Custom(SshSessionTag::descriptor()),
docs: "Session handle for `SSH_PUMP_CHANNEL` (pump ends take once).",
optional: false,
},
Field {
name: "command".to_string(),
ty: TypeTag::String,
docs: "Executed command, empty for shells.",
optional: false,
},
Field {
name: "username".to_string(),
ty: TypeTag::String,
docs: "Authenticated username, empty when unset.",
optional: false,
},
Field {
name: "addr".to_string(),
ty: TypeTag::String,
docs: "Peer address, empty when unset.",
optional: false,
},
])
}
pub fn module_with<P: ProcessManager>() -> HostModule<P> {
module_with_endpoints(Arc::new(EndpointRegistry::new(false)))
}
pub fn module_with_endpoints<P: ProcessManager>(registry: Arc<EndpointRegistry>) -> HostModule<P> {
HostModule {
name: "SSH".to_string(),
funcs: vec![
ssh_serve_registration(Arc::clone(®istry)),
SshAccept::registration(),
SshDequeue::registration(),
SshPumpChannel::registration(),
SshClose::registration(),
ssh_connect_registration(registry),
SshPump::registration(),
SshPtyRun::registration(),
],
types: vec![SshServerTag::descriptor(), SshSessionTag::descriptor()],
record_schemas: vec![
RecordSchema {
name: "SSH_SERVE_INFO",
fields: serve_result_fields(),
},
RecordSchema {
name: "SSH_DEQUEUE_INFO",
fields: dequeue_result_fields(),
},
],
}
}
fn ssh_serve_registration<P: ProcessManager>(
registry: Arc<EndpointRegistry>,
) -> HostRegistration<P> {
let params = vec![
FuncParam {
name: "bind".to_string(),
param_type: Some(TypeTag::String),
allowed: None,
docs: "Virtual service endpoint to serve (logical port or service name).",
options: None,
optional: false,
},
FuncParam {
name: "options".to_string(),
param_type: Some(TypeTag::Map),
allowed: None,
docs: "Server credentials and host key.",
options: Some(SSH_SERVE_OPTIONS),
optional: false,
},
];
let arity = params.len();
let func: NativeFn<P> = Arc::new(move |cx, values| {
if values.len() != arity {
bail!(
"SSH_SERVE() expects {arity} argument(s), got {}",
values.len()
);
}
let mut values = values.into_iter();
let bind = match values.next().expect("arity checked above").as_str() {
Some(s) => s.to_string(),
None => bail!("SSH_SERVE() argument `$bind` must be a STRING"),
};
let options_value = values.next().expect("arity checked above");
let options = match options_value.as_map() {
Some(map) => map.clone(),
None => bail!(
"SSH_SERVE() argument `$options` must be a MAP, got {}",
options_value.type_name()
),
};
ssh_serve(cx, ®istry, bind, options)
});
HostRegistration::Stateful {
name: "SSH_SERVE".to_string(),
meta: FuncMeta {
name: "SSH_SERVE".to_string(),
module: String::new(),
kind: FuncKind::HostCtx,
params: Some(params),
returns: Some(TypeTag::Record(serve_result_fields())),
rpn: false,
summary: "Serve SSH on a virtual service endpoint.",
docs: "Serve SSH on a virtual service endpoint.",
},
func,
}
}
fn ssh_connect_registration<P: ProcessManager>(
registry: Arc<EndpointRegistry>,
) -> HostRegistration<P> {
let params = vec![
FuncParam {
name: "target".to_string(),
param_type: Some(TypeTag::String),
allowed: None,
docs: "Dial target: logical port, service name, served address, or `host:port`.",
options: None,
optional: false,
},
FuncParam {
name: "username".to_string(),
param_type: Some(TypeTag::String),
allowed: None,
docs: "Inner credentials for the SSH session.",
options: None,
optional: false,
},
FuncParam {
name: "password".to_string(),
param_type: Some(TypeTag::String),
allowed: None,
docs: "Inner credentials for the SSH session.",
options: None,
optional: false,
},
FuncParam {
name: "in_pipe".to_string(),
param_type: Some(TypeTag::Pipe),
allowed: None,
docs: "Pipe carrying bytes consumed by the wire side.",
options: None,
optional: false,
},
FuncParam {
name: "out_pipe".to_string(),
param_type: Some(TypeTag::Pipe),
allowed: None,
docs: "Pipe carrying bytes produced by the wire side.",
options: None,
optional: false,
},
];
let arity = params.len();
let func: NativeFn<P> = Arc::new(move |cx, values| {
if values.len() != arity {
bail!(
"SSH_CONNECT() expects {arity} argument(s), got {}",
values.len()
);
}
let mut values = values.into_iter();
let target = match values.next().expect("arity checked above").as_str() {
Some(s) => s.to_string(),
None => bail!("SSH_CONNECT() argument `$target` must be a STRING"),
};
let username = match values.next().expect("arity checked above").as_str() {
Some(s) => s.to_string(),
None => bail!("SSH_CONNECT() argument `$username` must be a STRING"),
};
let password = match values.next().expect("arity checked above").as_str() {
Some(s) => s.to_string(),
None => bail!("SSH_CONNECT() argument `$password` must be a STRING"),
};
let in_pipe = values.next().expect("arity checked above");
if in_pipe.as_pipe_handle().is_none() {
bail!(
"SSH_CONNECT() argument `$in_pipe` must be a PIPE, got {}",
in_pipe.type_name()
);
}
let out_pipe = values.next().expect("arity checked above");
if out_pipe.as_pipe_handle().is_none() {
bail!(
"SSH_CONNECT() argument `$out_pipe` must be a PIPE, got {}",
out_pipe.type_name()
);
}
ssh_connect(cx, ®istry, target, username, password, in_pipe, out_pipe)
});
HostRegistration::Stateful {
name: "SSH_CONNECT".to_string(),
meta: FuncMeta {
name: "SSH_CONNECT".to_string(),
module: String::new(),
kind: FuncKind::HostCtx,
params: Some(params),
returns: Some(TypeTag::Map),
rpn: false,
summary: "Open an SSH client session into pipes.",
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.",
},
func,
}
}