diff --git a/nvx-rs/README.md b/nvx-rs/README.md index 6385fe54c..6bc521ddb 100644 --- a/nvx-rs/README.md +++ b/nvx-rs/README.md @@ -135,7 +135,7 @@ changes only when the module's purpose does. | [`nvx::host::session`, `platform`, `report`](#nvxhostsession-platform-report) | The authenticated control session, Linux and Windows primitives, and OpenVMM's outcome report | | [`nvx::host::sandbox`](#nvxhostsandbox) | The launch profile of `nvx-rs sandbox`: its plans, live shares, option checks, bindings, and prepared launches | | [`nvx::guest`](#nvxguest) | The programs that run in Linux guests; see [Guest binaries](#guest-binaries) | -| [`nvx::guest::mappings`](#nvxguestmappings) | `Mapper` and `MappingTable`: apply host mappings beneath the descriptors of their roots, and a host's mapping table, for any guest init or agent | +| [`nvx::guest::mappings`](#nvxguestmappings) | `Mapping` and `MappingTable`: host mappings, and the account of a host's mapping table, for any guest init or agent | | [`nvx::guest::nvxs`](#nvxguestnvxs) | `GuestConnection`: the guest's role of the NVXS session over a byte stream, such as the control console | | [`nvx::guest::terminal`](#nvxguestterminal) | `Terminal`: the terminal on which a guest agent serves its session, such as the VM's control console | | [`nvx::guest::spawn`](#nvxguestspawn) | `Command`: starts a program in a new process, for any guest init or agent | @@ -1113,6 +1113,12 @@ The programs that run in Linux guests; see [Guest binaries](#guest-binaries). ### `nvx::guest::mappings` +The mapping values, `Mapping`, `Access`, `Kind`, `InvalidMapping`, and +`MAX_PATH_BYTES`, and `MappingTable` are public. The mapper, in the hidden +`mapper` module, whose items keep their paths here, hidden too, is NVX's +internal reference code of the guest's space: unstable, and crate-private once +nothing outside NVX uses it. + `Mapper`: applies host mappings for any guest init or agent beneath the descriptor of a `TargetRoot`, the root of a mount of a whole file system, which `statmount` tells from a bind of a directory below it, such as a layered root's @@ -1415,6 +1421,9 @@ which its template captured: the runtime directory, the block devices, the timeout, the host filesystem device's virtio-fs tag, and the gateway of the template's NIC, if it has one, but waits for no device past the activation's deadline, which the adapter passes, so that the application ends by then. +`apply`, `RootTemplate`, `Applied`, `ApplyError`, `AppliedTeardownError`, and +`NetworkError` are hidden: NVX's internal reference code of the guest's space, +unstable, and crate-private once nothing outside NVX uses it. For a GPT disk, it first asks the kernel to reread the disk's partition table with `BLKRRPART`, since the kernel created the block devices of partitions for @@ -1482,7 +1491,8 @@ cloned, and formats none of them. `nvx-reseed` runs them. ### `nvx::guest::root` The operations of a layered root, for a guest init or agent, whether or not it -is PID 1. +is PID 1. The module is hidden: NVX's internal reference code of the guest's +space, unstable, and crate-private once nothing outside NVX uses it. `bootstrap`: the agent's and the workload's sibling cgroups of a `Layout`, with every process of their parent moved into the agent's, the agent's `memory.low`, @@ -1550,6 +1560,10 @@ and never power the VM off. ### `nvx::guest::gpt` +Hidden, like `nvx::guest::root`, which reads its disks through it: NVX's +internal reference code of the guest's space, unstable, and crate-private once +nothing outside NVX uses it. + `read_disk`: the partition table of a GPT disk, read and checked with `nvx::gpt`'s `Disk::read` through the disk's block device, which the caller opened, at the logical block size and size that `BLKSSZGET` and `BLKGETSIZE64` @@ -2630,10 +2644,13 @@ agent serves its session, `spawn` starts a program in a new process, `entry` has the program enter an execution's namespaces, view, root, and identity, `process` collects the status of a child that the caller names, `cgroup` places, kills, and settles the processes of an execution, `exec` drives one -program as an execution, `mappings` mounts host mappings beneath the -descriptors of the roots that its caller names, and `root` bootstraps the -guest for a layered root through `cgroup`, assembles the root, mounts live -shares and mappings in it through `mappings`, and tears it down. +program as an execution, and `mappings` describes host mappings and keeps the +account of a host's mapping table. NVX's own guest space is internal reference +code, hidden, unstable, and crate-private once nothing outside NVX uses it: +the mapper of `mappings` mounts host mappings beneath the descriptors of the +roots that its caller names, and `root` bootstraps the guest for a layered root +through `cgroup`, assembles the root, mounts live shares and mappings in it +through the mapper, and tears it down. `nvx-managed-agent` opens its control terminal, and launches, drives, collects, and settles its workloads, through them, has each sandbox workload enter its execution through `entry`, and applies its host mapping table through @@ -2648,7 +2665,7 @@ and a template's guest prepares for a capture before its root's assembly through caller's fence of workload admission, and through which each clone repairs its restore: it activates the restore's memory target, reseeds the kernel's random number generator, and finishes the restore, as `nvx-snapshot` does. -Nor is the `gpt` library a program: it reads the partition table of a GPT +Nor is the hidden `gpt` module a program: it reads the partition table of a GPT disk's block device. | Binary | Program | diff --git a/nvx-rs/public-api/linux.txt b/nvx-rs/public-api/linux.txt index e79121ac5..3bfd1226d 100644 --- a/nvx-rs/public-api/linux.txt +++ b/nvx-rs/public-api/linux.txt @@ -671,42 +671,42 @@ variant nvx::guest::clone::ActivationState::Started trait nvx::guest::clone::AdmissionFence method nvx::guest::clone::AdmissionFence::close method nvx::guest::clone::AdmissionFence::open -struct nvx::guest::clone::Applied -method nvx::guest::clone::Applied::announcer -method nvx::guest::clone::Applied::announcer_mut -method nvx::guest::clone::Applied::hostname -method nvx::guest::clone::Applied::identity -method nvx::guest::clone::Applied::into_parts -method nvx::guest::clone::Applied::machine_id -method nvx::guest::clone::Applied::proxy -method nvx::guest::clone::Applied::resolver -method nvx::guest::clone::Applied::root -method nvx::guest::clone::Applied::root_mut -method nvx::guest::clone::Applied::take_export -method nvx::guest::clone::Applied::teardown -struct nvx::guest::clone::AppliedTeardownError -method nvx::guest::clone::AppliedTeardownError::binds -method nvx::guest::clone::AppliedTeardownError::root -enum nvx::guest::clone::ApplyError -variant nvx::guest::clone::ApplyError::Account -field nvx::guest::clone::ApplyError::Account::error -field nvx::guest::clone::ApplyError::Account::teardown -variant nvx::guest::clone::ApplyError::Assembly -field nvx::guest::clone::ApplyError::Assembly::0 -variant nvx::guest::clone::ApplyError::Export -field nvx::guest::clone::ApplyError::Export::error -field nvx::guest::clone::ApplyError::Export::teardown -variant nvx::guest::clone::ApplyError::Gpt -field nvx::guest::clone::ApplyError::Gpt::0 -variant nvx::guest::clone::ApplyError::MachineId -field nvx::guest::clone::ApplyError::MachineId::error -field nvx::guest::clone::ApplyError::MachineId::teardown -variant nvx::guest::clone::ApplyError::Network -field nvx::guest::clone::ApplyError::Network::error -field nvx::guest::clone::ApplyError::Network::teardown -variant nvx::guest::clone::ApplyError::View -field nvx::guest::clone::ApplyError::View::error -field nvx::guest::clone::ApplyError::View::teardown +struct nvx::guest::clone::Applied (hidden) +method nvx::guest::clone::Applied::announcer (hidden) +method nvx::guest::clone::Applied::announcer_mut (hidden) +method nvx::guest::clone::Applied::hostname (hidden) +method nvx::guest::clone::Applied::identity (hidden) +method nvx::guest::clone::Applied::into_parts (hidden) +method nvx::guest::clone::Applied::machine_id (hidden) +method nvx::guest::clone::Applied::proxy (hidden) +method nvx::guest::clone::Applied::resolver (hidden) +method nvx::guest::clone::Applied::root (hidden) +method nvx::guest::clone::Applied::root_mut (hidden) +method nvx::guest::clone::Applied::take_export (hidden) +method nvx::guest::clone::Applied::teardown (hidden) +struct nvx::guest::clone::AppliedTeardownError (hidden) +method nvx::guest::clone::AppliedTeardownError::binds (hidden) +method nvx::guest::clone::AppliedTeardownError::root (hidden) +enum nvx::guest::clone::ApplyError (hidden) +variant nvx::guest::clone::ApplyError::Account (hidden) +field nvx::guest::clone::ApplyError::Account::error (hidden) +field nvx::guest::clone::ApplyError::Account::teardown (hidden) +variant nvx::guest::clone::ApplyError::Assembly (hidden) +field nvx::guest::clone::ApplyError::Assembly::0 (hidden) +variant nvx::guest::clone::ApplyError::Export (hidden) +field nvx::guest::clone::ApplyError::Export::error (hidden) +field nvx::guest::clone::ApplyError::Export::teardown (hidden) +variant nvx::guest::clone::ApplyError::Gpt (hidden) +field nvx::guest::clone::ApplyError::Gpt::0 (hidden) +variant nvx::guest::clone::ApplyError::MachineId (hidden) +field nvx::guest::clone::ApplyError::MachineId::error (hidden) +field nvx::guest::clone::ApplyError::MachineId::teardown (hidden) +variant nvx::guest::clone::ApplyError::Network (hidden) +field nvx::guest::clone::ApplyError::Network::error (hidden) +field nvx::guest::clone::ApplyError::Network::teardown (hidden) +variant nvx::guest::clone::ApplyError::View (hidden) +field nvx::guest::clone::ApplyError::View::error (hidden) +field nvx::guest::clone::ApplyError::View::teardown (hidden) struct nvx::guest::clone::CaptureBarrier method nvx::guest::clone::CaptureBarrier::cancel method nvx::guest::clone::CaptureBarrier::capture @@ -747,14 +747,14 @@ const nvx::guest::clone::MOUNT_TABLE_LIMIT struct nvx::guest::clone::Mounted method nvx::guest::clone::Mounted::mount_point method nvx::guest::clone::Mounted::origin -enum nvx::guest::clone::NetworkError -variant nvx::guest::clone::NetworkError::Announcer -field nvx::guest::clone::NetworkError::Announcer::0 -variant nvx::guest::clone::NetworkError::Bind -field nvx::guest::clone::NetworkError::Bind::0 -variant nvx::guest::clone::NetworkError::Gateway -variant nvx::guest::clone::NetworkError::Write -field nvx::guest::clone::NetworkError::Write::0 +enum nvx::guest::clone::NetworkError (hidden) +variant nvx::guest::clone::NetworkError::Announcer (hidden) +field nvx::guest::clone::NetworkError::Announcer::0 (hidden) +variant nvx::guest::clone::NetworkError::Bind (hidden) +field nvx::guest::clone::NetworkError::Bind::0 (hidden) +variant nvx::guest::clone::NetworkError::Gateway (hidden) +variant nvx::guest::clone::NetworkError::Write (hidden) +field nvx::guest::clone::NetworkError::Write::0 (hidden) enum nvx::guest::clone::Origin variant nvx::guest::clone::Origin::Distro variant nvx::guest::clone::Origin::Filesystem @@ -824,14 +824,14 @@ method nvx::guest::clone::Repaired::memory struct nvx::guest::clone::Restored method nvx::guest::clone::Restored::into_parts method nvx::guest::clone::Restored::restore -struct nvx::guest::clone::RootTemplate -field nvx::guest::clone::RootTemplate::distro -field nvx::guest::clone::RootTemplate::filesystem_tag -field nvx::guest::clone::RootTemplate::gateway -field nvx::guest::clone::RootTemplate::runtime -field nvx::guest::clone::RootTemplate::scratch -field nvx::guest::clone::RootTemplate::timeout -fn nvx::guest::clone::apply +struct nvx::guest::clone::RootTemplate (hidden) +field nvx::guest::clone::RootTemplate::distro (hidden) +field nvx::guest::clone::RootTemplate::filesystem_tag (hidden) +field nvx::guest::clone::RootTemplate::gateway (hidden) +field nvx::guest::clone::RootTemplate::runtime (hidden) +field nvx::guest::clone::RootTemplate::scratch (hidden) +field nvx::guest::clone::RootTemplate::timeout (hidden) +fn nvx::guest::clone::apply (hidden) fn nvx::guest::clone::repair mod nvx::guest::console_pending (hidden) fn nvx::guest::console_pending::main (hidden) @@ -1062,15 +1062,15 @@ variant nvx::guest::exec::binding::Event::SettlementFailed field nvx::guest::exec::binding::Event::SettlementFailed::0 mod nvx::guest::exit (hidden) fn nvx::guest::exit::main (hidden) -mod nvx::guest::gpt -enum nvx::guest::gpt::DeviceError -variant nvx::guest::gpt::DeviceError::LogicalBlockSize -field nvx::guest::gpt::DeviceError::LogicalBlockSize::0 -variant nvx::guest::gpt::DeviceError::Size -field nvx::guest::gpt::DeviceError::Size::0 -variant nvx::guest::gpt::DeviceError::Table -field nvx::guest::gpt::DeviceError::Table::0 -fn nvx::guest::gpt::read_disk +mod nvx::guest::gpt (hidden) +enum nvx::guest::gpt::DeviceError (hidden) +variant nvx::guest::gpt::DeviceError::LogicalBlockSize (hidden) +field nvx::guest::gpt::DeviceError::LogicalBlockSize::0 (hidden) +variant nvx::guest::gpt::DeviceError::Size (hidden) +field nvx::guest::gpt::DeviceError::Size::0 (hidden) +variant nvx::guest::gpt::DeviceError::Table (hidden) +field nvx::guest::gpt::DeviceError::Table::0 (hidden) +fn nvx::guest::gpt::read_disk (hidden) mod nvx::guest::ingress struct nvx::guest::ingress::Announcer method nvx::guest::ingress::Announcer::id @@ -1096,9 +1096,9 @@ mod nvx::guest::mappings enum nvx::guest::mappings::Access variant nvx::guest::mappings::Access::ReadOnly variant nvx::guest::mappings::Access::ReadWrite -struct nvx::guest::mappings::ApplyError -method nvx::guest::mappings::ApplyError::entry -method nvx::guest::mappings::ApplyError::error +struct nvx::guest::mappings::ApplyError (hidden) +method nvx::guest::mappings::ApplyError::entry (hidden) +method nvx::guest::mappings::ApplyError::error (hidden) enum nvx::guest::mappings::InvalidMapping variant nvx::guest::mappings::InvalidMapping::Source variant nvx::guest::mappings::InvalidMapping::Target @@ -1106,13 +1106,13 @@ enum nvx::guest::mappings::Kind variant nvx::guest::mappings::Kind::Directory variant nvx::guest::mappings::Kind::File const nvx::guest::mappings::MAX_PATH_BYTES -struct nvx::guest::mappings::Mapper -method nvx::guest::mappings::Mapper::apply -method nvx::guest::mappings::Mapper::check -method nvx::guest::mappings::Mapper::is_latched -method nvx::guest::mappings::Mapper::new -method nvx::guest::mappings::Mapper::targets -method nvx::guest::mappings::Mapper::teardown +struct nvx::guest::mappings::Mapper (hidden) +method nvx::guest::mappings::Mapper::apply (hidden) +method nvx::guest::mappings::Mapper::check (hidden) +method nvx::guest::mappings::Mapper::is_latched (hidden) +method nvx::guest::mappings::Mapper::new (hidden) +method nvx::guest::mappings::Mapper::targets (hidden) +method nvx::guest::mappings::Mapper::teardown (hidden) struct nvx::guest::mappings::Mapping method nvx::guest::mappings::Mapping::access method nvx::guest::mappings::Mapping::kind @@ -1120,26 +1120,26 @@ method nvx::guest::mappings::Mapping::new method nvx::guest::mappings::Mapping::source method nvx::guest::mappings::Mapping::target method nvx::guest::mappings::Mapping::with_kind -enum nvx::guest::mappings::MappingError -variant nvx::guest::mappings::MappingError::Foreign -field nvx::guest::mappings::MappingError::Foreign::path -variant nvx::guest::mappings::MappingError::Latched -variant nvx::guest::mappings::MappingError::Link -field nvx::guest::mappings::MappingError::Link::path -variant nvx::guest::mappings::MappingError::MountPoint -variant nvx::guest::mappings::MappingError::Moved -field nvx::guest::mappings::MappingError::Moved::mounted -variant nvx::guest::mappings::MappingError::NotDirectory -field nvx::guest::mappings::MappingError::NotDirectory::path -variant nvx::guest::mappings::MappingError::Overlap -field nvx::guest::mappings::MappingError::Overlap::mapped -variant nvx::guest::mappings::MappingError::Reserved -variant nvx::guest::mappings::MappingError::SourceKind -variant nvx::guest::mappings::MappingError::System -field nvx::guest::mappings::MappingError::System::error -field nvx::guest::mappings::MappingError::System::step -variant nvx::guest::mappings::MappingError::TargetKind -method nvx::guest::mappings::MappingError::raw_os_error +enum nvx::guest::mappings::MappingError (hidden) +variant nvx::guest::mappings::MappingError::Foreign (hidden) +field nvx::guest::mappings::MappingError::Foreign::path (hidden) +variant nvx::guest::mappings::MappingError::Latched (hidden) +variant nvx::guest::mappings::MappingError::Link (hidden) +field nvx::guest::mappings::MappingError::Link::path (hidden) +variant nvx::guest::mappings::MappingError::MountPoint (hidden) +variant nvx::guest::mappings::MappingError::Moved (hidden) +field nvx::guest::mappings::MappingError::Moved::mounted (hidden) +variant nvx::guest::mappings::MappingError::NotDirectory (hidden) +field nvx::guest::mappings::MappingError::NotDirectory::path (hidden) +variant nvx::guest::mappings::MappingError::Overlap (hidden) +field nvx::guest::mappings::MappingError::Overlap::mapped (hidden) +variant nvx::guest::mappings::MappingError::Reserved (hidden) +variant nvx::guest::mappings::MappingError::SourceKind (hidden) +variant nvx::guest::mappings::MappingError::System (hidden) +field nvx::guest::mappings::MappingError::System::error (hidden) +field nvx::guest::mappings::MappingError::System::step (hidden) +variant nvx::guest::mappings::MappingError::TargetKind (hidden) +method nvx::guest::mappings::MappingError::raw_os_error (hidden) struct nvx::guest::mappings::MappingTable method nvx::guest::mappings::MappingTable::announced method nvx::guest::mappings::MappingTable::applied @@ -1165,21 +1165,21 @@ field nvx::guest::mappings::Refusal::Mapping::error variant nvx::guest::mappings::Refusal::Order field nvx::guest::mappings::Refusal::Order::expected field nvx::guest::mappings::Refusal::Order::first -struct nvx::guest::mappings::Reserved -method nvx::guest::mappings::Reserved::container_root -method nvx::guest::mappings::Reserved::new -struct nvx::guest::mappings::SourceRoot -method nvx::guest::mappings::SourceRoot::open -enum nvx::guest::mappings::Step -variant nvx::guest::mappings::Step::Attach -variant nvx::guest::mappings::Step::Clone -variant nvx::guest::mappings::Step::Create -variant nvx::guest::mappings::Step::Locate -variant nvx::guest::mappings::Step::Restrict -variant nvx::guest::mappings::Step::Source -variant nvx::guest::mappings::Step::Status -variant nvx::guest::mappings::Step::Unmount -variant nvx::guest::mappings::Step::Walk +struct nvx::guest::mappings::Reserved (hidden) +method nvx::guest::mappings::Reserved::container_root (hidden) +method nvx::guest::mappings::Reserved::new (hidden) +struct nvx::guest::mappings::SourceRoot (hidden) +method nvx::guest::mappings::SourceRoot::open (hidden) +enum nvx::guest::mappings::Step (hidden) +variant nvx::guest::mappings::Step::Attach (hidden) +variant nvx::guest::mappings::Step::Clone (hidden) +variant nvx::guest::mappings::Step::Create (hidden) +variant nvx::guest::mappings::Step::Locate (hidden) +variant nvx::guest::mappings::Step::Restrict (hidden) +variant nvx::guest::mappings::Step::Source (hidden) +variant nvx::guest::mappings::Step::Status (hidden) +variant nvx::guest::mappings::Step::Unmount (hidden) +variant nvx::guest::mappings::Step::Walk (hidden) enum nvx::guest::mappings::TableError variant nvx::guest::mappings::TableError::Failed field nvx::guest::mappings::TableError::Failed::entry @@ -1188,15 +1188,70 @@ variant nvx::guest::mappings::TableError::Refused field nvx::guest::mappings::TableError::Refused::entry field nvx::guest::mappings::TableError::Refused::refusal method nvx::guest::mappings::TableError::entry -struct nvx::guest::mappings::TargetRoot -method nvx::guest::mappings::TargetRoot::add_mount -method nvx::guest::mappings::TargetRoot::open -struct nvx::guest::mappings::TeardownError -method nvx::guest::mappings::TeardownError::failures -struct nvx::guest::mappings::UnmountFailure -method nvx::guest::mappings::UnmountFailure::error -method nvx::guest::mappings::UnmountFailure::target -fn nvx::guest::mappings::bind +struct nvx::guest::mappings::TargetRoot (hidden) +method nvx::guest::mappings::TargetRoot::add_mount (hidden) +method nvx::guest::mappings::TargetRoot::open (hidden) +struct nvx::guest::mappings::TeardownError (hidden) +method nvx::guest::mappings::TeardownError::failures (hidden) +struct nvx::guest::mappings::UnmountFailure (hidden) +method nvx::guest::mappings::UnmountFailure::error (hidden) +method nvx::guest::mappings::UnmountFailure::target (hidden) +fn nvx::guest::mappings::bind (hidden) +mod nvx::guest::mappings::mapper (hidden) +struct nvx::guest::mappings::mapper::ApplyError (hidden) +method nvx::guest::mappings::mapper::ApplyError::entry (hidden) +method nvx::guest::mappings::mapper::ApplyError::error (hidden) +struct nvx::guest::mappings::mapper::Mapper (hidden) +method nvx::guest::mappings::mapper::Mapper::apply (hidden) +method nvx::guest::mappings::mapper::Mapper::check (hidden) +method nvx::guest::mappings::mapper::Mapper::is_latched (hidden) +method nvx::guest::mappings::mapper::Mapper::new (hidden) +method nvx::guest::mappings::mapper::Mapper::targets (hidden) +method nvx::guest::mappings::mapper::Mapper::teardown (hidden) +enum nvx::guest::mappings::mapper::MappingError (hidden) +variant nvx::guest::mappings::mapper::MappingError::Foreign (hidden) +field nvx::guest::mappings::mapper::MappingError::Foreign::path (hidden) +variant nvx::guest::mappings::mapper::MappingError::Latched (hidden) +variant nvx::guest::mappings::mapper::MappingError::Link (hidden) +field nvx::guest::mappings::mapper::MappingError::Link::path (hidden) +variant nvx::guest::mappings::mapper::MappingError::MountPoint (hidden) +variant nvx::guest::mappings::mapper::MappingError::Moved (hidden) +field nvx::guest::mappings::mapper::MappingError::Moved::mounted (hidden) +variant nvx::guest::mappings::mapper::MappingError::NotDirectory (hidden) +field nvx::guest::mappings::mapper::MappingError::NotDirectory::path (hidden) +variant nvx::guest::mappings::mapper::MappingError::Overlap (hidden) +field nvx::guest::mappings::mapper::MappingError::Overlap::mapped (hidden) +variant nvx::guest::mappings::mapper::MappingError::Reserved (hidden) +variant nvx::guest::mappings::mapper::MappingError::SourceKind (hidden) +variant nvx::guest::mappings::mapper::MappingError::System (hidden) +field nvx::guest::mappings::mapper::MappingError::System::error (hidden) +field nvx::guest::mappings::mapper::MappingError::System::step (hidden) +variant nvx::guest::mappings::mapper::MappingError::TargetKind (hidden) +method nvx::guest::mappings::mapper::MappingError::raw_os_error (hidden) +struct nvx::guest::mappings::mapper::Reserved (hidden) +method nvx::guest::mappings::mapper::Reserved::container_root (hidden) +method nvx::guest::mappings::mapper::Reserved::new (hidden) +struct nvx::guest::mappings::mapper::SourceRoot (hidden) +method nvx::guest::mappings::mapper::SourceRoot::open (hidden) +enum nvx::guest::mappings::mapper::Step (hidden) +variant nvx::guest::mappings::mapper::Step::Attach (hidden) +variant nvx::guest::mappings::mapper::Step::Clone (hidden) +variant nvx::guest::mappings::mapper::Step::Create (hidden) +variant nvx::guest::mappings::mapper::Step::Locate (hidden) +variant nvx::guest::mappings::mapper::Step::Restrict (hidden) +variant nvx::guest::mappings::mapper::Step::Source (hidden) +variant nvx::guest::mappings::mapper::Step::Status (hidden) +variant nvx::guest::mappings::mapper::Step::Unmount (hidden) +variant nvx::guest::mappings::mapper::Step::Walk (hidden) +struct nvx::guest::mappings::mapper::TargetRoot (hidden) +method nvx::guest::mappings::mapper::TargetRoot::add_mount (hidden) +method nvx::guest::mappings::mapper::TargetRoot::open (hidden) +struct nvx::guest::mappings::mapper::TeardownError (hidden) +method nvx::guest::mappings::mapper::TeardownError::failures (hidden) +struct nvx::guest::mappings::mapper::UnmountFailure (hidden) +method nvx::guest::mappings::mapper::UnmountFailure::error (hidden) +method nvx::guest::mappings::mapper::UnmountFailure::target (hidden) +fn nvx::guest::mappings::mapper::bind (hidden) mod nvx::guest::mmio_write (hidden) fn nvx::guest::mmio_write::main (hidden) mod nvx::guest::nvxs @@ -1247,221 +1302,221 @@ method nvx::guest::reseed::Seed::generation_id method nvx::guest::reseed::Seed::read fn nvx::guest::reseed::main (hidden) fn nvx::guest::reseed::reseed -mod nvx::guest::root -struct nvx::guest::root::Assembly -field nvx::guest::root::Assembly::distro -field nvx::guest::root::Assembly::image -field nvx::guest::root::Assembly::overlay -field nvx::guest::root::Assembly::runtime -field nvx::guest::root::Assembly::timeout -field nvx::guest::root::Assembly::upper -struct nvx::guest::root::AssemblyError -method nvx::guest::root::AssemblyError::cleanup -method nvx::guest::root::AssemblyError::error -method nvx::guest::root::AssemblyError::into_parts -struct nvx::guest::root::Bootstrap -method nvx::guest::root::Bootstrap::layout -method nvx::guest::root::Bootstrap::moved -method nvx::guest::root::Bootstrap::workload -enum nvx::guest::root::BootstrapStep -variant nvx::guest::root::BootstrapStep::AgentCgroup -variant nvx::guest::root::BootstrapStep::AgentMemoryLow -variant nvx::guest::root::BootstrapStep::Hierarchy -variant nvx::guest::root::BootstrapStep::Layout -variant nvx::guest::root::BootstrapStep::Placement -variant nvx::guest::root::BootstrapStep::UserNamespaces -variant nvx::guest::root::BootstrapStep::WorkloadCgroup -struct nvx::guest::root::Device -field nvx::guest::root::Device::mmio -field nvx::guest::root::Device::sectors -enum nvx::guest::root::DeviceStep -variant nvx::guest::root::DeviceStep::Access -variant nvx::guest::root::DeviceStep::Flush -variant nvx::guest::root::DeviceStep::Open -variant nvx::guest::root::DeviceStep::Reread -variant nvx::guest::root::DeviceStep::Size -variant nvx::guest::root::DeviceStep::Status -variant nvx::guest::root::DeviceStep::Superblock -enum nvx::guest::root::Error -variant nvx::guest::root::Error::Access -field nvx::guest::root::Error::Access::device -field nvx::guest::root::Error::Access::read_only -field nvx::guest::root::Error::Access::role -variant nvx::guest::root::Error::Bootstrap -field nvx::guest::root::Error::Bootstrap::error -field nvx::guest::root::Error::Bootstrap::step -variant nvx::guest::root::Error::Device -field nvx::guest::root::Error::Device::device -field nvx::guest::root::Error::Device::error -field nvx::guest::root::Error::Device::role -field nvx::guest::root::Error::Device::step -variant nvx::guest::root::Error::Disk -field nvx::guest::root::Error::Disk::device -field nvx::guest::root::Error::Disk::error -variant nvx::guest::root::Error::FirstPartition -field nvx::guest::root::Error::FirstPartition::device -field nvx::guest::root::Error::FirstPartition::error -variant nvx::guest::root::Error::Journal -field nvx::guest::root::Error::Journal::device -variant nvx::guest::root::Error::Lookup -field nvx::guest::root::Error::Lookup::error -field nvx::guest::root::Error::Lookup::mmio -field nvx::guest::root::Error::Lookup::role -variant nvx::guest::root::Error::Mapping -field nvx::guest::root::Error::Mapping::error -field nvx::guest::root::Error::Mapping::mount -variant nvx::guest::root::Error::Missing -field nvx::guest::root::Error::Missing::mmio -field nvx::guest::root::Error::Missing::role -variant nvx::guest::root::Error::Mount -field nvx::guest::root::Error::Mount::error -field nvx::guest::root::Error::Mount::mount -variant nvx::guest::root::Error::MountPoint -field nvx::guest::root::Error::MountPoint::error -field nvx::guest::root::Error::MountPoint::path -variant nvx::guest::root::Error::NotErofs -field nvx::guest::root::Error::NotErofs::device -variant nvx::guest::root::Error::NotExt4 -field nvx::guest::root::Error::NotExt4::device -variant nvx::guest::root::Error::NotExt4Layer -field nvx::guest::root::Error::NotExt4Layer::device -field nvx::guest::root::Error::NotExt4Layer::number -variant nvx::guest::root::Error::NotFresh -field nvx::guest::root::Error::NotFresh::path -variant nvx::guest::root::Error::Occupied -field nvx::guest::root::Error::Occupied::path -variant nvx::guest::root::Error::OverlayCheck -field nvx::guest::root::Error::OverlayCheck::error -field nvx::guest::root::Error::OverlayCheck::path -variant nvx::guest::root::Error::OverlayFallback -field nvx::guest::root::Error::OverlayFallback::effective -field nvx::guest::root::Error::OverlayFallback::requested -variant nvx::guest::root::Error::OverlayOptions -field nvx::guest::root::Error::OverlayOptions::length -variant nvx::guest::root::Error::Partition -field nvx::guest::root::Error::Partition::node -field nvx::guest::root::Error::Partition::number -variant nvx::guest::root::Error::Recovery -field nvx::guest::root::Error::Recovery::device -field nvx::guest::root::Error::Recovery::number -variant nvx::guest::root::Error::Reserved -field nvx::guest::root::Error::Reserved::path -variant nvx::guest::root::Error::Runtime -field nvx::guest::root::Error::Runtime::path -variant nvx::guest::root::Error::Share -field nvx::guest::root::Error::Share::0 -variant nvx::guest::root::Error::Size -field nvx::guest::root::Error::Size::actual -field nvx::guest::root::Error::Size::device -field nvx::guest::root::Error::Size::expected -field nvx::guest::root::Error::Size::role -variant nvx::guest::root::Error::Uuid -field nvx::guest::root::Error::Uuid::actual -field nvx::guest::root::Error::Uuid::expected -enum nvx::guest::root::Image -variant nvx::guest::root::Image::Erofs -field nvx::guest::root::Image::Erofs::uuid -variant nvx::guest::root::Image::Gpt -field nvx::guest::root::Image::Gpt::expected -field nvx::guest::root::Image::Gpt::first_partition_bound -enum nvx::guest::root::Journal -variant nvx::guest::root::Journal::Allowed -variant nvx::guest::root::Journal::Forbidden -struct nvx::guest::root::Lower -method nvx::guest::root::Lower::device -method nvx::guest::root::Lower::mount -method nvx::guest::root::Lower::partition -method nvx::guest::root::Lower::path -const nvx::guest::root::MOUNT_OPTIONS_LIMIT -enum nvx::guest::root::Mount -variant nvx::guest::root::Mount::Aggregate -field nvx::guest::root::Mount::Aggregate::tag -variant nvx::guest::root::Mount::Child -field nvx::guest::root::Mount::Child::name -field nvx::guest::root::Mount::Child::target -variant nvx::guest::root::Mount::Distro -variant nvx::guest::root::Mount::Export -field nvx::guest::root::Mount::Export::tag -variant nvx::guest::root::Mount::Layer -field nvx::guest::root::Mount::Layer::number -variant nvx::guest::root::Mount::Mapping -field nvx::guest::root::Mount::Mapping::target -variant nvx::guest::root::Mount::Overlay -variant nvx::guest::root::Mount::Scratch -variant nvx::guest::root::Mount::Share -field nvx::guest::root::Mount::Share::tag -field nvx::guest::root::Mount::Share::target -variant nvx::guest::root::Mount::Tmpfs -enum nvx::guest::root::OverlayMode -variant nvx::guest::root::OverlayMode::TrustedLowers -variant nvx::guest::root::OverlayMode::UntrustedLowers -method nvx::guest::root::OverlayMode::options -struct nvx::guest::root::Resources -field nvx::guest::root::Resources::agent_memory_low -field nvx::guest::root::Resources::workload_memory_max -field nvx::guest::root::Resources::workload_pids_max -enum nvx::guest::root::Role -variant nvx::guest::root::Role::Distro -variant nvx::guest::root::Role::Scratch -struct nvx::guest::root::Root -method nvx::guest::root::Root::first_partition -method nvx::guest::root::Root::is_latched -method nvx::guest::root::Root::lowers -method nvx::guest::root::Root::map -method nvx::guest::root::Root::mount_aggregate -method nvx::guest::root::Root::mount_export -method nvx::guest::root::Root::mount_share -method nvx::guest::root::Root::overlay -method nvx::guest::root::Root::path -method nvx::guest::root::Root::runtime -method nvx::guest::root::Root::teardown -method nvx::guest::root::Root::upper -struct nvx::guest::root::ShareChild -field nvx::guest::root::ShareChild::access -field nvx::guest::root::ShareChild::kind -field nvx::guest::root::ShareChild::name -field nvx::guest::root::ShareChild::target -enum nvx::guest::root::ShareKind -variant nvx::guest::root::ShareKind::Directory -variant nvx::guest::root::ShareKind::File -enum nvx::guest::root::ShareRefusal -variant nvx::guest::root::ShareRefusal::ChildName -field nvx::guest::root::ShareRefusal::ChildName::0 -variant nvx::guest::root::ShareRefusal::DuplicateChild -field nvx::guest::root::ShareRefusal::DuplicateChild::0 -variant nvx::guest::root::ShareRefusal::NoChildren -variant nvx::guest::root::ShareRefusal::NotCanonical -field nvx::guest::root::ShareRefusal::NotCanonical::0 -variant nvx::guest::root::ShareRefusal::Overlap -field nvx::guest::root::ShareRefusal::Overlap::claimed -field nvx::guest::root::ShareRefusal::Overlap::target -variant nvx::guest::root::ShareRefusal::Relative -field nvx::guest::root::ShareRefusal::Relative::0 -variant nvx::guest::root::ShareRefusal::Reserved -field nvx::guest::root::ShareRefusal::Reserved::0 -variant nvx::guest::root::ShareRefusal::ReservedCharacter -field nvx::guest::root::ShareRefusal::ReservedCharacter::0 -variant nvx::guest::root::ShareRefusal::SecondAggregate -variant nvx::guest::root::ShareRefusal::SecondExport -variant nvx::guest::root::ShareRefusal::Tag -field nvx::guest::root::ShareRefusal::Tag::0 -struct nvx::guest::root::TeardownError -method nvx::guest::root::TeardownError::failures -struct nvx::guest::root::Unmount -method nvx::guest::root::Unmount::error -method nvx::guest::root::Unmount::mount -method nvx::guest::root::Unmount::path -enum nvx::guest::root::Upper -variant nvx::guest::root::Upper::Scratch -field nvx::guest::root::Upper::Scratch::device -field nvx::guest::root::Upper::Scratch::journal -variant nvx::guest::root::Upper::Tmpfs -method nvx::guest::root::Upper::kind -enum nvx::guest::root::UpperKind -variant nvx::guest::root::UpperKind::Scratch -variant nvx::guest::root::UpperKind::Tmpfs -fn nvx::guest::root::assemble -fn nvx::guest::root::bootstrap +mod nvx::guest::root (hidden) +struct nvx::guest::root::Assembly (hidden) +field nvx::guest::root::Assembly::distro (hidden) +field nvx::guest::root::Assembly::image (hidden) +field nvx::guest::root::Assembly::overlay (hidden) +field nvx::guest::root::Assembly::runtime (hidden) +field nvx::guest::root::Assembly::timeout (hidden) +field nvx::guest::root::Assembly::upper (hidden) +struct nvx::guest::root::AssemblyError (hidden) +method nvx::guest::root::AssemblyError::cleanup (hidden) +method nvx::guest::root::AssemblyError::error (hidden) +method nvx::guest::root::AssemblyError::into_parts (hidden) +struct nvx::guest::root::Bootstrap (hidden) +method nvx::guest::root::Bootstrap::layout (hidden) +method nvx::guest::root::Bootstrap::moved (hidden) +method nvx::guest::root::Bootstrap::workload (hidden) +enum nvx::guest::root::BootstrapStep (hidden) +variant nvx::guest::root::BootstrapStep::AgentCgroup (hidden) +variant nvx::guest::root::BootstrapStep::AgentMemoryLow (hidden) +variant nvx::guest::root::BootstrapStep::Hierarchy (hidden) +variant nvx::guest::root::BootstrapStep::Layout (hidden) +variant nvx::guest::root::BootstrapStep::Placement (hidden) +variant nvx::guest::root::BootstrapStep::UserNamespaces (hidden) +variant nvx::guest::root::BootstrapStep::WorkloadCgroup (hidden) +struct nvx::guest::root::Device (hidden) +field nvx::guest::root::Device::mmio (hidden) +field nvx::guest::root::Device::sectors (hidden) +enum nvx::guest::root::DeviceStep (hidden) +variant nvx::guest::root::DeviceStep::Access (hidden) +variant nvx::guest::root::DeviceStep::Flush (hidden) +variant nvx::guest::root::DeviceStep::Open (hidden) +variant nvx::guest::root::DeviceStep::Reread (hidden) +variant nvx::guest::root::DeviceStep::Size (hidden) +variant nvx::guest::root::DeviceStep::Status (hidden) +variant nvx::guest::root::DeviceStep::Superblock (hidden) +enum nvx::guest::root::Error (hidden) +variant nvx::guest::root::Error::Access (hidden) +field nvx::guest::root::Error::Access::device (hidden) +field nvx::guest::root::Error::Access::read_only (hidden) +field nvx::guest::root::Error::Access::role (hidden) +variant nvx::guest::root::Error::Bootstrap (hidden) +field nvx::guest::root::Error::Bootstrap::error (hidden) +field nvx::guest::root::Error::Bootstrap::step (hidden) +variant nvx::guest::root::Error::Device (hidden) +field nvx::guest::root::Error::Device::device (hidden) +field nvx::guest::root::Error::Device::error (hidden) +field nvx::guest::root::Error::Device::role (hidden) +field nvx::guest::root::Error::Device::step (hidden) +variant nvx::guest::root::Error::Disk (hidden) +field nvx::guest::root::Error::Disk::device (hidden) +field nvx::guest::root::Error::Disk::error (hidden) +variant nvx::guest::root::Error::FirstPartition (hidden) +field nvx::guest::root::Error::FirstPartition::device (hidden) +field nvx::guest::root::Error::FirstPartition::error (hidden) +variant nvx::guest::root::Error::Journal (hidden) +field nvx::guest::root::Error::Journal::device (hidden) +variant nvx::guest::root::Error::Lookup (hidden) +field nvx::guest::root::Error::Lookup::error (hidden) +field nvx::guest::root::Error::Lookup::mmio (hidden) +field nvx::guest::root::Error::Lookup::role (hidden) +variant nvx::guest::root::Error::Mapping (hidden) +field nvx::guest::root::Error::Mapping::error (hidden) +field nvx::guest::root::Error::Mapping::mount (hidden) +variant nvx::guest::root::Error::Missing (hidden) +field nvx::guest::root::Error::Missing::mmio (hidden) +field nvx::guest::root::Error::Missing::role (hidden) +variant nvx::guest::root::Error::Mount (hidden) +field nvx::guest::root::Error::Mount::error (hidden) +field nvx::guest::root::Error::Mount::mount (hidden) +variant nvx::guest::root::Error::MountPoint (hidden) +field nvx::guest::root::Error::MountPoint::error (hidden) +field nvx::guest::root::Error::MountPoint::path (hidden) +variant nvx::guest::root::Error::NotErofs (hidden) +field nvx::guest::root::Error::NotErofs::device (hidden) +variant nvx::guest::root::Error::NotExt4 (hidden) +field nvx::guest::root::Error::NotExt4::device (hidden) +variant nvx::guest::root::Error::NotExt4Layer (hidden) +field nvx::guest::root::Error::NotExt4Layer::device (hidden) +field nvx::guest::root::Error::NotExt4Layer::number (hidden) +variant nvx::guest::root::Error::NotFresh (hidden) +field nvx::guest::root::Error::NotFresh::path (hidden) +variant nvx::guest::root::Error::Occupied (hidden) +field nvx::guest::root::Error::Occupied::path (hidden) +variant nvx::guest::root::Error::OverlayCheck (hidden) +field nvx::guest::root::Error::OverlayCheck::error (hidden) +field nvx::guest::root::Error::OverlayCheck::path (hidden) +variant nvx::guest::root::Error::OverlayFallback (hidden) +field nvx::guest::root::Error::OverlayFallback::effective (hidden) +field nvx::guest::root::Error::OverlayFallback::requested (hidden) +variant nvx::guest::root::Error::OverlayOptions (hidden) +field nvx::guest::root::Error::OverlayOptions::length (hidden) +variant nvx::guest::root::Error::Partition (hidden) +field nvx::guest::root::Error::Partition::node (hidden) +field nvx::guest::root::Error::Partition::number (hidden) +variant nvx::guest::root::Error::Recovery (hidden) +field nvx::guest::root::Error::Recovery::device (hidden) +field nvx::guest::root::Error::Recovery::number (hidden) +variant nvx::guest::root::Error::Reserved (hidden) +field nvx::guest::root::Error::Reserved::path (hidden) +variant nvx::guest::root::Error::Runtime (hidden) +field nvx::guest::root::Error::Runtime::path (hidden) +variant nvx::guest::root::Error::Share (hidden) +field nvx::guest::root::Error::Share::0 (hidden) +variant nvx::guest::root::Error::Size (hidden) +field nvx::guest::root::Error::Size::actual (hidden) +field nvx::guest::root::Error::Size::device (hidden) +field nvx::guest::root::Error::Size::expected (hidden) +field nvx::guest::root::Error::Size::role (hidden) +variant nvx::guest::root::Error::Uuid (hidden) +field nvx::guest::root::Error::Uuid::actual (hidden) +field nvx::guest::root::Error::Uuid::expected (hidden) +enum nvx::guest::root::Image (hidden) +variant nvx::guest::root::Image::Erofs (hidden) +field nvx::guest::root::Image::Erofs::uuid (hidden) +variant nvx::guest::root::Image::Gpt (hidden) +field nvx::guest::root::Image::Gpt::expected (hidden) +field nvx::guest::root::Image::Gpt::first_partition_bound (hidden) +enum nvx::guest::root::Journal (hidden) +variant nvx::guest::root::Journal::Allowed (hidden) +variant nvx::guest::root::Journal::Forbidden (hidden) +struct nvx::guest::root::Lower (hidden) +method nvx::guest::root::Lower::device (hidden) +method nvx::guest::root::Lower::mount (hidden) +method nvx::guest::root::Lower::partition (hidden) +method nvx::guest::root::Lower::path (hidden) +const nvx::guest::root::MOUNT_OPTIONS_LIMIT (hidden) +enum nvx::guest::root::Mount (hidden) +variant nvx::guest::root::Mount::Aggregate (hidden) +field nvx::guest::root::Mount::Aggregate::tag (hidden) +variant nvx::guest::root::Mount::Child (hidden) +field nvx::guest::root::Mount::Child::name (hidden) +field nvx::guest::root::Mount::Child::target (hidden) +variant nvx::guest::root::Mount::Distro (hidden) +variant nvx::guest::root::Mount::Export (hidden) +field nvx::guest::root::Mount::Export::tag (hidden) +variant nvx::guest::root::Mount::Layer (hidden) +field nvx::guest::root::Mount::Layer::number (hidden) +variant nvx::guest::root::Mount::Mapping (hidden) +field nvx::guest::root::Mount::Mapping::target (hidden) +variant nvx::guest::root::Mount::Overlay (hidden) +variant nvx::guest::root::Mount::Scratch (hidden) +variant nvx::guest::root::Mount::Share (hidden) +field nvx::guest::root::Mount::Share::tag (hidden) +field nvx::guest::root::Mount::Share::target (hidden) +variant nvx::guest::root::Mount::Tmpfs (hidden) +enum nvx::guest::root::OverlayMode (hidden) +variant nvx::guest::root::OverlayMode::TrustedLowers (hidden) +variant nvx::guest::root::OverlayMode::UntrustedLowers (hidden) +method nvx::guest::root::OverlayMode::options (hidden) +struct nvx::guest::root::Resources (hidden) +field nvx::guest::root::Resources::agent_memory_low (hidden) +field nvx::guest::root::Resources::workload_memory_max (hidden) +field nvx::guest::root::Resources::workload_pids_max (hidden) +enum nvx::guest::root::Role (hidden) +variant nvx::guest::root::Role::Distro (hidden) +variant nvx::guest::root::Role::Scratch (hidden) +struct nvx::guest::root::Root (hidden) +method nvx::guest::root::Root::first_partition (hidden) +method nvx::guest::root::Root::is_latched (hidden) +method nvx::guest::root::Root::lowers (hidden) +method nvx::guest::root::Root::map (hidden) +method nvx::guest::root::Root::mount_aggregate (hidden) +method nvx::guest::root::Root::mount_export (hidden) +method nvx::guest::root::Root::mount_share (hidden) +method nvx::guest::root::Root::overlay (hidden) +method nvx::guest::root::Root::path (hidden) +method nvx::guest::root::Root::runtime (hidden) +method nvx::guest::root::Root::teardown (hidden) +method nvx::guest::root::Root::upper (hidden) +struct nvx::guest::root::ShareChild (hidden) +field nvx::guest::root::ShareChild::access (hidden) +field nvx::guest::root::ShareChild::kind (hidden) +field nvx::guest::root::ShareChild::name (hidden) +field nvx::guest::root::ShareChild::target (hidden) +enum nvx::guest::root::ShareKind (hidden) +variant nvx::guest::root::ShareKind::Directory (hidden) +variant nvx::guest::root::ShareKind::File (hidden) +enum nvx::guest::root::ShareRefusal (hidden) +variant nvx::guest::root::ShareRefusal::ChildName (hidden) +field nvx::guest::root::ShareRefusal::ChildName::0 (hidden) +variant nvx::guest::root::ShareRefusal::DuplicateChild (hidden) +field nvx::guest::root::ShareRefusal::DuplicateChild::0 (hidden) +variant nvx::guest::root::ShareRefusal::NoChildren (hidden) +variant nvx::guest::root::ShareRefusal::NotCanonical (hidden) +field nvx::guest::root::ShareRefusal::NotCanonical::0 (hidden) +variant nvx::guest::root::ShareRefusal::Overlap (hidden) +field nvx::guest::root::ShareRefusal::Overlap::claimed (hidden) +field nvx::guest::root::ShareRefusal::Overlap::target (hidden) +variant nvx::guest::root::ShareRefusal::Relative (hidden) +field nvx::guest::root::ShareRefusal::Relative::0 (hidden) +variant nvx::guest::root::ShareRefusal::Reserved (hidden) +field nvx::guest::root::ShareRefusal::Reserved::0 (hidden) +variant nvx::guest::root::ShareRefusal::ReservedCharacter (hidden) +field nvx::guest::root::ShareRefusal::ReservedCharacter::0 (hidden) +variant nvx::guest::root::ShareRefusal::SecondAggregate (hidden) +variant nvx::guest::root::ShareRefusal::SecondExport (hidden) +variant nvx::guest::root::ShareRefusal::Tag (hidden) +field nvx::guest::root::ShareRefusal::Tag::0 (hidden) +struct nvx::guest::root::TeardownError (hidden) +method nvx::guest::root::TeardownError::failures (hidden) +struct nvx::guest::root::Unmount (hidden) +method nvx::guest::root::Unmount::error (hidden) +method nvx::guest::root::Unmount::mount (hidden) +method nvx::guest::root::Unmount::path (hidden) +enum nvx::guest::root::Upper (hidden) +variant nvx::guest::root::Upper::Scratch (hidden) +field nvx::guest::root::Upper::Scratch::device (hidden) +field nvx::guest::root::Upper::Scratch::journal (hidden) +variant nvx::guest::root::Upper::Tmpfs (hidden) +method nvx::guest::root::Upper::kind (hidden) +enum nvx::guest::root::UpperKind (hidden) +variant nvx::guest::root::UpperKind::Scratch (hidden) +variant nvx::guest::root::UpperKind::Tmpfs (hidden) +fn nvx::guest::root::assemble (hidden) +fn nvx::guest::root::bootstrap (hidden) mod nvx::guest::spawn struct nvx::guest::spawn::Barrier method nvx::guest::spawn::Barrier::release diff --git a/nvx-rs/src/guest/clone.rs b/nvx-rs/src/guest/clone.rs index caf0a354d..48c82c908 100644 --- a/nvx-rs/src/guest/clone.rs +++ b/nvx-rs/src/guest/clone.rs @@ -122,7 +122,7 @@ //! memory size that the repair reports, before anything has a side effect. An Activate whose //! record the adapter's framing refused unread, as longer than a record can be, fails as a //! record that long does; -//! 3. activating: the adapter applies the accepted record with [`apply`](fn@apply), which +//! 3. activating: the adapter applies the accepted record with `apply`, which //! activates the root and the workload with its settings, as below, passes the activation //! what the session received meanwhile, which came before Ready, then reports the result to //! [`Activation::complete`]; @@ -146,12 +146,16 @@ //! and its [`ActivationCause`], and which every later call returns again. The activation never //! powers the VM off: the adapter reports the failure, and ends the VM. //! -//! [`apply`](fn@apply) activates the clone as at a cold boot. It assembles the root as -//! [`root::assemble`] does, with the record's image, an EROFS image whose UUID it checks if the +//! The activation's application, `apply` and its types, is NVX's internal reference code of the +//! guest's space, hidden from this documentation and unstable: it becomes crate-private once +//! nothing outside NVX uses it. +//! +//! `apply` activates the clone as at a cold boot. It assembles the root as +//! `root::assemble` does, with the record's image, an EROFS image whose UUID it checks if the //! record expects one, or a GPT disk whose GUID it checks if the record expects one, its upper, a //! tmpfs or the scratch, with the record's journal policy, and its overlay mode, and with the //! inputs that the guest takes from its own configuration, which its template captured, a -//! [`RootTemplate`]: the runtime directory, the block devices, the host filesystem device's +//! `RootTemplate`: the runtime directory, the block devices, the host filesystem device's //! virtio-fs tag, the gateway of the template's NIC, if it has one, and how long the assembly waits //! for each block device, but never past the activation's deadline, which the adapter passes, so //! that the application ends by then. For a GPT disk, it first asks the kernel to reread the disk's @@ -171,7 +175,7 @@ //! [`MachineId::generate`](super::entry::MachineId::generate), after the repair's reseed, so that //! no two clones of a template share it, to [`MACHINE_ID_FILE`] in the template's runtime //! directory. If the record has an export, it mounts the host export through the template's -//! filesystem device, with [`Root::mount_export`](root::Root::mount_export), read-write, at +//! filesystem device, with `Root::mount_export`, read-write, at //! `hostfs/root` in the runtime directory, outside the root, where only the guest's root user //! reaches it: the record names no mode, and OpenVMM limits each of the export's children to its //! own access. If the record's network names a DNS server, it writes a resolver file that names @@ -184,14 +188,14 @@ //! the generated machine ID's file, read-only over the root's `/etc/machine-id`, and the //! resolver file, read-only over the root's `/etc/resolv.conf`, or, with neither, nothing. The //! entry checks the record's hostname first, which every execution's entry then takes. It returns -//! the [`Applied`] root and workload, which the adapter keeps, with the export's root, from which +//! the `Applied` root and workload, which the adapter keeps, with the export's root, from which //! the adapter maps the host's mapping table once the clone is ready, the network's proxy //! endpoint, which the adapter tells its workloads as at a cold boot, and the announcer, which the //! adapter watches, and must end the clone once the announcer ended: the gateway then keeps //! publishing the listeners that the announcer last announced until the VM ends, and learns of no -//! later change of them. The [`teardown`](Applied::teardown) of the [`Applied`] stops the +//! later change of them. The `teardown` of the `Applied` stops the //! announcer, closes the export's root, and removes the binds before it tears the root down. An -//! application that fails returns an [`ApplyError`] instead, after which nothing that it mounted or +//! application that fails returns an `ApplyError` instead, after which nothing that it mounted or //! bound stays mounted, unless the error holds the unmounts that failed, and no announcer that it //! started runs. //! @@ -276,12 +280,12 @@ //! as [strict mode](#strict-mode) tells, they never power the VM off, so a caller that is not //! PID 1 keeps its own reaping, transport, and shutdown. The activation needs no privilege, and //! makes no system call: of the clone, it changes only the caller's fence, which it opens. Its -//! application, [`apply`](fn@apply), needs the guest's root user, in the guest's initial mount -//! namespace, as [`root::assemble`] does: for a GPT disk, it asks the kernel to reread the disk's +//! application, `apply`, needs the guest's root user, in the guest's initial mount +//! namespace, as `root::assemble` does: for a GPT disk, it asks the kernel to reread the disk's //! partition table, which needs `CAP_SYS_ADMIN`; it mounts the root, reads the account databases //! below it, and, if it fails, tears it down. It starts no process but the announcer of a record //! whose network publishes the workload's listeners, whose socket it binds to a privileged source -//! port, and whose status it collects through the [`Applied`], and it generates at most one ID, a +//! port, and whose status it collects through the `Applied`, and it generates at most one ID, a //! machine ID that the record asks for. It mounts the host export of a record that has one, and //! writes the machine ID's and the resolver's files in the runtime directory, whose binds over //! the root's `/etc/machine-id` and `/etc/resolv.conf` need Linux 6.8 or later. @@ -308,8 +312,11 @@ use super::time::{ pub use self::activation::{ Activation, ActivationAction, ActivationCause, ActivationFailure, ActivationInput, - ActivationState, Applied, AppliedTeardownError, ApplyError, MACHINE_ID_FILE, NetworkError, - RESOLVER_FILE, RootTemplate, apply, + ActivationState, MACHINE_ID_FILE, RESOLVER_FILE, +}; +#[doc(hidden)] +pub use self::activation::{ + Applied, AppliedTeardownError, ApplyError, NetworkError, RootTemplate, apply, }; pub use self::mounts::{Mounted, Origin}; pub use self::repair::{ diff --git a/nvx-rs/src/guest/clone/activation.rs b/nvx-rs/src/guest/clone/activation.rs index e4956c96a..f9af8ae4f 100644 --- a/nvx-rs/src/guest/clone/activation.rs +++ b/nvx-rs/src/guest/clone/activation.rs @@ -30,7 +30,7 @@ pub use self::apply::{ /// The adapter passes it what it receives on the session, each an [`ActivationInput`], through /// [`input`](Self::input), and does what the [`ActivationAction`] that it returns says. The /// adapter applies the record of the Activate that the activation accepted, with -/// [`apply`](fn@apply), whose waits end by the activation's [`deadline`](Self::deadline), passes +/// `apply`, whose waits end by the activation's [`deadline`](Self::deadline), passes /// the activation what the session received while the application ran, which came before Ready, /// then reports the result through [`complete`](Self::complete), whose Ready answers the Activate /// and each retry that [joined](ActivationAction::Join) it, and it reports the start of the @@ -492,7 +492,7 @@ pub enum ActivationAction { Continue, /// The activation accepted the host's Activate, whose record decoded and validated, and /// which nothing before had any side effect of: the adapter applies the record with - /// [`apply`](fn@apply), which activates the root and the workload with its settings, passes + /// `apply`, which activates the root and the workload with its settings, passes /// the activation what the session received meanwhile, which came before Ready, then reports /// the result to [`Activation::complete`]. Apply(Box), diff --git a/nvx-rs/src/guest/clone/activation/apply.rs b/nvx-rs/src/guest/clone/activation/apply.rs index 7218ddef9..45ee8bba8 100644 --- a/nvx-rs/src/guest/clone/activation/apply.rs +++ b/nvx-rs/src/guest/clone/activation/apply.rs @@ -1,6 +1,10 @@ //! The application of the record of the Activate that a clone's [`Activation`] accepted: //! [`apply`](fn@apply), which activates the clone's root and workload with the record's settings, //! as at a cold boot, as the [module](super::super#activation) describes. +//! +//! The application, `apply` and its types, is NVX's internal reference code of the guest's space, +//! hidden from the documentation and unstable: it becomes crate-private once nothing outside NVX +//! uses it. #[cfg(test)] mod tests; @@ -29,14 +33,14 @@ use crate::guest::mappings::{self, Access, SourceRoot}; use crate::guest::root::{self, Assembly, AssemblyError, Device, Root, TeardownError}; use crate::protocol::cmdline::write_resolver; -/// The name of the file, in the template's [runtime directory](RootTemplate::runtime), to which -/// [`apply`](fn@apply) writes the machine ID that it generates for a record that asks for one, as -/// NVX's managed agent writes its own to `/run/nvx/workload-machine-id`. +/// The name of the file, in the template's runtime directory, to which the activation's +/// application writes the machine ID that it generates for a record that asks for one, as NVX's +/// managed agent writes its own to `/run/nvx/workload-machine-id`. pub const MACHINE_ID_FILE: &str = "workload-machine-id"; -/// The name of the file, in the template's [runtime directory](RootTemplate::runtime), to which -/// [`apply`](fn@apply) writes the resolver file that names the DNS server of a record's network, -/// which every execution sees read-only at `/etc/resolv.conf`. +/// The name of the file, in the template's runtime directory, to which the activation's +/// application writes the resolver file that names the DNS server of a record's network, which +/// every execution sees read-only at `/etc/resolv.conf`. pub const RESOLVER_FILE: &str = "resolv.conf"; /// The mode of the resolver file, whatever the umask: every execution may read it. @@ -48,6 +52,7 @@ const RESOLVER_MODE: u32 = 0o444; /// the assembly of the root waits for each, the host filesystem device, which its virtio-fs tag /// names, and the IPv4 gateway of the template's NIC, if it has one. [`apply`](fn@apply) takes /// the rest from the activation record. +#[doc(hidden)] #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct RootTemplate { /// The runtime directory, below which the root is mounted, as [`Assembly::runtime`] tells, @@ -94,6 +99,7 @@ pub struct RootTemplate { /// [`teardown`](Self::teardown) stops the announcer, closes the export's root, if the adapter did /// not take it, removes the binds, then tears the root down, and dropping it does the same, /// ignoring failures, as dropping a [`Root`] does. +#[doc(hidden)] #[derive(Debug)] pub struct Applied { /// The announcer of the workload's listeners, if the record's network publishes them, which a @@ -265,6 +271,7 @@ impl Drop for Binds { /// Why [`Applied::teardown`] failed: the runtime's binds that it failed to remove, which stay /// mounted and keep the root's mount busy, and the unmounts of the root's teardown that failed, /// whose mounts stay. At least one of them failed. +#[doc(hidden)] #[derive(Debug)] pub struct AppliedTeardownError { /// The binds that stay mounted, if any. @@ -392,6 +399,7 @@ impl std::error::Error for AppliedTeardownError {} /// It needs the guest's root user, in the guest's initial mount namespace, as /// [`root::assemble`] does, and the binds of a generated machine ID and of a resolver file need /// Linux 6.8 or later, as [`Entry::bind_runtime`] does. +#[doc(hidden)] pub fn apply( record: &ActivationRecord, template: &RootTemplate, @@ -415,6 +423,7 @@ pub fn apply( /// /// Nothing that the application mounted stays mounted, unless the error holds the unmounts that /// failed, whose mounts stay. +#[doc(hidden)] #[derive(Debug)] #[non_exhaustive] pub enum ApplyError { @@ -540,6 +549,7 @@ impl std::error::Error for ApplyError { /// Why the network settings of a record could not be applied, which an [`ApplyError::Network`] /// holds. +#[doc(hidden)] #[derive(Debug)] #[non_exhaustive] pub enum NetworkError { diff --git a/nvx-rs/src/guest/entry.rs b/nvx-rs/src/guest/entry.rs index b69083a86..b30b1fec2 100644 --- a/nvx-rs/src/guest/entry.rs +++ b/nvx-rs/src/guest/entry.rs @@ -3,7 +3,7 @@ //! //! An [`Entry`] describes how an adapter's executions enter its root: //! -//! - the root: the path of a mount, such as a [`Root`](super::root::Root)'s; +//! - the root: the path of a mount, such as a layered root's; //! - the [`Identity`]: the user and group IDs, the supplementary groups, the [`Capabilities`], //! from an allowlist of 13, and the [`AccountMode`]; //! - the hostname, `nvx-sandbox` unless the adapter names another; @@ -23,7 +23,7 @@ //! [`Entry::bind_runtime`] binds the file of a [generated](MachineId::Generated) machine ID over //! the root's `/etc/machine-id`, the time status's directory at the root's `/run/nvx/time`, and //! a [resolver](Entry::resolver) file, which names the guest's DNS servers, over the root's -//! `/etc/resolv.conf`, through the walk and attach of [`mappings::bind`]: each is read-only, +//! `/etc/resolv.conf`, through the walk and attach of the mapper's `bind`: each is read-only, //! `nosuid`, and `nodev` before anything sees it, and the walk creates what the root lacks only //! on the root's own mount, through no symbolic link, and refuses a target of another kind than //! its source. A symbolic link at `/etc/machine-id` or `/etc/resolv.conf` itself, which no bind @@ -43,7 +43,7 @@ //! which ends with it, and drop them. A bind that fails has the call remove the binds that it //! made before it, and an [`Error::Rollback`] names any of them that stays mounted. A bind that a //! rename moved while the walk ran, and that the attach failed to detach, fails the call, and -//! stays mounted wherever it went, as [`mappings::bind`] describes. +//! stays mounted wherever it went, as the mapper's `bind` does. //! //! # The execution //! diff --git a/nvx-rs/src/guest/gpt.rs b/nvx-rs/src/guest/gpt.rs index 096021e28..ddfa54362 100644 --- a/nvx-rs/src/guest/gpt.rs +++ b/nvx-rs/src/guest/gpt.rs @@ -1,5 +1,9 @@ //! GPT disks that the guest's kernel attached as block devices. //! +//! This module is NVX's internal reference code of the guest's space, hidden from the +//! documentation and unstable: it becomes crate-private once nothing outside NVX uses it. +//! [`crate::gpt`], which reads and checks the table, stays public. +//! //! [`read_disk`] reads the partition table of a disk through the disk's block device, such as //! `/dev/vda`, that the caller opened. It asks the device for its logical block size and its //! size, as `blockdev --getss` and `blockdev --getsize64` do, and reads and checks the table at diff --git a/nvx-rs/src/guest/mappings.rs b/nvx-rs/src/guest/mappings.rs index 784b5a76f..d026ed90b 100644 --- a/nvx-rs/src/guest/mappings.rs +++ b/nvx-rs/src/guest/mappings.rs @@ -1,125 +1,15 @@ -//! Bind mounts of host mappings beneath the descriptors of their roots, and the host mapping table -//! through which a guest agent applies them. +//! Host mappings, and the host mapping table through which a guest agent applies them. //! //! A [`Mapping`] names a source below a source root, such as the guest's mount of the host's -//! export; a target below a target root, the tree that the mappings go into; and the target's -//! [`Access`]. A [`Mapper`] applies mappings beneath one [`TargetRoot`], in order, from a -//! [`SourceRoot`], tracks them, and unmounts them at its [`teardown`](Mapper::teardown). [`bind`] -//! applies one runtime bind, such as a generated machine ID, a resolver file, or the runtime's time -//! status, through the same walk and attach, without the checks of a host mapping's target and -//! without tracking. A [`MappingTable`] checks the parts of a host mapping table, as the +//! export; a target below a target root, the tree that the mappings go into; the target's +//! [`Access`]; and, if it asks for one, the [`Kind`] that its source must have. A +//! [`MappingTable`] checks the parts of a host mapping table, as the //! [last section](#host-mapping-table) describes, and hands their mappings to the root of its //! caller's choice. //! -//! # Walk -//! -//! No path string names an object that a mapping uses. The mapper opens a target's components -//! one at a time, each with `openat2` beneath the descriptor of the one before it, starting from -//! the target root's, with `RESOLVE_BENEATH`, `RESOLVE_NO_SYMLINKS`, and -//! `RESOLVE_NO_MAGICLINKS`: a symbolic link or a magic link at any component, the last -//! included, is refused, and no path leads above the root. It opens a source beneath its root -//! the same way, in one call, and with `RESOLVE_NO_XDEV` too, so that a source is on its root's -//! mount. An empty source names the source root itself, such as the root of a directory export, -//! which it opens as `.` beneath the root, with the same flags. A target root is the root of a -//! mount, and that mount, like each that the caller adds with [`TargetRoot::add_mount`], shows its -//! whole file system, which `statmount` tells, rather than being a bind of a directory below that -//! file system's root: no rename, through it or another mount of its file system, can move a file -//! out of it, so nothing that the walk opened on one of the root's own mounts leaves the root, -//! whatever is renamed meanwhile. -//! -//! # Creation -//! -//! A missing component of a target is created, as a directory with mode 0755, or, for the last -//! component of a file's mapping, as an empty regular file with mode 0644, both exactly, whatever -//! the caller's umask or a default ACL of its parent, either of which could withhold -//! permissions, so that a workload that is not root reaches the mapping. It is created only -//! where `statx` shows its parent directory on one of the root's own mounts, by their unique -//! mount IDs: the target root's mount, such as a layered root's overlay, and those that the -//! caller adds with [`TargetRoot::add_mount`], such as a scratch file system of a root without -//! an overlay. So nothing is created inside another mapping, nor on another mount, not even on -//! a bind of the root's own file system, which has the device number of its source but a mount -//! ID of its own. -//! -//! A file gets its mode through the descriptor that its exclusive creation returns, which -//! refers to that file alone. A directory is created with no permissions, which neither the -//! umask nor an ACL can narrow, and the mapper then opens the component as it opens an existing -//! one, and checks whatever is there then as such. It gives the directory its mode through that -//! descriptor only if it still has no permissions and the mapper's user as its owner, as the -//! directory that it created has: a directory that a rename put in its place keeps its mode, -//! unless it, too, has no permissions and that owner, which no other user can give a directory, -//! nor move such a directory into its place from another. The mapper changes nothing that -//! existed already. -//! -//! # Checks -//! -//! Before it opens anything for a mapping, a mapper refuses a target that is: -//! -//! - reserved: in the `/run/nvx/time` tree, where the runtime binds its time status, or in one of -//! the root profile's [`Reserved`] trees; an ancestor of any of them, such as `/run` or -//! `/run/nvx`, which would shadow them; or one of the profile's reserved paths; -//! - an earlier mapping's target, or an ancestor of one, which would shadow it. -//! -//! The target then takes the kind of its source: a directory onto a directory, or a regular file -//! onto a regular file. A source of any other kind, or of another kind than -//! [`Mapping::with_kind`] asks for, and an existing target of another kind than its source, are -//! refused. So is a target on a mount that is neither the root's own nor an earlier mapping's, -//! and one that is the root of a mount already, which the mapping would shadow, unless the root -//! owns that mount, such as the tmpfs at a guest's `/tmp`, which a mapping of the host's `/tmp` -//! then covers until the teardown. -//! -//! # Attach -//! -//! The mapper never exposes a mapping without its restrictions: `open_tree` with -//! `OPEN_TREE_CLONE` copies the source's mount alone, detached; `mount_setattr` sets `nosuid`, -//! `nodev`, and the access's read-only flag on the copy; and only then `move_mount` attaches the -//! copy onto the target's descriptor. Nothing is bound first and restricted later, and a failure -//! before the attach leaves nothing mounted. The mapper then opens the target again from the -//! root, and checks that it is the new mount, so a mapping that it reports is at its target: one -//! that a rename moved while the walk ran is detached at once, as a lazy unmount does, wherever -//! it went, and refused. If that detach fails too, a mapper keeps the mapping's descriptor, and -//! detaches it at its teardown. -//! -//! The mounts are made in the caller's mount namespace, which must be recursively private, so -//! that they propagate nowhere: a guest's initial namespace, whose mounts are private unless its -//! init made them shared, or a namespace that the caller unshared and made private. The mapper -//! never changes the propagation of the caller's mounts. -//! -//! # Order and failure -//! -//! [`Mapper::apply`] applies a batch of mappings in order. Zero mappings do no work. The first -//! mapping that is refused or fails is reported with its index; the mappings before it stay -//! mapped, and the mapper refuses every later one, in this batch or another: the failure latches -//! for the mapper's lifetime, so that its caller starts nothing on a partial table. -//! -//! # Teardown -//! -//! [`Mapper::teardown`] first detaches the mapping that a rename moved, if its attach failed to -//! detach it, through the descriptor that the mapper kept, then unmounts the mappings in reverse -//! order. It opens each target again from the root, checks that the topmost mount there is the -//! mapping's, and unmounts it by its name in its parent directory, whose descriptor it opened -//! from the root, without following a link there and without detaching a busy mount; this needs -//! procfs at `/proc`. It attempts each, whatever failed before, and reports every failure. A -//! mapper that is dropped leaves its mappings mounted. -//! -//! A layered [`Root`](super::root::Root) mounts its live shares, and the mappings that its caller -//! applies, through one, which its teardown unmounts first. -//! -//! ```no_run -//! use std::path::Path; -//! -//! use nvx::guest::mappings::{Access, Mapper, Mapping, Reserved, SourceRoot, TargetRoot}; -//! -//! # fn main() -> Result<(), Box> { -//! let root = TargetRoot::open(Path::new("/newroot"))?; -//! let mut mapper = Mapper::new(root, Reserved::container_root()); -//! let export = SourceRoot::open(Path::new("/run/export"))?; -//! // Mounts the export's 0/workspace at /newroot/workspace, read-write, nosuid, and nodev. -//! let workspace = Mapping::new("0/workspace", "/workspace", Access::ReadWrite)?; -//! mapper.apply(&export, &[workspace])?; -//! mapper.teardown()?; -//! # Ok(()) -//! # } -//! ``` +//! NVX mounts mappings through its mapper, which binds each beneath the descriptor of its root. +//! The mapper, like the rest of the guest's space, is NVX's internal reference code: hidden from +//! this documentation, unstable, and crate-private once nothing outside NVX uses it. //! //! # Host mapping table //! @@ -139,45 +29,30 @@ //! children, no table maps: a table refuses an empty source. mod kernel; +#[doc(hidden)] +pub mod mapper; mod table; -#[cfg(test)] -mod tests; -use std::ffi::{CStr, OsStr}; +use std::ffi::OsStr; use std::fmt; -use std::io; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; -use super::sys::{ - self, Errno, FileDescriptor, FileKind, Mode, MountAttributes, MountFlags, OpenFlags, -}; -use crate::protocol::share::{RESERVED_EXACT_MOUNT_TARGETS, RESERVED_MOUNT_TARGETS}; +use super::sys::{self, FileKind, MountAttributes, MountFlags}; pub(crate) use self::kernel::{Kernel, SystemKernel}; +#[doc(hidden)] +pub use self::mapper::{ + ApplyError, Mapper, MappingError, Reserved, SourceRoot, Step, TargetRoot, TeardownError, + UnmountFailure, bind, +}; +pub(crate) use self::mapper::{Mapped, bind_with, unbind_with}; pub use self::table::{MappingTable, Refusal, TableError}; /// The longest source or target of a [`Mapping`], in bytes: Linux's `PATH_MAX` without its /// terminating NUL. pub const MAX_PATH_BYTES: usize = sys::PATH_MAX - 1; -/// The tree where the runtime binds its time status, below the target root, which every mapper -/// reserves: no mapping may be in it, or hold it. -const RUNTIME_TREE: &[u8] = b"run/nvx/time"; -/// The mode of each directory that a mapper creates, whatever the umask or a default ACL: -/// `rwxr-xr-x`. -const DIRECTORY_MODE: Mode = Mode::S_IRWXU - .union(Mode::S_IRGRP) - .union(Mode::S_IXGRP) - .union(Mode::S_IROTH) - .union(Mode::S_IXOTH); -/// The mode of each file target that a mapper creates, whatever the umask or a default ACL: -/// `rw-r--r--`. -const FILE_MODE: Mode = Mode::S_IRUSR - .union(Mode::S_IWUSR) - .union(Mode::S_IRGRP) - .union(Mode::S_IROTH); - /// Whether programs can write a mapping's target. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Access { @@ -242,8 +117,8 @@ impl fmt::Display for Kind { } } -/// The path that [`Mapping::new`] or [`Reserved::new`] refuses, because it does not name a path -/// below its root. +/// The path that [`Mapping::new`], or the mapper's `Reserved::new`, refuses, because it does not +/// name a path below its root. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum InvalidMapping { @@ -272,8 +147,8 @@ impl fmt::Display for InvalidMapping { impl std::error::Error for InvalidMapping {} -/// A host mapping: a source below a source root, which a [`Mapper`] mounts at a target below a -/// target root, with an [`Access`]. +/// A host mapping: a source below a source root, which a mapper mounts at a target below a target +/// root, with an [`Access`]. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Mapping { /// The source, relative to the source root. @@ -345,1047 +220,6 @@ impl Mapping { } } -/// The targets that a root profile reserves for its runtime, which no mapping may take, besides -/// the `/run/nvx/time` tree that every [`Mapper`] reserves: trees, which a mapping may be neither -/// in nor an ancestor of, and paths, at which a mapping may not be, though it may be below them. -/// -/// The default reserves nothing more. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -pub struct Reserved { - /// The reserved trees, relative to the target root. - trees: Vec, - /// The reserved paths, relative to the target root. - paths: Vec, -} - -impl Reserved { - /// Reserves `trees` and `paths`, absolute paths as seen from the target root, which must be - /// canonical, as a [`Mapping`]'s target is: otherwise [`InvalidMapping::Target`]. - pub fn new(trees: T, paths: P) -> Result - where - T: IntoIterator, - T::Item: AsRef, - P: IntoIterator, - P::Item: AsRef, - { - let relative = |path: &Path| { - below_its_root(path, true) - .map(Path::to_path_buf) - .ok_or(InvalidMapping::Target) - }; - Ok(Self { - trees: trees - .into_iter() - .map(|tree| relative(tree.as_ref())) - .collect::>()?, - paths: paths - .into_iter() - .map(|path| relative(path.as_ref())) - .collect::>()?, - }) - } - - /// Returns the targets that NVX's container runtime reserves in a container root, which - /// [`protocol::share`](crate::protocol::share) lists for the host and the guest: the trees - /// `/proc`, `/sys`, `/dev`, `/.nvx-agent`, `/etc/machine-id`, `/etc/resolv.conf`, and - /// `/run/nvx/time`, and the paths `/etc`, `/run`, and `/run/nvx`. - pub fn container_root() -> Self { - Self::new(RESERVED_MOUNT_TARGETS, RESERVED_EXACT_MOUNT_TARGETS) - .expect("the container runtime's reserved targets are canonical") - } - - /// Returns whether the relative `target` is reserved: in a reserved tree, or an ancestor of - /// one, or a reserved path. The runtime's tree is always reserved. - fn holds(&self, target: &[u8]) -> bool { - let tree = |tree: &[u8]| within(target, tree) || within(tree, target); - tree(RUNTIME_TREE) - || self.trees.iter().any(|reserved| tree(bytes(reserved))) - || self.paths.iter().any(|reserved| bytes(reserved) == target) - } -} - -/// The root beneath which a [`Mapper`] maps: a descriptor of the root of a mount of a whole file -/// system, and the root's own mounts, each of a whole file system too, on which the mapper may -/// create what a target lacks. -#[derive(Debug)] -pub struct TargetRoot { - /// The root's directory, opened with `O_PATH`. - directory: FileDescriptor, - /// The unique IDs of the root's own mounts: the root's mount first. - mounts: Vec, -} - -impl TargetRoot { - /// Opens the directory `path`, which must be the root of a mount that shows its whole file - /// system, not a bind of a directory below that file system's root, and whose mount becomes - /// the root's own: for example a layered root's overlay, or a guest's `/`. A final symbolic - /// link at `path` is not followed. It needs Linux 6.8 or later, for the unique mount IDs and - /// `statmount`. - pub fn open(path: &Path) -> io::Result { - Self::open_with(&mut SystemKernel, path) - } - - /// Adds the mount that the directory `path` is on, which must show its whole file system, to - /// the root's own mounts, on which the mapper may create what a target lacks, such as the - /// scratch file system of a root without an overlay, and whose root a mapping may cover. A - /// final symbolic link at `path` is not followed. - pub fn add_mount(&mut self, path: &Path) -> io::Result<()> { - self.add_mount_with(&mut SystemKernel, path) - } - - /// Implements [`open`](Self::open) with `kernel`. - pub(crate) fn open_with(kernel: &mut dyn Kernel, path: &Path) -> io::Result { - let directory = open_directory(path)?; - let status = kernel.status(&directory)?; - if !status.mount_root { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - format!("{} is not the root of a mount", path.display()), - )); - } - check_whole(kernel, status.mount, path)?; - Ok(Self { - directory, - mounts: vec![status.mount], - }) - } - - /// Implements [`add_mount`](Self::add_mount) with `kernel`. - pub(crate) fn add_mount_with( - &mut self, - kernel: &mut dyn Kernel, - path: &Path, - ) -> io::Result<()> { - let mount = kernel.status(&open_directory(path)?)?.mount; - check_whole(kernel, mount, path)?; - if !self.owns(mount) { - self.mounts.push(mount); - } - Ok(()) - } - - /// Returns whether the mount `mount` is one of the root's own. - fn owns(&self, mount: u64) -> bool { - self.mounts.contains(&mount) - } -} - -/// The root beneath which a [`Mapper`] or [`bind`] opens the sources of mappings, such as the -/// guest's mount of the host's export: a descriptor of a directory. -#[derive(Debug)] -pub struct SourceRoot { - /// The root's directory, opened with `O_PATH`. - directory: FileDescriptor, -} - -impl SourceRoot { - /// Opens the directory `path`, not through a final symbolic link. - pub fn open(path: &Path) -> io::Result { - Ok(Self { - directory: open_directory(path)?, - }) - } -} - -/// A step of applying or unmounting a mapping, at which a system call failed. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum Step { - /// Opening the source beneath its root: a missing source fails with `ENOENT`, a symbolic or - /// magic link on its path with `ELOOP`, and a path that crosses into another mount with - /// `EXDEV`. - Source, - /// Opening a component of the target. - Walk, - /// Creating a missing component of the target. - Create, - /// Reading the status of an open file. - Status, - /// Copying the source's mount, detached. - Clone, - /// Restricting the copy to the mapping's access, `nosuid`, and `nodev`. - Restrict, - /// Attaching the copy at the target. - Attach, - /// Opening the target again to find the mapping. - Locate, - /// Unmounting the mapping. - Unmount, -} - -impl fmt::Display for Step { - /// Writes the step as the verb phrase of a failure: `failed to {step}`. - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(match self { - Self::Source => "open the source", - Self::Walk => "open a component of the target", - Self::Create => "create a component of the target", - Self::Status => "read the status of a file", - Self::Clone => "copy the source's mount", - Self::Restrict => "restrict the mount", - Self::Attach => "attach the mount at the target", - Self::Locate => "find the mapping at its target", - Self::Unmount => "unmount the mapping", - }) - } -} - -/// Why a mapper refused a mapping, or failed to apply or unmount it. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -pub enum MappingError { - /// An earlier mapping of the mapper failed, so it refuses every later one. - Latched, - /// The runtime reserves the target, or a tree below it. - Reserved, - /// The target is the target of an earlier mapping, or holds it, and would shadow it. - Overlap { - /// The earlier mapping's target. - mapped: PathBuf, - }, - /// The source is neither a directory nor a regular file, or is not of the mapping's kind. - SourceKind, - /// A component of the target, at this path, is a symbolic link or a magic link. - Link { - /// The component's path in the root. - path: PathBuf, - }, - /// A component of the target, at this path, is not a directory, though the target is below - /// it. - NotDirectory { - /// The component's path in the root. - path: PathBuf, - }, - /// The target exists, but not as the kind of its source. - TargetKind, - /// The target, or a missing component of it, at this path, is not on one of the root's own - /// mounts, where the mapper may create it, nor, for an existing target, inside an earlier - /// mapping. - Foreign { - /// The path in the root. - path: PathBuf, - }, - /// The target is the root of a mount already, which the mapping would shadow, and the root - /// does not own that mount. - MountPoint, - /// The mapping was not the topmost mount at its target once attached, since a rename moved a - /// directory of the target while the walk ran, or, at a teardown, since a rename or another - /// mount at the target since then. - Moved { - /// Whether the mapping stays mounted, wherever it is: because detaching it failed too, - /// in which case a mapper's teardown detaches it, or because a teardown does not unmount - /// what it does not find at its target. - mounted: bool, - }, - /// A system call failed at a step. - System { - /// The step. - step: Step, - /// The call's `errno`. - error: i32, - }, -} - -impl MappingError { - /// Returns the `errno` that best describes the failure, such as a control protocol's status: - /// the call's own for [`MappingError::System`], and otherwise `ECANCELED` for a latched - /// mapper, `EPERM` for a reserved target, `EBUSY` for an overlap or a mount point, `EINVAL` - /// for a kind, `ELOOP` for a link, `ENOTDIR` for a component that is not a directory, `EXDEV` - /// for a foreign mount, and `EAGAIN` for a moved mapping. - pub fn raw_os_error(&self) -> i32 { - let error = match self { - Self::Latched => Errno::ECANCELED, - Self::Reserved => Errno::EPERM, - Self::Overlap { .. } | Self::MountPoint => Errno::EBUSY, - Self::SourceKind | Self::TargetKind => Errno::EINVAL, - Self::Link { .. } => Errno::ELOOP, - Self::NotDirectory { .. } => Errno::ENOTDIR, - Self::Foreign { .. } => Errno::EXDEV, - Self::Moved { .. } => Errno::EAGAIN, - Self::System { error, .. } => return *error, - }; - error as i32 - } -} - -impl fmt::Display for MappingError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Latched => formatter.write_str("an earlier mapping failed"), - Self::Reserved => formatter.write_str("the runtime reserves the target"), - Self::Overlap { mapped } => write!( - formatter, - "the target would shadow the mapping at {}", - mapped.display() - ), - Self::SourceKind => formatter - .write_str("the source is not a directory or a regular file of the mapping's kind"), - Self::Link { path } => write!( - formatter, - "{} is a symbolic link or a magic link", - path.display() - ), - Self::NotDirectory { path } => { - write!(formatter, "{} is not a directory", path.display()) - } - Self::TargetKind => { - formatter.write_str("the target exists as another kind than its source") - } - Self::Foreign { path } => write!( - formatter, - "{} is not on one of the root's own mounts or inside an earlier mapping", - path.display() - ), - Self::MountPoint => { - formatter.write_str("the target is the root of a mount that the root does not own") - } - Self::Moved { mounted } => write!( - formatter, - "the mapping is not at its target{}", - if *mounted { - ", and it stays mounted" - } else { - "" - } - ), - Self::System { step, error } => write!( - formatter, - "failed to {step}: {}", - io::Error::from_raw_os_error(*error) - ), - } - } -} - -impl std::error::Error for MappingError {} - -/// Which mapping of a batch a [`Mapper`] refused or failed to apply, from 0, and why. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct ApplyError { - /// The index of the mapping in its batch. - entry: usize, - /// Why it was refused or failed. - error: MappingError, -} - -impl ApplyError { - /// Returns the index of the mapping in its batch, from 0. - pub fn entry(&self) -> usize { - self.entry - } - - /// Returns why the mapping was refused or failed. - pub fn error(&self) -> &MappingError { - &self.error - } -} - -impl fmt::Display for ApplyError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(formatter, "mapping {} failed: {}", self.entry, self.error) - } -} - -impl std::error::Error for ApplyError {} - -/// A mapping that a teardown failed to unmount, which stays mounted. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct UnmountFailure { - /// The mapping's target, as an absolute path in the root. - target: PathBuf, - /// Why it was not unmounted. - error: MappingError, -} - -impl UnmountFailure { - /// Returns the mapping's target, as an absolute path in the root. - pub fn target(&self) -> &Path { - &self.target - } - - /// Returns why the mapping was not unmounted: [`MappingError::Moved`] if another mount is at - /// its target, and otherwise the failed [`Step::Locate`] or [`Step::Unmount`], which is also - /// the step of a mapping that a rename moved and that the teardown failed to detach. - pub fn error(&self) -> &MappingError { - &self.error - } -} - -impl fmt::Display for UnmountFailure { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - formatter, - "the mapping at {}: {}", - self.target.display(), - self.error - ) - } -} - -/// The mappings that a teardown failed to unmount, in the order in which it attempted them. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct TeardownError { - /// The failures, which is never empty. - failures: Vec, -} - -impl TeardownError { - /// Returns the failures, in the order in which the teardown attempted them. - pub fn failures(&self) -> &[UnmountFailure] { - &self.failures - } -} - -impl fmt::Display for TeardownError { - /// Writes each failure, separated by `; `. - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - for (index, failure) in self.failures.iter().enumerate() { - if index > 0 { - formatter.write_str("; ")?; - } - write!(formatter, "failed to unmount {failure}")?; - } - Ok(()) - } -} - -impl std::error::Error for TeardownError {} - -/// A mapping that a mapper attached and tracks, or a runtime bind that [`bind_with`] made, which -/// [`unbind_with`] unmounts. -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct Mapped { - /// The target, relative to the root. - target: PathBuf, - /// The unique ID of the mapping's mount. - mount: u64, -} - -/// A mapping that a rename moved away from its target while the walk ran, which the attach -/// failed to detach, and which stays mounted wherever it went. -#[derive(Debug)] -struct Stray { - /// The target, relative to the root. - target: PathBuf, - /// The descriptor of the mapping's mount, through which a teardown detaches it. - tree: FileDescriptor, -} - -/// The applier of a root's mappings, which checks, attaches, tracks, and unmounts them, as the -/// [module](self) describes. -#[derive(Debug)] -pub struct Mapper { - /// The root beneath which it maps. - root: TargetRoot, - /// The targets that the root's profile reserves. - reserved: Reserved, - /// The mappings that it attached, in order. - mapped: Vec, - /// The mapping that a rename moved and that it failed to detach, if any, which its last - /// attach left, since that failure latched it. - stray: Option, - /// Whether a mapping failed, after which it refuses every later one. - latched: bool, -} - -impl Mapper { - /// Returns a mapper of no mappings yet beneath `root`, whose profile reserves `reserved`. - pub fn new(root: TargetRoot, reserved: Reserved) -> Self { - Self { - root, - reserved, - mapped: Vec::new(), - stray: None, - latched: false, - } - } - - /// Applies `mappings` beneath the root, in order, from `source`, as the [module](self) - /// describes, and tracks them. It needs the privilege to mount. - /// - /// The first mapping that is refused or fails is reported with its index, after the mappings - /// before it, which stay mapped, and the mapper refuses every later mapping from then on. - /// Zero mappings do no work. A mapping that a rename moved, and that the mapper failed to - /// detach, [`MappingError::Moved`] with `mounted`, is not tracked, but the teardown detaches - /// it first. - pub fn apply(&mut self, source: &SourceRoot, mappings: &[Mapping]) -> Result<(), ApplyError> { - self.apply_with(&mut SystemKernel, source, mappings) - } - - /// Checks the target of `mapping` as [`apply`](Self::apply) does before it opens anything: - /// that it is neither reserved nor overlaps an earlier mapping. - pub fn check(&self, mapping: &Mapping) -> Result<(), MappingError> { - self.check_target(mapping.target()) - } - - /// Returns whether a mapping failed, after which the mapper refuses every later one. - pub fn is_latched(&self) -> bool { - self.latched - } - - /// Returns the targets of the mappings that the mapper tracks, in the order in which it - /// applied them, relative to the root. - pub fn targets(&self) -> impl ExactSizeIterator { - self.mapped.iter().map(|mapped| mapped.target.as_path()) - } - - /// Unmounts the mappings in reverse order, as the [module](self) describes, and reports every - /// one that it failed to unmount, which stays mounted. It first detaches the mapping that a - /// rename moved and that the mapper failed to detach, if any. - pub fn teardown(self) -> Result<(), TeardownError> { - self.teardown_with(&mut SystemKernel) - } - - /// Implements [`teardown`](Self::teardown) with `kernel`. - pub(crate) fn teardown_with(mut self, kernel: &mut dyn Kernel) -> Result<(), TeardownError> { - let failures: Vec = self - .unmount_with(kernel) - .into_iter() - .map(|(_, failure)| failure) - .collect(); - if failures.is_empty() { - Ok(()) - } else { - Err(TeardownError { failures }) - } - } - - /// Implements [`apply`](Self::apply) with `kernel`. - pub(crate) fn apply_with( - &mut self, - kernel: &mut dyn Kernel, - source: &SourceRoot, - mappings: &[Mapping], - ) -> Result<(), ApplyError> { - for (entry, mapping) in mappings.iter().enumerate() { - self.attach_with( - kernel, - Source::Beneath(source, mapping.source()), - mapping.target(), - mapping.access(), - mapping.kind(), - ) - .map_err(|error| ApplyError { entry, error })?; - } - Ok(()) - } - - /// Moves the mount whose root `mount` refers to, such as a file system that the caller - /// mounted where only it can reach, onto `target`, a path relative to the root, as the mapper - /// attaches a directory's mapping: with `nosuid`, `nodev`, and `access` set while the mount is - /// still where only the caller reaches it, and after the same checks. The mapper then tracks - /// it as a mapping, or, as [`apply`](Self::apply) does, detaches it at the teardown if a - /// rename moved it and detaching it failed. - pub(crate) fn move_mount_with( - &mut self, - kernel: &mut dyn Kernel, - mount: &FileDescriptor, - target: &Path, - access: Access, - ) -> Result<(), MappingError> { - self.attach_with( - kernel, - Source::Mount(mount), - target, - access, - Some(Kind::Directory), - ) - } - - /// Detaches the mapping that a rename moved, if the mapper failed to detach it, then unmounts - /// the mappings in reverse order with `kernel`, forgets them all, and returns, in the order of - /// the attempts, each that it failed to unmount, with its index among the mapper's attaches - /// that left a mount: the moved mapping's, which the mapper attached last, is the number of - /// its mappings. - pub(crate) fn unmount_with(&mut self, kernel: &mut dyn Kernel) -> Vec<(usize, UnmountFailure)> { - let mapped = std::mem::take(&mut self.mapped); - let mut failures = Vec::new(); - if let Some(stray) = self.stray.take() - && let Err(error) = kernel.detach(&stray.tree) - { - let target = absolute(&stray.target); - let error = system(Step::Unmount, error); - failures.push((mapped.len(), UnmountFailure { target, error })); - } - for (index, mapping) in mapped.iter().enumerate().rev() { - if let Err(error) = unmount(kernel, &self.root, mapping) { - let target = absolute(&mapping.target); - failures.push((index, UnmountFailure { target, error })); - } - } - failures - } - - /// Checks the relative `target` as [`check`](Self::check) does. - fn check_target(&self, target: &Path) -> Result<(), MappingError> { - let target = bytes(target); - if self.reserved.holds(target) { - return Err(MappingError::Reserved); - } - match self - .mapped - .iter() - .find(|mapped| within(bytes(&mapped.target), target)) - { - Some(mapped) => Err(MappingError::Overlap { - mapped: absolute(&mapped.target), - }), - None => Ok(()), - } - } - - /// Checks the relative `target`, attaches `source` there with `access`, and tracks the - /// mapping, unless the mapper is latched; a refusal or failure latches it, and the mapper - /// keeps a mapping that a rename moved and that the attach failed to detach. - fn attach_with( - &mut self, - kernel: &mut dyn Kernel, - source: Source<'_>, - target: &Path, - access: Access, - kind: Option, - ) -> Result<(), MappingError> { - if self.latched { - return Err(MappingError::Latched); - } - let attached = self - .check_target(target) - .map_err(AttachFailure::from) - .and_then(|()| { - let mounts: Vec = self.mapped.iter().map(|mapped| mapped.mount).collect(); - attach(kernel, &self.root, &mounts, source, target, access, kind) - }); - match attached { - Ok(mount) => { - self.mapped.push(Mapped { - target: target.to_path_buf(), - mount, - }); - Ok(()) - } - Err(failure) => { - self.latched = true; - self.stray = failure.stray.map(|tree| Stray { - target: target.to_path_buf(), - tree, - }); - Err(failure.error) - } - } - } -} - -/// Binds the source of `mapping`, beneath `source`, at its target beneath `root`, with the walk, -/// the creation, the checks of kinds and mounts, and the attach of a [`Mapper`]'s mapping, as the -/// [module](self) describes, but without the checks of reserved targets and overlaps, which a -/// runtime's own binds, such as a generated machine ID over `/etc/machine-id`, would fail, and -/// without tracking it: it lasts as long as the mount namespace, or until its caller unmounts it. -/// So does a bind that a rename moved and that it failed to detach, wherever it went, which it -/// reports as [`MappingError::Moved`] with `mounted`. It needs the privilege to mount. -pub fn bind(root: &TargetRoot, source: &SourceRoot, mapping: &Mapping) -> Result<(), MappingError> { - bind_with(&mut SystemKernel, root, source, mapping).map(drop) -} - -/// Implements [`bind`] with `kernel`, and returns the bind, which [`unbind_with`] unmounts. -pub(crate) fn bind_with( - kernel: &mut dyn Kernel, - root: &TargetRoot, - source: &SourceRoot, - mapping: &Mapping, -) -> Result { - attach( - kernel, - root, - &[], - Source::Beneath(source, mapping.source()), - mapping.target(), - mapping.access(), - mapping.kind(), - ) - .map(|mount| Mapped { - target: mapping.target().to_path_buf(), - mount, - }) - .map_err(|failure| failure.error) -} - -/// Unmounts `binds`, which [`bind_with`] made beneath `root`, in reverse order, with `kernel`, as a -/// mapper's teardown unmounts its mappings: each that is the topmost mount at its target, by its -/// name in its parent directory, without detaching a busy one. It attempts each, whatever failed -/// before, and reports every one that it failed to unmount, which stays mounted. -pub(crate) fn unbind_with( - kernel: &mut dyn Kernel, - root: &TargetRoot, - binds: &[Mapped], -) -> Result<(), TeardownError> { - let mut failures = Vec::new(); - for bind in binds.iter().rev() { - if let Err(error) = unmount(kernel, root, bind) { - let target = absolute(&bind.target); - failures.push(UnmountFailure { target, error }); - } - } - if failures.is_empty() { - Ok(()) - } else { - Err(TeardownError { failures }) - } -} - -/// What a mapping attaches: the object at a path beneath a source root, whose mount the attach -/// copies, or a mount that it moves. -#[derive(Clone, Copy, Debug)] -enum Source<'a> { - /// The object at a relative path beneath a source root. - Beneath(&'a SourceRoot, &'a Path), - /// The mount whose root a descriptor refers to. - Mount(&'a FileDescriptor), -} - -/// Why an attach failed, with the descriptor of the mapping's mount if a rename moved it and -/// detaching it failed too, so that it stays mounted wherever it went. -#[derive(Debug)] -struct AttachFailure { - /// Why it failed. - error: MappingError, - /// The descriptor of the mapping's mount, if it stays mounted. - stray: Option, -} - -impl From for AttachFailure { - fn from(error: MappingError) -> Self { - Self { error, stray: None } - } -} - -/// Attaches `source` at the relative `target` beneath `root`, with `access`, as the -/// [module](self) describes, where `mapped` are the mounts of the earlier mappings, inside which -/// an existing target may be, and returns the unique ID of the new mount. A source of another -/// kind than `kind`, if given, is refused. -fn attach( - kernel: &mut dyn Kernel, - root: &TargetRoot, - mapped: &[u64], - source: Source<'_>, - target: &Path, - access: Access, - kind: Option, -) -> Result { - let opened; - let (copied, found, clone) = match source { - Source::Beneath(source, path) => { - let (descriptor, found) = open_source(kernel, source, path)?; - opened = descriptor; - (&opened, found, true) - } - Source::Mount(descriptor) => { - let status = kernel - .status(descriptor) - .map_err(|error| system(Step::Source, error))?; - if !status.mount_root { - return Err(MappingError::SourceKind.into()); - } - let found = Kind::of(status.kind).ok_or(MappingError::SourceKind)?; - (descriptor, found, false) - } - }; - if kind.is_some_and(|kind| kind != found) { - return Err(MappingError::SourceKind.into()); - } - let destination = walk(kernel, root, mapped, target, found)?; - let tree = kernel - .open_tree(copied, clone) - .map_err(|error| system(Step::Clone, error))?; - let (set, clear) = access.attributes(); - kernel - .set_attributes(&tree, set, clear) - .map_err(|error| system(Step::Restrict, error))?; - let mount = kernel - .status(&tree) - .map_err(|error| system(Step::Status, error))? - .mount; - kernel - .move_mount(&tree, &destination) - .map_err(|error| system(Step::Attach, error))?; - match locate(kernel, root, target) { - Ok((_, status)) if status.mount == mount && status.mount_root => Ok(mount), - // The tree keeps the mount busy, so only a detach takes it off wherever it went. - _ => match kernel.detach(&tree) { - Ok(()) => Err(MappingError::Moved { mounted: false }.into()), - Err(_) => Err(AttachFailure { - error: MappingError::Moved { mounted: true }, - stray: Some(tree), - }), - }, - } -} - -/// Opens `path` beneath `source`, or the source root itself for an empty `path`, and returns it -/// and its kind, which must be a mapping's. -fn open_source( - kernel: &mut dyn Kernel, - source: &SourceRoot, - path: &Path, -) -> Result<(FileDescriptor, Kind), MappingError> { - // `openat2` resolves no empty path, so the root itself is `.` beneath it, which the same - // resolution confines to the root's own mount, as it does every other source. - let path = if path.as_os_str().is_empty() { - Path::new(".") - } else { - path - }; - let opened = sys::path_c_string(path).and_then(|path| { - let descriptor = kernel.open_beneath( - &source.directory, - &path, - OpenFlags::O_PATH, - Mode::empty(), - false, - )?; - let status = kernel.status(&descriptor)?; - Ok((descriptor, status)) - }); - let (descriptor, status) = opened.map_err(|error| system(Step::Source, error))?; - let kind = Kind::of(status.kind).ok_or(MappingError::SourceKind)?; - Ok((descriptor, kind)) -} - -/// Opens each component of the relative `target` beneath `root`, creating each that is missing, -/// as a directory, or as a regular file for the last one of a file's mapping, and returns the -/// target, which must be of `kind`, on one of the root's own mounts or in one of `mapped`, and -/// not the root of a mount, unless the root owns that mount, which the mapping then covers. -fn walk( - kernel: &mut dyn Kernel, - root: &TargetRoot, - mapped: &[u64], - target: &Path, - kind: Kind, -) -> Result { - let components: Vec<&OsStr> = target.iter().collect(); - let mut current: Option = None; - for (index, component) in components.iter().enumerate() { - let parent = current.as_ref().unwrap_or(&root.directory); - let name = - sys::c_string(component.as_bytes()).map_err(|error| system(Step::Walk, error))?; - let wanted = if index + 1 == components.len() { - kind - } else { - Kind::Directory - }; - let refused = |error| match error { - Errno::ELOOP => MappingError::Link { - path: leading(target, index + 1), - }, - Errno::ENOTDIR => MappingError::NotDirectory { - path: leading(target, index), - }, - error => system(Step::Walk, error), - }; - let open = |kernel: &mut dyn Kernel| { - kernel.open_beneath(parent, &name, OpenFlags::O_PATH, Mode::empty(), true) - }; - let opened = match open(kernel) { - Ok(opened) => opened, - Err(Errno::ENOENT) => { - let created = create(kernel, root, parent, &name, wanted, || { - leading(target, index + 1) - })?; - // What is there now, what it created or what another process put there first or - // since, is checked as an existing component. - let opened = open(kernel).map_err(refused)?; - if created && wanted == Kind::Directory { - give_mode(kernel, &opened)?; - } - opened - } - Err(error) => return Err(refused(error)), - }; - current = Some(opened); - } - let destination = current.ok_or_else(|| system(Step::Walk, Errno::EINVAL))?; - let status = kernel - .status(&destination) - .map_err(|error| system(Step::Status, error))?; - if Kind::of(status.kind) != Some(kind) { - return Err(MappingError::TargetKind); - } - // The root of one of the root's own mounts, such as the tmpfs at a guest's `/tmp`, is a - // target that the mapping covers; the root of any other, an earlier mapping's included, is - // not. - if status.mount_root && !root.owns(status.mount) { - return Err(MappingError::MountPoint); - } - if !root.owns(status.mount) && !mapped.contains(&status.mount) { - return Err(MappingError::Foreign { - path: absolute(target), - }); - } - Ok(destination) -} - -/// Creates `name` in `parent`, a directory on one of `root`'s own mounts, as a directory with no -/// permissions, which [`give_mode`] gives [`DIRECTORY_MODE`] once the walk opens it, or as an -/// empty regular file with exactly [`FILE_MODE`] for [`Kind::File`], whatever the umask or a -/// default ACL, and returns whether it created it: not if another process created an entry of -/// that name first. A parent on another mount is refused as [`MappingError::Foreign`] at -/// `path`. -fn create( - kernel: &mut dyn Kernel, - root: &TargetRoot, - parent: &FileDescriptor, - name: &CStr, - kind: Kind, - path: impl FnOnce() -> PathBuf, -) -> Result { - let status = kernel - .status(parent) - .map_err(|error| system(Step::Status, error))?; - if !root.owns(status.mount) { - return Err(MappingError::Foreign { path: path() }); - } - let created = match kind { - Kind::Directory => kernel.create_directory(parent, name, Mode::empty()), - Kind::File => kernel.create_file(parent, name, FILE_MODE), - }; - match created { - Ok(()) => Ok(true), - Err(Errno::EEXIST) => Ok(false), - Err(error) => Err(system(Step::Create, error)), - } -} - -/// Gives the directory that `opened` refers to [`DIRECTORY_MODE`], through `opened`, if it is -/// the one that [`create`] created, with no permissions, before the walk opened it: if it still -/// has no permissions, and the mapper's user, its effective user ID, as its owner. A directory -/// that a rename put in its place keeps its mode. It keeps the set-group-ID bit that a directory -/// inherits from a parent that has it, as `mkdir` does. -fn give_mode(kernel: &mut dyn Kernel, opened: &FileDescriptor) -> Result<(), MappingError> { - let status = kernel - .status(opened) - .map_err(|error| system(Step::Status, error))?; - let permissions = Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO; - let created = status.kind == FileKind::Directory - && status.owner == nix::unistd::geteuid().as_raw() - && status.mode & permissions.bits() == 0; - if !created { - return Ok(()); - } - let inherited = Mode::from_bits_truncate(status.mode) & Mode::S_ISGID; - kernel - .change_mode(opened, DIRECTORY_MODE | inherited) - .map_err(|error| system(Step::Create, error)) -} - -/// Opens the relative `target` beneath `root`, through the mounts below it, and returns it and -/// its status: the topmost mount at the target, if any. -fn locate( - kernel: &mut dyn Kernel, - root: &TargetRoot, - target: &Path, -) -> Result<(FileDescriptor, sys::FileStatus), Errno> { - let path = sys::path_c_string(target)?; - let descriptor = kernel.open_beneath( - &root.directory, - &path, - OpenFlags::O_PATH, - Mode::empty(), - true, - )?; - let status = kernel.status(&descriptor)?; - Ok((descriptor, status)) -} - -/// Unmounts `mapping` beneath `root`, after checking that its mount is the topmost one at its -/// target: by its name in its parent directory, which it opens from the root, since a -/// descriptor of the mapping itself would keep it busy. -fn unmount( - kernel: &mut dyn Kernel, - root: &TargetRoot, - mapping: &Mapped, -) -> Result<(), MappingError> { - let located = (|| -> Result<_, Errno> { - let parent = match mapping.target.parent() { - Some(parent) if !parent.as_os_str().is_empty() => { - let path = sys::path_c_string(parent)?; - let flags = OpenFlags::O_PATH | OpenFlags::O_DIRECTORY; - Some(kernel.open_beneath(&root.directory, &path, flags, Mode::empty(), true)?) - } - _ => None, - }; - let name = mapping.target.file_name().ok_or(Errno::EINVAL)?; - let name = sys::c_string(name.as_bytes())?; - let directory = parent.as_ref().unwrap_or(&root.directory); - let status = kernel - .open_beneath(directory, &name, OpenFlags::O_PATH, Mode::empty(), true) - .and_then(|target| kernel.status(&target))?; - Ok((parent, name, status)) - })(); - let (parent, name, status) = located.map_err(|error| system(Step::Locate, error))?; - if status.mount != mapping.mount || !status.mount_root { - return Err(MappingError::Moved { mounted: true }); - } - kernel - .unmount_beneath(parent.as_ref().unwrap_or(&root.directory), &name) - .map_err(|error| system(Step::Unmount, error)) -} - -/// Opens the directory `path` with `O_PATH`, not through a final symbolic link. -fn open_directory(path: &Path) -> io::Result { - let flags = - OpenFlags::O_PATH | OpenFlags::O_DIRECTORY | OpenFlags::O_NOFOLLOW | OpenFlags::O_CLOEXEC; - let path = sys::path_c_string(path)?; - Ok(sys::open(&path, flags, Mode::empty())?) -} - -/// Refuses `mount`, the mount that `path` is on, unless it shows its whole file system: on a -/// bind of a directory, a rename through another mount of its file system may move what a walk -/// opened out of the bind. -fn check_whole(kernel: &mut dyn Kernel, mount: u64, path: &Path) -> io::Result<()> { - if kernel.whole_file_system(mount)? { - return Ok(()); - } - Err(io::Error::new( - io::ErrorKind::InvalidInput, - format!( - "{} is on a mount of a directory below its file system's root, not of the whole \ - file system", - path.display() - ), - )) -} - -/// Returns the failure of a system call at `step` with `error`. -fn system(step: Step, error: Errno) -> MappingError { - MappingError::System { - step, - error: error as i32, - } -} - -/// Returns the bytes of `path`. -fn bytes(path: &Path) -> &[u8] { - path.as_os_str().as_bytes() -} - -/// Returns whether the relative path `inner` is the relative path `outer` or below it. -fn within(inner: &[u8], outer: &[u8]) -> bool { - inner - .strip_prefix(outer) - .is_some_and(|rest| rest.is_empty() || rest.starts_with(b"/")) -} - -/// Returns the first `count` components of the relative `target`, as an absolute path. -fn leading(target: &Path, count: usize) -> PathBuf { - let mut path = PathBuf::from("/"); - path.extend(target.iter().take(count)); - path -} - -/// Returns the relative `target` as an absolute path. -fn absolute(target: &Path) -> PathBuf { - Path::new("/").join(target) -} - /// Returns the part of `path` below its root: the whole of a relative path, or what follows the /// leading `/` of an `absolute` one. It returns `None` unless `path` holds at most /// [`MAX_PATH_BYTES`] bytes and no NUL byte, starts with `/` exactly when it is `absolute`, and diff --git a/nvx-rs/src/guest/mappings/mapper.rs b/nvx-rs/src/guest/mappings/mapper.rs new file mode 100644 index 000000000..990f282e0 --- /dev/null +++ b/nvx-rs/src/guest/mappings/mapper.rs @@ -0,0 +1,1194 @@ +//! Bind mounts of host mappings beneath the descriptors of their roots. +//! +//! This module is NVX's internal reference code of the guest's space, hidden from the +//! documentation and unstable: it becomes crate-private once nothing outside NVX uses it. +//! [`guest::mappings`](super) re-exports its public items at their former paths, hidden too, +//! beside the mapping values and the host mapping table, which stay public. +//! +//! A [`Mapper`] applies [`Mapping`]s beneath one [`TargetRoot`], in order, from a [`SourceRoot`], +//! tracks them, and unmounts them at its [`teardown`](Mapper::teardown). [`bind`] applies one +//! runtime bind, such as a generated machine ID, a resolver file, or the runtime's time status, +//! through the same walk and attach, without the checks of a host mapping's target and without +//! tracking. +//! +//! # Walk +//! +//! No path string names an object that a mapping uses. The mapper opens a target's components +//! one at a time, each with `openat2` beneath the descriptor of the one before it, starting from +//! the target root's, with `RESOLVE_BENEATH`, `RESOLVE_NO_SYMLINKS`, and +//! `RESOLVE_NO_MAGICLINKS`: a symbolic link or a magic link at any component, the last +//! included, is refused, and no path leads above the root. It opens a source beneath its root +//! the same way, in one call, and with `RESOLVE_NO_XDEV` too, so that a source is on its root's +//! mount. An empty source names the source root itself, such as the root of a directory export, +//! which it opens as `.` beneath the root, with the same flags. A target root is the root of a +//! mount, and that mount, like each that the caller adds with [`TargetRoot::add_mount`], shows its +//! whole file system, which `statmount` tells, rather than being a bind of a directory below that +//! file system's root: no rename, through it or another mount of its file system, can move a file +//! out of it, so nothing that the walk opened on one of the root's own mounts leaves the root, +//! whatever is renamed meanwhile. +//! +//! # Creation +//! +//! A missing component of a target is created, as a directory with mode 0755, or, for the last +//! component of a file's mapping, as an empty regular file with mode 0644, both exactly, whatever +//! the caller's umask or a default ACL of its parent, either of which could withhold +//! permissions, so that a workload that is not root reaches the mapping. It is created only +//! where `statx` shows its parent directory on one of the root's own mounts, by their unique +//! mount IDs: the target root's mount, such as a layered root's overlay, and those that the +//! caller adds with [`TargetRoot::add_mount`], such as a scratch file system of a root without +//! an overlay. So nothing is created inside another mapping, nor on another mount, not even on +//! a bind of the root's own file system, which has the device number of its source but a mount +//! ID of its own. +//! +//! A file gets its mode through the descriptor that its exclusive creation returns, which +//! refers to that file alone. A directory is created with no permissions, which neither the +//! umask nor an ACL can narrow, and the mapper then opens the component as it opens an existing +//! one, and checks whatever is there then as such. It gives the directory its mode through that +//! descriptor only if it still has no permissions and the mapper's user as its owner, as the +//! directory that it created has: a directory that a rename put in its place keeps its mode, +//! unless it, too, has no permissions and that owner, which no other user can give a directory, +//! nor move such a directory into its place from another. The mapper changes nothing that +//! existed already. +//! +//! # Checks +//! +//! Before it opens anything for a mapping, a mapper refuses a target that is: +//! +//! - reserved: in the `/run/nvx/time` tree, where the runtime binds its time status, or in one of +//! the root profile's [`Reserved`] trees; an ancestor of any of them, such as `/run` or +//! `/run/nvx`, which would shadow them; or one of the profile's reserved paths; +//! - an earlier mapping's target, or an ancestor of one, which would shadow it. +//! +//! The target then takes the kind of its source: a directory onto a directory, or a regular file +//! onto a regular file. A source of any other kind, or of another kind than +//! [`Mapping::with_kind`] asks for, and an existing target of another kind than its source, are +//! refused. So is a target on a mount that is neither the root's own nor an earlier mapping's, +//! and one that is the root of a mount already, which the mapping would shadow, unless the root +//! owns that mount, such as the tmpfs at a guest's `/tmp`, which a mapping of the host's `/tmp` +//! then covers until the teardown. +//! +//! # Attach +//! +//! The mapper never exposes a mapping without its restrictions: `open_tree` with +//! `OPEN_TREE_CLONE` copies the source's mount alone, detached; `mount_setattr` sets `nosuid`, +//! `nodev`, and the access's read-only flag on the copy; and only then `move_mount` attaches the +//! copy onto the target's descriptor. Nothing is bound first and restricted later, and a failure +//! before the attach leaves nothing mounted. The mapper then opens the target again from the +//! root, and checks that it is the new mount, so a mapping that it reports is at its target: one +//! that a rename moved while the walk ran is detached at once, as a lazy unmount does, wherever +//! it went, and refused. If that detach fails too, a mapper keeps the mapping's descriptor, and +//! detaches it at its teardown. +//! +//! The mounts are made in the caller's mount namespace, which must be recursively private, so +//! that they propagate nowhere: a guest's initial namespace, whose mounts are private unless its +//! init made them shared, or a namespace that the caller unshared and made private. The mapper +//! never changes the propagation of the caller's mounts. +//! +//! # Order and failure +//! +//! [`Mapper::apply`] applies a batch of mappings in order. Zero mappings do no work. The first +//! mapping that is refused or fails is reported with its index; the mappings before it stay +//! mapped, and the mapper refuses every later one, in this batch or another: the failure latches +//! for the mapper's lifetime, so that its caller starts nothing on a partial table. +//! +//! # Teardown +//! +//! [`Mapper::teardown`] first detaches the mapping that a rename moved, if its attach failed to +//! detach it, through the descriptor that the mapper kept, then unmounts the mappings in reverse +//! order. It opens each target again from the root, checks that the topmost mount there is the +//! mapping's, and unmounts it by its name in its parent directory, whose descriptor it opened +//! from the root, without following a link there and without detaching a busy mount; this needs +//! procfs at `/proc`. It attempts each, whatever failed before, and reports every failure. A +//! mapper that is dropped leaves its mappings mounted. +//! +//! A layered [`Root`](crate::guest::root::Root) mounts its live shares, and the mappings that its +//! caller applies, through one, which its teardown unmounts first. +//! +//! ```no_run +//! use std::path::Path; +//! +//! use nvx::guest::mappings::{Access, Mapper, Mapping, Reserved, SourceRoot, TargetRoot}; +//! +//! # fn main() -> Result<(), Box> { +//! let root = TargetRoot::open(Path::new("/newroot"))?; +//! let mut mapper = Mapper::new(root, Reserved::container_root()); +//! let export = SourceRoot::open(Path::new("/run/export"))?; +//! // Mounts the export's 0/workspace at /newroot/workspace, read-write, nosuid, and nodev. +//! let workspace = Mapping::new("0/workspace", "/workspace", Access::ReadWrite)?; +//! mapper.apply(&export, &[workspace])?; +//! mapper.teardown()?; +//! # Ok(()) +//! # } +//! ``` + +#[cfg(test)] +mod tests; + +use std::ffi::{CStr, OsStr}; +use std::fmt; +use std::io; +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; + +use super::kernel::{Kernel, SystemKernel}; +use super::{Access, InvalidMapping, Kind, Mapping, below_its_root}; +use crate::guest::sys::{self, Errno, FileDescriptor, FileKind, Mode, OpenFlags}; +use crate::protocol::share::{RESERVED_EXACT_MOUNT_TARGETS, RESERVED_MOUNT_TARGETS}; + +/// The tree where the runtime binds its time status, below the target root, which every mapper +/// reserves: no mapping may be in it, or hold it. +const RUNTIME_TREE: &[u8] = b"run/nvx/time"; +/// The mode of each directory that a mapper creates, whatever the umask or a default ACL: +/// `rwxr-xr-x`. +const DIRECTORY_MODE: Mode = Mode::S_IRWXU + .union(Mode::S_IRGRP) + .union(Mode::S_IXGRP) + .union(Mode::S_IROTH) + .union(Mode::S_IXOTH); +/// The mode of each file target that a mapper creates, whatever the umask or a default ACL: +/// `rw-r--r--`. +const FILE_MODE: Mode = Mode::S_IRUSR + .union(Mode::S_IWUSR) + .union(Mode::S_IRGRP) + .union(Mode::S_IROTH); + +/// The targets that a root profile reserves for its runtime, which no mapping may take, besides +/// the `/run/nvx/time` tree that every [`Mapper`] reserves: trees, which a mapping may be neither +/// in nor an ancestor of, and paths, at which a mapping may not be, though it may be below them. +/// +/// The default reserves nothing more. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Reserved { + /// The reserved trees, relative to the target root. + trees: Vec, + /// The reserved paths, relative to the target root. + paths: Vec, +} + +impl Reserved { + /// Reserves `trees` and `paths`, absolute paths as seen from the target root, which must be + /// canonical, as a [`Mapping`]'s target is: otherwise [`InvalidMapping::Target`]. + pub fn new(trees: T, paths: P) -> Result + where + T: IntoIterator, + T::Item: AsRef, + P: IntoIterator, + P::Item: AsRef, + { + let relative = |path: &Path| { + below_its_root(path, true) + .map(Path::to_path_buf) + .ok_or(InvalidMapping::Target) + }; + Ok(Self { + trees: trees + .into_iter() + .map(|tree| relative(tree.as_ref())) + .collect::>()?, + paths: paths + .into_iter() + .map(|path| relative(path.as_ref())) + .collect::>()?, + }) + } + + /// Returns the targets that NVX's container runtime reserves in a container root, which + /// [`protocol::share`](crate::protocol::share) lists for the host and the guest: the trees + /// `/proc`, `/sys`, `/dev`, `/.nvx-agent`, `/etc/machine-id`, `/etc/resolv.conf`, and + /// `/run/nvx/time`, and the paths `/etc`, `/run`, and `/run/nvx`. + pub fn container_root() -> Self { + Self::new(RESERVED_MOUNT_TARGETS, RESERVED_EXACT_MOUNT_TARGETS) + .expect("the container runtime's reserved targets are canonical") + } + + /// Returns whether the relative `target` is reserved: in a reserved tree, or an ancestor of + /// one, or a reserved path. The runtime's tree is always reserved. + fn holds(&self, target: &[u8]) -> bool { + let tree = |tree: &[u8]| within(target, tree) || within(tree, target); + tree(RUNTIME_TREE) + || self.trees.iter().any(|reserved| tree(bytes(reserved))) + || self.paths.iter().any(|reserved| bytes(reserved) == target) + } +} + +/// The root beneath which a [`Mapper`] maps: a descriptor of the root of a mount of a whole file +/// system, and the root's own mounts, each of a whole file system too, on which the mapper may +/// create what a target lacks. +#[derive(Debug)] +pub struct TargetRoot { + /// The root's directory, opened with `O_PATH`. + directory: FileDescriptor, + /// The unique IDs of the root's own mounts: the root's mount first. + mounts: Vec, +} + +impl TargetRoot { + /// Opens the directory `path`, which must be the root of a mount that shows its whole file + /// system, not a bind of a directory below that file system's root, and whose mount becomes + /// the root's own: for example a layered root's overlay, or a guest's `/`. A final symbolic + /// link at `path` is not followed. It needs Linux 6.8 or later, for the unique mount IDs and + /// `statmount`. + pub fn open(path: &Path) -> io::Result { + Self::open_with(&mut SystemKernel, path) + } + + /// Adds the mount that the directory `path` is on, which must show its whole file system, to + /// the root's own mounts, on which the mapper may create what a target lacks, such as the + /// scratch file system of a root without an overlay, and whose root a mapping may cover. A + /// final symbolic link at `path` is not followed. + pub fn add_mount(&mut self, path: &Path) -> io::Result<()> { + self.add_mount_with(&mut SystemKernel, path) + } + + /// Implements [`open`](Self::open) with `kernel`. + pub(crate) fn open_with(kernel: &mut dyn Kernel, path: &Path) -> io::Result { + let directory = open_directory(path)?; + let status = kernel.status(&directory)?; + if !status.mount_root { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} is not the root of a mount", path.display()), + )); + } + check_whole(kernel, status.mount, path)?; + Ok(Self { + directory, + mounts: vec![status.mount], + }) + } + + /// Implements [`add_mount`](Self::add_mount) with `kernel`. + pub(crate) fn add_mount_with( + &mut self, + kernel: &mut dyn Kernel, + path: &Path, + ) -> io::Result<()> { + let mount = kernel.status(&open_directory(path)?)?.mount; + check_whole(kernel, mount, path)?; + if !self.owns(mount) { + self.mounts.push(mount); + } + Ok(()) + } + + /// Returns whether the mount `mount` is one of the root's own. + fn owns(&self, mount: u64) -> bool { + self.mounts.contains(&mount) + } +} + +/// The root beneath which a [`Mapper`] or [`bind`] opens the sources of mappings, such as the +/// guest's mount of the host's export: a descriptor of a directory. +#[derive(Debug)] +pub struct SourceRoot { + /// The root's directory, opened with `O_PATH`. + directory: FileDescriptor, +} + +impl SourceRoot { + /// Opens the directory `path`, not through a final symbolic link. + pub fn open(path: &Path) -> io::Result { + Ok(Self { + directory: open_directory(path)?, + }) + } +} + +/// A step of applying or unmounting a mapping, at which a system call failed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Step { + /// Opening the source beneath its root: a missing source fails with `ENOENT`, a symbolic or + /// magic link on its path with `ELOOP`, and a path that crosses into another mount with + /// `EXDEV`. + Source, + /// Opening a component of the target. + Walk, + /// Creating a missing component of the target. + Create, + /// Reading the status of an open file. + Status, + /// Copying the source's mount, detached. + Clone, + /// Restricting the copy to the mapping's access, `nosuid`, and `nodev`. + Restrict, + /// Attaching the copy at the target. + Attach, + /// Opening the target again to find the mapping. + Locate, + /// Unmounting the mapping. + Unmount, +} + +impl fmt::Display for Step { + /// Writes the step as the verb phrase of a failure: `failed to {step}`. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Source => "open the source", + Self::Walk => "open a component of the target", + Self::Create => "create a component of the target", + Self::Status => "read the status of a file", + Self::Clone => "copy the source's mount", + Self::Restrict => "restrict the mount", + Self::Attach => "attach the mount at the target", + Self::Locate => "find the mapping at its target", + Self::Unmount => "unmount the mapping", + }) + } +} + +/// Why a mapper refused a mapping, or failed to apply or unmount it. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum MappingError { + /// An earlier mapping of the mapper failed, so it refuses every later one. + Latched, + /// The runtime reserves the target, or a tree below it. + Reserved, + /// The target is the target of an earlier mapping, or holds it, and would shadow it. + Overlap { + /// The earlier mapping's target. + mapped: PathBuf, + }, + /// The source is neither a directory nor a regular file, or is not of the mapping's kind. + SourceKind, + /// A component of the target, at this path, is a symbolic link or a magic link. + Link { + /// The component's path in the root. + path: PathBuf, + }, + /// A component of the target, at this path, is not a directory, though the target is below + /// it. + NotDirectory { + /// The component's path in the root. + path: PathBuf, + }, + /// The target exists, but not as the kind of its source. + TargetKind, + /// The target, or a missing component of it, at this path, is not on one of the root's own + /// mounts, where the mapper may create it, nor, for an existing target, inside an earlier + /// mapping. + Foreign { + /// The path in the root. + path: PathBuf, + }, + /// The target is the root of a mount already, which the mapping would shadow, and the root + /// does not own that mount. + MountPoint, + /// The mapping was not the topmost mount at its target once attached, since a rename moved a + /// directory of the target while the walk ran, or, at a teardown, since a rename or another + /// mount at the target since then. + Moved { + /// Whether the mapping stays mounted, wherever it is: because detaching it failed too, + /// in which case a mapper's teardown detaches it, or because a teardown does not unmount + /// what it does not find at its target. + mounted: bool, + }, + /// A system call failed at a step. + System { + /// The step. + step: Step, + /// The call's `errno`. + error: i32, + }, +} + +impl MappingError { + /// Returns the `errno` that best describes the failure, such as a control protocol's status: + /// the call's own for [`MappingError::System`], and otherwise `ECANCELED` for a latched + /// mapper, `EPERM` for a reserved target, `EBUSY` for an overlap or a mount point, `EINVAL` + /// for a kind, `ELOOP` for a link, `ENOTDIR` for a component that is not a directory, `EXDEV` + /// for a foreign mount, and `EAGAIN` for a moved mapping. + pub fn raw_os_error(&self) -> i32 { + let error = match self { + Self::Latched => Errno::ECANCELED, + Self::Reserved => Errno::EPERM, + Self::Overlap { .. } | Self::MountPoint => Errno::EBUSY, + Self::SourceKind | Self::TargetKind => Errno::EINVAL, + Self::Link { .. } => Errno::ELOOP, + Self::NotDirectory { .. } => Errno::ENOTDIR, + Self::Foreign { .. } => Errno::EXDEV, + Self::Moved { .. } => Errno::EAGAIN, + Self::System { error, .. } => return *error, + }; + error as i32 + } +} + +impl fmt::Display for MappingError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Latched => formatter.write_str("an earlier mapping failed"), + Self::Reserved => formatter.write_str("the runtime reserves the target"), + Self::Overlap { mapped } => write!( + formatter, + "the target would shadow the mapping at {}", + mapped.display() + ), + Self::SourceKind => formatter + .write_str("the source is not a directory or a regular file of the mapping's kind"), + Self::Link { path } => write!( + formatter, + "{} is a symbolic link or a magic link", + path.display() + ), + Self::NotDirectory { path } => { + write!(formatter, "{} is not a directory", path.display()) + } + Self::TargetKind => { + formatter.write_str("the target exists as another kind than its source") + } + Self::Foreign { path } => write!( + formatter, + "{} is not on one of the root's own mounts or inside an earlier mapping", + path.display() + ), + Self::MountPoint => { + formatter.write_str("the target is the root of a mount that the root does not own") + } + Self::Moved { mounted } => write!( + formatter, + "the mapping is not at its target{}", + if *mounted { + ", and it stays mounted" + } else { + "" + } + ), + Self::System { step, error } => write!( + formatter, + "failed to {step}: {}", + io::Error::from_raw_os_error(*error) + ), + } + } +} + +impl std::error::Error for MappingError {} + +/// Which mapping of a batch a [`Mapper`] refused or failed to apply, from 0, and why. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct ApplyError { + /// The index of the mapping in its batch. + entry: usize, + /// Why it was refused or failed. + error: MappingError, +} + +impl ApplyError { + /// Returns the index of the mapping in its batch, from 0. + pub fn entry(&self) -> usize { + self.entry + } + + /// Returns why the mapping was refused or failed. + pub fn error(&self) -> &MappingError { + &self.error + } +} + +impl fmt::Display for ApplyError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "mapping {} failed: {}", self.entry, self.error) + } +} + +impl std::error::Error for ApplyError {} + +/// A mapping that a teardown failed to unmount, which stays mounted. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct UnmountFailure { + /// The mapping's target, as an absolute path in the root. + target: PathBuf, + /// Why it was not unmounted. + error: MappingError, +} + +impl UnmountFailure { + /// Returns the mapping's target, as an absolute path in the root. + pub fn target(&self) -> &Path { + &self.target + } + + /// Returns why the mapping was not unmounted: [`MappingError::Moved`] if another mount is at + /// its target, and otherwise the failed [`Step::Locate`] or [`Step::Unmount`], which is also + /// the step of a mapping that a rename moved and that the teardown failed to detach. + pub fn error(&self) -> &MappingError { + &self.error + } +} + +impl fmt::Display for UnmountFailure { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "the mapping at {}: {}", + self.target.display(), + self.error + ) + } +} + +/// The mappings that a teardown failed to unmount, in the order in which it attempted them. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct TeardownError { + /// The failures, which is never empty. + failures: Vec, +} + +impl TeardownError { + /// Returns the failures, in the order in which the teardown attempted them. + pub fn failures(&self) -> &[UnmountFailure] { + &self.failures + } +} + +impl fmt::Display for TeardownError { + /// Writes each failure, separated by `; `. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + for (index, failure) in self.failures.iter().enumerate() { + if index > 0 { + formatter.write_str("; ")?; + } + write!(formatter, "failed to unmount {failure}")?; + } + Ok(()) + } +} + +impl std::error::Error for TeardownError {} + +/// A mapping that a mapper attached and tracks, or a runtime bind that [`bind_with`] made, which +/// [`unbind_with`] unmounts. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Mapped { + /// The target, relative to the root. + target: PathBuf, + /// The unique ID of the mapping's mount. + mount: u64, +} + +/// A mapping that a rename moved away from its target while the walk ran, which the attach +/// failed to detach, and which stays mounted wherever it went. +#[derive(Debug)] +struct Stray { + /// The target, relative to the root. + target: PathBuf, + /// The descriptor of the mapping's mount, through which a teardown detaches it. + tree: FileDescriptor, +} + +/// The applier of a root's mappings, which checks, attaches, tracks, and unmounts them, as the +/// [module](self) describes. +#[derive(Debug)] +pub struct Mapper { + /// The root beneath which it maps. + root: TargetRoot, + /// The targets that the root's profile reserves. + reserved: Reserved, + /// The mappings that it attached, in order. + mapped: Vec, + /// The mapping that a rename moved and that it failed to detach, if any, which its last + /// attach left, since that failure latched it. + stray: Option, + /// Whether a mapping failed, after which it refuses every later one. + latched: bool, +} + +impl Mapper { + /// Returns a mapper of no mappings yet beneath `root`, whose profile reserves `reserved`. + pub fn new(root: TargetRoot, reserved: Reserved) -> Self { + Self { + root, + reserved, + mapped: Vec::new(), + stray: None, + latched: false, + } + } + + /// Applies `mappings` beneath the root, in order, from `source`, as the [module](self) + /// describes, and tracks them. It needs the privilege to mount. + /// + /// The first mapping that is refused or fails is reported with its index, after the mappings + /// before it, which stay mapped, and the mapper refuses every later mapping from then on. + /// Zero mappings do no work. A mapping that a rename moved, and that the mapper failed to + /// detach, [`MappingError::Moved`] with `mounted`, is not tracked, but the teardown detaches + /// it first. + pub fn apply(&mut self, source: &SourceRoot, mappings: &[Mapping]) -> Result<(), ApplyError> { + self.apply_with(&mut SystemKernel, source, mappings) + } + + /// Checks the target of `mapping` as [`apply`](Self::apply) does before it opens anything: + /// that it is neither reserved nor overlaps an earlier mapping. + pub fn check(&self, mapping: &Mapping) -> Result<(), MappingError> { + self.check_target(mapping.target()) + } + + /// Returns whether a mapping failed, after which the mapper refuses every later one. + pub fn is_latched(&self) -> bool { + self.latched + } + + /// Returns the targets of the mappings that the mapper tracks, in the order in which it + /// applied them, relative to the root. + pub fn targets(&self) -> impl ExactSizeIterator { + self.mapped.iter().map(|mapped| mapped.target.as_path()) + } + + /// Unmounts the mappings in reverse order, as the [module](self) describes, and reports every + /// one that it failed to unmount, which stays mounted. It first detaches the mapping that a + /// rename moved and that the mapper failed to detach, if any. + pub fn teardown(self) -> Result<(), TeardownError> { + self.teardown_with(&mut SystemKernel) + } + + /// Implements [`teardown`](Self::teardown) with `kernel`. + pub(crate) fn teardown_with(mut self, kernel: &mut dyn Kernel) -> Result<(), TeardownError> { + let failures: Vec = self + .unmount_with(kernel) + .into_iter() + .map(|(_, failure)| failure) + .collect(); + if failures.is_empty() { + Ok(()) + } else { + Err(TeardownError { failures }) + } + } + + /// Implements [`apply`](Self::apply) with `kernel`. + pub(crate) fn apply_with( + &mut self, + kernel: &mut dyn Kernel, + source: &SourceRoot, + mappings: &[Mapping], + ) -> Result<(), ApplyError> { + for (entry, mapping) in mappings.iter().enumerate() { + self.attach_with( + kernel, + Source::Beneath(source, mapping.source()), + mapping.target(), + mapping.access(), + mapping.kind(), + ) + .map_err(|error| ApplyError { entry, error })?; + } + Ok(()) + } + + /// Moves the mount whose root `mount` refers to, such as a file system that the caller + /// mounted where only it can reach, onto `target`, a path relative to the root, as the mapper + /// attaches a directory's mapping: with `nosuid`, `nodev`, and `access` set while the mount is + /// still where only the caller reaches it, and after the same checks. The mapper then tracks + /// it as a mapping, or, as [`apply`](Self::apply) does, detaches it at the teardown if a + /// rename moved it and detaching it failed. + pub(crate) fn move_mount_with( + &mut self, + kernel: &mut dyn Kernel, + mount: &FileDescriptor, + target: &Path, + access: Access, + ) -> Result<(), MappingError> { + self.attach_with( + kernel, + Source::Mount(mount), + target, + access, + Some(Kind::Directory), + ) + } + + /// Detaches the mapping that a rename moved, if the mapper failed to detach it, then unmounts + /// the mappings in reverse order with `kernel`, forgets them all, and returns, in the order of + /// the attempts, each that it failed to unmount, with its index among the mapper's attaches + /// that left a mount: the moved mapping's, which the mapper attached last, is the number of + /// its mappings. + pub(crate) fn unmount_with(&mut self, kernel: &mut dyn Kernel) -> Vec<(usize, UnmountFailure)> { + let mapped = std::mem::take(&mut self.mapped); + let mut failures = Vec::new(); + if let Some(stray) = self.stray.take() + && let Err(error) = kernel.detach(&stray.tree) + { + let target = absolute(&stray.target); + let error = system(Step::Unmount, error); + failures.push((mapped.len(), UnmountFailure { target, error })); + } + for (index, mapping) in mapped.iter().enumerate().rev() { + if let Err(error) = unmount(kernel, &self.root, mapping) { + let target = absolute(&mapping.target); + failures.push((index, UnmountFailure { target, error })); + } + } + failures + } + + /// Checks the relative `target` as [`check`](Self::check) does. + fn check_target(&self, target: &Path) -> Result<(), MappingError> { + let target = bytes(target); + if self.reserved.holds(target) { + return Err(MappingError::Reserved); + } + match self + .mapped + .iter() + .find(|mapped| within(bytes(&mapped.target), target)) + { + Some(mapped) => Err(MappingError::Overlap { + mapped: absolute(&mapped.target), + }), + None => Ok(()), + } + } + + /// Checks the relative `target`, attaches `source` there with `access`, and tracks the + /// mapping, unless the mapper is latched; a refusal or failure latches it, and the mapper + /// keeps a mapping that a rename moved and that the attach failed to detach. + fn attach_with( + &mut self, + kernel: &mut dyn Kernel, + source: Source<'_>, + target: &Path, + access: Access, + kind: Option, + ) -> Result<(), MappingError> { + if self.latched { + return Err(MappingError::Latched); + } + let attached = self + .check_target(target) + .map_err(AttachFailure::from) + .and_then(|()| { + let mounts: Vec = self.mapped.iter().map(|mapped| mapped.mount).collect(); + attach(kernel, &self.root, &mounts, source, target, access, kind) + }); + match attached { + Ok(mount) => { + self.mapped.push(Mapped { + target: target.to_path_buf(), + mount, + }); + Ok(()) + } + Err(failure) => { + self.latched = true; + self.stray = failure.stray.map(|tree| Stray { + target: target.to_path_buf(), + tree, + }); + Err(failure.error) + } + } + } +} + +/// Binds the source of `mapping`, beneath `source`, at its target beneath `root`, with the walk, +/// the creation, the checks of kinds and mounts, and the attach of a [`Mapper`]'s mapping, as the +/// [module](self) describes, but without the checks of reserved targets and overlaps, which a +/// runtime's own binds, such as a generated machine ID over `/etc/machine-id`, would fail, and +/// without tracking it: it lasts as long as the mount namespace, or until its caller unmounts it. +/// So does a bind that a rename moved and that it failed to detach, wherever it went, which it +/// reports as [`MappingError::Moved`] with `mounted`. It needs the privilege to mount. +pub fn bind(root: &TargetRoot, source: &SourceRoot, mapping: &Mapping) -> Result<(), MappingError> { + bind_with(&mut SystemKernel, root, source, mapping).map(drop) +} + +/// Implements [`bind`] with `kernel`, and returns the bind, which [`unbind_with`] unmounts. +pub(crate) fn bind_with( + kernel: &mut dyn Kernel, + root: &TargetRoot, + source: &SourceRoot, + mapping: &Mapping, +) -> Result { + attach( + kernel, + root, + &[], + Source::Beneath(source, mapping.source()), + mapping.target(), + mapping.access(), + mapping.kind(), + ) + .map(|mount| Mapped { + target: mapping.target().to_path_buf(), + mount, + }) + .map_err(|failure| failure.error) +} + +/// Unmounts `binds`, which [`bind_with`] made beneath `root`, in reverse order, with `kernel`, as a +/// mapper's teardown unmounts its mappings: each that is the topmost mount at its target, by its +/// name in its parent directory, without detaching a busy one. It attempts each, whatever failed +/// before, and reports every one that it failed to unmount, which stays mounted. +pub(crate) fn unbind_with( + kernel: &mut dyn Kernel, + root: &TargetRoot, + binds: &[Mapped], +) -> Result<(), TeardownError> { + let mut failures = Vec::new(); + for bind in binds.iter().rev() { + if let Err(error) = unmount(kernel, root, bind) { + let target = absolute(&bind.target); + failures.push(UnmountFailure { target, error }); + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(TeardownError { failures }) + } +} + +/// What a mapping attaches: the object at a path beneath a source root, whose mount the attach +/// copies, or a mount that it moves. +#[derive(Clone, Copy, Debug)] +enum Source<'a> { + /// The object at a relative path beneath a source root. + Beneath(&'a SourceRoot, &'a Path), + /// The mount whose root a descriptor refers to. + Mount(&'a FileDescriptor), +} + +/// Why an attach failed, with the descriptor of the mapping's mount if a rename moved it and +/// detaching it failed too, so that it stays mounted wherever it went. +#[derive(Debug)] +struct AttachFailure { + /// Why it failed. + error: MappingError, + /// The descriptor of the mapping's mount, if it stays mounted. + stray: Option, +} + +impl From for AttachFailure { + fn from(error: MappingError) -> Self { + Self { error, stray: None } + } +} + +/// Attaches `source` at the relative `target` beneath `root`, with `access`, as the +/// [module](self) describes, where `mapped` are the mounts of the earlier mappings, inside which +/// an existing target may be, and returns the unique ID of the new mount. A source of another +/// kind than `kind`, if given, is refused. +fn attach( + kernel: &mut dyn Kernel, + root: &TargetRoot, + mapped: &[u64], + source: Source<'_>, + target: &Path, + access: Access, + kind: Option, +) -> Result { + let opened; + let (copied, found, clone) = match source { + Source::Beneath(source, path) => { + let (descriptor, found) = open_source(kernel, source, path)?; + opened = descriptor; + (&opened, found, true) + } + Source::Mount(descriptor) => { + let status = kernel + .status(descriptor) + .map_err(|error| system(Step::Source, error))?; + if !status.mount_root { + return Err(MappingError::SourceKind.into()); + } + let found = Kind::of(status.kind).ok_or(MappingError::SourceKind)?; + (descriptor, found, false) + } + }; + if kind.is_some_and(|kind| kind != found) { + return Err(MappingError::SourceKind.into()); + } + let destination = walk(kernel, root, mapped, target, found)?; + let tree = kernel + .open_tree(copied, clone) + .map_err(|error| system(Step::Clone, error))?; + let (set, clear) = access.attributes(); + kernel + .set_attributes(&tree, set, clear) + .map_err(|error| system(Step::Restrict, error))?; + let mount = kernel + .status(&tree) + .map_err(|error| system(Step::Status, error))? + .mount; + kernel + .move_mount(&tree, &destination) + .map_err(|error| system(Step::Attach, error))?; + match locate(kernel, root, target) { + Ok((_, status)) if status.mount == mount && status.mount_root => Ok(mount), + // The tree keeps the mount busy, so only a detach takes it off wherever it went. + _ => match kernel.detach(&tree) { + Ok(()) => Err(MappingError::Moved { mounted: false }.into()), + Err(_) => Err(AttachFailure { + error: MappingError::Moved { mounted: true }, + stray: Some(tree), + }), + }, + } +} + +/// Opens `path` beneath `source`, or the source root itself for an empty `path`, and returns it +/// and its kind, which must be a mapping's. +fn open_source( + kernel: &mut dyn Kernel, + source: &SourceRoot, + path: &Path, +) -> Result<(FileDescriptor, Kind), MappingError> { + // `openat2` resolves no empty path, so the root itself is `.` beneath it, which the same + // resolution confines to the root's own mount, as it does every other source. + let path = if path.as_os_str().is_empty() { + Path::new(".") + } else { + path + }; + let opened = sys::path_c_string(path).and_then(|path| { + let descriptor = kernel.open_beneath( + &source.directory, + &path, + OpenFlags::O_PATH, + Mode::empty(), + false, + )?; + let status = kernel.status(&descriptor)?; + Ok((descriptor, status)) + }); + let (descriptor, status) = opened.map_err(|error| system(Step::Source, error))?; + let kind = Kind::of(status.kind).ok_or(MappingError::SourceKind)?; + Ok((descriptor, kind)) +} + +/// Opens each component of the relative `target` beneath `root`, creating each that is missing, +/// as a directory, or as a regular file for the last one of a file's mapping, and returns the +/// target, which must be of `kind`, on one of the root's own mounts or in one of `mapped`, and +/// not the root of a mount, unless the root owns that mount, which the mapping then covers. +fn walk( + kernel: &mut dyn Kernel, + root: &TargetRoot, + mapped: &[u64], + target: &Path, + kind: Kind, +) -> Result { + let components: Vec<&OsStr> = target.iter().collect(); + let mut current: Option = None; + for (index, component) in components.iter().enumerate() { + let parent = current.as_ref().unwrap_or(&root.directory); + let name = + sys::c_string(component.as_bytes()).map_err(|error| system(Step::Walk, error))?; + let wanted = if index + 1 == components.len() { + kind + } else { + Kind::Directory + }; + let refused = |error| match error { + Errno::ELOOP => MappingError::Link { + path: leading(target, index + 1), + }, + Errno::ENOTDIR => MappingError::NotDirectory { + path: leading(target, index), + }, + error => system(Step::Walk, error), + }; + let open = |kernel: &mut dyn Kernel| { + kernel.open_beneath(parent, &name, OpenFlags::O_PATH, Mode::empty(), true) + }; + let opened = match open(kernel) { + Ok(opened) => opened, + Err(Errno::ENOENT) => { + let created = create(kernel, root, parent, &name, wanted, || { + leading(target, index + 1) + })?; + // What is there now, what it created or what another process put there first or + // since, is checked as an existing component. + let opened = open(kernel).map_err(refused)?; + if created && wanted == Kind::Directory { + give_mode(kernel, &opened)?; + } + opened + } + Err(error) => return Err(refused(error)), + }; + current = Some(opened); + } + let destination = current.ok_or_else(|| system(Step::Walk, Errno::EINVAL))?; + let status = kernel + .status(&destination) + .map_err(|error| system(Step::Status, error))?; + if Kind::of(status.kind) != Some(kind) { + return Err(MappingError::TargetKind); + } + // The root of one of the root's own mounts, such as the tmpfs at a guest's `/tmp`, is a + // target that the mapping covers; the root of any other, an earlier mapping's included, is + // not. + if status.mount_root && !root.owns(status.mount) { + return Err(MappingError::MountPoint); + } + if !root.owns(status.mount) && !mapped.contains(&status.mount) { + return Err(MappingError::Foreign { + path: absolute(target), + }); + } + Ok(destination) +} + +/// Creates `name` in `parent`, a directory on one of `root`'s own mounts, as a directory with no +/// permissions, which [`give_mode`] gives [`DIRECTORY_MODE`] once the walk opens it, or as an +/// empty regular file with exactly [`FILE_MODE`] for [`Kind::File`], whatever the umask or a +/// default ACL, and returns whether it created it: not if another process created an entry of +/// that name first. A parent on another mount is refused as [`MappingError::Foreign`] at +/// `path`. +fn create( + kernel: &mut dyn Kernel, + root: &TargetRoot, + parent: &FileDescriptor, + name: &CStr, + kind: Kind, + path: impl FnOnce() -> PathBuf, +) -> Result { + let status = kernel + .status(parent) + .map_err(|error| system(Step::Status, error))?; + if !root.owns(status.mount) { + return Err(MappingError::Foreign { path: path() }); + } + let created = match kind { + Kind::Directory => kernel.create_directory(parent, name, Mode::empty()), + Kind::File => kernel.create_file(parent, name, FILE_MODE), + }; + match created { + Ok(()) => Ok(true), + Err(Errno::EEXIST) => Ok(false), + Err(error) => Err(system(Step::Create, error)), + } +} + +/// Gives the directory that `opened` refers to [`DIRECTORY_MODE`], through `opened`, if it is +/// the one that [`create`] created, with no permissions, before the walk opened it: if it still +/// has no permissions, and the mapper's user, its effective user ID, as its owner. A directory +/// that a rename put in its place keeps its mode. It keeps the set-group-ID bit that a directory +/// inherits from a parent that has it, as `mkdir` does. +fn give_mode(kernel: &mut dyn Kernel, opened: &FileDescriptor) -> Result<(), MappingError> { + let status = kernel + .status(opened) + .map_err(|error| system(Step::Status, error))?; + let permissions = Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO; + let created = status.kind == FileKind::Directory + && status.owner == nix::unistd::geteuid().as_raw() + && status.mode & permissions.bits() == 0; + if !created { + return Ok(()); + } + let inherited = Mode::from_bits_truncate(status.mode) & Mode::S_ISGID; + kernel + .change_mode(opened, DIRECTORY_MODE | inherited) + .map_err(|error| system(Step::Create, error)) +} + +/// Opens the relative `target` beneath `root`, through the mounts below it, and returns it and +/// its status: the topmost mount at the target, if any. +fn locate( + kernel: &mut dyn Kernel, + root: &TargetRoot, + target: &Path, +) -> Result<(FileDescriptor, sys::FileStatus), Errno> { + let path = sys::path_c_string(target)?; + let descriptor = kernel.open_beneath( + &root.directory, + &path, + OpenFlags::O_PATH, + Mode::empty(), + true, + )?; + let status = kernel.status(&descriptor)?; + Ok((descriptor, status)) +} + +/// Unmounts `mapping` beneath `root`, after checking that its mount is the topmost one at its +/// target: by its name in its parent directory, which it opens from the root, since a +/// descriptor of the mapping itself would keep it busy. +fn unmount( + kernel: &mut dyn Kernel, + root: &TargetRoot, + mapping: &Mapped, +) -> Result<(), MappingError> { + let located = (|| -> Result<_, Errno> { + let parent = match mapping.target.parent() { + Some(parent) if !parent.as_os_str().is_empty() => { + let path = sys::path_c_string(parent)?; + let flags = OpenFlags::O_PATH | OpenFlags::O_DIRECTORY; + Some(kernel.open_beneath(&root.directory, &path, flags, Mode::empty(), true)?) + } + _ => None, + }; + let name = mapping.target.file_name().ok_or(Errno::EINVAL)?; + let name = sys::c_string(name.as_bytes())?; + let directory = parent.as_ref().unwrap_or(&root.directory); + let status = kernel + .open_beneath(directory, &name, OpenFlags::O_PATH, Mode::empty(), true) + .and_then(|target| kernel.status(&target))?; + Ok((parent, name, status)) + })(); + let (parent, name, status) = located.map_err(|error| system(Step::Locate, error))?; + if status.mount != mapping.mount || !status.mount_root { + return Err(MappingError::Moved { mounted: true }); + } + kernel + .unmount_beneath(parent.as_ref().unwrap_or(&root.directory), &name) + .map_err(|error| system(Step::Unmount, error)) +} + +/// Opens the directory `path` with `O_PATH`, not through a final symbolic link. +fn open_directory(path: &Path) -> io::Result { + let flags = + OpenFlags::O_PATH | OpenFlags::O_DIRECTORY | OpenFlags::O_NOFOLLOW | OpenFlags::O_CLOEXEC; + let path = sys::path_c_string(path)?; + Ok(sys::open(&path, flags, Mode::empty())?) +} + +/// Refuses `mount`, the mount that `path` is on, unless it shows its whole file system: on a +/// bind of a directory, a rename through another mount of its file system may move what a walk +/// opened out of the bind. +fn check_whole(kernel: &mut dyn Kernel, mount: u64, path: &Path) -> io::Result<()> { + if kernel.whole_file_system(mount)? { + return Ok(()); + } + Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!( + "{} is on a mount of a directory below its file system's root, not of the whole \ + file system", + path.display() + ), + )) +} + +/// Returns the failure of a system call at `step` with `error`. +fn system(step: Step, error: Errno) -> MappingError { + MappingError::System { + step, + error: error as i32, + } +} + +/// Returns the bytes of `path`. +fn bytes(path: &Path) -> &[u8] { + path.as_os_str().as_bytes() +} + +/// Returns whether the relative path `inner` is the relative path `outer` or below it. +fn within(inner: &[u8], outer: &[u8]) -> bool { + inner + .strip_prefix(outer) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(b"/")) +} + +/// Returns the first `count` components of the relative `target`, as an absolute path. +fn leading(target: &Path, count: usize) -> PathBuf { + let mut path = PathBuf::from("/"); + path.extend(target.iter().take(count)); + path +} + +/// Returns the relative `target` as an absolute path. +fn absolute(target: &Path) -> PathBuf { + Path::new("/").join(target) +} diff --git a/nvx-rs/src/guest/mappings/tests.rs b/nvx-rs/src/guest/mappings/mapper/tests.rs similarity index 99% rename from nvx-rs/src/guest/mappings/tests.rs rename to nvx-rs/src/guest/mappings/mapper/tests.rs index 09b66b627..b4d5263d0 100644 --- a/nvx-rs/src/guest/mappings/tests.rs +++ b/nvx-rs/src/guest/mappings/mapper/tests.rs @@ -10,7 +10,9 @@ use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use super::*; +use crate::guest::mappings::MAX_PATH_BYTES; use crate::guest::root::tests::{Call, FakeKernel, Operation, attach_calls}; +use crate::guest::sys::MountAttributes; mod privileged; diff --git a/nvx-rs/src/guest/mappings/tests/privileged.rs b/nvx-rs/src/guest/mappings/mapper/tests/privileged.rs similarity index 99% rename from nvx-rs/src/guest/mappings/tests/privileged.rs rename to nvx-rs/src/guest/mappings/mapper/tests/privileged.rs index 81bf0d862..a03f3c019 100644 --- a/nvx-rs/src/guest/mappings/tests/privileged.rs +++ b/nvx-rs/src/guest/mappings/mapper/tests/privileged.rs @@ -1,7 +1,7 @@ //! Tests of the mapper with the kernel itself, which need the privilege to mount and Linux 6.8 or //! later, for the unique mount IDs. Each runs in a private mount namespace of its own thread, on //! tmpfs roots below a temporary directory, and they are ignored unless asked for: -//! `cargo test --all-features -- --ignored guest::mappings::tests::privileged`, as root. +//! `cargo test --all-features -- --ignored guest::mappings::mapper::tests::privileged`, as root. //! //! They cover what the fake kernel cannot: symbolic links and magic links at every component, a //! rename race during the walk, kinds, a target inside another mapping, reserved targets, the @@ -21,6 +21,7 @@ use std::sync::{Arc, RwLock}; use nix::sys::statvfs::{FsFlags, statvfs}; use super::*; +use crate::guest::sys::MountFlags; /// A target root, a source root, and a directory outside both, each a tmpfs below a temporary /// directory, in a private mount namespace of the calling thread. diff --git a/nvx-rs/src/guest/mappings/table.rs b/nvx-rs/src/guest/mappings/table.rs index 2c7f162c4..6a873217a 100644 --- a/nvx-rs/src/guest/mappings/table.rs +++ b/nvx-rs/src/guest/mappings/table.rs @@ -21,9 +21,8 @@ use crate::protocol::{self, GuestHostMap, MAX_HOST_MAPPINGS, ProtocolError}; /// parts, each a `MAPS` payload of consecutive entries, in order, which /// [`protocol::decode_guest_maps_payload`] reads. [`apply`](Self::apply) checks each part against /// the table, and hands its entries, as [`Mapping`]s, to the caller, which maps them beneath the -/// root of its choice, from the host export: through a [`Mapper`](super::Mapper) beneath a -/// guest's own `/` or a container's root, for example, or through a layered -/// [`Root`](crate::guest::root::Root). +/// root of its choice, from the host export: through a mapper beneath a guest's own `/` or a +/// container's root, for example, or through a layered root. /// /// - The table refuses a part as a whole, and changes nothing, which [`TableError::Refused`] /// reports with the entry that the table expects next and the [`Refusal`]: once a mapping @@ -39,32 +38,26 @@ use crate::protocol::{self, GuestHostMap, MAX_HOST_MAPPINGS, ProtocolError}; /// mappings is complete at once, and its agent maps nothing. /// /// The root keeps the mappings, and its own teardown tears the table down, in reverse order, such -/// as [`Mapper::teardown`](super::Mapper::teardown), which reports each mapping that stays mounted, -/// or [`Root::teardown`](crate::guest::root::Root::teardown). +/// as a mapper's teardown, which reports each mapping that stays mounted, or a layered root's. /// /// NVX's managed agent applies its table through one, beneath its own root, `/`, in direct mode, /// and beneath the container's assembled root in sandbox mode, with a mapper that it opens at the /// first part that the table hands it, so that a table of zero mappings opens nothing. /// /// ```no_run -/// use std::path::Path; -/// -/// use nvx::guest::mappings::{ -/// Mapper, MappingTable, Reserved, SourceRoot, TableError, TargetRoot, -/// }; +/// use nvx::guest::mappings::{Mapping, MappingTable, TableError}; /// /// # fn parts() -> Vec> { Vec::new() } +/// # fn mount(_: &Mapping) -> std::io::Result<()> { Ok(()) } /// # fn main() -> Result<(), Box> { /// let mut table = MappingTable::announced(&std::fs::read("/proc/cmdline")?)?; -/// let root = TargetRoot::open(Path::new("/newroot"))?; -/// let mut mapper = Mapper::new(root, Reserved::container_root()); -/// let export = SourceRoot::open(Path::new("/run/nvx/hostfs/root"))?; /// // Each part of the table, in the order in which the host sends them. /// for part in parts() { +/// // `mount` mounts one mapping beneath the agent's root, from the host export. /// let applied = table.apply(&part, |mappings| { -/// mapper -/// .apply(&export, mappings) -/// .map_err(|error| (error.entry(), error)) +/// mappings.iter().enumerate().try_for_each(|(index, mapping)| { +/// mount(mapping).map_err(|error| (index, error)) +/// }) /// }); /// match applied { /// Ok(()) => println!("{} of {} mappings applied", table.applied(), table.expected()), @@ -73,9 +66,9 @@ use crate::protocol::{self, GuestHostMap, MAX_HOST_MAPPINGS, ProtocolError}; /// Err(error) => println!("{error}"), /// } /// } -/// // Start workloads only once the table is complete; then: +/// // Start workloads only once the table is complete; the root keeps the mappings until its +/// // teardown. /// assert!(table.is_complete()); -/// mapper.teardown()?; /// # Ok(()) /// # } /// ``` diff --git a/nvx-rs/src/guest/mod.rs b/nvx-rs/src/guest/mod.rs index e0cdc0f50..a3f4cb64a 100644 --- a/nvx-rs/src/guest/mod.rs +++ b/nvx-rs/src/guest/mod.rs @@ -4,22 +4,29 @@ //! a program; [`entry`], through which a program that it starts enters an execution's //! namespaces, view, root, and identity; [`process`], through which it collects the status of //! each child that it names, and of no other; [`cgroup`], through which it places, accounts, -//! kills, and settles the processes of its executions; [`mappings`], through which it mounts host -//! mappings beneath the descriptors of the roots that it names, and keeps the account of a host's -//! mapping table; [`exec`], which drives each program as one execution, with its launch, its -//! bounded output and input, its ending, and its outcome, alone or, through its -//! [`binding`](exec::binding), under the [execution engine](crate::exec); [`root`], through which -//! it bootstraps the guest for a layered root, assembles the root, mounts live shares and mappings -//! in it, and tears it down; -//! [`gpt`], through which it reads the partition table of a GPT disk that the kernel attached as -//! a block device; and, on x86-64, `clone`, through which a template's guest prepares for and -//! requests a snapshot's capture before its root's assembly, behind the caller's fence of -//! workload admission, with nothing mounted from the devices that its clones replace, and -//! through which each clone that a restore of the snapshot starts repairs its restore: it -//! activates the restore's memory target, reseeds the kernel's random number generator, and -//! finishes the restore, with its acknowledgement, and then takes its own configuration from the -//! host, in one Activate on a restricted control session, with which it assembles its root and -//! checks its workload identity before it admits any execution. +//! kills, and settles the processes of its executions; [`mappings`], the host mappings that it +//! mounts, and its account of a host's mapping table; [`exec`], which drives each program as one +//! execution, with its launch, its bounded output and input, its ending, and its outcome, alone +//! or, through its [`binding`](exec::binding), under the [execution engine](crate::exec); and, +//! on x86-64, `clone`, through which a template's guest prepares for and requests a snapshot's +//! capture before its root's assembly, behind the caller's fence of workload admission, with +//! nothing mounted from the devices that its clones replace, and through which each clone that a +//! restore of the snapshot starts repairs its restore: it activates the restore's memory target, +//! reseeds the kernel's random number generator, and finishes the restore, with its +//! acknowledgement, and then takes its own configuration from the host, in one Activate on a +//! restricted control session. +//! +//! The guest's space, the root that an init assembles and what it mounts in it, is each init's +//! own. NVX's own space is internal reference code, which NVX's guest programs use: it is hidden +//! from this documentation and unstable, and it becomes crate-private once nothing outside NVX +//! uses it. It is `root`, which bootstraps the guest for a layered root, assembles the root, +//! mounts live shares and mappings in it, and tears it down; `gpt`, which reads the partition +//! table of a GPT disk that the kernel attached as a block device; the mapper of `mappings`, which +//! mounts host mappings beneath the descriptors of the roots that it names; and the activation's +//! application, `clone::apply` and its types, with which a clone assembles its root and checks +//! its workload identity before it admits any execution. The contracts that every space reads +//! stay public: the mapping values and [`MappingTable`](mappings::MappingTable), and the tokens +//! and records of [`protocol`](crate::protocol) and [`activation`](crate::activation). //! //! Each other module holds one program, and the crate's binary of the same name runs its `main`. //! Two of them also offer their steps as typed calls, which any guest init or agent runs in its @@ -104,6 +111,7 @@ pub mod exec; #[cfg(target_arch = "x86_64")] #[doc(hidden)] pub mod exit; +#[doc(hidden)] pub mod gpt; pub mod ingress; #[doc(hidden)] @@ -115,6 +123,7 @@ pub mod mmio_write; pub mod nvxs; pub mod process; pub mod reseed; +#[doc(hidden)] pub mod root; pub mod spawn; pub mod terminal; diff --git a/nvx-rs/src/guest/root.rs b/nvx-rs/src/guest/root.rs index ae63a9cd8..f65f02ad3 100644 --- a/nvx-rs/src/guest/root.rs +++ b/nvx-rs/src/guest/root.rs @@ -2,10 +2,13 @@ //! mappings in it, and the host export from which mappings come, and tear it down, for a guest //! init or agent, whether or not it is PID 1. //! -//! - [`bootstrap`] prepares the guest once: it creates the agent's and the workload's sibling -//! cgroups of a [`Layout`](super::cgroup::Layout), moves every process of their parent into the -//! agent's, applies the agent's and the workload's resource values, and keeps user namespaces -//! unavailable. +//! This module is NVX's internal reference code of the guest's space, hidden from the +//! documentation and unstable: it becomes crate-private once nothing outside NVX uses it. +//! +//! - [`bootstrap`](fn@bootstrap) prepares the guest once: it creates the agent's and the +//! workload's sibling cgroups of a [`Layout`](super::cgroup::Layout), moves every process of +//! their parent into the agent's, applies the agent's and the workload's resource values, and +//! keeps user namespaces unavailable. //! - [`assemble`] finds the block devices of an [`Assembly`] by their MMIO windows, checks and //! flushes them, and mounts the root: an overlay, mounted `nosuid,nodev` with the option set of //! the caller's [`OverlayMode`], which it checks the kernel applied, of the read-only layers of @@ -1476,7 +1479,7 @@ impl fmt::Display for Mount { #[derive(Debug)] #[non_exhaustive] pub enum Error { - /// A step of [`bootstrap`] failed. + /// A step of [`bootstrap`](fn@bootstrap) failed. Bootstrap { /// The step that failed. step: BootstrapStep, diff --git a/nvx-rs/src/guest/root/share.rs b/nvx-rs/src/guest/root/share.rs index 9ed23c104..5861a0ddf 100644 --- a/nvx-rs/src/guest/root/share.rs +++ b/nvx-rs/src/guest/root/share.rs @@ -142,7 +142,7 @@ impl fmt::Display for ShareRefusal { impl From for Access { /// Returns the access of the guest's mount of a host export of `mode`, which - /// [`Root::mount_export`] takes: read-only for `ro`, and read-write for `rw`. + /// `Root::mount_export` takes: read-only for `ro`, and read-write for `rw`. fn from(mode: ExportMode) -> Self { match mode { ExportMode::ReadOnly => Self::ReadOnly, diff --git a/nvx-rs/src/lib.rs b/nvx-rs/src/lib.rs index ba5d8ae25..31684f719 100644 --- a/nvx-rs/src/lib.rs +++ b/nvx-rs/src/lib.rs @@ -42,16 +42,16 @@ //! a program in a new process (`guest::spawn`), has the program enter an execution's //! namespaces, view, root, and identity (`guest::entry`), collects the status of each child //! that it names (`guest::process`), places, kills, and settles the processes of its -//! executions in cgroups (`guest::cgroup`), mounts host mappings beneath the descriptors of the -//! roots that it names, and keeps the account of a host's mapping table (`guest::mappings`), -//! drives each program as one execution, with its launch, bounded output, input, ending, and -//! outcome (`guest::exec`), alone or under the execution engine (`guest::exec::binding`), -//! bootstraps the guest for a layered root, assembles the root, mounts live shares and mappings -//! in it, and tears it down (`guest::root`), and reads the partition table of a GPT disk's block -//! device (`guest::gpt`), the typed calls through which it runs the time ABI's steps -//! (`guest::time`) and reseeds after a restore (`guest::reseed`) in its own process, and the -//! preparation of a template's guest for a capture before its root's assembly, and the repair -//! of its clones (`guest::clone`). The crate's `nvx-*` guest binaries run the programs. +//! executions in cgroups (`guest::cgroup`), describes host mappings and keeps the account of a +//! host's mapping table (`guest::mappings`), and drives each program as one execution, with its +//! launch, bounded output, input, ending, and outcome (`guest::exec`), alone or under the +//! execution engine (`guest::exec::binding`), the typed calls through which it runs the time +//! ABI's steps (`guest::time`) and reseeds after a restore (`guest::reseed`) in its own process, +//! and the preparation of a template's guest for a capture before its root's assembly, and the +//! repair of its clones (`guest::clone`). The crate's `nvx-*` guest binaries run the programs. +//! NVX's own guest space, which assembles a layered root, reads GPT disks, mounts host mappings, +//! and applies a clone's activation, is internal reference code: hidden, unstable, and +//! crate-private once nothing outside NVX uses it. //! //! # Example //!