Skip to main content

hatchzip_core/
engine.rs

1//! In-place extraction, independent of the archive format.
2//!
3//! Units are processed from the highest offset down. After each batch the
4//! archive is truncated to where the batch began, which every filesystem
5//! supports, FAT32 and exFAT included, so this path needs no hole punching.
6//!
7//! A unit too large for the free space would need room for all of its
8//! output before any of its archive bytes could go. Where the filesystem can
9//! punch holes and the format can resume decoding mid-file, such a unit is
10//! streamed instead: every [`stream_step`] of output it is flushed, a resume
11//! point is journaled, and only then are the archive bytes before that point
12//! punched out. The archive's length stays the same until the unit commits
13//! through the ordinary path.
14//!
15//! A compressed tar is one stream that decodes only from the front, so it is
16//! one unit holding every entry, always streamed, front to back, with resume
17//! points between the files as well as inside them (see
18//! [`Run::stream_solid`]). Without hole punching it still streams, so a
19//! crash resumes from the last point, but nothing is freed until the end.
20//!
21//! A format whose decoder finds a unit only by reading everything before it
22//! (RAR, through UnRAR) says so with [`Format::serial`]; its batches are
23//! decoded on one thread, lowest unit first, by one worker.
24//!
25//! An extraction that keeps the archive (`Journal::keep`) runs the same
26//! batches, checks and commits, so it resumes the same way, but never
27//! truncates, punches or deletes: its storage is protected, and the run
28//! frees nothing, exactly like an output on another disk.
29
30use 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::{folders, fsutil, platform, replace};
48
49/// Larger batches extract in parallel better, smaller ones redo less work
50/// after a crash and keep the archive shrinking in fine steps.
51const 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
56/// Output written between two resume points of a streamed unit. Each point
57/// costs a flush and a journal write; the space check counts one step as the
58/// most a streamed unit holds that its archive bytes don't offset.
59const 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
65/// Units smaller than this are always extracted whole: streaming one would
66/// save less than a couple of steps.
67fn stream_threshold() -> u64 {
68    2 * stream_step()
69}
70
71/// The test suite streams every unit it can, whether it fits or not, so the
72/// streaming path runs on small archives.
73fn always_stream() -> bool {
74    test_knob("HATCHZIP_STREAM_STEP").is_some()
75}
76
77/// More than any disk holds. An archive whose files add up to more is
78/// refused, so the space check's sums of sizes stay far from overflowing.
79const MAX_TOTAL_SIZE: u64 = 1 << 62;
80
81/// The most an archive may hold after its last unit: the index and whatever
82/// else is saved before the extraction starts.
83fn 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    /// Units still to do, highest offset first.
99    pub units: Vec<Unit>,
100    pub tail_start: u64,
101    /// Where the archive currently ends: its original length, or wherever
102    /// the last commit truncated it.
103    pub top: u64,
104    /// Whether the archive's filesystem can free bytes inside a file, and
105    /// how much of a punched range it may keep allocated at each end. Probed
106    /// once, on first use.
107    punch: OnceLock<Option<u64>>,
108    /// The streamed unit a previous run left half done, if any.
109    resume: Option<Resume>,
110    /// Whether a run may have extracted anything yet. Until it has, what
111    /// sits at the paths of entries belongs to the person: a fresh archive,
112    /// or a run still moving the files it replaces aside.
113    started: bool,
114    /// Entries whose paths differ only in case. A filesystem that ignores
115    /// case would put both in one place, so these depend on the destination:
116    /// see [`Job::check_case`]. A resumed run goes by what its journal
117    /// recorded when it began, since a tar no longer lists the entries it
118    /// has extracted.
119    case_clashes: Box<CaseClashes>,
120}
121
122/// How many folders of one archive may hold names that differ only in case.
123/// A run lists them in its journal, which is rewritten at every commit, and a
124/// real tree has a handful.
125const MAX_CASE_FOLDERS: usize = 1000;
126
127/// The entries of a fresh archive whose paths differ only in case.
128#[derive(Default)]
129struct CaseClashes {
130    /// One pair for each folder where such names meet, as a path inside the
131    /// output folder.
132    met_in: BTreeMap<PathBuf, (PathBuf, PathBuf)>,
133    /// A pair outside plain ASCII, which a system that normalizes names may
134    /// make one file wherever it lands.
135    beyond_ascii: Option<(PathBuf, PathBuf)>,
136    /// A resumed run has no list of its own, only what its journal recorded.
137    recorded: Vec<PathBuf>,
138    recorded_beyond_ascii: bool,
139}
140
141impl CaseClashes {
142    /// `names` is every file, link and folder, sorted: the path with case
143    /// folded, the path, and whether it is a file or link.
144    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            // Folders alone just merge on a filesystem that ignores case.
148            if !group.iter().any(|n| n.2) {
149                continue;
150            }
151            // A path shares the most components with the nearest file on
152            // either side. These pairs cover every meeting folder without
153            // imposing case separation between folders alone in a branch.
154            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
186/// The folder holding the first names that differ between `a` and `b`, as a
187/// path inside the output folder. That one decides: if it keeps them apart,
188/// everything below is in two different folders.
189fn 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
197/// Whether `dir` is known to keep apart names that differ only in case. A
198/// debug build can be told it isn't, anywhere or at one folder, so that tests
199/// reach the refusals on a disk that does.
200pub(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
207/// Whether this system can make one file of different names even where case
208/// is kept. Likewise, so that tests reach the refusal everywhere.
209fn normalizes_names() -> bool {
210    platform::NORMALIZES_NAMES || test_knob("HATCHZIP_NORMALIZE_NAMES").is_some()
211}
212
213/// What a run recorded when it began, asked again: the output folder can have
214/// moved to a filesystem that ignores case, or to a system that normalizes
215/// names, and a tar no longer lists the entries it has extracted. There, an
216/// entry left to do resolves to its twin that is already out, which a resume
217/// would overwrite and a restore would delete as its own.
218pub(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
238/// The first of `folders`, paths inside `out`, whose names `apart` can't
239/// vouch for, with the folder it asked. A folder that doesn't exist yet takes
240/// after the nearest one above it that does, which can be a mount of its own.
241fn 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    /// `password` is only needed for encrypted archives. A missing one shows
270    /// up as [`archive::PasswordNeeded`], from here or from
271    /// [`Job::check_password`]. What opening reads is counted in `reads`.
272    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    /// [`Job::open`] without [`Job::check_layout`]. Restore checks what it
284    /// rebuilt with this: an archive an older release started on may hold
285    /// entries that collide, and giving it back is still the right thing to
286    /// do. A later extraction of it is refused as usual.
287    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        // The tail is read into memory when the extraction begins and stays
299        // there until it ends. An index is nowhere near this big. A run
300        // that already began has it loaded, so only a new one is refused.
301        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    /// Reopens an archive a previous run already started on. A read-only
312    /// open leaves a pending truncation for the next writable one. The
313    /// password is never stored, so an encrypted archive needs it again.
314    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            // Never truncated, so `committed_len` only marks progress and
327            // the whole archive must still be there.
328            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            // The last run committed a batch but stopped before truncating.
345            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            // Only the highest uncommitted unit is ever streamed, so a point
355            // for any other one means the journal and archive disagree.
356            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        // Units from `top` up were extracted by an earlier run. Ones that
371        // start at or past the end of the file never existed, and dropping
372        // them quietly would lose their files with the archive.
373        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        // A unit owns its bytes up to the next one's start. Two that start
384        // at the same offset can't both own them: committing one would
385        // truncate the other before it is extracted.
386        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    /// Refuses entries that differ only in case, unless the folder where
436    /// their names meet is known to keep them apart. Anywhere else they
437    /// would be one file, and would race inside a parallel batch.
438    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    /// What a run has to record: see [`Journal::case_folders`].
475    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    /// Refuses entries that can't all be created where the archive puts
484    /// them: a file or link at a path where another entry needs a folder,
485    /// which includes any entry inside a link, and a hard link to anything
486    /// but a file in the archive. Links are only made at the very end, once
487    /// the archive is gone, so without this such an archive fails after it
488    /// has been consumed. Paths that differ only in case depend on the
489    /// destination, so they are returned for [`Job::check_case`]. Names
490    /// ending in [`PART_SUFFIX`] are compared ignoring case everywhere.
491    ///
492    /// Only a fresh archive is checked: a resumed run no longer lists the
493    /// entries it has extracted, and one an older release started on has to
494    /// stay resumable and restorable.
495    fn check_layout(&self) -> Result<CaseClashes> {
496        let key = |p: &Path| crate::fsutil::fold_name(&p.to_string_lossy());
497        let items = || self.units.iter().flat_map(|u| &u.items);
498        // Every file is first written under its name plus the suffix. An
499        // entry named so would share that name with another entry's file,
500        // and which of the two is lost would depend on timing.
501        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        // Every folder the extraction creates, with the first entry inside
514        // that needs it, or `None` if it has an entry of its own.
515        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    /// `Some(granule)` if holes punched in the archive give its space back,
572    /// where `granule` is how much may stay allocated at each end of a
573    /// punched range. `None` on filesystems that can only truncate, such as
574    /// FAT32 and exFAT, which keep today's whole-unit behavior.
575    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    /// The archive is one compressed stream, extracted front to back.
593    pub fn is_stream(&self) -> bool {
594        self.format.solid().is_some()
595    }
596
597    /// The archive is one compressed stream that stays whole until the run
598    /// ends, because the filesystem can't free space inside it: the disk
599    /// has to hold the archive and every extracted file at once.
600    pub fn kept_whole(&self, reclaims: bool) -> bool {
601        self.is_stream() && reclaims && self.punch_support().is_none()
602    }
603
604    /// Proves the password before anything is deleted: decrypts the smallest
605    /// encrypted unit, which checks its CRC, up to a limit so a huge solid
606    /// block doesn't stall. ZipCrypto accepts about one wrong password in 256
607    /// at first sight; reading the data catches those.
608    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            // A wrong password only shows in the checksum at the end, so a
617            // sample would let it through and the run would fail later, after
618            // the archive is partly gone.
619            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    /// The smallest encrypted unit with data: an empty file decodes with
635    /// any password in formats whose only check is the file's checksum.
636    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    /// When [`check_password`](Self::check_password) has to decode a whole
644    /// file to prove the password, as for RAR 4: that file and its size, so
645    /// a front end can say the check may take a while.
646    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    /// Why the archive can't be extracted in place, if it can't. It can
655    /// still be extracted while it is kept.
656    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    /// The resume point recorded for `units[i]`, if it is half streamed.
680    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    /// Where the data of `units[i]` lies, if it is one file whose decoding
687    /// can be resumed from the middle.
688    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    /// Whether `units[i]` may free its own archive bytes while it is
699    /// extracted. A half-streamed unit always continues streaming: the bytes
700    /// before its resume point may be gone.
701    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    /// Bytes freed once `units[i]` is committed: everything from its start up
713    /// to whatever came after it.
714    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    /// Replays the extraction one unit at a time and returns `(peak, end)`:
724    /// the most free space it ever consumes beyond what is free now, and how
725    /// much it consumes once finished. `fresh` means the tail hasn't been
726    /// saved yet; `reclaims` that freed archive space lands on the output's
727    /// disk.
728    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            // Whatever precedes the first unit is deleted at the very end,
755            // along with the saved tail.
756            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    /// What streaming `units[i]` costs in free space: `(rise, net)`, the most
763    /// it consumes at any moment and what it consumes once committed.
764    ///
765    /// At any moment the unit holds the output written since the last resume
766    /// point (at most a step, plus one read buffer or deflate block), the
767    /// archive bytes at either end of the punched range the filesystem keeps
768    /// (a granule each), and however far the output so far has outgrown the
769    /// input it came from. For stored data that last part is zero. For
770    /// deflate it only grows as decoding goes on, since encoders fall back to
771    /// stored blocks rather than expand data, so the end state bounds it; a
772    /// 1/1024 margin covers block headers.
773    ///
774    /// Without punching (the filesystem stopped supporting it after a run
775    /// began), the unit holds all of its remaining output until it commits.
776    fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
777        let at = self.resumed(i);
778        // What a crashed run already wrote is on disk, so the free space
779        // measured now has paid for it.
780        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        // At most this much was punched already. It is free now, so the
785        // final truncation gives back that much less; assuming the most
786        // keeps the estimate on the safe side.
787        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    /// What streaming a compressed tar, `units[i]`, costs in free space:
808    /// `(rise, net)` as for [`stream_cost`](Self::stream_cost).
809    ///
810    /// Before each resume point is taken, the files hold what they held at
811    /// the point before, `lead` at most ahead of the compressed bytes freed
812    /// up to it, plus what was written since: under a step, plus the output
813    /// to the next point after the step is full, at most `gap`. The scan
814    /// measured both at the very points the run will meet. A read buffer
815    /// and a granule at each end of the punched range come on top. Links are
816    /// made at the end, once the archive is gone.
817    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        // Assumed punched already, as for a single streamed file.
820        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            // Nothing is freed until the run commits, so every file is on
832            // disk next to the whole archive.
833            _ => out_left,
834        };
835        (rise.max(net), net)
836    }
837
838    /// The entry a resume point stopped inside of, if any: the first item of
839    /// the first unit, whose part file holds `written` bytes.
840    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    /// Output a crashed run wrote for units it never committed. Nothing was
853    /// at those paths when it started, or it was moved aside before the
854    /// first entry was extracted, so anything there now is ours. A
855    /// half-streamed file is not in the list: its archive bytes may be gone,
856    /// so it is the only copy of its first part. For a compressed tar that
857    /// is the entry its point is in; the files after the point are still in
858    /// the archive.
859    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    /// Output a crashed stream wrote past its last resume point. It is cut
884    /// off before the stream continues, so it counts as free.
885    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    /// Reads every unit and lets the decoders check their checksums,
899    /// writing nothing.
900    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    /// One worker walks every unit from the lowest up.
918    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
965/// Added to a file's name while it is written.
966const 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
974/// Creates the part file a new file is first written to. Whatever is
975/// already at that name was not made by this run: a file there is someone
976/// else's to keep, and a link there would send the data wherever it points.
977/// Fresh runs refuse both before the archive is touched.
978fn 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
992/// Opens a streamed file's part file positioned at `written`, cutting off
993/// anything written after that point.
994fn 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        // The previous run finished the file and renamed it, then stopped
1000        // before committing. The point it journaled still holds.
1001        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
1023/// A file of a compressed tar being written to its part file.
1024struct OpenFile {
1025    item: Item,
1026    dest: PathBuf,
1027    part: PathBuf,
1028    file: File,
1029    written: u64,
1030}
1031
1032impl OpenFile {
1033    /// Gives the finished file its metadata and its real name.
1034    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
1051/// The output just before `written`, which a deflate stream may refer back
1052/// to. It is on disk, flushed before the point was journaled, so the
1053/// journal doesn't have to carry it.
1054fn 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    /// With a warning for the person if the folders could not be set.
1070    Finished(Option<String>),
1071    Paused,
1072}
1073
1074pub struct Run<'a> {
1075    pub job: Job,
1076    pub journal: Journal,
1077    pub paths: Paths,
1078    pub stop: &'a AtomicBool,
1079    pub progress: Progress,
1080    /// Free space the run must never eat into.
1081    pub keep_free: u64,
1082}
1083
1084impl Run<'_> {
1085    pub fn execute(mut self) -> Result<Outcome> {
1086        let out = self.journal.output.clone();
1087        fs::create_dir_all(&out)
1088            .with_context(|| format!("creating output folder {}", out.display()))?;
1089
1090        // Keeping the archive frees nothing, which is exactly the case of an
1091        // output on another disk: nothing is streamed or punched.
1092        let reclaims =
1093            !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
1094        if self.journal.keep {
1095            self.job.storage.protect();
1096        }
1097        if let Some(r) = self.journal.replace.as_mut()
1098            && !r.moved
1099        {
1100            replace::set_aside(&self.job, &out)?;
1101            r.moved = true;
1102            self.journal.save(&self.paths)?;
1103            self.job.started = true;
1104        }
1105        let mut next = 0;
1106        while next < self.job.units.len() {
1107            if self.stop.load(Ordering::Relaxed) {
1108                return Ok(Outcome::Paused);
1109            }
1110            if let Some(solid) = self.job.format.solid() {
1111                let walk = solid.walk(self.job.resumed(next))?;
1112                let Some(links) = self.stream_solid(next, walk, reclaims, &out)? else {
1113                    return Ok(Outcome::Paused);
1114                };
1115                self.commit(next, next + 1, links, &out)?;
1116                next += 1;
1117                continue;
1118            }
1119            if let Some(stream) = self.stream_now(next, reclaims, &out)? {
1120                if !self.stream_unit(next, &stream, &out)? {
1121                    return Ok(Outcome::Paused);
1122                }
1123                self.commit(next, next + 1, Vec::new(), &out)?;
1124                next += 1;
1125                continue;
1126            }
1127            let end = self.next_batch(next, &out, reclaims)?;
1128            let batch = &self.job.units[next..end];
1129
1130            let Some(links) = self.extract_batch(batch, &out)? else {
1131                return Ok(Outcome::Paused);
1132            };
1133            self.commit(next, end, links, &out)?;
1134            next = end;
1135        }
1136
1137        Ok(Outcome::Finished(self.finish(&out)?))
1138    }
1139
1140    /// Commits `units[start..end]`, all extracted, and truncates the archive
1141    /// behind them.
1142    fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
1143        let batch = &self.job.units[start..end];
1144        // The journal must never claim a file that a power cut could still
1145        // take back, since its archive bytes are about to be truncated.
1146        platform::sync_batch(out).context("flushing extracted files to disk")?;
1147        if platform::SYNC_EACH_FILE {
1148            // Links are only recorded here and made at the end, so their
1149            // folders may not exist yet.
1150            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        // Other programs on the computer, antivirus software above all, can
1163        // remove a file after it is written. Claiming one in the journal
1164        // would shorten the archive behind the only copy left. A streamed
1165        // unit with a resume point is skipped: some of its archive is
1166        // already freed, so some of its output may have no other copy, and
1167        // a rerun resumes past it.
1168        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        // A streamed unit's point is spent once the unit itself is claimed;
1177        // both change in the same atomic write.
1178        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    /// Whether `units[i]` is extracted by streaming: always if it is half
1196    /// streamed already, otherwise if it can be and its output wouldn't fit
1197    /// whole in the space there is right now. When it fits, the ordinary
1198    /// path is faster, since it extracts many units in parallel.
1199    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    /// Extracts the one file of `units[i]` while freeing the archive bytes
1220    /// behind it. Returns false if a stop request interrupted it; the last
1221    /// resume point stays in the journal and the next run continues there.
1222    ///
1223    /// The order at every point is what makes a crash harmless: the output
1224    /// up to the point is flushed, then the point is journaled, and only then
1225    /// is the archive punched, never past the byte the point restarts in. A
1226    /// crash before the journal write leaves the previous point in force,
1227    /// and everything it needs is still in the archive.
1228    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        // Opened before anything below may delete it: if something is in the
1246        // way of a new part file, it is not ours to remove.
1247        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            // Nothing was punched yet, so the next run starts this file over.
1253            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                // A deflate block runs as long as its encoder likes; zlib-ng
1317                // and zlib-rs write level 1 as a single block. Until it ends
1318                // there is nowhere to resume from, so nothing can be freed,
1319                // and the run has to stop before the disk fills.
1320                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        // From here a crash leaves the finished file under its real name
1350        // while the journal still holds the last point; `open_part` takes it
1351        // back as the part file.
1352        fs::rename(part, dest)?;
1353        Ok(true)
1354    }
1355
1356    /// Makes `point` the one a crash resumes from, then frees the archive
1357    /// bytes it no longer needs. Returns whether to keep punching.
1358    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        // The part file and the folders above it may be new; a point that
1370        // outlives its file would resume into nothing.
1371        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        // Decoding restarts inside the byte holding `point.bit`, so that byte
1387        // and everything after it must stay.
1388        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            // The probe said this works; if the filesystem disagrees after
1396            // all, the run continues without freeing anything mid-file.
1397            return Ok(None);
1398        }
1399        crash_point("stream-after-punch");
1400        Ok(punching)
1401    }
1402
1403    /// Extracts a compressed tar, `units[i]`, front to back from `walk`,
1404    /// freeing the compressed bytes behind the decoder. Returns the links
1405    /// found since the last resume point, for the commit, or `None` if a
1406    /// stop request interrupted it; the last point stays in the journal and
1407    /// the next run continues there.
1408    ///
1409    /// Each point follows the order of [`stream_unit`](Self::stream_unit):
1410    /// every file written before it is flushed, then the point is journaled,
1411    /// with the links found so far, and only then is the archive punched up
1412    /// to the byte it restarts in. Files finished after the last point are
1413    /// written again on resume, the half-written one is cut back to the
1414    /// point.
1415    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        // With the output on another disk, freeing the archive's space
1425        // doesn't help it, and the space check didn't count on it.
1426        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        // This run hasn't punched anything yet. Its first punch starts at 0,
1433        // in case the last run stopped between journaling a point and
1434        // punching up to it.
1435        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                    // A deflate block runs as long as its encoder likes, and
1500                    // until it ends there is nowhere to resume from, so nothing
1501                    // can be freed: stop before the disk fills.
1502                    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    /// Makes `point` the one a crash resumes from, then frees the archive
1562    /// bytes before it. Returns whether to keep punching.
1563    #[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            // Files were flushed as they were finished; their names live in
1583            // the folders, which may be new themselves.
1584            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            // A filesystem that rounds a punch inwards keeps the granule
1619            // holding `byte` allocated. Starting the next punch one granule
1620            // earlier covers it; it still never reaches `byte`, the point a
1621            // resume parses.
1622            *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    /// Stops a stream at a resume point, before it writes what doesn't fit.
1630    /// `left` is the output still to write.
1631    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    /// Pick units starting at `start` whose output fits in the space there is
1654    /// right now. Always takes at least one, or explains why it can't.
1655    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            // The upfront check makes this rare: it takes something else on
1662            // the machine filling the disk while we run.
1663            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    /// Returns `None` if a stop request interrupted the batch. Nothing in the
1696    /// archive has been touched at that point, so the batch simply reruns.
1697    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            // Lowest first, so the worker reads the archive front to back.
1713            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(mut self, out: &Path) -> Result<Option<String>> {
1759        make_links_and_settle(&mut self.journal, &self.paths, out)?;
1760        // Last, since every file, link and put-back file changes its
1761        // folder's time.
1762        let warning = set_folders(&self.journal, &self.paths, out)?;
1763        if self.journal.keep {
1764            // The archive stays as it was; only the progress files go.
1765            self.paths.remove()?;
1766            return Ok(warning);
1767        }
1768        let Self { job, paths, .. } = self;
1769        let Job {
1770            storage, format, ..
1771        } = job;
1772        // The format holds its own handle on the storage; it has to go first.
1773        drop(format);
1774        let storage = Arc::try_unwrap(storage)
1775            .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
1776        // What is left is at most a self-extractor stub in front of the
1777        // first entry. The saved index goes with it.
1778        storage.remove()?;
1779        paths.remove()?;
1780        Ok(warning)
1781    }
1782}
1783
1784/// Checks that every file `batch` extracted is whole on disk under its final
1785/// name. The journal is about to claim them and free the archive bytes
1786/// behind them, so a file that another program removed or changed has to
1787/// stop the run here: its unit keeps its place in the journal and the
1788/// archive still holds it, and a rerun extracts it again.
1789///
1790/// Links are made at the very end, once the archive is gone, so link
1791/// entries have nothing on disk yet.
1792fn verify_extracted(batch: &[Unit], out: &Path) -> Result<()> {
1793    for item in batch.iter().flat_map(|u| &u.items) {
1794        if item.kind != Kind::File {
1795            continue;
1796        }
1797        let dest = out.join(&item.path);
1798        // Never follows a link: what matters is what sits at the name.
1799        let meta = match fs::symlink_metadata(&dest) {
1800            Ok(meta) => meta,
1801            Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
1802                "'{}' disappeared while it was extracted. Antivirus software sometimes removes \
1803                 files as they are written. The archive still holds it ({} bytes), so running \
1804                 the same command again extracts it",
1805                item.path.display(),
1806                item.size
1807            ),
1808            Err(e) => {
1809                return Err(e).with_context(|| {
1810                    format!("checking '{}' after extracting it", item.path.display())
1811                });
1812            }
1813        };
1814        if !meta.is_file() {
1815            bail!(
1816                "'{}' is no longer a file after it was extracted, but the archive has a file \
1817                 there. The archive still holds it, so move what is in its place away and run \
1818                 the same command again",
1819                item.path.display()
1820            );
1821        }
1822        if meta.len() != item.size {
1823            bail!(
1824                "'{}' changed while it was extracted: the archive records {} bytes, but the \
1825                 file has {}. The archive still holds it, so move it away and run the same \
1826                 command again",
1827                item.path.display(),
1828                item.size,
1829                meta.len()
1830            );
1831        }
1832    }
1833    Ok(())
1834}
1835
1836/// Lets the test suite remove an extracted file between the batch reaching
1837/// the disk and the journal claiming it, as antivirus software might.
1838fn remove_after_extract(batch: &[Unit], out: &Path) {
1839    if !cfg!(debug_assertions) {
1840        return;
1841    }
1842    let Ok(rel) = std::env::var("HATCHZIP_REMOVE_AFTER_EXTRACT") else {
1843        return;
1844    };
1845    let rel = Path::new(&rel);
1846    let extracted = batch
1847        .iter()
1848        .flat_map(|u| &u.items)
1849        .any(|item| item.kind == Kind::File && item.path == rel);
1850    if extracted {
1851        let _ = fs::remove_file(out.join(rel));
1852    }
1853}
1854
1855/// A run that crashed after deleting the archive but before cleaning up only
1856/// has its links and side files left to deal with. Returns a warning for the
1857/// person if the folders could not be set.
1858pub fn finish_orphaned(journal: &mut Journal, paths: &Paths) -> Result<Option<String>> {
1859    let out = journal.output.clone();
1860    make_links_and_settle(journal, paths, &out)?;
1861    let warning = set_folders(journal, paths, &out)?;
1862    // The final commit was interrupted before the archive was removed, and
1863    // all of it is free to go now. A kept archive stays.
1864    if journal.done && !journal.keep {
1865        for (part, _) in &journal.parts {
1866            match fs::remove_file(part) {
1867                Err(e) if e.kind() != io::ErrorKind::NotFound => {
1868                    return Err(e).with_context(|| format!("deleting {}", part.display()));
1869                }
1870                _ => {}
1871            }
1872        }
1873    }
1874    paths.remove()?;
1875    Ok(warning)
1876}
1877
1878/// Makes the links and puts the replaced files back, unless an earlier run
1879/// got past them. With folders still to set, the journal then says only
1880/// they are left, so a resume never makes a link again inside a folder
1881/// whose mode no longer lets it.
1882fn make_links_and_settle(journal: &mut Journal, paths: &Paths, out: &Path) -> Result<()> {
1883    if journal.folders_left {
1884        return Ok(());
1885    }
1886    make_final_links(&journal.links, out)?;
1887    // Before the journal goes, so a crash in between deletes the rest on
1888    // resume rather than leaving it.
1889    if let Some(r) = &journal.replace {
1890        replace::settle(out, r)?;
1891        replace::remove(out)?;
1892    }
1893    if journal.folders.is_some() {
1894        journal.folders_left = true;
1895        journal.save(paths)?;
1896    }
1897    Ok(())
1898}
1899
1900/// Sets the saved folders' permissions and times. The journal stays until
1901/// they are set, so a crash before the end sets them again on resume. Every
1902/// file is safe by now, so a list that can't be read doesn't stop the run: it
1903/// gets a warning, which can only count the folders, since only the list names
1904/// them.
1905fn set_folders(journal: &Journal, paths: &Paths, out: &Path) -> Result<Option<String>> {
1906    let Some(saved) = journal.folders else {
1907        return Ok(None);
1908    };
1909    crash_point("before-folders");
1910    let list = match folders::load(&paths.folders, saved) {
1911        Ok(list) => list,
1912        Err(e) => {
1913            let folders = match saved.count {
1914                1 => "1 folder".to_string(),
1915                n => format!("{n} folders"),
1916            };
1917            return Ok(Some(format!(
1918                "{e:#}, so {folders} in {} kept the default permissions and modified times",
1919                out.display()
1920            )));
1921        }
1922    };
1923    folders::apply(&list, out)?;
1924    crash_point("after-folders");
1925    Ok(None)
1926}
1927
1928/// The last step of a run, when every file is extracted and the archive is
1929/// gone: a link that can't be made is all that is left. The journal keeps
1930/// the links, so once the cause is fixed a resumed run makes them and
1931/// finishes.
1932fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
1933    make_links(links, out).map_err(|e| {
1934        anyhow!(
1935            "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
1936             each one, for example by moving or renaming a folder that is in the way, then \
1937             resume the extraction to create them"
1938        )
1939    })
1940}
1941
1942/// Makes `links`. Each one is tried, and the error lists every one that
1943/// failed and why. Links that were made are made again by the next call,
1944/// replacing themselves.
1945pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
1946    let failed: Vec<(&Link, anyhow::Error)> = links
1947        .iter()
1948        .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
1949        .collect();
1950    if failed.is_empty() {
1951        return Ok(());
1952    }
1953    let mut msg = match failed.len() {
1954        1 => "1 link could not be created:".to_string(),
1955        n => format!("{n} links could not be created:"),
1956    };
1957    for (link, e) in failed.iter().take(10) {
1958        let kind = if link.hard {
1959            "hard link"
1960        } else {
1961            "symbolic link"
1962        };
1963        msg.push_str(&format!(
1964            "\n  '{}' ({kind} to '{}'): {e:#}",
1965            link.path.display(),
1966            link.target.display()
1967        ));
1968    }
1969    if failed.len() > 10 {
1970        msg.push_str(&format!("\n  and {} more", failed.len() - 10));
1971    }
1972    Err(anyhow!(msg))
1973}
1974
1975fn make_link(link: &Link, out: &Path) -> Result<()> {
1976    // A run an older release started may hold a link inside another link.
1977    // Going through it would write outside the output folder.
1978    if let Some(via) = link_on_the_way(out, &link.path) {
1979        bail!(
1980            "'{}' is a link, and this one would be created through it",
1981            via.display()
1982        );
1983    }
1984    let path = out.join(&link.path);
1985    if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
1986        bail!("a folder already exists at this location");
1987    }
1988    if let Some(parent) = path.parent() {
1989        fs::create_dir_all(parent)?;
1990    }
1991    if link.hard {
1992        if let Some(via) = link_on_the_way(out, &link.target) {
1993            bail!(
1994                "'{}' is a link, and the target would be reached through it",
1995                via.display()
1996            );
1997        }
1998        let target = out.join(&link.target);
1999        let _ = fs::remove_file(&path);
2000        // FAT32 and exFAT have no hard links; a copy is the next best thing.
2001        fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
2002    } else {
2003        platform::create_symlink(&path, &link.target)?;
2004    }
2005    Ok(())
2006}
2007
2008/// The first folder on the way to `rel` inside `out` that is really a link.
2009pub(crate) fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
2010    let mut ancestors: Vec<&Path> = rel
2011        .ancestors()
2012        .skip(1)
2013        .filter(|p| !p.as_os_str().is_empty())
2014        .collect();
2015    ancestors.reverse();
2016    ancestors
2017        .into_iter()
2018        .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
2019        .map(Path::to_path_buf)
2020}
2021
2022struct DiskSink<'a> {
2023    out: &'a Path,
2024    stop: &'a AtomicBool,
2025    on_bytes: &'a (dyn Fn(u64) + Sync),
2026    buf: Vec<u8>,
2027    links: Vec<Link>,
2028}
2029
2030impl Sink for DiskSink<'_> {
2031    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2032        self.write(item, data)
2033            .with_context(|| format!("extracting '{}'", item.path.display()))
2034    }
2035}
2036
2037impl DiskSink<'_> {
2038    fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2039        let dest = self.out.join(&item.path);
2040        match &item.kind {
2041            Kind::Dir => {
2042                fs::create_dir_all(&dest)?;
2043                return Ok(());
2044            }
2045            Kind::Symlink => {
2046                let mut target = Vec::new();
2047                data.take(MAX_SYMLINK).read_to_end(&mut target)?;
2048                let target = PathBuf::from(String::from_utf8(target)?);
2049                self.links.push(Link {
2050                    path: item.path.clone(),
2051                    target,
2052                    hard: false,
2053                });
2054                return Ok(());
2055            }
2056            Kind::HardLink(target) => {
2057                self.links.push(Link {
2058                    path: item.path.clone(),
2059                    target: target.clone(),
2060                    hard: true,
2061                });
2062                return Ok(());
2063            }
2064            Kind::File => {}
2065        }
2066
2067        if let Some(parent) = dest.parent() {
2068            fs::create_dir_all(parent)?;
2069        }
2070        let part = part_path(&dest);
2071        // Only a part file this call created is removed on failure.
2072        let dst = create_part(&part)?;
2073        let result = self.copy(item, data, dst);
2074        if result.is_err() {
2075            let _ = fs::remove_file(&part);
2076            return result;
2077        }
2078        fs::rename(&part, &dest)?;
2079        Ok(())
2080    }
2081
2082    fn copy(&mut self, item: &Item, data: &mut dyn Read, mut dst: File) -> Result<()> {
2083        let mut written = 0u64;
2084        loop {
2085            if self.stop.load(Ordering::Relaxed) {
2086                return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2087            }
2088            // Decoders check their CRC when the stream ends, so a read error
2089            // here is how corruption surfaces.
2090            let n = data.read(&mut self.buf)?;
2091            if n == 0 {
2092                break;
2093            }
2094            written += n as u64;
2095            if written > item.size {
2096                bail!("it is larger than the archive records");
2097            }
2098            dst.write_all(&self.buf[..n])?;
2099            (self.on_bytes)(n as u64);
2100        }
2101        if written != item.size {
2102            bail!("it is smaller than the archive records");
2103        }
2104        if let Some(t) = item.mtime {
2105            dst.set_modified(t)?;
2106        }
2107        platform::apply_mode(&dst, item.mode)?;
2108        if platform::SYNC_EACH_FILE {
2109            dst.sync_all()?;
2110        }
2111        Ok(())
2112    }
2113}
2114
2115/// Reads at most `left` bytes, then stops the decoder with [`ProbeDone`].
2116struct ProbeSink {
2117    left: u64,
2118    buf: Vec<u8>,
2119}
2120
2121#[derive(Debug)]
2122struct ProbeDone;
2123
2124impl std::fmt::Display for ProbeDone {
2125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2126        f.write_str("read enough to prove the password")
2127    }
2128}
2129
2130impl std::error::Error for ProbeDone {}
2131
2132impl Sink for ProbeSink {
2133    fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
2134        loop {
2135            let n = data.read(&mut self.buf)?;
2136            if n == 0 {
2137                return Ok(());
2138            }
2139            self.left = self.left.saturating_sub(n as u64);
2140            if self.left == 0 {
2141                return Err(ProbeDone.into());
2142            }
2143        }
2144    }
2145}
2146
2147struct VerifySink<'a> {
2148    on_bytes: &'a (dyn Fn(u64) + Sync),
2149    buf: Vec<u8>,
2150}
2151
2152impl Sink for VerifySink<'_> {
2153    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2154        let mut read = 0;
2155        loop {
2156            let n = data
2157                .read(&mut self.buf)
2158                .with_context(|| format!("'{}'", item.path.display()))?;
2159            if n == 0 {
2160                break;
2161            }
2162            read += n as u64;
2163            (self.on_bytes)(n as u64);
2164        }
2165        if item.kind == Kind::File && read != item.size {
2166            bail!(
2167                "'{}' is shorter than the archive records",
2168                item.path.display()
2169            );
2170        }
2171        Ok(())
2172    }
2173}
2174
2175fn is_interrupt(e: &anyhow::Error) -> bool {
2176    e.chain()
2177        .filter_map(|c| c.downcast_ref::<io::Error>())
2178        .any(|io| io.kind() == io::ErrorKind::Interrupted)
2179}
2180
2181/// Settings only the test suite uses. Release builds ignore them.
2182fn test_knob(name: &str) -> Option<u32> {
2183    if !cfg!(debug_assertions) {
2184        return None;
2185    }
2186    std::env::var(name).ok()?.parse().ok()
2187}
2188
2189/// Lets the test suite kill the process at the two moments that matter for
2190/// crash safety: after a batch is on disk, and after it is journaled.
2191pub(crate) fn crash_point(name: &str) {
2192    if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
2193        return;
2194    }
2195    static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2196    if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
2197        std::process::abort();
2198    }
2199}
2200
2201pub fn human(bytes: u64) -> String {
2202    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
2203    let mut v = bytes as f64;
2204    let mut unit = 0;
2205    while v >= 1000.0 && unit < UNITS.len() - 1 {
2206        v /= 1000.0;
2207        unit += 1;
2208    }
2209    if unit == 0 {
2210        format!("{bytes} B")
2211    } else {
2212        format!("{v:.1} {}", UNITS[unit])
2213    }
2214}
2215
2216#[cfg(test)]
2217mod tests {
2218    use super::*;
2219    use crate::archive::{Opened, Worker};
2220
2221    /// Stands in for a format: these tests only plan, they never decode.
2222    struct NoFormat;
2223
2224    impl Format for NoFormat {
2225        fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
2226            bail!("nothing is decoded in these tests")
2227        }
2228    }
2229
2230    /// The folder that decides is the one holding the first names to differ.
2231    #[test]
2232    fn names_meet_where_they_first_differ() {
2233        for (a, b, folder) in [
2234            ("a/Makefile", "a/makefile", "a"),
2235            ("Makefile", "makefile", ""),
2236            ("D/x", "d/x", ""),
2237            ("D", "d/inner.txt", ""),
2238            ("a/B/c/F", "a/b/c/f", "a"),
2239        ] {
2240            assert_eq!(
2241                meeting_folder(Path::new(a), Path::new(b)),
2242                Path::new(folder),
2243                "{a} and {b}"
2244            );
2245        }
2246    }
2247
2248    fn clashes(paths: &[&'static str]) -> CaseClashes {
2249        let mut names: Vec<(String, &Path, bool)> = paths
2250            .iter()
2251            .map(|p| (crate::fsutil::fold_name(p), Path::new(*p), true))
2252            .collect();
2253        names.sort_unstable();
2254        CaseClashes::of(&names)
2255    }
2256
2257    /// Names that only full case folding or normalization makes one, which
2258    /// lowercasing alone misses, still pair up, and outside ASCII.
2259    #[test]
2260    fn names_a_filesystem_folds_together_pair_up() {
2261        for pair in [
2262            ["stra\u{df}e.txt", "STRASSE.txt"],
2263            ["s.txt", "\u{17f}.txt"],
2264            ["\u{3c3}.txt", "\u{3c2}.txt"],
2265            ["fi.txt", "\u{fb01}.txt"],
2266            ["caf\u{e9}.txt", "cafe\u{301}.txt"],
2267        ] {
2268            let c = clashes(&pair);
2269            assert_eq!(c.met_in.len(), 1, "{pair:?}");
2270            assert!(c.beyond_ascii.is_some(), "{pair:?}");
2271        }
2272        assert!(clashes(&["\u{65e5}.txt", "\u{4e2d}.txt"]).met_in.is_empty());
2273    }
2274
2275    /// Three that clash have to name every folder where any two meet, here
2276    /// `x` as well as the top, or a casefolded `x` would go unnoticed.
2277    #[test]
2278    fn clashes_cover_every_folder_where_names_meet() {
2279        let met = clashes(&["X/a/f", "x/A/f", "x/a/f", "other", "OTHER2"]).met_in;
2280        assert_eq!(
2281            met.keys().collect::<Vec<_>>(),
2282            [Path::new(""), Path::new("x")]
2283        );
2284    }
2285
2286    /// A file in a separate case-sensitive branch does not stop folders
2287    /// inside the other branch from merging on a case-insensitive mount.
2288    #[test]
2289    fn directory_aliases_need_no_case_separation_in_a_fileless_branch() {
2290        let tmp = tempfile::tempdir().unwrap();
2291        let path = tmp.path().join("archive.bin");
2292        fs::write(&path, [0u8; 64]).unwrap();
2293        let storage = Arc::new(Storage::open(&path, false).unwrap());
2294        let units = ["A/f", "a/F/one.txt", "a/f/two.txt"]
2295            .iter()
2296            .enumerate()
2297            .map(|(i, name)| unit(i as u64, name, 1))
2298            .collect();
2299        let job = Job::build(storage, opened(units, 64), 64).unwrap();
2300        let clashes = job.check_layout().unwrap();
2301        assert_eq!(clashes.met_in.keys().collect::<Vec<_>>(), [Path::new("")]);
2302    }
2303
2304    /// Folders between files must still meet the file on each side. Compare
2305    /// every mixture of absent paths, folders and files with all real pairs
2306    /// across three levels, including fileless branches between two files.
2307    #[test]
2308    fn case_folders_match_every_file_file_and_file_folder_pair() {
2309        let paths = [
2310            "A/B/C", "A/B/c", "A/b/C", "A/b/c", "a/B/C", "a/B/c", "a/b/C", "a/b/c",
2311        ];
2312        for mut choices in 0..3usize.pow(paths.len() as u32) {
2313            let mut names = Vec::new();
2314            for path in paths {
2315                let kind = choices % 3;
2316                choices /= 3;
2317                if kind != 0 {
2318                    names.push((path.to_lowercase(), Path::new(path), kind == 2));
2319                }
2320            }
2321            let mut expected = std::collections::BTreeSet::new();
2322            for (i, a) in names.iter().enumerate() {
2323                for b in &names[i + 1..] {
2324                    if a.2 || b.2 {
2325                        expected.insert(meeting_folder(a.1, b.1));
2326                    }
2327                }
2328            }
2329            let clashes = CaseClashes::of(&names);
2330            assert_eq!(
2331                clashes.met_in.keys().collect::<Vec<_>>(),
2332                expected.iter().collect::<Vec<_>>(),
2333                "{names:?}"
2334            );
2335        }
2336    }
2337
2338    /// A file against thousands of folders is a pair for each neighbour, not
2339    /// one for each combination, or a small archive could exhaust memory.
2340    #[test]
2341    fn clashes_stay_linear_in_the_names() {
2342        let paths: Vec<String> = (0..4096u32)
2343            .map(|bits| {
2344                (0..12)
2345                    .map(|i| if bits >> i & 1 == 1 { 'A' } else { 'a' })
2346                    .collect()
2347            })
2348            .collect();
2349        let mut names: Vec<(String, &Path, bool)> = paths
2350            .iter()
2351            .enumerate()
2352            .map(|(i, p)| (p.to_lowercase(), Path::new(p), i % 2 == 0))
2353            .collect();
2354        names.sort_unstable();
2355        assert_eq!(CaseClashes::of(&names).met_in.len(), 1);
2356    }
2357
2358    /// U+212A KELVIN SIGN lowercases to `k`, and APFS takes it for `K` even
2359    /// on a case-sensitive volume. Noted everywhere, since a run can go on
2360    /// from one system on another.
2361    #[test]
2362    fn names_beyond_ascii_are_noted_on_every_system() {
2363        assert!(clashes(&["K.txt", "\u{212a}.txt"]).beyond_ascii.is_some());
2364        assert!(clashes(&["Makefile", "makefile"]).beyond_ascii.is_none());
2365    }
2366
2367    /// The folder asked is the one that exists nearest to where the names
2368    /// meet, not the output folder, which an earlier check would have passed.
2369    #[test]
2370    fn the_nearest_existing_folder_decides() {
2371        let tmp = tempfile::TempDir::new().unwrap();
2372        let out = tmp.path().join("out");
2373        fs::create_dir_all(out.join("mounted")).unwrap();
2374        let asked = std::cell::RefCell::new(Vec::new());
2375        let result = first_not_apart(
2376            &out,
2377            [
2378                Path::new(""),
2379                Path::new("new/deep"),
2380                Path::new("mounted/new"),
2381            ],
2382            |dir| {
2383                asked.borrow_mut().push(dir.to_path_buf());
2384                dir != out.join("mounted")
2385            },
2386        );
2387        assert_eq!(
2388            result,
2389            Some((Path::new("mounted/new"), out.join("mounted")))
2390        );
2391        assert_eq!(*asked.borrow(), [out.clone(), out.join("mounted")]);
2392    }
2393
2394    fn unit(start: u64, name: &str, size: u64) -> Unit {
2395        Unit {
2396            start,
2397            key: 0,
2398            items: vec![Item {
2399                path: name.into(),
2400                size,
2401                kind: Kind::File,
2402                mode: None,
2403                mtime: None,
2404            }],
2405            encrypted: false,
2406        }
2407    }
2408
2409    /// A 64 byte file standing in for an archive, in its own folder.
2410    fn storage(test: &str) -> (PathBuf, Arc<Storage>) {
2411        let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2412        fs::create_dir_all(&dir).unwrap();
2413        let path = dir.join("archive.bin");
2414        fs::write(&path, [0u8; 64]).unwrap();
2415        let storage = Arc::new(Storage::open(&path, false).unwrap());
2416        (dir, storage)
2417    }
2418
2419    fn opened(units: Vec<Unit>, tail_start: u64) -> Opened {
2420        Opened {
2421            name: "test",
2422            format: Box::new(NoFormat),
2423            units,
2424            tail_start,
2425        }
2426    }
2427
2428    /// An empty folder of this test's own, under the system's temporary one.
2429    fn scratch(test: &str) -> PathBuf {
2430        let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2431        let _ = fs::remove_dir_all(&dir);
2432        fs::create_dir_all(&dir).unwrap();
2433        dir
2434    }
2435
2436    /// What a batch claims must be on disk, whole, or the journal would
2437    /// truncate the archive behind a file that another program took away.
2438    #[test]
2439    fn a_batch_that_is_all_on_disk_verifies() {
2440        let out = scratch("verify-complete");
2441        fs::create_dir_all(out.join("game")).unwrap();
2442        fs::write(out.join("game/a"), b"hello").unwrap();
2443        fs::write(out.join("game/empty"), b"").unwrap();
2444        let batch = [unit(10, "game/a", 5), unit(20, "game/empty", 0)];
2445        assert!(verify_extracted(&batch, &out).is_ok());
2446        fs::remove_dir_all(&out).unwrap();
2447    }
2448
2449    #[test]
2450    fn a_missing_file_fails_verification() {
2451        let out = scratch("verify-missing");
2452        let err = verify_extracted(&[unit(0, "game/gone", 12)], &out)
2453            .err()
2454            .unwrap();
2455        let text = err.to_string();
2456        assert!(text.contains("game/gone"), "{text}");
2457        assert!(text.contains("disappeared"), "{text}");
2458        assert!(text.contains("12 bytes"), "{text}");
2459        fs::remove_dir_all(&out).unwrap();
2460    }
2461
2462    #[test]
2463    fn a_file_of_the_wrong_size_fails_verification() {
2464        let out = scratch("verify-size");
2465        fs::create_dir_all(out.join("game")).unwrap();
2466        fs::write(out.join("game/a"), b"abc").unwrap();
2467        let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2468            .err()
2469            .unwrap();
2470        let text = err.to_string();
2471        assert!(text.contains("game/a"), "{text}");
2472        assert!(text.contains("records 5 bytes"), "{text}");
2473        assert!(text.contains("has 3"), "{text}");
2474        fs::remove_dir_all(&out).unwrap();
2475    }
2476
2477    #[test]
2478    fn a_folder_at_the_name_of_a_file_fails_verification() {
2479        let out = scratch("verify-folder");
2480        fs::create_dir_all(out.join("game/a")).unwrap();
2481        let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2482            .err()
2483            .unwrap();
2484        assert!(err.to_string().contains("no longer a file"), "{err}");
2485        fs::remove_dir_all(&out).unwrap();
2486    }
2487
2488    /// The link points at a file of exactly the recorded size, so only a
2489    /// check that never follows links can refuse it.
2490    #[cfg(unix)]
2491    #[test]
2492    fn a_link_at_the_name_of_a_file_fails_verification() {
2493        let out = scratch("verify-link");
2494        fs::write(out.join("real"), b"hello").unwrap();
2495        std::os::unix::fs::symlink("real", out.join("link")).unwrap();
2496        let err = verify_extracted(&[unit(0, "link", 5)], &out).err().unwrap();
2497        assert!(err.to_string().contains("no longer a file"), "{err}");
2498        fs::remove_dir_all(&out).unwrap();
2499    }
2500
2501    /// Folders and links are not on disk yet when a batch commits; links are
2502    /// made at the very end.
2503    #[test]
2504    fn other_kinds_of_entries_are_not_verified() {
2505        let out = scratch("verify-kinds");
2506        let item = |kind: Kind| Item {
2507            path: "absent".into(),
2508            size: 0,
2509            kind,
2510            mode: None,
2511            mtime: None,
2512        };
2513        let batch = Unit {
2514            start: 0,
2515            key: 0,
2516            items: vec![
2517                item(Kind::Dir),
2518                item(Kind::Symlink),
2519                item(Kind::HardLink("absent".into())),
2520            ],
2521            encrypted: false,
2522        };
2523        assert!(verify_extracted(&[batch], &out).is_ok());
2524        fs::remove_dir_all(&out).unwrap();
2525    }
2526
2527    /// Committing one of two units that start at the same offset would
2528    /// truncate the other before it is extracted.
2529    #[test]
2530    fn units_sharing_a_start_are_refused() {
2531        let (dir, storage) = storage("shared-start");
2532        let shared = vec![unit(10, "a", 1), unit(30, "b", 1), unit(10, "c", 1)];
2533        let err = Job::build(storage.clone(), opened(shared, 40), 64)
2534            .err()
2535            .unwrap();
2536        assert!(err.to_string().contains("same offset"), "{err:#}");
2537        let apart = vec![unit(10, "a", 1), unit(30, "b", 1)];
2538        assert!(Job::build(storage, opened(apart, 40), 64).is_ok());
2539        fs::remove_dir_all(&dir).unwrap();
2540    }
2541
2542    /// A unit at or past the end of the file used to be dropped as if an
2543    /// earlier run had extracted it, and a tail past the end can't be saved.
2544    #[test]
2545    fn data_past_the_end_of_the_file_is_refused() {
2546        let (dir, storage) = storage("past-the-end");
2547        for (starts, tail_start) in [(vec![10, 64], 40), (vec![10, 70], 40), (vec![10], 65)] {
2548            let units = starts
2549                .iter()
2550                .map(|&s| unit(s, &format!("f{s}"), 1))
2551                .collect();
2552            let err = Job::build(storage.clone(), opened(units, tail_start), 64)
2553                .err()
2554                .unwrap();
2555            assert!(err.is::<archive::Damaged>(), "{starts:?}: {err:#}");
2556        }
2557        // Resumed with the end already truncated away, it is simply done.
2558        let job = Job::build(
2559            storage,
2560            opened(vec![unit(10, "a", 1), unit(50, "b", 1)], 60),
2561            40,
2562        );
2563        assert_eq!(job.unwrap().units.len(), 1);
2564        fs::remove_dir_all(&dir).unwrap();
2565    }
2566
2567    /// Sizes come from the archive's headers. Summed or rounded up to whole
2568    /// blocks in 64 bits they could wrap, and the space check would count
2569    /// next to nothing.
2570    #[test]
2571    fn sizes_too_large_to_add_up_are_refused() {
2572        let (dir, storage) = storage("huge-sizes");
2573        let half = 1u64 << 63;
2574        for sizes in [vec![half, half], vec![u64::MAX - 10], vec![(1 << 62) + 1]] {
2575            let units = sizes
2576                .iter()
2577                .enumerate()
2578                .map(|(i, &s)| unit(10 + i as u64, &format!("f{i}"), s))
2579                .collect();
2580            let err = Job::build(storage.clone(), opened(units, 40), 64)
2581                .err()
2582                .unwrap();
2583            assert!(err.is::<archive::Damaged>(), "{sizes:?}: {err:#}");
2584        }
2585        assert_eq!(on_disk(&unit(0, "f", u64::MAX - 10)), u64::MAX);
2586        let mut two = unit(0, "f", half);
2587        two.items.extend(unit(0, "g", half).items);
2588        assert_eq!(two.size(), u64::MAX);
2589        assert_eq!(on_disk(&two), u64::MAX);
2590        fs::remove_dir_all(&dir).unwrap();
2591    }
2592}