1use std::collections::{BTreeMap, BTreeSet};
4
5use serde::{Deserialize, Serialize};
6use sim_core::platform::Platform;
7
8use crate::{Error, Result};
9
10pub const FORMAT: u32 = 1;
13
14pub const CHUNK_SIZE: u64 = 1 << 20;
18
19pub const COMPRESSION: &str = "lz4";
22
23pub const COLD_BOOT: &str = "cold-boot";
25
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Manifest {
28 pub format: u32,
29 pub simee_version: String,
31 pub platform: Platform,
32 pub device: Device,
33 pub identity: Identity,
35 pub captures: Captures,
36 pub resume: String,
38 pub secrets: Vec<Secret>,
40 pub guest_identity: GuestIdentity,
42 #[serde(default, skip_serializing_if = "Vec::is_empty")]
45 pub dropped: Vec<String>,
46 pub chunk_size: u64,
47 pub compression: String,
48 pub disks: Vec<Disk>,
49 pub files: Vec<File>,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53pub struct Device {
54 pub name: String,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub form_factor: Option<String>,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Identity {
65 Android(AndroidImage),
66}
67
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71pub struct AndroidImage {
72 pub api: String,
73 pub tag: String,
74 pub abi: String,
75 pub revision: String,
76 pub package: String,
79 pub files: BTreeMap<String, String>,
81 pub fingerprint: String,
82}
83
84#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
85pub struct Captures {
86 pub disks: bool,
87 pub ram: bool,
88}
89
90#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Secret {
92 pub item: String,
94 pub what: String,
95 pub excludable: bool,
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
99pub struct GuestIdentity {
100 pub on_import: String,
103 pub identifiers: Vec<String>,
105}
106
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Disk {
110 pub path: String,
112 pub size: u64,
113 pub blake3: String,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub base: Option<Base>,
119 pub extents: Vec<Extent>,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub struct Base {
125 pub kind: String,
126 pub identity: String,
127 pub blake3: String,
128}
129
130#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
133pub struct Extent {
134 pub offset: u64,
135 pub len: u64,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub hash: Option<String>,
138 #[serde(default, skip_serializing_if = "is_false")]
139 pub zero: bool,
140 #[serde(default, skip_serializing_if = "is_false")]
141 pub from_base: bool,
142}
143
144fn is_false(b: &bool) -> bool {
145 !*b
146}
147
148#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
150pub struct File {
151 pub path: String,
152 pub size: u64,
153 pub blake3: String,
154 pub chunks: Vec<String>,
155}
156
157impl Extent {
158 pub fn chunk(offset: u64, len: u64, hash: String) -> Extent {
159 Extent { offset, len, hash: Some(hash), zero: false, from_base: false }
160 }
161
162 pub fn zero(offset: u64, len: u64) -> Extent {
163 Extent { offset, len, hash: None, zero: true, from_base: false }
164 }
165}
166
167pub fn safe_path(path: &str) -> bool {
170 !path.is_empty()
171 && !path.starts_with('/')
172 && !path.contains(['\\', '\0'])
173 && path.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
174}
175
176pub fn is_hash(h: &str) -> bool {
178 h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
179}
180
181impl Manifest {
182 pub fn parse(bytes: &[u8]) -> Result<Manifest> {
185 #[derive(Deserialize)]
188 struct FormatOnly {
189 format: Option<u64>,
190 }
191 let only: FormatOnly = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
192 match only.format {
193 Some(f) if f == u64::from(FORMAT) => {}
194 Some(f) => return Err(Error::Format(f)),
195 None => return Err(Error::Manifest("no `format`".into())),
196 }
197 let m: Manifest = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
198 m.validate()?;
199 Ok(m)
200 }
201
202 pub fn to_json(&self) -> Vec<u8> {
203 let mut v = serde_json::to_vec_pretty(self).unwrap_or_default();
204 v.push(b'\n');
205 v
206 }
207
208 pub fn validate(&self) -> Result<()> {
211 let bad = |s: String| Err(Error::Manifest(s));
212 if self.format != FORMAT {
213 return Err(Error::Format(u64::from(self.format)));
214 }
215 if self.compression != COMPRESSION {
216 return bad(format!("unknown compression `{}`", self.compression));
217 }
218 if !self.chunk_size.is_power_of_two() || !(4096..=64 << 20).contains(&self.chunk_size) {
219 return bad(format!("chunk_size {} is not a power of two from 4 KiB to 64 MiB", self.chunk_size));
220 }
221 let mut seen = BTreeSet::new();
222 for path in self.disks.iter().map(|d| &d.path).chain(self.files.iter().map(|f| &f.path)) {
223 if !safe_path(path) {
224 return Err(Error::Path(path.clone()));
225 }
226 if !seen.insert(path.as_str()) {
227 return bad(format!("`{path}` appears twice"));
228 }
229 }
230 for d in &self.disks {
231 if !is_hash(&d.blake3) {
232 return bad(format!("{}: bad blake3", d.path));
233 }
234 let mut at = 0;
235 for e in &d.extents {
236 let kinds = [e.hash.is_some(), e.zero, e.from_base].iter().filter(|k| **k).count();
237 if kinds != 1 {
238 return bad(format!("{}: the extent at {} must be exactly one of hash, zero, from_base", d.path, e.offset));
239 }
240 if e.offset != at || e.len == 0 {
241 return bad(format!("{}: extent at {} (len {}) leaves a gap or overlaps at {at}", d.path, e.offset, e.len));
242 }
243 if let Some(h) = &e.hash
244 && (!is_hash(h) || e.len > self.chunk_size)
245 {
246 return bad(format!("{}: the chunk at {} is malformed or longer than chunk_size", d.path, e.offset));
247 }
248 if e.from_base && d.base.is_none() {
249 return bad(format!("{}: from_base without a base", d.path));
250 }
251 at = e.offset.checked_add(e.len).ok_or_else(|| Error::Manifest(format!("{}: extents overflow", d.path)))?;
252 }
253 if at != d.size {
254 return bad(format!("{}: extents cover {at} of {} bytes", d.path, d.size));
255 }
256 }
257 for f in &self.files {
258 if !is_hash(&f.blake3) || !f.chunks.iter().all(|h| is_hash(h)) {
259 return bad(format!("{}: bad hash", f.path));
260 }
261 if f.chunks.len() as u64 != f.size.div_ceil(self.chunk_size) {
262 return bad(format!("{}: {} chunks for {} bytes", f.path, f.chunks.len(), f.size));
263 }
264 }
265 Ok(())
266 }
267
268 pub fn chunk_hashes(&self) -> Vec<&str> {
270 let mut seen = BTreeSet::new();
271 let disks = self.disks.iter().flat_map(|d| d.extents.iter().filter_map(|e| e.hash.as_deref()));
272 let files = self.files.iter().flat_map(|f| f.chunks.iter().map(String::as_str));
273 disks.chain(files).filter(|h| seen.insert(*h)).collect()
274 }
275}