The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(mounts): deliver directory FDs and guest mount operations (#3028)
Vitus696a1fd0a5aa
diff --git a/docs/contributing/architecture/vmm/README.md b/docs/contributing/architecture/vmm/README.mdindex cb0ba9e29..9ffa28088 100644--- a/docs/contributing/architecture/vmm/README.md+++ b/docs/contributing/architecture/vmm/README.md@@ -554,10 +554,11 @@ logged.attach order (`vda` container, `vdb` guest root), and defaults to `console=hvc0`.The single filesystem device exports logical shares below its aggregate root;matching mount instructions are sent only for the native engine.-- **Runtime control.** The runtime sends `resize_disk` to the native shim over- the host-only `vmm.sock`, which stays open across transient accept errors.- The shim routes requests by `block_id` through- [`VmControl`](../../../../src/vmm/README.md#virtio-block-device).+- **Runtime control.** The host-only `vmm.sock` handles disk resize and+ [directory delivery](../../../../src/vmm/README.md#host-directory-delivery)+ through a serial control thread. The shim routes resize requests by `block_id`+ through [`VmControl`](../../../../src/vmm/README.md#virtio-block-device).+ The `box.sock` listener forwards guest RPCs, including Mount and Detach.- **File size limits.** The VMM bounds guest I/O by virtual disk capacity.The host kernel enforces the shim's configured or inherited[`RLIMIT_FSIZE` soft limit](../../../../src/boxlite/src/jailer/README.md#layer-3-resource-limits).diff --git a/make/test.mk b/make/test.mkindex f28ab3335..bb76658d9 100644--- a/make/test.mk+++ b/make/test.mk@@ -372,6 +372,13 @@ test\:integration\:vmm\:native: _ensure-kvm _ensure-vmm-kernel $(if $(SETUP_DONE@timeout 300s cargo test -p boxlite --features native --lib vmm::native::tests:: -- --ignored --test-threads=1@timeout 600s cargo test -p boxlite --features krun,gvproxy,native --test native_vmm -- --ignored --test-threads=1+# PR2 primitives: descriptor registration, guest RPC attach/detach, and reference lifetime.+PHONY_TARGETS += test\:integration\:vmm\:mount-delivery+test\:integration\:vmm\:mount-delivery: export BOXLITE_TEST_ENGINE := native+test\:integration\:vmm\:mount-delivery: _ensure-kvm _ensure-vmm-kernel $(if $(SETUP_DONE),,runtime\:debug)+ @cargo test -p boxlite --features native --test native_mount_delivery --no-run+ @timeout 180s cargo test -p boxlite --features native --test native_mount_delivery -- --ignored --test-threads=1 --nocapture+# A host without Hypervisor.framework must fail HVF qualification, not report skipped tests as a pass._ensure-hvf:@test "$$(uname -s -m)" = "Darwin arm64" || { echo "macOS arm64 is required" >&2; exit 1; }diff --git a/src/boxlite/src/litebox/box_impl.rs b/src/boxlite/src/litebox/box_impl.rsindex 61f1a97e1..b146af949 100644--- a/src/boxlite/src/litebox/box_impl.rs+++ b/src/boxlite/src/litebox/box_impl.rs@@ -2080,6 +2080,13 @@ mod tests {) -> Result<Response<boxlite_shared::ContainerMountResponse>, Status> {Err(Status::unimplemented("not used by these tests"))}++ async fn detach(+ &self,+ _: Request<boxlite_shared::ContainerDetachRequest>,+ ) -> Result<Response<boxlite_shared::ContainerDetachResponse>, Status> {+ Err(Status::unimplemented("not used by these tests"))+ }}#[derive(Default)]diff --git a/src/boxlite/src/litebox/init/tasks/guest_init.rs b/src/boxlite/src/litebox/init/tasks/guest_init.rsindex a05996a29..44e3b25bd 100644--- a/src/boxlite/src/litebox/init/tasks/guest_init.rs+++ b/src/boxlite/src/litebox/init/tasks/guest_init.rs@@ -397,6 +397,14 @@ mod tests {{Err(tonic::Status::unimplemented("not used by these tests"))}++ async fn detach(+ &self,+ _: tonic::Request<boxlite_shared::ContainerDetachRequest>,+ ) -> Result<tonic::Response<boxlite_shared::ContainerDetachResponse>, tonic::Status>+ {+ Err(tonic::Status::unimplemented("not used by these tests"))+ }}fn bootstrap_for_version_gate() -> GuestBootstrapConfig {diff --git a/src/boxlite/src/litebox/ssh_tests.rs b/src/boxlite/src/litebox/ssh_tests.rsindex b324f89c6..7895aa8cd 100644--- a/src/boxlite/src/litebox/ssh_tests.rs+++ b/src/boxlite/src/litebox/ssh_tests.rs@@ -117,6 +117,13 @@ impl proto::Container for MockService {) -> Result<Response<proto::ContainerMountResponse>, Status> {Err(Status::unimplemented("not used by these tests"))}++ async fn detach(+ &self,+ _: Request<proto::ContainerDetachRequest>,+ ) -> Result<Response<proto::ContainerDetachResponse>, Status> {+ Err(Status::unimplemented("not used by these tests"))+ }}struct TestHandler;diff --git a/src/boxlite/src/portal/interfaces/container.rs b/src/boxlite/src/portal/interfaces/container.rsindex 4066cec4f..488d0d9db 100644--- a/src/boxlite/src/portal/interfaces/container.rs+++ b/src/boxlite/src/portal/interfaces/container.rs@@ -324,10 +324,60 @@ impl ContainerInterface {source: source.to_string(),destination: destination.to_string(),read_only: true,+ // Legacy share delivery only; aggregate delivery carries+ // export_key and device_tag (M6 runtime coordination).+ export_key: String::new(),+ device_tag: String::new(),}).await?;Ok(())}++ /// M6 aggregate delivery: bind the export `export_key` beneath the+ /// aggregate root of `device_tag` at `destination` in the running+ /// container. `read_only` gates the guest bind mode; content policy+ /// stays with the host backend.+ pub async fn mount_aggregate(+ &mut self,+ container_id: &str,+ export_key: &str,+ device_tag: &str,+ destination: &str,+ read_only: bool,+ ) -> BoxliteResult<()> {+ self.client+ .mount(boxlite_shared::ContainerMountRequest {+ container_id: container_id.to_string(),+ source: String::new(),+ destination: destination.to_string(),+ read_only,+ export_key: export_key.to_string(),+ device_tag: device_tag.to_string(),+ })+ .await+ .map_err(map_mount_status)?;+ Ok(())+ }++ /// Lazily detach the runtime mount at `destination`: the destination+ /// leaves the container mount table while descriptors opened before the+ /// detach keep working.+ pub async fn detach(+ &mut self,+ container_id: &str,+ destination: &str,+ export_key: &str,+ ) -> BoxliteResult<()> {+ self.client+ .detach(boxlite_shared::ContainerDetachRequest {+ container_id: container_id.to_string(),+ destination: destination.to_string(),+ export_key: export_key.to_string(),+ })+ .await+ .map_err(map_mount_status)?;+ Ok(())+ }}fn map_container_init_status(status: tonic::Status) -> BoxliteError {@@ -337,6 +387,13 @@ fn map_container_init_status(status: tonic::Status) -> BoxliteError {status.into()}+fn map_mount_status(status: tonic::Status) -> BoxliteError {+ if status.code() == tonic::Code::Unimplemented {+ return BoxliteError::Unsupported(status.message().to_owned());+ }+ status.into()+}+#[cfg(test)]mod tests {use super::*;@@ -350,6 +407,18 @@ mod tests {use tonic::transport::{Endpoint, Server};use tonic::{Request, Response, Status};+ #[test]+ fn unsupported_mounts_preserve_the_capability_error_category() {+ assert!(+ matches!(map_mount_status(tonic::Status::unimplemented("CAP_SYS_ADMIN")),+ BoxliteError::Unsupported(message) if message == "CAP_SYS_ADMIN")+ );+ assert!(matches!(+ map_mount_status(tonic::Status::unavailable("guest disconnected")),+ BoxliteError::Rpc(_)+ ));+ }+#[test]fn container_init_preserves_invalid_argument_status() {let error = map_container_init_status(Status::invalid_argument(@@ -377,6 +446,8 @@ mod tests {init_error: Option<ContainerInitErrorKind>,/// Last `Container.Init` request the stub saw, for wire assertions.seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,+ seen_mounts: Arc<Mutex<Vec<boxlite_shared::ContainerMountRequest>>>,+ seen_detaches: Arc<Mutex<Vec<boxlite_shared::ContainerDetachRequest>>>,}#[tonic::async_trait]@@ -421,9 +492,20 @@ mod tests {async fn mount(&self,- _: Request<boxlite_shared::ContainerMountRequest>,+ request: Request<boxlite_shared::ContainerMountRequest>,) -> Result<Response<boxlite_shared::ContainerMountResponse>, Status> {- Err(Status::unimplemented("not used by these tests"))+ self.seen_mounts.lock().unwrap().push(request.into_inner());+ Ok(Response::new(boxlite_shared::ContainerMountResponse {}))+ }+ async fn detach(+ &self,+ request: Request<boxlite_shared::ContainerDetachRequest>,+ ) -> Result<Response<boxlite_shared::ContainerDetachResponse>, Status> {+ self.seen_detaches+ .lock()+ .unwrap()+ .push(request.into_inner());+ Ok(Response::new(boxlite_shared::ContainerDetachResponse {}))}}@@ -437,6 +519,23 @@ mod tests {start_reply: StartReply,init_error: Option<ContainerInitErrorKind>,seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,+ ) -> ContainerInterface {+ interface_delivering(+ start_reply,+ init_error,+ seen_init,+ Arc::default(),+ Arc::default(),+ )+ .await+ }++ async fn interface_delivering(+ start_reply: StartReply,+ init_error: Option<ContainerInitErrorKind>,+ seen_init: Arc<Mutex<Option<ContainerInitRequest>>>,+ seen_mounts: Arc<Mutex<Vec<boxlite_shared::ContainerMountRequest>>>,+ seen_detaches: Arc<Mutex<Vec<boxlite_shared::ContainerDetachRequest>>>,) -> ContainerInterface {// Bind with std to learn a free port, then hand the address to tonic.let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();@@ -449,6 +548,8 @@ mod tests {start_reply,init_error,seen_init,+ seen_mounts,+ seen_detaches,})).serve(addr).await@@ -473,6 +574,47 @@ mod tests {ContainerInterface::new(channel)}+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn delivery_requests_preserve_incarnation_modes_and_legacy_source_on_wire() {+ let mounts = Arc::new(Mutex::new(Vec::new()));+ let detaches = Arc::new(Mutex::new(Vec::new()));+ let mut iface = interface_delivering(+ StartReply::Success,+ None,+ Arc::default(),+ Arc::clone(&mounts),+ Arc::clone(&detaches),+ )+ .await;+ iface.mount("box", "agents", "/opt/agents").await.unwrap();+ for read_only in [false, true] {+ iface+ .mount_aggregate("box", "export-42", "boxlite", "/data", read_only)+ .await+ .unwrap();+ }+ iface.detach("box", "/data", "export-42").await.unwrap();+ let mounts = mounts.lock().unwrap();+ assert_eq!(mounts.len(), 3);+ assert_eq!(mounts[0].source, "agents");+ assert!(mounts[0].read_only);+ assert!(mounts[0].export_key.is_empty());+ assert!(mounts[0].device_tag.is_empty());+ for (request, read_only) in mounts[1..].iter().zip([false, true]) {+ assert_eq!(request.container_id, "box");+ assert!(request.source.is_empty());+ assert_eq!(request.export_key, "export-42");+ assert_eq!(request.device_tag, "boxlite");+ assert_eq!(request.destination, "/data");+ assert_eq!(request.read_only, read_only);+ }+ let detaches = detaches.lock().unwrap();+ assert_eq!(detaches.len(), 1);+ assert_eq!(detaches[0].container_id, "box");+ assert_eq!(detaches[0].destination, "/data");+ assert_eq!(detaches[0].export_key, "export-42");+ }+/// #988 regression: a guest agent that predates `Container.Start` answers/// with gRPC `Unimplemented`. Its fused `Container.Init` already started the/// container, so the host must treat the missing method as "already started"diff --git a/src/boxlite/src/vmm/controller/mod.rs b/src/boxlite/src/vmm/controller/mod.rsindex b9e648b1a..48a293ffe 100644--- a/src/boxlite/src/vmm/controller/mod.rs+++ b/src/boxlite/src/vmm/controller/mod.rs@@ -15,6 +15,8 @@//! - Caller-controlled GuestSession creationmod handler;+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub mod mount_control;mod shim;mod spawn;pub mod watchdog;diff --git a/src/boxlite/src/vmm/controller/mount_control.rs b/src/boxlite/src/vmm/controller/mount_control.rsnew file mode 100644index 000000000..b04072633--- /dev/null+++ b/src/boxlite/src/vmm/controller/mount_control.rs@@ -0,0 +1,118 @@+//! Host directory delivery to a single VM through its `vmm.sock`.+//!+//! Registration publishes `Preparing` before replying. A lost reply can be+//! reconciled with `list`. The caller owns guest acknowledgment and recovery.++use crate::vmm::vmm_socket::{self, ControlError, ControlOp, ControlReply};+use serde::{Deserialize, Serialize};+use std::fs::File;+use std::io;+use std::path::PathBuf;+use std::time::Duration;++mod registry;+pub(crate) use registry::Registry;++// Include time queued behind an online disk resize in the exchange budget.+const CONTROL_TIMEOUT: Duration = Duration::from_secs(15);++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum MountState {+ Preparing,+ Mounted,+ Detaching,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ControlMount {+ pub export: String,+ pub source: String,+ pub target: String,+ pub read_only: bool,+ pub state: MountState,+}++/// Blocking client. Each operation opens a connection for one exchange.+/// Call from `spawn_blocking` when using an async executor.+pub struct MountControlClient {+ path: PathBuf,+}++impl MountControlClient {+ pub fn new(path: impl Into<PathBuf>) -> Self {+ Self { path: path.into() }+ }++ fn exchange(&self, op: ControlOp, directory: Option<&File>) -> io::Result<ControlReply> {+ match vmm_socket::exchange(&self.path, op, directory, CONTROL_TIMEOUT)? {+ Ok(reply) => Ok(reply),+ Err(ControlError::Mount(errno)) => Err(io::Error::from_raw_os_error(errno)),+ Err(ControlError::Unsupported(message)) => {+ Err(io::Error::new(io::ErrorKind::Unsupported, message))+ }+ Err(ControlError::InvalidInput(message)) => {+ Err(io::Error::new(io::ErrorKind::InvalidInput, message))+ }+ Err(error) => Err(io::Error::other(error)),+ }+ }++ pub fn register(+ &self,+ source: String,+ target: String,+ file: File,+ read_only: bool,+ ) -> io::Result<ControlMount> {+ match self.exchange(+ ControlOp::RegisterMount {+ source,+ target,+ read_only,+ },+ Some(&file),+ )? {+ ControlReply::MountRegistered(mount) => Ok(mount),+ _ => Err(unexpected_reply()),+ }+ }++ pub fn list(&self) -> io::Result<Vec<ControlMount>> {+ match self.exchange(ControlOp::ListMounts, None)? {+ ControlReply::Mounts(mounts) => Ok(mounts),+ _ => Err(unexpected_reply()),+ }+ }++ pub fn set_state(&self, export: &str, state: MountState) -> io::Result<()> {+ match self.exchange(+ ControlOp::SetMountState {+ export: export.into(),+ state,+ },+ None,+ )? {+ ControlReply::MountUpdated => Ok(()),+ _ => Err(unexpected_reply()),+ }+ }++ pub fn remove(&self, export: &str) -> io::Result<()> {+ match self.exchange(+ ControlOp::RemoveMount {+ export: export.into(),+ },+ None,+ )? {+ ControlReply::MountUpdated => Ok(()),+ _ => Err(unexpected_reply()),+ }+ }+}++fn unexpected_reply() -> io::Error {+ io::Error::new(+ io::ErrorKind::InvalidData,+ "unexpected mount control response",+ )+}diff --git a/src/boxlite/src/vmm/controller/mount_control/registry.rs b/src/boxlite/src/vmm/controller/mount_control/registry.rsnew file mode 100644index 000000000..5b18f9c75--- /dev/null+++ b/src/boxlite/src/vmm/controller/mount_control/registry.rs@@ -0,0 +1,144 @@+use super::{ControlMount, MountState};+use crate::vmm::vmm_socket::{ControlOp, ControlReply, MAX_FRAME};+use boxlite_vmm::lookup_aggregate;+use std::fs::File;+use std::io;+use std::path::{Component, Path};++/// Maximum length in bytes of a source or target path in a mount request.+const MAX_PATH_BYTES: usize = 4096;++#[derive(Default)]+pub(crate) struct Registry {+ next: u64,+ mounts: Vec<ControlMount>,+ list_bytes: usize,+}++fn errno(code: i32) -> io::Error {+ io::Error::from_raw_os_error(code)+}++fn record_cost(mount: &ControlMount) -> io::Result<usize> {+ struct Counter(usize);+ impl io::Write for Counter {+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {+ self.0 += bytes.len();+ Ok(bytes.len())+ }+ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+ }+ let mut counter = Counter(0);+ serde_json::to_writer(&mut counter, mount)?;+ // Reserve a comma per record (one extra is harmless). `Preparing` is as+ // long as the record ever serializes: `Detaching` matches it, `Mounted` is shorter.+ Ok(counter.0 + 1)+}++fn normalize_target(target: &str) -> io::Result<String> {+ if target.len() > MAX_PATH_BYTES || target.contains('\0') || !target.starts_with('/') {+ return Err(errno(libc::EINVAL));+ }+ let mut components = Vec::new();+ for component in Path::new(target).components() {+ match component {+ Component::RootDir | Component::CurDir => (),+ Component::Normal(name) => {+ components.push(name.to_str().ok_or_else(|| errno(libc::EINVAL))?)+ }+ _ => return Err(errno(libc::EINVAL)),+ }+ }+ if components.is_empty() {+ return Err(errno(libc::EINVAL));+ }+ Ok(format!("/{}", components.join("/")))+}++impl Registry {+ pub(crate) fn request(+ &mut self,+ tag: &str,+ request: ControlOp,+ directory: Option<File>,+ ) -> io::Result<ControlReply> {+ let filesystem = lookup_aggregate(tag)?;+ match request {+ ControlOp::RegisterMount {+ source,+ target,+ read_only,+ } => {+ let directory = directory.ok_or_else(|| errno(libc::EINVAL))?;+ if source.is_empty() || source.len() > MAX_PATH_BYTES || source.contains('\0') {+ return Err(errno(libc::EINVAL));+ }+ let target = normalize_target(&target)?;+ if self.mounts.iter().any(|mount| mount.target == target) {+ return Err(errno(libc::EBUSY));+ }+ let next = self+ .next+ .checked_add(1)+ .ok_or_else(|| errno(libc::EOVERFLOW))?;+ let mount = ControlMount {+ export: format!("mount-{next}"),+ source,+ target,+ read_only,+ state: MountState::Preparing,+ };+ // Empty List envelope plus worst-case serialized records; the+ // counter includes JSON escaping without copying existing records.+ let cost = record_cost(&mount)?;+ let envelope = br#"{"Ok":{"mounts":[]}}"#.len();+ if self.list_bytes + cost + envelope > MAX_FRAME as usize {+ return Err(errno(libc::ENOSPC));+ }+ // Reserve memory before publication so the remaining record insertion+ // cannot fail after register_fd has taken ownership.+ self.mounts+ .try_reserve(1)+ .map_err(|_| errno(libc::ENOMEM))?;+ self.next = next;+ filesystem.register_fd(mount.export.clone(), directory, read_only)?;+ self.mounts.push(mount.clone());+ self.list_bytes += cost;+ Ok(ControlReply::MountRegistered(mount))+ }+ ControlOp::ListMounts => Ok(ControlReply::Mounts(self.mounts.clone())),+ ControlOp::SetMountState { export, state } => {+ let mount = self+ .mounts+ .iter_mut()+ .find(|mount| mount.export == export)+ .ok_or_else(|| errno(libc::ENOENT))?;+ match (mount.state, state) {+ (current, requested) if current == requested => (),+ (MountState::Preparing, MountState::Mounted | MountState::Detaching)+ | (MountState::Mounted, MountState::Detaching) => mount.state = state,+ _ => return Err(errno(libc::EINVAL)),+ }+ Ok(ControlReply::MountUpdated)+ }+ ControlOp::RemoveMount { export } => {+ let index = self+ .mounts+ .iter()+ .position(|mount| mount.export == export)+ .ok_or_else(|| errno(libc::ENOENT))?;+ if self.mounts[index].state != MountState::Detaching {+ return Err(errno(libc::EBUSY));+ }+ let cost = record_cost(&self.mounts[index])?;+ filesystem.remove(&export)?;+ self.mounts.remove(index);+ self.list_bytes -= cost;+ Ok(ControlReply::MountUpdated)+ }+ ControlOp::ResizeDisk { .. } => unreachable!("disk resize is dispatched by the VMM"),+ }+ }+}diff --git a/src/boxlite/src/vmm/native/engine.rs b/src/boxlite/src/vmm/native/engine.rsindex c548f8052..1e12983d7 100644--- a/src/boxlite/src/vmm/native/engine.rs+++ b/src/boxlite/src/vmm/native/engine.rs@@ -8,6 +8,7 @@ use std::{fs::File, io, path::PathBuf, time::Duration};use crate::experimental::custom_kernel::KernelFormat;use crate::rootfs::guest::Strategy;use crate::runtime::constants::vm_defaults::{DEFAULT_CPUS, DEFAULT_MEMORY_MIB};+use crate::vmm::controller::mount_control::Registry;use crate::vmm::vmm_socket::{self, ControlError, ControlOp, ControlReply, ControlResponse};use crate::vmm::{DiskFormat, InstanceSpec, Vmm, VmmConfig, VmmInstance, VmmKind, engine::VmmInstanceImpl,@@ -52,11 +53,11 @@ impl VmmInstanceImpl for NativeVmmInstance {})?),None => Box::new(io::sink()),};+ let mut mounts = self.config.vsock.is_some().then(Registry::default);let mut vm = Vm::new(self.config, sink).map_err(map_vmm_error)?;let vm_control = vm.control();- // Without the channel the box still runs; it only cannot grow online.- if let Err(error) = vmm_socket::serve(&self.vmm_socket_path, move |op| {- handle_control_op(&vm_control, op)+ if let Err(error) = vmm_socket::serve(&self.vmm_socket_path, move |op, directory| {+ handle_control_op(&vm_control, mounts.as_mut(), op, directory)}) {tracing::warn!(%error,@@ -73,8 +74,13 @@ impl VmmInstanceImpl for NativeVmmInstance {/// How long a grow may wait for the block device's worker.const GROW_TIMEOUT: Duration = Duration::from_secs(10);-/// Serves one control operation against the VM's disks.-pub(crate) fn handle_control_op(vm: &VmControl, op: ControlOp) -> ControlResponse {+/// Serves host requests against this VM and its mount records.+fn handle_control_op(+ vm: &VmControl,+ mounts: Option<&mut Registry>,+ op: ControlOp,+ directory: Option<File>,+) -> ControlResponse {match op {ControlOp::ResizeDisk { block_id, bytes } => vm.resize_disk(&block_id, bytes, GROW_TIMEOUT)@@ -85,6 +91,14 @@ pub(crate) fn handle_control_op(vm: &VmControl, op: ControlOp) -> ControlRespons}_ => ControlError::Failed(error.to_string()),}),+ op => mounts+ .ok_or_else(|| ControlError::Unsupported("guest transport is unavailable".into()))?+ .request(+ boxlite_shared::constants::mount_tags::AGGREGATE,+ op,+ directory,+ )+ .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap_or(libc::EIO))),}}@@ -155,7 +169,7 @@ pub(crate) fn build_config(spec: &InstanceSpec) -> BoxliteResult<VmConfig> {cmdline: build_cmdline(spec, kernel.command_line.as_deref()),initramfs: kernel.initramfs.clone(),disks,- filesystem: (!spec.fs_shares.shares().is_empty()).then(|| FsConfig {+ filesystem: Some(FsConfig {tag: boxlite_shared::constants::mount_tags::AGGREGATE.into(),shares: spec.fs_sharesdiff --git a/src/boxlite/src/vmm/native/tests/mod.rs b/src/boxlite/src/vmm/native/tests/mod.rsindex c2d5e32a0..021d971a7 100644--- a/src/boxlite/src/vmm/native/tests/mod.rs+++ b/src/boxlite/src/vmm/native/tests/mod.rs@@ -271,11 +271,11 @@ fn shares_network_and_the_agent_bridge_reach_the_vm_config() {}#[test]-fn optional_devices_stay_absent_and_non_unix_agent_bridges_are_rejected() {+fn empty_aggregate_accepts_later_delivery_and_non_unix_agent_bridges_are_rejected() {let test_box = TestBox::new();let kernel = test_box.stage_kernel(&fake_kernel(), None);let config = build_config(&test_box.spec(Some(kernel.clone()))).unwrap();- assert!(config.filesystem.is_none());+ assert!(config.filesystem.unwrap().shares.is_empty());assert!(config.vsock.is_none());assert!(config.network.is_none());let mut spec = runtime_like_spec(&test_box, Some(kernel));diff --git a/src/boxlite/src/vmm/tests/vmm_socket.rs b/src/boxlite/src/vmm/tests/vmm_socket.rsindex e4ee9d85a..399c24d4a 100644--- a/src/boxlite/src/vmm/tests/vmm_socket.rs+++ b/src/boxlite/src/vmm/tests/vmm_socket.rs@@ -15,13 +15,15 @@ fn grow_to(block_id: &str, bytes: u64) -> ControlRequest {fn a_request_reaches_the_handler_and_its_answer_returns() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |op| match op {+ serve(&path, |op, _| match op {ControlOp::ResizeDisk { block_id, bytes } if block_id == "container" => {Ok(ControlReply::DiskSize(bytes))}ControlOp::ResizeDisk { block_id, .. } => {Err(ControlError::InvalidInput(format!("no disk {block_id}")))}+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ _ => panic!("expected a resize request"),}).unwrap();let mode = std::fs::metadata(&path).unwrap().permissions().mode();@@ -70,7 +72,13 @@ fn accept_recovers_from_temporary_errors_with_bounded_backoff() {let mut waits = Vec::new();serve_connections(incoming,- |ControlOp::ResizeDisk { bytes, .. }| Ok(ControlReply::DiskSize(bytes)),+ // SAFETY: `geteuid` has no preconditions.+ unsafe { libc::geteuid() },+ |op, _| match op {+ ControlOp::ResizeDisk { bytes, .. } => Ok(ControlReply::DiskSize(bytes)),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ _ => panic!("expected a resize request"),+ },|delay| waits.push(delay),);@@ -84,7 +92,7 @@ fn accept_recovers_from_temporary_errors_with_bounded_backoff() {fn another_version_is_unsupported_and_the_shim_keeps_serving() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |_| Ok(ControlReply::DiskSize(1))).unwrap();+ serve(&path, |_, _| Ok(ControlReply::DiskSize(1))).unwrap();let timeout = Duration::from_secs(5);let mut future = grow_to("container", 512);future.version = VERSION + 1;@@ -102,7 +110,7 @@ fn another_version_is_unsupported_and_the_shim_keeps_serving() {fn an_oversized_or_unknown_request_is_bounded() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |_| Ok(ControlReply::DiskSize(1))).unwrap();+ serve(&path, |_, _| Ok(ControlReply::DiskSize(1))).unwrap();// An oversized frame ends the connection without a reply.let mut stream = UnixStream::connect(&path).unwrap();@@ -118,8 +126,9 @@ fn an_oversized_or_unknown_request_is_bounded() {serde_json::from_slice(&read_frame(&mut stream).unwrap()).unwrap();assert!(matches!(response, Err(ControlError::InvalidInput(_))));- // A client that never sends is dropped after the timeout; serving goes on.- let _silent = UnixStream::connect(&path).unwrap();+ // A partial header times out, and the next connection is accepted.+ let mut partial = UnixStream::connect(&path).unwrap();+ partial.write_all(&[1, 0]).unwrap();assert_eq!(request(&path, &grow_to("container", 512), Duration::from_secs(5)).unwrap(),Ok(ControlReply::DiskSize(1))@@ -131,7 +140,7 @@ fn serving_replaces_a_stale_socket() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");drop(UnixListener::bind(&path).unwrap());- serve(&path, |_| Ok(ControlReply::DiskSize(7))).unwrap();+ serve(&path, |_, _| Ok(ControlReply::DiskSize(7))).unwrap();assert_eq!(request(&path, &grow_to("container", 7), Duration::from_secs(5)).unwrap(),Ok(ControlReply::DiskSize(7))@@ -142,7 +151,7 @@ fn serving_replaces_a_stale_socket() {fn resize_requires_a_block_id_and_rejects_index_only_requests() {let dir = tempfile::tempdir().unwrap();let path = dir.path().join("vmm.sock");- serve(&path, |_| {+ serve(&path, |_, _| {panic!("invalid requests must not reach the handler")}).unwrap();@@ -160,3 +169,238 @@ fn resize_requires_a_block_id_and_rejects_index_only_requests() {assert!(matches!(response, Err(ControlError::InvalidInput(_))));}}++#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+mod mounts {+ use super::*;+ use crate::vmm::controller::mount_control::{MountControlClient, MountState, Registry};+ use boxlite_vmm::AggregateFs;+ use std::os::fd::AsRawFd;+ use std::path::PathBuf;+ use std::sync::Arc;++ const TIMEOUT: Duration = Duration::from_secs(5);++ fn fixture() -> (tempfile::TempDir, Arc<AggregateFs>, PathBuf) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let tag = dir.path().to_str().unwrap().to_owned();+ let fs = Arc::new(AggregateFs::new(vec![]).unwrap());+ boxlite_vmm::insert_aggregate(&tag, fs.clone());+ let mut registry = Registry::default();+ serve(&path, move |op, directory| {+ registry+ .request(&tag, op, directory)+ .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap()))+ })+ .unwrap();+ (dir, fs, path)+ }++ fn registration(target: &str) -> ControlOp {+ ControlOp::RegisterMount {+ source: "/source".into(),+ target: target.into(),+ read_only: false,+ }+ }++ #[test]+ fn fragmented_directory_delivery_survives_an_unread_reply() {+ let (dir, _fs, path) = fixture();+ let directory = File::open(dir.path()).unwrap();+ let mut stream = UnixStream::connect(&path).unwrap();+ stream.set_read_timeout(Some(TIMEOUT)).unwrap();+ let frame = serde_json::to_vec(&ControlRequest {+ version: VERSION,+ op: registration("/data"),+ })+ .unwrap();+ let header = (frame.len() as u32).to_le_bytes();+ stream.write_all(&header[..2]).unwrap();+ transport::send_parts(+ &stream,+ &header[2..],+ &frame[..1],+ Some(directory.as_raw_fd()),+ Instant::now() + TIMEOUT,+ )+ .unwrap();+ stream.write_all(&frame[1..]).unwrap();+ stream.read_exact(&mut [0]).unwrap();+ drop(stream);++ let client = MountControlClient::new(path);+ let records = client.list().unwrap();+ let [mount] = records.as_slice() else {+ panic!("expected one recoverable registration, got {records:?}");+ };+ assert_eq!(mount.target, "/data");+ assert_eq!(mount.state, MountState::Preparing);+ client+ .set_state(&mount.export, MountState::Mounted)+ .unwrap();+ assert_eq!(client.list().unwrap()[0].state, MountState::Mounted);+ client+ .set_state(&mount.export, MountState::Detaching)+ .unwrap();+ client.remove(&mount.export).unwrap();+ assert!(client.list().unwrap().is_empty());+ }++ #[test]+ fn invalid_descriptors_do_not_publish_a_mount() {+ let (dir, _fs, path) = fixture();+ let directory = File::open(dir.path()).unwrap();+ assert_eq!(+ exchange(&path, registration("/data"), None, TIMEOUT).unwrap(),+ Err(ControlError::Mount(libc::EINVAL))+ );+ assert_eq!(+ exchange(&path, ControlOp::ListMounts, Some(&directory), TIMEOUT).unwrap(),+ Err(ControlError::Mount(libc::EINVAL))+ );+ let file = tempfile::tempfile().unwrap();+ assert_eq!(+ exchange(&path, registration("/data"), Some(&file), TIMEOUT).unwrap(),+ Err(ControlError::Mount(libc::ENOTDIR))+ );+ let frame = serde_json::to_vec(&ControlRequest {+ version: VERSION,+ op: registration("/data"),+ })+ .unwrap();+ let stream = UnixStream::connect(&path).unwrap();+ let end = Instant::now() + TIMEOUT;+ let descriptor = Some(directory.as_raw_fd());+ transport::send_parts(+ &stream,+ &(frame.len() as u32).to_le_bytes(),+ &[],+ descriptor,+ end,+ )+ .unwrap();+ transport::send_parts(&stream, &frame, &[], descriptor, end).unwrap();+ // Closing the malformed exchange must still leave the listener usable.+ assert_eq!(+ transport::receive_frame(&stream, end).unwrap_err().kind(),+ io::ErrorKind::UnexpectedEof+ );+ let client = MountControlClient::new(path);+ assert!(client.list().unwrap().is_empty());+ client+ .register("/source".into(), "/data".into(), directory, false)+ .unwrap();+ }++ #[test]+ fn mount_list_fits_after_registration_reaches_capacity() {+ let (dir, _fs, path) = fixture();+ let client = MountControlClient::new(path);+ let mut admitted = 0;+ loop {+ let result = client.register(+ "\\".repeat(2000),+ format!("/{admitted}{}", "\"".repeat(2000)),+ File::open(dir.path()).unwrap(),+ true,+ );+ match result {+ Ok(mount) => {+ client+ .set_state(&mount.export, MountState::Mounted)+ .unwrap();+ admitted += 1;+ }+ Err(error) => {+ assert_eq!(error.raw_os_error(), Some(libc::ENOSPC));+ break;+ }+ }+ }+ let mounts = client.list().unwrap();+ assert!(admitted > 0);+ assert_eq!(mounts.len(), admitted);+ for mount in mounts {+ client+ .set_state(&mount.export, MountState::Detaching)+ .unwrap();+ }+ assert_eq!(client.list().unwrap().len(), admitted);+ }++ #[test]+ fn client_deadline_includes_a_full_listener_backlog() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let listener = UnixListener::bind(&path).unwrap();+ // SAFETY: the fd belongs to a live Unix listener.+ assert_eq!(unsafe { libc::listen(listener.as_raw_fd(), 0) }, 0);+ let queued = UnixStream::connect(&path).unwrap();+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ let deadline = Instant::now() + Duration::from_millis(100);+ tx.send(transport::connect(&path, deadline)).unwrap();+ });+ let result = rx.recv_timeout(TIMEOUT);+ drop(queued);+ drop(listener);+ assert_eq!(result.unwrap().unwrap_err().kind(), io::ErrorKind::TimedOut);+ }++ #[test]+ fn another_uid_is_refused_mount_control() {+ use std::sync::atomic::{AtomicUsize, Ordering};++ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("vmm.sock");+ let tag = dir.path().to_str().unwrap().to_owned();+ let fs = Arc::new(AggregateFs::new(vec![]).unwrap());+ boxlite_vmm::insert_aggregate(&tag, fs.clone());+ let mut registry = Registry::default();+ let listener = UnixListener::bind(&path).unwrap();+ // This shim belongs to another uid, so the test process is a foreign peer.+ // SAFETY: `geteuid` has no preconditions.+ let owner = unsafe { libc::geteuid() } + 1;+ let handled = Arc::new(AtomicUsize::new(0));+ let seen = Arc::clone(&handled);+ std::thread::spawn(move || {+ serve_connections(+ listener.incoming(),+ owner,+ move |op, directory| {+ seen.fetch_add(1, Ordering::SeqCst);+ registry+ .request(&tag, op, directory)+ .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap()))+ },+ std::thread::sleep,+ )+ });+ for (op, directory) in [+ (ControlOp::ListMounts, None),+ (registration("/data"), Some(File::open(dir.path()).unwrap())),+ ] {+ assert_eq!(+ exchange(&path, op, directory.as_ref(), TIMEOUT).unwrap(),+ Err(ControlError::Mount(libc::EPERM))+ );+ }+ assert_eq!(+ handled.load(Ordering::SeqCst),+ 0,+ "a refused request must not reach the registry"+ );+ }++ #[test]+ fn a_kernel_socket_timeout_reports_the_deadline() {+ let (stream, _silent_peer) = UnixStream::pair().unwrap();+ let end = Instant::now() + Duration::from_millis(100);+ assert_eq!(+ transport::receive_frame(&stream, end).unwrap_err().kind(),+ io::ErrorKind::TimedOut+ );+ }+}diff --git a/src/boxlite/src/vmm/vmm_socket.rs b/src/boxlite/src/vmm/vmm_socket.rsindex 5d2b12870..451759224 100644--- a/src/boxlite/src/vmm/vmm_socket.rs+++ b/src/boxlite/src/vmm/vmm_socket.rs@@ -5,20 +5,33 @@//! host-only (mode 0600, never bridged into guest vsock) and at a fixed path,//! so a runtime that restarts can still reach a running box. Each connection//! carries one request and one response: a 4-byte little-endian length, then-//! a JSON object of at most [`MAX_FRAME`] bytes. Requests name [`VERSION`];-//! a shim answers any other version, or an operation its engine lacks, with-//! [`ControlError::Unsupported`].+//! a JSON object of at most [`MAX_FRAME`] bytes. Native directory registration+//! carries one open directory via `SCM_RIGHTS`. Requests name [`VERSION`].-use std::io::{self, Read, Write};+use std::fs::File;+use std::io;+#[cfg(test)]+use std::io::{Read, Write};use std::os::unix::net::{UnixListener, UnixStream};use std::path::Path;use std::time::Duration;use serde::{Deserialize, Serialize};+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+use super::controller::mount_control::{ControlMount, MountState};+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+use std::time::Instant;++#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+mod transport;+/// The protocol version a request names.pub(crate) const VERSION: u32 = 1;/// The largest frame either side accepts.+#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub(crate) const MAX_FRAME: u32 = 64 * 1024;+#[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]const MAX_FRAME: u32 = 4096;/// How long the shim waits for a request or a reply write.const IO_TIMEOUT: Duration = Duration::from_secs(2);@@ -40,6 +53,18 @@ pub(crate) struct ControlRequest {pub(crate) enum ControlOp {/// Grows the disk with the configured `block_id` to `bytes`.ResizeDisk { block_id: String, bytes: u64 },+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ RegisterMount {+ source: String,+ target: String,+ read_only: bool,+ },+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ ListMounts,+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ SetMountState { export: String, state: MountState },+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ RemoveMount { export: String },}/// The shim's answer.@@ -51,6 +76,12 @@ pub(crate) type ControlResponse = Result<ControlReply, ControlError>;pub(crate) enum ControlReply {/// The disk's size in bytes after the operation.DiskSize(u64),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ MountRegistered(ControlMount),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ Mounts(Vec<ControlMount>),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ MountUpdated,}/// Why an operation failed.@@ -63,28 +94,35 @@ pub(crate) enum ControlError {InvalidInput(String),#[error("{0}")]Failed(String),+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ #[error("mount control errno {0}")]+ Mount(i32),}/// Binds `path` (replacing a stale socket), makes it owner-only, and serves/// each connection on a `vmm-control` thread with `handle`.pub(crate) fn serve(path: &Path,- handle: impl Fn(ControlOp) -> ControlResponse + Send + 'static,+ handle: impl FnMut(ControlOp, Option<File>) -> ControlResponse + Send + 'static,) -> io::Result<()> {if std::fs::symlink_metadata(path).is_ok() {std::fs::remove_file(path)?;}let listener = UnixListener::bind(path)?;restrict_to_owner(path)?;+ // SAFETY: `geteuid` has no preconditions.+ let owner = unsafe { libc::geteuid() };std::thread::Builder::new().name("vmm-control".into())- .spawn(move || serve_connections(listener.incoming(), handle, std::thread::sleep))?;+ .spawn(move || serve_connections(listener.incoming(), owner, handle, std::thread::sleep))?;Ok(())}+/// `owner` is the uid whose mount control requests this shim accepts.fn serve_connections(incoming: impl Iterator<Item = io::Result<UnixStream>>,- handle: impl Fn(ControlOp) -> ControlResponse,+ owner: libc::uid_t,+ mut handle: impl FnMut(ControlOp, Option<File>) -> ControlResponse,mut sleep: impl FnMut(Duration),) {use io::ErrorKind::{ConnectionAborted, Interrupted};@@ -115,27 +153,96 @@ fn serve_connections(continue;}};- if let Err(error) = answer(stream, &handle) {+ if let Err(error) = answer(stream, owner, &mut handle) {tracing::debug!(%error, "control connection ended");}}}fn answer(- mut stream: UnixStream,- handle: &impl Fn(ControlOp) -> ControlResponse,+ stream: UnixStream,+ owner: libc::uid_t,+ handle: &mut impl FnMut(ControlOp, Option<File>) -> ControlResponse,) -> io::Result<()> {- stream.set_read_timeout(Some(IO_TIMEOUT))?;- stream.set_write_timeout(Some(IO_TIMEOUT))?;- let response = match serde_json::from_slice::<ControlRequest>(&read_frame(&mut stream)?) {- Ok(request) if request.version == VERSION => handle(request.op),+ // The resize path of other platforms has no peer check.+ #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]+ let _ = owner;+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ let (frame, file) = transport::receive_frame(&stream, Instant::now() + IO_TIMEOUT)?;+ #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]+ let (mut stream, frame, file) = {+ let mut stream = stream;+ stream.set_read_timeout(Some(IO_TIMEOUT))?;+ stream.set_write_timeout(Some(IO_TIMEOUT))?;+ let frame = read_frame(&mut stream)?;+ (stream, frame, None)+ };+ let response = match serde_json::from_slice::<ControlRequest>(&frame) {+ Ok(request) if request.version == VERSION => {+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ let checked = check_request(&stream, owner, &request.op, file.is_some());+ #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]+ let checked = Ok(());+ checked.and_then(|()| handle(request.op, file))+ }Ok(request) => Err(ControlError::Unsupported(format!("protocol version {}",request.version))),Err(error) => Err(ControlError::InvalidInput(error.to_string())),};- write_frame(&mut stream, &serde_json::to_vec(&response)?)+ let reply = serde_json::to_vec(&response)?;+ #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+ return transport::send_frame(&stream, &reply, None, Instant::now() + IO_TIMEOUT);+ #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]+ write_frame(&mut stream, &reply)+}++#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+fn check_request(+ stream: &UnixStream,+ owner: libc::uid_t,+ op: &ControlOp,+ has_fd: bool,+) -> Result<(), ControlError> {+ let register = matches!(op, ControlOp::RegisterMount { .. });+ if has_fd != register {+ return Err(ControlError::Mount(libc::EINVAL));+ }+ if !matches!(op, ControlOp::ResizeDisk { .. })+ && !transport::same_user(stream, owner)+ .map_err(|error| ControlError::Mount(error.raw_os_error().unwrap_or(libc::EIO)))?+ {+ return Err(ControlError::Mount(libc::EPERM));+ }+ Ok(())+}++#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]+pub(crate) fn exchange(+ path: &Path,+ op: ControlOp,+ directory: Option<&File>,+ timeout: Duration,+) -> io::Result<ControlResponse> {+ use std::os::fd::AsRawFd;++ let deadline = Instant::now() + timeout;+ let stream = transport::connect(path, deadline)?;+ let request = ControlRequest {+ version: VERSION,+ op,+ };+ let frame = serde_json::to_vec(&request)?;+ transport::send_frame(&stream, &frame, directory.map(AsRawFd::as_raw_fd), deadline)?;+ let (reply, attached) = transport::receive_frame(&stream, deadline)?;+ if attached.is_some() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "descriptor in control reply",+ ));+ }+ Ok(serde_json::from_slice(&reply)?)}/// Sends `request` to the shim at `path` and waits up to `timeout` for the@@ -153,6 +260,7 @@ pub(crate) fn request(Ok(serde_json::from_slice(&read_frame(&mut stream)?)?)}+#[cfg(test)]fn read_frame(stream: &mut UnixStream) -> io::Result<Vec<u8>> {let mut length = [0u8; 4];stream.read_exact(&mut length)?;@@ -168,6 +276,7 @@ fn read_frame(stream: &mut UnixStream) -> io::Result<Vec<u8>> {Ok(frame)}+#[cfg(test)]fn write_frame(stream: &mut UnixStream, frame: &[u8]) -> io::Result<()> {let length = u32::try_from(frame.len()).ok()diff --git a/src/boxlite/src/vmm/vmm_socket/transport.rs b/src/boxlite/src/vmm/vmm_socket/transport.rsnew file mode 100644index 000000000..6a30653d7--- /dev/null+++ b/src/boxlite/src/vmm/vmm_socket/transport.rs@@ -0,0 +1,263 @@+use super::MAX_FRAME;+use std::fs::File;+use std::io;+use std::mem::{size_of, zeroed};+use std::os::fd::{AsRawFd, FromRawFd, RawFd};+use std::os::unix::ffi::OsStrExt;+use std::os::unix::net::UnixStream;+use std::path::Path;+use std::time::{Duration, Instant};++fn remaining(end: Instant) -> io::Result<Duration> {+ end.checked_duration_since(Instant::now())+ .filter(|d| !d.is_zero())+ .ok_or_else(|| io::Error::new(io::ErrorKind::TimedOut, "VMM control deadline"))+}++/// A kernel socket timeout is the deadline, whichever loop the kernel interrupted.+fn timed_out(error: io::Error) -> io::Error {+ match error.kind() {+ io::ErrorKind::WouldBlock => {+ io::Error::new(io::ErrorKind::TimedOut, "VMM control deadline")+ }+ _ => error,+ }+}++pub(super) fn connect(path: &Path, end: Instant) -> io::Result<UnixStream> {+ let bytes = path.as_os_str().as_bytes();+ // SAFETY: a zeroed address has a NUL-terminated pathname buffer.+ let mut address: libc::sockaddr_un = unsafe { zeroed() };+ if bytes.is_empty() || bytes.contains(&0) || bytes.len() >= address.sun_path.len() {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ "VMM control socket path",+ ));+ }+ address.sun_family = libc::AF_UNIX as _;+ for (destination, source) in address.sun_path.iter_mut().zip(bytes) {+ *destination = *source as libc::c_char;+ }+ let length =+ (std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as libc::socklen_t;+ // SAFETY: socket has scalar arguments and returns a fresh fd on success.+ let fd = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0) };+ if fd < 0 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: this stream takes ownership of the fresh socket.+ let stream = unsafe { UnixStream::from_raw_fd(fd) };+ // Linux applies SO_SNDTIMEO to a blocking connect waiting on the listener backlog.+ stream.set_write_timeout(Some(remaining(end)?))?;+ // SAFETY: the initialized address covers `length` bytes, including the trailing NUL.+ if unsafe { libc::connect(fd, (&address as *const libc::sockaddr_un).cast(), length) } < 0 {+ return Err(timed_out(io::Error::last_os_error()));+ }+ Ok(stream)+}++// cmsghdr alignment is required even when the byte capacity is sufficient.+#[repr(C)]+struct Ancillary {+ alignment: [libc::cmsghdr; 0],+ bytes: [u8; 64],+}++pub(super) fn send_frame(+ stream: &UnixStream,+ payload: &[u8],+ fd: Option<RawFd>,+ end: Instant,+) -> io::Result<()> {+ if payload.len() > MAX_FRAME as usize {+ return Err(io::Error::from_raw_os_error(libc::EMSGSIZE));+ }+ send_parts(+ stream,+ &(payload.len() as u32).to_le_bytes(),+ payload,+ fd,+ end,+ )+}++pub(super) fn send_parts(+ stream: &UnixStream,+ head: &[u8],+ body: &[u8],+ mut fd: Option<RawFd>,+ end: Instant,+) -> io::Result<()> {+ let mut offset = 0;+ while offset < head.len() + body.len() {+ stream.set_write_timeout(Some(remaining(end)?))?;+ let mut control = Ancillary {+ alignment: [],+ bytes: [0; 64],+ };+ let (first, second) = if offset < head.len() {+ (&head[offset..], body)+ } else {+ (&body[offset - head.len()..], &[][..])+ };+ let mut iov = [+ libc::iovec {+ iov_base: first.as_ptr().cast_mut().cast(),+ iov_len: first.len(),+ },+ libc::iovec {+ iov_base: second.as_ptr().cast_mut().cast(),+ iov_len: second.len(),+ },+ ];+ // SAFETY: a zeroed msghdr has no optional address or ancillary pointers.+ let mut msg: libc::msghdr = unsafe { zeroed() };+ msg.msg_iov = iov.as_mut_ptr();+ msg.msg_iovlen = if second.is_empty() { 1 } else { 2 };+ if let Some(fd) = fd {+ msg.msg_control = control.bytes.as_mut_ptr().cast();+ msg.msg_controllen = unsafe { libc::CMSG_SPACE(size_of::<RawFd>() as _) } as _;+ unsafe {+ let header = libc::CMSG_FIRSTHDR(&msg);+ (*header).cmsg_level = libc::SOL_SOCKET;+ (*header).cmsg_type = libc::SCM_RIGHTS;+ (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as _) as _;+ std::ptr::write_unaligned(libc::CMSG_DATA(header).cast::<RawFd>(), fd);+ }+ }+ let sent = unsafe { libc::sendmsg(stream.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) };+ if sent < 0 {+ let error = io::Error::last_os_error();+ if error.kind() == io::ErrorKind::Interrupted {+ continue;+ }+ return Err(timed_out(error));+ }+ if sent == 0 {+ return Err(io::Error::new(io::ErrorKind::WriteZero, "VMM control send"));+ }+ offset += sent as usize;+ // A positive send transferred ancillary ownership even on a short write.+ fd = None;+ }+ Ok(())+}++pub(super) fn receive_exact(+ stream: &UnixStream,+ bytes: &mut [u8],+ file: &mut Option<File>,+ end: Instant,+) -> io::Result<()> {+ let mut offset = 0;+ while offset < bytes.len() {+ stream.set_read_timeout(Some(remaining(end)?))?;+ let mut control = Ancillary {+ alignment: [],+ bytes: [0; 64],+ };+ let mut iov = libc::iovec {+ iov_base: bytes[offset..].as_mut_ptr().cast(),+ iov_len: bytes.len() - offset,+ };+ let mut msg: libc::msghdr = unsafe { zeroed() };+ msg.msg_iov = &mut iov;+ msg.msg_iovlen = 1;+ msg.msg_control = control.bytes.as_mut_ptr().cast();+ msg.msg_controllen = control.bytes.len() as _;+ let received =+ unsafe { libc::recvmsg(stream.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC) };+ if received < 0 {+ let error = io::Error::last_os_error();+ if error.kind() == io::ErrorKind::Interrupted {+ continue;+ }+ return Err(timed_out(error));+ }+ let mut invalid = false;+ // SAFETY: recvmsg populated msg and its aligned control buffer.+ let (mut header, base) = unsafe { (libc::CMSG_FIRSTHDR(&msg), libc::CMSG_LEN(0) as usize) };+ while !header.is_null() {+ // SAFETY: this header was returned by the walk over the live buffer.+ let cmsg = unsafe { &*header };+ let length = cmsg.cmsg_len;+ #[cfg(target_env = "musl")]+ let length = length as usize;+ if length < base {+ invalid = true;+ break;+ }+ if cmsg.cmsg_level == libc::SOL_SOCKET && cmsg.cmsg_type == libc::SCM_RIGHTS {+ let count = (length - base) / size_of::<RawFd>();+ // SAFETY: the kernel initialized this header and its payload.+ let data = unsafe { libc::CMSG_DATA(header) }.cast::<RawFd>();+ for index in 0..count {+ // SAFETY: each full FD fits in the payload. recvmsg transferred+ // ownership, including descriptors from a rejected frame.+ let received = unsafe { File::from_raw_fd(data.add(index).read_unaligned()) };+ if file.is_some() {+ invalid = true;+ } else {+ *file = Some(received);+ }+ }+ invalid |= !(length - base).is_multiple_of(size_of::<RawFd>());+ } else {+ invalid = true;+ }+ // SAFETY: header belongs to msg's live, kernel-populated buffer.+ header = unsafe { libc::CMSG_NXTHDR(&msg, header) };+ }+ if invalid || msg.msg_flags & (libc::MSG_CTRUNC | libc::MSG_TRUNC) != 0 {+ return Err(io::Error::new(+ io::ErrorKind::InvalidData,+ "VMM control ancillary data",+ ));+ }+ if received == 0 {+ return Err(io::Error::new(+ io::ErrorKind::UnexpectedEof,+ "VMM control frame",+ ));+ }+ offset += received as usize;+ }+ Ok(())+}++pub(super) fn receive_frame(+ stream: &UnixStream,+ end: Instant,+) -> io::Result<(Vec<u8>, Option<File>)> {+ let mut file = None;+ let mut header = [0; 4];+ receive_exact(stream, &mut header, &mut file, end)?;+ let length = u32::from_le_bytes(header);+ if length > MAX_FRAME {+ return Err(io::Error::from_raw_os_error(libc::EMSGSIZE));+ }+ let mut payload = vec![0; length as usize];+ receive_exact(stream, &mut payload, &mut file, end)?;+ Ok((payload, file))+}++/// Whether the peer connected as `owner`, the uid this shim serves.+pub(super) fn same_user(stream: &UnixStream, owner: libc::uid_t) -> io::Result<bool> {+ // SAFETY: ucred is initialized before getsockopt writes to it.+ let mut credentials: libc::ucred = unsafe { zeroed() };+ let mut length = size_of::<libc::ucred>() as libc::socklen_t;+ // SAFETY: credentials and length are writable for the supplied size.+ let result = unsafe {+ libc::getsockopt(+ stream.as_raw_fd(),+ libc::SOL_SOCKET,+ libc::SO_PEERCRED,+ (&mut credentials as *mut libc::ucred).cast(),+ &mut length,+ )+ };+ if result < 0 {+ return Err(io::Error::last_os_error());+ }+ Ok(length as usize == size_of::<libc::ucred>() && credentials.uid == owner)+}diff --git a/src/boxlite/tests/native_mount_delivery.rs b/src/boxlite/tests/native_mount_delivery.rsnew file mode 100644index 000000000..c6ef03ee1--- /dev/null+++ b/src/boxlite/tests/native_mount_delivery.rs@@ -0,0 +1,265 @@+//! Native directory delivery through vmm.sock and the guest RPC bridge.++#![cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]++mod common;++use boxlite::runtime::options::{BoxliteOptions, NetworkSpec};+use boxlite::vmm::controller::mount_control::{MountControlClient, MountState};+use boxlite::{BoxCommand, LiteBox};+use boxlite_shared::{ContainerClient, ContainerDetachRequest, ContainerMountRequest};+use futures::StreamExt;+use hyper_util::rt::TokioIo;+use std::{+ fs::File,+ io,+ path::{Path, PathBuf},+ time::Duration,+};+use tonic::transport::{Channel, Endpoint};++async fn control<T: Send + 'static>(+ socket: &Path,+ operation: impl FnOnce(&MountControlClient) -> io::Result<T> + Send + 'static,+) -> io::Result<T> {+ let socket = socket.to_owned();+ tokio::task::spawn_blocking(move || operation(&MountControlClient::new(socket)))+ .await+ .expect("control task")+}++async fn run(bx: &LiteBox, script: &str) -> (i32, String) {+ let mut execution = bx+ .exec(BoxCommand::new("sh").args(["-c", script]))+ .await+ .unwrap();+ let mut output = String::new();+ if let Some(mut stream) = execution.stdout() {+ while let Some(chunk) = stream.next().await {+ output.push_str(&chunk);+ }+ }+ (execution.wait().await.unwrap().exit_code, output)+}++async fn guest(socket: PathBuf) -> ContainerClient<Channel> {+ let channel = Endpoint::from_static("http://[::]:50051")+ .connect_timeout(Duration::from_secs(10))+ .connect_with_connector(tower::service_fn(move |_| {+ let socket = socket.clone();+ async move {+ tokio::net::UnixStream::connect(socket)+ .await+ .map(TokioIo::new)+ }+ }))+ .await+ .unwrap();+ ContainerClient::new(channel)+}++async fn mounted(+ client: &mut ContainerClient<Channel>,+ container: &str,+ export: &str,+ read_only: bool,+) {+ client+ .mount(ContainerMountRequest {+ container_id: container.into(),+ source: String::new(),+ destination: "/workspace".into(),+ export_key: export.into(),+ device_tag: boxlite_shared::constants::mount_tags::AGGREGATE.into(),+ read_only,+ })+ .await+ .unwrap();+}++async fn detached(client: &mut ContainerClient<Channel>, container: &str, export: &str) {+ client+ .detach(ContainerDetachRequest {+ container_id: container.into(),+ destination: "/workspace".into(),+ export_key: export.into(),+ })+ .await+ .unwrap();+}++async fn state(socket: &Path, export: &str, state: MountState) {+ let export = export.to_owned();+ control(socket, move |client| client.set_state(&export, state))+ .await+ .unwrap();+}++async fn retire(socket: &Path, export: &str) {+ let export = export.to_owned();+ control(socket, move |client| client.remove(&export))+ .await+ .unwrap();+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL; make test:integration:vmm:mount-delivery"]+async fn descriptor_delivery_mounts_and_detaches_in_an_existing_container() {+ assert_eq!(+ std::env::var("BOXLITE_TEST_ENGINE").as_deref(),+ Ok("native")+ );+ let home = common::home::PerTestBoxHome::new();+ let runtime = common::TestRuntime::new(BoxliteOptions {+ home_dir: home.path.clone(),+ image_registries: common::test_registries(),+ ..Default::default()+ })+ .unwrap();+ let source = tempfile::tempdir_in("/tmp").unwrap();+ std::fs::write(source.path().join("value"), "host").unwrap();+ let mut options = common::alpine_opts();+ options.network = NetworkSpec::Disabled;+ options.cmd = Some(vec!["sleep".into(), "300".into()]);+ assert!(options.volumes.is_empty());+ let bx = runtime.create(options, None).await.unwrap();+ bx.start().await.unwrap();+ let container = bx+ .executions()+ .list()+ .await+ .unwrap()+ .into_iter()+ .find(|execution| execution.is_main_session)+ .expect("running main session")+ .execution_id;+ let sockets = home+ .path+ .join("boxes")+ .join(bx.id().as_str())+ .join("sockets");+ let socket = sockets.join("vmm.sock");+ let mut rpc = guest(sockets.join("box.sock")).await;++ let path = source.path().to_owned();+ let mount = control(&socket, move |client| {+ client.register(+ path.to_str().unwrap().into(),+ "/workspace".into(),+ File::open(&path)?,+ false,+ )+ })+ .await+ .unwrap();+ assert_eq!(mount.state, MountState::Preparing);+ assert_eq!(+ control(&socket, |client| client.list()).await.unwrap(),+ vec![mount.clone()]+ );+ mounted(&mut rpc, &container, &mount.export, false).await;+ state(&socket, &mount.export, MountState::Mounted).await;+ assert_eq!(run(&bx, "cat /workspace/value").await, (0, "host".into()));+ assert_eq!(run(&bx, "printf guest > /workspace/from-guest").await.0, 0);+ assert_eq!(+ std::fs::read_to_string(source.path().join("from-guest")).unwrap(),+ "guest"+ );++ state(&socket, &mount.export, MountState::Detaching).await;+ detached(&mut rpc, &container, &mount.export).await;+ retire(&socket, &mount.export).await;+ assert_eq!(run(&bx, "test ! -e /workspace/value").await.0, 0);+ assert!(+ control(&socket, |client| client.list())+ .await+ .unwrap()+ .is_empty()+ );+ bx.stop().await.unwrap();+ runtime.remove(bx.id().as_str(), true).await.unwrap();+}++#[tokio::test]+#[ignore = "requires native runtime, KVM and VMM_KERNEL; make test:integration:vmm:mount-delivery"]+async fn mount_administrative_containers_keep_privileges_and_reject_runtime_delivery() {+ use boxlite::runtime::advanced_options::ContainerCapabilities;+ assert_eq!(+ std::env::var("BOXLITE_TEST_ENGINE").as_deref(),+ Ok("native")+ );+ for privileged in [false, true] {+ let home = common::home::PerTestBoxHome::new();+ let runtime = common::TestRuntime::new(BoxliteOptions {+ home_dir: home.path.clone(),+ image_registries: common::test_registries(),+ ..Default::default()+ })+ .unwrap();+ let mut options = common::alpine_opts();+ options.network = NetworkSpec::Disabled;+ options.cmd = Some(vec!["sleep".into(), "300".into()]);+ if privileged {+ options.advanced.privileged = true;+ } else {+ options+ .advanced+ .set_capabilities(Some(ContainerCapabilities {+ add: vec!["SYS_ADMIN".into()],+ drop: vec![],+ }))+ .unwrap();+ }+ let bx = runtime.create(options, None).await.unwrap();+ bx.start().await.unwrap();+ let container = bx+ .executions()+ .list()+ .await+ .unwrap()+ .into_iter()+ .find(|execution| execution.is_main_session)+ .unwrap()+ .execution_id;+ let socket = home+ .path+ .join("boxes")+ .join(bx.id().as_str())+ .join("sockets/box.sock");+ let mut rpc = guest(socket).await;+ let error = rpc+ .mount(ContainerMountRequest {+ container_id: container.clone(),+ source: String::new(),+ destination: "/workspace".into(),+ export_key: "not-published".into(),+ device_tag: "boxlite".into(),+ read_only: false,+ })+ .await+ .unwrap_err();+ assert_eq!(error.code(), tonic::Code::Unimplemented);+ assert!(error.message().contains("CAP_SYS_ADMIN"));+ let error = rpc+ .detach(ContainerDetachRequest {+ container_id: container,+ destination: "/workspace".into(),+ export_key: "not-published".into(),+ })+ .await+ .unwrap_err();+ assert_eq!(error.code(), tonic::Code::Unimplemented);+ assert!(error.message().contains("CAP_SYS_ADMIN"));+ assert_eq!(run(&bx, "test ! -e /workspace").await.0, 0);+ let (exit, bounding) = run(&bx, "awk '/^CapBnd:/ {print $2}' /proc/self/status").await;+ assert_eq!(exit, 0);+ let bounding = u64::from_str_radix(bounding.trim(), 16).unwrap();+ assert_ne!(+ bounding & (1 << 21),+ 0,+ "configured CAP_SYS_ADMIN must remain granted"+ );+ bx.stop().await.unwrap();+ runtime.remove(bx.id().as_str(), true).await.unwrap();+ }+}diff --git a/src/guest/README.md b/src/guest/README.mdindex 3063265fe..49edab11e 100644--- a/src/guest/README.md+++ b/src/guest/README.md@@ -12,6 +12,76 @@ TCP and Unix listeners return `PermissionDenied` for `Guest.SyncClock`.The host samples current UTC after connecting and immediately before sending. The agent accepts the call only from the host control plane (the vsock listener rejects non-host peers before tonic sees them), validates a post-epoch timestamp with a valid subsecond part, then reads `CLOCK_REALTIME`. Only an absolute difference greater than 100ms calls `clock_settime`, in either direction; a difference of exactly 100ms or less returns success without adjusting the clock. The host is the clock authority, so legitimate timestamps after long sleeps have no ahead-of-guest bound. Invalid timestamps, clock-read failures, and clock-setting failures propagate as gRPC errors; only successful responses update the shim's successful-push baseline. The 100ms threshold is a decision to adjust, not a precision guarantee: transport and scheduling delay remain uncompensated. The correction never touches the RTC or `CLOCK_MONOTONIC`, so the guest's own RTC offset and alarms survive it, and user containers need no additional `CAP_SYS_TIME`.+## Runtime directory delivery++`Container.Mount` has two source forms. A legacy `source` is one folder name+inside the container's shared volumes directory and requires `read_only=true`.+Aggregate delivery leaves `source` empty and supplies `device_tag`, a unique+`export_key` incarnation, an absolute `destination`, and the requested read-only+or writable bind mode. Initialization registers each aggregate root by device+tag. Installed initialization mounts already belong to the rollback guard when+root publication starts; failed publication unwinds them without replacing a+previous registration. Committing initialization keeps the roots available for+later RPCs.++Aggregate Mount and Detach require a container whose capability bounding set+excludes `CAP_SYS_ADMIN`. Aggregate Mount also requires that the target mount+namespace belong to the guest agent's user namespace. The agent rejects+unsupported targets before publishing a mount. Mount replay and Detach must+refer to the recorded namespace. If init has switched namespaces, the agent+reports a failed precondition and retains the record. Legacy share delivery is+read-only.++The agent clones the export with `open_tree`, applies recursive read-only flags+when requested, and moves the clone into the running container's mount namespace+with `move_mount`. It refuses destinations containing entries and walks every+component without following symlinks. Guest writable mode does not override the+host export's permission policy. A retry must match the incarnation's source,+mode, destination, and actual mounted tree.++The incarnation record retains the original cloned-tree descriptor. This pins+the mounted tree rather than the directory underneath it, preventing mount-ID+reuse while the record is attached. The agent reads that tree's checked+`statx(STATX_MNT_ID)` identity before publishing it, because a mount keeps its ID+when it moves. Before retry success or detach, another child opens the destination+without following links and compares its mount ID with the retained tree. A+replacement at the original path leaves the old record intact while its mount+still exists. This ownership follows Linux's+[`open_detached_copy`, `do_move_mount`, and `dissolve_on_fput`](https://github.com/torvalds/linux/blob/v6.12/fs/namespace.c):+moving changes the mount's namespace, while the open file retains its reference.++`Container.Detach(container_id, destination, export_key)` uses `MNT_DETACH`.+New opens lose access through the destination; already-open files and directory+references remain usable. Runtime and OCI descendants must be detached first.+Removing a runtime overmount removes only its last bookkeeping entry, preserving+the underlying OCI entry. Repeated detach succeeds without another unmount;+detach of an unseen incarnation records a tombstone that rejects delayed Mount.+Detached records and tombstones stay for the agent's lifetime, so their count follows+the Detach requests the host has issued; each holds a key, a path, and two flags.+Mount and Detach hold the same per-container write lock through syscall execution+and bookkeeping, in an owned task that survives RPC caller cancellation.++Aggregate Mount checks that the kernel supports mount namespace IDs and the+`statmount` recovery query before publishing a mount. If the helper's final+report is lost, the agent returns an error and retains the mount identity and+destination. Detach verifies any still-present tree at its original path in+the recorded namespace. If an ancestor was renamed before Detach opened the+destination, restore the original path to retry.++After a lost detach report, the agent clears the record once `statmount`+confirms absence in the same namespace. If that query is unavailable or fails,+the record and destination remain reserved.++These are lower-level delivery operations. The caller coordinates guest+acknowledgment with host export retirement and reconciles unknown RPC outcomes.+They do not expose a public Box mount transaction API.++Run `make test:unit:guest FILTER=storage::attach::tests` for validation and+tombstone checks, and `make test:guest-perms` for the ignored `privileged_`+namespace cases: actual RO/RW delivery, replay, descendant refusal, lazy detach+with an open descriptor, and ancestor rename plus mount replacement. The guest+unit suite also covers root publication rollback and OCI bookkeeping.+## Startup ownership| Responsibility | Native PID 1 | libkrun child |diff --git a/src/guest/src/container/capabilities.rs b/src/guest/src/container/capabilities.rsindex a8f4838a1..c8b70ca6b 100644--- a/src/guest/src/container/capabilities.rs+++ b/src/guest/src/container/capabilities.rs@@ -174,7 +174,6 @@ impl CapabilitySet {self.0.len()}- #[cfg(test)]pub(crate) fn contains(&self, capability: &Capability) -> bool {self.0.contains(capability)}diff --git a/src/guest/src/container/lifecycle.rs b/src/guest/src/container/lifecycle.rsindex 681537c98..81706c336 100644--- a/src/guest/src/container/lifecycle.rs+++ b/src/guest/src/container/lifecycle.rs@@ -342,6 +342,20 @@ impl Container {self.user}+ /// Runtime mount identity checks require a workload that cannot change its+ /// own mount table. This policy is also the OCI bounding set for init and exec.+ pub(crate) fn ensure_runtime_mounts_supported(&self) -> BoxliteResult<()> {+ if self+ .capabilities+ .contains(&oci_spec::runtime::Capability::SysAdmin)+ {+ return Err(BoxliteError::Unsupported(+ "runtime directory mounts require a container without CAP_SYS_ADMIN".into(),+ ));+ }+ Ok(())+ }+/// Destinations of every mount in the container: those it was created with,/// plus those `Container.Mount` added since (see/// [`Self::record_mount_destination`]).@@ -370,6 +384,24 @@ impl Container {self.mount_destinations.push(destination);}+ /// Includes both OCI mounts and directories delivered at runtime.+ pub(crate) fn has_mount_descendants(&self, destination: &Path) -> bool {+ self.mount_destinations+ .iter()+ .any(|mount| mount != destination && mount.starts_with(destination))+ }++ /// Remove only the runtime layer, retaining any underlying OCI mount.+ pub fn remove_mount_destination(&mut self, destination: &Path) {+ if let Some(index) = self+ .mount_destinations+ .iter()+ .rposition(|recorded| recorded == destination)+ {+ self.mount_destinations.remove(index);+ }+ }+/// The attacher, behind the lock that orders mounts and copies (see the/// field). Taken without holding this container's lock.pub(crate) fn attacher(&self) -> Arc<tokio::sync::RwLock<Attacher>> {@@ -721,6 +753,47 @@ mod tests {}}+ #[test]+ fn runtime_mount_removal_preserves_oci_layers_and_descendant_bookkeeping() {+ let root = tempfile::tempdir().unwrap();+ let mut container = Container {+ id: "mount-bookkeeping".into(),+ state_root: root.path().join("state"),+ bundle_path: root.path().join("bundle"),+ env: HashMap::new(),+ user: (0, 0),+ mount_destinations: vec!["/data".into(), "/data/oci-child".into(), "/database".into()],+ attacher: Arc::default(),+ capabilities: CapabilitySet::default(),+ stdio: ContainerStdio::pipes().unwrap().0,+ is_shutdown: std::sync::atomic::AtomicBool::new(true),+ };+ container.record_mount_destination("/data".into());+ container.record_mount_destination("/data/runtime-child".into());+ assert!(container.has_mount_descendants(Path::new("/data")));+ container.remove_mount_destination(Path::new("/data/runtime-child"));+ assert!(+ container.has_mount_descendants(Path::new("/data")),+ "OCI descendant still prevents detach"+ );+ container.remove_mount_destination(Path::new("/data"));+ assert_eq!(+ container.mount_destinations(),+ &[+ PathBuf::from("/data"),+ PathBuf::from("/data/oci-child"),+ PathBuf::from("/database"),+ ]+ );+ assert!(!container.has_mount_descendants(Path::new("/data/oci-child")));+ assert!(+ !container.has_mount_descendants(Path::new("/dat")),+ "prefixes are component-aware"+ );+ container.remove_mount_destination(Path::new("/absent"));+ assert_eq!(container.mount_destinations().len(), 3);+ }+#[test]fn init_pipe_handle_failure_reaps_init() {let child = ChildGuard(diff --git a/src/guest/src/service/container.rs b/src/guest/src/service/container.rsindex 74472d603..07ae02a38 100644--- a/src/guest/src/service/container.rs+++ b/src/guest/src/service/container.rs@@ -3,17 +3,18 @@//!//! Handles OCI container lifecycle (Init RPC).-use std::path::{Component, Path, PathBuf};+use std::path::{Path, PathBuf};use crate::service::server::GuestServer;+use crate::storage::aggregate_root;use crate::storage::attach::{validate_destination, Target};use boxlite_shared::errors::{BoxliteError, BoxliteResult};use boxlite_shared::{container_init_response, container_start_response, rootfs_init, BindMount, BindMountKind,- Container as ContainerService, ContainerInitError, ContainerInitErrorKind,- ContainerInitRequest, ContainerInitResponse, ContainerInitSuccess, ContainerMountRequest,- ContainerMountResponse, ContainerStartRequest, ContainerStartResponse, ContainerStartSuccess,- Filesystem, RootfsInit,+ Container as ContainerService, ContainerDetachRequest, ContainerDetachResponse,+ ContainerInitError, ContainerInitErrorKind, ContainerInitRequest, ContainerInitResponse,+ ContainerInitSuccess, ContainerMountRequest, ContainerMountResponse, ContainerStartRequest,+ ContainerStartResponse, ContainerStartSuccess, Filesystem, RootfsInit,};use nix::mount::{mount, MsFlags};use tonic::{Request, Response, Status};@@ -84,29 +85,75 @@ fn bind_mount_source(mount: &BindMount) -> BoxliteResult<BindMountSource<'_>> {}}-/// Check a `Container.Mount` request: read-only, a source that is one share-/// folder name so it stays inside `containers/<id>/volumes/`, and a valid-/// container path. Returns the destination.+/// Byte width of the tag field in the virtio-fs device configuration.+const VIRTIO_FS_TAG_LEN: usize = 36;++/// What a `Container.Mount` request delivers, after validation.+#[derive(Debug)]+enum MountSource {+ /// Legacy share folder in the container's volumes directory.+ Volume,+ /// M6 aggregate export beneath the registered root of `device_tag`.+ Aggregate {+ device_tag: String,+ export_key: String,+ },+}++fn one_component(value: &str) -> bool {+ !value.is_empty() && value != "." && value != ".." && !value.contains(['/', '\0'])+}++/// Check a `Container.Mount` request: legacy delivery stays read-only with a+/// source that is one share folder name so it stays inside+/// `containers/<id>/volumes/`; aggregate delivery requires an export key and+/// device tag instead. Returns the checked destination.#[allow(clippy::result_large_err)]-fn checked_mount(request: &ContainerMountRequest) -> Result<PathBuf, Status> {- if !request.read_only {- return Err(Status::invalid_argument(- "Container.Mount mounts share folders read-only",- ));- }- let one_component = matches!(- Path::new(&request.source).components().collect::<Vec<_>>()[..],- [Component::Normal(_)]- );- if !one_component {- return Err(Status::invalid_argument(format!(- "source must be one share folder name, not a path: {:?}",- request.source- )));- }+fn checked_mount(request: &ContainerMountRequest) -> Result<(MountSource, PathBuf), Status> {+ let source = if request.export_key.is_empty() {+ if !request.device_tag.is_empty() {+ return Err(Status::invalid_argument("device_tag requires export_key"));+ }+ if !request.read_only {+ return Err(Status::invalid_argument(+ "legacy share mounts are read-only; aggregate delivery carries the mode",+ ));+ }+ if !one_component(&request.source) {+ return Err(Status::invalid_argument(format!(+ "source must be one share folder name, not a path: {:?}",+ request.source+ )));+ }+ MountSource::Volume+ } else {+ if !request.source.is_empty() {+ return Err(Status::invalid_argument(+ "aggregate delivery takes export_key, not a share folder name",+ ));+ }+ if !one_component(&request.export_key) {+ return Err(Status::invalid_argument(format!(+ "export_key must be one component, not a path: {:?}",+ request.export_key+ )));+ }+ if request.device_tag.is_empty()+ || request.device_tag.len() > VIRTIO_FS_TAG_LEN+ || request.device_tag.contains('\0')+ {+ return Err(Status::invalid_argument(format!(+ "aggregate delivery requires a device tag of 1..={VIRTIO_FS_TAG_LEN} bytes"+ )));+ }+ MountSource::Aggregate {+ device_tag: request.device_tag.clone(),+ export_key: request.export_key.clone(),+ }+ };let destination = PathBuf::from(&request.destination);validate_destination(&destination).map_err(BoxliteError::into_validation_status)?;- Ok(destination)+ Ok((source, destination))}/// Report a failed attach: caller mistakes stay `INVALID_ARGUMENT`; a@@ -116,6 +163,7 @@ fn checked_mount(request: &ContainerMountRequest) -> Result<PathBuf, Status> {fn mount_status(error: BoxliteError) -> Status {match error {BoxliteError::InvalidArgument(message) => Status::invalid_argument(message),+ BoxliteError::Unsupported(message) => Status::unimplemented(message),BoxliteError::InvalidState(message) | BoxliteError::NotFound(message) => {Status::failed_precondition(message)}@@ -766,7 +814,7 @@ impl ContainerService for GuestServer {request: Request<ContainerMountRequest>,) -> Result<Response<ContainerMountResponse>, Status> {let request = request.into_inner();- let destination = checked_mount(&request)?;+ let (source_kind, destination) = checked_mount(&request)?;let container_id = request.container_id;let Some(container_arc) = self.containers.lock().await.get(&container_id).cloned() else {@@ -776,6 +824,11 @@ impl ContainerService for GuestServer {};let (target, attacher) = {let container = container_arc.lock().await;+ if matches!(&source_kind, MountSource::Aggregate { .. }) {+ container+ .ensure_runtime_mounts_supported()+ .map_err(mount_status)?;+ }let init = container.init_pid().filter(|_| container.is_running())@@ -787,37 +840,140 @@ impl ContainerService for GuestServer {let target = Target::open(init).map_err(mount_status)?;(target, container.attacher())};- let source = self- .layout- .shared()- .container(&container_id)- .volume_dir(&request.source);+ let source = match &source_kind {+ MountSource::Volume => self+ .layout+ .shared()+ .container(&container_id)+ .volume_dir(&request.source),+ MountSource::Aggregate {+ device_tag,+ export_key,+ } => {+ let root = aggregate_root(device_tag).ok_or_else(|| {+ Status::failed_precondition(format!(+ "no aggregate root registered for device tag {device_tag}"+ ))+ })?;+ root.join(export_key)+ }+ };+ let read_only = request.read_only;let mount_point = destination.clone();+ let export_key = request.export_key;// Attach and record in a task of their own, so a caller that gives up// cannot leave a mount the container does not know about. The write// lock is held until the mount is recorded: a copy waits for both.let attach = tokio::spawn(async move {let mut attacher = attacher.write_owned().await;let attacher = tokio::task::spawn_blocking(move || {- attacher.attach_read_only(&source, &target, &mount_point)?;- Ok::<_, BoxliteError>(attacher)+ let (added, confirmation) = if export_key.is_empty() {+ attacher.attach(&source, &target, &mount_point, read_only)?;+ (true, Ok(()))+ } else {+ let attempt = attacher.attach_runtime(+ &export_key,+ &source,+ &target,+ &mount_point,+ read_only,+ )?;+ (attempt.added, attempt.confirmation)+ };+ Ok::<_, BoxliteError>((attacher, added, confirmation))}).await.map_err(|error| Status::internal(format!("attach task failed: {error}")))?.map_err(mount_status)?;- container_arc- .lock()- .await- .record_mount_destination(destination);+ let (attacher, added, confirmation) = attacher;+ if added {+ container_arc+ .lock()+ .await+ .record_mount_destination(destination);+ }drop(attacher);- Ok::<_, Status>(())+ confirmation.map_err(mount_status)});attach.await.map_err(|error| Status::internal(format!("attach task failed: {error}")))??;- info!(container_id = %container_id, destination = %request.destination, "Mounted a share folder read-only");+ info!(container_id = %container_id, destination = %request.destination, "Mounted a directory into the container");Ok(Response::new(ContainerMountResponse {}))}++ async fn detach(+ &self,+ request: Request<ContainerDetachRequest>,+ ) -> Result<Response<ContainerDetachResponse>, Status> {+ let request = request.into_inner();+ let destination = PathBuf::from(&request.destination);+ validate_destination(&destination).map_err(BoxliteError::into_validation_status)?;+ if request.export_key.is_empty() || !one_component(&request.export_key) {+ return Err(Status::invalid_argument(+ "detach requires a runtime export_key",+ ));+ }++ let container_id = request.container_id;+ let Some(container_arc) = self.containers.lock().await.get(&container_id).cloned() else {+ return Err(Status::not_found(format!(+ "No such container: {container_id}"+ )));+ };+ let (target, attacher) = {+ let container = container_arc.lock().await;+ container+ .ensure_runtime_mounts_supported()+ .map_err(mount_status)?;+ let init = container+ .init_pid()+ .filter(|_| container.is_running())+ .ok_or_else(|| {+ Status::failed_precondition(format!("container {container_id} is not running"))+ })?;+ let target = Target::open(init).map_err(mount_status)?;+ (target, container.attacher())+ };+ // Detach in a task of its own, mirroring the mount: a caller that+ // gives up cannot leave the container believing in a stale mount.+ let recorded = destination.clone();+ let detach = tokio::spawn(async move {+ let mut attacher = attacher.write_owned().await;+ if attacher.runtime_attached(&request.export_key)+ && container_arc+ .lock()+ .await+ .has_mount_descendants(&destination)+ {+ return Err(Status::failed_precondition(+ "detach descendant mounts first",+ ));+ }+ let attacher = tokio::task::spawn_blocking(move || {+ let removed =+ attacher.detach_runtime(&request.export_key, &target, &destination)?;+ Ok::<_, BoxliteError>((attacher, removed))+ })+ .await+ .map_err(|error| Status::internal(format!("detach task failed: {error}")))?+ .map_err(mount_status)?;+ let (attacher, removed) = attacher;+ if removed {+ container_arc+ .lock()+ .await+ .remove_mount_destination(&recorded);+ }+ drop(attacher);+ Ok::<_, Status>(())+ });+ detach+ .await+ .map_err(|error| Status::internal(format!("detach task failed: {error}")))??;+ info!(container_id = %container_id, destination = %request.destination, "Detached a container mount");+ Ok(Response::new(ContainerDetachResponse {}))+ }}impl GuestServer {@@ -862,12 +1018,31 @@ mod tests {source: source.to_string(),destination: destination.to_string(),read_only: true,+ export_key: String::new(),+ device_tag: String::new(),+ }+ }++ fn aggregate_export(+ export_key: &str,+ destination: &str,+ read_only: bool,+ ) -> ContainerMountRequest {+ ContainerMountRequest {+ container_id: "box".to_string(),+ source: String::new(),+ destination: destination.to_string(),+ read_only,+ export_key: export_key.to_string(),+ device_tag: boxlite_shared::constants::mount_tags::AGGREGATE.to_string(),}}#[test]fn mount_accepts_a_read_only_share_folder() {- let destination = checked_mount(&share_folder("agents", "/opt/boxlite/agents")).unwrap();+ let (source, destination) =+ checked_mount(&share_folder("agents", "/opt/boxlite/agents")).unwrap();+ assert!(matches!(source, MountSource::Volume));assert_eq!(destination, PathBuf::from("/opt/boxlite/agents"));}@@ -881,7 +1056,7 @@ mod tests {}#[test]- fn mount_refuses_writable_or_misplaced_mounts() {+ fn mount_refuses_writable_or_misplaced_legacy_mounts() {let writable = ContainerMountRequest {read_only: false,..share_folder("agents", "/opt/boxlite/agents")@@ -947,6 +1122,24 @@ mod tests {}}+ #[test]+ fn mount_accepts_aggregate_exports_in_either_mode() {+ for read_only in [true, false] {+ let (source, destination) =+ checked_mount(&aggregate_export("late", "/opt/boxlite/late", read_only)).unwrap();+ let MountSource::Aggregate {+ device_tag,+ export_key,+ } = source+ else {+ panic!("expected an aggregate source");+ };+ assert_eq!(device_tag, boxlite_shared::constants::mount_tags::AGGREGATE);+ assert_eq!(export_key, "late");+ assert_eq!(destination, PathBuf::from("/opt/boxlite/late"));+ }+ }+#[test]fn bind_mount_rejects_unknown_kinds_and_invalid_subpaths() {let unknown = BindMount {@@ -975,6 +1168,29 @@ mod tests {}}+ #[test]+ fn aggregate_delivery_rejects_paths_and_missing_device_tag() {+ for request in [+ aggregate_export("a/b", "/opt/boxlite/late", true),+ aggregate_export("..", "/opt/boxlite/late", true),+ aggregate_export("late/", "/opt/boxlite/late", true),+ aggregate_export("late\0other", "/opt/boxlite/late", true),+ aggregate_export("", "/opt/boxlite/late", true),+ ContainerMountRequest {+ export_key: "late".into(),+ device_tag: String::new(),+ ..aggregate_export("late", "/opt/boxlite/late", true)+ },+ ContainerMountRequest {+ source: "agents".into(),+ ..aggregate_export("late", "/opt/boxlite/late", true)+ },+ ] {+ let status = checked_mount(&request).unwrap_err();+ assert_eq!(status.code(), Code::InvalidArgument, "{}", status.message());+ }+ }+#[test]fn attach_failures_keep_their_grpc_codes() {let cases = [@@ -990,6 +1206,10 @@ mod tests {BoxliteError::NotFound("init gone".into()),Code::FailedPrecondition,),+ (+ BoxliteError::Unsupported("CAP_SYS_ADMIN".into()),+ Code::Unimplemented,+ ),(BoxliteError::Storage("move_mount".into()), Code::Internal),];for (error, code) in cases {diff --git a/src/guest/src/storage/aggregate.rs b/src/guest/src/storage/aggregate.rsindex 34d7eb97c..8befa9d74 100644--- a/src/guest/src/storage/aggregate.rs+++ b/src/guest/src/storage/aggregate.rs@@ -1,7 +1,8 @@//! Aggregate mounts own their bindings and roots until the whole batch succeeds.-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap};use std::path::{Path, PathBuf};+use std::sync::{LazyLock, Mutex};use boxlite_shared::errors::{BoxliteError, BoxliteResult};use boxlite_shared::layout::GUEST_BASE;@@ -11,6 +12,17 @@ use nix::mount::{mount, umount, MsFlags};use super::virtiofs::VirtiofsMount;use super::volume::{mount_volume, resolve_mount_point};+/// Aggregate roots mounted during guest initialization, keyed by device tag.+/// The mount RPC delivers runtime exports from these roots; the agent+/// process serves one VM, so the map lives as long as the process.+static ROOTS: LazyLock<Mutex<BTreeMap<String, PathBuf>>> =+ LazyLock::new(|| Mutex::new(BTreeMap::new()));++/// The registered root of an aggregate device, for runtime export delivery.+pub(crate) fn aggregate_root(tag: &str) -> Option<PathBuf> {+ ROOTS.lock().unwrap().get(tag).cloned()+}+#[derive(Debug, PartialEq, Eq)]enum Mount {Root {@@ -107,16 +119,25 @@ fn plan(volumes: &[Volume]) -> BoxliteResult<Vec<Mount>> {}/// Rolls aggregate mounts back if a later guest initialization step fails.-pub(crate) struct MountedVolumes(Vec<PathBuf>);+pub(crate) struct MountedVolumes(Vec<PathBuf>, Vec<(String, PathBuf)>);impl MountedVolumes {pub(crate) fn commit(mut self) {self.0.clear();+ self.1.clear();}}impl Drop for MountedVolumes {fn drop(&mut self) {+ // Rollback must still release installed mounts after registry poison.+ let mut roots = ROOTS.lock().unwrap_or_else(|error| error.into_inner());+ for (tag, root) in &self.1 {+ if roots.get(tag) == Some(root) {+ roots.remove(tag);+ }+ }+ drop(roots);for path in self.0.iter().rev() {if let Err(error) = unmount(path) {tracing::error!(%error, "Aggregate mount rollback failed");@@ -169,14 +190,16 @@ pub(crate) fn mount_volumes(volumes: &[Volume]) -> BoxliteResult<MountedVolumes>});if !aggregate {super::mount_volumes(volumes)?;- return Ok(MountedVolumes(Vec::new()));+ return Ok(MountedVolumes(Vec::new(), Vec::new()));}- execute(- &plan(volumes)?,+ let mounts = plan(volumes)?;+ let owned = execute(+ &mounts,|operation| match operation {Mount::Root { tag, target } => {prepare_destination(target)?;- VirtiofsMount::mount(tag, target, false)+ VirtiofsMount::mount(tag, target, false)?;+ Ok(())}Mount::Bind {source,@@ -186,8 +209,37 @@ pub(crate) fn mount_volumes(volumes: &[Volume]) -> BoxliteResult<MountedVolumes>Mount::Legacy { index, .. } => mount_volume(&volumes[*index]),},unmount,- )- .map(MountedVolumes)+ )?;+ let mounted = MountedVolumes(owned, Vec::new());+ let published: Vec<_> = mounts+ .iter()+ .filter_map(|operation| match operation {+ Mount::Root { tag, target } => Some((tag.clone(), target.clone())),+ _ => None,+ })+ .collect();+ publish_roots(mounted, published)+}++fn publish_roots(+ mut mounted: MountedVolumes,+ published: Vec<(String, PathBuf)>,+) -> BoxliteResult<MountedVolumes> {+ // The guard owns installed mounts before the fallible registry lock.+ // Until publication succeeds, it owns no registry entries.+ let mut roots = ROOTS+ .lock()+ .map_err(|_| BoxliteError::Storage("Aggregate root registry is poisoned".into()))?;+ if published.iter().any(|(tag, _)| roots.contains_key(tag)) {+ drop(roots);+ return Err(BoxliteError::Storage(+ "Aggregate device tag already registered".into(),+ ));+ }+ roots.extend(published.iter().cloned());+ mounted.1 = published;+ drop(roots);+ Ok(mounted)}fn prepare_destination(target: &Path) -> BoxliteResult<()> {@@ -260,6 +312,29 @@ fn unmount(path: &Path) -> BoxliteResult<()> {mod tests {use super::*;+ #[test]+ fn initialization_guard_removes_only_its_registry_entries() {+ let tag = "rollback-registry-test".to_string();+ let root = PathBuf::from("/registry-test-root");+ ROOTS.lock().unwrap().insert(tag.clone(), root.clone());+ drop(MountedVolumes(+ Vec::new(),+ vec![(tag.clone(), root.clone())],+ ));+ assert_eq!(aggregate_root(&tag), None);+ ROOTS.lock().unwrap().insert(tag.clone(), root.clone());+ MountedVolumes(Vec::new(), vec![(tag.clone(), root.clone())]).commit();+ assert_eq!(aggregate_root(&tag), Some(root.clone()));+ let replacement = PathBuf::from("/registry-replacement");+ ROOTS+ .lock()+ .unwrap()+ .insert(tag.clone(), replacement.clone());+ drop(MountedVolumes(Vec::new(), vec![(tag.clone(), root)]));+ assert_eq!(aggregate_root(&tag), Some(replacement));+ ROOTS.lock().unwrap().remove(&tag);+ }+fn share(tag: &str, key: &str, target: &str) -> Volume {Volume {mount_point: target.into(),@@ -460,20 +535,41 @@ mod tests {std::fs::write(target.join("file"), b"guest bytes").unwrap();assert_eq!(std::fs::read(source.join("file")).unwrap(), b"guest bytes");{- let _initializing = MountedVolumes(vec![target.clone()]);+ let _initializing = MountedVolumes(vec![target.clone()], Vec::new());}assert!(!target.join("file").exists(),"later init failure drops aggregate ownership");bind(&source, &target, false).unwrap();- MountedVolumes(vec![target.clone()]).commit();+ MountedVolumes(vec![target.clone()], Vec::new()).commit();assert!(target.join("file").exists(),"successful init retains the mount");unmount(&target).unwrap();+ // Root publication failure is a later initialization failure too:+ // unwind installed mounts while keeping the existing registry entry.+ let tag = "publication-collision-test".to_string();+ let original_root = dir.path().join("registered");+ ROOTS+ .lock()+ .unwrap()+ .insert(tag.clone(), original_root.clone());+ bind(&source, &target, false).unwrap();+ assert!(publish_roots(+ MountedVolumes(vec![target.clone()], Vec::new()),+ vec![(tag.clone(), target.clone())],+ )+ .is_err());+ assert!(+ !target.join("file").exists(),+ "failed publication rolled back its binding"+ );+ assert_eq!(aggregate_root(&tag), Some(original_root));+ ROOTS.lock().unwrap().remove(&tag);+let parent = dir.path().join("parent");let child = dir.path().join("child");std::fs::create_dir_all(parent.join("nested")).unwrap();@@ -520,7 +616,7 @@ mod tests {std::fs::read(nested.join("marker")).unwrap(),b"child export");- drop(MountedVolumes(owned));+ drop(MountedVolumes(owned, Vec::new()));assert!(!nested.join("marker").exists());}diff --git a/src/guest/src/storage/attach.rs b/src/guest/src/storage/attach.rsindex 205e46eb9..7aee90deb 100644--- a/src/guest/src/storage/attach.rs+++ b/src/guest/src/storage/attach.rs@@ -1,8 +1,8 @@-//! Mount a share folder read-only into a running container.+//! Deliver a directory into a running container and detach its incarnation.//!//! The folder lives in the guest's own mount namespace, inside the Box share//! under `/run/boxlite/shared`. The agent clones it with `open_tree`, makes the-//! clone read-only with `mount_setattr`, and a child moves the clone into the+//! clone read-only when requested with `mount_setattr`, and a child moves it into the//! mount namespace of a process in the container, so every process there sees//! the folder and the agent's own namespace never changes. The container's//! root filesystem gains only the destination directory and any missing@@ -19,18 +19,22 @@//! the agent answers go, which the agent does only within [`ATTACH_DEADLINE`];//! past that the agent kills it, so a late child never mounts.+use std::collections::HashMap;use std::ffi::{CStr, CString, OsStr};use std::fs::File;use std::io;+use std::num::NonZeroU64;use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};use std::os::unix::ffi::OsStrExt;-use std::path::{Component, Path};+use std::os::unix::fs::MetadataExt;+use std::path::{Component, Path, PathBuf};use std::time::{Duration, Instant};use boxlite_shared::errors::{BoxliteError, BoxliteResult};use nix::fcntl::OFlag;use nix::libc;use nix::unistd::Pid;+use rustix::fs::StatxFlags;use super::idmap::sys;@@ -45,6 +49,7 @@ const KILL_GRACE: Duration = Duration::from_millis(500);const NR_PIDFD_SEND_SIGNAL: libc::c_long = 424;const NR_CLONE3: libc::c_long = 435;const NR_CLOSE_RANGE: libc::c_long = 436;+const NR_STATMOUNT: libc::c_long = 457;const P_PIDFD: libc::idtype_t = 3;/// Accept only an absolute path of normal components other than `/`, shorter@@ -87,6 +92,37 @@ fn bad_destination(destination: &Path) -> BoxliteError {pub(crate) struct Attacher {/// Pidfd of a killed child that had not exited yet.straggler: Option<OwnedFd>,+ runtime: HashMap<String, RuntimeMount>,+}++#[derive(Debug)]+struct RuntimeMount {+ source: PathBuf,+ destination: PathBuf,+ read_only: bool,+ namespace_id: Option<NonZeroU64>,+ // Retain the tree while it may still be published, even if confirmation was lost.+ tree: Option<MountedTree>,+}++#[derive(Debug)]+struct MountedTree {+ fd: OwnedFd,+ id: u64,+}++/// The destination must be recorded even when a move may have succeeded without a report.+#[derive(Debug)]+pub(crate) struct RuntimeAttach {+ pub(crate) added: bool,+ pub(crate) confirmation: BoxliteResult<()>,+}++#[cfg(test)]+impl RuntimeAttach {+ fn confirmed(self) -> BoxliteResult<bool> {+ self.confirmation.map(|()| self.added)+ }}/// The mount namespace of a process in the container, opened at once so the@@ -108,24 +144,279 @@ impl Target {})?;Ok(Self { pid, namespace })}++ fn namespace_id(&self) -> BoxliteResult<NonZeroU64> {+ let mut id = 0u64;+ // SAFETY: the namespace descriptor is owned and the ioctl writes one u64.+ if unsafe { libc::ioctl(self.namespace.as_raw_fd(), libc::NS_GET_MNTNS_ID, &mut id) } != 0 {+ return Err(BoxliteError::Unsupported(format!(+ "read runtime mount namespace ID: {}",+ io::Error::last_os_error()+ )));+ }+ NonZeroU64::new(id)+ .ok_or_else(|| BoxliteError::Unsupported("runtime mount namespace ID is zero".into()))+ }++ fn check_runtime_owner(&self) -> BoxliteResult<()> {+ // SAFETY: NS_GET_USERNS reads the namespace FD and returns a new FD.+ let owner = unsafe { libc::ioctl(self.namespace.as_raw_fd(), libc::NS_GET_USERNS) };+ if owner < 0 {+ return Err(BoxliteError::Unsupported(format!(+ "read runtime mount namespace owner: {}",+ io::Error::last_os_error()+ )));+ }+ // SAFETY: the successful ioctl transferred ownership of this descriptor.+ let owner = unsafe { File::from_raw_fd(owner) };+ let metadata_error =+ |error| BoxliteError::Storage(format!("read user namespace identity: {error}"));+ let owner = owner.metadata().map_err(metadata_error)?;+ let agent = std::fs::metadata("/proc/self/ns/user").map_err(metadata_error)?;+ if (owner.dev(), owner.ino()) != (agent.dev(), agent.ino()) {+ return Err(BoxliteError::Unsupported(+ "runtime mounts require a mount namespace owned by the guest agent's user namespace"+ .into(),+ ));+ }+ Ok(())+ }++ fn check_namespace(&self, recorded: Option<NonZeroU64>) -> BoxliteResult<NonZeroU64> {+ let id = self.namespace_id()?;+ if recorded != Some(id) {+ return Err(BoxliteError::InvalidState(format!(+ "mount namespace changed for container process {}",+ self.pid+ )));+ }+ Ok(id)+ }++ fn check_current_namespace(&self, id: NonZeroU64) -> BoxliteResult<()> {+ Self::open(self.pid)?.check_namespace(Some(id))?;+ Ok(())+ }}impl Attacher {- /// Bind `source` read-only at `destination` inside the mount namespace of- /// `target`. A missing destination is created; one with entries, or one- /// reached through a link, is refused. Waits at most [`ATTACH_DEADLINE`]- /// for the child to get ready (use from `spawn_blocking`).- pub(crate) fn attach_read_only(+ pub(crate) fn runtime_attached(&self, key: &str) -> bool {+ self.runtime+ .get(key)+ .is_some_and(|record| record.tree.is_some())+ }+ /// The caller holds the container's attacher write lock across the syscall+ /// and its metadata update. Tombstones outlive canceled RPC callers.+ pub(crate) fn attach_runtime(+ &mut self,+ key: &str,+ source: &Path,+ target: &Target,+ destination: &Path,+ read_only: bool,+ ) -> BoxliteResult<RuntimeAttach> {+ if let Some(record) = self.runtime.get(key) {+ if record.destination != destination+ || (record.tree.is_some()+ && (record.source != source || record.read_only != read_only))+ {+ return Err(BoxliteError::InvalidArgument(+ "mount incarnation does not match request".into(),+ ));+ }+ let Some(tree) = &record.tree else {+ return Err(BoxliteError::InvalidState(+ "mount incarnation has been detached".into(),+ ));+ };+ let namespace_id = target.check_namespace(record.namespace_id)?;+ self.check_runtime(target, destination, Mode::Verify(tree.id))?;+ target.check_current_namespace(namespace_id)?;+ return Ok(RuntimeAttach {+ added: false,+ confirmation: Ok(()),+ });+ }+ if self+ .runtime+ .values()+ .any(|record| record.tree.is_some() && record.destination == destination)+ {+ return Err(BoxliteError::InvalidState(+ "destination already has a runtime mount".into(),+ ));+ }+ target.check_runtime_owner()?;+ let namespace_id = target.namespace_id()?;+ let (tree, confirmation) =+ self.attach_tree(source, target, destination, read_only, Some(namespace_id))?;+ self.runtime.insert(+ key.to_owned(),+ RuntimeMount {+ source: source.to_owned(),+ destination: destination.to_owned(),+ read_only,+ namespace_id: Some(namespace_id),+ tree: Some(tree),+ },+ );+ Ok(RuntimeAttach {+ added: true,+ confirmation: confirmation.and_then(|()| target.check_current_namespace(namespace_id)),+ })+ }++ pub(crate) fn detach_runtime(+ &mut self,+ key: &str,+ target: &Target,+ destination: &Path,+ ) -> BoxliteResult<bool> {+ if let Some(record) = self.runtime.get(key) {+ if record.destination != destination {+ return Err(BoxliteError::InvalidArgument(+ "mount incarnation destination mismatch".into(),+ ));+ }+ if record.tree.is_none() {+ return Ok(false);+ }+ } else {+ self.runtime.insert(+ key.to_owned(),+ RuntimeMount {+ source: PathBuf::new(),+ destination: destination.to_owned(),+ read_only: false,+ namespace_id: None,+ tree: None,+ },+ );+ return Ok(false);+ }+ if self.runtime.values().any(|record| {+ record.tree.is_some()+ && record.destination != destination+ && record.destination.starts_with(destination)+ }) {+ return Err(BoxliteError::InvalidState(+ "detach runtime descendants first".into(),+ ));+ }+ let record = &self.runtime[key];+ let namespace_id = target.check_namespace(record.namespace_id)?;+ let id = record.tree.as_ref().expect("attached tree").id;+ if let Err(error) = self.check_runtime(target, destination, Mode::Detach(id)) {+ let tree = self.runtime[key].tree.as_ref().expect("attached tree");+ // A different tree at the path does not prove the original was detached.+ let absent = matches!(tree.is_mounted_in(namespace_id.get()), Ok(false));+ if !absent {+ return Err(error);+ }+ }+ // The helper's namespace FD can outlive init's membership in it.+ target.check_current_namespace(namespace_id)?;+ let record = self.runtime.get_mut(key).expect("checked incarnation");+ record.tree = None;+ Ok(true)+ }+ /// Bind `source` at `destination` inside the mount namespace of `target`.+ /// A missing destination is created; one with entries, or one reached+ /// through a link, is refused. `read_only` gates the guest bind mode:+ /// whether entries may change is still decided by the export's policy in+ /// the host backend. Waits at most [`ATTACH_DEADLINE`] for the child to+ /// get ready (use from `spawn_blocking`).+ pub(crate) fn attach(+ &mut self,+ source: &Path,+ target: &Target,+ destination: &Path,+ read_only: bool,+ ) -> BoxliteResult<()> {+ let (_, confirmation) = self.attach_tree(source, target, destination, read_only, None)?;+ confirmation+ }++ fn attach_tree(&mut self,source: &Path,target: &Target,destination: &Path,+ read_only: bool,+ runtime_namespace: Option<NonZeroU64>,+ ) -> BoxliteResult<(MountedTree, BoxliteResult<()>)> {+ validate_destination(destination)?;+ if self+ .runtime+ .values()+ .any(|record| record.tree.is_some() && record.destination.starts_with(destination))+ {+ return Err(BoxliteError::InvalidState(+ "destination would cover a runtime mount".into(),+ ));+ }+ self.reap_straggler()?;+ let fd = clone_detached(source, read_only)?;+ // A mount keeps its ID when it moves, so the installed mount is identified+ // before anything is published in the container.+ let id = mount_identity(fd.as_raw_fd()).map_err(|code| {+ BoxliteError::Storage(format!(+ "statx detached tree: {}",+ io::Error::from_raw_os_error(code)+ ))+ })?;+ let tree = MountedTree { fd, id };+ if let Some(namespace_id) = runtime_namespace {+ // Probe the recovery query against the detached tree before publishing it.+ tree.is_mounted_in(namespace_id.get()).map_err(|error| {+ BoxliteError::Unsupported(format!("runtime mount recovery unavailable: {error}"))+ })?;+ }+ let components = components(destination)?;+ let child = Child::spawn(+ &target.namespace,+ Some(&tree.fd),+ &components,+ Stall::No,+ Mode::Attach,+ )?;+ let (report, after_go) = match child.report_within(ATTACH_DEADLINE) {+ Some(report) if report.stage == Some(Stage::Ready) => (child.go(), true),+ Some(report) => {+ child.reap();+ (report, false)+ }+ None => {+ self.straggler = child.kill();+ return Err(BoxliteError::Storage(format!(+ "mount at {} in {} was not ready within {ATTACH_DEADLINE:?}; the attempt was stopped",+ destination.display(),+ target.pid+ )));+ }+ };+ if after_go && report.stage.is_none() {+ // The child has exited, but it may have moved this tree before exiting.+ return Ok((tree, report.into_result(target.pid, destination)));+ }+ report.into_result(target.pid, destination)?;+ Ok((tree, Ok(())))+ }++ /// Detach a runtime mount at `destination` from `target`'s namespace with+ /// `MNT_DETACH`: the destination leaves the mount table, descriptors+ /// opened before keep working until their last reference. The+ /// destination must exist and is never created; links refuse the walk.+ fn check_runtime(+ &mut self,+ target: &Target,+ destination: &Path,+ mode: Mode,) -> BoxliteResult<()> {validate_destination(destination)?;self.reap_straggler()?;- let tree = clone_read_only(source)?;let components = components(destination)?;- let child = Child::spawn(&target.namespace, &tree, &components, Stall::No)?;+ let child = Child::spawn(&target.namespace, None, &components, Stall::No, mode)?;let report = match child.report_within(ATTACH_DEADLINE) {Some(report) if report.stage == Some(Stage::Ready) => child.go(),Some(report) => {@@ -135,7 +426,7 @@ impl Attacher {None => {self.straggler = child.kill();return Err(BoxliteError::Storage(format!(- "mount at {} in {} was not ready within {ATTACH_DEADLINE:?}; the attempt was stopped",+ "detach of {} in {} was not ready within {ATTACH_DEADLINE:?}; the attempt was stopped",destination.display(),target.pid)));@@ -169,8 +460,10 @@ impl Drop for Attacher {}}-/// Clone `source` as a detached, read-only mount tree.-fn clone_read_only(source: &Path) -> BoxliteResult<OwnedFd> {+/// Clone `source` as a detached mount tree, optionally marked read-only.+/// A writable clone keeps the source mount's own flags; content policy for+/// read-only exports is enforced by the host backend either way.+fn clone_detached(source: &Path, read_only: bool) -> BoxliteResult<OwnedFd> {let path = c_string(source.as_os_str())?;let tree = sys::open_tree(libc::AT_FDCWD,@@ -178,7 +471,10 @@ fn clone_read_only(source: &Path) -> BoxliteResult<OwnedFd> {sys::OPEN_TREE_CLONE | sys::OPEN_TREE_CLOEXEC | sys::AT_RECURSIVE,).map_err(|error| BoxliteError::Storage(format!("clone {}: {error}", source.display())))?;- let read_only = sys::MountAttr {+ if !read_only {+ return Ok(tree);+ }+ let read_only_attr = sys::MountAttr {attr_set: sys::MOUNT_ATTR_RDONLY,attr_clr: 0,propagation: 0,@@ -188,7 +484,7 @@ fn clone_read_only(source: &Path) -> BoxliteResult<OwnedFd> {tree.as_raw_fd(),c"",sys::AT_EMPTY_PATH | sys::AT_RECURSIVE,- &read_only,+ &read_only_attr,).map_err(|error| {BoxliteError::Storage(format!("make {} read-only: {error}", source.display()))@@ -196,6 +492,66 @@ fn clone_read_only(source: &Path) -> BoxliteResult<OwnedFd> {Ok(tree)}+impl MountedTree {+ fn is_mounted_in(&self, namespace_id: u64) -> io::Result<bool> {+ // statmount takes the non-recycled ID introduced by STATX_MNT_ID_UNIQUE.+ const UNIQUE_ID: StatxFlags = StatxFlags::from_bits_retain(0x4000);+ #[repr(C)]+ struct MountIdRequest {+ size: u32,+ namespace_fd: u32,+ mount_id: u64,+ mask: u64,+ namespace_id: u64,+ }+ let request = MountIdRequest {+ size: std::mem::size_of::<MountIdRequest>() as u32,+ namespace_fd: 0,+ mount_id: statx_mount_id(self.fd.as_raw_fd(), UNIQUE_ID)+ .map_err(io::Error::from_raw_os_error)?,+ mask: 0,+ namespace_id,+ };+ let mut size = 0u32;+ // SAFETY: the request matches Linux mnt_id_req. With no fields requested,+ // statmount accepts the header's size field as the entire output buffer.+ let rc = unsafe {+ libc::syscall(+ NR_STATMOUNT,+ &request,+ &mut size,+ std::mem::size_of::<u32>(),+ 0u32,+ )+ };+ if rc == 0 {+ return Ok(true);+ }+ let error = io::Error::last_os_error();+ if error.raw_os_error() == Some(libc::ENOENT) {+ return Ok(false);+ }+ Err(error)+ }+}++/// Descriptor-based identity: of a detached clone in the agent, or of a mount point in the child.+/// STATX_MNT_ID is reusable only after the last mount reference is released.+fn mount_identity(fd: RawFd) -> Result<u64, i32> {+ statx_mount_id(fd, StatxFlags::MNT_ID)+}++fn statx_mount_id(fd: RawFd, flag: StatxFlags) -> Result<u64, i32> {+ use rustix::fs::{statx, AtFlags};+ // SAFETY: the caller keeps this descriptor alive for the syscall.+ let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(fd) };+ let stat = statx(fd, c"", AtFlags::EMPTY_PATH, flag).map_err(|error| error.raw_os_error())?;+ if !StatxFlags::from_bits_retain(stat.stx_mask).contains(flag) {+ return Err(libc::EOPNOTSUPP);+ }+ Ok(stat.stx_mnt_id)+}+/// The destination's components below `/`, prepared before the clone.fn components(destination: &Path) -> BoxliteResult<Vec<CString>> {destination@@ -210,13 +566,19 @@ fn c_string(value: &OsStr) -> BoxliteResult<CString> {.map_err(|_| BoxliteError::InvalidArgument(format!("path has a NUL byte: {:?}", value)))}-/// Whether the child blocks before it joins the namespace. Only tests block,-/// standing in for a container path that never answers.+/// Test-only interruptions of the child before readiness or after the operation.#[derive(Clone, Copy, PartialEq, Eq)]enum Stall {No,#[cfg(test)]BeforeReady,+ #[cfg(test)]+ AfterOperation,+}++#[cfg(test)]+thread_local! {+ static DROP_FINAL_REPORT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// `clone3` arguments up to `tls` (`CLONE_ARGS_SIZE_VER0`).@@ -253,19 +615,32 @@ struct Child {impl Child {fn spawn(namespace: &File,- tree: &OwnedFd,+ tree: Option<&OwnedFd>,components: &[CString],stall: Stall,+ mode: Mode,) -> BoxliteResult<Self> {+ #[cfg(test)]+ let stall = if DROP_FINAL_REPORT.take() {+ Stall::AfterOperation+ } else {+ stall+ };let pipe = || {nix::unistd::pipe2(OFlag::O_CLOEXEC).map_err(|error| BoxliteError::Storage(format!("create a pipe: {error}")))};let (reports, report_end) = pipe()?;let (go_end, go) = pipe()?;+ // A detach child never touches a tree; a duplicate of the namespace+ // fd reserves the slot so the child's descriptor set stays four wide.+ let tree = match tree {+ Some(tree) => tree.as_raw_fd(),+ None => namespace.as_raw_fd(),+ };let fds = ChildFds {namespace: namespace.as_raw_fd(),- tree: tree.as_raw_fd(),+ tree,reports: report_end.as_raw_fd(),go: go_end.as_raw_fd(),};@@ -288,7 +663,7 @@ impl Child {)};match pid {- 0 => run_child(&keep, &fds, components, stall),+ 0 => run_child(&keep, &fds, components, stall, &mode),pid if pid < 0 => Err(BoxliteError::Storage(format!("clone the attach child: {}",io::Error::last_os_error()@@ -391,9 +766,32 @@ fn reap(pidfd: &OwnedFd) {}}+/// What the cloned child does once the agent says go.+enum Mode {+ /// Move the prepared tree onto the checked mount point.+ Attach,+ /// Detach through the pinned directory, without resolving ancestors again.+ Detach(u64),+ /// Verify a retry still names the tree originally installed for its key.+ Verify(u64),+}+/// Runs in the cloned child and never returns.-fn run_child(keep: &[RawFd; 4], fds: &ChildFds, components: &[CString], stall: Stall) -> ! {- if let Some(report) = attach_in_child(keep, fds, components, stall) {+fn run_child(+ keep: &[RawFd; 4],+ fds: &ChildFds,+ components: &[CString],+ stall: Stall,+ mode: &Mode,+) -> ! {+ if let Some(report) = attach_in_child(keep, fds, components, stall, mode) {+ #[cfg(test)]+ if stall == Stall::AfterOperation+ && matches!(report.stage, Some(Stage::Attached | Stage::Detached))+ {+ // SAFETY: exit after the real system call without sending its result.+ unsafe { libc::_exit(1) }+ }report.send(fds.reports);}// SAFETY: leave without destructors or exit handlers.@@ -404,12 +802,14 @@ fn run_child(keep: &[RawFd; 4], fds: &ChildFds, components: &[CString], stall: S/// check it is empty, report ready, wait for go, attach. System calls only./// The mount goes onto the directory fd that was checked, so a container/// process cannot swap in another directory between the check and the mount.+/// The detach mode skips the empty check and unties the checked mount point./// Returns `None` when the agent gave up before go.fn attach_in_child(keep: &[RawFd; 4],fds: &ChildFds,components: &[CString],stall: Stall,+ mode: &Mode,) -> Option<Report> {let errno = || io::Error::last_os_error().raw_os_error().unwrap_or(0);// SAFETY: system calls on descriptors and buffers prepared before the clone.@@ -425,32 +825,58 @@ fn attach_in_child(if libc::setns(fds.namespace, libc::CLONE_NEWNS) != 0 {return Some(Report::new(Stage::JoinNamespace, errno()));}- let directory = match open_mount_point(components) {+ let create = matches!(mode, Mode::Attach);+ let directory = match open_mount_point(components, create) {Ok(directory) => directory,Err(report) => return Some(report),};- match has_entries(directory) {- Err(code) => return Some(Report::new(Stage::ListMountPoint, code)),- Ok(true) => return Some(Report::new(Stage::HasEntries, 0)),- Ok(false) => {}+ if matches!(mode, Mode::Attach) {+ match has_entries(directory) {+ Err(code) => return Some(Report::new(Stage::ListMountPoint, code)),+ Ok(true) => return Some(Report::new(Stage::HasEntries, 0)),+ Ok(false) => {}+ }+ }+ if let Mode::Detach(expected) | Mode::Verify(expected) = mode {+ match mount_identity(directory) {+ Ok(actual) if actual == *expected => {}+ Ok(_) => return Some(Report::new(Stage::IdentityMismatch, 0)),+ Err(code) => return Some(Report::new(Stage::Identity, code)),+ }}Report::new(Stage::Ready, 0).send(fds.reports);let mut byte = 0u8;if libc::read(fds.go, (&mut byte as *mut u8).cast(), 1) != 1 {return None;}- Some(- match sys::move_mount(- fds.tree,- c"",- directory,- c"",- sys::MOVE_MOUNT_F_EMPTY_PATH | sys::MOVE_MOUNT_T_EMPTY_PATH,- ) {- Ok(()) => Report::new(Stage::Attached, 0),- Err(error) => Report::new(Stage::Attach, error.raw_os_error().unwrap_or(0)),- },- )+ match mode {+ Mode::Attach => Some(+ match sys::move_mount(+ fds.tree,+ c"",+ directory,+ c"",+ sys::MOVE_MOUNT_F_EMPTY_PATH | sys::MOVE_MOUNT_T_EMPTY_PATH,+ ) {+ Ok(()) => Report::new(Stage::Attached, 0),+ Err(error) => Report::new(Stage::Attach, error.raw_os_error().unwrap_or(0)),+ },+ ),+ Mode::Verify(_) => Some(Report::new(Stage::Verified, 0)),+ Mode::Detach(_) => {+ // cwd pins the checked mount even if an ancestor is renamed.+ if libc::fchdir(directory) != 0 {+ return Some(Report::new(Stage::Detach, errno()));+ }+ let unmounted =+ libc::umount2(c".".as_ptr(), libc::MNT_DETACH | libc::UMOUNT_NOFOLLOW);+ if unmounted == 0 {+ Some(Report::new(Stage::Detached, 0))+ } else {+ Some(Report::new(Stage::Detach, errno()))+ }+ }+ }}}@@ -470,7 +896,7 @@ unsafe fn close_others(keep: &[RawFd; 4]) -> libc::c_long {/// Open the mount point from the container's root, creating each missing/// directory and following no link. With `O_DIRECTORY | O_NOFOLLOW` a link/// fails with `ENOTDIR` (`ELOOP` without `O_DIRECTORY`). System calls only.-unsafe fn open_mount_point(components: &[CString]) -> Result<RawFd, Report> {+unsafe fn open_mount_point(components: &[CString], create: bool) -> Result<RawFd, Report> {let errno = || io::Error::last_os_error().raw_os_error().unwrap_or(0);let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;let mut directory = libc::open(c"/".as_ptr(), flags);@@ -478,7 +904,7 @@ unsafe fn open_mount_point(components: &[CString]) -> Result<RawFd, Report> {return Err(Report::new(Stage::OpenMountPoint, errno()));}for name in components {- if libc::mkdirat(directory, name.as_ptr(), 0o755) != 0 {+ if create && libc::mkdirat(directory, name.as_ptr(), 0o755) != 0 {let code = errno();if code != libc::EEXIST {libc::close(directory);@@ -514,9 +940,14 @@ enum Stage {Ready = 7,NotDirectory = 8,CloseDescriptors = 9,+ Detached = 10,+ Detach = 11,+ Identity = 12,+ IdentityMismatch = 13,+ Verified = 14,}-const STAGES: [Stage; 10] = [+const STAGES: [Stage; 15] = [Stage::Attached,Stage::JoinNamespace,Stage::CreateMountPoint,@@ -527,6 +958,11 @@ const STAGES: [Stage; 10] = [Stage::Ready,Stage::NotDirectory,Stage::CloseDescriptors,+ Stage::Detached,+ Stage::Detach,+ Stage::Identity,+ Stage::IdentityMismatch,+ Stage::Verified,];struct Report {@@ -572,7 +1008,19 @@ impl Report {let errno = io::Error::from_raw_os_error(self.errno);let place = destination.display();match self.stage {- Some(Stage::Attached) => Ok(()),+ Some(Stage::Attached) | Some(Stage::Detached) | Some(Stage::Verified) => Ok(()),+ Some(Stage::IdentityMismatch) => Err(BoxliteError::InvalidState(format!(+ "mount identity at {place} does not match this incarnation; record retained"+ ))),+ Some(Stage::Identity) => Err(BoxliteError::Storage(format!(+ "statx mount identity at {place}: {errno}"+ ))),+ Some(Stage::Detach) => Err(BoxliteError::Storage(format!(+ "detach {place} in {target} failed at umount2: {errno}"+ ))),+ Some(Stage::OpenMountPoint) | Some(Stage::ListMountPoint) => Err(+ BoxliteError::Storage(format!("could not open {place} in {target}: {errno}")),+ ),Some(Stage::HasEntries) => Err(BoxliteError::InvalidState(format!("{place} already has entries in the container; mounting there would hide them"))),@@ -585,9 +1033,6 @@ impl Report {Some(Stage::CreateMountPoint) => {Err(BoxliteError::Storage(format!("create {place}: {errno}")))}- Some(Stage::OpenMountPoint) | Some(Stage::ListMountPoint) => {- Err(BoxliteError::Storage(format!("read {place}: {errno}")))- }Some(Stage::Attach) => Err(BoxliteError::Storage(format!("mount at {place} in {target}: {errno}"))),@@ -670,7 +1115,14 @@ mod tests {fn stalled_child() -> Child {let namespace = File::open("/proc/self/ns/mnt").unwrap();let tree = OwnedFd::from(File::open("/").unwrap());- Child::spawn(&namespace, &tree, &[], Stall::BeforeReady).unwrap()+ Child::spawn(+ &namespace,+ Some(&tree),+ &[],+ Stall::BeforeReady,+ Mode::Attach,+ )+ .unwrap()}fn child_pid(pidfd: &OwnedFd) -> Pid {@@ -712,9 +1164,8 @@ mod tests {#[test]fn an_attach_is_refused_while_an_earlier_child_still_runs() {let child = stalled_child();- let mut attacher = Attacher {- straggler: Some(child.pidfd),- };+ let mut attacher = Attacher::default();+ attacher.straggler = Some(child.pidfd);let error = attacher.reap_straggler().unwrap_err();assert!(matches!(error, BoxliteError::InvalidState(_)), "{error}");@@ -797,6 +1248,217 @@ mod tests {}}+ #[test]+ fn canceled_incarnation_never_attaches_or_detaches_another_mount() {+ let target = Target::open(nix::unistd::getpid()).unwrap();+ let mut attacher = Attacher::default();+ let destination = Path::new("/runtime-mount");+ assert!(!attacher+ .detach_runtime("canceled", &target, destination)+ .unwrap());+ assert!(!attacher+ .detach_runtime("canceled", &target, destination)+ .unwrap());+ assert!(attacher+ .attach_runtime(+ "canceled",+ Path::new("/missing"),+ &target,+ destination,+ false+ )+ .is_err());+ assert!(attacher+ .detach_runtime("canceled", &target, Path::new("/different"))+ .is_err());+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_detach_can_recover_an_unconfirmed_attachment() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("marker"), b"mounted").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("mount");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let mut attacher = Attacher::default();++ DROP_FINAL_REPORT.set(true);+ let error = attacher+ .attach_runtime("unconfirmed", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap_err();+ assert!(matches!(error, BoxliteError::Internal(_)));+ let marker = holder.view(&destination).join("marker");+ assert_eq!(fs::read(&marker).unwrap(), b"mounted");++ attacher+ .detach_runtime("unconfirmed", &target, &destination)+ .unwrap();+ assert!(!marker.exists(), "detach must remove the unconfirmed mount");+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_detach_confirms_absence_after_its_result_is_lost() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("marker"), b"mounted").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("mount");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let mut attacher = Attacher::default();++ attacher+ .attach_runtime("original", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap();+ DROP_FINAL_REPORT.set(true);+ let result = attacher.detach_runtime("original", &target, &destination);+ let marker = holder.view(&destination).join("marker");+ assert!(+ !marker.exists(),+ "the kernel has already detached the mount"+ );+ assert!(result.expect("detach must confirm that the mount is absent"));++ assert!(attacher+ .attach_runtime("replacement", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ attacher+ .detach_runtime("original", &target, &destination)+ .unwrap();+ assert_eq!(fs::read(marker).unwrap(), b"mounted");+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_detach_refuses_a_different_namespace() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("marker"), b"original").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("mount");+ let mut attacher = Attacher::default();+ {+ let original = NamespaceHolder::spawn();+ let target = Target::open(original.pid).unwrap();+ attacher+ .attach_runtime("original", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap();+ assert_eq!(+ fs::read(original.view(&destination).join("marker")).unwrap(),+ b"original"+ );+ }++ let other = NamespaceHolder::spawn();+ let target = Target::open(other.pid).unwrap();+ let result = attacher.detach_runtime("original", &target, &destination);+ assert!(+ matches!(result, Err(BoxliteError::InvalidState(_))),+ "{result:?}"+ );+ assert!(attacher.runtime_attached("original"));+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_incarnation_replay_and_replacement_are_safe() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("marker"), b"runtime").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("mount");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let mut attacher = Attacher::default();+ let blocked = root.path().join("blocked");+ fs::create_dir(&blocked).unwrap();+ fs::write(blocked.join("image"), b"preserve").unwrap();+ assert!(attacher+ .attach_runtime("failed", source.path(), &target, &blocked, false)+ .is_err());+ assert!(!attacher.runtime.contains_key("failed"));+ assert!(attacher+ .attach_runtime("old", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ assert!(!attacher+ .attach_runtime("old", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ assert!(attacher+ .attach_runtime("old", source.path(), &target, &destination, true)+ .is_err());+ assert!(attacher+ .detach_runtime("old", &target, &destination)+ .unwrap());+ assert!(!holder.view(&destination).join("marker").exists());+ assert!(attacher+ .attach_runtime("new", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ assert!(!attacher+ .detach_runtime("old", &target, &destination)+ .unwrap());+ assert_eq!(+ fs::read(holder.view(&destination).join("marker")).unwrap(),+ b"runtime"+ );+ let nested = destination.join("nested");+ assert!(attacher+ .attach_runtime("child", source.path(), &target, &nested, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ assert!(attacher+ .detach_runtime("new", &target, &destination)+ .is_err());+ assert!(attacher.runtime_attached("new"));+ assert!(attacher.detach_runtime("child", &target, &nested).unwrap());+ assert!(attacher+ .detach_runtime("new", &target, &destination)+ .unwrap());+ assert!(!holder.view(&destination).join("marker").exists());+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_detach_pins_mount_across_ancestor_rename() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("marker"), b"original").unwrap();+ let root = tempfile::tempdir().unwrap();+ let ancestor = root.path().join("parent");+ let destination = ancestor.join("mount");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let (tree, confirmation) = Attacher::default()+ .attach_tree(source.path(), &target, &destination, false, None)+ .unwrap();+ confirmation.unwrap();+ let parts = components(&destination).unwrap();+ let child = Child::spawn(+ &target.namespace,+ None,+ &parts,+ Stall::No,+ Mode::Detach(tree.id),+ )+ .unwrap();+ assert_eq!(+ child.report_within(ATTACH_DEADLINE).unwrap().stage,+ Some(Stage::Ready)+ );+ let renamed = root.path().join("renamed");+ fs::rename(&ancestor, &renamed).unwrap();+ fs::create_dir_all(&destination).unwrap();+ fs::write(destination.join("replacement"), b"keep").unwrap();+ child.go().into_result(holder.pid, &destination).unwrap();+ assert!(!holder.view(&renamed.join("mount")).join("marker").exists());+ assert_eq!(fs::read(destination.join("replacement")).unwrap(), b"keep");+ }+#[test]#[ignore = "needs root in a private mount namespace: make test:guest-perms"]fn privileged_attached_folder_is_read_only_and_only_in_the_target_namespace() {@@ -807,10 +1469,11 @@ mod tests {let holder = NamespaceHolder::spawn();Attacher::default()- .attach_read_only(+ .attach(source.path(),&Target::open(holder.pid).unwrap(),&destination,+ true,).unwrap();@@ -833,10 +1496,11 @@ mod tests {let holder = NamespaceHolder::spawn();let error = Attacher::default()- .attach_read_only(+ .attach(source.path(),&Target::open(holder.pid).unwrap(),destination.path(),+ true,).unwrap_err();@@ -860,10 +1524,11 @@ mod tests {let holder = NamespaceHolder::spawn();let error = Attacher::default()- .attach_read_only(+ .attach(source.path(),&Target::open(holder.pid).unwrap(),&root.path().join("opt/agents"),+ true,).unwrap_err();@@ -874,6 +1539,165 @@ mod tests {);}+ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_writable_attach_allows_writes_until_detached() {+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("agent"), b"agent-bytes").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("opt/boxlite/late");+ let holder = NamespaceHolder::spawn();+ let mut attacher = Attacher::default();+ let target = Target::open(holder.pid).unwrap();++ // A writable delivery binds writable: writes land on the host source.+ attacher+ .attach_runtime("rw", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap();+ let seen = holder.view(&destination);+ fs::write(seen.join("written"), b"container bytes").unwrap();+ assert_eq!(+ fs::read(source.path().join("written")).unwrap(),+ b"container bytes"+ );++ // The detach unties the name in the container namespace; the agent+ // view shows the empty destination directory again.+ attacher+ .detach_runtime("rw", &target, &destination)+ .unwrap();+ assert_eq!(+ fs::read_dir(&destination).unwrap().count(),+ 0,+ "detached in the holder namespace"+ );+ // The same path accepts a fresh delivery, and its read-only mode+ // refuses writes through the bind.+ attacher+ .attach(source.path(), &target, &destination, true)+ .unwrap();+ let seen = holder.view(&destination);+ assert_eq!(fs::read(seen.join("agent")).unwrap(), b"agent-bytes");+ let write = fs::write(seen.join("no"), b"x").unwrap_err();+ assert_eq!(write.raw_os_error(), Some(libc::EROFS));+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_detach_of_an_absent_destination_creates_nothing() {+ let root = tempfile::tempdir().unwrap();+ let holder = NamespaceHolder::spawn();+ let mut attacher = Attacher::default();+ let target = Target::open(holder.pid).unwrap();++ let error = attacher+ .check_runtime(&target, &root.path().join("absent"), Mode::Detach(u64::MAX))+ .unwrap_err();+ assert!(matches!(error, BoxliteError::Storage(_)), "{error}");+ assert!(+ !root.path().join("absent").exists(),+ "a failed detach must not create the destination"+ );+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_lazy_detach_keeps_open_descriptors_readable() {+ use std::io::Read as _;+ let source = tempfile::tempdir().unwrap();+ fs::write(source.path().join("payload"), b"still readable").unwrap();+ let root = tempfile::tempdir().unwrap();+ let destination = root.path().join("mounted");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let mut attacher = Attacher::default();+ attacher+ .attach_runtime("open", source.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap();+ let mut descriptor = File::open(holder.view(&destination).join("payload")).unwrap();+ let directory = File::open(holder.view(&destination)).unwrap();+ assert!(attacher+ .detach_runtime("open", &target, &destination)+ .unwrap());+ let mut content = Vec::new();+ descriptor.read_to_end(&mut content).unwrap();+ assert_eq!(content, b"still readable");+ let through_directory = PathBuf::from(format!("/proc/self/fd/{}", directory.as_raw_fd()));+ assert_eq!(+ fs::read(through_directory.join("payload")).unwrap(),+ b"still readable"+ );+ assert!(!holder.view(&destination).join("payload").exists());+ }++ #[test]+ #[ignore = "needs root in a private mount namespace: make test:guest-perms"]+ fn privileged_incarnation_rejects_renamed_and_replaced_destination() {+ let original = tempfile::tempdir().unwrap();+ let replacement = tempfile::tempdir().unwrap();+ fs::write(original.path().join("marker"), b"original").unwrap();+ fs::write(replacement.path().join("marker"), b"replacement").unwrap();+ let root = tempfile::tempdir().unwrap();+ let ancestor = root.path().join("parent");+ let renamed = root.path().join("renamed");+ let destination = ancestor.join("mount");+ let holder = NamespaceHolder::spawn();+ let target = Target::open(holder.pid).unwrap();+ let mut attacher = Attacher::default();+ assert!(attacher+ .attach_runtime("original", original.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ let id = attacher.runtime["original"].tree.as_ref().unwrap().id;+ let mounted = File::open(holder.view(&destination)).unwrap();+ assert_eq!(+ mount_identity(mounted.as_raw_fd()).unwrap(),+ id,+ "the retained clone must identify the installed mount, not the underlying directory"+ );+ fs::rename(&ancestor, &renamed).unwrap();+ // A different attacher models a mount installed outside this registry.+ let (replacement_tree, confirmation) = Attacher::default()+ .attach_tree(replacement.path(), &target, &destination, false, None)+ .unwrap();+ confirmation.unwrap();+ assert_ne!(replacement_tree.id, id);+ for result in [+ attacher.detach_runtime("original", &target, &destination),+ attacher+ .attach_runtime("original", original.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed),+ ] {+ assert!(matches!(result, Err(BoxliteError::InvalidState(_))));+ }+ assert!(attacher.runtime_attached("original"));+ assert_eq!(+ fs::read(holder.view(&destination).join("marker")).unwrap(),+ b"replacement"+ );+ assert_eq!(+ fs::read(holder.view(&renamed.join("mount")).join("marker")).unwrap(),+ b"original"+ );+ // Restore the name to show a rejected detach retained enough identity+ // and state to detach the original later.+ Attacher::default()+ .check_runtime(&target, &destination, Mode::Detach(replacement_tree.id))+ .unwrap();+ fs::remove_dir_all(&ancestor).unwrap();+ fs::rename(&renamed, &ancestor).unwrap();+ assert!(!attacher+ .attach_runtime("original", original.path(), &target, &destination, false)+ .and_then(RuntimeAttach::confirmed)+ .unwrap());+ assert!(attacher+ .detach_runtime("original", &target, &destination)+ .unwrap());+ assert!(!holder.view(&destination).join("marker").exists());+ }+#[test]#[ignore = "needs root in a private mount namespace: make test:guest-perms"]fn privileged_child_stopped_before_go_mounts_nothing_and_holds_no_exec_stdin() {@@ -885,10 +1709,17 @@ mod tests {// Stands in for the stdin write end the agent holds for an exec.let (stdin_read, stdin_write) = nix::unistd::pipe2(OFlag::O_CLOEXEC).unwrap();let target = Target::open(holder.pid).unwrap();- let tree = clone_read_only(source.path()).unwrap();+ let tree = clone_detached(source.path(), true).unwrap();let components = components(&destination).unwrap();- let child = Child::spawn(&target.namespace, &tree, &components, Stall::No).unwrap();+ let child = Child::spawn(+ &target.namespace,+ Some(&tree),+ &components,+ Stall::No,+ Mode::Attach,+ )+ .unwrap();let ready = child.report_within(Duration::from_secs(10)).unwrap();assert_eq!(ready.stage, Some(Stage::Ready));diff --git a/src/guest/src/storage/mod.rs b/src/guest/src/storage/mod.rsindex a5b9a463a..5f747ccdf 100644--- a/src/guest/src/storage/mod.rs+++ b/src/guest/src/storage/mod.rs@@ -15,5 +15,6 @@ pub(crate) mod resolved_mount;mod virtiofs;mod volume;+pub(crate) use aggregate::aggregate_root;pub(crate) use aggregate::mount_volumes as mount_initial_volumes;pub use volume::mount_volumes;diff --git a/src/shared/proto/boxlite/v1/service.proto b/src/shared/proto/boxlite/v1/service.protoindex 5fd65f258..895e8a7d9 100644--- a/src/shared/proto/boxlite/v1/service.proto+++ b/src/shared/proto/boxlite/v1/service.proto@@ -24,9 +24,15 @@ service Container {rpc Start(ContainerStartRequest) returns (ContainerStartResponse);// Bind a folder of the container's share into the running container,- // read-only, without restarting it. The mount joins the container's own- // mount namespace, so every process in it sees the folder.+ // without restarting it. Legacy share delivery is read-only; aggregate+ // exports carry their mode and unique incarnation. The mount joins the+ // container's own mount namespace, so every process there sees it.rpc Mount(ContainerMountRequest) returns (ContainerMountResponse);++ // Detach a runtime-mounted directory with MNT_DETACH: the destination+ // leaves the container's mount table while file descriptors opened before+ // the detach keep working. Runtime directory delivery only.+ rpc Detach(ContainerDetachRequest) returns (ContainerDetachResponse);}// Guest agent management@@ -368,16 +374,35 @@ message ContainerMountRequest {string container_id = 1;// Folder name in this container's share, one path component, never a path:// /run/boxlite/shared/containers/{container_id}/volumes/{source}+ // Only for legacy share delivery; aggregate delivery leaves it empty.string source = 2;// Absolute path inside the container. Missing directories are created; one// that has entries is refused, so no image content is hidden.string destination = 3;- // Must be true: writable mounts are refused.+ // Legacy delivery must set it. Aggregate delivery uses it as the guest+ // bind mode only: whether the container may write the entries is decided+ // by the export's read-only policy in the host backend.bool read_only = 4;+ // Aggregate delivery (M6): the export key beneath the aggregate root+ // registered for device_tag. One path component, never a path; when set,+ // source must be empty.+ string export_key = 5;+ // The virtio-fs device whose aggregate root holds the export.+ string device_tag = 6;}message ContainerMountResponse {}+message ContainerDetachRequest {+ string container_id = 1;+ // Absolute path inside the container of a runtime-mounted directory.+ string destination = 2;+ // Runtime mount incarnation; retries never detach a replacement.+ string export_key = 3;+}++message ContainerDetachResponse {}+message ContainerStartResponse {oneof result {ContainerStartSuccess success = 1;diff --git a/src/vmm/README.md b/src/vmm/README.mdindex 247057202..2bd0f15fd 100644--- a/src/vmm/README.md+++ b/src/vmm/README.md@@ -46,8 +46,9 @@ boxlite-vmmThe Linux x86_64 native engine composes disks, reporting balloon, aggregatevirtio-fs, Unix-backed vsock, gvproxy stream networking and virtio-console.-The adapter maps the runtime specification into `VmConfig`; optional devices-are omitted when not requested.+The adapter maps the runtime specification into `VmConfig`. It creates an+empty aggregate filesystem when there are no initial shares, so directory+delivery remains available after boot. Network and vsock remain optional.The aggregate virtio-fs device is runtime-extensible: `insert_aggregate`publishes a live device by tag when it enters the transport, and@@ -77,6 +78,59 @@ Neither new crate depends on `boxlite-shared`; the release workflow publishes`boxlite-hypervisor`, then `boxlite-vmm`, before `boxlite`, now that the engineadapter depends on `boxlite-vmm`.+## Host directory delivery++On Linux x86_64 native Boxes, the host delivers directory descriptors to the+shim on `vmm.sock`. The host-only socket uses mode `0600`. Mount requests also+check the peer UID. Each connection carries one version 1 request and reply,+with a four-byte little-endian length and up to 64 KiB of JSON. Registration+accepts one directory FD via `SCM_RIGHTS`. Guest RPCs use `box.sock`.++```mermaid+sequenceDiagram+ participant Host as Host client+ participant Shim as Shim on vmm.sock+ participant FS as Aggregate virtio-fs+ participant Guest as Guest agent on box.sock+ Host->>Shim: Register with directory FD+ Shim->>FS: Publish directory export+ Shim-->>Host: Preparing record+ Host->>Guest: Mount(export key, device tag, destination, mode)+ Guest-->>Host: Mount complete+ Host->>Shim: Set state Mounted+```++Registration reserves a target, allocates an export identity, and publishes a+`Preparing` record before replying. A new connection can query the record if+the reply is lost. List admission accounts for serialized JSON bytes,+including escaping and later state changes.++The kernel queues connections for the serial control thread. The client has+one deadline for connect, queue wait, and I/O, including time behind a disk+resize. The frame reader owns received descriptors before validating the+request, so rejection releases them.++Aggregate Mount and Detach reject containers whose capability bounding set+includes `CAP_SYS_ADMIN`, before any namespace or mount mutation. The configured+capabilities are preserved; ordinary containers retain directory delivery.++Guest `Mount` resolves the export beneath the mounted aggregate root and binds+it into the running container namespace. `Detach` lazily unmounts only the+matching export incarnation and actual kernel mount identity. Open file and+directory references survive detach; repeating an old detach does not remove a+replacement. Descendant mounts must be detached first. A detach received before+its corresponding mount retains a tombstone that rejects that delayed mount.++Run `make test:unit:rust FILTER=vmm_socket` for frame and record checks.+Run `make test:integration:vmm:mount-delivery` with a compatible `VMM_KERNEL`+to register, attach, and retire a directory through the native shim and guest.++The host control client is blocking and belongs in `spawn_blocking` when used+from async code. Its caller must mark an incarnation `Detaching` before requesting+guest detach, acknowledge that detach before retiring the export, and retain recovery ownership when outcomes+are uncertain. The public `box.mounts()` facade and runtime transaction+coordinator are a separate layer above these delivery primitives.+## Virtio network device`devices::net::Net::new(socket_path, mac)` implements an internal RX/TX queue