Skip to main content

simee_bundle/
manifest.rs

1//! `manifest.json`: what a bundle holds and how to put it back together.
2
3use 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
11/// The format's major version. A reader refuses any other: a new major may change what an
12/// existing field means. Additions that old readers can ignore keep the major.
13pub const FORMAT: u32 = 1;
14
15/// Disk images are cut into chunks of this size (the last one shorter). Fixed boundaries suit
16/// disks, written in place: an offset never shifts, so content-defined chunking would find the
17/// same boundaries, and a small chunk limits what one dirty block drags into a bundle.
18pub const CHUNK_SIZE: u64 = 1 << 20;
19
20/// The only chunk compression in format 1: each chunk is one LZ4 block (no frame or size header;
21/// the manifest gives each chunk's length).
22pub const COMPRESSION: &str = "lz4";
23
24/// What `resume` means in format 1: the receiver boots the disks cold (no RAM state).
25pub const COLD_BOOT: &str = "cold-boot";
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Manifest {
29    pub format: u32,
30    /// The simee that wrote it.
31    pub simee_version: String,
32    pub platform: Platform,
33    pub device: Device,
34    /// What the device runs on, matched by content on import (never by path).
35    pub identity: Identity,
36    pub captures: Captures,
37    /// What the receiver does with it: [`COLD_BOOT`] in format 1.
38    pub resume: String,
39    /// What in the bundle may be a secret, and whether an export can leave it out.
40    pub secrets: Vec<Secret>,
41    /// What an import shares with the device it came from.
42    pub guest_identity: GuestIdentity,
43    /// What the export changed or left out to make the bundle host-independent (a `config.ini`
44    /// key that held a host path), so the receiver can tell.
45    #[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    /// A file tree's directories and symlinks, and its files' modes (an iOS data directory):
52    /// what `disks` and `files` don't say. Empty for a bundle of disk images.
53    #[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    /// The name it had where it was exported (an import names it anew).
60    pub name: String,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub form_factor: Option<String>,
63}
64
65/// What a device needs on the receiving host: the system image (Android), or the runtime and
66/// device type (iOS).
67#[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/// An iOS simulator's device type and runtime, by the service's identifiers. An import needs the
75/// same runtime build; the version and name only say what to install when it is missing.
76#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
77pub struct IosSimulator {
78    /// `com.apple.CoreSimulator.SimDeviceType.iPhone-17`.
79    pub device_type: String,
80    /// `com.apple.CoreSimulator.SimRuntime.iOS-26-1`.
81    pub runtime: String,
82    /// The runtime's build (`23B80`).
83    pub build: String,
84    /// The runtime's version (`26.1`).
85    pub version: String,
86    /// The runtime's name (`iOS 26.1`).
87    pub runtime_name: String,
88}
89
90/// What a [tree](Manifest::tree) entry is.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum EntryKind {
94    Dir,
95    /// A regular file, stored as the disk (or file) at the same path.
96    File,
97    Symlink,
98}
99
100/// One directory, file or symlink of a file tree, at its path in the bundle.
101#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102pub struct Entry {
103    pub path: String,
104    pub kind: EntryKind,
105    /// Permission bits (at most `0o7777`) of a directory or file; none for a symlink.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub mode: Option<u32>,
108    /// A symlink's target, as the link holds it (relative, or a path inside the device).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub target: Option<String>,
111}
112
113/// An Android system image by content: `source.properties`'s API level, tag, ABI and revision,
114/// the BLAKE3 of the files that boot it, and `build.prop`'s fingerprint.
115#[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    /// The SDK package that held it where it was exported (`system-images;android-36;google_apis;arm64-v8a`):
122    /// what to install when no image matches. Never used to find the image.
123    pub package: String,
124    /// File name (`system.img`, `vendor.img`, `kernel-ranchu`, `ramdisk.img`) to its BLAKE3.
125    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    /// A path in the bundle, or what it is (`accounts`).
138    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    /// `duplicated`: an import is the same device to the guest's apps and services as the one it
146    /// came from, so two of them on one network look like one device.
147    pub on_import: String,
148    /// The identifiers that come along (`ro.serialno`, `android_id`).
149    pub identifiers: Vec<String>,
150}
151
152/// A disk image: its chunks, in order, covering `size` bytes.
153#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
154pub struct Disk {
155    /// Where it goes, relative to the device directory (`simee/userdata.img`).
156    pub path: String,
157    pub size: u64,
158    /// BLAKE3 of all `size` bytes.
159    pub blake3: String,
160    /// Reserved for base deltas (#171): the disk this one is a delta against. A format 1 reader
161    /// that meets one refuses the bundle.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub base: Option<Base>,
164    pub extents: Vec<Extent>,
165}
166
167/// The disk a delta is against, checked by its hash before use (#171).
168#[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/// `len` bytes of a disk at `offset`: one stored chunk (`hash`), zeros (all-zero data and holes,
176/// never stored; an import leaves a hole), or the same range of the base (`from_base`, #171).
177#[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/// A small file (`config.ini`): its chunks, each [`Manifest::chunk_size`] but the last.
194#[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
212/// Whether `path` is safe to join to a destination directory: at most [`MAX_TARGET`] bytes, relative, `/`-separated, with no
213/// empty, `.` or `..` component, no backslash, no NUL and no [`ignorable`] code point.
214pub 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
223/// The longest symlink target macOS makes: `symlink` refuses a longer one (`ENAMETOOLONG`).
224pub const MAX_TARGET: usize = 1023;
225
226/// Whether `target` is a symlink target a bundle may hold: not empty, at most [`MAX_TARGET`]
227/// bytes, with no NUL and no [`ignorable`] code point.
228pub fn safe_target(target: &str) -> bool {
229    !target.is_empty() && target.len() <= MAX_TARGET && !target.contains('\0') && !target.chars().any(ignorable)
230}
231
232/// Whether `c` is a format code point (Unicode category Cf) or a default-ignorable one: what a
233/// volume may skip when it compares names (HFS+ skips some, APFS none) and a renderer draws as
234/// nothing. A simulator's data has no use for one in a name, and a name that holds one can fold
235/// like another that the volume keeps apart, so a bundle path or link target with one is refused.
236pub 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
267/// The most bytes (logical, holes included) a bundle's disks and files may add up to: an import
268/// reads every byte back to check its hash, so a sparse disk of a petabyte would take days.
269pub const MAX_SIZE: u64 = 1 << 40;
270
271/// `path` as a case-insensitive, normalization-insensitive volume (APFS's default, HFS+)
272/// compares names: canonically decomposed (NFD), case-folded, without the code points HFS+
273/// ignores. Two paths that fold alike are one file there. It folds at least as much as the
274/// volume does, so it may join names the volume keeps apart, never the reverse. Case is folded
275/// by lowercasing, uppercasing and lowercasing again, so every case of a letter whose uppercase
276/// is more than one letter joins it: `ẞ` lowercases to `ß`, which uppercases to `SS`, so `ẞ`,
277/// `ß` and `ss` are one name, as on APFS. An ASCII path is only lowercased, which is the same.
278pub(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
292/// Whether `h` is a BLAKE3 hash as the manifest writes it: 64 lowercase hex digits.
293pub 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    /// Parses and [validates](Manifest::validate) `manifest.json`. The format is checked before
299    /// anything else, so a newer major is refused as such rather than as malformed.
300    pub fn parse(bytes: &[u8]) -> Result<Manifest> {
301        /// Only `format`: serde skips everything else without building it, so a hostile manifest
302        /// costs no more than its own bytes before it is refused.
303        #[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    /// Checks everything an import relies on: the format, every path, that each disk's extents
325    /// cover it exactly in order, every hash's shape, and each file's chunk count.
326    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    /// The tree's checks: each entry's path is safe and appears once, also as a case- and
393    /// normalization-insensitive volume compares names ([`fold`]); a file entry is a disk or file
394    /// of the bundle and no other entry is; a symlink has a target and no mode, and nothing lies
395    /// under one in any spelling that folds alike (extracting through a link would write outside
396    /// the destination, and on such a volume `data/l/x` goes through a link `data/L`).
397    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            // The links in one map by folded path, each ancestor prefix looked up by hash: a path of
440            // L bytes costs O(L) (and `safe_path` bounds L), not O(L^2).
441            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    /// The bytes an extract writes: the disks' stored extents and the files (zeros stay holes).
454    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    /// Every stored chunk's hash, once, in the order the manifest first names it.
460    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}