1use std::collections::{HashMap, HashSet};
31use std::fs::{self, File, OpenOptions};
32use std::io::{self, Read, Seek, SeekFrom, Write};
33use std::path::{Path, PathBuf};
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::sync::{Arc, OnceLock};
36
37use anyhow::{Context, Result, anyhow, bail};
38use rayon::prelude::*;
39
40use crate::archive::resumable::{self, Decoder};
41use crate::archive::storage::{Reads, Storage, Tail};
42use crate::archive::targz::{Event, Profile, Walker};
43use crate::archive::{self, Codec, Format, Item, Kind, PasswordCheck, Sink, Stream, Unit};
44use crate::journal::{Journal, Link, Paths, Resume, TarAt};
45use crate::{fsutil, platform};
46
47const BATCH_MAX_UNITS: usize = 512;
50const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
51const BUF_SIZE: usize = 1024 * 1024;
52const MAX_SYMLINK: u64 = 64 * 1024;
53
54const STREAM_STEP: u64 = 256 * 1024 * 1024;
58
59fn stream_step() -> u64 {
60 test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
61}
62
63fn stream_threshold() -> u64 {
66 2 * stream_step()
67}
68
69fn always_stream() -> bool {
72 test_knob("HATCHZIP_STREAM_STEP").is_some()
73}
74
75fn on_disk(u: &Unit) -> u64 {
76 u.items.iter().map(|i| i.size.next_multiple_of(4096)).sum()
77}
78
79pub struct Job {
80 pub storage: Arc<Storage>,
81 pub format_name: &'static str,
82 format: Box<dyn Format>,
83 pub units: Vec<Unit>,
85 pub tail_start: u64,
86 pub top: u64,
89 punch: OnceLock<Option<u64>>,
93 resume: Option<Resume>,
95}
96
97impl Job {
98 pub fn open(
102 path: &Path,
103 writable: bool,
104 password: Option<&str>,
105 reads: Arc<Reads>,
106 ) -> Result<Self> {
107 let job = Self::open_as_is(path, writable, password, reads)?;
108 job.check_layout()?;
109 Ok(job)
110 }
111
112 pub(crate) fn open_as_is(
117 path: &Path,
118 writable: bool,
119 password: Option<&str>,
120 reads: Arc<Reads>,
121 ) -> Result<Self> {
122 let mut storage = Storage::open(path, writable)?;
123 storage.count_reads(reads);
124 let storage = Arc::new(storage);
125 let opened = archive::open(&storage, None, password)?;
126 let top = storage.original_len();
127 Self::build(storage, opened, top)
128 }
129
130 pub fn resume(
134 journal: &Journal,
135 tail: Arc<Tail>,
136 writable: bool,
137 password: Option<&str>,
138 reads: Arc<Reads>,
139 ) -> Result<Self> {
140 let mut storage = Storage::from_parts(&journal.parts, writable)?;
141 storage.count_reads(reads);
142 let storage = Arc::new(storage);
143 let current = storage.current_len()?;
144 if journal.keep {
145 storage.protect();
148 if current != storage.original_len() {
149 bail!(
150 "{} has changed since the extraction started. Put the original archive back \
151 to resume, or run restore to discard the progress",
152 storage.primary().display()
153 );
154 }
155 }
156 if current < journal.committed_len {
157 bail!(
158 "{} is shorter than HatchZip left it and will not be modified",
159 storage.primary().display()
160 );
161 }
162 if current > journal.committed_len && writable && !journal.keep {
163 storage.set_len(journal.committed_len)?;
165 }
166 let point = journal.resume.as_ref();
167 let opened = archive::open(&storage, Some((&journal.format, tail, point)), password)?;
168 let mut job = Self::build(storage, opened, journal.committed_len)?;
169 if let Some(r) = &journal.resume {
170 if job.units.first().map(|u| u.start) != Some(r.unit) {
173 bail!(
174 "the journal of {} records a partially extracted file that is not the next one \
175 in the archive. The archive will not be modified",
176 job.storage.primary().display()
177 );
178 }
179 job.resume = Some(r.clone());
180 }
181 Ok(job)
182 }
183
184 fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
185 let mut units = opened.units;
186 units.retain(|u| u.start < top);
187 units.sort_by_key(|u| std::cmp::Reverse(u.start));
188
189 let mut seen = HashSet::new();
190 for item in units.iter().flat_map(|u| &u.items) {
191 for part in item.path.iter() {
192 if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
193 bail!(
194 "'{}' cannot be created at this location: {why}. The archive was not modified",
195 item.path.display()
196 );
197 }
198 }
199 if item.kind != Kind::Dir && !seen.insert(item.path.to_string_lossy().to_lowercase()) {
202 bail!(
203 "'{}' appears more than once in the archive (ignoring case); extraction refused",
204 item.path.display()
205 );
206 }
207 }
208 Ok(Self {
209 storage,
210 format_name: opened.name,
211 format: opened.format,
212 units,
213 tail_start: opened.tail_start,
214 top,
215 punch: OnceLock::new(),
216 resume: None,
217 })
218 }
219
220 fn check_layout(&self) -> Result<()> {
232 let key = |p: &Path| p.to_string_lossy().to_lowercase();
233 let items = || self.units.iter().flat_map(|u| &u.items);
234 let mut folders: HashMap<String, (&Path, bool)> = HashMap::new();
237 for item in items() {
238 if item.kind == Kind::Dir {
239 folders.insert(key(&item.path), (&item.path, true));
240 }
241 for parent in item.path.ancestors().skip(1) {
242 if parent.as_os_str().is_empty() {
243 break;
244 }
245 folders.entry(key(parent)).or_insert((&item.path, false));
246 }
247 }
248 let files: HashSet<&Path> = items()
249 .filter(|i| i.kind == Kind::File)
250 .map(|i| i.path.as_path())
251 .collect();
252 for item in items() {
253 let what = match &item.kind {
254 Kind::Dir => continue,
255 Kind::File => "a file",
256 Kind::Symlink => "a symbolic link",
257 Kind::HardLink(_) => "a hard link",
258 };
259 match folders.get(&key(&item.path)) {
260 Some((dir, true)) if *dir == item.path => bail!(
261 "'{}' is both {what} and a folder in the archive; extraction refused",
262 item.path.display()
263 ),
264 Some((dir, true)) => bail!(
265 "'{}' is {what}, and '{}' is a folder in the archive; extraction refused",
266 item.path.display(),
267 dir.display()
268 ),
269 Some((inside, false)) => bail!(
270 "'{}' is {what}, but '{}' requires a folder at that location; extraction \
271 refused",
272 item.path.display(),
273 inside.display()
274 ),
275 None => {}
276 }
277 if let Kind::HardLink(target) = &item.kind
278 && !files.contains(target.as_path())
279 {
280 bail!(
281 "hard link '{}' points to '{}', which is not a file in the archive; \
282 extraction refused",
283 item.path.display(),
284 target.display()
285 );
286 }
287 }
288 Ok(())
289 }
290
291 pub fn punch_support(&self) -> Option<u64> {
296 *self.punch.get_or_init(|| {
297 if test_knob("HATCHZIP_NO_PUNCH").is_some() {
298 return None;
299 }
300 let dir = match self.storage.primary().parent() {
301 Some(d) if !d.as_os_str().is_empty() => d,
302 _ => Path::new("."),
303 };
304 fsutil::can_punch(dir).then(|| platform::punch_granule(dir))
305 })
306 }
307
308 pub fn encrypted(&self) -> bool {
309 self.units.iter().any(|u| u.encrypted)
310 }
311
312 pub fn is_stream(&self) -> bool {
314 self.format.solid().is_some()
315 }
316
317 pub fn kept_whole(&self, reclaims: bool) -> bool {
321 self.is_stream() && reclaims && self.punch_support().is_none()
322 }
323
324 pub fn check_password(&self) -> Result<()> {
329 const ENOUGH: u64 = 64 * 1024 * 1024;
330 let Some(unit) = self.smallest_encrypted() else {
331 return Ok(());
332 };
333 let left = match self.format.password_check() {
334 PasswordCheck::Headers => return self.format.prove_password(),
335 PasswordCheck::Sample => ENOUGH,
336 PasswordCheck::WholeUnit => u64::MAX,
340 };
341 let mut worker = self.format.worker(1)?;
342 let mut sink = ProbeSink {
343 left,
344 buf: vec![0; BUF_SIZE],
345 };
346 match worker.extract(unit, &mut sink) {
347 Ok(()) => Ok(()),
348 Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
349 Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
350 Err(_) => Err(archive::WrongPassword.into()),
351 }
352 }
353
354 fn smallest_encrypted(&self) -> Option<&Unit> {
357 self.units
358 .iter()
359 .filter(|u| u.encrypted)
360 .min_by_key(|u| (u.size() == 0, u.size()))
361 }
362
363 pub fn slow_password_check(&self) -> Option<(&Path, u64)> {
367 if !self.encrypted() || self.format.password_check() != PasswordCheck::WholeUnit {
368 return None;
369 }
370 let unit = self.smallest_encrypted()?;
371 Some((unit.items.first()?.path.as_path(), unit.size()))
372 }
373
374 pub fn in_place_refusal(&self) -> Option<String> {
377 self.format.refuses_in_place()
378 }
379
380 pub fn item_count(&self) -> usize {
381 self.units.iter().map(|u| u.items.len()).sum()
382 }
383
384 pub fn remaining_size(&self) -> u64 {
385 let done = self.resume.as_ref().map_or(0, |r| r.written);
386 self.units.iter().map(Unit::size).sum::<u64>() - done
387 }
388
389 fn resumed(&self, i: usize) -> Option<&Resume> {
391 self.resume
392 .as_ref()
393 .filter(|r| r.unit == self.units[i].start)
394 }
395
396 fn stream_of(&self, i: usize) -> Option<Stream> {
399 let unit = &self.units[i];
400 match unit.items.as_slice() {
401 [item] if item.kind == Kind::File && !unit.encrypted => {
402 self.format.stream(unit).ok().flatten()
403 }
404 _ => None,
405 }
406 }
407
408 fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
412 if self.resumed(i).is_some() {
413 return self.stream_of(i);
414 }
415 if !reclaims || self.units[i].size() < stream_threshold() {
416 return None;
417 }
418 self.punch_support()?;
419 self.stream_of(i)
420 }
421
422 fn span(&self, i: usize) -> u64 {
425 let end = if i == 0 {
426 self.top
427 } else {
428 self.units[i - 1].start
429 };
430 end - self.units[i].start
431 }
432
433 pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
439 let tail = (self.storage.original_len() - self.tail_start) as i128;
440 let mut extra: i128 = if fresh { tail } else { 0 };
441 let mut peak = extra;
442 for (i, u) in self.units.iter().enumerate() {
443 let span = self.span(i) as i128;
444 if let Some(solid) = self.format.solid() {
445 let (rise, net) = self.solid_cost(i, &solid.profile, span, reclaims);
446 peak = peak.max(extra + rise);
447 extra += net;
448 continue;
449 }
450 if let Some(s) = self.streams(i, reclaims) {
451 let (rise, net) = self.stream_cost(i, &s, span, reclaims);
452 peak = peak.max(extra + rise);
453 extra += net;
454 continue;
455 }
456 let on_disk = on_disk(u) as i128;
457 peak = peak.max(extra + on_disk);
458 extra += on_disk;
459 if reclaims {
460 extra -= span;
461 }
462 }
463 if reclaims {
464 let stub = self.units.last().map_or(self.top, |u| u.start);
467 extra -= stub as i128 + tail;
468 }
469 (peak.max(0) as u64, extra)
470 }
471
472 fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
487 let at = self.resumed(i);
488 let done = at.map_or(0, |r| r.written / 4096 * 4096);
491 let out_left = (on_disk(&self.units[i]) - done) as i128;
492 let read_to = at.map_or(s.data_start, |r| r.bit / 8);
493 let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
494 let freed = read_to.saturating_sub(s.data_start) as i128;
498 let net = if reclaims {
499 out_left - (span - freed)
500 } else {
501 out_left
502 };
503 let rise = match self.punch_support() {
504 Some(granule) if reclaims => {
505 let slack = match s.codec {
506 Codec::Stored => 0,
507 Codec::Deflate => out_left / 1024,
508 };
509 let step = (stream_step() + BUF_SIZE as u64 + 2 * granule) as i128;
510 ((out_left - data_left).max(0) + slack + step).min(out_left)
511 }
512 _ => out_left,
513 };
514 (rise, net)
515 }
516
517 fn solid_cost(&self, i: usize, p: &Profile, span: i128, reclaims: bool) -> (i128, i128) {
528 let out_left = (p.files + p.links) as i128;
529 let freed = self.resumed(i).map_or(0, |r| r.bit / 8) as i128;
531 let net = if reclaims {
532 out_left - (span - freed)
533 } else {
534 out_left
535 };
536 let rise = match self.punch_support() {
537 Some(granule) if reclaims => {
538 let ahead = stream_step() + p.gap + BUF_SIZE as u64 + 2 * granule;
539 (p.lead.max(0) + ahead as i128).min(p.files as i128)
540 }
541 _ => out_left,
544 };
545 (rise.max(net), net)
546 }
547
548 fn open_entry(&self) -> Option<&Item> {
551 let r = self.resume.as_ref()?;
552 let inside = match &r.stream {
553 Some(s) => matches!(s.at, TarAt::File { .. }),
554 None => true,
555 };
556 if !inside {
557 return None;
558 }
559 self.units.first().and_then(|u| u.items.first())
560 }
561
562 pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
569 let open = self.open_entry().is_some();
570 let mut found = Vec::new();
571 for (i, u) in self.units.iter().enumerate() {
572 for (k, item) in u.items.iter().enumerate() {
573 if item.kind != Kind::File || (open && i == 0 && k == 0) {
574 continue;
575 }
576 let dest = out.join(&item.path);
577 for p in [part_path(&dest), dest] {
578 if let Ok(m) = fs::symlink_metadata(&p)
579 && m.is_file()
580 {
581 found.push((p, m.len().next_multiple_of(4096)));
582 }
583 }
584 }
585 }
586 found
587 }
588
589 pub fn past_resume_point(&self, out: &Path) -> u64 {
592 let (Some(r), Some(item)) = (self.resume.as_ref(), self.open_entry()) else {
593 return 0;
594 };
595 let dest = out.join(&item.path);
596 [part_path(&dest), dest]
597 .iter()
598 .find_map(|p| fs::metadata(p).ok())
599 .map_or(0, |m| {
600 (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
601 })
602 }
603
604 pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
607 let failures = if self.format.serial() {
608 self.verify_serial(on_bytes)?
609 } else {
610 self.verify_parallel(on_bytes)
611 };
612 if failures.is_empty() {
613 return Ok(());
614 }
615 let mut msg = format!("{} damaged:", failures.len());
616 for f in failures.iter().take(10) {
617 msg.push_str("\n ");
618 msg.push_str(f);
619 }
620 Err(anyhow!(msg))
621 }
622
623 fn verify_serial(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<Vec<String>> {
625 let mut worker = self.format.worker(1)?;
626 let mut sink = VerifySink {
627 on_bytes,
628 buf: vec![0; BUF_SIZE],
629 };
630 Ok(self
631 .units
632 .iter()
633 .rev()
634 .filter_map(|u| worker.extract(u, &mut sink).err())
635 .map(|e| format!("{e:#}"))
636 .collect())
637 }
638
639 fn verify_parallel(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Vec<String> {
640 let threads = threads_per_unit(self.units.len());
641 self.units
642 .par_iter()
643 .map_init(
644 || {
645 (
646 self.format.worker(threads),
647 VerifySink {
648 on_bytes,
649 buf: vec![0; BUF_SIZE],
650 },
651 )
652 },
653 |(worker, sink), unit| {
654 let mut run = || -> Result<()> {
655 let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
656 w.extract(unit, sink)
657 };
658 run().err().map(|e| format!("{e:#}"))
659 },
660 )
661 .flatten()
662 .collect()
663 }
664}
665
666fn threads_per_unit(units: usize) -> u32 {
667 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
668 (cores / units.max(1)).max(1) as u32
669}
670
671fn part_path(dest: &Path) -> PathBuf {
672 let mut part = dest.as_os_str().to_owned();
673 part.push(".hatchzip-part");
674 PathBuf::from(part)
675}
676
677fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
680 if written == 0 {
681 return OpenOptions::new()
682 .read(true)
683 .write(true)
684 .create(true)
685 .truncate(true)
686 .open(part)
687 .with_context(|| format!("creating {}", part.display()));
688 }
689 if !part.exists() && dest.exists() {
690 fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
693 }
694 let mut file = OpenOptions::new()
695 .read(true)
696 .write(true)
697 .open(part)
698 .with_context(|| {
699 format!(
700 "{} is missing, and the archive data it was extracted from is already \
701 released, so this file cannot be completed",
702 part.display()
703 )
704 })?;
705 if file.metadata()?.len() < written {
706 bail!(
707 "{} is shorter than when its progress was saved; the extraction cannot continue",
708 part.display()
709 );
710 }
711 file.set_len(written)?;
712 file.seek(SeekFrom::Start(written))?;
713 Ok(file)
714}
715
716struct OpenFile {
718 item: Item,
719 dest: PathBuf,
720 part: PathBuf,
721 file: File,
722 written: u64,
723}
724
725impl OpenFile {
726 fn finish(self) -> Result<()> {
728 if self.written != self.item.size {
729 bail!("it is smaller than the archive records");
730 }
731 if let Some(t) = self.item.mtime {
732 self.file.set_modified(t)?;
733 }
734 platform::apply_mode(&self.file, self.item.mode)?;
735 if platform::SYNC_EACH_FILE {
736 self.file.sync_all()?;
737 }
738 drop(self.file);
739 fs::rename(&self.part, &self.dest)?;
740 Ok(())
741 }
742}
743
744fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
748 let n = written.min(resumable::WINDOW as u64);
749 let mut window = vec![0; n as usize];
750 file.seek(SeekFrom::Start(written - n))?;
751 file.read_exact(&mut window)?;
752 file.seek(SeekFrom::Start(written))?;
753 Ok(window)
754}
755
756pub struct Progress {
757 pub on_bytes: Box<dyn Fn(u64) + Sync>,
758 pub on_commit: Box<dyn Fn(u64) + Sync>,
759}
760
761pub enum Outcome {
762 Finished,
763 Paused,
764}
765
766pub struct Run<'a> {
767 pub job: Job,
768 pub journal: Journal,
769 pub paths: Paths,
770 pub stop: &'a AtomicBool,
771 pub progress: Progress,
772 pub keep_free: u64,
774}
775
776impl Run<'_> {
777 pub fn execute(mut self) -> Result<Outcome> {
778 let out = self.journal.output.clone();
779 fs::create_dir_all(&out)
780 .with_context(|| format!("creating output folder {}", out.display()))?;
781
782 let reclaims =
785 !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
786 if self.journal.keep {
787 self.job.storage.protect();
788 }
789 let mut next = 0;
790 while next < self.job.units.len() {
791 if self.stop.load(Ordering::Relaxed) {
792 return Ok(Outcome::Paused);
793 }
794 if let Some(solid) = self.job.format.solid() {
795 let walk = solid.walk(self.job.resumed(next))?;
796 let Some(links) = self.stream_solid(next, walk, reclaims, &out)? else {
797 return Ok(Outcome::Paused);
798 };
799 self.commit(next, next + 1, links, &out)?;
800 next += 1;
801 continue;
802 }
803 if let Some(stream) = self.stream_now(next, reclaims, &out)? {
804 if !self.stream_unit(next, &stream, &out)? {
805 return Ok(Outcome::Paused);
806 }
807 self.commit(next, next + 1, Vec::new(), &out)?;
808 next += 1;
809 continue;
810 }
811 let end = self.next_batch(next, &out, reclaims)?;
812 let batch = &self.job.units[next..end];
813
814 let Some(links) = self.extract_batch(batch, &out)? else {
815 return Ok(Outcome::Paused);
816 };
817 self.commit(next, end, links, &out)?;
818 next = end;
819 }
820
821 self.finish(&out)?;
822 Ok(Outcome::Finished)
823 }
824
825 fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
828 let batch = &self.job.units[start..end];
829 platform::sync_batch(out).context("flushing extracted files to disk")?;
832 if platform::SYNC_EACH_FILE {
833 let dirs: HashSet<PathBuf> = batch
836 .iter()
837 .flat_map(|u| &u.items)
838 .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
839 .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
840 .collect();
841 for d in &dirs {
842 fsutil::sync_dir(d)?;
843 }
844 }
845 crash_point("after-extract");
846
847 let new_len = batch.last().expect("batches are never empty").start;
848 self.journal.committed_len = new_len;
849 self.journal.links.extend(links);
850 self.journal.resume = None;
853 self.job.resume = None;
854 self.journal.save(&self.paths)?;
855 crash_point("after-journal");
856
857 if self.journal.keep {
858 return Ok(());
859 }
860 self.job
861 .storage
862 .set_len(new_len)
863 .context("shrinking the archive")?;
864 (self.progress.on_commit)(new_len);
865 Ok(())
866 }
867
868 fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
873 if self.job.resumed(i).is_some() {
874 return match self.job.stream_of(i) {
875 Some(s) => Ok(Some(s)),
876 None => bail!(
877 "the journal records '{}' as partially extracted, but it cannot be resumed",
878 self.job.units[i].items[0].path.display()
879 ),
880 };
881 }
882 let Some(stream) = self.job.streams(i, reclaims) else {
883 return Ok(None);
884 };
885 if always_stream() {
886 return Ok(Some(stream));
887 }
888 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
889 Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
890 }
891
892 fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
902 let unit_start = self.job.units[i].start;
903 let item = self.job.units[i].items[0].clone();
904 let dest = out.join(&item.path);
905 let part = part_path(&dest);
906 let at = self.job.resumed(i).cloned().unwrap_or(Resume {
907 unit: unit_start,
908 written: 0,
909 bit: stream.data_start * 8,
910 crc: 0,
911 stream: None,
912 });
913 let started_here = at.written == 0;
914 let result = self
915 .stream_file(&item, stream, at, &dest, &part, out)
916 .with_context(|| format!("extracting '{}'", item.path.display()));
917 if result.is_err() && started_here && self.journal.resume.is_none() {
918 let _ = fs::remove_file(&part);
920 }
921 result
922 }
923
924 fn stream_file(
925 &mut self,
926 item: &Item,
927 stream: &Stream,
928 at: Resume,
929 dest: &Path,
930 part: &Path,
931 out: &Path,
932 ) -> Result<bool> {
933 if let Some(parent) = dest.parent() {
934 fs::create_dir_all(parent)?;
935 }
936 let mut file = open_part(dest, part, at.written)?;
937 let window = match stream.codec {
938 Codec::Stored => Vec::new(),
939 Codec::Deflate => read_window(&mut file, at.written)?,
940 };
941 let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
942 let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
943 let mut written = at.written;
944 let mut since_point = 0;
945 let step = stream_step();
946 let mut punching = self.job.punch_support();
947 let what = format!("'{}'", item.path.display());
948 self.ensure_room(out, &what, item.size - written, punching)?;
949
950 let mut buf = vec![0; BUF_SIZE];
951 loop {
952 if self.stop.load(Ordering::Relaxed) {
953 return Ok(false);
954 }
955 let n = decoder.read(&mut buf)?;
956 if n == 0 {
957 break;
958 }
959 written += n as u64;
960 if written > item.size {
961 bail!("it is larger than the archive records");
962 }
963 file.write_all(&buf[..n])?;
964 crc.update(&buf[..n]);
965 (self.progress.on_bytes)(n as u64);
966 since_point += n as u64;
967
968 if since_point < step || written == item.size {
969 continue;
970 }
971 match decoder.restart_point() {
972 Some(bit) => {
973 let point = Resume {
974 unit: at.unit,
975 written,
976 bit,
977 crc: crc.clone().finalize(),
978 stream: None,
979 };
980 punching = self.save_point(&file, part, out, point, stream, punching)?;
981 since_point = 0;
982 self.ensure_room(out, &what, item.size - written, punching)?;
983 }
984 None => {
989 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
990 if avail < 2 * BUF_SIZE as u64 {
991 bail!(
992 "not enough disk space to continue: the compressed data of this entry has \
993 no resume point in the last {}, so its archive space cannot be \
994 released yet. {} more is required (the remainder of this file). \
995 Progress is saved; free up space and resume the extraction.",
996 human(since_point),
997 human(item.size - written),
998 );
999 }
1000 }
1001 }
1002 }
1003 if written != item.size {
1004 bail!("it is smaller than the archive records");
1005 }
1006 if let Some(expected) = stream.crc
1007 && crc.finalize() != expected
1008 {
1009 bail!("its data is damaged (CRC mismatch)");
1010 }
1011 if let Some(t) = item.mtime {
1012 file.set_modified(t)?;
1013 }
1014 platform::apply_mode(&file, item.mode)?;
1015 file.sync_all()?;
1016 drop(file);
1017 fs::rename(part, dest)?;
1021 Ok(true)
1022 }
1023
1024 fn save_point(
1027 &mut self,
1028 file: &File,
1029 part: &Path,
1030 out: &Path,
1031 point: Resume,
1032 stream: &Stream,
1033 punching: Option<u64>,
1034 ) -> Result<Option<u64>> {
1035 file.sync_all()
1036 .context("flushing the extracted file to disk")?;
1037 let mut dir = part.parent();
1040 while let Some(d) = dir {
1041 fsutil::sync_dir(d)?;
1042 if d == out {
1043 break;
1044 }
1045 dir = d.parent();
1046 }
1047 crash_point("stream-after-sync");
1048
1049 self.journal.resume = Some(point.clone());
1050 self.journal.save(&self.paths)?;
1051 self.job.resume = Some(point.clone());
1052 crash_point("stream-after-journal");
1053
1054 if punching.is_some()
1057 && !self
1058 .job
1059 .storage
1060 .punch(stream.data_start, point.bit / 8)
1061 .context("freeing extracted archive bytes")?
1062 {
1063 return Ok(None);
1066 }
1067 crash_point("stream-after-punch");
1068 Ok(punching)
1069 }
1070
1071 fn stream_solid(
1084 &mut self,
1085 i: usize,
1086 mut walk: Walker,
1087 reclaims: bool,
1088 out: &Path,
1089 ) -> Result<Option<Vec<Link>>> {
1090 let unit = self.job.units[i].start;
1091 let step = stream_step();
1092 let mut punching = self.job.punch_support().filter(|_| reclaims);
1095 let profile = match self.job.format.solid() {
1096 Some(s) => s.profile.clone(),
1097 None => bail!("the archive is not a compressed stream"),
1098 };
1099 let mut left = profile.files;
1100 let mut punched = 0;
1104 let mut since_point = 0u64;
1105 let mut checked = 0u64;
1106 let mut open: Option<OpenFile> = None;
1107 let mut links = Vec::new();
1108 let mut dirs = HashSet::new();
1109 self.ensure_room(out, "the archive", left, punching)?;
1110
1111 loop {
1112 if self.stop.load(Ordering::Relaxed) {
1113 return Ok(None);
1114 }
1115 match walk.next(BUF_SIZE)? {
1116 Event::Entry { item, link, done } => {
1117 let dest = out.join(&item.path);
1118 let what = || format!("extracting '{}'", item.path.display());
1119 match &item.kind {
1120 Kind::Dir => {
1121 fs::create_dir_all(&dest).with_context(what)?;
1122 dirs.insert(dest);
1123 }
1124 Kind::Symlink => {
1125 let target = String::from_utf8(link.unwrap_or_default())
1126 .map_err(|_| anyhow!("the link target is not valid UTF-8"))
1127 .with_context(what)?;
1128 links.push(Link {
1129 path: item.path.clone(),
1130 target: PathBuf::from(target),
1131 hard: false,
1132 });
1133 }
1134 Kind::HardLink(target) => links.push(Link {
1135 path: item.path.clone(),
1136 target: target.clone(),
1137 hard: true,
1138 }),
1139 Kind::File => {
1140 if let Some(parent) = dest.parent() {
1141 fs::create_dir_all(parent).with_context(what)?;
1142 }
1143 let part = part_path(&dest);
1144 let file = open_part(&dest, &part, done).with_context(what)?;
1145 open = Some(OpenFile {
1146 item,
1147 dest,
1148 part,
1149 file,
1150 written: done,
1151 });
1152 }
1153 }
1154 }
1155 Event::Data(bytes) => {
1156 let f = open
1157 .as_mut()
1158 .ok_or_else(|| anyhow!("the tar stream holds data outside a file"))?;
1159 f.file
1160 .write_all(bytes)
1161 .with_context(|| format!("extracting '{}'", f.item.path.display()))?;
1162 let n = bytes.len() as u64;
1163 f.written += n;
1164 since_point += n;
1165 left = left.saturating_sub(n);
1166 (self.progress.on_bytes)(n);
1167 if punching.is_some()
1171 && since_point >= step
1172 && since_point - checked >= BUF_SIZE as u64
1173 {
1174 checked = since_point;
1175 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1176 if avail < 2 * BUF_SIZE as u64 {
1177 bail!(
1178 "not enough disk space to continue: the compressed data has no \
1179 resume point in the last {}, so its space cannot be released \
1180 yet. {} more is required (the remainder of the archive). \
1181 Progress is saved; free up space and resume the extraction.",
1182 human(since_point),
1183 human(left),
1184 );
1185 }
1186 }
1187 }
1188 Event::FileEnd => {
1189 let f = open
1190 .take()
1191 .ok_or_else(|| anyhow!("the tar stream ends a file it never began"))?;
1192 let pad = f.item.size.next_multiple_of(4096) - f.item.size;
1193 let path = f.item.path.clone();
1194 let parent = f.dest.parent().map(Path::to_path_buf);
1195 f.finish()
1196 .with_context(|| format!("extracting '{}'", path.display()))?;
1197 dirs.extend(parent);
1198 since_point += pad;
1199 left = left.saturating_sub(pad);
1200 }
1201 Event::Point => {
1202 if since_point < step {
1203 continue;
1204 }
1205 let mut point = walk.point()?;
1206 point.unit = unit;
1207 punching = self.solid_point(
1208 point,
1209 open.as_ref(),
1210 &mut links,
1211 &mut dirs,
1212 out,
1213 punching,
1214 &mut punched,
1215 )?;
1216 since_point = 0;
1217 checked = 0;
1218 self.ensure_room(out, "the archive", left, punching)?;
1219 }
1220 Event::End => break,
1221 }
1222 }
1223 if open.is_some() {
1224 bail!("the tar stream ended inside a file");
1225 }
1226 Ok(Some(links))
1227 }
1228
1229 #[allow(clippy::too_many_arguments)]
1232 fn solid_point(
1233 &mut self,
1234 point: Resume,
1235 open: Option<&OpenFile>,
1236 links: &mut Vec<Link>,
1237 dirs: &mut HashSet<PathBuf>,
1238 out: &Path,
1239 punching: Option<u64>,
1240 punched: &mut u64,
1241 ) -> Result<Option<u64>> {
1242 if let Some(f) = open {
1243 f.file
1244 .sync_all()
1245 .context("flushing the extracted file to disk")?;
1246 dirs.extend(f.part.parent().map(Path::to_path_buf));
1247 }
1248 platform::sync_batch(out).context("flushing extracted files to disk")?;
1249 if platform::SYNC_EACH_FILE {
1250 let mut done = HashSet::new();
1253 for d in dirs.drain() {
1254 let mut dir = Some(d.as_path());
1255 while let Some(d) = dir {
1256 if !done.insert(d.to_path_buf()) {
1257 break;
1258 }
1259 fsutil::sync_dir(d)?;
1260 if d == out {
1261 break;
1262 }
1263 dir = d.parent();
1264 }
1265 }
1266 }
1267 dirs.clear();
1268 crash_point("stream-after-sync");
1269
1270 let byte = point.bit / 8;
1271 self.journal.links.append(links);
1272 self.journal.resume = Some(point.clone());
1273 self.journal.save(&self.paths)?;
1274 self.job.resume = Some(point);
1275 crash_point("stream-after-journal");
1276
1277 if punching.is_some() {
1278 if !self
1279 .job
1280 .storage
1281 .punch(*punched, byte)
1282 .context("freeing extracted archive bytes")?
1283 {
1284 return Ok(None);
1285 }
1286 *punched = byte;
1287 (self.progress.on_commit)(self.job.top - byte);
1288 }
1289 crash_point("stream-after-punch");
1290 Ok(punching)
1291 }
1292
1293 fn ensure_room(&self, out: &Path, what: &str, left: u64, punching: Option<u64>) -> Result<()> {
1296 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1297 let left = left.next_multiple_of(4096);
1298 let need = match punching {
1299 Some(granule) => (stream_step() + BUF_SIZE as u64 + 2 * granule).min(left),
1300 None => left,
1301 };
1302 if need > avail {
1303 bail!(
1304 "not enough disk space to continue: the next part of {} requires {} and {} is \
1305 available ({} reserved).\n{} more is required. Progress is saved; free up space \
1306 and resume the extraction.",
1307 what,
1308 human(need),
1309 human(avail),
1310 human(self.keep_free),
1311 human(need - avail),
1312 );
1313 }
1314 Ok(())
1315 }
1316
1317 fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
1320 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1321 let units = &self.job.units;
1322 let need = on_disk;
1323 let first = need(&units[start]);
1324 if first > avail {
1325 let what = match units[start].items.as_slice() {
1328 [one] => format!("'{}'", one.path.display()),
1329 many => format!("the next block of {} files", many.len()),
1330 };
1331 bail!(
1332 "not enough disk space to continue: {what} requires {} and {} is available \
1333 ({} reserved).\n{} more is required. Progress is saved; free up space and \
1334 resume the extraction.",
1335 human(first),
1336 human(avail),
1337 human(self.keep_free),
1338 human(first - avail),
1339 );
1340 }
1341 let budget = avail.min(BATCH_MAX_BYTES.max(first));
1342 let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
1343 let mut used = 0;
1344 let mut end = start;
1345 while end < units.len() && end - start < max_units {
1346 let size = need(&units[end]);
1347 if end > start && used + size > budget {
1348 break;
1349 }
1350 if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
1351 break;
1352 }
1353 used += size;
1354 end += 1;
1355 }
1356 Ok(end)
1357 }
1358
1359 fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
1362 let on_bytes = &*self.progress.on_bytes;
1363 if self.job.format.serial() {
1364 let mut sink = DiskSink {
1365 out,
1366 stop: self.stop,
1367 on_bytes,
1368 buf: vec![0; BUF_SIZE],
1369 links: Vec::new(),
1370 };
1371 let mut worker = self
1372 .job
1373 .format
1374 .worker(1)
1375 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1376 for unit in batch.iter().rev() {
1378 match worker.extract(unit, &mut sink) {
1379 Ok(()) => {}
1380 Err(e) if is_interrupt(&e) => return Ok(None),
1381 Err(e) => return Err(e),
1382 }
1383 }
1384 return Ok(Some(sink.links));
1385 }
1386 let threads = threads_per_unit(batch.len());
1387 let results: Vec<Result<Vec<Link>>> = batch
1388 .par_iter()
1389 .map_init(
1390 || {
1391 let sink = DiskSink {
1392 out,
1393 stop: self.stop,
1394 on_bytes,
1395 buf: vec![0; BUF_SIZE],
1396 links: Vec::new(),
1397 };
1398 (self.job.format.worker(threads), sink)
1399 },
1400 |(worker, sink), unit| {
1401 let w = worker
1402 .as_mut()
1403 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1404 w.extract(unit, sink)?;
1405 Ok(std::mem::take(&mut sink.links))
1406 },
1407 )
1408 .collect();
1409
1410 let mut links = Vec::new();
1411 let mut interrupted = false;
1412 for r in results {
1413 match r {
1414 Ok(l) => links.extend(l),
1415 Err(e) if is_interrupt(&e) => interrupted = true,
1416 Err(e) => return Err(e),
1417 }
1418 }
1419 Ok((!interrupted).then_some(links))
1420 }
1421
1422 fn finish(self, out: &Path) -> Result<()> {
1423 make_final_links(&self.journal.links, out)?;
1424 if self.journal.keep {
1425 return self.paths.remove();
1427 }
1428 let Self { job, paths, .. } = self;
1429 let Job {
1430 storage, format, ..
1431 } = job;
1432 drop(format);
1434 let storage = Arc::try_unwrap(storage)
1435 .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
1436 storage.remove()?;
1439 paths.remove()
1440 }
1441}
1442
1443pub fn finish_orphaned(journal: &Journal, paths: &Paths) -> Result<()> {
1446 make_final_links(&journal.links, &journal.output)?;
1447 paths.remove()
1448}
1449
1450fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
1455 make_links(links, out).map_err(|e| {
1456 anyhow!(
1457 "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
1458 each one, for example by moving or renaming a folder that is in the way, then \
1459 resume the extraction to create them"
1460 )
1461 })
1462}
1463
1464pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
1468 let failed: Vec<(&Link, anyhow::Error)> = links
1469 .iter()
1470 .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
1471 .collect();
1472 if failed.is_empty() {
1473 return Ok(());
1474 }
1475 let mut msg = match failed.len() {
1476 1 => "1 link could not be created:".to_string(),
1477 n => format!("{n} links could not be created:"),
1478 };
1479 for (link, e) in failed.iter().take(10) {
1480 let kind = if link.hard {
1481 "hard link"
1482 } else {
1483 "symbolic link"
1484 };
1485 msg.push_str(&format!(
1486 "\n '{}' ({kind} to '{}'): {e:#}",
1487 link.path.display(),
1488 link.target.display()
1489 ));
1490 }
1491 if failed.len() > 10 {
1492 msg.push_str(&format!("\n and {} more", failed.len() - 10));
1493 }
1494 Err(anyhow!(msg))
1495}
1496
1497fn make_link(link: &Link, out: &Path) -> Result<()> {
1498 if let Some(via) = link_on_the_way(out, &link.path) {
1501 bail!(
1502 "'{}' is a link, and this one would be created through it",
1503 via.display()
1504 );
1505 }
1506 let path = out.join(&link.path);
1507 if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
1508 bail!("a folder already exists at this location");
1509 }
1510 if let Some(parent) = path.parent() {
1511 fs::create_dir_all(parent)?;
1512 }
1513 if link.hard {
1514 if let Some(via) = link_on_the_way(out, &link.target) {
1515 bail!(
1516 "'{}' is a link, and the target would be reached through it",
1517 via.display()
1518 );
1519 }
1520 let target = out.join(&link.target);
1521 let _ = fs::remove_file(&path);
1522 fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
1524 } else {
1525 platform::create_symlink(&path, &link.target)?;
1526 }
1527 Ok(())
1528}
1529
1530fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
1532 let mut ancestors: Vec<&Path> = rel
1533 .ancestors()
1534 .skip(1)
1535 .filter(|p| !p.as_os_str().is_empty())
1536 .collect();
1537 ancestors.reverse();
1538 ancestors
1539 .into_iter()
1540 .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
1541 .map(Path::to_path_buf)
1542}
1543
1544struct DiskSink<'a> {
1545 out: &'a Path,
1546 stop: &'a AtomicBool,
1547 on_bytes: &'a (dyn Fn(u64) + Sync),
1548 buf: Vec<u8>,
1549 links: Vec<Link>,
1550}
1551
1552impl Sink for DiskSink<'_> {
1553 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1554 self.write(item, data)
1555 .with_context(|| format!("extracting '{}'", item.path.display()))
1556 }
1557}
1558
1559impl DiskSink<'_> {
1560 fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1561 let dest = self.out.join(&item.path);
1562 match &item.kind {
1563 Kind::Dir => {
1564 fs::create_dir_all(&dest)?;
1565 return Ok(());
1566 }
1567 Kind::Symlink => {
1568 let mut target = Vec::new();
1569 data.take(MAX_SYMLINK).read_to_end(&mut target)?;
1570 let target = PathBuf::from(String::from_utf8(target)?);
1571 self.links.push(Link {
1572 path: item.path.clone(),
1573 target,
1574 hard: false,
1575 });
1576 return Ok(());
1577 }
1578 Kind::HardLink(target) => {
1579 self.links.push(Link {
1580 path: item.path.clone(),
1581 target: target.clone(),
1582 hard: true,
1583 });
1584 return Ok(());
1585 }
1586 Kind::File => {}
1587 }
1588
1589 if let Some(parent) = dest.parent() {
1590 fs::create_dir_all(parent)?;
1591 }
1592 let part = part_path(&dest);
1593 let result = self.copy(item, data, &part);
1594 if result.is_err() {
1595 let _ = fs::remove_file(&part);
1596 return result;
1597 }
1598 fs::rename(&part, &dest)?;
1599 Ok(())
1600 }
1601
1602 fn copy(&mut self, item: &Item, data: &mut dyn Read, part: &Path) -> Result<()> {
1603 let mut dst = File::create(part)?;
1604 let mut written = 0u64;
1605 loop {
1606 if self.stop.load(Ordering::Relaxed) {
1607 return Err(io::Error::from(io::ErrorKind::Interrupted).into());
1608 }
1609 let n = data.read(&mut self.buf)?;
1612 if n == 0 {
1613 break;
1614 }
1615 written += n as u64;
1616 if written > item.size {
1617 bail!("it is larger than the archive records");
1618 }
1619 dst.write_all(&self.buf[..n])?;
1620 (self.on_bytes)(n as u64);
1621 }
1622 if written != item.size {
1623 bail!("it is smaller than the archive records");
1624 }
1625 if let Some(t) = item.mtime {
1626 dst.set_modified(t)?;
1627 }
1628 platform::apply_mode(&dst, item.mode)?;
1629 if platform::SYNC_EACH_FILE {
1630 dst.sync_all()?;
1631 }
1632 Ok(())
1633 }
1634}
1635
1636struct ProbeSink {
1638 left: u64,
1639 buf: Vec<u8>,
1640}
1641
1642#[derive(Debug)]
1643struct ProbeDone;
1644
1645impl std::fmt::Display for ProbeDone {
1646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1647 f.write_str("read enough to prove the password")
1648 }
1649}
1650
1651impl std::error::Error for ProbeDone {}
1652
1653impl Sink for ProbeSink {
1654 fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
1655 loop {
1656 let n = data.read(&mut self.buf)?;
1657 if n == 0 {
1658 return Ok(());
1659 }
1660 self.left = self.left.saturating_sub(n as u64);
1661 if self.left == 0 {
1662 return Err(ProbeDone.into());
1663 }
1664 }
1665 }
1666}
1667
1668struct VerifySink<'a> {
1669 on_bytes: &'a (dyn Fn(u64) + Sync),
1670 buf: Vec<u8>,
1671}
1672
1673impl Sink for VerifySink<'_> {
1674 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1675 let mut read = 0;
1676 loop {
1677 let n = data
1678 .read(&mut self.buf)
1679 .with_context(|| format!("'{}'", item.path.display()))?;
1680 if n == 0 {
1681 break;
1682 }
1683 read += n as u64;
1684 (self.on_bytes)(n as u64);
1685 }
1686 if item.kind == Kind::File && read != item.size {
1687 bail!(
1688 "'{}' is shorter than the archive records",
1689 item.path.display()
1690 );
1691 }
1692 Ok(())
1693 }
1694}
1695
1696fn is_interrupt(e: &anyhow::Error) -> bool {
1697 e.chain()
1698 .filter_map(|c| c.downcast_ref::<io::Error>())
1699 .any(|io| io.kind() == io::ErrorKind::Interrupted)
1700}
1701
1702fn test_knob(name: &str) -> Option<u32> {
1704 if !cfg!(debug_assertions) {
1705 return None;
1706 }
1707 std::env::var(name).ok()?.parse().ok()
1708}
1709
1710pub(crate) fn crash_point(name: &str) {
1713 if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
1714 return;
1715 }
1716 static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1717 if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
1718 std::process::abort();
1719 }
1720}
1721
1722pub fn human(bytes: u64) -> String {
1723 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
1724 let mut v = bytes as f64;
1725 let mut unit = 0;
1726 while v >= 1000.0 && unit < UNITS.len() - 1 {
1727 v /= 1000.0;
1728 unit += 1;
1729 }
1730 if unit == 0 {
1731 format!("{bytes} B")
1732 } else {
1733 format!("{v:.1} {}", UNITS[unit])
1734 }
1735}