use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use sim_core::platform::Platform;
use crate::{Error, Result};
pub const FORMAT: u32 = 1;
pub const CHUNK_SIZE: u64 = 1 << 20;
pub const COMPRESSION: &str = "lz4";
pub const COLD_BOOT: &str = "cold-boot";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
pub format: u32,
pub simee_version: String,
pub platform: Platform,
pub device: Device,
pub identity: Identity,
pub captures: Captures,
pub resume: String,
pub secrets: Vec<Secret>,
pub guest_identity: GuestIdentity,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dropped: Vec<String>,
pub chunk_size: u64,
pub compression: String,
pub disks: Vec<Disk>,
pub files: Vec<File>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Device {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub form_factor: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Identity {
Android(AndroidImage),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AndroidImage {
pub api: String,
pub tag: String,
pub abi: String,
pub revision: String,
pub package: String,
pub files: BTreeMap<String, String>,
pub fingerprint: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Captures {
pub disks: bool,
pub ram: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Secret {
pub item: String,
pub what: String,
pub excludable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GuestIdentity {
pub on_import: String,
pub identifiers: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Disk {
pub path: String,
pub size: u64,
pub blake3: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base: Option<Base>,
pub extents: Vec<Extent>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Base {
pub kind: String,
pub identity: String,
pub blake3: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Extent {
pub offset: u64,
pub len: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hash: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub zero: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub from_base: bool,
}
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct File {
pub path: String,
pub size: u64,
pub blake3: String,
pub chunks: Vec<String>,
}
impl Extent {
pub fn chunk(offset: u64, len: u64, hash: String) -> Extent {
Extent { offset, len, hash: Some(hash), zero: false, from_base: false }
}
pub fn zero(offset: u64, len: u64) -> Extent {
Extent { offset, len, hash: None, zero: true, from_base: false }
}
}
pub fn safe_path(path: &str) -> bool {
!path.is_empty()
&& !path.starts_with('/')
&& !path.contains(['\\', '\0'])
&& path.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
}
pub fn is_hash(h: &str) -> bool {
h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
impl Manifest {
pub fn parse(bytes: &[u8]) -> Result<Manifest> {
#[derive(Deserialize)]
struct FormatOnly {
format: Option<u64>,
}
let only: FormatOnly = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
match only.format {
Some(f) if f == u64::from(FORMAT) => {}
Some(f) => return Err(Error::Format(f)),
None => return Err(Error::Manifest("no `format`".into())),
}
let m: Manifest = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
m.validate()?;
Ok(m)
}
pub fn to_json(&self) -> Vec<u8> {
let mut v = serde_json::to_vec_pretty(self).unwrap_or_default();
v.push(b'\n');
v
}
pub fn validate(&self) -> Result<()> {
let bad = |s: String| Err(Error::Manifest(s));
if self.format != FORMAT {
return Err(Error::Format(u64::from(self.format)));
}
if self.compression != COMPRESSION {
return bad(format!("unknown compression `{}`", self.compression));
}
if !self.chunk_size.is_power_of_two() || !(4096..=64 << 20).contains(&self.chunk_size) {
return bad(format!("chunk_size {} is not a power of two from 4 KiB to 64 MiB", self.chunk_size));
}
let mut seen = BTreeSet::new();
for path in self.disks.iter().map(|d| &d.path).chain(self.files.iter().map(|f| &f.path)) {
if !safe_path(path) {
return Err(Error::Path(path.clone()));
}
if !seen.insert(path.as_str()) {
return bad(format!("`{path}` appears twice"));
}
}
for d in &self.disks {
if !is_hash(&d.blake3) {
return bad(format!("{}: bad blake3", d.path));
}
let mut at = 0;
for e in &d.extents {
let kinds = [e.hash.is_some(), e.zero, e.from_base].iter().filter(|k| **k).count();
if kinds != 1 {
return bad(format!("{}: the extent at {} must be exactly one of hash, zero, from_base", d.path, e.offset));
}
if e.offset != at || e.len == 0 {
return bad(format!("{}: extent at {} (len {}) leaves a gap or overlaps at {at}", d.path, e.offset, e.len));
}
if let Some(h) = &e.hash
&& (!is_hash(h) || e.len > self.chunk_size)
{
return bad(format!("{}: the chunk at {} is malformed or longer than chunk_size", d.path, e.offset));
}
if e.from_base && d.base.is_none() {
return bad(format!("{}: from_base without a base", d.path));
}
at = e.offset.checked_add(e.len).ok_or_else(|| Error::Manifest(format!("{}: extents overflow", d.path)))?;
}
if at != d.size {
return bad(format!("{}: extents cover {at} of {} bytes", d.path, d.size));
}
}
for f in &self.files {
if !is_hash(&f.blake3) || !f.chunks.iter().all(|h| is_hash(h)) {
return bad(format!("{}: bad hash", f.path));
}
if f.chunks.len() as u64 != f.size.div_ceil(self.chunk_size) {
return bad(format!("{}: {} chunks for {} bytes", f.path, f.chunks.len(), f.size));
}
}
Ok(())
}
pub fn chunk_hashes(&self) -> Vec<&str> {
let mut seen = BTreeSet::new();
let disks = self.disks.iter().flat_map(|d| d.extents.iter().filter_map(|e| e.hash.as_deref()));
let files = self.files.iter().flat_map(|f| f.chunks.iter().map(String::as_str));
disks.chain(files).filter(|h| seen.insert(*h)).collect()
}
}