1use std::collections::HashSet;
16use std::fs::{self, File, OpenOptions};
17use std::io::{self, Read, Seek, SeekFrom, Write};
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, OnceLock};
21
22use anyhow::{Context, Result, anyhow, bail};
23use rayon::prelude::*;
24
25use crate::archive::resumable::{self, Decoder};
26use crate::archive::storage::{Storage, Tail};
27use crate::archive::{self, Codec, Format, Item, Kind, Sink, Stream, Unit};
28use crate::journal::{Journal, Link, Paths, Resume};
29use crate::{fsutil, platform};
30
31const BATCH_MAX_UNITS: usize = 512;
34const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
35const BUF_SIZE: usize = 1024 * 1024;
36const MAX_SYMLINK: u64 = 64 * 1024;
37
38const STREAM_STEP: u64 = 256 * 1024 * 1024;
42
43fn stream_step() -> u64 {
44 test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
45}
46
47fn stream_threshold() -> u64 {
50 2 * stream_step()
51}
52
53fn always_stream() -> bool {
56 test_knob("HATCHZIP_STREAM_STEP").is_some()
57}
58
59fn on_disk(u: &Unit) -> u64 {
60 u.items.iter().map(|i| i.size.next_multiple_of(4096)).sum()
61}
62
63pub struct Job {
64 pub storage: Arc<Storage>,
65 pub format_name: &'static str,
66 format: Box<dyn Format>,
67 pub units: Vec<Unit>,
69 pub tail_start: u64,
70 pub top: u64,
73 punch: OnceLock<Option<u64>>,
77 resume: Option<Resume>,
79}
80
81impl Job {
82 pub fn open(path: &Path, writable: bool, password: Option<&str>) -> Result<Self> {
86 let storage = Arc::new(Storage::open(path, writable)?);
87 let opened = archive::open(&storage, None, password)?;
88 let top = storage.original_len();
89 Self::build(storage, opened, top)
90 }
91
92 pub fn resume(
96 journal: &Journal,
97 tail: Arc<Tail>,
98 writable: bool,
99 password: Option<&str>,
100 ) -> Result<Self> {
101 let storage = Arc::new(Storage::from_parts(&journal.parts, writable)?);
102 let current = storage.current_len()?;
103 if current < journal.committed_len {
104 bail!(
105 "{} is shorter than HatchZip left it; refusing to touch it",
106 storage.primary().display()
107 );
108 }
109 if current > journal.committed_len && writable {
110 storage.set_len(journal.committed_len)?;
112 }
113 let opened = archive::open(&storage, Some((&journal.format, tail)), password)?;
114 let mut job = Self::build(storage, opened, journal.committed_len)?;
115 if let Some(r) = &journal.resume {
116 if job.units.first().map(|u| u.start) != Some(r.unit) {
119 bail!(
120 "the journal of {} records a half-extracted file that isn't the next one \
121 in the archive; refusing to touch it",
122 job.storage.primary().display()
123 );
124 }
125 job.resume = Some(r.clone());
126 }
127 Ok(job)
128 }
129
130 fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
131 let mut units = opened.units;
132 units.retain(|u| u.start < top);
133 units.sort_by_key(|u| std::cmp::Reverse(u.start));
134
135 let mut seen = HashSet::new();
136 for item in units.iter().flat_map(|u| &u.items) {
137 for part in item.path.iter() {
138 if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
139 bail!(
140 "'{}' can't be created here: {why}. Nothing was changed",
141 item.path.display()
142 );
143 }
144 }
145 if item.kind != Kind::Dir && !seen.insert(item.path.to_string_lossy().to_lowercase()) {
148 bail!(
149 "'{}' appears twice in the archive (ignoring case); refusing to guess which one wins",
150 item.path.display()
151 );
152 }
153 }
154 Ok(Self {
155 storage,
156 format_name: opened.name,
157 format: opened.format,
158 units,
159 tail_start: opened.tail_start,
160 top,
161 punch: OnceLock::new(),
162 resume: None,
163 })
164 }
165
166 pub fn punch_support(&self) -> Option<u64> {
171 *self.punch.get_or_init(|| {
172 if test_knob("HATCHZIP_NO_PUNCH").is_some() {
173 return None;
174 }
175 let dir = match self.storage.primary().parent() {
176 Some(d) if !d.as_os_str().is_empty() => d,
177 _ => Path::new("."),
178 };
179 fsutil::can_punch(dir).then(|| platform::punch_granule(dir))
180 })
181 }
182
183 pub fn encrypted(&self) -> bool {
184 self.units.iter().any(|u| u.encrypted)
185 }
186
187 pub fn check_password(&self) -> Result<()> {
192 const ENOUGH: u64 = 64 * 1024 * 1024;
193 let Some(unit) = self
194 .units
195 .iter()
196 .filter(|u| u.encrypted)
197 .min_by_key(|u| u.size())
198 else {
199 return Ok(());
200 };
201 let mut worker = self.format.worker(1)?;
202 let mut sink = ProbeSink {
203 left: ENOUGH,
204 buf: vec![0; BUF_SIZE],
205 };
206 match worker.extract(unit, &mut sink) {
207 Ok(()) => Ok(()),
208 Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
209 Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
210 Err(_) => Err(archive::WrongPassword.into()),
211 }
212 }
213
214 pub fn item_count(&self) -> usize {
215 self.units.iter().map(|u| u.items.len()).sum()
216 }
217
218 pub fn remaining_size(&self) -> u64 {
219 let done = self.resume.as_ref().map_or(0, |r| r.written);
220 self.units.iter().map(Unit::size).sum::<u64>() - done
221 }
222
223 fn resumed(&self, i: usize) -> Option<&Resume> {
225 self.resume
226 .as_ref()
227 .filter(|r| r.unit == self.units[i].start)
228 }
229
230 fn stream_of(&self, i: usize) -> Option<Stream> {
233 let unit = &self.units[i];
234 match unit.items.as_slice() {
235 [item] if item.kind == Kind::File && !unit.encrypted => {
236 self.format.stream(unit).ok().flatten()
237 }
238 _ => None,
239 }
240 }
241
242 fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
246 if self.resumed(i).is_some() {
247 return self.stream_of(i);
248 }
249 if !reclaims || self.units[i].size() < stream_threshold() {
250 return None;
251 }
252 self.punch_support()?;
253 self.stream_of(i)
254 }
255
256 fn span(&self, i: usize) -> u64 {
259 let end = if i == 0 {
260 self.top
261 } else {
262 self.units[i - 1].start
263 };
264 end - self.units[i].start
265 }
266
267 pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
273 let tail = (self.storage.original_len() - self.tail_start) as i128;
274 let mut extra: i128 = if fresh { tail } else { 0 };
275 let mut peak = extra;
276 for (i, u) in self.units.iter().enumerate() {
277 let span = self.span(i) as i128;
278 if let Some(s) = self.streams(i, reclaims) {
279 let (rise, net) = self.stream_cost(i, &s, span, reclaims);
280 peak = peak.max(extra + rise);
281 extra += net;
282 continue;
283 }
284 let on_disk = on_disk(u) as i128;
285 peak = peak.max(extra + on_disk);
286 extra += on_disk;
287 if reclaims {
288 extra -= span;
289 }
290 }
291 if reclaims {
292 let stub = self.units.last().map_or(self.top, |u| u.start);
295 extra -= stub as i128 + tail;
296 }
297 (peak.max(0) as u64, extra)
298 }
299
300 fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
315 let at = self.resumed(i);
316 let done = at.map_or(0, |r| r.written / 4096 * 4096);
319 let out_left = (on_disk(&self.units[i]) - done) as i128;
320 let read_to = at.map_or(s.data_start, |r| r.bit / 8);
321 let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
322 let freed = read_to.saturating_sub(s.data_start) as i128;
326 let net = if reclaims {
327 out_left - (span - freed)
328 } else {
329 out_left
330 };
331 let rise = match self.punch_support() {
332 Some(granule) if reclaims => {
333 let slack = match s.codec {
334 Codec::Stored => 0,
335 Codec::Deflate => out_left / 1024,
336 };
337 let step = (stream_step() + BUF_SIZE as u64 + 2 * granule) as i128;
338 ((out_left - data_left).max(0) + slack + step).min(out_left)
339 }
340 _ => out_left,
341 };
342 (rise, net)
343 }
344
345 pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
350 let mut found = Vec::new();
351 for (i, u) in self.units.iter().enumerate() {
352 if self.resumed(i).is_some() {
353 continue;
354 }
355 for item in &u.items {
356 if item.kind != Kind::File {
357 continue;
358 }
359 let dest = out.join(&item.path);
360 for p in [part_path(&dest), dest] {
361 if let Ok(m) = fs::symlink_metadata(&p)
362 && m.is_file()
363 {
364 found.push((p, m.len().next_multiple_of(4096)));
365 }
366 }
367 }
368 }
369 found
370 }
371
372 pub fn past_resume_point(&self, out: &Path) -> u64 {
375 let Some(r) = self.resume.as_ref() else {
376 return 0;
377 };
378 let Some(item) = self.units.first().and_then(|u| u.items.first()) else {
379 return 0;
380 };
381 let dest = out.join(&item.path);
382 [part_path(&dest), dest]
383 .iter()
384 .find_map(|p| fs::metadata(p).ok())
385 .map_or(0, |m| {
386 (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
387 })
388 }
389
390 pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
393 let threads = threads_per_unit(self.units.len());
394 let failures: Vec<String> = self
395 .units
396 .par_iter()
397 .map_init(
398 || {
399 (
400 self.format.worker(threads),
401 VerifySink {
402 on_bytes,
403 buf: vec![0; BUF_SIZE],
404 },
405 )
406 },
407 |(worker, sink), unit| {
408 let mut run = || -> Result<()> {
409 let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
410 w.extract(unit, sink)
411 };
412 run().err().map(|e| format!("{e:#}"))
413 },
414 )
415 .flatten()
416 .collect();
417 if failures.is_empty() {
418 return Ok(());
419 }
420 let mut msg = format!("{} damaged:", failures.len());
421 for f in failures.iter().take(10) {
422 msg.push_str("\n ");
423 msg.push_str(f);
424 }
425 Err(anyhow!(msg))
426 }
427}
428
429fn threads_per_unit(units: usize) -> u32 {
430 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
431 (cores / units.max(1)).max(1) as u32
432}
433
434fn part_path(dest: &Path) -> PathBuf {
435 let mut part = dest.as_os_str().to_owned();
436 part.push(".hatchzip-part");
437 PathBuf::from(part)
438}
439
440fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
443 if written == 0 {
444 return OpenOptions::new()
445 .read(true)
446 .write(true)
447 .create(true)
448 .truncate(true)
449 .open(part)
450 .with_context(|| format!("creating {}", part.display()));
451 }
452 if !part.exists() && dest.exists() {
453 fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
456 }
457 let mut file = OpenOptions::new()
458 .read(true)
459 .write(true)
460 .open(part)
461 .with_context(|| {
462 format!(
463 "{} is missing, and the archive bytes it was extracted from are already \
464 freed, so this file can't be finished",
465 part.display()
466 )
467 })?;
468 if file.metadata()?.len() < written {
469 bail!(
470 "{} is shorter than when its progress was saved; refusing to continue",
471 part.display()
472 );
473 }
474 file.set_len(written)?;
475 file.seek(SeekFrom::Start(written))?;
476 Ok(file)
477}
478
479fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
483 let n = written.min(resumable::WINDOW as u64);
484 let mut window = vec![0; n as usize];
485 file.seek(SeekFrom::Start(written - n))?;
486 file.read_exact(&mut window)?;
487 file.seek(SeekFrom::Start(written))?;
488 Ok(window)
489}
490
491pub struct Progress {
492 pub on_bytes: Box<dyn Fn(u64) + Sync>,
493 pub on_commit: Box<dyn Fn(u64) + Sync>,
494}
495
496pub enum Outcome {
497 Finished,
498 Paused,
499}
500
501pub struct Run<'a> {
502 pub job: Job,
503 pub journal: Journal,
504 pub paths: Paths,
505 pub stop: &'a AtomicBool,
506 pub progress: Progress,
507 pub keep_free: u64,
509}
510
511impl Run<'_> {
512 pub fn execute(mut self) -> Result<Outcome> {
513 let out = self.journal.output.clone();
514 fs::create_dir_all(&out)
515 .with_context(|| format!("creating output folder {}", out.display()))?;
516
517 let reclaims = fsutil::same_filesystem(self.job.storage.primary(), &out);
518 let mut next = 0;
519 while next < self.job.units.len() {
520 if self.stop.load(Ordering::Relaxed) {
521 return Ok(Outcome::Paused);
522 }
523 if let Some(stream) = self.stream_now(next, reclaims, &out)? {
524 if !self.stream_unit(next, &stream, &out)? {
525 return Ok(Outcome::Paused);
526 }
527 self.commit(next, next + 1, Vec::new(), &out)?;
528 next += 1;
529 continue;
530 }
531 let end = self.next_batch(next, &out, reclaims)?;
532 let batch = &self.job.units[next..end];
533
534 let Some(links) = self.extract_batch(batch, &out)? else {
535 return Ok(Outcome::Paused);
536 };
537 self.commit(next, end, links, &out)?;
538 next = end;
539 }
540
541 self.finish(&out)?;
542 Ok(Outcome::Finished)
543 }
544
545 fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
548 let batch = &self.job.units[start..end];
549 platform::sync_batch(out).context("flushing extracted files to disk")?;
552 if platform::SYNC_EACH_FILE {
553 let dirs: HashSet<PathBuf> = batch
556 .iter()
557 .flat_map(|u| &u.items)
558 .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
559 .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
560 .collect();
561 for d in &dirs {
562 fsutil::sync_dir(d)?;
563 }
564 }
565 crash_point("after-extract");
566
567 let new_len = batch.last().expect("batches are never empty").start;
568 self.journal.committed_len = new_len;
569 self.journal.links.extend(links);
570 self.journal.resume = None;
573 self.job.resume = None;
574 self.journal.save(&self.paths)?;
575 crash_point("after-journal");
576
577 self.job
578 .storage
579 .set_len(new_len)
580 .context("shrinking the archive")?;
581 (self.progress.on_commit)(new_len);
582 Ok(())
583 }
584
585 fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
590 if self.job.resumed(i).is_some() {
591 return match self.job.stream_of(i) {
592 Some(s) => Ok(Some(s)),
593 None => bail!(
594 "the journal says '{}' is half extracted, but it can't be resumed",
595 self.job.units[i].items[0].path.display()
596 ),
597 };
598 }
599 let Some(stream) = self.job.streams(i, reclaims) else {
600 return Ok(None);
601 };
602 if always_stream() {
603 return Ok(Some(stream));
604 }
605 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
606 Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
607 }
608
609 fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
619 let unit_start = self.job.units[i].start;
620 let item = self.job.units[i].items[0].clone();
621 let dest = out.join(&item.path);
622 let part = part_path(&dest);
623 let at = self.job.resumed(i).cloned().unwrap_or(Resume {
624 unit: unit_start,
625 written: 0,
626 bit: stream.data_start * 8,
627 crc: 0,
628 });
629 let started_here = at.written == 0;
630 let result = self
631 .stream_file(&item, stream, at, &dest, &part, out)
632 .with_context(|| format!("extracting '{}'", item.path.display()));
633 if result.is_err() && started_here && self.journal.resume.is_none() {
634 let _ = fs::remove_file(&part);
636 }
637 result
638 }
639
640 fn stream_file(
641 &mut self,
642 item: &Item,
643 stream: &Stream,
644 at: Resume,
645 dest: &Path,
646 part: &Path,
647 out: &Path,
648 ) -> Result<bool> {
649 if let Some(parent) = dest.parent() {
650 fs::create_dir_all(parent)?;
651 }
652 let mut file = open_part(dest, part, at.written)?;
653 let window = match stream.codec {
654 Codec::Stored => Vec::new(),
655 Codec::Deflate => read_window(&mut file, at.written)?,
656 };
657 let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
658 let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
659 let mut written = at.written;
660 let mut since_point = 0;
661 let step = stream_step();
662 let mut punching = self.job.punch_support();
663 self.ensure_room(out, item, written, punching)?;
664
665 let mut buf = vec![0; BUF_SIZE];
666 loop {
667 if self.stop.load(Ordering::Relaxed) {
668 return Ok(false);
669 }
670 let n = decoder.read(&mut buf)?;
671 if n == 0 {
672 break;
673 }
674 written += n as u64;
675 if written > item.size {
676 bail!("it is larger than the archive says it is");
677 }
678 file.write_all(&buf[..n])?;
679 crc.update(&buf[..n]);
680 (self.progress.on_bytes)(n as u64);
681 since_point += n as u64;
682
683 if since_point < step || written == item.size {
684 continue;
685 }
686 match decoder.restart_point() {
687 Some(bit) => {
688 let point = Resume {
689 unit: at.unit,
690 written,
691 bit,
692 crc: crc.clone().finalize(),
693 };
694 punching = self.save_point(&file, part, out, point, stream, punching)?;
695 since_point = 0;
696 self.ensure_room(out, item, written, punching)?;
697 }
698 None => {
703 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
704 if avail < 2 * BUF_SIZE as u64 {
705 bail!(
706 "stopped inside it: its compressed data has no point to resume from \
707 in the last {}, so its archive space can't be freed yet. Nothing \
708 is lost. Free up {} (what is left of this file) and run the same \
709 command again to continue.",
710 human(since_point),
711 human(item.size - written),
712 );
713 }
714 }
715 }
716 }
717 if written != item.size {
718 bail!("it is smaller than the archive says it is");
719 }
720 if let Some(expected) = stream.crc
721 && crc.finalize() != expected
722 {
723 bail!("its data is damaged (CRC mismatch)");
724 }
725 if let Some(t) = item.mtime {
726 file.set_modified(t)?;
727 }
728 platform::apply_mode(&file, item.mode)?;
729 file.sync_all()?;
730 drop(file);
731 fs::rename(part, dest)?;
735 Ok(true)
736 }
737
738 fn save_point(
741 &mut self,
742 file: &File,
743 part: &Path,
744 out: &Path,
745 point: Resume,
746 stream: &Stream,
747 punching: Option<u64>,
748 ) -> Result<Option<u64>> {
749 file.sync_all()
750 .context("flushing the extracted file to disk")?;
751 let mut dir = part.parent();
754 while let Some(d) = dir {
755 fsutil::sync_dir(d)?;
756 if d == out {
757 break;
758 }
759 dir = d.parent();
760 }
761 crash_point("stream-after-sync");
762
763 self.journal.resume = Some(point.clone());
764 self.journal.save(&self.paths)?;
765 self.job.resume = Some(point.clone());
766 crash_point("stream-after-journal");
767
768 if punching.is_some()
771 && !self
772 .job
773 .storage
774 .punch(stream.data_start, point.bit / 8)
775 .context("freeing extracted archive bytes")?
776 {
777 return Ok(None);
780 }
781 crash_point("stream-after-punch");
782 Ok(punching)
783 }
784
785 fn ensure_room(
787 &self,
788 out: &Path,
789 item: &Item,
790 written: u64,
791 punching: Option<u64>,
792 ) -> Result<()> {
793 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
794 let left = (item.size - written).next_multiple_of(4096);
795 let need = match punching {
796 Some(granule) => (stream_step() + BUF_SIZE as u64 + 2 * granule).min(left),
797 None => left,
798 };
799 if need > avail {
800 bail!(
801 "stopped inside '{}': the next part needs {} and only {} is free (keeping {} \
802 spare).\nNothing is lost. Free up {} and run the same command again to continue.",
803 item.path.display(),
804 human(need),
805 human(avail),
806 human(self.keep_free),
807 human(need - avail),
808 );
809 }
810 Ok(())
811 }
812
813 fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
816 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
817 let units = &self.job.units;
818 let need = on_disk;
819 let first = need(&units[start]);
820 if first > avail {
821 let what = match units[start].items.as_slice() {
824 [one] => format!("'{}'", one.path.display()),
825 many => format!("the next block of {} files", many.len()),
826 };
827 bail!(
828 "stopped before {what}: it needs {} and only {} is free (keeping {} spare).\n\
829 Nothing is lost. Free up {} and run the same command again to continue.",
830 human(first),
831 human(avail),
832 human(self.keep_free),
833 human(first - avail),
834 );
835 }
836 let budget = avail.min(BATCH_MAX_BYTES.max(first));
837 let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
838 let mut used = 0;
839 let mut end = start;
840 while end < units.len() && end - start < max_units {
841 let size = need(&units[end]);
842 if end > start && used + size > budget {
843 break;
844 }
845 if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
846 break;
847 }
848 used += size;
849 end += 1;
850 }
851 Ok(end)
852 }
853
854 fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
857 let threads = threads_per_unit(batch.len());
858 let on_bytes = &*self.progress.on_bytes;
859 let results: Vec<Result<Vec<Link>>> = batch
860 .par_iter()
861 .map_init(
862 || {
863 let sink = DiskSink {
864 out,
865 stop: self.stop,
866 on_bytes,
867 buf: vec![0; BUF_SIZE],
868 links: Vec::new(),
869 };
870 (self.job.format.worker(threads), sink)
871 },
872 |(worker, sink), unit| {
873 let w = worker
874 .as_mut()
875 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
876 w.extract(unit, sink)?;
877 Ok(std::mem::take(&mut sink.links))
878 },
879 )
880 .collect();
881
882 let mut links = Vec::new();
883 let mut interrupted = false;
884 for r in results {
885 match r {
886 Ok(l) => links.extend(l),
887 Err(e) if is_interrupt(&e) => interrupted = true,
888 Err(e) => return Err(e),
889 }
890 }
891 Ok((!interrupted).then_some(links))
892 }
893
894 fn finish(self, out: &Path) -> Result<()> {
895 make_links(&self.journal.links, out)?;
896 let Self { job, paths, .. } = self;
897 let Job {
898 storage, format, ..
899 } = job;
900 drop(format);
902 let storage = Arc::try_unwrap(storage)
903 .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
904 storage.remove()?;
907 paths.remove()
908 }
909}
910
911pub fn finish_orphaned(journal: &Journal, paths: &Paths) -> Result<()> {
914 make_links(&journal.links, &journal.output)?;
915 paths.remove()
916}
917
918pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
919 for link in links {
920 let path = out.join(&link.path);
921 if let Some(parent) = path.parent() {
922 fs::create_dir_all(parent)?;
923 }
924 let made = if link.hard {
925 let target = out.join(&link.target);
926 let _ = fs::remove_file(&path);
927 fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))
929 } else {
930 platform::create_symlink(&path, &link.target)
931 };
932 made.with_context(|| format!("creating link '{}'", link.path.display()))?;
933 }
934 Ok(())
935}
936
937struct DiskSink<'a> {
938 out: &'a Path,
939 stop: &'a AtomicBool,
940 on_bytes: &'a (dyn Fn(u64) + Sync),
941 buf: Vec<u8>,
942 links: Vec<Link>,
943}
944
945impl Sink for DiskSink<'_> {
946 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
947 self.write(item, data)
948 .with_context(|| format!("extracting '{}'", item.path.display()))
949 }
950}
951
952impl DiskSink<'_> {
953 fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
954 let dest = self.out.join(&item.path);
955 match &item.kind {
956 Kind::Dir => {
957 fs::create_dir_all(&dest)?;
958 return Ok(());
959 }
960 Kind::Symlink => {
961 let mut target = Vec::new();
962 data.take(MAX_SYMLINK).read_to_end(&mut target)?;
963 let target = PathBuf::from(String::from_utf8(target)?);
964 self.links.push(Link {
965 path: item.path.clone(),
966 target,
967 hard: false,
968 });
969 return Ok(());
970 }
971 Kind::HardLink(target) => {
972 self.links.push(Link {
973 path: item.path.clone(),
974 target: target.clone(),
975 hard: true,
976 });
977 return Ok(());
978 }
979 Kind::File => {}
980 }
981
982 if let Some(parent) = dest.parent() {
983 fs::create_dir_all(parent)?;
984 }
985 let part = part_path(&dest);
986 let result = self.copy(item, data, &part);
987 if result.is_err() {
988 let _ = fs::remove_file(&part);
989 return result;
990 }
991 fs::rename(&part, &dest)?;
992 Ok(())
993 }
994
995 fn copy(&mut self, item: &Item, data: &mut dyn Read, part: &Path) -> Result<()> {
996 let mut dst = File::create(part)?;
997 let mut written = 0u64;
998 loop {
999 if self.stop.load(Ordering::Relaxed) {
1000 return Err(io::Error::from(io::ErrorKind::Interrupted).into());
1001 }
1002 let n = data.read(&mut self.buf)?;
1005 if n == 0 {
1006 break;
1007 }
1008 written += n as u64;
1009 if written > item.size {
1010 bail!("it is larger than the archive says it is");
1011 }
1012 dst.write_all(&self.buf[..n])?;
1013 (self.on_bytes)(n as u64);
1014 }
1015 if written != item.size {
1016 bail!("it is smaller than the archive says it is");
1017 }
1018 if let Some(t) = item.mtime {
1019 dst.set_modified(t)?;
1020 }
1021 platform::apply_mode(&dst, item.mode)?;
1022 if platform::SYNC_EACH_FILE {
1023 dst.sync_all()?;
1024 }
1025 Ok(())
1026 }
1027}
1028
1029struct ProbeSink {
1031 left: u64,
1032 buf: Vec<u8>,
1033}
1034
1035#[derive(Debug)]
1036struct ProbeDone;
1037
1038impl std::fmt::Display for ProbeDone {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.write_str("read enough to prove the password")
1041 }
1042}
1043
1044impl std::error::Error for ProbeDone {}
1045
1046impl Sink for ProbeSink {
1047 fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
1048 loop {
1049 let n = data.read(&mut self.buf)?;
1050 if n == 0 {
1051 return Ok(());
1052 }
1053 self.left = self.left.saturating_sub(n as u64);
1054 if self.left == 0 {
1055 return Err(ProbeDone.into());
1056 }
1057 }
1058 }
1059}
1060
1061struct VerifySink<'a> {
1062 on_bytes: &'a (dyn Fn(u64) + Sync),
1063 buf: Vec<u8>,
1064}
1065
1066impl Sink for VerifySink<'_> {
1067 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1068 let mut read = 0;
1069 loop {
1070 let n = data
1071 .read(&mut self.buf)
1072 .with_context(|| format!("'{}'", item.path.display()))?;
1073 if n == 0 {
1074 break;
1075 }
1076 read += n as u64;
1077 (self.on_bytes)(n as u64);
1078 }
1079 if item.kind == Kind::File && read != item.size {
1080 bail!(
1081 "'{}' is shorter than the archive says it is",
1082 item.path.display()
1083 );
1084 }
1085 Ok(())
1086 }
1087}
1088
1089fn is_interrupt(e: &anyhow::Error) -> bool {
1090 e.chain()
1091 .filter_map(|c| c.downcast_ref::<io::Error>())
1092 .any(|io| io.kind() == io::ErrorKind::Interrupted)
1093}
1094
1095fn test_knob(name: &str) -> Option<u32> {
1097 if !cfg!(debug_assertions) {
1098 return None;
1099 }
1100 std::env::var(name).ok()?.parse().ok()
1101}
1102
1103pub(crate) fn crash_point(name: &str) {
1106 if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
1107 return;
1108 }
1109 static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1110 if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
1111 std::process::abort();
1112 }
1113}
1114
1115pub fn human(bytes: u64) -> String {
1116 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
1117 let mut v = bytes as f64;
1118 let mut unit = 0;
1119 while v >= 1000.0 && unit < UNITS.len() - 1 {
1120 v /= 1000.0;
1121 unit += 1;
1122 }
1123 if unit == 0 {
1124 format!("{bytes} B")
1125 } else {
1126 format!("{v:.1} {}", UNITS[unit])
1127 }
1128}