1use std::collections::{BTreeMap, HashMap, HashSet};
31use std::fs::{self, File};
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};
43use crate::archive::{
44 self, Codec, Format, Item, Kind, PasswordCheck, Sink, SolidWalker, Stream, Unit,
45};
46use crate::journal::{Journal, Link, Paths, Resume, TarAt};
47use crate::{fsutil, platform, replace};
48
49const BATCH_MAX_UNITS: usize = 512;
52const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
53const BUF_SIZE: usize = 1024 * 1024;
54const MAX_SYMLINK: u64 = 64 * 1024;
55
56const STREAM_STEP: u64 = 256 * 1024 * 1024;
60
61fn stream_step() -> u64 {
62 test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
63}
64
65fn stream_threshold() -> u64 {
68 2 * stream_step()
69}
70
71fn always_stream() -> bool {
74 test_knob("HATCHZIP_STREAM_STEP").is_some()
75}
76
77const MAX_TOTAL_SIZE: u64 = 1 << 62;
80
81fn max_tail() -> u64 {
84 test_knob("HATCHZIP_MAX_TAIL").map_or(1_000_000_000, u64::from)
85}
86
87fn on_disk(u: &Unit) -> u64 {
88 u.items.iter().fold(0u64, |sum, i| {
89 let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
90 sum.saturating_add(size)
91 })
92}
93
94pub struct Job {
95 pub storage: Arc<Storage>,
96 pub format_name: &'static str,
97 format: Box<dyn Format>,
98 pub units: Vec<Unit>,
100 pub tail_start: u64,
101 pub top: u64,
104 punch: OnceLock<Option<u64>>,
108 resume: Option<Resume>,
110 started: bool,
114 case_clashes: Box<CaseClashes>,
120}
121
122const MAX_CASE_FOLDERS: usize = 1000;
126
127#[derive(Default)]
129struct CaseClashes {
130 met_in: BTreeMap<PathBuf, (PathBuf, PathBuf)>,
133 beyond_ascii: Option<(PathBuf, PathBuf)>,
136 recorded: Vec<PathBuf>,
138 recorded_beyond_ascii: bool,
139}
140
141impl CaseClashes {
142 fn of(names: &[(String, &Path, bool)]) -> Self {
145 let mut clashes = Self::default();
146 for group in names.chunk_by(|a, b| a.0 == b.0) {
147 if !group.iter().any(|n| n.2) {
149 continue;
150 }
151 let mut previous_file = None;
155 for (_, path, is_file) in group {
156 if let Some(file) = previous_file {
157 clashes.add_pair(file, path);
158 }
159 if *is_file {
160 previous_file = Some(*path);
161 }
162 }
163 let mut next_file = None;
164 for (_, path, is_file) in group.iter().rev() {
165 if *is_file {
166 next_file = Some(*path);
167 } else if let Some(file) = next_file {
168 clashes.add_pair(path, file);
169 }
170 }
171 }
172 clashes
173 }
174
175 fn add_pair(&mut self, a: &Path, b: &Path) {
176 self.met_in
177 .entry(meeting_folder(a, b))
178 .or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
179 if !(a.to_string_lossy().is_ascii() && b.to_string_lossy().is_ascii()) {
180 self.beyond_ascii
181 .get_or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
182 }
183 }
184}
185
186fn meeting_folder(a: &Path, b: &Path) -> PathBuf {
190 a.components()
191 .zip(b.components())
192 .take_while(|(x, y)| x == y)
193 .map(|(x, _)| x)
194 .collect()
195}
196
197pub(crate) fn keeps_case_apart(dir: &Path) -> bool {
201 let at = std::env::var_os("HATCHZIP_IGNORE_CASE_AT").filter(|_| cfg!(debug_assertions));
202 test_knob("HATCHZIP_IGNORE_CASE").is_none()
203 && at.is_none_or(|at| Path::new(&at) != dir)
204 && platform::case_sensitive(dir)
205}
206
207fn normalizes_names() -> bool {
210 platform::NORMALIZES_NAMES || test_knob("HATCHZIP_NORMALIZE_NAMES").is_some()
211}
212
213pub(crate) fn check_case_record(out: &Path, folders: &[PathBuf], beyond_ascii: bool) -> Result<()> {
219 if beyond_ascii && normalizes_names() {
220 bail!(
221 "this extraction has names that differ only in case with characters outside ASCII, \
222 which this system may treat as one file, so going on here could lose files. Go on \
223 where it started"
224 );
225 }
226 let folders = folders.iter().map(PathBuf::as_path);
227 if let Some((_, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
228 bail!(
229 "this extraction has names that differ only in case, and {} is not known to keep \
230 such names apart, so going on here could lose files. Move the output folder back \
231 to a case-sensitive filesystem and run the command again",
232 nearest.display()
233 );
234 }
235 Ok(())
236}
237
238fn first_not_apart<'a>(
242 out: &Path,
243 folders: impl IntoIterator<Item = &'a Path>,
244 apart: impl Fn(&Path) -> bool,
245) -> Option<(&'a Path, PathBuf)> {
246 let mut known = HashMap::new();
247 for folder in folders {
248 let nearest = if folder.as_os_str().is_empty() {
249 fsutil::existing_ancestor(out)
250 } else {
251 fsutil::existing_ancestor(&out.join(folder))
252 };
253 let ok = match known.get(&nearest) {
254 Some(ok) => *ok,
255 None => {
256 let ok = apart(&nearest);
257 known.insert(nearest.clone(), ok);
258 ok
259 }
260 };
261 if !ok {
262 return Some((folder, nearest));
263 }
264 }
265 None
266}
267
268impl Job {
269 pub fn open(
273 path: &Path,
274 writable: bool,
275 password: Option<&str>,
276 reads: Arc<Reads>,
277 ) -> Result<Self> {
278 let mut job = Self::open_as_is(path, writable, password, reads)?;
279 job.case_clashes = Box::new(job.check_layout()?);
280 Ok(job)
281 }
282
283 pub(crate) fn open_as_is(
288 path: &Path,
289 writable: bool,
290 password: Option<&str>,
291 reads: Arc<Reads>,
292 ) -> Result<Self> {
293 let mut storage = Storage::open(path, writable)?;
294 storage.count_reads(reads);
295 let storage = Arc::new(storage);
296 let opened = archive::open(&storage, None, password)?;
297 let top = storage.original_len();
298 if top.saturating_sub(opened.tail_start) > max_tail() {
302 bail!(
303 "this archive holds more than {} after its last entry, which HatchZip would \
304 have to keep in memory for the whole extraction. The archive was not modified",
305 human(max_tail())
306 );
307 }
308 Self::build(storage, opened, top)
309 }
310
311 pub fn resume(
315 journal: &Journal,
316 tail: Arc<Tail>,
317 writable: bool,
318 password: Option<&str>,
319 reads: Arc<Reads>,
320 ) -> Result<Self> {
321 let mut storage = Storage::from_parts(&journal.parts, writable)?;
322 storage.count_reads(reads);
323 let storage = Arc::new(storage);
324 let current = storage.current_len()?;
325 if journal.keep {
326 storage.protect();
329 if current != storage.original_len() {
330 bail!(
331 "{} has changed since the extraction started. Put the original archive back \
332 to resume, or run restore to discard the progress",
333 storage.primary().display()
334 );
335 }
336 }
337 if current < journal.committed_len {
338 bail!(
339 "{} is shorter than HatchZip left it and will not be modified",
340 storage.primary().display()
341 );
342 }
343 if current > journal.committed_len && writable && !journal.keep {
344 storage.set_len(journal.committed_len)?;
346 }
347 let point = journal.resume.as_ref();
348 let opened = archive::open(&storage, Some((&journal.format, tail, point)), password)?;
349 let mut job = Self::build(storage, opened, journal.committed_len)?;
350 job.started = journal.replace.as_ref().is_none_or(|r| r.moved);
351 job.case_clashes.recorded.clone_from(&journal.case_folders);
352 job.case_clashes.recorded_beyond_ascii = journal.case_beyond_ascii;
353 if let Some(r) = &journal.resume {
354 if job.units.first().map(|u| u.start) != Some(r.unit) {
357 bail!(
358 "the journal of {} records a partially extracted file that is not the next one \
359 in the archive. The archive will not be modified",
360 job.storage.primary().display()
361 );
362 }
363 job.resume = Some(r.clone());
364 }
365 Ok(job)
366 }
367
368 fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
369 let mut units = opened.units;
370 let len = storage.original_len();
374 if opened.tail_start > len || units.iter().any(|u| u.start >= len) {
375 return Err(archive::Damaged(anyhow!(
376 "this archive records data past the end of the file, so it is damaged or \
377 incomplete. Nothing was modified"
378 ))
379 .into());
380 }
381 units.retain(|u| u.start < top);
382 units.sort_by_key(|u| std::cmp::Reverse(u.start));
383 if units.windows(2).any(|w| w[0].start == w[1].start) {
387 bail!(
388 "two parts of this archive start at the same offset, so extracting it in place \
389 could destroy data before it is extracted; extraction refused"
390 );
391 }
392 let total = units
393 .iter()
394 .flat_map(|u| &u.items)
395 .try_fold(0u64, |sum, i| sum.checked_add(i.size));
396 if total.is_none_or(|t| t > MAX_TOTAL_SIZE) {
397 return Err(archive::Damaged(anyhow!(
398 "the file sizes recorded in this archive add up to more than any disk can hold, \
399 so the archive is damaged. Nothing was modified"
400 ))
401 .into());
402 }
403
404 let mut seen = HashSet::new();
405 for item in units.iter().flat_map(|u| &u.items) {
406 for part in item.path.iter() {
407 if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
408 bail!(
409 "'{}' cannot be created at this location: {why}. The archive was not modified",
410 item.path.display()
411 );
412 }
413 }
414 if item.kind != Kind::Dir && !seen.insert(item.path.as_path()) {
415 bail!(
416 "'{}' appears more than once in the archive; extraction refused",
417 item.path.display()
418 );
419 }
420 }
421 Ok(Self {
422 storage,
423 format_name: opened.name,
424 format: opened.format,
425 units,
426 tail_start: opened.tail_start,
427 top,
428 punch: OnceLock::new(),
429 resume: None,
430 started: false,
431 case_clashes: Box::default(),
432 })
433 }
434
435 pub(crate) fn check_case(&self, out: &Path) -> Result<()> {
439 let clashes = &self.case_clashes;
440 check_case_record(out, &clashes.recorded, clashes.recorded_beyond_ascii)?;
441 if let Some((a, b)) = clashes.beyond_ascii.as_ref().filter(|_| normalizes_names()) {
442 bail!(
443 "'{}' and '{}' differ only in case, and with characters outside ASCII this \
444 system may treat them as one file on any volume; extraction refused. Extract \
445 this archive with another program",
446 a.display(),
447 b.display()
448 );
449 }
450 let met_in = &clashes.met_in;
451 if met_in.len() > MAX_CASE_FOLDERS {
452 bail!(
453 "this archive has names that differ only in case in {} folders, more than \
454 HatchZip can keep track of; extraction refused. Extract this archive with \
455 another program",
456 met_in.len()
457 );
458 }
459 let folders = met_in.keys().map(PathBuf::as_path);
460 if let Some((met, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
461 let (a, b) = &met_in[met];
462 bail!(
463 "'{}' and '{}' differ only in case, and {} is not known to keep such names \
464 apart; extraction refused. Extract to a folder on a case-sensitive filesystem, \
465 or with another program",
466 a.display(),
467 b.display(),
468 nearest.display()
469 );
470 }
471 Ok(())
472 }
473
474 pub(crate) fn case_folders(&self) -> Vec<PathBuf> {
476 self.case_clashes.met_in.keys().cloned().collect()
477 }
478
479 pub(crate) fn case_beyond_ascii(&self) -> bool {
480 self.case_clashes.beyond_ascii.is_some()
481 }
482
483 fn check_layout(&self) -> Result<CaseClashes> {
496 let key = |p: &Path| p.to_string_lossy().to_lowercase();
497 let items = || self.units.iter().flat_map(|u| &u.items);
498 if let Some(item) = items().find(|i| {
502 i.path
503 .iter()
504 .any(|c| c.to_string_lossy().to_lowercase().ends_with(PART_SUFFIX))
505 }) {
506 bail!(
507 "'{}' uses a name ending in {PART_SUFFIX}, which HatchZip gives a file while it \
508 writes it, so extraction is refused. Extract this archive with another program. \
509 Nothing was modified",
510 item.path.display()
511 );
512 }
513 let mut folders: HashMap<&Path, Option<&Path>> = HashMap::new();
516 for item in items() {
517 if item.kind == Kind::Dir {
518 folders.insert(&item.path, None);
519 }
520 for parent in item.path.ancestors().skip(1) {
521 if parent.as_os_str().is_empty() {
522 break;
523 }
524 folders.entry(parent).or_insert(Some(&item.path));
525 }
526 }
527 let files: HashSet<&Path> = items()
528 .filter(|i| i.kind == Kind::File)
529 .map(|i| i.path.as_path())
530 .collect();
531 for item in items() {
532 let what = match &item.kind {
533 Kind::Dir => continue,
534 Kind::File => "a file",
535 Kind::Symlink => "a symbolic link",
536 Kind::HardLink(_) => "a hard link",
537 };
538 match folders.get(item.path.as_path()) {
539 Some(None) => bail!(
540 "'{}' is both {what} and a folder in the archive; extraction refused",
541 item.path.display()
542 ),
543 Some(Some(inside)) => bail!(
544 "'{}' is {what}, but '{}' requires a folder at that location; extraction \
545 refused",
546 item.path.display(),
547 inside.display()
548 ),
549 None => {}
550 }
551 if let Kind::HardLink(target) = &item.kind
552 && !files.contains(target.as_path())
553 {
554 bail!(
555 "hard link '{}' points to '{}', which is not a file in the archive; \
556 extraction refused",
557 item.path.display(),
558 target.display()
559 );
560 }
561 }
562 let mut names: Vec<(String, &Path, bool)> = items()
563 .filter(|i| i.kind != Kind::Dir)
564 .map(|i| (key(&i.path), i.path.as_path(), true))
565 .chain(folders.keys().map(|f| (key(f), *f, false)))
566 .collect();
567 names.sort_unstable();
568 Ok(CaseClashes::of(&names))
569 }
570
571 pub fn punch_support(&self) -> Option<u64> {
576 *self.punch.get_or_init(|| {
577 if test_knob("HATCHZIP_NO_PUNCH").is_some() {
578 return None;
579 }
580 let dir = match self.storage.primary().parent() {
581 Some(d) if !d.as_os_str().is_empty() => d,
582 _ => Path::new("."),
583 };
584 fsutil::can_punch(dir).then(|| platform::punch_granule(dir))
585 })
586 }
587
588 pub fn encrypted(&self) -> bool {
589 self.units.iter().any(|u| u.encrypted)
590 }
591
592 pub fn is_stream(&self) -> bool {
594 self.format.solid().is_some()
595 }
596
597 pub fn kept_whole(&self, reclaims: bool) -> bool {
601 self.is_stream() && reclaims && self.punch_support().is_none()
602 }
603
604 pub fn check_password(&self) -> Result<()> {
609 const ENOUGH: u64 = 64 * 1024 * 1024;
610 let Some(unit) = self.smallest_encrypted() else {
611 return Ok(());
612 };
613 let left = match self.format.password_check() {
614 PasswordCheck::Headers => return self.format.prove_password(),
615 PasswordCheck::Sample => ENOUGH,
616 PasswordCheck::WholeUnit => u64::MAX,
620 };
621 let mut worker = self.format.worker(1)?;
622 let mut sink = ProbeSink {
623 left,
624 buf: vec![0; BUF_SIZE],
625 };
626 match worker.extract(unit, &mut sink) {
627 Ok(()) => Ok(()),
628 Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
629 Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
630 Err(_) => Err(archive::WrongPassword.into()),
631 }
632 }
633
634 fn smallest_encrypted(&self) -> Option<&Unit> {
637 self.units
638 .iter()
639 .filter(|u| u.encrypted)
640 .min_by_key(|u| (u.size() == 0, u.size()))
641 }
642
643 pub fn slow_password_check(&self) -> Option<(&Path, u64)> {
647 if !self.encrypted() || self.format.password_check() != PasswordCheck::WholeUnit {
648 return None;
649 }
650 let unit = self.smallest_encrypted()?;
651 Some((unit.items.first()?.path.as_path(), unit.size()))
652 }
653
654 pub fn in_place_refusal(&self) -> Option<String> {
657 self.format.refuses_in_place().or_else(|| {
658 self.storage.hard_linked().map(|path| {
659 format!(
660 "{} has another hard link, which extracting in place would empty as well",
661 path.display()
662 )
663 })
664 })
665 }
666
667 pub fn item_count(&self) -> usize {
668 self.units.iter().map(|u| u.items.len()).sum()
669 }
670
671 pub fn remaining_size(&self) -> u64 {
672 let done = self.resume.as_ref().map_or(0, |r| r.written);
673 self.units
674 .iter()
675 .fold(0u64, |sum, u| sum.saturating_add(u.size()))
676 .saturating_sub(done)
677 }
678
679 fn resumed(&self, i: usize) -> Option<&Resume> {
681 self.resume
682 .as_ref()
683 .filter(|r| r.unit == self.units[i].start)
684 }
685
686 fn stream_of(&self, i: usize) -> Option<Stream> {
689 let unit = &self.units[i];
690 match unit.items.as_slice() {
691 [item] if item.kind == Kind::File && !unit.encrypted => {
692 self.format.stream(unit).ok().flatten()
693 }
694 _ => None,
695 }
696 }
697
698 fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
702 if self.resumed(i).is_some() {
703 return self.stream_of(i);
704 }
705 if !reclaims || self.units[i].size() < stream_threshold() {
706 return None;
707 }
708 self.punch_support()?;
709 self.stream_of(i)
710 }
711
712 fn span(&self, i: usize) -> u64 {
715 let end = if i == 0 {
716 self.top
717 } else {
718 self.units[i - 1].start
719 };
720 end - self.units[i].start
721 }
722
723 pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
729 let tail = self.storage.original_len().saturating_sub(self.tail_start) as i128;
730 let mut extra: i128 = if fresh { tail } else { 0 };
731 let mut peak = extra;
732 for (i, u) in self.units.iter().enumerate() {
733 let span = self.span(i) as i128;
734 if let Some(solid) = self.format.solid() {
735 let (rise, net) = self.solid_cost(i, solid.profile(), span, reclaims);
736 peak = peak.max(extra + rise);
737 extra += net;
738 continue;
739 }
740 if let Some(s) = self.streams(i, reclaims) {
741 let (rise, net) = self.stream_cost(i, &s, span, reclaims);
742 peak = peak.max(extra + rise);
743 extra += net;
744 continue;
745 }
746 let on_disk = on_disk(u) as i128;
747 peak = peak.max(extra + on_disk);
748 extra += on_disk;
749 if reclaims {
750 extra -= span;
751 }
752 }
753 if reclaims {
754 let stub = self.units.last().map_or(self.top, |u| u.start);
757 extra -= stub as i128 + tail;
758 }
759 (peak.max(0) as u64, extra)
760 }
761
762 fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
777 let at = self.resumed(i);
778 let done = at.map_or(0, |r| r.written / 4096 * 4096);
781 let out_left = on_disk(&self.units[i]).saturating_sub(done) as i128;
782 let read_to = at.map_or(s.data_start, |r| r.bit / 8);
783 let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
784 let freed = read_to.saturating_sub(s.data_start) as i128;
788 let net = if reclaims {
789 out_left - (span - freed)
790 } else {
791 out_left
792 };
793 let rise = match self.punch_support() {
794 Some(granule) if reclaims => {
795 let slack = match s.codec {
796 Codec::Stored => 0,
797 Codec::Deflate => out_left / 1024,
798 };
799 let step = (stream_step() + BUF_SIZE as u64 + 2 * granule) as i128;
800 ((out_left - data_left).max(0) + slack + step).min(out_left)
801 }
802 _ => out_left,
803 };
804 (rise, net)
805 }
806
807 fn solid_cost(&self, i: usize, p: &Profile, span: i128, reclaims: bool) -> (i128, i128) {
818 let out_left = (p.files + p.links) as i128;
819 let freed = self.resumed(i).map_or(0, |r| r.bit / 8) as i128;
821 let net = if reclaims {
822 out_left - (span - freed)
823 } else {
824 out_left
825 };
826 let rise = match self.punch_support() {
827 Some(granule) if reclaims => {
828 let ahead = stream_step() + p.gap + BUF_SIZE as u64 + 2 * granule;
829 (p.lead.max(0) + ahead as i128).min(p.files as i128)
830 }
831 _ => out_left,
834 };
835 (rise.max(net), net)
836 }
837
838 fn open_entry(&self) -> Option<&Item> {
841 let r = self.resume.as_ref()?;
842 let inside = match &r.stream {
843 Some(s) => matches!(s.at, TarAt::File { .. }),
844 None => true,
845 };
846 if !inside {
847 return None;
848 }
849 self.units.first().and_then(|u| u.items.first())
850 }
851
852 pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
860 if !self.started {
861 return Vec::new();
862 }
863 let open = self.open_entry().is_some();
864 let mut found = Vec::new();
865 for (i, u) in self.units.iter().enumerate() {
866 for (k, item) in u.items.iter().enumerate() {
867 if item.kind != Kind::File || (open && i == 0 && k == 0) {
868 continue;
869 }
870 let dest = out.join(&item.path);
871 for p in [part_path(&dest), dest] {
872 if let Ok(m) = fs::symlink_metadata(&p)
873 && m.is_file()
874 {
875 found.push((p, m.len().next_multiple_of(4096)));
876 }
877 }
878 }
879 }
880 found
881 }
882
883 pub fn past_resume_point(&self, out: &Path) -> u64 {
886 let (Some(r), Some(item)) = (self.resume.as_ref(), self.open_entry()) else {
887 return 0;
888 };
889 let dest = out.join(&item.path);
890 [part_path(&dest), dest]
891 .iter()
892 .find_map(|p| fs::metadata(p).ok())
893 .map_or(0, |m| {
894 (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
895 })
896 }
897
898 pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
901 let failures = if self.format.serial() {
902 self.verify_serial(on_bytes)?
903 } else {
904 self.verify_parallel(on_bytes)
905 };
906 if failures.is_empty() {
907 return Ok(());
908 }
909 let mut msg = format!("{} damaged:", failures.len());
910 for f in failures.iter().take(10) {
911 msg.push_str("\n ");
912 msg.push_str(f);
913 }
914 Err(anyhow!(msg))
915 }
916
917 fn verify_serial(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<Vec<String>> {
919 let mut worker = self.format.worker(1)?;
920 let mut sink = VerifySink {
921 on_bytes,
922 buf: vec![0; BUF_SIZE],
923 };
924 Ok(self
925 .units
926 .iter()
927 .rev()
928 .filter_map(|u| worker.extract(u, &mut sink).err())
929 .map(|e| format!("{e:#}"))
930 .collect())
931 }
932
933 fn verify_parallel(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Vec<String> {
934 let threads = threads_per_unit(self.units.len());
935 self.units
936 .par_iter()
937 .map_init(
938 || {
939 (
940 self.format.worker(threads),
941 VerifySink {
942 on_bytes,
943 buf: vec![0; BUF_SIZE],
944 },
945 )
946 },
947 |(worker, sink), unit| {
948 let mut run = || -> Result<()> {
949 let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
950 w.extract(unit, sink)
951 };
952 run().err().map(|e| format!("{e:#}"))
953 },
954 )
955 .flatten()
956 .collect()
957 }
958}
959
960fn threads_per_unit(units: usize) -> u32 {
961 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
962 (cores / units.max(1)).max(1) as u32
963}
964
965const PART_SUFFIX: &str = ".hatchzip-part";
967
968pub(crate) fn part_path(dest: &Path) -> PathBuf {
969 let mut part = dest.as_os_str().to_owned();
970 part.push(PART_SUFFIX);
971 PathBuf::from(part)
972}
973
974fn create_part(part: &Path) -> Result<File> {
979 platform::create_new_no_follow(part).map_err(|e| {
980 if e.kind() == io::ErrorKind::AlreadyExists {
981 anyhow!(
982 "{} already exists, and HatchZip does not replace a file it did not create. \
983 Move it, then run the extraction again",
984 part.display()
985 )
986 } else {
987 anyhow::Error::new(e).context(format!("creating {}", part.display()))
988 }
989 })
990}
991
992fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
995 if written == 0 {
996 return create_part(part);
997 }
998 if fs::symlink_metadata(part).is_err() && fs::symlink_metadata(dest).is_ok() {
999 fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
1002 }
1003 let mut file = match platform::open_existing_no_follow(part) {
1004 Ok(f) => f,
1005 Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
1006 "{} is missing, and the archive data it was extracted from is already released, so \
1007 this file cannot be completed",
1008 part.display()
1009 ),
1010 Err(e) => return Err(e).with_context(|| format!("reopening {}", part.display())),
1011 };
1012 if file.metadata()?.len() < written {
1013 bail!(
1014 "{} is shorter than when its progress was saved; the extraction cannot continue",
1015 part.display()
1016 );
1017 }
1018 file.set_len(written)?;
1019 file.seek(SeekFrom::Start(written))?;
1020 Ok(file)
1021}
1022
1023struct OpenFile {
1025 item: Item,
1026 dest: PathBuf,
1027 part: PathBuf,
1028 file: File,
1029 written: u64,
1030}
1031
1032impl OpenFile {
1033 fn finish(self) -> Result<()> {
1035 if self.written != self.item.size {
1036 bail!("it is smaller than the archive records");
1037 }
1038 if let Some(t) = self.item.mtime {
1039 self.file.set_modified(t)?;
1040 }
1041 platform::apply_mode(&self.file, self.item.mode)?;
1042 if platform::SYNC_EACH_FILE {
1043 self.file.sync_all()?;
1044 }
1045 drop(self.file);
1046 fs::rename(&self.part, &self.dest)?;
1047 Ok(())
1048 }
1049}
1050
1051fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
1055 let n = written.min(resumable::WINDOW as u64);
1056 let mut window = vec![0; n as usize];
1057 file.seek(SeekFrom::Start(written - n))?;
1058 file.read_exact(&mut window)?;
1059 file.seek(SeekFrom::Start(written))?;
1060 Ok(window)
1061}
1062
1063pub struct Progress {
1064 pub on_bytes: Box<dyn Fn(u64) + Sync>,
1065 pub on_commit: Box<dyn Fn(u64) + Sync>,
1066}
1067
1068pub enum Outcome {
1069 Finished,
1070 Paused,
1071}
1072
1073pub struct Run<'a> {
1074 pub job: Job,
1075 pub journal: Journal,
1076 pub paths: Paths,
1077 pub stop: &'a AtomicBool,
1078 pub progress: Progress,
1079 pub keep_free: u64,
1081}
1082
1083impl Run<'_> {
1084 pub fn execute(mut self) -> Result<Outcome> {
1085 let out = self.journal.output.clone();
1086 fs::create_dir_all(&out)
1087 .with_context(|| format!("creating output folder {}", out.display()))?;
1088
1089 let reclaims =
1092 !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
1093 if self.journal.keep {
1094 self.job.storage.protect();
1095 }
1096 if let Some(r) = self.journal.replace.as_mut()
1097 && !r.moved
1098 {
1099 replace::set_aside(&self.job, &out)?;
1100 r.moved = true;
1101 self.journal.save(&self.paths)?;
1102 self.job.started = true;
1103 }
1104 let mut next = 0;
1105 while next < self.job.units.len() {
1106 if self.stop.load(Ordering::Relaxed) {
1107 return Ok(Outcome::Paused);
1108 }
1109 if let Some(solid) = self.job.format.solid() {
1110 let walk = solid.walk(self.job.resumed(next))?;
1111 let Some(links) = self.stream_solid(next, walk, reclaims, &out)? else {
1112 return Ok(Outcome::Paused);
1113 };
1114 self.commit(next, next + 1, links, &out)?;
1115 next += 1;
1116 continue;
1117 }
1118 if let Some(stream) = self.stream_now(next, reclaims, &out)? {
1119 if !self.stream_unit(next, &stream, &out)? {
1120 return Ok(Outcome::Paused);
1121 }
1122 self.commit(next, next + 1, Vec::new(), &out)?;
1123 next += 1;
1124 continue;
1125 }
1126 let end = self.next_batch(next, &out, reclaims)?;
1127 let batch = &self.job.units[next..end];
1128
1129 let Some(links) = self.extract_batch(batch, &out)? else {
1130 return Ok(Outcome::Paused);
1131 };
1132 self.commit(next, end, links, &out)?;
1133 next = end;
1134 }
1135
1136 self.finish(&out)?;
1137 Ok(Outcome::Finished)
1138 }
1139
1140 fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
1143 let batch = &self.job.units[start..end];
1144 platform::sync_batch(out).context("flushing extracted files to disk")?;
1147 if platform::SYNC_EACH_FILE {
1148 let dirs: HashSet<PathBuf> = batch
1151 .iter()
1152 .flat_map(|u| &u.items)
1153 .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
1154 .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
1155 .collect();
1156 for d in &dirs {
1157 fsutil::sync_dir(d)?;
1158 }
1159 }
1160 crash_point("after-extract");
1161
1162 if self.journal.resume.is_none() {
1169 remove_after_extract(batch, out);
1170 verify_extracted(batch, out)?;
1171 }
1172
1173 let new_len = batch.last().expect("batches are never empty").start;
1174 self.journal.committed_len = new_len;
1175 self.journal.links.extend(links);
1176 self.journal.resume = None;
1179 self.journal.done = end == self.job.units.len();
1180 self.job.resume = None;
1181 self.journal.save(&self.paths)?;
1182 crash_point("after-journal");
1183
1184 if self.journal.keep {
1185 return Ok(());
1186 }
1187 self.job
1188 .storage
1189 .set_len(new_len)
1190 .context("shrinking the archive")?;
1191 (self.progress.on_commit)(new_len);
1192 Ok(())
1193 }
1194
1195 fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
1200 if self.job.resumed(i).is_some() {
1201 return match self.job.stream_of(i) {
1202 Some(s) => Ok(Some(s)),
1203 None => bail!(
1204 "the journal records '{}' as partially extracted, but it cannot be resumed",
1205 self.job.units[i].items[0].path.display()
1206 ),
1207 };
1208 }
1209 let Some(stream) = self.job.streams(i, reclaims) else {
1210 return Ok(None);
1211 };
1212 if always_stream() {
1213 return Ok(Some(stream));
1214 }
1215 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1216 Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
1217 }
1218
1219 fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
1229 let unit_start = self.job.units[i].start;
1230 let item = self.job.units[i].items[0].clone();
1231 let dest = out.join(&item.path);
1232 let part = part_path(&dest);
1233 let at = self.job.resumed(i).cloned().unwrap_or(Resume {
1234 unit: unit_start,
1235 written: 0,
1236 bit: stream.data_start * 8,
1237 crc: 0,
1238 stream: None,
1239 });
1240 let started_here = at.written == 0;
1241 let what = || format!("extracting '{}'", item.path.display());
1242 if let Some(parent) = dest.parent() {
1243 fs::create_dir_all(parent).with_context(what)?;
1244 }
1245 let file = open_part(&dest, &part, at.written).with_context(what)?;
1248 let result = self
1249 .stream_file(&item, stream, at, file, &dest, &part, out)
1250 .with_context(what);
1251 if result.is_err() && started_here && self.journal.resume.is_none() {
1252 let _ = fs::remove_file(&part);
1254 }
1255 result
1256 }
1257
1258 #[allow(clippy::too_many_arguments)]
1259 fn stream_file(
1260 &mut self,
1261 item: &Item,
1262 stream: &Stream,
1263 at: Resume,
1264 mut file: File,
1265 dest: &Path,
1266 part: &Path,
1267 out: &Path,
1268 ) -> Result<bool> {
1269 let window = match stream.codec {
1270 Codec::Stored => Vec::new(),
1271 Codec::Deflate => read_window(&mut file, at.written)?,
1272 };
1273 let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
1274 let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
1275 let mut written = at.written;
1276 let mut since_point = 0;
1277 let step = stream_step();
1278 let mut punching = self.job.punch_support();
1279 let what = format!("'{}'", item.path.display());
1280 self.ensure_room(out, &what, item.size - written, punching)?;
1281
1282 let mut buf = vec![0; BUF_SIZE];
1283 loop {
1284 if self.stop.load(Ordering::Relaxed) {
1285 return Ok(false);
1286 }
1287 let n = decoder.read(&mut buf)?;
1288 if n == 0 {
1289 break;
1290 }
1291 written += n as u64;
1292 if written > item.size {
1293 bail!("it is larger than the archive records");
1294 }
1295 file.write_all(&buf[..n])?;
1296 crc.update(&buf[..n]);
1297 (self.progress.on_bytes)(n as u64);
1298 since_point += n as u64;
1299
1300 if since_point < step || written == item.size {
1301 continue;
1302 }
1303 match decoder.restart_point() {
1304 Some(bit) => {
1305 let point = Resume {
1306 unit: at.unit,
1307 written,
1308 bit,
1309 crc: crc.clone().finalize(),
1310 stream: None,
1311 };
1312 punching = self.save_point(&file, part, out, point, stream, punching)?;
1313 since_point = 0;
1314 self.ensure_room(out, &what, item.size - written, punching)?;
1315 }
1316 None => {
1321 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1322 if avail < 2 * BUF_SIZE as u64 {
1323 bail!(
1324 "not enough disk space to continue: the compressed data of this entry has \
1325 no resume point in the last {}, so its archive space cannot be \
1326 released yet. {} more is required (the remainder of this file). \
1327 Progress is saved; free up space and resume the extraction.",
1328 human(since_point),
1329 human(item.size - written),
1330 );
1331 }
1332 }
1333 }
1334 }
1335 if written != item.size {
1336 bail!("it is smaller than the archive records");
1337 }
1338 if let Some(expected) = stream.crc
1339 && crc.finalize() != expected
1340 {
1341 bail!("its data is damaged (CRC mismatch)");
1342 }
1343 if let Some(t) = item.mtime {
1344 file.set_modified(t)?;
1345 }
1346 platform::apply_mode(&file, item.mode)?;
1347 file.sync_all()?;
1348 drop(file);
1349 fs::rename(part, dest)?;
1353 Ok(true)
1354 }
1355
1356 fn save_point(
1359 &mut self,
1360 file: &File,
1361 part: &Path,
1362 out: &Path,
1363 point: Resume,
1364 stream: &Stream,
1365 punching: Option<u64>,
1366 ) -> Result<Option<u64>> {
1367 file.sync_all()
1368 .context("flushing the extracted file to disk")?;
1369 let mut dir = part.parent();
1372 while let Some(d) = dir {
1373 fsutil::sync_dir(d)?;
1374 if d == out {
1375 break;
1376 }
1377 dir = d.parent();
1378 }
1379 crash_point("stream-after-sync");
1380
1381 self.journal.resume = Some(point.clone());
1382 self.journal.save(&self.paths)?;
1383 self.job.resume = Some(point.clone());
1384 crash_point("stream-after-journal");
1385
1386 if punching.is_some()
1389 && !self
1390 .job
1391 .storage
1392 .punch(stream.data_start, point.bit / 8)
1393 .context("freeing extracted archive bytes")?
1394 {
1395 return Ok(None);
1398 }
1399 crash_point("stream-after-punch");
1400 Ok(punching)
1401 }
1402
1403 fn stream_solid(
1416 &mut self,
1417 i: usize,
1418 mut walk: Box<dyn SolidWalker>,
1419 reclaims: bool,
1420 out: &Path,
1421 ) -> Result<Option<Vec<Link>>> {
1422 let unit = self.job.units[i].start;
1423 let step = stream_step();
1424 let mut punching = self.job.punch_support().filter(|_| reclaims);
1427 let profile = match self.job.format.solid() {
1428 Some(s) => s.profile().clone(),
1429 None => bail!("the archive is not a compressed stream"),
1430 };
1431 let mut left = profile.files;
1432 let mut punched = 0;
1436 let mut since_point = 0u64;
1437 let mut checked = 0u64;
1438 let mut open: Option<OpenFile> = None;
1439 let mut links = Vec::new();
1440 let mut dirs = HashSet::new();
1441 self.ensure_room(out, "the archive", left, punching)?;
1442
1443 loop {
1444 if self.stop.load(Ordering::Relaxed) {
1445 return Ok(None);
1446 }
1447 match walk.next(BUF_SIZE)? {
1448 Event::Entry { item, link, done } => {
1449 let dest = out.join(&item.path);
1450 let what = || format!("extracting '{}'", item.path.display());
1451 match &item.kind {
1452 Kind::Dir => {
1453 fs::create_dir_all(&dest).with_context(what)?;
1454 dirs.insert(dest);
1455 }
1456 Kind::Symlink => {
1457 let target = String::from_utf8(link.unwrap_or_default())
1458 .map_err(|_| anyhow!("the link target is not valid UTF-8"))
1459 .with_context(what)?;
1460 links.push(Link {
1461 path: item.path.clone(),
1462 target: PathBuf::from(target),
1463 hard: false,
1464 });
1465 }
1466 Kind::HardLink(target) => links.push(Link {
1467 path: item.path.clone(),
1468 target: target.clone(),
1469 hard: true,
1470 }),
1471 Kind::File => {
1472 if let Some(parent) = dest.parent() {
1473 fs::create_dir_all(parent).with_context(what)?;
1474 }
1475 let part = part_path(&dest);
1476 let file = open_part(&dest, &part, done).with_context(what)?;
1477 open = Some(OpenFile {
1478 item,
1479 dest,
1480 part,
1481 file,
1482 written: done,
1483 });
1484 }
1485 }
1486 }
1487 Event::Data(bytes) => {
1488 let f = open
1489 .as_mut()
1490 .ok_or_else(|| anyhow!("the tar stream holds data outside a file"))?;
1491 f.file
1492 .write_all(bytes)
1493 .with_context(|| format!("extracting '{}'", f.item.path.display()))?;
1494 let n = bytes.len() as u64;
1495 f.written += n;
1496 since_point += n;
1497 left = left.saturating_sub(n);
1498 (self.progress.on_bytes)(n);
1499 if punching.is_some()
1503 && since_point >= step
1504 && since_point - checked >= BUF_SIZE as u64
1505 {
1506 checked = since_point;
1507 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1508 if avail < 2 * BUF_SIZE as u64 {
1509 bail!(
1510 "not enough disk space to continue: the compressed data has no \
1511 resume point in the last {}, so its space cannot be released \
1512 yet. {} more is required (the remainder of the archive). \
1513 Progress is saved; free up space and resume the extraction.",
1514 human(since_point),
1515 human(left),
1516 );
1517 }
1518 }
1519 }
1520 Event::FileEnd => {
1521 let f = open
1522 .take()
1523 .ok_or_else(|| anyhow!("the tar stream ends a file it never began"))?;
1524 let pad = f.item.size.next_multiple_of(4096) - f.item.size;
1525 let path = f.item.path.clone();
1526 let parent = f.dest.parent().map(Path::to_path_buf);
1527 f.finish()
1528 .with_context(|| format!("extracting '{}'", path.display()))?;
1529 dirs.extend(parent);
1530 since_point += pad;
1531 left = left.saturating_sub(pad);
1532 }
1533 Event::Point => {
1534 if since_point < step {
1535 continue;
1536 }
1537 let mut point = walk.point()?;
1538 point.unit = unit;
1539 punching = self.solid_point(
1540 point,
1541 open.as_ref(),
1542 &mut links,
1543 &mut dirs,
1544 out,
1545 punching,
1546 &mut punched,
1547 )?;
1548 since_point = 0;
1549 checked = 0;
1550 self.ensure_room(out, "the archive", left, punching)?;
1551 }
1552 Event::End => break,
1553 }
1554 }
1555 if open.is_some() {
1556 bail!("the tar stream ended inside a file");
1557 }
1558 Ok(Some(links))
1559 }
1560
1561 #[allow(clippy::too_many_arguments)]
1564 fn solid_point(
1565 &mut self,
1566 point: Resume,
1567 open: Option<&OpenFile>,
1568 links: &mut Vec<Link>,
1569 dirs: &mut HashSet<PathBuf>,
1570 out: &Path,
1571 punching: Option<u64>,
1572 punched: &mut u64,
1573 ) -> Result<Option<u64>> {
1574 if let Some(f) = open {
1575 f.file
1576 .sync_all()
1577 .context("flushing the extracted file to disk")?;
1578 dirs.extend(f.part.parent().map(Path::to_path_buf));
1579 }
1580 platform::sync_batch(out).context("flushing extracted files to disk")?;
1581 if platform::SYNC_EACH_FILE {
1582 let mut done = HashSet::new();
1585 for d in dirs.drain() {
1586 let mut dir = Some(d.as_path());
1587 while let Some(d) = dir {
1588 if !done.insert(d.to_path_buf()) {
1589 break;
1590 }
1591 fsutil::sync_dir(d)?;
1592 if d == out {
1593 break;
1594 }
1595 dir = d.parent();
1596 }
1597 }
1598 }
1599 dirs.clear();
1600 crash_point("stream-after-sync");
1601
1602 let byte = point.bit / 8;
1603 self.journal.links.append(links);
1604 self.journal.resume = Some(point.clone());
1605 self.journal.save(&self.paths)?;
1606 self.job.resume = Some(point);
1607 crash_point("stream-after-journal");
1608
1609 if let Some(granule) = punching {
1610 if !self
1611 .job
1612 .storage
1613 .punch(*punched, byte)
1614 .context("freeing extracted archive bytes")?
1615 {
1616 return Ok(None);
1617 }
1618 *punched = byte.saturating_sub(granule);
1623 (self.progress.on_commit)(self.job.top - byte);
1624 }
1625 crash_point("stream-after-punch");
1626 Ok(punching)
1627 }
1628
1629 fn ensure_room(&self, out: &Path, what: &str, left: u64, punching: Option<u64>) -> Result<()> {
1632 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1633 let left = left.next_multiple_of(4096);
1634 let need = match punching {
1635 Some(granule) => (stream_step() + BUF_SIZE as u64 + 2 * granule).min(left),
1636 None => left,
1637 };
1638 if need > avail {
1639 bail!(
1640 "not enough disk space to continue: the next part of {} requires {} and {} is \
1641 available ({} reserved).\n{} more is required. Progress is saved; free up space \
1642 and resume the extraction.",
1643 what,
1644 human(need),
1645 human(avail),
1646 human(self.keep_free),
1647 human(need - avail),
1648 );
1649 }
1650 Ok(())
1651 }
1652
1653 fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
1656 let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1657 let units = &self.job.units;
1658 let need = on_disk;
1659 let first = need(&units[start]);
1660 if first > avail {
1661 let what = match units[start].items.as_slice() {
1664 [one] => format!("'{}'", one.path.display()),
1665 many => format!("the next block of {} files", many.len()),
1666 };
1667 bail!(
1668 "not enough disk space to continue: {what} requires {} and {} is available \
1669 ({} reserved).\n{} more is required. Progress is saved; free up space and \
1670 resume the extraction.",
1671 human(first),
1672 human(avail),
1673 human(self.keep_free),
1674 human(first - avail),
1675 );
1676 }
1677 let budget = avail.min(BATCH_MAX_BYTES.max(first));
1678 let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
1679 let mut used = 0u64;
1680 let mut end = start;
1681 while end < units.len() && end - start < max_units {
1682 let size = need(&units[end]);
1683 if end > start && used.saturating_add(size) > budget {
1684 break;
1685 }
1686 if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
1687 break;
1688 }
1689 used += size;
1690 end += 1;
1691 }
1692 Ok(end)
1693 }
1694
1695 fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
1698 let on_bytes = &*self.progress.on_bytes;
1699 if self.job.format.serial() {
1700 let mut sink = DiskSink {
1701 out,
1702 stop: self.stop,
1703 on_bytes,
1704 buf: vec![0; BUF_SIZE],
1705 links: Vec::new(),
1706 };
1707 let mut worker = self
1708 .job
1709 .format
1710 .worker(1)
1711 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1712 for unit in batch.iter().rev() {
1714 match worker.extract(unit, &mut sink) {
1715 Ok(()) => {}
1716 Err(e) if is_interrupt(&e) => return Ok(None),
1717 Err(e) => return Err(e),
1718 }
1719 }
1720 return Ok(Some(sink.links));
1721 }
1722 let threads = threads_per_unit(batch.len());
1723 let results: Vec<Result<Vec<Link>>> = batch
1724 .par_iter()
1725 .map_init(
1726 || {
1727 let sink = DiskSink {
1728 out,
1729 stop: self.stop,
1730 on_bytes,
1731 buf: vec![0; BUF_SIZE],
1732 links: Vec::new(),
1733 };
1734 (self.job.format.worker(threads), sink)
1735 },
1736 |(worker, sink), unit| {
1737 let w = worker
1738 .as_mut()
1739 .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1740 w.extract(unit, sink)?;
1741 Ok(std::mem::take(&mut sink.links))
1742 },
1743 )
1744 .collect();
1745
1746 let mut links = Vec::new();
1747 let mut interrupted = false;
1748 for r in results {
1749 match r {
1750 Ok(l) => links.extend(l),
1751 Err(e) if is_interrupt(&e) => interrupted = true,
1752 Err(e) => return Err(e),
1753 }
1754 }
1755 Ok((!interrupted).then_some(links))
1756 }
1757
1758 fn finish(self, out: &Path) -> Result<()> {
1759 make_final_links(&self.journal.links, out)?;
1760 if let Some(r) = &self.journal.replace {
1763 replace::settle(out, r)?;
1764 replace::remove(out)?;
1765 }
1766 if self.journal.keep {
1767 return self.paths.remove();
1769 }
1770 let Self { job, paths, .. } = self;
1771 let Job {
1772 storage, format, ..
1773 } = job;
1774 drop(format);
1776 let storage = Arc::try_unwrap(storage)
1777 .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
1778 storage.remove()?;
1781 paths.remove()
1782 }
1783}
1784
1785fn verify_extracted(batch: &[Unit], out: &Path) -> Result<()> {
1794 for item in batch.iter().flat_map(|u| &u.items) {
1795 if item.kind != Kind::File {
1796 continue;
1797 }
1798 let dest = out.join(&item.path);
1799 let meta = match fs::symlink_metadata(&dest) {
1801 Ok(meta) => meta,
1802 Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
1803 "'{}' disappeared while it was extracted. Antivirus software sometimes removes \
1804 files as they are written. The archive still holds it ({} bytes), so running \
1805 the same command again extracts it",
1806 item.path.display(),
1807 item.size
1808 ),
1809 Err(e) => {
1810 return Err(e).with_context(|| {
1811 format!("checking '{}' after extracting it", item.path.display())
1812 });
1813 }
1814 };
1815 if !meta.is_file() {
1816 bail!(
1817 "'{}' is no longer a file after it was extracted, but the archive has a file \
1818 there. The archive still holds it, so move what is in its place away and run \
1819 the same command again",
1820 item.path.display()
1821 );
1822 }
1823 if meta.len() != item.size {
1824 bail!(
1825 "'{}' changed while it was extracted: the archive records {} bytes, but the \
1826 file has {}. The archive still holds it, so move it away and run the same \
1827 command again",
1828 item.path.display(),
1829 item.size,
1830 meta.len()
1831 );
1832 }
1833 }
1834 Ok(())
1835}
1836
1837fn remove_after_extract(batch: &[Unit], out: &Path) {
1840 if !cfg!(debug_assertions) {
1841 return;
1842 }
1843 let Ok(rel) = std::env::var("HATCHZIP_REMOVE_AFTER_EXTRACT") else {
1844 return;
1845 };
1846 let rel = Path::new(&rel);
1847 let extracted = batch
1848 .iter()
1849 .flat_map(|u| &u.items)
1850 .any(|item| item.kind == Kind::File && item.path == rel);
1851 if extracted {
1852 let _ = fs::remove_file(out.join(rel));
1853 }
1854}
1855
1856pub fn finish_orphaned(journal: &Journal, paths: &Paths) -> Result<()> {
1859 make_final_links(&journal.links, &journal.output)?;
1860 if let Some(r) = &journal.replace {
1861 replace::settle(&journal.output, r)?;
1862 replace::remove(&journal.output)?;
1863 }
1864 if journal.done && !journal.keep {
1867 for (part, _) in &journal.parts {
1868 match fs::remove_file(part) {
1869 Err(e) if e.kind() != io::ErrorKind::NotFound => {
1870 return Err(e).with_context(|| format!("deleting {}", part.display()));
1871 }
1872 _ => {}
1873 }
1874 }
1875 }
1876 paths.remove()
1877}
1878
1879fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
1884 make_links(links, out).map_err(|e| {
1885 anyhow!(
1886 "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
1887 each one, for example by moving or renaming a folder that is in the way, then \
1888 resume the extraction to create them"
1889 )
1890 })
1891}
1892
1893pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
1897 let failed: Vec<(&Link, anyhow::Error)> = links
1898 .iter()
1899 .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
1900 .collect();
1901 if failed.is_empty() {
1902 return Ok(());
1903 }
1904 let mut msg = match failed.len() {
1905 1 => "1 link could not be created:".to_string(),
1906 n => format!("{n} links could not be created:"),
1907 };
1908 for (link, e) in failed.iter().take(10) {
1909 let kind = if link.hard {
1910 "hard link"
1911 } else {
1912 "symbolic link"
1913 };
1914 msg.push_str(&format!(
1915 "\n '{}' ({kind} to '{}'): {e:#}",
1916 link.path.display(),
1917 link.target.display()
1918 ));
1919 }
1920 if failed.len() > 10 {
1921 msg.push_str(&format!("\n and {} more", failed.len() - 10));
1922 }
1923 Err(anyhow!(msg))
1924}
1925
1926fn make_link(link: &Link, out: &Path) -> Result<()> {
1927 if let Some(via) = link_on_the_way(out, &link.path) {
1930 bail!(
1931 "'{}' is a link, and this one would be created through it",
1932 via.display()
1933 );
1934 }
1935 let path = out.join(&link.path);
1936 if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
1937 bail!("a folder already exists at this location");
1938 }
1939 if let Some(parent) = path.parent() {
1940 fs::create_dir_all(parent)?;
1941 }
1942 if link.hard {
1943 if let Some(via) = link_on_the_way(out, &link.target) {
1944 bail!(
1945 "'{}' is a link, and the target would be reached through it",
1946 via.display()
1947 );
1948 }
1949 let target = out.join(&link.target);
1950 let _ = fs::remove_file(&path);
1951 fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
1953 } else {
1954 platform::create_symlink(&path, &link.target)?;
1955 }
1956 Ok(())
1957}
1958
1959pub(crate) fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
1961 let mut ancestors: Vec<&Path> = rel
1962 .ancestors()
1963 .skip(1)
1964 .filter(|p| !p.as_os_str().is_empty())
1965 .collect();
1966 ancestors.reverse();
1967 ancestors
1968 .into_iter()
1969 .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
1970 .map(Path::to_path_buf)
1971}
1972
1973struct DiskSink<'a> {
1974 out: &'a Path,
1975 stop: &'a AtomicBool,
1976 on_bytes: &'a (dyn Fn(u64) + Sync),
1977 buf: Vec<u8>,
1978 links: Vec<Link>,
1979}
1980
1981impl Sink for DiskSink<'_> {
1982 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1983 self.write(item, data)
1984 .with_context(|| format!("extracting '{}'", item.path.display()))
1985 }
1986}
1987
1988impl DiskSink<'_> {
1989 fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1990 let dest = self.out.join(&item.path);
1991 match &item.kind {
1992 Kind::Dir => {
1993 fs::create_dir_all(&dest)?;
1994 return Ok(());
1995 }
1996 Kind::Symlink => {
1997 let mut target = Vec::new();
1998 data.take(MAX_SYMLINK).read_to_end(&mut target)?;
1999 let target = PathBuf::from(String::from_utf8(target)?);
2000 self.links.push(Link {
2001 path: item.path.clone(),
2002 target,
2003 hard: false,
2004 });
2005 return Ok(());
2006 }
2007 Kind::HardLink(target) => {
2008 self.links.push(Link {
2009 path: item.path.clone(),
2010 target: target.clone(),
2011 hard: true,
2012 });
2013 return Ok(());
2014 }
2015 Kind::File => {}
2016 }
2017
2018 if let Some(parent) = dest.parent() {
2019 fs::create_dir_all(parent)?;
2020 }
2021 let part = part_path(&dest);
2022 let dst = create_part(&part)?;
2024 let result = self.copy(item, data, dst);
2025 if result.is_err() {
2026 let _ = fs::remove_file(&part);
2027 return result;
2028 }
2029 fs::rename(&part, &dest)?;
2030 Ok(())
2031 }
2032
2033 fn copy(&mut self, item: &Item, data: &mut dyn Read, mut dst: File) -> Result<()> {
2034 let mut written = 0u64;
2035 loop {
2036 if self.stop.load(Ordering::Relaxed) {
2037 return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2038 }
2039 let n = data.read(&mut self.buf)?;
2042 if n == 0 {
2043 break;
2044 }
2045 written += n as u64;
2046 if written > item.size {
2047 bail!("it is larger than the archive records");
2048 }
2049 dst.write_all(&self.buf[..n])?;
2050 (self.on_bytes)(n as u64);
2051 }
2052 if written != item.size {
2053 bail!("it is smaller than the archive records");
2054 }
2055 if let Some(t) = item.mtime {
2056 dst.set_modified(t)?;
2057 }
2058 platform::apply_mode(&dst, item.mode)?;
2059 if platform::SYNC_EACH_FILE {
2060 dst.sync_all()?;
2061 }
2062 Ok(())
2063 }
2064}
2065
2066struct ProbeSink {
2068 left: u64,
2069 buf: Vec<u8>,
2070}
2071
2072#[derive(Debug)]
2073struct ProbeDone;
2074
2075impl std::fmt::Display for ProbeDone {
2076 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2077 f.write_str("read enough to prove the password")
2078 }
2079}
2080
2081impl std::error::Error for ProbeDone {}
2082
2083impl Sink for ProbeSink {
2084 fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
2085 loop {
2086 let n = data.read(&mut self.buf)?;
2087 if n == 0 {
2088 return Ok(());
2089 }
2090 self.left = self.left.saturating_sub(n as u64);
2091 if self.left == 0 {
2092 return Err(ProbeDone.into());
2093 }
2094 }
2095 }
2096}
2097
2098struct VerifySink<'a> {
2099 on_bytes: &'a (dyn Fn(u64) + Sync),
2100 buf: Vec<u8>,
2101}
2102
2103impl Sink for VerifySink<'_> {
2104 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2105 let mut read = 0;
2106 loop {
2107 let n = data
2108 .read(&mut self.buf)
2109 .with_context(|| format!("'{}'", item.path.display()))?;
2110 if n == 0 {
2111 break;
2112 }
2113 read += n as u64;
2114 (self.on_bytes)(n as u64);
2115 }
2116 if item.kind == Kind::File && read != item.size {
2117 bail!(
2118 "'{}' is shorter than the archive records",
2119 item.path.display()
2120 );
2121 }
2122 Ok(())
2123 }
2124}
2125
2126fn is_interrupt(e: &anyhow::Error) -> bool {
2127 e.chain()
2128 .filter_map(|c| c.downcast_ref::<io::Error>())
2129 .any(|io| io.kind() == io::ErrorKind::Interrupted)
2130}
2131
2132fn test_knob(name: &str) -> Option<u32> {
2134 if !cfg!(debug_assertions) {
2135 return None;
2136 }
2137 std::env::var(name).ok()?.parse().ok()
2138}
2139
2140pub(crate) fn crash_point(name: &str) {
2143 if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
2144 return;
2145 }
2146 static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2147 if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
2148 std::process::abort();
2149 }
2150}
2151
2152pub fn human(bytes: u64) -> String {
2153 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
2154 let mut v = bytes as f64;
2155 let mut unit = 0;
2156 while v >= 1000.0 && unit < UNITS.len() - 1 {
2157 v /= 1000.0;
2158 unit += 1;
2159 }
2160 if unit == 0 {
2161 format!("{bytes} B")
2162 } else {
2163 format!("{v:.1} {}", UNITS[unit])
2164 }
2165}
2166
2167#[cfg(test)]
2168mod tests {
2169 use super::*;
2170 use crate::archive::{Opened, Worker};
2171
2172 struct NoFormat;
2174
2175 impl Format for NoFormat {
2176 fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
2177 bail!("nothing is decoded in these tests")
2178 }
2179 }
2180
2181 #[test]
2183 fn names_meet_where_they_first_differ() {
2184 for (a, b, folder) in [
2185 ("a/Makefile", "a/makefile", "a"),
2186 ("Makefile", "makefile", ""),
2187 ("D/x", "d/x", ""),
2188 ("D", "d/inner.txt", ""),
2189 ("a/B/c/F", "a/b/c/f", "a"),
2190 ] {
2191 assert_eq!(
2192 meeting_folder(Path::new(a), Path::new(b)),
2193 Path::new(folder),
2194 "{a} and {b}"
2195 );
2196 }
2197 }
2198
2199 fn clashes(paths: &[&'static str]) -> CaseClashes {
2200 let mut names: Vec<(String, &Path, bool)> = paths
2201 .iter()
2202 .map(|p| (p.to_lowercase(), Path::new(*p), true))
2203 .collect();
2204 names.sort_unstable();
2205 CaseClashes::of(&names)
2206 }
2207
2208 #[test]
2211 fn clashes_cover_every_folder_where_names_meet() {
2212 let met = clashes(&["X/a/f", "x/A/f", "x/a/f", "other", "OTHER2"]).met_in;
2213 assert_eq!(
2214 met.keys().collect::<Vec<_>>(),
2215 [Path::new(""), Path::new("x")]
2216 );
2217 }
2218
2219 #[test]
2222 fn directory_aliases_need_no_case_separation_in_a_fileless_branch() {
2223 let tmp = tempfile::tempdir().unwrap();
2224 let path = tmp.path().join("archive.bin");
2225 fs::write(&path, [0u8; 64]).unwrap();
2226 let storage = Arc::new(Storage::open(&path, false).unwrap());
2227 let units = ["A/f", "a/F/one.txt", "a/f/two.txt"]
2228 .iter()
2229 .enumerate()
2230 .map(|(i, name)| unit(i as u64, name, 1))
2231 .collect();
2232 let job = Job::build(storage, opened(units, 64), 64).unwrap();
2233 let clashes = job.check_layout().unwrap();
2234 assert_eq!(clashes.met_in.keys().collect::<Vec<_>>(), [Path::new("")]);
2235 }
2236
2237 #[test]
2241 fn case_folders_match_every_file_file_and_file_folder_pair() {
2242 let paths = [
2243 "A/B/C", "A/B/c", "A/b/C", "A/b/c", "a/B/C", "a/B/c", "a/b/C", "a/b/c",
2244 ];
2245 for mut choices in 0..3usize.pow(paths.len() as u32) {
2246 let mut names = Vec::new();
2247 for path in paths {
2248 let kind = choices % 3;
2249 choices /= 3;
2250 if kind != 0 {
2251 names.push((path.to_lowercase(), Path::new(path), kind == 2));
2252 }
2253 }
2254 let mut expected = std::collections::BTreeSet::new();
2255 for (i, a) in names.iter().enumerate() {
2256 for b in &names[i + 1..] {
2257 if a.2 || b.2 {
2258 expected.insert(meeting_folder(a.1, b.1));
2259 }
2260 }
2261 }
2262 let clashes = CaseClashes::of(&names);
2263 assert_eq!(
2264 clashes.met_in.keys().collect::<Vec<_>>(),
2265 expected.iter().collect::<Vec<_>>(),
2266 "{names:?}"
2267 );
2268 }
2269 }
2270
2271 #[test]
2274 fn clashes_stay_linear_in_the_names() {
2275 let paths: Vec<String> = (0..4096u32)
2276 .map(|bits| {
2277 (0..12)
2278 .map(|i| if bits >> i & 1 == 1 { 'A' } else { 'a' })
2279 .collect()
2280 })
2281 .collect();
2282 let mut names: Vec<(String, &Path, bool)> = paths
2283 .iter()
2284 .enumerate()
2285 .map(|(i, p)| (p.to_lowercase(), Path::new(p), i % 2 == 0))
2286 .collect();
2287 names.sort_unstable();
2288 assert_eq!(CaseClashes::of(&names).met_in.len(), 1);
2289 }
2290
2291 #[test]
2295 fn names_beyond_ascii_are_noted_on_every_system() {
2296 assert!(clashes(&["K.txt", "\u{212a}.txt"]).beyond_ascii.is_some());
2297 assert!(clashes(&["Makefile", "makefile"]).beyond_ascii.is_none());
2298 }
2299
2300 #[test]
2303 fn the_nearest_existing_folder_decides() {
2304 let tmp = tempfile::TempDir::new().unwrap();
2305 let out = tmp.path().join("out");
2306 fs::create_dir_all(out.join("mounted")).unwrap();
2307 let asked = std::cell::RefCell::new(Vec::new());
2308 let result = first_not_apart(
2309 &out,
2310 [
2311 Path::new(""),
2312 Path::new("new/deep"),
2313 Path::new("mounted/new"),
2314 ],
2315 |dir| {
2316 asked.borrow_mut().push(dir.to_path_buf());
2317 dir != out.join("mounted")
2318 },
2319 );
2320 assert_eq!(
2321 result,
2322 Some((Path::new("mounted/new"), out.join("mounted")))
2323 );
2324 assert_eq!(*asked.borrow(), [out.clone(), out.join("mounted")]);
2325 }
2326
2327 fn unit(start: u64, name: &str, size: u64) -> Unit {
2328 Unit {
2329 start,
2330 key: 0,
2331 items: vec![Item {
2332 path: name.into(),
2333 size,
2334 kind: Kind::File,
2335 mode: None,
2336 mtime: None,
2337 }],
2338 encrypted: false,
2339 }
2340 }
2341
2342 fn storage(test: &str) -> (PathBuf, Arc<Storage>) {
2344 let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2345 fs::create_dir_all(&dir).unwrap();
2346 let path = dir.join("archive.bin");
2347 fs::write(&path, [0u8; 64]).unwrap();
2348 let storage = Arc::new(Storage::open(&path, false).unwrap());
2349 (dir, storage)
2350 }
2351
2352 fn opened(units: Vec<Unit>, tail_start: u64) -> Opened {
2353 Opened {
2354 name: "test",
2355 format: Box::new(NoFormat),
2356 units,
2357 tail_start,
2358 }
2359 }
2360
2361 fn scratch(test: &str) -> PathBuf {
2363 let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2364 let _ = fs::remove_dir_all(&dir);
2365 fs::create_dir_all(&dir).unwrap();
2366 dir
2367 }
2368
2369 #[test]
2372 fn a_batch_that_is_all_on_disk_verifies() {
2373 let out = scratch("verify-complete");
2374 fs::create_dir_all(out.join("game")).unwrap();
2375 fs::write(out.join("game/a"), b"hello").unwrap();
2376 fs::write(out.join("game/empty"), b"").unwrap();
2377 let batch = [unit(10, "game/a", 5), unit(20, "game/empty", 0)];
2378 assert!(verify_extracted(&batch, &out).is_ok());
2379 fs::remove_dir_all(&out).unwrap();
2380 }
2381
2382 #[test]
2383 fn a_missing_file_fails_verification() {
2384 let out = scratch("verify-missing");
2385 let err = verify_extracted(&[unit(0, "game/gone", 12)], &out)
2386 .err()
2387 .unwrap();
2388 let text = err.to_string();
2389 assert!(text.contains("game/gone"), "{text}");
2390 assert!(text.contains("disappeared"), "{text}");
2391 assert!(text.contains("12 bytes"), "{text}");
2392 fs::remove_dir_all(&out).unwrap();
2393 }
2394
2395 #[test]
2396 fn a_file_of_the_wrong_size_fails_verification() {
2397 let out = scratch("verify-size");
2398 fs::create_dir_all(out.join("game")).unwrap();
2399 fs::write(out.join("game/a"), b"abc").unwrap();
2400 let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2401 .err()
2402 .unwrap();
2403 let text = err.to_string();
2404 assert!(text.contains("game/a"), "{text}");
2405 assert!(text.contains("records 5 bytes"), "{text}");
2406 assert!(text.contains("has 3"), "{text}");
2407 fs::remove_dir_all(&out).unwrap();
2408 }
2409
2410 #[test]
2411 fn a_folder_at_the_name_of_a_file_fails_verification() {
2412 let out = scratch("verify-folder");
2413 fs::create_dir_all(out.join("game/a")).unwrap();
2414 let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2415 .err()
2416 .unwrap();
2417 assert!(err.to_string().contains("no longer a file"), "{err}");
2418 fs::remove_dir_all(&out).unwrap();
2419 }
2420
2421 #[cfg(unix)]
2424 #[test]
2425 fn a_link_at_the_name_of_a_file_fails_verification() {
2426 let out = scratch("verify-link");
2427 fs::write(out.join("real"), b"hello").unwrap();
2428 std::os::unix::fs::symlink("real", out.join("link")).unwrap();
2429 let err = verify_extracted(&[unit(0, "link", 5)], &out).err().unwrap();
2430 assert!(err.to_string().contains("no longer a file"), "{err}");
2431 fs::remove_dir_all(&out).unwrap();
2432 }
2433
2434 #[test]
2437 fn other_kinds_of_entries_are_not_verified() {
2438 let out = scratch("verify-kinds");
2439 let item = |kind: Kind| Item {
2440 path: "absent".into(),
2441 size: 0,
2442 kind,
2443 mode: None,
2444 mtime: None,
2445 };
2446 let batch = Unit {
2447 start: 0,
2448 key: 0,
2449 items: vec![
2450 item(Kind::Dir),
2451 item(Kind::Symlink),
2452 item(Kind::HardLink("absent".into())),
2453 ],
2454 encrypted: false,
2455 };
2456 assert!(verify_extracted(&[batch], &out).is_ok());
2457 fs::remove_dir_all(&out).unwrap();
2458 }
2459
2460 #[test]
2463 fn units_sharing_a_start_are_refused() {
2464 let (dir, storage) = storage("shared-start");
2465 let shared = vec![unit(10, "a", 1), unit(30, "b", 1), unit(10, "c", 1)];
2466 let err = Job::build(storage.clone(), opened(shared, 40), 64)
2467 .err()
2468 .unwrap();
2469 assert!(err.to_string().contains("same offset"), "{err:#}");
2470 let apart = vec![unit(10, "a", 1), unit(30, "b", 1)];
2471 assert!(Job::build(storage, opened(apart, 40), 64).is_ok());
2472 fs::remove_dir_all(&dir).unwrap();
2473 }
2474
2475 #[test]
2478 fn data_past_the_end_of_the_file_is_refused() {
2479 let (dir, storage) = storage("past-the-end");
2480 for (starts, tail_start) in [(vec![10, 64], 40), (vec![10, 70], 40), (vec![10], 65)] {
2481 let units = starts
2482 .iter()
2483 .map(|&s| unit(s, &format!("f{s}"), 1))
2484 .collect();
2485 let err = Job::build(storage.clone(), opened(units, tail_start), 64)
2486 .err()
2487 .unwrap();
2488 assert!(err.is::<archive::Damaged>(), "{starts:?}: {err:#}");
2489 }
2490 let job = Job::build(
2492 storage,
2493 opened(vec![unit(10, "a", 1), unit(50, "b", 1)], 60),
2494 40,
2495 );
2496 assert_eq!(job.unwrap().units.len(), 1);
2497 fs::remove_dir_all(&dir).unwrap();
2498 }
2499
2500 #[test]
2504 fn sizes_too_large_to_add_up_are_refused() {
2505 let (dir, storage) = storage("huge-sizes");
2506 let half = 1u64 << 63;
2507 for sizes in [vec![half, half], vec![u64::MAX - 10], vec![(1 << 62) + 1]] {
2508 let units = sizes
2509 .iter()
2510 .enumerate()
2511 .map(|(i, &s)| unit(10 + i as u64, &format!("f{i}"), s))
2512 .collect();
2513 let err = Job::build(storage.clone(), opened(units, 40), 64)
2514 .err()
2515 .unwrap();
2516 assert!(err.is::<archive::Damaged>(), "{sizes:?}: {err:#}");
2517 }
2518 assert_eq!(on_disk(&unit(0, "f", u64::MAX - 10)), u64::MAX);
2519 let mut two = unit(0, "f", half);
2520 two.items.extend(unit(0, "g", half).items);
2521 assert_eq!(two.size(), u64::MAX);
2522 assert_eq!(on_disk(&two), u64::MAX);
2523 fs::remove_dir_all(&dir).unwrap();
2524 }
2525}