1mod beneath;
14pub mod ios;
15mod manifest;
16mod store;
17mod tar;
18
19use sim_core::hostfs::{FileExt, allocated_bytes};
20use std::collections::{BTreeMap, VecDeque};
21use std::fs;
22use std::io::{BufReader, BufWriter};
23use std::path::{Path, PathBuf};
24use std::time::Instant;
25
26pub use manifest::{
27 AndroidImage, Base, CHUNK_SIZE, COLD_BOOT, COMPRESSION, Captures, Device, Disk, Entry, EntryKind, Extent, FORMAT, File, GuestIdentity,
28 Identity, IosSimulator, MAX_SIZE, MAX_TARGET, Manifest, Secret, ignorable, is_hash, safe_path, safe_target,
29};
30pub use store::{ChunkStore, chunk_name, compress, decompress_verified, hash, hash_file, max_compressed, parse_chunk_name, read_regular};
31pub use tar::{TarReader, TarWriter};
32
33pub const MANIFEST: &str = "manifest.json";
35
36pub const MAX_MANIFEST: u64 = 32 << 20;
38
39#[derive(Debug, thiserror::Error)]
40pub enum Error {
41 #[error("bundle format {0} isn't one this simee reads (it reads format {FORMAT}); update simee")]
42 Format(u64),
43 #[error("bad bundle manifest: {0}")]
44 Manifest(String),
45 #[error("unsafe path `{0}` in the bundle (absolute, empty, with `.` or `..`, or with an ignorable or format code point)")]
46 Path(String),
47 #[error("chunk {0} doesn't match its hash")]
48 ChunkHash(String),
49 #[error("{0} doesn't match its hash in the manifest")]
50 Hash(String),
51 #[error("the bundle lacks {count} chunk(s) (first: {first})")]
52 Missing { first: String, count: usize },
53 #[error("bad bundle archive: {0}")]
54 Tar(String),
55 #[error("{0}: {1}")]
56 Io(PathBuf, std::io::Error),
57 #[error("reading the bundle: {0}")]
58 Read(std::io::Error),
59 #[error("writing the bundle: {0}")]
60 Write(std::io::Error),
61 #[error("{0}")]
62 Unsupported(String),
63 #[error("{0} changed while it was exported")]
64 Changed(String),
65 #[error("{0} already exists")]
66 Exists(PathBuf),
67 #[error("{0}")]
69 Refused(String),
70 #[error("`{0}` is a symlink, and nothing is written through one")]
73 ThroughLink(String),
74}
75
76pub type Result<T> = std::result::Result<T, Error>;
77
78#[derive(Clone, Debug, Default)]
80pub struct Options {
81 pub threads: usize,
83}
84
85#[derive(Clone, Debug, Default)]
88pub struct Contents {
89 pub disks: Vec<(String, PathBuf)>,
90 pub files: Vec<(String, Vec<u8>)>,
91}
92
93#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
96pub struct Summary {
97 pub form: String,
99 pub disk_bytes: u64,
101 pub allocated_bytes: u64,
103 pub zero_bytes: u64,
105 pub data_bytes: u64,
107 pub unique_bytes: u64,
109 pub chunks: u64,
110 pub unique_chunks: u64,
111 pub compressed_bytes: u64,
113 pub bundle_bytes: u64,
115 pub seconds: f64,
116}
117
118#[derive(Clone, Copy)]
120enum Origin {
121 Disk { disk: usize, offset: u64, len: u64 },
122 File { file: usize, offset: u64, len: u64 },
123}
124
125fn is_zero(buf: &[u8]) -> bool {
126 let (words, rest) = buf.as_chunks::<64>();
127 words.iter().all(|w| w.iter().fold(0, |a, &b| a | b) == 0) && rest.iter().all(|&b| b == 0)
128}
129
130fn read_at(f: &fs::File, path: &Path, buf: &mut [u8], offset: u64) -> Result<usize> {
132 let mut got = 0;
133 while got < buf.len() {
134 match f.read_at(&mut buf[got..], offset + got as u64) {
135 Ok(0) => break,
136 Ok(n) => got += n,
137 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
138 Err(e) => return Err(Error::Io(path.to_path_buf(), e)),
139 }
140 }
141 Ok(got)
142}
143
144fn plan_disk(path: &str, file: &Path, chunk_size: u64) -> Result<Disk> {
146 let f = fs::File::open(file).map_err(|e| Error::Io(file.to_path_buf(), e))?;
147 let size = f.metadata().map_err(|e| Error::Io(file.to_path_buf(), e))?.len();
148 let mut whole = blake3::Hasher::new();
149 let mut buf = vec![0u8; chunk_size as usize];
150 let mut extents: Vec<Extent> = Vec::new();
151 let mut offset = 0;
152 while offset < size {
153 let want = (size - offset).min(chunk_size) as usize;
154 if read_at(&f, file, &mut buf[..want], offset)? != want {
155 return Err(Error::Changed(file.display().to_string()));
156 }
157 let data = &buf[..want];
158 whole.update(data);
159 match extents.last_mut() {
160 Some(last) if last.zero && is_zero(data) => last.len += want as u64,
161 _ if is_zero(data) => extents.push(Extent::zero(offset, want as u64)),
162 _ => extents.push(Extent::chunk(offset, want as u64, hash(data))),
163 }
164 offset += want as u64;
165 }
166 Ok(Disk { path: path.to_owned(), size, blake3: whole.finalize().to_hex().to_string(), base: None, extents })
167}
168
169fn plan_file(path: &str, data: &[u8], chunk_size: u64) -> File {
170 let chunks = data.chunks(chunk_size as usize).map(hash).collect();
171 File { path: path.to_owned(), size: data.len() as u64, blake3: hash(data), chunks }
172}
173
174fn origins(m: &Manifest) -> Vec<(String, Origin)> {
176 let mut seen = std::collections::BTreeSet::new();
177 let mut out = Vec::new();
178 for (disk, d) in m.disks.iter().enumerate() {
179 for e in &d.extents {
180 if let Some(h) = &e.hash
181 && seen.insert(h.clone())
182 {
183 out.push((h.clone(), Origin::Disk { disk, offset: e.offset, len: e.len }));
184 }
185 }
186 }
187 for (file, f) in m.files.iter().enumerate() {
188 for (i, h) in f.chunks.iter().enumerate() {
189 let offset = i as u64 * m.chunk_size;
190 if seen.insert(h.clone()) {
191 out.push((h.clone(), Origin::File { file, offset, len: (f.size - offset).min(m.chunk_size) }));
192 }
193 }
194 }
195 out
196}
197
198enum Sink {
199 Dir(ChunkStore),
200 Tar(TarWriter<BufWriter<fs::File>>),
201}
202
203impl Sink {
204 fn put(&mut self, hash: &str, compressed: &[u8]) -> Result<()> {
205 match self {
206 Sink::Dir(store) => store.put(hash, compressed).map(|_| ()),
207 Sink::Tar(w) => w.entry(&chunk_name(hash), compressed),
208 }
209 }
210}
211
212pub fn is_archive(to: &Path) -> bool {
214 to.extension().is_some_and(|x| x == "tar")
215}
216
217pub fn export(mut manifest: Manifest, contents: &Contents, to: &Path, opts: &Options) -> Result<(Manifest, Summary)> {
222 let start = Instant::now();
223 if to.exists() {
224 return Err(Error::Exists(to.to_path_buf()));
225 }
226 manifest.format = FORMAT;
227 manifest.chunk_size = CHUNK_SIZE;
228 manifest.compression = COMPRESSION.to_owned();
229 manifest.disks = contents.disks.iter().map(|(p, f)| plan_disk(p, f, CHUNK_SIZE)).collect::<Result<_>>()?;
230 manifest.files = contents.files.iter().map(|(p, d)| plan_file(p, d, CHUNK_SIZE)).collect();
231 manifest.validate()?;
232 let mut summary = Summary { form: if is_archive(to) { "tar" } else { "dir" }.into(), ..Summary::default() };
233 for ((_, file), d) in contents.disks.iter().zip(&manifest.disks) {
234 summary.disk_bytes += d.size;
235 summary.allocated_bytes += fs::metadata(file).map(|m| allocated_bytes(&m)).unwrap_or(0);
236 for e in &d.extents {
237 if e.zero {
238 summary.zero_bytes += e.len;
239 } else {
240 summary.data_bytes += e.len;
241 summary.chunks += 1;
242 }
243 }
244 }
245 for f in &manifest.files {
246 summary.data_bytes += f.size;
247 summary.chunks += f.chunks.len() as u64;
248 }
249
250 let partial = to.with_file_name(format!(".{}.partial", to.file_name().and_then(|n| n.to_str()).unwrap_or("bundle")));
251 let made = (|| -> Result<u64> {
252 let mut sink = if is_archive(to) {
253 let f = fs::File::create_new(&partial).map_err(|e| Error::Io(partial.clone(), e))?;
254 let mut w = TarWriter::new(BufWriter::with_capacity(1 << 20, f));
255 w.entry(MANIFEST, &manifest.to_json())?;
256 Sink::Tar(w)
257 } else {
258 fs::create_dir(&partial).map_err(|e| Error::Io(partial.clone(), e))?;
259 Sink::Dir(ChunkStore::new(&partial))
260 };
261 let mut open: Option<(usize, fs::File)> = None;
264 let threads = match opts.threads {
265 0 => std::thread::available_parallelism().map_or(4, |n| n.get()).min(8),
266 n => n,
267 };
268 let all = origins(&manifest);
269 for batch in all.chunks(threads * 2) {
270 let mut raw = Vec::with_capacity(batch.len());
271 for (h, origin) in batch {
272 let data = match *origin {
273 Origin::Disk { disk, offset, len } => {
274 let mut buf = vec![0u8; len as usize];
275 let path = &contents.disks[disk].1;
276 let f = match &mut open {
277 Some((at, f)) if *at == disk => &*f,
278 slot => {
279 *slot = None;
280 &slot.insert((disk, fs::File::open(path).map_err(|e| Error::Io(path.clone(), e))?)).1
281 }
282 };
283 if read_at(f, path, &mut buf, offset)? != buf.len() || hash(&buf) != *h {
284 return Err(Error::Changed(path.display().to_string()));
285 }
286 buf
287 }
288 Origin::File { file, offset, len } => contents.files[file].1[offset as usize..(offset + len) as usize].to_vec(),
289 };
290 raw.push(data);
291 }
292 let packed: Vec<Result<Vec<u8>>> = std::thread::scope(|s| {
293 let per = raw.len().div_ceil(threads).max(1);
294 let handles: Vec<_> =
295 raw.chunks(per).map(|group| s.spawn(move || group.iter().map(|d| Ok(compress(d))).collect::<Vec<_>>())).collect();
296 handles
297 .into_iter()
298 .flat_map(|h| h.join().unwrap_or_else(|_| vec![Err(Error::Unsupported("a compression thread panicked".into()))]))
299 .collect()
300 });
301 for (((h, _), data), z) in batch.iter().zip(&raw).zip(packed) {
302 let z = z?;
303 summary.unique_bytes += data.len() as u64;
304 summary.unique_chunks += 1;
305 summary.compressed_bytes += z.len() as u64;
306 sink.put(h, &z)?;
307 }
308 }
309 Ok(match sink {
310 Sink::Tar(w) => {
311 let written = w.written() + 1024;
312 w.finish()?;
313 written
314 }
315 Sink::Dir(_) => {
316 let json = manifest.to_json();
317 let path = partial.join(MANIFEST);
318 fs::write(&path, &json).map_err(|e| Error::Io(path, e))?;
319 summary.compressed_bytes + json.len() as u64
320 }
321 })
322 })();
323 match made {
324 Ok(bytes) => {
325 fs::rename(&partial, to).map_err(|e| Error::Io(to.to_path_buf(), e))?;
326 summary.bundle_bytes = bytes;
327 summary.seconds = (start.elapsed().as_secs_f64() * 100.0).round() / 100.0;
328 Ok((manifest, summary))
329 }
330 Err(e) => {
331 let _ = if partial.is_dir() { fs::remove_dir_all(&partial) } else { fs::remove_file(&partial) };
332 Err(e)
333 }
334 }
335}
336
337pub const OPEN_FILES: usize = 32;
340
341struct Targets<'a> {
344 root: &'a beneath::Beneath,
345 paths: Vec<String>,
346 open: VecDeque<(usize, fs::File)>,
347}
348
349impl Targets<'_> {
350 fn host_path(&self, t: usize) -> PathBuf {
351 self.root.path().join(&self.paths[t])
352 }
353
354 fn keep(&mut self, t: usize, f: fs::File) {
355 if self.open.len() >= OPEN_FILES {
356 self.open.pop_front();
357 }
358 self.open.push_back((t, f));
359 }
360
361 fn create(&mut self, path: &str, size: u64) -> Result<usize> {
363 let f = self.root.create(path)?;
364 let t = self.paths.len();
365 self.paths.push(path.to_owned());
366 f.set_len(size).map_err(|e| Error::Io(self.host_path(t), e))?;
367 self.keep(t, f);
368 Ok(t)
369 }
370
371 fn get(&mut self, t: usize) -> Result<(PathBuf, &fs::File)> {
373 match self.open.iter().position(|(at, _)| *at == t) {
374 Some(i) if i + 1 == self.open.len() => {}
375 Some(i) => {
376 if let Some(e) = self.open.remove(i) {
377 self.open.push_back(e);
378 }
379 }
380 None => {
381 let f = self.root.open(&self.paths[t])?;
382 self.keep(t, f);
383 }
384 }
385 let path = self.host_path(t);
386 match self.open.back() {
387 Some((_, f)) => Ok((path, f)),
388 None => Err(Error::Io(path, std::io::ErrorKind::NotFound.into())),
389 }
390 }
391
392 fn take(&mut self, t: usize) -> Result<(PathBuf, fs::File)> {
394 let path = self.host_path(t);
395 match self.open.iter().position(|(at, _)| *at == t).and_then(|i| self.open.remove(i)) {
396 Some((_, f)) => Ok((path, f)),
397 None => Ok((path, self.root.open(&self.paths[t])?)),
398 }
399 }
400}
401
402enum Source {
403 Dir(PathBuf),
404 Tar(TarReader<BufReader<fs::File>>),
405}
406
407pub struct Reader {
409 manifest: Manifest,
410 source: Source,
411}
412
413#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
415pub struct Extracted {
416 pub written_bytes: u64,
418 pub chunks: u64,
419 pub seconds: f64,
420}
421
422impl Reader {
423 pub fn open(path: &Path) -> Result<Reader> {
427 let (manifest, source) = if path.is_dir() {
428 let bytes = read_regular(&path.join(MANIFEST), MAX_MANIFEST)?;
429 (Manifest::parse(&bytes)?, Source::Dir(path.to_path_buf()))
430 } else {
431 let f = fs::File::open(path).map_err(|e| Error::Io(path.to_path_buf(), e))?;
432 let mut tar = TarReader::new(BufReader::with_capacity(1 << 20, f));
433 match tar.next_entry(MAX_MANIFEST)? {
434 Some((name, bytes)) if name == MANIFEST => (Manifest::parse(&bytes)?, Source::Tar(tar)),
435 Some((name, _)) => return Err(Error::Tar(format!("the first entry is `{name}`, not {MANIFEST}"))),
436 None => return Err(Error::Tar("the archive is empty".into())),
437 }
438 };
439 if let Some(d) = manifest.disks.iter().find(|d| d.base.is_some()) {
440 return Err(Error::Unsupported(format!("{} is a delta against a base disk (#171), which this simee can't apply yet", d.path)));
441 }
442 Ok(Reader { manifest, source })
443 }
444
445 pub fn manifest(&self) -> &Manifest {
446 &self.manifest
447 }
448
449 pub fn extract(self, dest: &Path) -> Result<Extracted> {
458 let start = Instant::now();
459 let m = self.manifest;
460 let root = beneath::Beneath::new(dest)?;
461 let need = m.stored_bytes();
462 if let Some(free) = root.free_bytes()
463 && need > free
464 {
465 return Err(Error::Refused(format!(
466 "the bundle holds {need} bytes of data and {} has {free} free; free some space and import again",
467 dest.display()
468 )));
469 }
470 let mut targets = Targets { root: &root, paths: Vec::new(), open: VecDeque::new() };
471 let mut places: BTreeMap<String, Vec<(usize, u64, u64)>> = BTreeMap::new();
472 let mut create = |path: &str, size: u64| -> Result<usize> {
473 if !safe_path(path) {
474 return Err(Error::Path(path.to_owned()));
475 }
476 targets.create(path, size)
477 };
478 for d in &m.disks {
479 let t = create(&d.path, d.size)?;
480 for e in &d.extents {
481 if let Some(h) = &e.hash {
482 places.entry(h.clone()).or_default().push((t, e.offset, e.len));
483 }
484 }
485 }
486 for f in &m.files {
487 let t = create(&f.path, f.size)?;
488 for (i, h) in f.chunks.iter().enumerate() {
489 let offset = i as u64 * m.chunk_size;
490 places.entry(h.clone()).or_default().push((t, offset, (f.size - offset).min(m.chunk_size)));
491 }
492 }
493 let mut out = Extracted::default();
494 let mut place = |h: &str, data: &[u8], places: &mut BTreeMap<String, Vec<(usize, u64, u64)>>| -> Result<()> {
495 let spots = places.remove(h).ok_or_else(|| Error::Tar(format!("chunk {h} isn't in the manifest, or comes twice")))?;
496 for (t, offset, len) in spots {
497 if len != data.len() as u64 {
498 return Err(Error::ChunkHash(h.to_owned()));
499 }
500 let (path, f) = targets.get(t)?;
501 f.write_all_at(data, offset).map_err(|e| Error::Io(path, e))?;
502 out.written_bytes += len;
503 }
504 out.chunks += 1;
505 Ok(())
506 };
507 match self.source {
508 Source::Dir(root) => {
509 let store = ChunkStore::new(&root);
510 for h in m.chunk_hashes() {
511 let data = store.get(h, m.chunk_size)?;
512 place(h, &data, &mut places)?;
513 }
514 }
515 Source::Tar(mut tar) => {
516 let max = max_compressed(m.chunk_size);
518 while let Some((name, z)) = tar.next_entry(max)? {
519 let h = parse_chunk_name(&name).ok_or_else(|| Error::Tar(format!("unexpected entry `{name}`")))?;
520 let data = decompress_verified(h, &z, m.chunk_size)?;
521 place(h, &data, &mut places)?;
522 }
523 }
524 }
525 if let Some(first) = places.keys().next() {
526 return Err(Error::Missing { first: first.clone(), count: places.len() });
527 }
528 let wholes = m.disks.iter().map(|d| (&d.path, &d.blake3)).chain(m.files.iter().map(|f| (&f.path, &f.blake3)));
529 for (t, (name, want)) in wholes.enumerate() {
530 let (path, f) = targets.take(t)?;
531 let mut h = blake3::Hasher::new();
532 let mut r = BufReader::with_capacity(1 << 20, f);
533 std::io::Seek::rewind(&mut r).map_err(|e| Error::Io(path.clone(), e))?;
534 h.update_reader(&mut r).map_err(|e| Error::Io(path.clone(), e))?;
535 if h.finalize().to_hex().as_str() != want.as_str() {
536 return Err(Error::Hash(name.clone()));
537 }
538 }
539 out.seconds = (start.elapsed().as_secs_f64() * 100.0).round() / 100.0;
540 Ok(out)
541 }
542}
543
544#[cfg(test)]
545mod tests;