1use std::collections::{BTreeMap, BTreeSet, HashMap};
4
5use serde::{Deserialize, Serialize};
6use sim_core::platform::Platform;
7use unicode_normalization::UnicodeNormalization;
8
9use crate::{Error, Result};
10
11pub const FORMAT: u32 = 1;
14
15pub const CHUNK_SIZE: u64 = 1 << 20;
19
20pub const COMPRESSION: &str = "lz4";
23
24pub const COLD_BOOT: &str = "cold-boot";
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Manifest {
29 pub format: u32,
30 pub simee_version: String,
32 pub platform: Platform,
33 pub device: Device,
34 pub identity: Identity,
36 pub captures: Captures,
37 pub resume: String,
39 pub secrets: Vec<Secret>,
41 pub guest_identity: GuestIdentity,
43 #[serde(default, skip_serializing_if = "Vec::is_empty")]
46 pub dropped: Vec<String>,
47 pub chunk_size: u64,
48 pub compression: String,
49 pub disks: Vec<Disk>,
50 pub files: Vec<File>,
51 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub tree: Vec<Entry>,
55}
56
57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58pub struct Device {
59 pub name: String,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub form_factor: Option<String>,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum Identity {
70 Android(AndroidImage),
71 Ios(IosSimulator),
72}
73
74#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
77pub struct IosSimulator {
78 pub device_type: String,
80 pub runtime: String,
82 pub build: String,
84 pub version: String,
86 pub runtime_name: String,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum EntryKind {
94 Dir,
95 File,
97 Symlink,
98}
99
100#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102pub struct Entry {
103 pub path: String,
104 pub kind: EntryKind,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub mode: Option<u32>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub target: Option<String>,
111}
112
113#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
116pub struct AndroidImage {
117 pub api: String,
118 pub tag: String,
119 pub abi: String,
120 pub revision: String,
121 pub package: String,
124 pub files: BTreeMap<String, String>,
126 pub fingerprint: String,
127}
128
129#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
130pub struct Captures {
131 pub disks: bool,
132 pub ram: bool,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
136pub struct Secret {
137 pub item: String,
139 pub what: String,
140 pub excludable: bool,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
144pub struct GuestIdentity {
145 pub on_import: String,
148 pub identifiers: Vec<String>,
150}
151
152#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154pub struct Disk {
155 pub path: String,
157 pub size: u64,
158 pub blake3: String,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub base: Option<Base>,
164 pub extents: Vec<Extent>,
165}
166
167#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169pub struct Base {
170 pub kind: String,
171 pub identity: String,
172 pub blake3: String,
173}
174
175#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
178pub struct Extent {
179 pub offset: u64,
180 pub len: u64,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub hash: Option<String>,
183 #[serde(default, skip_serializing_if = "is_false")]
184 pub zero: bool,
185 #[serde(default, skip_serializing_if = "is_false")]
186 pub from_base: bool,
187}
188
189fn is_false(b: &bool) -> bool {
190 !*b
191}
192
193#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
195pub struct File {
196 pub path: String,
197 pub size: u64,
198 pub blake3: String,
199 pub chunks: Vec<String>,
200}
201
202impl Extent {
203 pub fn chunk(offset: u64, len: u64, hash: String) -> Extent {
204 Extent { offset, len, hash: Some(hash), zero: false, from_base: false }
205 }
206
207 pub fn zero(offset: u64, len: u64) -> Extent {
208 Extent { offset, len, hash: None, zero: true, from_base: false }
209 }
210}
211
212pub fn safe_path(path: &str) -> bool {
215 !path.is_empty()
216 && path.len() <= MAX_TARGET
217 && !path.starts_with('/')
218 && !path.contains(['\\', '\0'])
219 && !path.chars().any(ignorable)
220 && path.split('/').all(|c| !c.is_empty() && c != "." && c != "..")
221}
222
223pub const MAX_TARGET: usize = 1023;
225
226pub fn safe_target(target: &str) -> bool {
229 !target.is_empty() && target.len() <= MAX_TARGET && !target.contains('\0') && !target.chars().any(ignorable)
230}
231
232pub fn ignorable(c: char) -> bool {
237 matches!(
238 c,
239 '\u{ad}'
240 | '\u{34f}'
241 | '\u{600}'..='\u{605}'
242 | '\u{61c}'
243 | '\u{6dd}'
244 | '\u{70f}'
245 | '\u{890}'..='\u{891}'
246 | '\u{8e2}'
247 | '\u{115f}'..='\u{1160}'
248 | '\u{17b4}'..='\u{17b5}'
249 | '\u{180b}'..='\u{180f}'
250 | '\u{200b}'..='\u{200f}'
251 | '\u{202a}'..='\u{202e}'
252 | '\u{2060}'..='\u{206f}'
253 | '\u{3164}'
254 | '\u{fe00}'..='\u{fe0f}'
255 | '\u{feff}'
256 | '\u{ffa0}'
257 | '\u{fff0}'..='\u{fffb}'
258 | '\u{110bd}'
259 | '\u{110cd}'
260 | '\u{13430}'..='\u{1343f}'
261 | '\u{1bca0}'..='\u{1bca3}'
262 | '\u{1d173}'..='\u{1d17a}'
263 | '\u{e0000}'..='\u{e0fff}'
264 )
265}
266
267pub const MAX_SIZE: u64 = 1 << 40;
270
271pub(crate) fn fold(path: &str) -> String {
279 if path.is_ascii() {
280 return path.to_ascii_lowercase();
281 }
282 let hfs_ignores = |c: &char| matches!(*c, '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}');
283 path.nfd()
284 .flat_map(char::to_lowercase)
285 .flat_map(char::to_uppercase)
286 .flat_map(char::to_lowercase)
287 .filter(|c| !hfs_ignores(c))
288 .nfd()
289 .collect()
290}
291
292pub fn is_hash(h: &str) -> bool {
294 h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
295}
296
297impl Manifest {
298 pub fn parse(bytes: &[u8]) -> Result<Manifest> {
301 #[derive(Deserialize)]
304 struct FormatOnly {
305 format: Option<u64>,
306 }
307 let only: FormatOnly = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
308 match only.format {
309 Some(f) if f == u64::from(FORMAT) => {}
310 Some(f) => return Err(Error::Format(f)),
311 None => return Err(Error::Manifest("no `format`".into())),
312 }
313 let m: Manifest = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?;
314 m.validate()?;
315 Ok(m)
316 }
317
318 pub fn to_json(&self) -> Vec<u8> {
319 let mut v = serde_json::to_vec_pretty(self).unwrap_or_default();
320 v.push(b'\n');
321 v
322 }
323
324 pub fn validate(&self) -> Result<()> {
327 let bad = |s: String| Err(Error::Manifest(s));
328 if self.format != FORMAT {
329 return Err(Error::Format(u64::from(self.format)));
330 }
331 if self.compression != COMPRESSION {
332 return bad(format!("unknown compression `{}`", self.compression));
333 }
334 if !self.chunk_size.is_power_of_two() || !(4096..=64 << 20).contains(&self.chunk_size) {
335 return bad(format!("chunk_size {} is not a power of two from 4 KiB to 64 MiB", self.chunk_size));
336 }
337 let mut seen = BTreeSet::new();
338 let mut folded = BTreeMap::new();
339 for path in self.disks.iter().map(|d| &d.path).chain(self.files.iter().map(|f| &f.path)) {
340 if !safe_path(path) {
341 return Err(Error::Path(path.clone()));
342 }
343 if !seen.insert(path.as_str()) {
344 return bad(format!("`{path}` appears twice"));
345 }
346 if let Some(other) = folded.insert(fold(path), path) {
347 return bad(format!("`{other}` and `{path}` are one file on a case-insensitive volume"));
348 }
349 }
350 let total = self.disks.iter().map(|d| d.size).chain(self.files.iter().map(|f| f.size)).try_fold(0u64, u64::checked_add);
351 if total.is_none_or(|t| t > MAX_SIZE) {
352 return bad(format!("the disks and files add up to more than {MAX_SIZE} bytes"));
353 }
354 for d in &self.disks {
355 if !is_hash(&d.blake3) {
356 return bad(format!("{}: bad blake3", d.path));
357 }
358 let mut at = 0;
359 for e in &d.extents {
360 let kinds = [e.hash.is_some(), e.zero, e.from_base].iter().filter(|k| **k).count();
361 if kinds != 1 {
362 return bad(format!("{}: the extent at {} must be exactly one of hash, zero, from_base", d.path, e.offset));
363 }
364 if e.offset != at || e.len == 0 {
365 return bad(format!("{}: extent at {} (len {}) leaves a gap or overlaps at {at}", d.path, e.offset, e.len));
366 }
367 if let Some(h) = &e.hash
368 && (!is_hash(h) || e.len > self.chunk_size)
369 {
370 return bad(format!("{}: the chunk at {} is malformed or longer than chunk_size", d.path, e.offset));
371 }
372 if e.from_base && d.base.is_none() {
373 return bad(format!("{}: from_base without a base", d.path));
374 }
375 at = e.offset.checked_add(e.len).ok_or_else(|| Error::Manifest(format!("{}: extents overflow", d.path)))?;
376 }
377 if at != d.size {
378 return bad(format!("{}: extents cover {at} of {} bytes", d.path, d.size));
379 }
380 }
381 for f in &self.files {
382 if !is_hash(&f.blake3) || !f.chunks.iter().all(|h| is_hash(h)) {
383 return bad(format!("{}: bad hash", f.path));
384 }
385 if f.chunks.len() as u64 != f.size.div_ceil(self.chunk_size) {
386 return bad(format!("{}: {} chunks for {} bytes", f.path, f.chunks.len(), f.size));
387 }
388 }
389 self.validate_tree(&seen)
390 }
391
392 fn validate_tree(&self, stored: &BTreeSet<&str>) -> Result<()> {
398 let bad = |s: String| Err(Error::Manifest(s));
399 let mut paths = BTreeSet::new();
400 let mut folded = BTreeMap::new();
401 let mut links: HashMap<String, &str> = HashMap::new();
402 for e in &self.tree {
403 if !safe_path(&e.path) {
404 return Err(Error::Path(e.path.clone()));
405 }
406 if !paths.insert(e.path.as_str()) {
407 return bad(format!("tree: `{}` appears twice", e.path));
408 }
409 if let Some(other) = folded.insert(fold(&e.path), e.path.as_str()) {
410 return bad(format!("tree: `{other}` and `{}` are one path on a case-insensitive volume", e.path));
411 }
412 let is_stored = stored.contains(e.path.as_str());
413 if (e.kind == EntryKind::File) != is_stored {
414 let what = if is_stored { "stored" } else { "not stored" };
415 return bad(format!("tree: `{}` is a {:?} entry but {what} in the bundle", e.path, e.kind));
416 }
417 match (e.kind, &e.target, e.mode) {
418 (EntryKind::Symlink, Some(t), None) if safe_target(t) => {
419 links.insert(fold(&e.path), e.path.as_str());
420 }
421 (EntryKind::Symlink, ..) => {
422 return bad(format!(
423 "tree: the symlink `{}` needs a target (at most {MAX_TARGET} bytes, with no NUL or ignorable code point) \
424 and no mode",
425 e.path
426 ));
427 }
428 (_, Some(_), _) => return bad(format!("tree: `{}` has a target but isn't a symlink", e.path)),
429 (_, None, Some(m)) if m > 0o7777 => return bad(format!("tree: `{}` has mode {m:o}", e.path)),
430 _ => {}
431 }
432 }
433 if !self.tree.is_empty()
434 && let Some(p) = stored.iter().find(|p| !paths.contains(*p))
435 {
436 return bad(format!("tree: `{p}` is stored but not in the tree"));
437 }
438 if !links.is_empty() {
439 for p in paths.iter().chain(stored.iter()) {
442 let f = fold(p);
443 for (i, _) in f.match_indices('/') {
444 if let Some(link) = links.get(&f[..i]) {
445 return bad(format!("tree: `{p}` lies under the symlink `{link}`"));
446 }
447 }
448 }
449 }
450 Ok(())
451 }
452
453 pub fn stored_bytes(&self) -> u64 {
455 let disks = self.disks.iter().flat_map(|d| d.extents.iter().filter(|e| e.hash.is_some()).map(|e| e.len));
456 disks.chain(self.files.iter().map(|f| f.size)).fold(0, u64::saturating_add)
457 }
458
459 pub fn chunk_hashes(&self) -> Vec<&str> {
461 let mut seen = BTreeSet::new();
462 let disks = self.disks.iter().flat_map(|d| d.extents.iter().filter_map(|e| e.hash.as_deref()));
463 let files = self.files.iter().flat_map(|f| f.chunks.iter().map(String::as_str));
464 disks.chain(files).filter(|h| seen.insert(*h)).collect()
465 }
466}