1mod manifest;
14mod store;
15mod tar;
16
17use std::collections::BTreeMap;
18use std::fs;
19use std::io::{BufReader, BufWriter};
20use std::os::unix::fs::{FileExt, MetadataExt};
21use std::path::{Path, PathBuf};
22use std::time::Instant;
23
24pub use manifest::{
25 AndroidImage, Base, CHUNK_SIZE, COLD_BOOT, COMPRESSION, Captures, Device, Disk, Extent, FORMAT, File, GuestIdentity, Identity,
26 Manifest, Secret, is_hash, safe_path,
27};
28pub use store::{ChunkStore, chunk_name, compress, decompress_verified, hash, hash_file, max_compressed, parse_chunk_name, read_regular};
29pub use tar::{TarReader, TarWriter};
30
31pub const MANIFEST: &str = "manifest.json";
33
34pub const MAX_MANIFEST: u64 = 32 << 20;
36
37#[derive(Debug, thiserror::Error)]
38pub enum Error {
39 #[error("bundle format {0} isn't one this simee reads (it reads format {FORMAT}); update simee")]
40 Format(u64),
41 #[error("bad bundle manifest: {0}")]
42 Manifest(String),
43 #[error("unsafe path `{0}` in the bundle (absolute, empty, or with `.` or `..`)")]
44 Path(String),
45 #[error("chunk {0} doesn't match its hash")]
46 ChunkHash(String),
47 #[error("{0} doesn't match its hash in the manifest")]
48 Hash(String),
49 #[error("the bundle lacks {count} chunk(s) (first: {first})")]
50 Missing { first: String, count: usize },
51 #[error("bad bundle archive: {0}")]
52 Tar(String),
53 #[error("{0}: {1}")]
54 Io(PathBuf, std::io::Error),
55 #[error("reading the bundle: {0}")]
56 Read(std::io::Error),
57 #[error("writing the bundle: {0}")]
58 Write(std::io::Error),
59 #[error("{0}")]
60 Unsupported(String),
61 #[error("{0} changed while it was exported")]
62 Changed(String),
63 #[error("{0} already exists")]
64 Exists(PathBuf),
65}
66
67pub type Result<T> = std::result::Result<T, Error>;
68
69#[derive(Clone, Debug, Default)]
71pub struct Options {
72 pub threads: usize,
74}
75
76#[derive(Clone, Debug, Default)]
79pub struct Contents {
80 pub disks: Vec<(String, PathBuf)>,
81 pub files: Vec<(String, Vec<u8>)>,
82}
83
84#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
87pub struct Summary {
88 pub form: String,
90 pub disk_bytes: u64,
92 pub allocated_bytes: u64,
94 pub zero_bytes: u64,
96 pub data_bytes: u64,
98 pub unique_bytes: u64,
100 pub chunks: u64,
101 pub unique_chunks: u64,
102 pub compressed_bytes: u64,
104 pub bundle_bytes: u64,
106 pub seconds: f64,
107}
108
109#[derive(Clone, Copy)]
111enum Origin {
112 Disk { disk: usize, offset: u64, len: u64 },
113 File { file: usize, offset: u64, len: u64 },
114}
115
116fn is_zero(buf: &[u8]) -> bool {
117 let (words, rest) = buf.as_chunks::<64>();
118 words.iter().all(|w| w.iter().fold(0, |a, &b| a | b) == 0) && rest.iter().all(|&b| b == 0)
119}
120
121fn read_at(f: &fs::File, path: &Path, buf: &mut [u8], offset: u64) -> Result<usize> {
123 let mut got = 0;
124 while got < buf.len() {
125 match f.read_at(&mut buf[got..], offset + got as u64) {
126 Ok(0) => break,
127 Ok(n) => got += n,
128 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
129 Err(e) => return Err(Error::Io(path.to_path_buf(), e)),
130 }
131 }
132 Ok(got)
133}
134
135fn plan_disk(path: &str, file: &Path, chunk_size: u64) -> Result<Disk> {
137 let f = fs::File::open(file).map_err(|e| Error::Io(file.to_path_buf(), e))?;
138 let size = f.metadata().map_err(|e| Error::Io(file.to_path_buf(), e))?.len();
139 let mut whole = blake3::Hasher::new();
140 let mut buf = vec![0u8; chunk_size as usize];
141 let mut extents: Vec<Extent> = Vec::new();
142 let mut offset = 0;
143 while offset < size {
144 let want = (size - offset).min(chunk_size) as usize;
145 if read_at(&f, file, &mut buf[..want], offset)? != want {
146 return Err(Error::Changed(file.display().to_string()));
147 }
148 let data = &buf[..want];
149 whole.update(data);
150 match extents.last_mut() {
151 Some(last) if last.zero && is_zero(data) => last.len += want as u64,
152 _ if is_zero(data) => extents.push(Extent::zero(offset, want as u64)),
153 _ => extents.push(Extent::chunk(offset, want as u64, hash(data))),
154 }
155 offset += want as u64;
156 }
157 Ok(Disk { path: path.to_owned(), size, blake3: whole.finalize().to_hex().to_string(), base: None, extents })
158}
159
160fn plan_file(path: &str, data: &[u8], chunk_size: u64) -> File {
161 let chunks = data.chunks(chunk_size as usize).map(hash).collect();
162 File { path: path.to_owned(), size: data.len() as u64, blake3: hash(data), chunks }
163}
164
165fn origins(m: &Manifest) -> Vec<(String, Origin)> {
167 let mut seen = std::collections::BTreeSet::new();
168 let mut out = Vec::new();
169 for (disk, d) in m.disks.iter().enumerate() {
170 for e in &d.extents {
171 if let Some(h) = &e.hash
172 && seen.insert(h.clone())
173 {
174 out.push((h.clone(), Origin::Disk { disk, offset: e.offset, len: e.len }));
175 }
176 }
177 }
178 for (file, f) in m.files.iter().enumerate() {
179 for (i, h) in f.chunks.iter().enumerate() {
180 let offset = i as u64 * m.chunk_size;
181 if seen.insert(h.clone()) {
182 out.push((h.clone(), Origin::File { file, offset, len: (f.size - offset).min(m.chunk_size) }));
183 }
184 }
185 }
186 out
187}
188
189enum Sink {
190 Dir(ChunkStore),
191 Tar(TarWriter<BufWriter<fs::File>>),
192}
193
194impl Sink {
195 fn put(&mut self, hash: &str, compressed: &[u8]) -> Result<()> {
196 match self {
197 Sink::Dir(store) => store.put(hash, compressed).map(|_| ()),
198 Sink::Tar(w) => w.entry(&chunk_name(hash), compressed),
199 }
200 }
201}
202
203pub fn is_archive(to: &Path) -> bool {
205 to.extension().is_some_and(|x| x == "tar")
206}
207
208pub fn export(mut manifest: Manifest, contents: &Contents, to: &Path, opts: &Options) -> Result<(Manifest, Summary)> {
213 let start = Instant::now();
214 if to.exists() {
215 return Err(Error::Exists(to.to_path_buf()));
216 }
217 manifest.format = FORMAT;
218 manifest.chunk_size = CHUNK_SIZE;
219 manifest.compression = COMPRESSION.to_owned();
220 manifest.disks = contents.disks.iter().map(|(p, f)| plan_disk(p, f, CHUNK_SIZE)).collect::<Result<_>>()?;
221 manifest.files = contents.files.iter().map(|(p, d)| plan_file(p, d, CHUNK_SIZE)).collect();
222 manifest.validate()?;
223 let mut summary = Summary { form: if is_archive(to) { "tar" } else { "dir" }.into(), ..Summary::default() };
224 for ((_, file), d) in contents.disks.iter().zip(&manifest.disks) {
225 summary.disk_bytes += d.size;
226 summary.allocated_bytes += fs::metadata(file).map(|m| m.blocks() * 512).unwrap_or(0);
227 for e in &d.extents {
228 if e.zero {
229 summary.zero_bytes += e.len;
230 } else {
231 summary.data_bytes += e.len;
232 summary.chunks += 1;
233 }
234 }
235 }
236 for f in &manifest.files {
237 summary.data_bytes += f.size;
238 summary.chunks += f.chunks.len() as u64;
239 }
240
241 let partial = to.with_file_name(format!(".{}.partial", to.file_name().and_then(|n| n.to_str()).unwrap_or("bundle")));
242 let made = (|| -> Result<u64> {
243 let mut sink = if is_archive(to) {
244 let f = fs::File::create_new(&partial).map_err(|e| Error::Io(partial.clone(), e))?;
245 let mut w = TarWriter::new(BufWriter::with_capacity(1 << 20, f));
246 w.entry(MANIFEST, &manifest.to_json())?;
247 Sink::Tar(w)
248 } else {
249 fs::create_dir(&partial).map_err(|e| Error::Io(partial.clone(), e))?;
250 Sink::Dir(ChunkStore::new(&partial))
251 };
252 let disks: Vec<fs::File> =
253 contents.disks.iter().map(|(_, f)| fs::File::open(f).map_err(|e| Error::Io(f.clone(), e))).collect::<Result<_>>()?;
254 let threads = match opts.threads {
255 0 => std::thread::available_parallelism().map_or(4, |n| n.get()).min(8),
256 n => n,
257 };
258 let all = origins(&manifest);
259 for batch in all.chunks(threads * 2) {
260 let mut raw = Vec::with_capacity(batch.len());
261 for (h, origin) in batch {
262 let data = match *origin {
263 Origin::Disk { disk, offset, len } => {
264 let mut buf = vec![0u8; len as usize];
265 let path = &contents.disks[disk].1;
266 if read_at(&disks[disk], path, &mut buf, offset)? != buf.len() || hash(&buf) != *h {
267 return Err(Error::Changed(path.display().to_string()));
268 }
269 buf
270 }
271 Origin::File { file, offset, len } => contents.files[file].1[offset as usize..(offset + len) as usize].to_vec(),
272 };
273 raw.push(data);
274 }
275 let packed: Vec<Result<Vec<u8>>> = std::thread::scope(|s| {
276 let per = raw.len().div_ceil(threads).max(1);
277 let handles: Vec<_> =
278 raw.chunks(per).map(|group| s.spawn(move || group.iter().map(|d| Ok(compress(d))).collect::<Vec<_>>())).collect();
279 handles
280 .into_iter()
281 .flat_map(|h| h.join().unwrap_or_else(|_| vec![Err(Error::Unsupported("a compression thread panicked".into()))]))
282 .collect()
283 });
284 for (((h, _), data), z) in batch.iter().zip(&raw).zip(packed) {
285 let z = z?;
286 summary.unique_bytes += data.len() as u64;
287 summary.unique_chunks += 1;
288 summary.compressed_bytes += z.len() as u64;
289 sink.put(h, &z)?;
290 }
291 }
292 Ok(match sink {
293 Sink::Tar(w) => {
294 let written = w.written() + 1024;
295 w.finish()?;
296 written
297 }
298 Sink::Dir(_) => {
299 let json = manifest.to_json();
300 let path = partial.join(MANIFEST);
301 fs::write(&path, &json).map_err(|e| Error::Io(path, e))?;
302 summary.compressed_bytes + json.len() as u64
303 }
304 })
305 })();
306 match made {
307 Ok(bytes) => {
308 fs::rename(&partial, to).map_err(|e| Error::Io(to.to_path_buf(), e))?;
309 summary.bundle_bytes = bytes;
310 summary.seconds = (start.elapsed().as_secs_f64() * 100.0).round() / 100.0;
311 Ok((manifest, summary))
312 }
313 Err(e) => {
314 let _ = if partial.is_dir() { fs::remove_dir_all(&partial) } else { fs::remove_file(&partial) };
315 Err(e)
316 }
317 }
318}
319
320enum Source {
321 Dir(PathBuf),
322 Tar(TarReader<BufReader<fs::File>>),
323}
324
325pub struct Reader {
327 manifest: Manifest,
328 source: Source,
329}
330
331#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
333pub struct Extracted {
334 pub written_bytes: u64,
336 pub chunks: u64,
337 pub seconds: f64,
338}
339
340impl Reader {
341 pub fn open(path: &Path) -> Result<Reader> {
345 let (manifest, source) = if path.is_dir() {
346 let bytes = read_regular(&path.join(MANIFEST), MAX_MANIFEST)?;
347 (Manifest::parse(&bytes)?, Source::Dir(path.to_path_buf()))
348 } else {
349 let f = fs::File::open(path).map_err(|e| Error::Io(path.to_path_buf(), e))?;
350 let mut tar = TarReader::new(BufReader::with_capacity(1 << 20, f));
351 match tar.next_entry(MAX_MANIFEST)? {
352 Some((name, bytes)) if name == MANIFEST => (Manifest::parse(&bytes)?, Source::Tar(tar)),
353 Some((name, _)) => return Err(Error::Tar(format!("the first entry is `{name}`, not {MANIFEST}"))),
354 None => return Err(Error::Tar("the archive is empty".into())),
355 }
356 };
357 if let Some(d) = manifest.disks.iter().find(|d| d.base.is_some()) {
358 return Err(Error::Unsupported(format!("{} is a delta against a base disk (#171), which this simee can't apply yet", d.path)));
359 }
360 Ok(Reader { manifest, source })
361 }
362
363 pub fn manifest(&self) -> &Manifest {
364 &self.manifest
365 }
366
367 pub fn extract(self, dest: &Path) -> Result<Extracted> {
373 let start = Instant::now();
374 let m = self.manifest;
375 let mut targets: Vec<(PathBuf, fs::File)> = Vec::new();
376 let mut places: BTreeMap<String, Vec<(usize, u64, u64)>> = BTreeMap::new();
377 let mut create = |path: &str, size: u64| -> Result<usize> {
378 if !safe_path(path) {
379 return Err(Error::Path(path.to_owned()));
380 }
381 let p = dest.join(path);
382 if let Some(dir) = p.parent() {
383 fs::create_dir_all(dir).map_err(|e| Error::Io(dir.to_path_buf(), e))?;
384 }
385 let f = fs::File::create_new(&p).map_err(|e| Error::Io(p.clone(), e))?;
386 f.set_len(size).map_err(|e| Error::Io(p.clone(), e))?;
387 targets.push((p, f));
388 Ok(targets.len() - 1)
389 };
390 for d in &m.disks {
391 let t = create(&d.path, d.size)?;
392 for e in &d.extents {
393 if let Some(h) = &e.hash {
394 places.entry(h.clone()).or_default().push((t, e.offset, e.len));
395 }
396 }
397 }
398 for f in &m.files {
399 let t = create(&f.path, f.size)?;
400 for (i, h) in f.chunks.iter().enumerate() {
401 let offset = i as u64 * m.chunk_size;
402 places.entry(h.clone()).or_default().push((t, offset, (f.size - offset).min(m.chunk_size)));
403 }
404 }
405 let mut out = Extracted::default();
406 let mut place = |h: &str, data: &[u8], places: &mut BTreeMap<String, Vec<(usize, u64, u64)>>| -> Result<()> {
407 let spots = places.remove(h).ok_or_else(|| Error::Tar(format!("chunk {h} isn't in the manifest, or comes twice")))?;
408 for (t, offset, len) in spots {
409 if len != data.len() as u64 {
410 return Err(Error::ChunkHash(h.to_owned()));
411 }
412 let (path, f) = &targets[t];
413 f.write_all_at(data, offset).map_err(|e| Error::Io(path.clone(), e))?;
414 out.written_bytes += len;
415 }
416 out.chunks += 1;
417 Ok(())
418 };
419 match self.source {
420 Source::Dir(root) => {
421 let store = ChunkStore::new(&root);
422 for h in m.chunk_hashes() {
423 let data = store.get(h, m.chunk_size)?;
424 place(h, &data, &mut places)?;
425 }
426 }
427 Source::Tar(mut tar) => {
428 let max = max_compressed(m.chunk_size);
430 while let Some((name, z)) = tar.next_entry(max)? {
431 let h = parse_chunk_name(&name).ok_or_else(|| Error::Tar(format!("unexpected entry `{name}`")))?;
432 let data = decompress_verified(h, &z, m.chunk_size)?;
433 place(h, &data, &mut places)?;
434 }
435 }
436 }
437 if let Some(first) = places.keys().next() {
438 return Err(Error::Missing { first: first.clone(), count: places.len() });
439 }
440 let wholes = m.disks.iter().map(|d| (&d.path, &d.blake3)).chain(m.files.iter().map(|f| (&f.path, &f.blake3)));
441 for ((path, f), (name, want)) in targets.iter().zip(wholes) {
442 let mut h = blake3::Hasher::new();
443 let mut r = BufReader::with_capacity(1 << 20, f);
444 std::io::Seek::rewind(&mut r).map_err(|e| Error::Io(path.clone(), e))?;
445 h.update_reader(&mut r).map_err(|e| Error::Io(path.clone(), e))?;
446 if h.finalize().to_hex().as_str() != want.as_str() {
447 return Err(Error::Hash(name.clone()));
448 }
449 }
450 out.seconds = (start.elapsed().as_secs_f64() * 100.0).round() / 100.0;
451 Ok(out)
452 }
453}
454
455#[cfg(test)]
456mod tests;