From 80d7d0197fd4dda2a42d9ea3cd5c4e52ede0fc0f Mon Sep 17 00:00:00 2001 From: xxx Date: Fri, 12 Jun 2026 14:09:27 -0700 Subject: [PATCH] refactor(minimald): coalesce code paths between UDS and vsock listeners --- Cargo.lock | 1 + crates/minimald/Cargo.toml | 1 + crates/minimald/src/connection.rs | 11 - crates/minimald/src/guest.rs | 34 +-- crates/minimald/src/main.rs | 311 ++++++++++++++++------------ crates/minimald/src/server.rs | 126 ++++++----- crates/minimald/src/test_harness.rs | 4 +- crates/paths/src/lib.rs | 6 + 8 files changed, 287 insertions(+), 207 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2c2bc5a512..848a832ec0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3441,6 +3441,7 @@ dependencies = [ "libc", "mctx", "mfile", + "nix 0.31.3", "ot", "path-absolutize", "paths", diff --git a/crates/minimald/Cargo.toml b/crates/minimald/Cargo.toml index f3828d1848..376e1ca908 100644 --- a/crates/minimald/Cargo.toml +++ b/crates/minimald/Cargo.toml @@ -38,4 +38,5 @@ stdlib.workspace = true # The guest (initramfs pid-1) boot path is Linux-only. [target.'cfg(target_os = "linux")'.dependencies] +nix.workspace = true tokio-vsock.workspace = true diff --git a/crates/minimald/src/connection.rs b/crates/minimald/src/connection.rs index 496574f2b3..9e4ce15d84 100644 --- a/crates/minimald/src/connection.rs +++ b/crates/minimald/src/connection.rs @@ -10,7 +10,6 @@ use std::{ }; use tokio::{ io::{AsyncRead, AsyncWrite}, - net::UnixStream, sync::{Mutex, MutexGuard}, }; @@ -155,16 +154,6 @@ impl Connection { ) } - /// Thin wrapper over [`Connection::from_stream`] for the UDS transport. - pub(crate) async fn from_socket( - s: UnixStream, - c: Arc, - serv: ServerStateHandle, - was_local_uds: bool, - ) -> (ConnectionHandle, RunningSession) { - Self::from_stream(s, c, serv, was_local_uds).await - } - pub(crate) fn pending_config_mut(&mut self, id: ChannelId) -> Option<&mut ChannelConfig> { let c = self.channels.get_mut(&id)?; if c.closed { diff --git a/crates/minimald/src/guest.rs b/crates/minimald/src/guest.rs index 0d72aba5ae..9b491d3045 100644 --- a/crates/minimald/src/guest.rs +++ b/crates/minimald/src/guest.rs @@ -96,28 +96,32 @@ fn raw_mount( } /// Enter the generic upstream guest rootfs from the initramfs. Mounts the rootfs -/// block `device` (ext4, read-only) at `newroot`, brings up the -/// pseudo-filesystems + a writable tmpfs (for session state) inside it, then -/// chroots in. minimald (static, already running) keeps executing with the -/// rootfs as its filesystem view, so `/bin/sh` and its libs resolve. The -/// `newroot/{dev,proc,sys,run}` mountpoints must exist in the rootfs (the -/// generic microvm-rootfs provides them). -pub fn enter_rootfs(device: &str, newroot: &str) -> std::io::Result<()> { - std::fs::create_dir_all(newroot)?; - raw_mount(device, newroot, "ext4", libc::MS_RDONLY)?; - raw_mount("devtmpfs", &format!("{newroot}/dev"), "devtmpfs", 0)?; - raw_mount("proc", &format!("{newroot}/proc"), "proc", 0)?; - raw_mount("sysfs", &format!("{newroot}/sys"), "sysfs", 0)?; - raw_mount("tmpfs", &format!("{newroot}/run"), "tmpfs", 0)?; +/// block `device` (ext4, read-only), brings up the pseudo-filesystems + +/// a writable tmpfs (for session state) inside it, then chroots in. +/// +/// NOTE: The rootfs at the time this function is called is expected to be the initramfs. +/// If it is instead another filesystem, then its memory will not be reclaimed. +/// +/// The `/{dev,proc,sys,run}` mountpoints must already exist on the provided rootfs +/// device. +pub fn enter_rootfs(device: &str) -> std::io::Result<()> { + const NEWROOT: &str = "/newroot"; + std::fs::create_dir_all(NEWROOT)?; + raw_mount(device, NEWROOT, "ext4", libc::MS_RDONLY)?; + raw_mount("devtmpfs", &format!("{NEWROOT}/dev"), "devtmpfs", 0)?; + raw_mount("proc", &format!("{NEWROOT}/proc"), "proc", 0)?; + raw_mount("sysfs", &format!("{NEWROOT}/sys"), "sysfs", 0)?; + raw_mount("tmpfs", &format!("{NEWROOT}/run"), "tmpfs", 0)?; let to_io = |_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "NUL in chroot path"); - let c_newroot = CString::new(newroot).map_err(to_io)?; + let c_newroot = CString::new(NEWROOT).map_err(to_io)?; // SAFETY: `chroot(2)` with a valid C string for the new root. if unsafe { libc::chroot(c_newroot.as_ptr()) } != 0 { return Err(std::io::Error::last_os_error()); } std::env::set_current_dir("/")?; - tracing::info!(device, "entered upstream rootfs (chroot)"); + + tracing::info!(device, "switched to upstream rootfs (pivot_root)"); Ok(()) } diff --git a/crates/minimald/src/main.rs b/crates/minimald/src/main.rs index bf006aa446..818f7d924d 100644 --- a/crates/minimald/src/main.rs +++ b/crates/minimald/src/main.rs @@ -10,10 +10,14 @@ use tracing_subscriber::{EnvFilter, fmt, prelude::*}; use minimald::server::{Config, HostKey, Server}; -/// Default AF_VSOCK port the guest relay listens on (the boot-contract bridge -/// port the host registers via `krun_add_vsock_port2`). #[cfg(target_os = "linux")] -const DEFAULT_VSOCK_PORT: u32 = 2222; +use tokio_vsock::{VMADDR_CID_ANY, VsockAddr, VsockListener}; + +/// Base AF_VSOCK port the guest relay listens on when in vsock mode. +/// +/// The actual port is `DEFAULT_VSOCK_PORT_BASE` + `instance_num`. +#[cfg(target_os = "linux")] +const DEFAULT_VSOCK_PORT_BASE: u32 = 2222; #[derive(Parser)] #[command(name = "minimald", version = env!("CARGO_PKG_VERSION"), long_version = env!("LONG_VERSION"))] @@ -30,7 +34,7 @@ impl Cli { /// Returns the path to the minimal-dir (base directory for state) /// based on command-line arguments. pub fn minimal_state_dir(&self) -> DaemonAbsPath { - match &self.global_args.minimal_dir { + match &self.global_args.minimal_state_dir { Some(p) => p.resolve().unwrap(), None => DaemonAbsPath::try_new( Utf8PathBuf::from_path_buf( @@ -47,27 +51,65 @@ impl Cli { /// Returns the path to base directory for caching /// based on command-line arguments. pub fn minimal_cache_dir(&self) -> DaemonAbsPath { - DaemonAbsPath::try_new( - Utf8PathBuf::from_path_buf( - dirs::cache_dir() - .unwrap_or_else(|| dirs::home_dir().unwrap().join(".local/cache")) - .join("minimal"), + match &self.global_args.minimal_cache_dir { + Some(p) => p.resolve().unwrap(), + None => DaemonAbsPath::try_new( + Utf8PathBuf::from_path_buf( + dirs::cache_dir() + .unwrap_or_else(|| dirs::home_dir().unwrap().join(".local/cache")) + .join("minimal"), + ) + .unwrap(), ) .unwrap(), - ) - .unwrap() + } + } + + fn listen_args(&self) -> Option<&ListenArgs> { + match &self.command { + Command::Run(a) => Some(a), + _ => None, + } + } + + fn instance_num(&self) -> u32 { + self.listen_args().map(|a| a.instance_num).unwrap_or(0) } /// Returns the path to the directory containing sockets/info about this daemon for clients. pub fn client_instance_dir(&self) -> DaemonAbsPath { - let instance_num = match &self.command { - Command::Run(ListenArgs { instance_num }) => *instance_num, - _ => 0, - }; + let instance_num = self.instance_num(); sub_path!(self.minimal_state_dir(), "providers") .join(&DaemonRelPath::try_new(format!("local-{instance_num}")).unwrap()) } + /// Returns fragments of the command-line arguments which should be passed to an ssh invocation in + /// order to connect to the UDS socket. + /// + /// The first argument is a list of SSH options and their values, the second is the name of + /// the ssh server. + pub fn ssh_args(&self) -> (Vec<(&'static str, String)>, String) { + ( + vec![ + ( + "ProxyCommand", + if cfg!(target_os = "macos") { + format!("nc -U {}", self.listen_on()) + } else { + format!("socat - UNIX-CONNECT:{}", self.listen_on()) + }, + ), + ( + "UserKnownHostsFile", + sub_path!(self.client_instance_dir(), "known_hosts") + .as_utf8_path() + .to_string(), + ), + ], + format!("local-{}", self.instance_num()), + ) + } + /// Returns the path to the UDS socket we should listen on. pub fn listen_on(&self) -> DaemonAbsPath { sub_path!(self.client_instance_dir(), "ssh.sock") @@ -96,9 +138,13 @@ struct CompletionsArgs { /// Shared arguments for all subcommands. #[derive(Debug, Args)] pub struct GlobalArgs { - /// Override the state directory used for operations (default: $XDG_STATE_DIR/minimal) + /// Override the directory where state is stored (default: $XDG_STATE_DIR/minimal) + #[arg(long, alias = "minimal_dir")] + minimal_state_dir: Option>, + /// Override the directory where artifacts are cached (default: $XDG_CACHE_DIR/minimal) #[arg(long)] - minimal_dir: Option>, + minimal_cache_dir: Option>, + /// Load the minimal standard library from the given path instead #[arg(long)] #[clap(hide = !std::env::var("MINIMAL_SCIENCE_MODE").is_ok())] @@ -118,12 +164,41 @@ pub struct ListenArgs { /// The SSH socket is accessible as `ssh.sock`. #[arg(long, default_value_t = 0)] instance_num: u32, + + /// Host the SSH socket over vsock instead of UDS. + /// + /// The vsock port will be `DEFAULT_VSOCK_PORT_BASE` + `instance_num`. + #[arg(long, default_value_t = false)] + vsock: bool, + + /// Mount `/dev`. Only useful if minimald is a VM's init process. + #[arg(long, default_value_t = false)] + #[clap(hide = true)] + mount_dev: bool, + + /// Mounts the given device as the rootfs and pivot to it. This also mounts + /// standard puesdo-filesystems in the / including proc, sys, dev, and run. + #[arg(long)] + #[clap(hide = true)] + mount_rootfs: Option, } /// An error at the top level of minimald. #[derive(Debug)] pub enum MainError { IO(std::io::Error, &'static str), + Other(String), +} + +impl From for MainError { + fn from(value: russh::keys::ssh_key::Error) -> Self { + Self::Other(format!("ssh key: {value}")) + } +} +impl From for MainError { + fn from(value: russh::keys::Error) -> Self { + Self::Other(format!("ssh key: {value}")) + } } fn main() -> Result<(), MainError> { @@ -148,20 +223,30 @@ async fn async_main() -> Result<(), MainError> { .with(filter) .init(); - // Run as the initramfs `/init` (pid-1 in the guest) — detect via argv[0] - // basename (the kernel appends its own cmdline tokens to init's argv, so an - // arg-count check is unreliable). Handle before clap, which requires a - // subcommand. - #[cfg(target_os = "linux")] - if std::env::args_os() - .next() - .map(|a0| std::path::Path::new(&a0).file_name() == Some(std::ffi::OsStr::new("init"))) - .unwrap_or(false) - { - return run_initramfs().await; - } - - let cli = Cli::parse(); + // Use hardcoded configuration if we are the init process (`argv[0] == "/init"`), which + // would indicate we are operating in a single-purpose micro-vm. + // + // If we are not the init process, we load our config from CLI args. + let cli = if is_minimal_microvm() { + Cli { + command: Command::Run(ListenArgs { + instance_num: 0, + vsock: true, + mount_dev: true, + mount_rootfs: Some("/dev/vda".to_string()), + }), + global_args: GlobalArgs { + minimal_state_dir: Some(DaemonAbsPath::try_new("/run/minimal").unwrap().into()), + minimal_cache_dir: Some( + DaemonAbsPath::try_new("/run/minimal/cache").unwrap().into(), + ), + num_parallel_builds: None, + stdlib_dir: None, + }, + } + } else { + Cli::parse() + }; // Handle non-{launch,run} commands. if let Command::Completions(CompletionsArgs { shell }) = cli.command { @@ -171,6 +256,24 @@ async fn async_main() -> Result<(), MainError> { return Ok(()); } + let listen_args = cli.listen_args().unwrap(); + + // Handle setup specific to operating in a micro-vm. + use minimald::guest; + if listen_args.mount_dev { + guest::mount_dev(); + } + if let Some(root_dev) = &listen_args.mount_rootfs + && let Err(e) = guest::enter_rootfs(root_dev) + { + tracing::warn!(error = %e, "no rootfs disk; initramfs READY-only"); + guest::mount_pseudo_filesystems(); + let _ = guest::emit_ready_marker().await; + loop { + tokio::time::sleep(std::time::Duration::from_secs(3600)).await; + } + } + if let Err(e) = std::fs::create_dir_all(cli.minimal_state_dir()) && e.kind() != std::io::ErrorKind::AlreadyExists { @@ -196,105 +299,59 @@ async fn async_main() -> Result<(), MainError> { minimal_state_dir: cli.minimal_state_dir(), minimal_cache_dir: cli.minimal_cache_dir(), }; + // Ensure the SSH host key is accessible in a instance-specific known_hosts file. + russh::keys::known_hosts::learn_known_hosts_path( + &format!("local-{}", cli.instance_num()), + 22, + config.host_key()?.public_key(), + sub_path!(cli.client_instance_dir(), "known_hosts").as_utf8_path(), + )?; // If we got this far we need to launch minimald. - // - // Listen on the UDS socket. - if let Err(e) = std::fs::remove_file(cli.listen_on()) - && e.kind() != std::io::ErrorKind::NotFound - { - return Err(MainError::IO(e, "socket already in use")); - } - let listener = - UnixListener::bind(cli.listen_on()).map_err(|e| MainError::IO(e, "listening to socket"))?; - tracing::info!("Started listening on {}", cli.listen_on()); - tracing::info!( - "Run the following to debug the socket:\n\nssh -o ProxyCommand='socat - UNIX-CONNECT:{}' \\\n\t-o 'StrictHostKeyChecking=no' -o 'UserKnownHostsFile=/dev/null' \\\n\tlocal", - cli.listen_on() - ); - - // TODO: When we have a daemonize command, daemonize here. - - match cli.command { - Command::Completions(_) => unreachable!(), - Command::Run(_) => Server::run_on_uds(config, listener), - } - .await - .unwrap(); - - Ok(()) -} - -/// Builds a guest server config rooted at `base` (state, cache, host key). -/// -/// `base` is the hardcoded absolute guest state root (`/run/minimal`); the path -/// newtype constructors below therefore cannot fail, so a failure is a broken -/// invariant rather than a recoverable error. -#[cfg(target_os = "linux")] -fn guest_config_at(base: &str) -> Config { - let state = DaemonAbsPath::try_new(Utf8PathBuf::from(base)) - .expect("guest state root `base` is an absolute path"); - let cache = DaemonAbsPath::try_new(Utf8PathBuf::from(format!("{base}/cache"))) - .expect("guest cache dir under an absolute `base` is an absolute path"); - let provider = sub_path!(state, "providers").join( - &DaemonRelPath::try_new("local-0".to_string()).expect("`local-0` is a valid relative path"), - ); - let host_key_path = sub_path!(provider, "ssh_host_ed25519_key"); - Config { - host_key: HostKey::OnDisk { - path: host_key_path.as_utf8_path().into(), - create_if_missing: true, - }, - minimal_state_dir: state, - minimal_cache_dir: cache, - } -} - -/// Run as the initramfs `/init` (pid-1) and serve a full session against the -/// GENERIC upstream rootfs — no minimald baked into the rootfs. -/// -/// Mounts `/dev`, then mounts the upstream rootfs (`/dev/vda`) and chroots into -/// it so the userland (`/bin/sh`, libs) resolves. Session state lives on a tmpfs -/// (`/run/minimal`) — no data disk, no `mke2fs`. Emits READY, then serves SSH -/// directly over the host-bridged AF_VSOCK port (no socat relay). Falls back to -/// READY-only + idle if there is no rootfs disk. -/// -/// Requires libkrun >= 1.19.0 on the host: 1.18.1's vsock device mis-handled -/// multi-descriptor TX chains from Linux 6.2+ guests, intermittently stalling a -/// direct session (fixed upstream by libkrun `0ecf4d5f7`). -#[cfg(target_os = "linux")] -async fn run_initramfs() -> Result<(), MainError> { - use minimald::guest; - - // /dev in the initramfs first, so /dev/vda and /dev/vsock exist. - guest::mount_dev(); - // NB: no eager `waitpid(-1)` SIGCHLD reaper — it races tokio's process - // reaping and steals exec children's exit status (ECHILD -> wrong exit code). - // tokio reaps its own children; reaping hakoniwa double-fork orphans needs a - // tokio-compatible reaper and is deferred (spec: revisit if zombies bite). - - if let Err(e) = guest::enter_rootfs("/dev/vda", "/newroot") { - tracing::warn!(error = %e, "no rootfs disk; initramfs READY-only"); - guest::mount_pseudo_filesystems(); - let _ = guest::emit_ready_marker().await; - loop { - tokio::time::sleep(std::time::Duration::from_secs(3600)).await; + if !cli.listen_args().unwrap().vsock { + // standard path, listening on UDS socket + if let Err(e) = std::fs::remove_file(cli.listen_on()) + && e.kind() != std::io::ErrorKind::NotFound + { + return Err(MainError::IO(e, "socket already in use")); } + let listener = UnixListener::bind(cli.listen_on()) + .map_err(|e| MainError::IO(e, "listening to socket"))?; + + tracing::info!("Started listening on {}", cli.listen_on()); + let (opts, ssh_name) = cli.ssh_args(); + tracing::info!( + "Run the following to debug the socket:\n\nssh \\\n\t{} \\\n\t{}", + opts.into_iter() + .map(|(n, v)| format!("-o '{n}={v}'")) + .collect::>() + .join(" \\\n\t"), + ssh_name, + ); + // TODO: When we have a daemonize command, daemonize here. + + Server::run(config, listener) + .await + .map_err(|e| MainError::IO(e, "serving on UDS")) + } else { + // micro-vm path, listen on vsock + if let Err(e) = guest::emit_ready_marker().await { + tracing::warn!(error = %e, "initramfs: READY marker failed"); + } + let port_num = DEFAULT_VSOCK_PORT_BASE + listen_args.instance_num; + let listener = VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, port_num)) + .map_err(|e| MainError::IO(e, "binding vsock port"))?; + + tracing::info!("Started listening on vsock:{port_num}"); + Server::run(config, listener) + .await + .map_err(|e| MainError::IO(e, "serving on guest vsock")) } +} - // Inside the upstream rootfs now. Session state on the tmpfs at /run/minimal. - const BASE: &str = "/run/minimal"; - std::fs::create_dir_all(format!("{BASE}/providers/local-0")) - .map_err(|e| MainError::IO(e, "creating provider dir"))?; - std::fs::create_dir_all(format!("{BASE}/cache")) - .map_err(|e| MainError::IO(e, "creating cache dir"))?; - let config = guest_config_at(BASE); - - if let Err(e) = guest::emit_ready_marker().await { - tracing::warn!(error = %e, "initramfs: READY marker failed"); - } - tracing::info!("initramfs: serving session over vsock from upstream rootfs (tmpfs state)"); - Server::run_on_vsock(config, DEFAULT_VSOCK_PORT) - .await - .map_err(|e| MainError::IO(e, "serving on guest vsock")) +fn is_minimal_microvm() -> bool { + std::env::args_os() + .next() + .map(|a0| std::path::Path::new(&a0).file_name() == Some(std::ffi::OsStr::new("init"))) + .unwrap_or(false) } diff --git a/crates/minimald/src/server.rs b/crates/minimald/src/server.rs index 589c1cb596..a2a502f99d 100644 --- a/crates/minimald/src/server.rs +++ b/crates/minimald/src/server.rs @@ -4,7 +4,8 @@ use russh::keys::{PrivateKey, ssh_key::Error as KeyError}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::sync::Arc; -use tokio::net::UnixListener; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::net::{UnixListener, UnixStream}; use tokio::sync::Mutex; use tokio::task::JoinSet; @@ -121,74 +122,95 @@ impl ServerStateHandle { } } -/// A listening minimald server. -#[derive(Debug)] -pub struct Server { - state: ServerStateHandle, - listener: UnixListener, +/// A transport that accepts byte-stream connections for the SSH server. +/// +/// The russh stack is transport-agnostic, so any listener yielding an +/// async byte stream works: a [`UnixListener`] for the native UDS daemon +/// or a [`tokio_vsock::VsockListener`] for the in-VM (pid-1) guest. +pub trait Listener: Send { + /// The accepted connection's byte stream. + type Stream: AsyncRead + AsyncWrite + Unpin + Send + 'static; + /// Peer address, used only for logging. + type Addr: std::fmt::Debug; + + /// Short transport name for log fields, e.g. `"uds"` / `"vsock"`. + const TRANSPORT: &'static str; + /// Whether peers on this transport are pre-authenticated as local + /// ([`Auth::Local`]). Both the UDS and the host-mediated vsock + /// transports are equally trusted, so both set this to `true`. + const IS_LOCAL: bool; + + fn accept(&self) -> impl Future> + Send; } -impl Server { - /// Launches minimald, listening for connections on the given UDS socket. - pub async fn run_on_uds(config: Config, listener: UnixListener) -> Result<(), std::io::Error> { - let state = ServerStateHandle::new(config).await?; - Server { state, listener }.run().await +impl Listener for UnixListener { + type Stream = UnixStream; + type Addr = tokio::net::unix::SocketAddr; + + const TRANSPORT: &'static str = "uds"; + const IS_LOCAL: bool = true; + + async fn accept(&self) -> std::io::Result<(Self::Stream, Self::Addr)> { + UnixListener::accept(self).await } +} - /// Launches minimald listening for connections directly on an AF_VSOCK port. - /// - /// Used by the in-VM (pid-1) guest: the host registers the port via - /// `krun_add_vsock_port2` and bridges client SSH connections to it. The - /// vsock peer is host-mediated (`net=none`) and as trusted as the UDS peer, - /// so accepted connections are treated as local ([`Auth::Local`]), matching - /// `run_on_uds`. Sessions are driven over the bridged vsock stream directly, - /// with no socat UDS relay in between. - /// - /// Requires libkrun >= 1.19.0: on 1.18.1 the bridged vsock intermittently - /// stalled a full session (a multi-descriptor TX-chain bug in libkrun's vsock - /// device, fixed upstream by `0ecf4d5f7`); a socat relay was the prior - /// workaround. - #[cfg(target_os = "linux")] - pub async fn run_on_vsock(config: Config, port: u32) -> Result<(), std::io::Error> { - use tokio_vsock::{VMADDR_CID_ANY, VsockAddr, VsockListener}; +/// The AF_VSOCK transport, used by the in-VM (pid-1) guest: the host +/// registers the port via `krun_add_vsock_port2` and bridges client SSH +/// connections to it. The vsock peer is host-mediated (`net=none`) and as +/// trusted as the UDS peer, so accepted connections are treated as local +/// ([`Auth::Local`]), matching the UDS transport. Sessions are driven over +/// the bridged vsock stream directly, with no socat UDS relay in between. +/// +/// Requires libkrun >= 1.19.0: on 1.18.1 the bridged vsock intermittently +/// stalled a full session (a multi-descriptor TX-chain bug in libkrun's vsock +/// device, fixed upstream by `0ecf4d5f7`); a socat relay was the prior +/// workaround. +#[cfg(target_os = "linux")] +impl Listener for tokio_vsock::VsockListener { + type Stream = tokio_vsock::VsockStream; + type Addr = tokio_vsock::VsockAddr; + + const TRANSPORT: &'static str = "vsock"; + const IS_LOCAL: bool = true; + + async fn accept(&self) -> std::io::Result<(Self::Stream, Self::Addr)> { + tokio_vsock::VsockListener::accept(self).await + } +} - let state = ServerStateHandle::new(config).await?; - let listener = VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, port))?; - tracing::info!(port, "minimald listening on vsock"); +/// A listening minimald server. +#[derive(Debug)] +pub struct Server; +impl Server { + /// Launches minimald, accepting connections on the given listener and + /// driving an SSH session over each until the listener errors. + pub async fn run(config: Config, listener: L) -> Result<(), std::io::Error> { + let state = ServerStateHandle::new(config).await?; let russh_config = build_russh_config(&state) .await .map_err(std::io::Error::other)?; let mut session_set = JoinSet::new(); + loop { - let (stream, peer) = listener.accept().await?; - tracing::info!(?peer, "accepted vsock connection"); - let (_conn_hnd, session_fut) = - Connection::from_stream(stream, russh_config.clone(), state.clone(), true).await; - // Log session errors instead of silently dropping the spawned - // future, so a failed handshake on the vsock transport is visible. - session_set.spawn(async move { - if let Err(e) = session_fut.await { - tracing::warn!(error = %e, "vsock session ended with error"); + // Drain any completed sessions to prevent unbounded growth. + while let Some(result) = session_set.try_join_next() { + if let Err(e) = result { + tracing::error!(error = %e, "session task panicked"); } - }); - } - } + } - async fn run(self) -> Result<(), std::io::Error> { - let russh_config = build_russh_config(&self.state) - .await - .map_err(std::io::Error::other)?; - let mut session_set = JoinSet::new(); - loop { - let (socket, _) = self.listener.accept().await?; - tracing::info!("accepted UDS connection"); + let (stream, peer) = listener.accept().await?; + tracing::info!(?peer, transport = L::TRANSPORT, "accepted connection"); let (_conn_hnd, session_fut) = - Connection::from_socket(socket, russh_config.clone(), self.state.clone(), true) + Connection::from_stream(stream, russh_config.clone(), state.clone(), L::IS_LOCAL) .await; + // Log session errors instead of silently dropping the spawned + // future, so a failed handshake is visible on any transport. session_set.spawn(async move { if let Err(e) = session_fut.await { - tracing::warn!(error = %e, "session ended with error"); + tracing::warn!(error = %e, transport = L::TRANSPORT, "session ended with error"); } }); } diff --git a/crates/minimald/src/test_harness.rs b/crates/minimald/src/test_harness.rs index 1f14a392e9..ef9b7b4477 100644 --- a/crates/minimald/src/test_harness.rs +++ b/crates/minimald/src/test_harness.rs @@ -92,7 +92,7 @@ impl TestServer { let state = self.state.clone(); let server_setup = async move { let (_conn, session_fut) = - Connection::from_socket(server_side, russh_config, state, true).await; + Connection::from_stream(server_side, russh_config, state, true).await; tokio::spawn(session_fut); }; @@ -122,7 +122,7 @@ impl TestServer { let state = state.clone(); tokio::spawn(async move { let (_conn, session_fut) = - Connection::from_socket(socket, russh_config, state, true).await; + Connection::from_stream(socket, russh_config, state, true).await; let _ = session_fut.await; }); } diff --git a/crates/paths/src/lib.rs b/crates/paths/src/lib.rs index e3045f5fa4..24f6669bd5 100644 --- a/crates/paths/src/lib.rs +++ b/crates/paths/src/lib.rs @@ -959,6 +959,12 @@ impl FromStr for CwdRelative { } } +impl From> for CwdRelative { + fn from(value: AbsPath) -> Self { + Self(EitherPath::Abs(value)) + } +} + impl Clone for CwdRelative { fn clone(&self) -> Self { Self(self.0.clone())