Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions native/.cargo/mutants.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ exclude_re = [
"suidhelper/src/net/vm\\.rs:.*VmNet<'_>::",
"suidhelper/src/cli/vm/claim\\.rs:.*SocketPin<'_>::",
"suidhelper/src/cli/vm/teardown\\.rs:.*Teardown::unpin_sockets",
# The metadata-device check runs as root against a fake dmsetup; killed by suidhelper's
# a_meta_that_is_not_the_pools_metadata_is_refused_before_any_snapshot_as_root (tests/e2e/
# fork_delta.rs) in the privileged E2E job.
"suidhelper/src/cli/fork_delta\\.rs:.*replace != with == in <impl Op for ThinForkDelta>::run$",
# Guest network setup runs inside a booted guest; killed by test/e2e/guest_network_test.exs
# in the KVM integration job.
"guest-agent/src/net\\.rs:.*GuestNet::(from_proc|configure)",
Expand Down
2 changes: 1 addition & 1 deletion native/hyperrs-linux/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ license = "MIT"
redundant_field_names = "allow"

[dependencies]
derive_more = { version = "2.1.1", features = ["as_ref", "display", "constructor", "from", "into", "try_unwrap"] }
derive_more = { version = "2.1.1", features = ["as_ref", "constructor", "deref", "display", "from", "into", "try_unwrap"] }
hyperrs-fs = { path = "../hyperrs-fs" }
hyperrs-process = { path = "../hyperrs-process" }
netlink-packet-core = "0.9"
Expand Down
65 changes: 65 additions & 0 deletions native/hyperrs-linux/src/dm/dev_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use super::name::MAPPER_PREFIX;
use derive_more::{Deref, Into};
use hyperrs_fs::path::{self, IsAbsolute, SafePathBuf, StrictComponents};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use thiserror::Error as ThisError;

// The kernel's `isspace` (lib/ctype.c) classes the Latin-1 byte 0xA0 as a
// space, so `dm_split_args` splits a UTF-8 path through any char holding it.
const KERNEL_SPACE: u8 = 0xa0;

/// A table `<dev path>` operand: an absolute, strict path to a non-dm block
/// device that holds no byte the kernel's table tokenizer splits on, so it
/// renders as exactly one operand.
#[derive(Debug, Clone, PartialEq, Eq, Deref, Into)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize),
serde(try_from = "PathBuf")
)]
pub struct DevPath(SafePathBuf<IsAbsolute, StrictComponents>);

#[derive(Debug, ThisError)]
pub enum DevPathError {
#[error(transparent)]
Path(#[from] path::ValidationError),
#[error("{}: whitespace would split it into several table operands", .0.display())]
Splits(PathBuf),
#[error("{}: a dm device is a table operand by name, not by path", .0.display())]
DmDevice(PathBuf),
}

impl TryFrom<SafePathBuf<IsAbsolute, StrictComponents>> for DevPath {
type Error = DevPathError;

fn try_from(path: SafePathBuf<IsAbsolute, StrictComponents>) -> Result<Self, Self::Error> {
let bytes = path.as_path().as_os_str().as_bytes();
if bytes.contains(&KERNEL_SPACE)
|| String::from_utf8_lossy(bytes).contains(char::is_whitespace)
{
return Err(DevPathError::Splits(path.into()));
}
if path.as_path().starts_with(Path::new(MAPPER_PREFIX)) {
return Err(DevPathError::DmDevice(path.into()));
}
Ok(Self(path))
}
}

impl TryFrom<PathBuf> for DevPath {
type Error = DevPathError;

fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
SafePathBuf::try_from(path)?.try_into()
}
}

impl FromStr for DevPath {
type Err = DevPathError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
PathBuf::from(s).try_into()
}
}
6 changes: 4 additions & 2 deletions native/hyperrs-linux/src/dm/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Utilities for operating on linux `dsetup`.

mod dev_path;
mod device;
mod name;
mod table;
Expand All @@ -8,14 +9,15 @@ pub mod thin_dump;

use super::Access;
use derive_more::Constructor;
pub use dev_path::{DevPath, DevPathError};
pub use device::{Device, NumberError};
use hyperrs_process::binary::RootSafeBin;
pub use name::{DmName, InvalidDmName, OpenDeviceError, ParseDmDeviceError, SizeError};
use std::ffi::OsStr;
use std::io;
pub use table::{
DevPath, DmTable, LinearTable, Origin, ParseTableError, Persistence, Role, SnapshotTable,
ThinPoolTable, ThinTable,
DmTable, LinearTable, Origin, ParseTableError, Persistence, Role, SnapshotTable, ThinPoolTable,
ThinTable,
};
pub use thin::{
Active, Inactive, OpenThinError, ParseThinIdError, ParseThinMessageError, SnapshotError, Thin,
Expand Down
9 changes: 3 additions & 6 deletions native/hyperrs-linux/src/dm/table.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
use super::name::MAPPER_PREFIX;
use super::{DevPath, DevPathError};
use super::{DmName, ParseDmDeviceError, ParseThinIdError, ThinId};
use derive_more::{Display, TryUnwrap};
use hyperrs_fs::path::{self, IsAbsolute, SafePathBuf, StrictComponents};
use std::num::ParseIntError;
use std::str::FromStr;
use thiserror::Error as ThisError;

/// A table `<dev path>` operand: an absolute path to a block device.
pub type DevPath = SafePathBuf<IsAbsolute, StrictComponents>;

/// Dmsetup tables. See `man dmsetup` for more info, under the `--table` docs.
#[derive(Debug, Clone, PartialEq, Eq, Display)]
pub enum DmTable {
Expand Down Expand Up @@ -115,9 +112,9 @@ pub enum ParseTableError {
/// A `/dev/mapper/` operand that is not a valid dm name.
#[error(transparent)]
Device(#[from] ParseDmDeviceError),
/// A backing operand that is not an absolute, strict path.
/// A backing operand that is not a [`DevPath`].
#[error("backing file path: {0}")]
Path(#[from] path::ValidationError),
Path(#[from] DevPathError),
/// A sector count, chunk size, block size, or low-water mark that is not a `u64`.
#[error("table number: {0}")]
Number(#[from] ParseIntError),
Expand Down
48 changes: 44 additions & 4 deletions native/hyperrs-linux/src/dm/thin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ pub enum SnapshotError {
#[derive(Debug, Clone)]
pub struct ThinPool<'a> {
device: Device<'a>,
metadata: DeviceNumber,
}

#[derive(Debug, Clone, Copy)]
Expand All @@ -150,21 +151,36 @@ pub struct Thin<'a, S> {
impl<'a> ThinPool<'a> {
pub(super) fn open(dmsetup: &'a Dmsetup, name: &DmName) -> Result<Self, ThinPoolError> {
let table = dmsetup.run([OsStr::new("table"), name.as_ref()])?;
match table.lines().collect::<Vec<_>>().as_slice() {
[line] if line.split_whitespace().nth(2) == Some("thin-pool") => Ok(Self {
match Self::pool_metadata(&table) {
Some(metadata) => Ok(Self {
device: dmsetup.device(name),
metadata,
}),
_ => Err(ThinPoolError::NotAThinPool {
None => Err(ThinPoolError::NotAThinPool {
name: name.clone(),
table,
}),
}
}

fn pool_metadata(table: &str) -> Option<DeviceNumber> {
match table.lines().collect::<Vec<_>>()[..] {
[line] => match line.split_whitespace().collect::<Vec<_>>()[..] {
[_, _, "thin-pool", metadata, ..] => metadata.parse().ok(),
_ => None,
},
_ => None,
}
}

pub fn device(&self) -> &Device<'a> {
&self.device
}

pub fn metadata(&self) -> DeviceNumber {
self.metadata
}

pub fn create_thin(&self, id: ThinId) -> Result<Thin<'a, Inactive>, RunError> {
self.send(ThinMessage::CreateThin(id))?;
Ok(Thin {
Expand Down Expand Up @@ -306,7 +322,7 @@ impl<'a> Thin<'a, Active<'a>> {
mod tests {
use super::{
Inactive, OpenThinError, ParseThinMessageError, SnapshotError, Thin, ThinId, ThinMessage,
ThinPoolError,
ThinPool, ThinPoolError,
};
use crate::dm::{DmName, Dmsetup};
use assert_fs::fixture::ChildPath;
Expand Down Expand Up @@ -409,6 +425,30 @@ mod tests {

const POOL_TABLE: &str = "0 100 thin-pool 7:0 7:1 128 0 0";

#[rstest]
#[case::pool(POOL_TABLE, Some("7:0"))]
#[case::pool_with_trailing_newline("0 100 thin-pool 7:0 7:1 128 0 0\n", Some("7:0"))]
#[case::linear("0 100 linear 7:0 0", None)]
#[case::thin("0 100 thin 7:0 1", None)]
#[case::target_in_another_column("0 thin-pool 100 7:0 7:1 128 0 0", None)]
#[case::metadata_not_a_device_number("0 100 thin-pool /dev/loop0 7:1 128 0 0", None)]
#[case::no_metadata("0 100 thin-pool", None)]
#[case::two_pool_segments(
"0 100 thin-pool 7:0 7:1 128 0 0\n100 100 thin-pool 7:2 7:3 128 0 0",
None
)]
#[case::empty("", None)]
fn only_a_single_thin_pool_segment_names_a_metadata_device(
#[case] table: &str,
#[case] metadata: Option<&str>,
) {
assert_eq!(
ThinPool::pool_metadata(table),
metadata.map(|m| m.parse().unwrap()),
"{table:?}"
);
}

fn name(s: &str) -> DmName {
s.parse().unwrap()
}
Expand Down
14 changes: 9 additions & 5 deletions native/hyperrs-linux/src/dm/thin_dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,16 @@ impl Superblock {

let ranges: Vec<BlockRange> = device.mappings.iter().map(Mapping::range).collect();

let got: u64 = ranges.iter().map(|range| range.length).sum();
let truncated = |got| MappingsError::Truncated {
expected: device.mapped_blocks,
got,
};
let got = ranges
.iter()
.try_fold(0u64, |sum, range| sum.checked_add(range.length))
.ok_or_else(|| truncated(u64::MAX))?;
if got != device.mapped_blocks {
return Err(MappingsError::Truncated {
expected: device.mapped_blocks,
got,
});
return Err(truncated(got));
}

Ok(ThinMappings {
Expand Down
104 changes: 104 additions & 0 deletions native/hyperrs-linux/tests/dm_kernel_argv_as_root.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
//! The live counterpart of `dm_kernel_argv_properties`: a table `Dmsetup`
//! creates must make the kernel open the very device each path operand names.
//! Law: for a `DevPath` the type accepts, the dm device built over it is
//! backed by that path's device, never by a different file whose name is a
//! prefix of it. Root only: it attaches loop devices and creates a dm device.

#![feature(adt_const_params, unsized_const_params)]
#![allow(incomplete_features)]

use assert_fs::TempDir;
use hyperrs_fs::file::{Any, IsRegularFile, OpenFlags, SafeFile};
use hyperrs_fs::path::{IsAbsolute, SafePathBuf, StrictComponents};
use hyperrs_linux::dm::{DevPath, DmName, DmTable, Dmsetup, LinearTable, Origin, RemoveMode};
use hyperrs_linux::loopdev::{LoopControl, LoopDevice};
use hyperrs_linux::Access;
use hyperrs_process::binary::RootSafeBin;
use pretty_assertions::assert_eq;
use rstest::rstest;
use std::ffi::OsStr;
use std::fs;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{symlink, MetadataExt};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

const DMSETUP: &str = "/usr/sbin/dmsetup";

fn attach(file: &Path) -> LoopDevice {
fs::File::create(file).unwrap().set_len(1 << 20).unwrap();
let path: SafePathBuf<IsAbsolute, StrictComponents> = file.to_path_buf().try_into().unwrap();
let backing = SafeFile::<IsRegularFile, Any, Any>::open(&path, OpenFlags::PATH).unwrap();
LoopControl::open()
.unwrap()
.attach(&backing, Access::ReadOnly, Duration::from_secs(2))
.unwrap()
}

fn major_minor(dev: &Path) -> String {
let rdev = fs::metadata(dev).unwrap().rdev();
format!(
"{}:{}",
nix::sys::stat::major(rdev),
nix::sys::stat::minor(rdev)
)
}

struct Removing(String);

impl Drop for Removing {
fn drop(&mut self) {
let _ = Command::new(DMSETUP)
.args(["remove", "--retry", &self.0])
.output();
}
}

#[rstest]
#[case::copyright_sign(b"x\xc2\xa9", b"x\xc2")]
#[case::latin_e_acute(b"\xc3\xa9", b"\xc3")]
fn a_linear_table_is_backed_by_the_path_it_names_as_root(
#[case] named: &[u8],
#[case] prefix: &[u8],
) {
if !nix::unistd::geteuid().is_root() {
eprintln!("SKIP: needs root");
return;
}
let dir = TempDir::new().unwrap();
let base = fs::canonicalize(dir.path()).unwrap();
let wanted = attach(&base.join("wanted.img"));
let decoy = attach(&base.join("decoy.img"));
let named = base.join(OsStr::from_bytes(named));
symlink(wanted.path().as_path(), &named).unwrap();
symlink(decoy.path().as_path(), base.join(OsStr::from_bytes(prefix))).unwrap();

let origin: DevPath = PathBuf::from(&named)
.try_into()
.expect("the type accepts it");
let dm = Dmsetup::new(RootSafeBin::open(Path::new(DMSETUP)).unwrap());
let name: DmName = format!("hyperrs-argv-{}", std::process::id())
.parse()
.unwrap();
let _guard = Removing(name.to_string());
let table = DmTable::Linear(LinearTable {
sectors: 8,
origin: Origin::Path(origin),
});
let device = dm.create(&name, &table, Access::ReadOnly).unwrap();

let live = Command::new(DMSETUP)
.args(["table", &name.to_string()])
.output()
.unwrap();
let live = String::from_utf8(live.stdout).unwrap();
device.remove(RemoveMode::Retry).unwrap();
assert_eq!(
live.split_whitespace().nth(3),
Some(major_minor(wanted.path().as_path()).as_str()),
"the kernel opened {} (decoy is {}) for {named:?}",
live.trim(),
major_minor(decoy.path().as_path()),
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc c114d108d6e992cde0bcff6ceeac1f49d0eb06eb9f29e0d42822b02b0369753a # shrinks to input = _TheKernelOpensExactlyTheOperandsOfAnyConstructibleTableArgs { t: ThinPool(ThinPoolTable { sectors: 0, metadata: SafePathBuf("/!", PhantomData<(hyperrs_fs::path::IsAbsolute, hyperrs_fs::path::StrictComponents)>), data: SafePathBuf("/\u{e0000}", PhantomData<(hyperrs_fs::path::IsAbsolute, hyperrs_fs::path::StrictComponents)>), block_sectors: 0, low_water: 0 }) }
Loading
Loading