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};
4
5use serde::{Deserialize, Serialize};
6use sim_core::platform::Platform;
7
8use crate::{Error, Result};
9
10/// The format's major version. A reader refuses any other: a new major may change what an
11/// existing field means. Additions that old readers can ignore keep the major.
12pub const FORMAT: u32 = 1;
13
14/// Disk images are cut into chunks of this size (the last one shorter). Fixed boundaries suit
15/// disks, written in place: an offset never shifts, so content-defined chunking would find the
16/// same boundaries, and a small chunk limits what one dirty block drags into a bundle.
17pub const CHUNK_SIZE: u64 = 1 << 20;
18
19/// The only chunk compression in format 1: each chunk is one LZ4 block (no frame or size header;
20/// the manifest gives each chunk's length).
21pub const COMPRESSION: &str = "lz4";
22
23/// What `resume` means in format 1: the receiver boots the disks cold (no RAM state).
24pub const COLD_BOOT: &str = "cold-boot";
25
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Manifest {
28    pub format: u32,
29    /// The simee that wrote it.
30    pub simee_version: String,
31    pub platform: Platform,
32    pub device: Device,
33    /// What the device runs on, matched by content on import (never by path).
34    pub identity: Identity,
35    pub captures: Captures,
36    /// What the receiver does with it: [`COLD_BOOT`] in format 1.
37    pub resume: String,
38    /// What in the bundle may be a secret, and whether an export can leave it out.
39    pub secrets: Vec<Secret>,
40    /// What an import shares with the device it came from.
41    pub guest_identity: GuestIdentity,
42    /// What the export changed or left out to make the bundle host-independent (a `config.ini`
43    /// key that held a host path), so the receiver can tell.
44    #[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    /// The name it had where it was exported (an import names it anew).
55    pub name: String,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub form_factor: Option<String>,
58}
59
60/// The system image (Android) a device needs. iOS's runtime and device type come in its own
61/// variant.
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Identity {
65    Android(AndroidImage),
66}
67
68/// An Android system image by content: `source.properties`'s API level, tag, ABI and revision,
69/// the BLAKE3 of the files that boot it, and `build.prop`'s fingerprint.
70#[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    /// The SDK package that held it where it was exported (`system-images;android-36;google_apis;arm64-v8a`):
77    /// what to install when no image matches. Never used to find the image.
78    pub package: String,
79    /// File name (`system.img`, `vendor.img`, `kernel-ranchu`, `ramdisk.img`) to its BLAKE3.
80    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    /// A path in the bundle, or what it is (`accounts`).
93    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    /// `duplicated`: an import is the same device to the guest's apps and services as the one it
101    /// came from, so two of them on one network look like one device.
102    pub on_import: String,
103    /// The identifiers that come along (`ro.serialno`, `android_id`).
104    pub identifiers: Vec<String>,
105}
106
107/// A disk image: its chunks, in order, covering `size` bytes.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
109pub struct Disk {
110    /// Where it goes, relative to the device directory (`simee/userdata.img`).
111    pub path: String,
112    pub size: u64,
113    /// BLAKE3 of all `size` bytes.
114    pub blake3: String,
115    /// Reserved for base deltas (#171): the disk this one is a delta against. A format 1 reader
116    /// that meets one refuses the bundle.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub base: Option<Base>,
119    pub extents: Vec<Extent>,
120}
121
122/// The disk a delta is against, checked by its hash before use (#171).
123#[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/// `len` bytes of a disk at `offset`: one stored chunk (`hash`), zeros (all-zero data and holes,
131/// never stored; an import leaves a hole), or the same range of the base (`from_base`, #171).
132#[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/// A small file (`config.ini`): its chunks, each [`Manifest::chunk_size`] but the last.
149#[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
167/// Whether `path` is safe to join to a destination directory: relative, `/`-separated, with no
168/// empty, `.` or `..` component, no backslash and no NUL.
169pub 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
176/// Whether `h` is a BLAKE3 hash as the manifest writes it: 64 lowercase hex digits.
177pub 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    /// Parses and [validates](Manifest::validate) `manifest.json`. The format is checked before
183    /// anything else, so a newer major is refused as such rather than as malformed.
184    pub fn parse(bytes: &[u8]) -> Result<Manifest> {
185        /// Only `format`: serde skips everything else without building it, so a hostile manifest
186        /// costs no more than its own bytes before it is refused.
187        #[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    /// Checks everything an import relies on: the format, every path, that each disk's extents
209    /// cover it exactly in order, every hash's shape, and each file's chunk count.
210    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    /// Every stored chunk's hash, once, in the order the manifest first names it.
269    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}