1use std::collections::{BTreeMap, HashMap, HashSet};
37use std::fs::{self, File};
38use std::io::{self, Read, Seek, SeekFrom, Write};
39use std::path::{Component, Path, PathBuf};
40use std::sync::atomic::{AtomicBool, Ordering};
41use std::sync::{Arc, OnceLock};
42
43use anyhow::{Context, Result, anyhow, bail};
44use rayon::prelude::*;
45
46use crate::archive::resumable::{self, Decoder};
47use crate::archive::storage::{Reads, Storage, Tail};
48use crate::archive::targz::{Event, Profile};
49use crate::archive::{
50 self, Codec, Format, Item, Kind, PasswordCheck, Sink, SolidWalker, Stream, Unit,
51};
52use crate::journal::{Journal, Link, Paths, Resume, TarAt};
53use crate::{folders, fsutil, platform, replace};
54
55const BATCH_MAX_UNITS: usize = 512;
58const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
59const BUF_SIZE: usize = 1024 * 1024;
60const MAX_SYMLINK: u64 = 64 * 1024;
61
62const STREAM_STEP: u64 = 256 * 1024 * 1024;
66
67fn stream_step() -> u64 {
68 test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
69}
70
71fn stream_threshold() -> u64 {
74 2 * stream_step()
75}
76
77fn always_stream() -> bool {
80 test_knob("HATCHZIP_STREAM_STEP").is_some()
81}
82
83const MAX_TOTAL_SIZE: u64 = 1 << 62;
86
87fn max_tail() -> u64 {
90 test_knob("HATCHZIP_MAX_TAIL").map_or(1_000_000_000, u64::from)
91}
92
93fn on_disk(u: &Unit) -> u64 {
94 u.items.iter().fold(0u64, |sum, i| {
95 let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
96 sum.saturating_add(size)
97 })
98}
99
100pub struct Job {
101 pub storage: Arc<Storage>,
102 pub format_name: &'static str,
103 format: Box<dyn Format>,
104 pub units: Vec<Unit>,
106 pub tail_start: u64,
107 pub top: u64,
110 punch: OnceLock<Option<Punch>>,
113 resume: Option<Resume>,
115 started: bool,
119 case_clashes: Box<CaseClashes>,
125 only: Option<Only>,
127}
128
129struct Only {
132 paths: Vec<PathBuf>,
135 whole: HashMap<u64, Unit>,
138}
139
140pub fn picks(only: &[PathBuf], path: &Path) -> bool {
142 only.iter().any(|p| path.starts_with(p))
143}
144
145pub fn selection_path(given: &Path) -> Result<PathBuf> {
148 let mut path = PathBuf::new();
149 for c in given.components() {
150 match c {
151 Component::Normal(n) => path.push(n),
152 Component::CurDir => {}
153 _ => bail!(
154 "'{}' is not a path inside the archive. Give it as the archive lists it, such as \
155 docs/readme.txt. Nothing was modified",
156 given.display()
157 ),
158 }
159 }
160 if path.as_os_str().is_empty() {
161 bail!(
162 "'{}' names no entry. Give a path as the archive lists it, such as docs/readme.txt. \
163 Nothing was modified",
164 given.display()
165 );
166 }
167 Ok(path)
168}
169
170const MAX_CASE_FOLDERS: usize = 1000;
174
175#[derive(Default)]
177struct CaseClashes {
178 met_in: BTreeMap<PathBuf, (PathBuf, PathBuf)>,
181 beyond_ascii: Option<(PathBuf, PathBuf)>,
184 recorded: Vec<PathBuf>,
186 recorded_beyond_ascii: bool,
187}
188
189impl CaseClashes {
190 fn of(names: &[(String, &Path, bool)]) -> Self {
193 let mut clashes = Self::default();
194 for group in names.chunk_by(|a, b| a.0 == b.0) {
195 if !group.iter().any(|n| n.2) {
197 continue;
198 }
199 let mut previous_file = None;
203 for (_, path, is_file) in group {
204 if let Some(file) = previous_file {
205 clashes.add_pair(file, path);
206 }
207 if *is_file {
208 previous_file = Some(*path);
209 }
210 }
211 let mut next_file = None;
212 for (_, path, is_file) in group.iter().rev() {
213 if *is_file {
214 next_file = Some(*path);
215 } else if let Some(file) = next_file {
216 clashes.add_pair(path, file);
217 }
218 }
219 }
220 clashes
221 }
222
223 fn add_pair(&mut self, a: &Path, b: &Path) {
224 self.met_in
225 .entry(meeting_folder(a, b))
226 .or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
227 if !(a.to_string_lossy().is_ascii() && b.to_string_lossy().is_ascii()) {
228 self.beyond_ascii
229 .get_or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
230 }
231 }
232}
233
234fn meeting_folder(a: &Path, b: &Path) -> PathBuf {
238 a.components()
239 .zip(b.components())
240 .take_while(|(x, y)| x == y)
241 .map(|(x, _)| x)
242 .collect()
243}
244
245pub(crate) fn keeps_case_apart(dir: &Path) -> bool {
249 let at = std::env::var_os("HATCHZIP_IGNORE_CASE_AT").filter(|_| cfg!(debug_assertions));
250 test_knob("HATCHZIP_IGNORE_CASE").is_none()
251 && at.is_none_or(|at| Path::new(&at) != dir)
252 && platform::case_sensitive(dir)
253}
254
255fn normalizes_names() -> bool {
258 platform::NORMALIZES_NAMES || test_knob("HATCHZIP_NORMALIZE_NAMES").is_some()
259}
260
261pub(crate) fn check_case_record(out: &Path, folders: &[PathBuf], beyond_ascii: bool) -> Result<()> {
267 if beyond_ascii && normalizes_names() {
268 bail!(
269 "this extraction has names that differ only in case with characters outside ASCII, \
270 which this system may treat as one file, so going on here could lose files. Go on \
271 where it started"
272 );
273 }
274 let folders = folders.iter().map(PathBuf::as_path);
275 if let Some((_, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
276 bail!(
277 "this extraction has names that differ only in case, and {} is not known to keep \
278 such names apart, so going on here could lose files. Move the output folder back \
279 to a case-sensitive filesystem and run the command again",
280 nearest.display()
281 );
282 }
283 Ok(())
284}
285
286fn first_not_apart<'a>(
290 out: &Path,
291 folders: impl IntoIterator<Item = &'a Path>,
292 apart: impl Fn(&Path) -> bool,
293) -> Option<(&'a Path, PathBuf)> {
294 let mut known = HashMap::new();
295 for folder in folders {
296 let nearest = if folder.as_os_str().is_empty() {
297 fsutil::existing_ancestor(out)
298 } else {
299 fsutil::existing_ancestor(&out.join(folder))
300 };
301 let ok = match known.get(&nearest) {
302 Some(ok) => *ok,
303 None => {
304 let ok = apart(&nearest);
305 known.insert(nearest.clone(), ok);
306 ok
307 }
308 };
309 if !ok {
310 return Some((folder, nearest));
311 }
312 }
313 None
314}
315
316#[derive(Clone, Copy, Debug)]
322pub struct Punch {
323 pub margin: u64,
324 pub overlap: u64,
325}
326
327impl Job {
328 pub fn open(
332 path: &Path,
333 writable: bool,
334 password: Option<&str>,
335 reads: Arc<Reads>,
336 ) -> Result<Self> {
337 let mut job = Self::open_as_is(path, writable, password, reads)?;
338 job.case_clashes = Box::new(job.check_layout()?);
339 Ok(job)
340 }
341
342 pub(crate) fn open_as_is(
347 path: &Path,
348 writable: bool,
349 password: Option<&str>,
350 reads: Arc<Reads>,
351 ) -> Result<Self> {
352 let mut storage = Storage::open(path, writable)?;
353 storage.count_reads(reads);
354 let storage = Arc::new(storage);
355 let opened = archive::open(&storage, None, password)?;
356 let top = storage.original_len();
357 if top.saturating_sub(opened.tail_start) > max_tail() {
361 bail!(
362 "this archive holds more than {} after its last entry, which HatchZip would \
363 have to keep in memory for the whole extraction. The archive was not modified",
364 human(max_tail())
365 );
366 }
367 Self::build(storage, opened, top)
368 }
369
370 pub fn resume(
374 journal: &Journal,
375 tail: Arc<Tail>,
376 writable: bool,
377 password: Option<&str>,
378 reads: Arc<Reads>,
379 ) -> Result<Self> {
380 let mut storage = Storage::from_parts(&journal.parts, writable)?;
381 storage.count_reads(reads);
382 let storage = Arc::new(storage);
383 let current = storage.current_len()?;
384 if journal.keep {
385 storage.protect();
388 if current != storage.original_len() {
389 bail!(
390 "{} has changed since the extraction started. Put the original archive back \
391 to resume, or run restore to discard the progress",
392 storage.primary().display()
393 );
394 }
395 }
396 if current < journal.committed_len {
397 bail!(
398 "{} is shorter than HatchZip left it and will not be modified",
399 storage.primary().display()
400 );
401 }
402 let point = journal.resume.as_ref();
403 let opened = archive::open(&storage, Some((&journal.format, tail, point)), password)?;
404 let mut job = Self::build(storage, opened, journal.committed_len)?;
405 if let Some(only) = &journal.only {
406 if journal.resume.is_some() {
408 bail!(
409 "the journal of {} records a partially extracted file in an extraction of \
410 selected entries, which never has one. The archive will not be modified",
411 job.storage.primary().display()
412 );
413 }
414 job.restrict(only.clone());
415 }
416 job.started = journal.replace.as_ref().is_none_or(|r| r.moved);
417 job.case_clashes.recorded.clone_from(&journal.case_folders);
418 job.case_clashes.recorded_beyond_ascii = journal.case_beyond_ascii;
419 if let Some(r) = &journal.resume {
420 if job.units.first().map(|u| u.start) != Some(r.unit) {
423 bail!(
424 "the journal of {} records a partially extracted file that is not the next one \
425 in the archive. The archive will not be modified",
426 job.storage.primary().display()
427 );
428 }
429 job.resume = Some(r.clone());
430 }
431 if current > journal.committed_len && writable && !journal.keep {
435 job.storage.set_len(journal.committed_len)?;
436 }
437 Ok(job)
438 }
439
440 fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
441 let mut units = opened.units;
442 let len = storage.original_len();
446 if opened.tail_start > len || units.iter().any(|u| u.start >= len) {
447 return Err(archive::Damaged(anyhow!(
448 "this archive records data past the end of the file, so it is damaged or \
449 incomplete. Nothing was modified"
450 ))
451 .into());
452 }
453 units.retain(|u| u.start < top);
454 units.sort_by_key(|u| std::cmp::Reverse(u.start));
455 if units.windows(2).any(|w| w[0].start == w[1].start) {
459 bail!(
460 "two parts of this archive start at the same offset, so extracting it in place \
461 could destroy data before it is extracted; extraction refused"
462 );
463 }
464 let total = units
465 .iter()
466 .flat_map(|u| &u.items)
467 .try_fold(0u64, |sum, i| sum.checked_add(i.size));
468 if total.is_none_or(|t| t > MAX_TOTAL_SIZE) {
469 return Err(archive::Damaged(anyhow!(
470 "the file sizes recorded in this archive add up to more than any disk can hold, \
471 so the archive is damaged. Nothing was modified"
472 ))
473 .into());
474 }
475
476 let mut seen = HashSet::new();
477 for item in units.iter().flat_map(|u| &u.items) {
478 for part in item.path.iter() {
479 if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
480 bail!(
481 "'{}' cannot be created at this location: {why}. The archive was not modified",
482 item.path.display()
483 );
484 }
485 }
486 if item.kind != Kind::Dir && !seen.insert(item.path.as_path()) {
487 bail!(
488 "'{}' appears more than once in the archive; extraction refused",
489 item.path.display()
490 );
491 }
492 }
493 Ok(Self {
494 storage,
495 format_name: opened.name,
496 format: opened.format,
497 units,
498 tail_start: opened.tail_start,
499 top,
500 punch: OnceLock::new(),
501 resume: None,
502 started: false,
503 case_clashes: Box::default(),
504 only: None,
505 })
506 }
507
508 pub fn select(&mut self, given: &[PathBuf]) -> Result<()> {
519 if self.only.is_some() {
520 bail!("the entries to extract were already chosen");
521 }
522 if given.is_empty() {
523 bail!("no entries were selected. Nothing was modified");
524 }
525 let mut paths: Vec<PathBuf> = Vec::new();
526 for g in given {
527 let p = selection_path(g)?;
528 if !paths.contains(&p) {
529 paths.push(p);
530 }
531 }
532 let items = || self.units.iter().flat_map(|u| &u.items);
533 for p in &paths {
534 if !items().any(|i| i.path.starts_with(p)) {
535 bail!(
536 "'{}' is not in the archive. Run `hatchzip list` on it to see its paths, and \
537 give one as listed. Nothing was modified",
538 p.display()
539 );
540 }
541 }
542 let targets: Vec<PathBuf> = items()
543 .filter(|i| picks(&paths, &i.path))
544 .filter_map(|i| match &i.kind {
545 Kind::HardLink(t) if !picks(&paths, t) => Some(t.clone()),
546 _ => None,
547 })
548 .collect();
549 for t in targets {
550 if !paths.contains(&t) {
551 paths.push(t);
552 }
553 }
554 self.restrict(paths);
555 Ok(())
556 }
557
558 fn restrict(&mut self, paths: Vec<PathBuf>) {
561 let mut whole = HashMap::new();
562 self.units.retain_mut(|u| {
563 let picked = u.items.iter().filter(|i| picks(&paths, &i.path)).count();
564 if picked == 0 {
565 return false;
566 }
567 if picked < u.items.len() {
568 whole.insert(u.start, u.clone());
569 u.items.retain(|i| picks(&paths, &i.path));
570 }
571 true
572 });
573 self.only = Some(Only { paths, whole });
574 }
575
576 pub fn selection(&self) -> Option<&[PathBuf]> {
579 self.only.as_ref().map(|o| o.paths.as_slice())
580 }
581
582 fn decodable<'a>(&'a self, unit: &'a Unit) -> &'a Unit {
585 self.only
586 .as_ref()
587 .and_then(|o| o.whole.get(&unit.start))
588 .unwrap_or(unit)
589 }
590
591 pub(crate) fn check_case(&self, out: &Path) -> Result<()> {
595 let clashes = &self.case_clashes;
596 check_case_record(out, &clashes.recorded, clashes.recorded_beyond_ascii)?;
597 if let Some((a, b)) = clashes.beyond_ascii.as_ref().filter(|_| normalizes_names()) {
598 bail!(
599 "'{}' and '{}' differ only in case, and with characters outside ASCII this \
600 system may treat them as one file on any volume; extraction refused. Extract \
601 this archive with another program",
602 a.display(),
603 b.display()
604 );
605 }
606 let met_in = &clashes.met_in;
607 if met_in.len() > MAX_CASE_FOLDERS {
608 bail!(
609 "this archive has names that differ only in case in {} folders, more than \
610 HatchZip can keep track of; extraction refused. Extract this archive with \
611 another program",
612 met_in.len()
613 );
614 }
615 let folders = met_in.keys().map(PathBuf::as_path);
616 if let Some((met, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
617 let (a, b) = &met_in[met];
618 bail!(
619 "'{}' and '{}' differ only in case, and {} is not known to keep such names \
620 apart; extraction refused. Extract to a folder on a case-sensitive filesystem, \
621 or with another program",
622 a.display(),
623 b.display(),
624 nearest.display()
625 );
626 }
627 Ok(())
628 }
629
630 pub(crate) fn case_folders(&self) -> Vec<PathBuf> {
632 self.case_clashes.met_in.keys().cloned().collect()
633 }
634
635 pub(crate) fn case_beyond_ascii(&self) -> bool {
636 self.case_clashes.beyond_ascii.is_some()
637 }
638
639 fn check_layout(&self) -> Result<CaseClashes> {
653 let key = |p: &Path| crate::fsutil::fold_name(&p.to_string_lossy());
654 let items = || self.units.iter().flat_map(|u| &u.items);
655 if let Some(item) = items().find(|i| {
659 i.path
660 .iter()
661 .any(|c| c.to_string_lossy().to_lowercase().ends_with(PART_SUFFIX))
662 }) {
663 bail!(
664 "'{}' uses a name ending in {PART_SUFFIX}, which HatchZip gives a file while it \
665 writes it, so extraction is refused. Extract this archive with another program. \
666 Nothing was modified",
667 item.path.display()
668 );
669 }
670 if let Some((item, suffix)) = items().find_map(|i| {
675 i.path.iter().find_map(|c| {
676 let name = c.to_string_lossy().to_lowercase();
677 PROGRESS_SUFFIXES
678 .into_iter()
679 .find(|s| name.ends_with(*s))
680 .map(|s| (i, s))
681 })
682 }) {
683 bail!(
684 "'{}' uses a name ending in {suffix}, which HatchZip gives the progress files of \
685 an extraction, so extraction is refused. Extract this archive with another \
686 program. Nothing was modified",
687 item.path.display()
688 );
689 }
690 let mut folders: HashMap<&Path, Option<&Path>> = HashMap::new();
693 for item in items() {
694 if item.kind == Kind::Dir {
695 folders.insert(&item.path, None);
696 }
697 for parent in item.path.ancestors().skip(1) {
698 if parent.as_os_str().is_empty() {
699 break;
700 }
701 folders.entry(parent).or_insert(Some(&item.path));
702 }
703 }
704 let files: HashSet<&Path> = items()
705 .filter(|i| i.kind == Kind::File)
706 .map(|i| i.path.as_path())
707 .collect();
708 for item in items() {
709 let what = match &item.kind {
710 Kind::Dir => continue,
711 Kind::File => "a file",
712 Kind::Symlink => "a symbolic link",
713 Kind::HardLink(_) => "a hard link",
714 };
715 match folders.get(item.path.as_path()) {
716 Some(None) => bail!(
717 "'{}' is both {what} and a folder in the archive; extraction refused",
718 item.path.display()
719 ),
720 Some(Some(inside)) => bail!(
721 "'{}' is {what}, but '{}' requires a folder at that location; extraction \
722 refused",
723 item.path.display(),
724 inside.display()
725 ),
726 None => {}
727 }
728 if let Kind::HardLink(target) = &item.kind
729 && !files.contains(target.as_path())
730 {
731 bail!(
732 "hard link '{}' points to '{}', which is not a file in the archive; \
733 extraction refused",
734 item.path.display(),
735 target.display()
736 );
737 }
738 }
739 let mut names: Vec<(String, &Path, bool)> = items()
740 .filter(|i| i.kind != Kind::Dir)
741 .map(|i| (key(&i.path), i.path.as_path(), true))
742 .chain(folders.keys().map(|f| (key(f), *f, false)))
743 .collect();
744 names.sort_unstable();
745 Ok(CaseClashes::of(&names))
746 }
747
748 pub fn punch_support(&self) -> Option<Punch> {
752 *self.punch.get_or_init(|| {
753 if test_knob("HATCHZIP_NO_PUNCH").is_some() {
754 return None;
755 }
756 let dir = match self.storage.primary().parent() {
757 Some(d) if !d.as_os_str().is_empty() => d,
758 _ => Path::new("."),
759 };
760 fsutil::can_punch(dir).then(|| Punch {
761 margin: platform::punch_margin(dir),
762 overlap: platform::punch_overlap(dir),
763 })
764 })
765 }
766
767 pub fn encrypted(&self) -> bool {
768 self.units.iter().any(|u| u.encrypted)
769 }
770
771 pub fn is_stream(&self) -> bool {
773 self.format.solid().is_some()
774 }
775
776 pub fn kept_whole(&self, reclaims: bool) -> bool {
780 self.is_stream() && reclaims && self.punch_support().is_none()
781 }
782
783 pub fn check_password(&self) -> Result<()> {
788 const ENOUGH: u64 = 64 * 1024 * 1024;
789 let Some(unit) = self.smallest_encrypted() else {
790 return Ok(());
791 };
792 let left = match self.format.password_check() {
793 PasswordCheck::Headers => return self.format.prove_password(),
794 PasswordCheck::Sample => ENOUGH,
795 PasswordCheck::WholeUnit => u64::MAX,
799 };
800 let mut worker = self.format.worker(1)?;
801 let mut sink = ProbeSink {
802 left,
803 buf: vec![0; BUF_SIZE],
804 };
805 match worker.extract(self.decodable(unit), &mut sink) {
806 Ok(()) => Ok(()),
807 Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
808 Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
809 Err(_) => Err(archive::WrongPassword.into()),
810 }
811 }
812
813 fn smallest_encrypted(&self) -> Option<&Unit> {
816 self.units
817 .iter()
818 .filter(|u| u.encrypted)
819 .min_by_key(|u| (u.size() == 0, u.size()))
820 }
821
822 pub fn slow_password_check(&self) -> Option<(&Path, u64)> {
826 if !self.encrypted() || self.format.password_check() != PasswordCheck::WholeUnit {
827 return None;
828 }
829 let unit = self.smallest_encrypted()?;
830 Some((unit.items.first()?.path.as_path(), unit.size()))
831 }
832
833 pub fn in_place_refusal(&self) -> Option<String> {
836 self.format.refuses_in_place().or_else(|| {
837 self.storage.hard_linked().map(|path| {
838 format!(
839 "{} has another hard link, which extracting in place would empty as well",
840 path.display()
841 )
842 })
843 })
844 }
845
846 pub fn item_count(&self) -> usize {
847 self.units.iter().map(|u| u.items.len()).sum()
848 }
849
850 pub fn remaining_size(&self) -> u64 {
851 let done = self.resume.as_ref().map_or(0, |r| r.written);
852 self.units
853 .iter()
854 .fold(0u64, |sum, u| sum.saturating_add(u.size()))
855 .saturating_sub(done)
856 }
857
858 fn resumed(&self, i: usize) -> Option<&Resume> {
860 self.resume
861 .as_ref()
862 .filter(|r| r.unit == self.units[i].start)
863 }
864
865 fn stream_of(&self, i: usize) -> Option<Stream> {
868 let unit = &self.units[i];
869 match unit.items.as_slice() {
870 [item] if item.kind == Kind::File && !unit.encrypted => {
871 self.format.stream(unit).ok().flatten()
872 }
873 _ => None,
874 }
875 }
876
877 fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
881 if self.resumed(i).is_some() {
882 return self.stream_of(i);
883 }
884 if !reclaims || self.units[i].size() < stream_threshold() {
885 return None;
886 }
887 self.punch_support()?;
888 self.stream_of(i)
889 }
890
891 fn span(&self, i: usize) -> u64 {
894 let end = if i == 0 {
895 self.top
896 } else {
897 self.units[i - 1].start
898 };
899 end - self.units[i].start
900 }
901
902 pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
908 let tail = self.storage.original_len().saturating_sub(self.tail_start) as i128;
909 let mut extra: i128 = if fresh { tail } else { 0 };
910 let mut peak = extra;
911 for (i, u) in self.units.iter().enumerate() {
912 let span = self.span(i) as i128;
913 if let Some(solid) = self.format.solid() {
914 let (rise, net) = self.solid_cost(i, solid.profile(), span, reclaims);
915 peak = peak.max(extra + rise);
916 extra += net;
917 continue;
918 }
919 if let Some(s) = self.streams(i, reclaims) {
920 let (rise, net) = self.stream_cost(i, &s, span, reclaims);
921 peak = peak.max(extra + rise);
922 extra += net;
923 continue;
924 }
925 let on_disk = on_disk(u) as i128;
926 peak = peak.max(extra + on_disk);
927 extra += on_disk;
928 if reclaims {
929 extra -= span;
930 }
931 }
932 if reclaims {
933 let stub = self.units.last().map_or(self.top, |u| u.start);
936 extra -= stub as i128 + tail;
937 }
938 (peak.max(0) as u64, extra)
939 }
940
941 fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
956 let at = self.resumed(i);
957 let done = at.map_or(0, |r| r.written / 4096 * 4096);
960 let out_left = on_disk(&self.units[i]).saturating_sub(done) as i128;
961 let read_to = at.map_or(s.data_start, |r| r.bit / 8);
962 let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
963 let freed = read_to.saturating_sub(s.data_start) as i128;
967 let net = if reclaims {
968 out_left - (span - freed)
969 } else {
970 out_left
971 };
972 let rise = match self.punch_support() {
973 Some(punch) if reclaims => {
974 let slack = match s.codec {
975 Codec::Stored => 0,
976 Codec::Deflate => out_left / 1024,
977 };
978 let step = (stream_step() + BUF_SIZE as u64 + 2 * punch.margin) as i128;
979 ((out_left - data_left).max(0) + slack + step).min(out_left)
980 }
981 _ => out_left,
982 };
983 (rise, net)
984 }
985
986 fn solid_cost(&self, i: usize, p: &Profile, span: i128, reclaims: bool) -> (i128, i128) {
997 let out_left = match self.only {
999 Some(_) => on_disk(&self.units[i]),
1000 None => p.files + p.links,
1001 } as i128;
1002 let freed = self.resumed(i).map_or(0, |r| r.bit / 8) as i128;
1004 let net = if reclaims {
1005 out_left - (span - freed)
1006 } else {
1007 out_left
1008 };
1009 let rise = match self.punch_support() {
1010 Some(punch) if reclaims => {
1011 let ahead = stream_step() + p.gap + BUF_SIZE as u64 + 2 * punch.margin;
1012 (p.lead.max(0) + ahead as i128).min(p.files as i128)
1013 }
1014 _ => out_left,
1017 };
1018 (rise.max(net), net)
1019 }
1020
1021 fn open_entry(&self) -> Option<&Item> {
1024 let r = self.resume.as_ref()?;
1025 let inside = match &r.stream {
1026 Some(s) => matches!(s.at, TarAt::File { .. }),
1027 None => true,
1028 };
1029 if !inside {
1030 return None;
1031 }
1032 self.units.first().and_then(|u| u.items.first())
1033 }
1034
1035 pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
1043 self.uncommitted_files(out, true)
1044 }
1045
1046 pub(crate) fn discarded_output(&self, out: &Path) -> Vec<(PathBuf, u64)> {
1050 self.uncommitted_files(out, false)
1051 }
1052
1053 fn uncommitted_files(&self, out: &Path, preserve_open: bool) -> Vec<(PathBuf, u64)> {
1054 if !self.started {
1055 return Vec::new();
1056 }
1057 let open = preserve_open && self.open_entry().is_some();
1058 let mut found = Vec::new();
1059 for (i, u) in self.units.iter().enumerate() {
1060 for (k, item) in u.items.iter().enumerate() {
1061 if item.kind != Kind::File || (open && i == 0 && k == 0) {
1062 continue;
1063 }
1064 let dest = out.join(&item.path);
1065 for p in [part_path(&dest), dest] {
1066 if let Ok(m) = fs::symlink_metadata(&p)
1067 && m.is_file()
1068 {
1069 found.push((p, m.len().next_multiple_of(4096)));
1070 }
1071 }
1072 }
1073 }
1074 found
1075 }
1076
1077 pub fn past_resume_point(&self, out: &Path) -> u64 {
1080 let (Some(r), Some(item)) = (self.resume.as_ref(), self.open_entry()) else {
1081 return 0;
1082 };
1083 let dest = out.join(&item.path);
1084 [part_path(&dest), dest]
1085 .iter()
1086 .find_map(|p| fs::metadata(p).ok())
1087 .map_or(0, |m| {
1088 (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
1089 })
1090 }
1091
1092 pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
1095 let failures = if self.format.serial() {
1096 self.verify_serial(on_bytes)?
1097 } else {
1098 self.verify_parallel(on_bytes)
1099 };
1100 if failures.is_empty() {
1101 return Ok(());
1102 }
1103 let mut msg = format!("{} damaged:", failures.len());
1104 for f in failures.iter().take(10) {
1105 msg.push_str("\n ");
1106 msg.push_str(f);
1107 }
1108 Err(anyhow!(msg))
1109 }
1110
1111 fn verify_serial(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<Vec<String>> {
1113 let mut worker = self.format.worker(1)?;
1114 let mut sink = VerifySink {
1115 on_bytes,
1116 buf: vec![0; BUF_SIZE],
1117 };
1118 Ok(self
1119 .units
1120 .iter()
1121 .rev()
1122 .filter_map(|u| worker.extract(self.decodable(u), &mut sink).err())
1123 .map(|e| format!("{e:#}"))
1124 .collect())
1125 }
1126
1127 fn verify_parallel(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Vec<String> {
1128 let threads = threads_per_unit(self.units.len());
1129 self.units
1130 .par_iter()
1131 .map_init(
1132 || {
1133 (
1134 self.format.worker(threads),
1135 VerifySink {
1136 on_bytes,
1137 buf: vec![0; BUF_SIZE],
1138 },
1139 )
1140 },
1141 |(worker, sink), unit| {
1142 let mut run = || -> Result<()> {
1143 let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
1144 w.extract(self.decodable(unit), sink)
1145 };
1146 run().err().map(|e| format!("{e:#}"))
1147 },
1148 )
1149 .flatten()
1150 .collect()
1151 }
1152}
1153
1154fn threads_per_unit(units: usize) -> u32 {
1155 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
1156 (cores / units.max(1)).max(1) as u32
1157}
1158
1159const PART_SUFFIX: &str = ".hatchzip-part";
1161
1162const PROGRESS_SUFFIXES: [&str; 3] = [".hatchzip", ".hatchzip-tail", ".hatchzip-folders"];
1165
1166pub(crate) fn part_path(dest: &Path) -> PathBuf {
1167 let mut part = dest.as_os_str().to_owned();
1168 part.push(PART_SUFFIX);
1169 PathBuf::from(part)
1170}
1171
1172fn create_part(part: &Path) -> Result<File> {
1177 platform::create_new_no_follow(part).map_err(|e| {
1178 if e.kind() == io::ErrorKind::AlreadyExists {
1179 anyhow!(
1180 "{} already exists, and HatchZip does not replace a file it did not create. \
1181 Move it, then run the extraction again",
1182 part.display()
1183 )
1184 } else {
1185 anyhow::Error::new(e).context(format!("creating {}", part.display()))
1186 }
1187 })
1188}
1189
1190fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
1193 if written == 0 {
1194 return create_part(part);
1195 }
1196 if fs::symlink_metadata(part).is_err() && fs::symlink_metadata(dest).is_ok() {
1197 fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
1200 }
1201 let mut file = match platform::open_existing_no_follow(part) {
1202 Ok(f) => f,
1203 Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
1204 "{} is missing, and the archive data it was extracted from is already released, so \
1205 this file cannot be completed",
1206 part.display()
1207 ),
1208 Err(e) => return Err(e).with_context(|| format!("reopening {}", part.display())),
1209 };
1210 if file.metadata()?.len() < written {
1211 bail!(
1212 "{} is shorter than when its progress was saved; the extraction cannot continue",
1213 part.display()
1214 );
1215 }
1216 file.set_len(written)?;
1217 file.seek(SeekFrom::Start(written))?;
1218 Ok(file)
1219}
1220
1221struct OpenFile {
1223 item: Item,
1224 dest: PathBuf,
1225 part: PathBuf,
1226 file: File,
1227 written: u64,
1228}
1229
1230impl OpenFile {
1231 fn finish(self) -> Result<()> {
1233 if self.written != self.item.size {
1234 bail!("it is smaller than the archive records");
1235 }
1236 if let Some(t) = self.item.mtime {
1237 self.file.set_modified(t)?;
1238 }
1239 platform::apply_mode(&self.file, self.item.mode)?;
1240 if platform::SYNC_EACH_FILE {
1241 self.file.sync_all()?;
1242 }
1243 drop(self.file);
1244 fs::rename(&self.part, &self.dest)?;
1245 Ok(())
1246 }
1247}
1248
1249fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
1253 let n = written.min(resumable::WINDOW as u64);
1254 let mut window = vec![0; n as usize];
1255 file.seek(SeekFrom::Start(written - n))?;
1256 file.read_exact(&mut window)?;
1257 file.seek(SeekFrom::Start(written))?;
1258 Ok(window)
1259}
1260
1261pub struct Progress {
1262 pub on_bytes: Box<dyn Fn(u64) + Sync>,
1263 pub on_commit: Box<dyn Fn(u64) + Sync>,
1264}
1265
1266pub enum Outcome {
1267 Finished(Option<String>),
1269 Paused,
1270}
1271
1272pub struct Run<'a> {
1273 pub job: Job,
1274 pub journal: Journal,
1275 pub paths: Paths,
1276 pub stop: &'a AtomicBool,
1277 pub progress: Progress,
1278 pub keep_free: u64,
1280}
1281
1282impl Run<'_> {
1283 pub fn execute(mut self) -> Result<Outcome> {
1284 let out = self.journal.output.clone();
1285 fs::create_dir_all(&out)
1286 .with_context(|| format!("creating output folder {}", out.display()))?;
1287
1288 if self.job.only.is_some() && !self.journal.keep {
1291 bail!(
1292 "only some entries are selected, which are extracted only while the archive is \
1293 kept. Nothing was modified"
1294 );
1295 }
1296 let reclaims =
1297 !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
1298 if self.journal.keep {
1299 self.job.storage.protect();
1300 }
1301 if let Some(r) = self.journal.replace.as_mut()
1302 && !r.moved
1303 {
1304 replace::set_aside(&self.job, &out)?;
1305 r.moved = true;
1306 self.journal.save(&self.paths)?;
1307 self.job.started = true;
1308 }
1309 let mut next = 0;
1310 while next < self.job.units.len() {
1311 if self.stop.load(Ordering::Relaxed) {
1312 return Ok(Outcome::Paused);
1313 }
1314 if let Some(solid) = self.job.format.solid() {
1315 let walk = solid.walk(self.job.resumed(next))?;
1316 let what = describe(std::slice::from_ref(&self.job.units[next]));
1317 let Some(links) = self
1318 .stream_solid(next, walk, reclaims, &out)
1319 .map_err(|e| out_of_space(e, &what))?
1320 else {
1321 return Ok(Outcome::Paused);
1322 };
1323 self.commit(next, next + 1, links, &out)?;
1324 next += 1;
1325 continue;
1326 }
1327 if let Some(stream) = self.stream_now(next, reclaims, &out)? {
1328 let what = describe(std::slice::from_ref(&self.job.units[next]));
1329 if !self
1330 .stream_unit(next, &stream, &out)
1331 .map_err(|e| out_of_space(e, &what))?
1332 {
1333 return Ok(Outcome::Paused);
1334 }
1335 self.commit(next, next + 1, Vec::new(), &out)?;
1336 next += 1;
1337 continue;
1338 }
1339 let end = self.next_batch(next, &out, reclaims)?;
1340 let batch = &self.job.units[next..end];
1341 let what = describe(batch);
1342
1343 let Some(links) = self
1344 .extract_batch(batch, &out)
1345 .map_err(|e| out_of_space(e, &what))?
1346 else {
1347 return Ok(Outcome::Paused);
1348 };
1349 self.commit(next, end, links, &out)?;
1350 next = end;
1351 }
1352
1353 Ok(Outcome::Finished(self.finish(&out)?))
1354 }
1355
1356 fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
1359 let batch = &self.job.units[start..end];
1360 platform::sync_batch(out).context("flushing extracted files to disk")?;
1363 if platform::SYNC_EACH_FILE {
1364 let dirs: HashSet<PathBuf> = batch
1367 .iter()
1368 .flat_map(|u| &u.items)
1369 .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
1370 .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
1371 .collect();
1372 for d in &dirs {
1373 fsutil::sync_dir(d)?;
1374 }
1375 }
1376 crash_point("after-extract");
1377
1378 if self.journal.resume.is_none() {
1385 remove_after_extract(batch, out);
1386 verify_extracted(batch, out)?;
1387 }
1388
1389 let new_len = batch.last().expect("batches are never empty").start;
1390 self.journal.committed_len = new_len;
1391 self.journal.links.extend(links);
1392 self.journal.resume = None;
1395 self.journal.done = end == self.job.units.len();
1396 self.job.resume = None;
1397 self.journal.save(&self.paths)?;
1398 crash_point("after-journal");
1399
1400 if self.journal.keep {
1401 return Ok(());
1402 }
1403 self.job
1404 .storage
1405 .set_len(new_len)
1406 .context("shrinking the archive")?;
1407 (self.progress.on_commit)(new_len);
1408 Ok(())
1409 }
1410
1411 fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
1416 if self.job.resumed(i).is_some() {
1417 return match self.job.stream_of(i) {
1418 Some(s) => Ok(Some(s)),
1419 None => bail!(
1420 "the journal records '{}' as partially extracted, but it cannot be resumed",
1421 self.job.units[i].items[0].path.display()
1422 ),
1423 };
1424 }
1425 let Some(stream) = self.job.streams(i, reclaims) else {
1426 return Ok(None);
1427 };
1428 if always_stream() {
1429 return Ok(Some(stream));
1430 }
1431 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1432 Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
1433 }
1434
1435 fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
1445 let unit_start = self.job.units[i].start;
1446 let item = self.job.units[i].items[0].clone();
1447 let dest = out.join(&item.path);
1448 let part = part_path(&dest);
1449 let at = self.job.resumed(i).cloned().unwrap_or(Resume {
1450 unit: unit_start,
1451 written: 0,
1452 bit: stream.data_start * 8,
1453 crc: 0,
1454 stream: None,
1455 });
1456 let started_here = at.written == 0;
1457 let what = || format!("extracting '{}'", item.path.display());
1458 if let Some(parent) = dest.parent() {
1459 fs::create_dir_all(parent).with_context(what)?;
1460 }
1461 let file = open_part(&dest, &part, at.written).with_context(what)?;
1464 let result = self
1465 .stream_file(&item, stream, at, file, &dest, &part, out)
1466 .with_context(what);
1467 if result.is_err() && started_here && self.journal.resume.is_none() {
1468 let _ = fs::remove_file(&part);
1470 }
1471 result
1472 }
1473
1474 #[allow(clippy::too_many_arguments)]
1475 fn stream_file(
1476 &mut self,
1477 item: &Item,
1478 stream: &Stream,
1479 at: Resume,
1480 mut file: File,
1481 dest: &Path,
1482 part: &Path,
1483 out: &Path,
1484 ) -> Result<bool> {
1485 let window = match stream.codec {
1486 Codec::Stored => Vec::new(),
1487 Codec::Deflate => read_window(&mut file, at.written)?,
1488 };
1489 let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
1490 let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
1491 let mut written = at.written;
1492 let mut since_point = 0;
1493 let step = stream_step();
1494 let mut punching = self.job.punch_support();
1495 let what = format!("'{}'", item.path.display());
1496 self.ensure_room(out, &what, item.size - written, punching)?;
1497
1498 let mut buf = vec![0; BUF_SIZE];
1499 loop {
1500 if self.stop.load(Ordering::Relaxed) {
1501 return Ok(false);
1502 }
1503 let n = decoder.read(&mut buf)?;
1504 if n == 0 {
1505 break;
1506 }
1507 written += n as u64;
1508 if written > item.size {
1509 bail!("it is larger than the archive records");
1510 }
1511 file.write_all(&buf[..n])?;
1512 crc.update(&buf[..n]);
1513 (self.progress.on_bytes)(n as u64);
1514 since_point += n as u64;
1515
1516 if since_point < step || written == item.size {
1517 continue;
1518 }
1519 match decoder.restart_point() {
1520 Some(bit) => {
1521 let point = Resume {
1522 unit: at.unit,
1523 written,
1524 bit,
1525 crc: crc.clone().finalize(),
1526 stream: None,
1527 };
1528 punching = self.save_point(&file, part, out, point, stream, punching)?;
1529 since_point = 0;
1530 self.ensure_room(out, &what, item.size - written, punching)?;
1531 }
1532 None => {
1537 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1538 if avail < 2 * BUF_SIZE as u64 {
1539 bail!(
1540 "not enough disk space to continue: the compressed data of this entry has \
1541 no resume point in the last {}, so its archive space cannot be \
1542 released yet. {} more is required (the remainder of this file). \
1543 Progress is saved; free up space and resume the extraction.",
1544 human(since_point),
1545 human(item.size - written),
1546 );
1547 }
1548 }
1549 }
1550 }
1551 if written != item.size {
1552 bail!("it is smaller than the archive records");
1553 }
1554 if let Some(expected) = stream.crc
1555 && crc.finalize() != expected
1556 {
1557 bail!("its data is damaged (CRC mismatch)");
1558 }
1559 if let Some(t) = item.mtime {
1560 file.set_modified(t)?;
1561 }
1562 platform::apply_mode(&file, item.mode)?;
1563 file.sync_all()?;
1564 drop(file);
1565 fs::rename(part, dest)?;
1569 Ok(true)
1570 }
1571
1572 fn save_point(
1575 &mut self,
1576 file: &File,
1577 part: &Path,
1578 out: &Path,
1579 point: Resume,
1580 stream: &Stream,
1581 punching: Option<Punch>,
1582 ) -> Result<Option<Punch>> {
1583 file.sync_all()
1584 .context("flushing the extracted file to disk")?;
1585 let mut dir = part.parent();
1588 while let Some(d) = dir {
1589 fsutil::sync_dir(d)?;
1590 if d == out {
1591 break;
1592 }
1593 dir = d.parent();
1594 }
1595 crash_point("stream-after-sync");
1596
1597 self.journal.resume = Some(point.clone());
1598 self.journal.save(&self.paths)?;
1599 self.job.resume = Some(point.clone());
1600 crash_point("stream-after-journal");
1601
1602 if punching.is_some()
1605 && !self
1606 .job
1607 .storage
1608 .punch(stream.data_start, point.bit / 8)
1609 .context("freeing extracted archive bytes")?
1610 {
1611 return Ok(None);
1614 }
1615 crash_point("stream-after-punch");
1616 Ok(punching)
1617 }
1618
1619 fn stream_solid(
1632 &mut self,
1633 i: usize,
1634 mut walk: Box<dyn SolidWalker>,
1635 reclaims: bool,
1636 out: &Path,
1637 ) -> Result<Option<Vec<Link>>> {
1638 let unit = self.job.units[i].start;
1639 let step = stream_step();
1640 let mut punching = self.job.punch_support().filter(|_| reclaims);
1643 let profile = match self.job.format.solid() {
1644 Some(s) => s.profile().clone(),
1645 None => bail!("the archive is not a compressed stream"),
1646 };
1647 let mut left = match self.job.only {
1648 Some(_) => on_disk(&self.job.units[i]),
1649 None => profile.files,
1650 };
1651 let mut skipping = false;
1653 let mut punched = 0;
1657 let mut since_point = 0u64;
1658 let mut checked = 0u64;
1659 let mut open: Option<OpenFile> = None;
1660 let mut links = Vec::new();
1661 let mut dirs = HashSet::new();
1662 self.ensure_room(out, "the archive", left, punching)?;
1663
1664 loop {
1665 if self.stop.load(Ordering::Relaxed) {
1666 return Ok(None);
1667 }
1668 match walk.next(BUF_SIZE)? {
1669 Event::Entry { item, link, done } => {
1670 if self.job.selection().is_some_and(|o| !picks(o, &item.path)) {
1671 skipping = item.kind == Kind::File;
1672 continue;
1673 }
1674 let dest = out.join(&item.path);
1675 let what = || format!("extracting '{}'", item.path.display());
1676 match &item.kind {
1677 Kind::Dir => {
1678 fs::create_dir_all(&dest).with_context(what)?;
1679 dirs.insert(dest);
1680 }
1681 Kind::Symlink => {
1682 let target = String::from_utf8(link.unwrap_or_default())
1683 .map_err(|_| anyhow!("the link target is not valid UTF-8"))
1684 .with_context(what)?;
1685 links.push(Link {
1686 path: item.path.clone(),
1687 target: PathBuf::from(target),
1688 hard: false,
1689 });
1690 }
1691 Kind::HardLink(target) => links.push(Link {
1692 path: item.path.clone(),
1693 target: target.clone(),
1694 hard: true,
1695 }),
1696 Kind::File => {
1697 if let Some(parent) = dest.parent() {
1698 fs::create_dir_all(parent).with_context(what)?;
1699 }
1700 let part = part_path(&dest);
1701 let file = open_part(&dest, &part, done).with_context(what)?;
1702 open = Some(OpenFile {
1703 item,
1704 dest,
1705 part,
1706 file,
1707 written: done,
1708 });
1709 }
1710 }
1711 }
1712 Event::Data(_) if skipping => {}
1713 Event::Data(bytes) => {
1714 let f = open
1715 .as_mut()
1716 .ok_or_else(|| anyhow!("the tar stream holds data outside a file"))?;
1717 f.file
1718 .write_all(bytes)
1719 .with_context(|| format!("extracting '{}'", f.item.path.display()))?;
1720 let n = bytes.len() as u64;
1721 f.written += n;
1722 since_point += n;
1723 left = left.saturating_sub(n);
1724 (self.progress.on_bytes)(n);
1725 if punching.is_some()
1729 && since_point >= step
1730 && since_point - checked >= BUF_SIZE as u64
1731 {
1732 checked = since_point;
1733 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1734 if avail < 2 * BUF_SIZE as u64 {
1735 bail!(
1736 "not enough disk space to continue: the compressed data has no \
1737 resume point in the last {}, so its space cannot be released \
1738 yet. {} more is required (the remainder of the archive). \
1739 Progress is saved; free up space and resume the extraction.",
1740 human(since_point),
1741 human(left),
1742 );
1743 }
1744 }
1745 }
1746 Event::FileEnd if skipping => {
1747 skipping = false;
1748 crash_point("stream-skipped");
1750 }
1751 Event::FileEnd => {
1752 let f = open
1753 .take()
1754 .ok_or_else(|| anyhow!("the tar stream ends a file it never began"))?;
1755 let pad = f.item.size.next_multiple_of(4096) - f.item.size;
1756 let path = f.item.path.clone();
1757 let parent = f.dest.parent().map(Path::to_path_buf);
1758 f.finish()
1759 .with_context(|| format!("extracting '{}'", path.display()))?;
1760 dirs.extend(parent);
1761 since_point += pad;
1762 left = left.saturating_sub(pad);
1763 }
1764 Event::Point => {
1765 if since_point < step || self.job.only.is_some() {
1770 continue;
1771 }
1772 let mut point = walk.point()?;
1773 point.unit = unit;
1774 punching = self.solid_point(
1775 point,
1776 open.as_ref(),
1777 &mut links,
1778 &mut dirs,
1779 out,
1780 punching,
1781 &mut punched,
1782 )?;
1783 since_point = 0;
1784 checked = 0;
1785 self.ensure_room(out, "the archive", left, punching)?;
1786 }
1787 Event::End => break,
1788 }
1789 }
1790 if open.is_some() {
1791 bail!("the tar stream ended inside a file");
1792 }
1793 Ok(Some(links))
1794 }
1795
1796 #[allow(clippy::too_many_arguments)]
1799 fn solid_point(
1800 &mut self,
1801 point: Resume,
1802 open: Option<&OpenFile>,
1803 links: &mut Vec<Link>,
1804 dirs: &mut HashSet<PathBuf>,
1805 out: &Path,
1806 punching: Option<Punch>,
1807 punched: &mut u64,
1808 ) -> Result<Option<Punch>> {
1809 if let Some(f) = open {
1810 f.file
1811 .sync_all()
1812 .context("flushing the extracted file to disk")?;
1813 dirs.extend(f.part.parent().map(Path::to_path_buf));
1814 }
1815 platform::sync_batch(out).context("flushing extracted files to disk")?;
1816 if platform::SYNC_EACH_FILE {
1817 let mut done = HashSet::new();
1820 for d in dirs.drain() {
1821 let mut dir = Some(d.as_path());
1822 while let Some(d) = dir {
1823 if !done.insert(d.to_path_buf()) {
1824 break;
1825 }
1826 fsutil::sync_dir(d)?;
1827 if d == out {
1828 break;
1829 }
1830 dir = d.parent();
1831 }
1832 }
1833 }
1834 dirs.clear();
1835 crash_point("stream-after-sync");
1836
1837 let byte = point.bit / 8;
1838 self.journal.links.append(links);
1839 self.journal.resume = Some(point.clone());
1840 self.journal.save(&self.paths)?;
1841 self.job.resume = Some(point);
1842 crash_point("stream-after-journal");
1843
1844 if let Some(punch) = punching {
1845 if !self
1846 .job
1847 .storage
1848 .punch(*punched, byte)
1849 .context("freeing extracted archive bytes")?
1850 {
1851 return Ok(None);
1852 }
1853 *punched = byte.saturating_sub(punch.overlap);
1858 (self.progress.on_commit)(self.job.top - byte);
1859 }
1860 crash_point("stream-after-punch");
1861 Ok(punching)
1862 }
1863
1864 fn ensure_room(
1867 &self,
1868 out: &Path,
1869 what: &str,
1870 left: u64,
1871 punching: Option<Punch>,
1872 ) -> Result<()> {
1873 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1874 let left = left.next_multiple_of(4096);
1875 let need = match punching {
1876 Some(punch) => (stream_step() + BUF_SIZE as u64 + 2 * punch.margin).min(left),
1877 None => left,
1878 };
1879 if need > avail {
1880 bail!(
1881 "not enough disk space to continue: the next part of {} requires {} and {} is \
1882 available ({} reserved).\n{} more is required. Progress is saved; free up space \
1883 and resume the extraction.",
1884 what,
1885 human(need),
1886 human(avail),
1887 human(self.keep_free),
1888 human(need - avail),
1889 );
1890 }
1891 Ok(())
1892 }
1893
1894 fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
1897 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1898 let units = &self.job.units;
1899 let need = on_disk;
1900 let first = need(&units[start]);
1901 if first > avail {
1902 let what = describe(std::slice::from_ref(&units[start]));
1905 bail!(
1906 "not enough disk space to continue: {what} requires {} and {} is available \
1907 ({} reserved).\n{} more is required. Progress is saved; free up space and \
1908 resume the extraction.",
1909 human(first),
1910 human(avail),
1911 human(self.keep_free),
1912 human(first - avail),
1913 );
1914 }
1915 let budget = avail.min(BATCH_MAX_BYTES.max(first));
1916 let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
1917 let mut used = 0u64;
1918 let mut end = start;
1919 while end < units.len() && end - start < max_units {
1920 let size = need(&units[end]);
1921 if end > start && used.saturating_add(size) > budget {
1922 break;
1923 }
1924 if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
1925 break;
1926 }
1927 used += size;
1928 end += 1;
1929 }
1930 Ok(end)
1931 }
1932
1933 fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
1936 let on_bytes = &*self.progress.on_bytes;
1937 if self.job.format.serial() {
1938 let mut sink = DiskSink {
1939 out,
1940 stop: self.stop,
1941 on_bytes,
1942 buf: vec![0; BUF_SIZE],
1943 links: Vec::new(),
1944 only: self.job.selection(),
1945 };
1946 let mut worker = self
1947 .job
1948 .format
1949 .worker(1)
1950 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1951 for unit in batch.iter().rev() {
1953 match worker.extract(self.job.decodable(unit), &mut sink) {
1954 Ok(()) => {}
1955 Err(e) if is_interrupt(&e) => return Ok(None),
1956 Err(e) => return Err(e),
1957 }
1958 }
1959 return Ok(Some(sink.links));
1960 }
1961 let threads = threads_per_unit(batch.len());
1962 let results: Vec<Result<Vec<Link>>> = batch
1963 .par_iter()
1964 .map_init(
1965 || {
1966 let sink = DiskSink {
1967 out,
1968 stop: self.stop,
1969 on_bytes,
1970 buf: vec![0; BUF_SIZE],
1971 links: Vec::new(),
1972 only: self.job.selection(),
1973 };
1974 (self.job.format.worker(threads), sink)
1975 },
1976 |(worker, sink), unit| {
1977 let w = worker
1978 .as_mut()
1979 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1980 w.extract(self.job.decodable(unit), sink)?;
1981 Ok(std::mem::take(&mut sink.links))
1982 },
1983 )
1984 .collect();
1985
1986 let mut links = Vec::new();
1987 let mut interrupted = false;
1988 for r in results {
1989 match r {
1990 Ok(l) => links.extend(l),
1991 Err(e) if is_interrupt(&e) => interrupted = true,
1992 Err(e) => return Err(e),
1993 }
1994 }
1995 Ok((!interrupted).then_some(links))
1996 }
1997
1998 fn finish(mut self, out: &Path) -> Result<Option<String>> {
1999 make_links_and_settle(&mut self.journal, &self.paths, out)?;
2000 let warning = set_folders(&self.journal, &self.paths, out)?;
2003 if self.journal.keep {
2004 self.paths.remove()?;
2006 return Ok(warning);
2007 }
2008 let Self { job, paths, .. } = self;
2009 let Job {
2010 storage, format, ..
2011 } = job;
2012 drop(format);
2014 let storage = Arc::try_unwrap(storage)
2015 .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
2016 storage.remove()?;
2019 paths.remove()?;
2020 Ok(warning)
2021 }
2022}
2023
2024fn verify_extracted(batch: &[Unit], out: &Path) -> Result<()> {
2033 for item in batch.iter().flat_map(|u| &u.items) {
2034 if item.kind != Kind::File {
2035 continue;
2036 }
2037 let dest = out.join(&item.path);
2038 let meta = match fs::symlink_metadata(&dest) {
2040 Ok(meta) => meta,
2041 Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
2042 "'{}' disappeared while it was extracted. Antivirus software sometimes removes \
2043 files as they are written. The archive still holds it ({} bytes), so running \
2044 the same command again extracts it",
2045 item.path.display(),
2046 item.size
2047 ),
2048 Err(e) => {
2049 return Err(e).with_context(|| {
2050 format!("checking '{}' after extracting it", item.path.display())
2051 });
2052 }
2053 };
2054 if !meta.is_file() {
2055 bail!(
2056 "'{}' is no longer a file after it was extracted, but the archive has a file \
2057 there. The archive still holds it, so move what is in its place away and run \
2058 the same command again",
2059 item.path.display()
2060 );
2061 }
2062 if meta.len() != item.size {
2063 bail!(
2064 "'{}' changed while it was extracted: the archive records {} bytes, but the \
2065 file has {}. The archive still holds it, so move it away and run the same \
2066 command again",
2067 item.path.display(),
2068 item.size,
2069 meta.len()
2070 );
2071 }
2072 }
2073 Ok(())
2074}
2075
2076fn remove_after_extract(batch: &[Unit], out: &Path) {
2079 if !cfg!(debug_assertions) {
2080 return;
2081 }
2082 let Ok(rel) = std::env::var("HATCHZIP_REMOVE_AFTER_EXTRACT") else {
2083 return;
2084 };
2085 let rel = Path::new(&rel);
2086 let extracted = batch
2087 .iter()
2088 .flat_map(|u| &u.items)
2089 .any(|item| item.kind == Kind::File && item.path == rel);
2090 if extracted {
2091 let _ = fs::remove_file(out.join(rel));
2092 }
2093}
2094
2095pub fn finish_orphaned(journal: &mut Journal, paths: &Paths) -> Result<Option<String>> {
2099 let out = journal.output.clone();
2100 make_links_and_settle(journal, paths, &out)?;
2101 let warning = set_folders(journal, paths, &out)?;
2102 if journal.done && !journal.keep {
2105 for (part, _) in &journal.parts {
2106 match fs::remove_file(part) {
2107 Err(e) if e.kind() != io::ErrorKind::NotFound => {
2108 return Err(e).with_context(|| format!("deleting {}", part.display()));
2109 }
2110 _ => {}
2111 }
2112 }
2113 }
2114 paths.remove()?;
2115 Ok(warning)
2116}
2117
2118fn make_links_and_settle(journal: &mut Journal, paths: &Paths, out: &Path) -> Result<()> {
2123 if journal.folders_left {
2124 return Ok(());
2125 }
2126 make_final_links(&journal.links, out)?;
2127 if let Some(r) = &journal.replace {
2130 replace::settle(out, r)?;
2131 replace::remove(out)?;
2132 }
2133 if journal.folders.is_some() {
2134 journal.folders_left = true;
2135 journal.save(paths)?;
2136 }
2137 Ok(())
2138}
2139
2140fn set_folders(journal: &Journal, paths: &Paths, out: &Path) -> Result<Option<String>> {
2146 let Some(saved) = journal.folders else {
2147 return Ok(None);
2148 };
2149 crash_point("before-folders");
2150 let list = match folders::load(&paths.folders, saved) {
2151 Ok(list) => list,
2152 Err(e) => {
2153 let folders = match saved.count {
2154 1 => "1 folder".to_string(),
2155 n => format!("{n} folders"),
2156 };
2157 return Ok(Some(format!(
2158 "{e:#}, so {folders} in {} kept the default permissions and modified times",
2159 out.display()
2160 )));
2161 }
2162 };
2163 folders::apply(&list, out)?;
2164 crash_point("after-folders");
2165 Ok(None)
2166}
2167
2168fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
2173 make_links(links, out).map_err(|e| {
2174 anyhow!(
2175 "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
2176 each one, for example by moving or renaming a folder that is in the way, then \
2177 resume the extraction to create them"
2178 )
2179 })
2180}
2181
2182pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
2186 let failed: Vec<(&Link, anyhow::Error)> = links
2187 .iter()
2188 .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
2189 .collect();
2190 if failed.is_empty() {
2191 return Ok(());
2192 }
2193 let mut msg = match failed.len() {
2194 1 => "1 link could not be created:".to_string(),
2195 n => format!("{n} links could not be created:"),
2196 };
2197 for (link, e) in failed.iter().take(10) {
2198 let kind = if link.hard {
2199 "hard link"
2200 } else {
2201 "symbolic link"
2202 };
2203 msg.push_str(&format!(
2204 "\n '{}' ({kind} to '{}'): {e:#}",
2205 link.path.display(),
2206 link.target.display()
2207 ));
2208 }
2209 if failed.len() > 10 {
2210 msg.push_str(&format!("\n and {} more", failed.len() - 10));
2211 }
2212 Err(anyhow!(msg))
2213}
2214
2215fn make_link(link: &Link, out: &Path) -> Result<()> {
2216 if let Some(via) = link_on_the_way(out, &link.path) {
2219 bail!(
2220 "'{}' is a link, and this one would be created through it",
2221 via.display()
2222 );
2223 }
2224 let path = out.join(&link.path);
2225 if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
2226 bail!("a folder already exists at this location");
2227 }
2228 if let Some(parent) = path.parent() {
2229 fs::create_dir_all(parent)?;
2230 }
2231 if link.hard {
2232 if let Some(via) = link_on_the_way(out, &link.target) {
2233 bail!(
2234 "'{}' is a link, and the target would be reached through it",
2235 via.display()
2236 );
2237 }
2238 let target = out.join(&link.target);
2239 let _ = fs::remove_file(&path);
2240 fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
2242 } else {
2243 platform::create_symlink(&path, &link.target)?;
2244 }
2245 Ok(())
2246}
2247
2248pub(crate) fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
2250 let mut ancestors: Vec<&Path> = rel
2251 .ancestors()
2252 .skip(1)
2253 .filter(|p| !p.as_os_str().is_empty())
2254 .collect();
2255 ancestors.reverse();
2256 ancestors
2257 .into_iter()
2258 .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
2259 .map(Path::to_path_buf)
2260}
2261
2262struct DiskSink<'a> {
2263 out: &'a Path,
2264 stop: &'a AtomicBool,
2265 on_bytes: &'a (dyn Fn(u64) + Sync),
2266 buf: Vec<u8>,
2267 links: Vec<Link>,
2268 only: Option<&'a [PathBuf]>,
2270}
2271
2272impl Sink for DiskSink<'_> {
2273 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2274 if self.only.is_some_and(|o| !picks(o, &item.path)) {
2275 return self
2276 .skip(data)
2277 .with_context(|| format!("reading past '{}'", item.path.display()));
2278 }
2279 self.write(item, data)
2280 .with_context(|| format!("extracting '{}'", item.path.display()))
2281 }
2282}
2283
2284impl DiskSink<'_> {
2285 fn skip(&mut self, data: &mut dyn Read) -> Result<()> {
2288 loop {
2289 if self.stop.load(Ordering::Relaxed) {
2290 return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2291 }
2292 if data.read(&mut self.buf)? == 0 {
2293 return Ok(());
2294 }
2295 }
2296 }
2297
2298 fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2299 let dest = self.out.join(&item.path);
2300 match &item.kind {
2301 Kind::Dir => {
2302 fs::create_dir_all(&dest)?;
2303 return Ok(());
2304 }
2305 Kind::Symlink => {
2306 let mut target = Vec::new();
2307 data.take(MAX_SYMLINK).read_to_end(&mut target)?;
2308 let target = PathBuf::from(String::from_utf8(target)?);
2309 self.links.push(Link {
2310 path: item.path.clone(),
2311 target,
2312 hard: false,
2313 });
2314 return Ok(());
2315 }
2316 Kind::HardLink(target) => {
2317 self.links.push(Link {
2318 path: item.path.clone(),
2319 target: target.clone(),
2320 hard: true,
2321 });
2322 return Ok(());
2323 }
2324 Kind::File => {}
2325 }
2326
2327 if let Some(parent) = dest.parent() {
2328 fs::create_dir_all(parent)?;
2329 }
2330 let part = part_path(&dest);
2331 let dst = create_part(&part)?;
2333 let result = self.copy(item, data, dst);
2334 if result.is_err() {
2335 let _ = fs::remove_file(&part);
2336 return result;
2337 }
2338 fs::rename(&part, &dest)?;
2339 Ok(())
2340 }
2341
2342 fn copy(&mut self, item: &Item, data: &mut dyn Read, mut dst: File) -> Result<()> {
2343 let mut written = 0u64;
2344 loop {
2345 if self.stop.load(Ordering::Relaxed) {
2346 return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2347 }
2348 let n = data.read(&mut self.buf)?;
2351 if n == 0 {
2352 break;
2353 }
2354 written += n as u64;
2355 if written > item.size {
2356 bail!("it is larger than the archive records");
2357 }
2358 dst.write_all(&self.buf[..n])?;
2359 (self.on_bytes)(n as u64);
2360 }
2361 if written != item.size {
2362 bail!("it is smaller than the archive records");
2363 }
2364 if let Some(t) = item.mtime {
2365 dst.set_modified(t)?;
2366 }
2367 platform::apply_mode(&dst, item.mode)?;
2368 if platform::SYNC_EACH_FILE {
2369 dst.sync_all()?;
2370 }
2371 Ok(())
2372 }
2373}
2374
2375struct ProbeSink {
2377 left: u64,
2378 buf: Vec<u8>,
2379}
2380
2381#[derive(Debug)]
2382struct ProbeDone;
2383
2384impl std::fmt::Display for ProbeDone {
2385 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2386 f.write_str("read enough to prove the password")
2387 }
2388}
2389
2390impl std::error::Error for ProbeDone {}
2391
2392impl Sink for ProbeSink {
2393 fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
2394 loop {
2395 let n = data.read(&mut self.buf)?;
2396 if n == 0 {
2397 return Ok(());
2398 }
2399 self.left = self.left.saturating_sub(n as u64);
2400 if self.left == 0 {
2401 return Err(ProbeDone.into());
2402 }
2403 }
2404 }
2405}
2406
2407struct VerifySink<'a> {
2408 on_bytes: &'a (dyn Fn(u64) + Sync),
2409 buf: Vec<u8>,
2410}
2411
2412impl Sink for VerifySink<'_> {
2413 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2414 let mut read = 0;
2415 loop {
2416 let n = data
2417 .read(&mut self.buf)
2418 .with_context(|| format!("'{}'", item.path.display()))?;
2419 if n == 0 {
2420 break;
2421 }
2422 read += n as u64;
2423 (self.on_bytes)(n as u64);
2424 }
2425 if item.kind == Kind::File && read != item.size {
2426 bail!(
2427 "'{}' is shorter than the archive records",
2428 item.path.display()
2429 );
2430 }
2431 Ok(())
2432 }
2433}
2434
2435fn is_interrupt(e: &anyhow::Error) -> bool {
2436 e.chain()
2437 .filter_map(|c| c.downcast_ref::<io::Error>())
2438 .any(|io| io.kind() == io::ErrorKind::Interrupted)
2439}
2440
2441fn is_disk_full(e: &anyhow::Error) -> bool {
2448 e.chain()
2449 .filter_map(|c| c.downcast_ref::<io::Error>())
2450 .any(|io| {
2451 matches!(
2452 io.kind(),
2453 io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded
2454 )
2455 })
2456}
2457
2458fn out_of_space(e: anyhow::Error, what: &str) -> anyhow::Error {
2461 if !is_disk_full(&e) {
2462 return e;
2463 }
2464 e.context(format!(
2465 "not enough disk space to continue: {what} could not be written because the disk filled \
2466 up.\nProgress is saved; free up space and resume the extraction"
2467 ))
2468}
2469
2470fn describe(units: &[Unit]) -> String {
2471 let items: usize = units.iter().map(|u| u.items.len()).sum();
2472 match units {
2473 [one] if one.items.len() == 1 => format!("'{}'", one.items[0].path.display()),
2474 _ => format!("the next block of {items} files"),
2475 }
2476}
2477
2478fn test_knob(name: &str) -> Option<u32> {
2480 if !cfg!(debug_assertions) {
2481 return None;
2482 }
2483 std::env::var(name).ok()?.parse().ok()
2484}
2485
2486pub(crate) fn crash_point(name: &str) {
2489 if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
2490 return;
2491 }
2492 static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2493 if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
2494 std::process::abort();
2495 }
2496}
2497
2498pub fn human(bytes: u64) -> String {
2499 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
2500 let mut v = bytes as f64;
2501 let mut unit = 0;
2502 while v >= 1000.0 && unit < UNITS.len() - 1 {
2503 v /= 1000.0;
2504 unit += 1;
2505 }
2506 if unit == 0 {
2507 format!("{bytes} B")
2508 } else {
2509 format!("{v:.1} {}", UNITS[unit])
2510 }
2511}
2512
2513#[cfg(test)]
2514mod tests {
2515 use super::*;
2516 use crate::archive::{Opened, Worker};
2517
2518 struct NoFormat;
2520
2521 impl Format for NoFormat {
2522 fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
2523 bail!("nothing is decoded in these tests")
2524 }
2525 }
2526
2527 #[test]
2529 fn names_meet_where_they_first_differ() {
2530 for (a, b, folder) in [
2531 ("a/Makefile", "a/makefile", "a"),
2532 ("Makefile", "makefile", ""),
2533 ("D/x", "d/x", ""),
2534 ("D", "d/inner.txt", ""),
2535 ("a/B/c/F", "a/b/c/f", "a"),
2536 ] {
2537 assert_eq!(
2538 meeting_folder(Path::new(a), Path::new(b)),
2539 Path::new(folder),
2540 "{a} and {b}"
2541 );
2542 }
2543 }
2544
2545 fn clashes(paths: &[&'static str]) -> CaseClashes {
2546 let mut names: Vec<(String, &Path, bool)> = paths
2547 .iter()
2548 .map(|p| (crate::fsutil::fold_name(p), Path::new(*p), true))
2549 .collect();
2550 names.sort_unstable();
2551 CaseClashes::of(&names)
2552 }
2553
2554 #[test]
2557 fn names_a_filesystem_folds_together_pair_up() {
2558 for pair in [
2559 ["stra\u{df}e.txt", "STRASSE.txt"],
2560 ["s.txt", "\u{17f}.txt"],
2561 ["\u{3c3}.txt", "\u{3c2}.txt"],
2562 ["fi.txt", "\u{fb01}.txt"],
2563 ["caf\u{e9}.txt", "cafe\u{301}.txt"],
2564 ] {
2565 let c = clashes(&pair);
2566 assert_eq!(c.met_in.len(), 1, "{pair:?}");
2567 assert!(c.beyond_ascii.is_some(), "{pair:?}");
2568 }
2569 assert!(clashes(&["\u{65e5}.txt", "\u{4e2d}.txt"]).met_in.is_empty());
2570 }
2571
2572 #[test]
2575 fn clashes_cover_every_folder_where_names_meet() {
2576 let met = clashes(&["X/a/f", "x/A/f", "x/a/f", "other", "OTHER2"]).met_in;
2577 assert_eq!(
2578 met.keys().collect::<Vec<_>>(),
2579 [Path::new(""), Path::new("x")]
2580 );
2581 }
2582
2583 #[test]
2586 fn directory_aliases_need_no_case_separation_in_a_fileless_branch() {
2587 let tmp = tempfile::tempdir().unwrap();
2588 let path = tmp.path().join("archive.bin");
2589 fs::write(&path, [0u8; 64]).unwrap();
2590 let storage = Arc::new(Storage::open(&path, false).unwrap());
2591 let units = ["A/f", "a/F/one.txt", "a/f/two.txt"]
2592 .iter()
2593 .enumerate()
2594 .map(|(i, name)| unit(i as u64, name, 1))
2595 .collect();
2596 let job = Job::build(storage, opened(units, 64), 64).unwrap();
2597 let clashes = job.check_layout().unwrap();
2598 assert_eq!(clashes.met_in.keys().collect::<Vec<_>>(), [Path::new("")]);
2599 }
2600
2601 #[test]
2605 fn case_folders_match_every_file_file_and_file_folder_pair() {
2606 let paths = [
2607 "A/B/C", "A/B/c", "A/b/C", "A/b/c", "a/B/C", "a/B/c", "a/b/C", "a/b/c",
2608 ];
2609 for mut choices in 0..3usize.pow(paths.len() as u32) {
2610 let mut names = Vec::new();
2611 for path in paths {
2612 let kind = choices % 3;
2613 choices /= 3;
2614 if kind != 0 {
2615 names.push((path.to_lowercase(), Path::new(path), kind == 2));
2616 }
2617 }
2618 let mut expected = std::collections::BTreeSet::new();
2619 for (i, a) in names.iter().enumerate() {
2620 for b in &names[i + 1..] {
2621 if a.2 || b.2 {
2622 expected.insert(meeting_folder(a.1, b.1));
2623 }
2624 }
2625 }
2626 let clashes = CaseClashes::of(&names);
2627 assert_eq!(
2628 clashes.met_in.keys().collect::<Vec<_>>(),
2629 expected.iter().collect::<Vec<_>>(),
2630 "{names:?}"
2631 );
2632 }
2633 }
2634
2635 #[test]
2638 fn clashes_stay_linear_in_the_names() {
2639 let paths: Vec<String> = (0..4096u32)
2640 .map(|bits| {
2641 (0..12)
2642 .map(|i| if bits >> i & 1 == 1 { 'A' } else { 'a' })
2643 .collect()
2644 })
2645 .collect();
2646 let mut names: Vec<(String, &Path, bool)> = paths
2647 .iter()
2648 .enumerate()
2649 .map(|(i, p)| (p.to_lowercase(), Path::new(p), i % 2 == 0))
2650 .collect();
2651 names.sort_unstable();
2652 assert_eq!(CaseClashes::of(&names).met_in.len(), 1);
2653 }
2654
2655 #[test]
2659 fn names_beyond_ascii_are_noted_on_every_system() {
2660 assert!(clashes(&["K.txt", "\u{212a}.txt"]).beyond_ascii.is_some());
2661 assert!(clashes(&["Makefile", "makefile"]).beyond_ascii.is_none());
2662 }
2663
2664 #[test]
2667 fn the_nearest_existing_folder_decides() {
2668 let tmp = tempfile::TempDir::new().unwrap();
2669 let out = tmp.path().join("out");
2670 fs::create_dir_all(out.join("mounted")).unwrap();
2671 let asked = std::cell::RefCell::new(Vec::new());
2672 let result = first_not_apart(
2673 &out,
2674 [
2675 Path::new(""),
2676 Path::new("new/deep"),
2677 Path::new("mounted/new"),
2678 ],
2679 |dir| {
2680 asked.borrow_mut().push(dir.to_path_buf());
2681 dir != out.join("mounted")
2682 },
2683 );
2684 assert_eq!(
2685 result,
2686 Some((Path::new("mounted/new"), out.join("mounted")))
2687 );
2688 assert_eq!(*asked.borrow(), [out.clone(), out.join("mounted")]);
2689 }
2690
2691 fn unit(start: u64, name: &str, size: u64) -> Unit {
2692 Unit {
2693 start,
2694 key: 0,
2695 items: vec![Item {
2696 path: name.into(),
2697 size,
2698 kind: Kind::File,
2699 mode: None,
2700 mtime: None,
2701 }],
2702 encrypted: false,
2703 }
2704 }
2705
2706 fn storage(test: &str) -> (PathBuf, Arc<Storage>) {
2708 let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2709 fs::create_dir_all(&dir).unwrap();
2710 let path = dir.join("archive.bin");
2711 fs::write(&path, [0u8; 64]).unwrap();
2712 let storage = Arc::new(Storage::open(&path, false).unwrap());
2713 (dir, storage)
2714 }
2715
2716 fn opened(units: Vec<Unit>, tail_start: u64) -> Opened {
2717 Opened {
2718 name: "test",
2719 format: Box::new(NoFormat),
2720 units,
2721 tail_start,
2722 }
2723 }
2724
2725 fn scratch(test: &str) -> PathBuf {
2727 let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2728 let _ = fs::remove_dir_all(&dir);
2729 fs::create_dir_all(&dir).unwrap();
2730 dir
2731 }
2732
2733 #[test]
2736 fn a_batch_that_is_all_on_disk_verifies() {
2737 let out = scratch("verify-complete");
2738 fs::create_dir_all(out.join("game")).unwrap();
2739 fs::write(out.join("game/a"), b"hello").unwrap();
2740 fs::write(out.join("game/empty"), b"").unwrap();
2741 let batch = [unit(10, "game/a", 5), unit(20, "game/empty", 0)];
2742 assert!(verify_extracted(&batch, &out).is_ok());
2743 fs::remove_dir_all(&out).unwrap();
2744 }
2745
2746 #[test]
2747 fn a_missing_file_fails_verification() {
2748 let out = scratch("verify-missing");
2749 let err = verify_extracted(&[unit(0, "game/gone", 12)], &out)
2750 .err()
2751 .unwrap();
2752 let text = err.to_string();
2753 assert!(text.contains("game/gone"), "{text}");
2754 assert!(text.contains("disappeared"), "{text}");
2755 assert!(text.contains("12 bytes"), "{text}");
2756 fs::remove_dir_all(&out).unwrap();
2757 }
2758
2759 #[test]
2760 fn a_file_of_the_wrong_size_fails_verification() {
2761 let out = scratch("verify-size");
2762 fs::create_dir_all(out.join("game")).unwrap();
2763 fs::write(out.join("game/a"), b"abc").unwrap();
2764 let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2765 .err()
2766 .unwrap();
2767 let text = err.to_string();
2768 assert!(text.contains("game/a"), "{text}");
2769 assert!(text.contains("records 5 bytes"), "{text}");
2770 assert!(text.contains("has 3"), "{text}");
2771 fs::remove_dir_all(&out).unwrap();
2772 }
2773
2774 #[test]
2775 fn a_folder_at_the_name_of_a_file_fails_verification() {
2776 let out = scratch("verify-folder");
2777 fs::create_dir_all(out.join("game/a")).unwrap();
2778 let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2779 .err()
2780 .unwrap();
2781 assert!(err.to_string().contains("no longer a file"), "{err}");
2782 fs::remove_dir_all(&out).unwrap();
2783 }
2784
2785 #[cfg(unix)]
2788 #[test]
2789 fn a_link_at_the_name_of_a_file_fails_verification() {
2790 let out = scratch("verify-link");
2791 fs::write(out.join("real"), b"hello").unwrap();
2792 std::os::unix::fs::symlink("real", out.join("link")).unwrap();
2793 let err = verify_extracted(&[unit(0, "link", 5)], &out).err().unwrap();
2794 assert!(err.to_string().contains("no longer a file"), "{err}");
2795 fs::remove_dir_all(&out).unwrap();
2796 }
2797
2798 #[test]
2801 fn other_kinds_of_entries_are_not_verified() {
2802 let out = scratch("verify-kinds");
2803 let item = |kind: Kind| Item {
2804 path: "absent".into(),
2805 size: 0,
2806 kind,
2807 mode: None,
2808 mtime: None,
2809 };
2810 let batch = Unit {
2811 start: 0,
2812 key: 0,
2813 items: vec![
2814 item(Kind::Dir),
2815 item(Kind::Symlink),
2816 item(Kind::HardLink("absent".into())),
2817 ],
2818 encrypted: false,
2819 };
2820 assert!(verify_extracted(&[batch], &out).is_ok());
2821 fs::remove_dir_all(&out).unwrap();
2822 }
2823
2824 #[test]
2827 fn units_sharing_a_start_are_refused() {
2828 let (dir, storage) = storage("shared-start");
2829 let shared = vec![unit(10, "a", 1), unit(30, "b", 1), unit(10, "c", 1)];
2830 let err = Job::build(storage.clone(), opened(shared, 40), 64)
2831 .err()
2832 .unwrap();
2833 assert!(err.to_string().contains("same offset"), "{err:#}");
2834 let apart = vec![unit(10, "a", 1), unit(30, "b", 1)];
2835 assert!(Job::build(storage, opened(apart, 40), 64).is_ok());
2836 fs::remove_dir_all(&dir).unwrap();
2837 }
2838
2839 #[test]
2842 fn data_past_the_end_of_the_file_is_refused() {
2843 let (dir, storage) = storage("past-the-end");
2844 for (starts, tail_start) in [(vec![10, 64], 40), (vec![10, 70], 40), (vec![10], 65)] {
2845 let units = starts
2846 .iter()
2847 .map(|&s| unit(s, &format!("f{s}"), 1))
2848 .collect();
2849 let err = Job::build(storage.clone(), opened(units, tail_start), 64)
2850 .err()
2851 .unwrap();
2852 assert!(err.is::<archive::Damaged>(), "{starts:?}: {err:#}");
2853 }
2854 let job = Job::build(
2856 storage,
2857 opened(vec![unit(10, "a", 1), unit(50, "b", 1)], 60),
2858 40,
2859 );
2860 assert_eq!(job.unwrap().units.len(), 1);
2861 fs::remove_dir_all(&dir).unwrap();
2862 }
2863
2864 #[test]
2868 fn sizes_too_large_to_add_up_are_refused() {
2869 let (dir, storage) = storage("huge-sizes");
2870 let half = 1u64 << 63;
2871 for sizes in [vec![half, half], vec![u64::MAX - 10], vec![(1 << 62) + 1]] {
2872 let units = sizes
2873 .iter()
2874 .enumerate()
2875 .map(|(i, &s)| unit(10 + i as u64, &format!("f{i}"), s))
2876 .collect();
2877 let err = Job::build(storage.clone(), opened(units, 40), 64)
2878 .err()
2879 .unwrap();
2880 assert!(err.is::<archive::Damaged>(), "{sizes:?}: {err:#}");
2881 }
2882 assert_eq!(on_disk(&unit(0, "f", u64::MAX - 10)), u64::MAX);
2883 let mut two = unit(0, "f", half);
2884 two.items.extend(unit(0, "g", half).items);
2885 assert_eq!(two.size(), u64::MAX);
2886 assert_eq!(on_disk(&two), u64::MAX);
2887 fs::remove_dir_all(&dir).unwrap();
2888 }
2889}
2890
2891#[cfg(test)]
2892mod space_errors {
2893 use super::{is_disk_full, out_of_space};
2894 use anyhow::Context;
2895 use std::io;
2896
2897 #[test]
2898 fn disk_full_errors_become_the_resume_stop() {
2899 for kind in [io::ErrorKind::StorageFull, io::ErrorKind::QuotaExceeded] {
2900 let e: anyhow::Error = Err::<(), _>(io::Error::from(kind))
2901 .context("extracting 'game/a'")
2902 .unwrap_err();
2903 assert!(is_disk_full(&e), "{kind:?} not recognized as full");
2904 let e = out_of_space(e, "'game/a'");
2905 let msg = e.to_string();
2906 assert!(msg.contains("not enough disk space to continue"), "{msg}");
2907 assert!(msg.contains("Progress is saved"), "{msg}");
2908 let full = format!("{e:#}");
2910 assert!(full.contains("extracting 'game/a'"), "{full}");
2911 }
2912 }
2913
2914 #[test]
2915 fn other_write_errors_pass_through() {
2916 for kind in [
2917 io::ErrorKind::PermissionDenied,
2918 io::ErrorKind::AlreadyExists,
2919 ] {
2920 let e: anyhow::Error = Err::<(), _>(io::Error::from(kind))
2921 .context("extracting 'game/a'")
2922 .unwrap_err();
2923 assert!(!is_disk_full(&e), "{kind:?} taken for a full disk");
2924 let msg = out_of_space(e, "'game/a'").to_string();
2925 assert!(msg.contains("extracting 'game/a'"), "{msg}");
2926 assert!(!msg.contains("Progress is saved"), "{msg}");
2927 }
2928 }
2929}