capsid-protocol 0.1.0-alpha.1

Versioned, size-bounded messages between the Capsid host and its guest agent.
Documentation
use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use crate::{Error, Result, path};

pub const MAX_MOUNTS: usize = 8;

const RESERVED: [&str; 3] = ["/dev", "/proc", "/sys"];

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Mount {
    pub device: u8,

    pub target: String,

    pub read_only: bool,
}

pub fn validate_targets<'a>(targets: impl IntoIterator<Item = &'a str>) -> Result<()> {
    let mut selected = BTreeSet::<&str>::new();
    for target in targets {
        if !path::is_guest_target(target, &RESERVED) {
            return Err(Error::Invalid("invalid or reserved guest volume target"));
        }

        if selected.len() == MAX_MOUNTS || selected.iter().any(|old| path::overlap(old, target)) {
            return Err(Error::Invalid(
                "local block volumes require at most eight distinct, non-overlapping targets",
            ));
        }

        selected.insert(target);
    }
    Ok(())
}

pub fn validate_mounts(mounts: &[Mount]) -> Result<()> {
    validate_targets(mounts.iter().map(|mount| mount.target.as_str()))?;
    let mut devices = BTreeSet::new();
    for mount in mounts {
        if usize::from(mount.device) >= MAX_MOUNTS || !devices.insert(mount.device) {
            return Err(Error::Invalid("invalid or duplicate attached block device"));
        }
    }
    Ok(())
}