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::{HashMap, HashSet};
31use std::fs::{self, File, OpenOptions};
32use std::io::{self, Read, Seek, SeekFrom, Write};
33use std::path::{Path, PathBuf};
34use std::sync::atomic::{AtomicBool, Ordering};
35use std::sync::{Arc, OnceLock};
36
37use anyhow::{Context, Result, anyhow, bail};
38use rayon::prelude::*;
39
40use crate::archive::resumable::{self, Decoder};
41use crate::archive::storage::{Reads, Storage, Tail};
42use crate::archive::targz::{Event, Profile, Walker};
43use crate::archive::{self, Codec, Format, Item, Kind, PasswordCheck, Sink, Stream, Unit};
44use crate::journal::{Journal, Link, Paths, Resume, TarAt};
45use crate::{fsutil, platform};
46
47/// Larger batches extract in parallel better, smaller ones redo less work
48/// after a crash and keep the archive shrinking in fine steps.
49const BATCH_MAX_UNITS: usize = 512;
50const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
51const BUF_SIZE: usize = 1024 * 1024;
52const MAX_SYMLINK: u64 = 64 * 1024;
53
54/// Output written between two resume points of a streamed unit. Each point
55/// costs a flush and a journal write; the space check counts one step as the
56/// most a streamed unit holds that its archive bytes don't offset.
57const STREAM_STEP: u64 = 256 * 1024 * 1024;
58
59fn stream_step() -> u64 {
60    test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
61}
62
63/// Units smaller than this are always extracted whole: streaming one would
64/// save less than a couple of steps.
65fn stream_threshold() -> u64 {
66    2 * stream_step()
67}
68
69/// The test suite streams every unit it can, whether it fits or not, so the
70/// streaming path runs on small archives.
71fn always_stream() -> bool {
72    test_knob("HATCHZIP_STREAM_STEP").is_some()
73}
74
75fn on_disk(u: &Unit) -> u64 {
76    u.items.iter().map(|i| i.size.next_multiple_of(4096)).sum()
77}
78
79pub struct Job {
80    pub storage: Arc<Storage>,
81    pub format_name: &'static str,
82    format: Box<dyn Format>,
83    /// Units still to do, highest offset first.
84    pub units: Vec<Unit>,
85    pub tail_start: u64,
86    /// Where the archive currently ends: its original length, or wherever
87    /// the last commit truncated it.
88    pub top: u64,
89    /// Whether the archive's filesystem can free bytes inside a file, and
90    /// how much of a punched range it may keep allocated at each end. Probed
91    /// once, on first use.
92    punch: OnceLock<Option<u64>>,
93    /// The streamed unit a previous run left half done, if any.
94    resume: Option<Resume>,
95}
96
97impl Job {
98    /// `password` is only needed for encrypted archives. A missing one shows
99    /// up as [`archive::PasswordNeeded`], from here or from
100    /// [`Job::check_password`]. What opening reads is counted in `reads`.
101    pub fn open(
102        path: &Path,
103        writable: bool,
104        password: Option<&str>,
105        reads: Arc<Reads>,
106    ) -> Result<Self> {
107        let job = Self::open_as_is(path, writable, password, reads)?;
108        job.check_layout()?;
109        Ok(job)
110    }
111
112    /// [`Job::open`] without [`Job::check_layout`]. Restore checks what it
113    /// rebuilt with this: an archive an older release started on may hold
114    /// entries that collide, and giving it back is still the right thing to
115    /// do. A later extraction of it is refused as usual.
116    pub(crate) fn open_as_is(
117        path: &Path,
118        writable: bool,
119        password: Option<&str>,
120        reads: Arc<Reads>,
121    ) -> Result<Self> {
122        let mut storage = Storage::open(path, writable)?;
123        storage.count_reads(reads);
124        let storage = Arc::new(storage);
125        let opened = archive::open(&storage, None, password)?;
126        let top = storage.original_len();
127        Self::build(storage, opened, top)
128    }
129
130    /// Reopens an archive a previous run already started on. A read-only
131    /// open leaves a pending truncation for the next writable one. The
132    /// password is never stored, so an encrypted archive needs it again.
133    pub fn resume(
134        journal: &Journal,
135        tail: Arc<Tail>,
136        writable: bool,
137        password: Option<&str>,
138        reads: Arc<Reads>,
139    ) -> Result<Self> {
140        let mut storage = Storage::from_parts(&journal.parts, writable)?;
141        storage.count_reads(reads);
142        let storage = Arc::new(storage);
143        let current = storage.current_len()?;
144        if journal.keep {
145            // Never truncated, so `committed_len` only marks progress and
146            // the whole archive must still be there.
147            storage.protect();
148            if current != storage.original_len() {
149                bail!(
150                    "{} has changed since the extraction started. Put the original archive back \
151                     to resume, or run restore to discard the progress",
152                    storage.primary().display()
153                );
154            }
155        }
156        if current < journal.committed_len {
157            bail!(
158                "{} is shorter than HatchZip left it and will not be modified",
159                storage.primary().display()
160            );
161        }
162        if current > journal.committed_len && writable && !journal.keep {
163            // The last run committed a batch but stopped before truncating.
164            storage.set_len(journal.committed_len)?;
165        }
166        let point = journal.resume.as_ref();
167        let opened = archive::open(&storage, Some((&journal.format, tail, point)), password)?;
168        let mut job = Self::build(storage, opened, journal.committed_len)?;
169        if let Some(r) = &journal.resume {
170            // Only the highest uncommitted unit is ever streamed, so a point
171            // for any other one means the journal and archive disagree.
172            if job.units.first().map(|u| u.start) != Some(r.unit) {
173                bail!(
174                    "the journal of {} records a partially extracted file that is not the next one \
175                     in the archive. The archive will not be modified",
176                    job.storage.primary().display()
177                );
178            }
179            job.resume = Some(r.clone());
180        }
181        Ok(job)
182    }
183
184    fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
185        let mut units = opened.units;
186        units.retain(|u| u.start < top);
187        units.sort_by_key(|u| std::cmp::Reverse(u.start));
188
189        let mut seen = HashSet::new();
190        for item in units.iter().flat_map(|u| &u.items) {
191            for part in item.path.iter() {
192                if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
193                    bail!(
194                        "'{}' cannot be created at this location: {why}. The archive was not modified",
195                        item.path.display()
196                    );
197                }
198            }
199            // Case-insensitive filesystems would let two items race for one
200            // file inside a parallel batch.
201            if item.kind != Kind::Dir && !seen.insert(item.path.to_string_lossy().to_lowercase()) {
202                bail!(
203                    "'{}' appears more than once in the archive (ignoring case); extraction refused",
204                    item.path.display()
205                );
206            }
207        }
208        Ok(Self {
209            storage,
210            format_name: opened.name,
211            format: opened.format,
212            units,
213            tail_start: opened.tail_start,
214            top,
215            punch: OnceLock::new(),
216            resume: None,
217        })
218    }
219
220    /// Refuses entries that can't all be created where the archive puts
221    /// them: a file or link at a path where another entry needs a folder,
222    /// which includes any entry inside a link, and a hard link to anything
223    /// but a file in the archive. Links are only made at the very end, once
224    /// the archive is gone, so without this such an archive fails after it
225    /// has been consumed. Paths are compared ignoring case, as for
226    /// duplicates.
227    ///
228    /// Only a fresh archive is checked: a resumed run no longer lists the
229    /// entries it has extracted, and one an older release started on has to
230    /// stay resumable and restorable.
231    fn check_layout(&self) -> Result<()> {
232        let key = |p: &Path| p.to_string_lossy().to_lowercase();
233        let items = || self.units.iter().flat_map(|u| &u.items);
234        // Every folder the extraction creates, with the entry that needs it:
235        // the folder's own entry if it has one, else the first entry inside.
236        let mut folders: HashMap<String, (&Path, bool)> = HashMap::new();
237        for item in items() {
238            if item.kind == Kind::Dir {
239                folders.insert(key(&item.path), (&item.path, true));
240            }
241            for parent in item.path.ancestors().skip(1) {
242                if parent.as_os_str().is_empty() {
243                    break;
244                }
245                folders.entry(key(parent)).or_insert((&item.path, false));
246            }
247        }
248        let files: HashSet<&Path> = items()
249            .filter(|i| i.kind == Kind::File)
250            .map(|i| i.path.as_path())
251            .collect();
252        for item in items() {
253            let what = match &item.kind {
254                Kind::Dir => continue,
255                Kind::File => "a file",
256                Kind::Symlink => "a symbolic link",
257                Kind::HardLink(_) => "a hard link",
258            };
259            match folders.get(&key(&item.path)) {
260                Some((dir, true)) if *dir == item.path => bail!(
261                    "'{}' is both {what} and a folder in the archive; extraction refused",
262                    item.path.display()
263                ),
264                Some((dir, true)) => bail!(
265                    "'{}' is {what}, and '{}' is a folder in the archive; extraction refused",
266                    item.path.display(),
267                    dir.display()
268                ),
269                Some((inside, false)) => bail!(
270                    "'{}' is {what}, but '{}' requires a folder at that location; extraction \
271                     refused",
272                    item.path.display(),
273                    inside.display()
274                ),
275                None => {}
276            }
277            if let Kind::HardLink(target) = &item.kind
278                && !files.contains(target.as_path())
279            {
280                bail!(
281                    "hard link '{}' points to '{}', which is not a file in the archive; \
282                     extraction refused",
283                    item.path.display(),
284                    target.display()
285                );
286            }
287        }
288        Ok(())
289    }
290
291    /// `Some(granule)` if holes punched in the archive give its space back,
292    /// where `granule` is how much may stay allocated at each end of a
293    /// punched range. `None` on filesystems that can only truncate, such as
294    /// FAT32 and exFAT, which keep today's whole-unit behavior.
295    pub fn punch_support(&self) -> Option<u64> {
296        *self.punch.get_or_init(|| {
297            if test_knob("HATCHZIP_NO_PUNCH").is_some() {
298                return None;
299            }
300            let dir = match self.storage.primary().parent() {
301                Some(d) if !d.as_os_str().is_empty() => d,
302                _ => Path::new("."),
303            };
304            fsutil::can_punch(dir).then(|| platform::punch_granule(dir))
305        })
306    }
307
308    pub fn encrypted(&self) -> bool {
309        self.units.iter().any(|u| u.encrypted)
310    }
311
312    /// The archive is one compressed stream, extracted front to back.
313    pub fn is_stream(&self) -> bool {
314        self.format.solid().is_some()
315    }
316
317    /// The archive is one compressed stream that stays whole until the run
318    /// ends, because the filesystem can't free space inside it: the disk
319    /// has to hold the archive and every extracted file at once.
320    pub fn kept_whole(&self, reclaims: bool) -> bool {
321        self.is_stream() && reclaims && self.punch_support().is_none()
322    }
323
324    /// Proves the password before anything is deleted: decrypts the smallest
325    /// encrypted unit, which checks its CRC, up to a limit so a huge solid
326    /// block doesn't stall. ZipCrypto accepts about one wrong password in 256
327    /// at first sight; reading the data catches those.
328    pub fn check_password(&self) -> Result<()> {
329        const ENOUGH: u64 = 64 * 1024 * 1024;
330        let Some(unit) = self.smallest_encrypted() else {
331            return Ok(());
332        };
333        let left = match self.format.password_check() {
334            PasswordCheck::Headers => return self.format.prove_password(),
335            PasswordCheck::Sample => ENOUGH,
336            // A wrong password only shows in the checksum at the end, so a
337            // sample would let it through and the run would fail later, after
338            // the archive is partly gone.
339            PasswordCheck::WholeUnit => u64::MAX,
340        };
341        let mut worker = self.format.worker(1)?;
342        let mut sink = ProbeSink {
343            left,
344            buf: vec![0; BUF_SIZE],
345        };
346        match worker.extract(unit, &mut sink) {
347            Ok(()) => Ok(()),
348            Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
349            Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
350            Err(_) => Err(archive::WrongPassword.into()),
351        }
352    }
353
354    /// The smallest encrypted unit with data: an empty file decodes with
355    /// any password in formats whose only check is the file's checksum.
356    fn smallest_encrypted(&self) -> Option<&Unit> {
357        self.units
358            .iter()
359            .filter(|u| u.encrypted)
360            .min_by_key(|u| (u.size() == 0, u.size()))
361    }
362
363    /// When [`check_password`](Self::check_password) has to decode a whole
364    /// file to prove the password, as for RAR 4: that file and its size, so
365    /// a front end can say the check may take a while.
366    pub fn slow_password_check(&self) -> Option<(&Path, u64)> {
367        if !self.encrypted() || self.format.password_check() != PasswordCheck::WholeUnit {
368            return None;
369        }
370        let unit = self.smallest_encrypted()?;
371        Some((unit.items.first()?.path.as_path(), unit.size()))
372    }
373
374    /// Why the archive can't be extracted in place, if it can't. It can
375    /// still be extracted while it is kept.
376    pub fn in_place_refusal(&self) -> Option<String> {
377        self.format.refuses_in_place()
378    }
379
380    pub fn item_count(&self) -> usize {
381        self.units.iter().map(|u| u.items.len()).sum()
382    }
383
384    pub fn remaining_size(&self) -> u64 {
385        let done = self.resume.as_ref().map_or(0, |r| r.written);
386        self.units.iter().map(Unit::size).sum::<u64>() - done
387    }
388
389    /// The resume point recorded for `units[i]`, if it is half streamed.
390    fn resumed(&self, i: usize) -> Option<&Resume> {
391        self.resume
392            .as_ref()
393            .filter(|r| r.unit == self.units[i].start)
394    }
395
396    /// Where the data of `units[i]` lies, if it is one file whose decoding
397    /// can be resumed from the middle.
398    fn stream_of(&self, i: usize) -> Option<Stream> {
399        let unit = &self.units[i];
400        match unit.items.as_slice() {
401            [item] if item.kind == Kind::File && !unit.encrypted => {
402                self.format.stream(unit).ok().flatten()
403            }
404            _ => None,
405        }
406    }
407
408    /// Whether `units[i]` may free its own archive bytes while it is
409    /// extracted. A half-streamed unit always continues streaming: the bytes
410    /// before its resume point may be gone.
411    fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
412        if self.resumed(i).is_some() {
413            return self.stream_of(i);
414        }
415        if !reclaims || self.units[i].size() < stream_threshold() {
416            return None;
417        }
418        self.punch_support()?;
419        self.stream_of(i)
420    }
421
422    /// Bytes freed once `units[i]` is committed: everything from its start up
423    /// to whatever came after it.
424    fn span(&self, i: usize) -> u64 {
425        let end = if i == 0 {
426            self.top
427        } else {
428            self.units[i - 1].start
429        };
430        end - self.units[i].start
431    }
432
433    /// Replays the extraction one unit at a time and returns `(peak, end)`:
434    /// the most free space it ever consumes beyond what is free now, and how
435    /// much it consumes once finished. `fresh` means the tail hasn't been
436    /// saved yet; `reclaims` that freed archive space lands on the output's
437    /// disk.
438    pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
439        let tail = (self.storage.original_len() - self.tail_start) as i128;
440        let mut extra: i128 = if fresh { tail } else { 0 };
441        let mut peak = extra;
442        for (i, u) in self.units.iter().enumerate() {
443            let span = self.span(i) as i128;
444            if let Some(solid) = self.format.solid() {
445                let (rise, net) = self.solid_cost(i, &solid.profile, span, reclaims);
446                peak = peak.max(extra + rise);
447                extra += net;
448                continue;
449            }
450            if let Some(s) = self.streams(i, reclaims) {
451                let (rise, net) = self.stream_cost(i, &s, span, reclaims);
452                peak = peak.max(extra + rise);
453                extra += net;
454                continue;
455            }
456            let on_disk = on_disk(u) as i128;
457            peak = peak.max(extra + on_disk);
458            extra += on_disk;
459            if reclaims {
460                extra -= span;
461            }
462        }
463        if reclaims {
464            // Whatever precedes the first unit is deleted at the very end,
465            // along with the saved tail.
466            let stub = self.units.last().map_or(self.top, |u| u.start);
467            extra -= stub as i128 + tail;
468        }
469        (peak.max(0) as u64, extra)
470    }
471
472    /// What streaming `units[i]` costs in free space: `(rise, net)`, the most
473    /// it consumes at any moment and what it consumes once committed.
474    ///
475    /// At any moment the unit holds the output written since the last resume
476    /// point (at most a step, plus one read buffer or deflate block), the
477    /// archive bytes at either end of the punched range the filesystem keeps
478    /// (a granule each), and however far the output so far has outgrown the
479    /// input it came from. For stored data that last part is zero. For
480    /// deflate it only grows as decoding goes on, since encoders fall back to
481    /// stored blocks rather than expand data, so the end state bounds it; a
482    /// 1/1024 margin covers block headers.
483    ///
484    /// Without punching (the filesystem stopped supporting it after a run
485    /// began), the unit holds all of its remaining output until it commits.
486    fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
487        let at = self.resumed(i);
488        // What a crashed run already wrote is on disk, so the free space
489        // measured now has paid for it.
490        let done = at.map_or(0, |r| r.written / 4096 * 4096);
491        let out_left = (on_disk(&self.units[i]) - done) as i128;
492        let read_to = at.map_or(s.data_start, |r| r.bit / 8);
493        let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
494        // At most this much was punched already. It is free now, so the
495        // final truncation gives back that much less; assuming the most
496        // keeps the estimate on the safe side.
497        let freed = read_to.saturating_sub(s.data_start) as i128;
498        let net = if reclaims {
499            out_left - (span - freed)
500        } else {
501            out_left
502        };
503        let rise = match self.punch_support() {
504            Some(granule) if reclaims => {
505                let slack = match s.codec {
506                    Codec::Stored => 0,
507                    Codec::Deflate => out_left / 1024,
508                };
509                let step = (stream_step() + BUF_SIZE as u64 + 2 * granule) as i128;
510                ((out_left - data_left).max(0) + slack + step).min(out_left)
511            }
512            _ => out_left,
513        };
514        (rise, net)
515    }
516
517    /// What streaming a compressed tar, `units[i]`, costs in free space:
518    /// `(rise, net)` as for [`stream_cost`](Self::stream_cost).
519    ///
520    /// Before each resume point is taken, the files hold what they held at
521    /// the point before, `lead` at most ahead of the compressed bytes freed
522    /// up to it, plus what was written since: under a step, plus the output
523    /// to the next point after the step is full, at most `gap`. The scan
524    /// measured both at the very points the run will meet. A read buffer
525    /// and a granule at each end of the punched range come on top. Links are
526    /// made at the end, once the archive is gone.
527    fn solid_cost(&self, i: usize, p: &Profile, span: i128, reclaims: bool) -> (i128, i128) {
528        let out_left = (p.files + p.links) as i128;
529        // Assumed punched already, as for a single streamed file.
530        let freed = self.resumed(i).map_or(0, |r| r.bit / 8) as i128;
531        let net = if reclaims {
532            out_left - (span - freed)
533        } else {
534            out_left
535        };
536        let rise = match self.punch_support() {
537            Some(granule) if reclaims => {
538                let ahead = stream_step() + p.gap + BUF_SIZE as u64 + 2 * granule;
539                (p.lead.max(0) + ahead as i128).min(p.files as i128)
540            }
541            // Nothing is freed until the run commits, so every file is on
542            // disk next to the whole archive.
543            _ => out_left,
544        };
545        (rise.max(net), net)
546    }
547
548    /// The entry a resume point stopped inside of, if any: the first item of
549    /// the first unit, whose part file holds `written` bytes.
550    fn open_entry(&self) -> Option<&Item> {
551        let r = self.resume.as_ref()?;
552        let inside = match &r.stream {
553            Some(s) => matches!(s.at, TarAt::File { .. }),
554            None => true,
555        };
556        if !inside {
557            return None;
558        }
559        self.units.first().and_then(|u| u.items.first())
560    }
561
562    /// Output a crashed run wrote for units it never committed. The output
563    /// folder started empty, so anything at those paths is ours. A
564    /// half-streamed file is not in the list: its archive bytes may be gone,
565    /// so it is the only copy of its first part. For a compressed tar that
566    /// is the entry its point is in; the files after the point are still in
567    /// the archive.
568    pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
569        let open = self.open_entry().is_some();
570        let mut found = Vec::new();
571        for (i, u) in self.units.iter().enumerate() {
572            for (k, item) in u.items.iter().enumerate() {
573                if item.kind != Kind::File || (open && i == 0 && k == 0) {
574                    continue;
575                }
576                let dest = out.join(&item.path);
577                for p in [part_path(&dest), dest] {
578                    if let Ok(m) = fs::symlink_metadata(&p)
579                        && m.is_file()
580                    {
581                        found.push((p, m.len().next_multiple_of(4096)));
582                    }
583                }
584            }
585        }
586        found
587    }
588
589    /// Output a crashed stream wrote past its last resume point. It is cut
590    /// off before the stream continues, so it counts as free.
591    pub fn past_resume_point(&self, out: &Path) -> u64 {
592        let (Some(r), Some(item)) = (self.resume.as_ref(), self.open_entry()) else {
593            return 0;
594        };
595        let dest = out.join(&item.path);
596        [part_path(&dest), dest]
597            .iter()
598            .find_map(|p| fs::metadata(p).ok())
599            .map_or(0, |m| {
600                (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
601            })
602    }
603
604    /// Reads every unit and lets the decoders check their checksums,
605    /// writing nothing.
606    pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
607        let failures = if self.format.serial() {
608            self.verify_serial(on_bytes)?
609        } else {
610            self.verify_parallel(on_bytes)
611        };
612        if failures.is_empty() {
613            return Ok(());
614        }
615        let mut msg = format!("{} damaged:", failures.len());
616        for f in failures.iter().take(10) {
617            msg.push_str("\n  ");
618            msg.push_str(f);
619        }
620        Err(anyhow!(msg))
621    }
622
623    /// One worker walks every unit from the lowest up.
624    fn verify_serial(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<Vec<String>> {
625        let mut worker = self.format.worker(1)?;
626        let mut sink = VerifySink {
627            on_bytes,
628            buf: vec![0; BUF_SIZE],
629        };
630        Ok(self
631            .units
632            .iter()
633            .rev()
634            .filter_map(|u| worker.extract(u, &mut sink).err())
635            .map(|e| format!("{e:#}"))
636            .collect())
637    }
638
639    fn verify_parallel(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Vec<String> {
640        let threads = threads_per_unit(self.units.len());
641        self.units
642            .par_iter()
643            .map_init(
644                || {
645                    (
646                        self.format.worker(threads),
647                        VerifySink {
648                            on_bytes,
649                            buf: vec![0; BUF_SIZE],
650                        },
651                    )
652                },
653                |(worker, sink), unit| {
654                    let mut run = || -> Result<()> {
655                        let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
656                        w.extract(unit, sink)
657                    };
658                    run().err().map(|e| format!("{e:#}"))
659                },
660            )
661            .flatten()
662            .collect()
663    }
664}
665
666fn threads_per_unit(units: usize) -> u32 {
667    let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
668    (cores / units.max(1)).max(1) as u32
669}
670
671fn part_path(dest: &Path) -> PathBuf {
672    let mut part = dest.as_os_str().to_owned();
673    part.push(".hatchzip-part");
674    PathBuf::from(part)
675}
676
677/// Opens a streamed file's part file positioned at `written`, cutting off
678/// anything written after that point.
679fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
680    if written == 0 {
681        return OpenOptions::new()
682            .read(true)
683            .write(true)
684            .create(true)
685            .truncate(true)
686            .open(part)
687            .with_context(|| format!("creating {}", part.display()));
688    }
689    if !part.exists() && dest.exists() {
690        // The previous run finished the file and renamed it, then stopped
691        // before committing. The point it journaled still holds.
692        fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
693    }
694    let mut file = OpenOptions::new()
695        .read(true)
696        .write(true)
697        .open(part)
698        .with_context(|| {
699            format!(
700                "{} is missing, and the archive data it was extracted from is already \
701                 released, so this file cannot be completed",
702                part.display()
703            )
704        })?;
705    if file.metadata()?.len() < written {
706        bail!(
707            "{} is shorter than when its progress was saved; the extraction cannot continue",
708            part.display()
709        );
710    }
711    file.set_len(written)?;
712    file.seek(SeekFrom::Start(written))?;
713    Ok(file)
714}
715
716/// A file of a compressed tar being written to its part file.
717struct OpenFile {
718    item: Item,
719    dest: PathBuf,
720    part: PathBuf,
721    file: File,
722    written: u64,
723}
724
725impl OpenFile {
726    /// Gives the finished file its metadata and its real name.
727    fn finish(self) -> Result<()> {
728        if self.written != self.item.size {
729            bail!("it is smaller than the archive records");
730        }
731        if let Some(t) = self.item.mtime {
732            self.file.set_modified(t)?;
733        }
734        platform::apply_mode(&self.file, self.item.mode)?;
735        if platform::SYNC_EACH_FILE {
736            self.file.sync_all()?;
737        }
738        drop(self.file);
739        fs::rename(&self.part, &self.dest)?;
740        Ok(())
741    }
742}
743
744/// The output just before `written`, which a deflate stream may refer back
745/// to. It is on disk, flushed before the point was journaled, so the
746/// journal doesn't have to carry it.
747fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
748    let n = written.min(resumable::WINDOW as u64);
749    let mut window = vec![0; n as usize];
750    file.seek(SeekFrom::Start(written - n))?;
751    file.read_exact(&mut window)?;
752    file.seek(SeekFrom::Start(written))?;
753    Ok(window)
754}
755
756pub struct Progress {
757    pub on_bytes: Box<dyn Fn(u64) + Sync>,
758    pub on_commit: Box<dyn Fn(u64) + Sync>,
759}
760
761pub enum Outcome {
762    Finished,
763    Paused,
764}
765
766pub struct Run<'a> {
767    pub job: Job,
768    pub journal: Journal,
769    pub paths: Paths,
770    pub stop: &'a AtomicBool,
771    pub progress: Progress,
772    /// Free space the run must never eat into.
773    pub keep_free: u64,
774}
775
776impl Run<'_> {
777    pub fn execute(mut self) -> Result<Outcome> {
778        let out = self.journal.output.clone();
779        fs::create_dir_all(&out)
780            .with_context(|| format!("creating output folder {}", out.display()))?;
781
782        // Keeping the archive frees nothing, which is exactly the case of an
783        // output on another disk: nothing is streamed or punched.
784        let reclaims =
785            !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
786        if self.journal.keep {
787            self.job.storage.protect();
788        }
789        let mut next = 0;
790        while next < self.job.units.len() {
791            if self.stop.load(Ordering::Relaxed) {
792                return Ok(Outcome::Paused);
793            }
794            if let Some(solid) = self.job.format.solid() {
795                let walk = solid.walk(self.job.resumed(next))?;
796                let Some(links) = self.stream_solid(next, walk, reclaims, &out)? else {
797                    return Ok(Outcome::Paused);
798                };
799                self.commit(next, next + 1, links, &out)?;
800                next += 1;
801                continue;
802            }
803            if let Some(stream) = self.stream_now(next, reclaims, &out)? {
804                if !self.stream_unit(next, &stream, &out)? {
805                    return Ok(Outcome::Paused);
806                }
807                self.commit(next, next + 1, Vec::new(), &out)?;
808                next += 1;
809                continue;
810            }
811            let end = self.next_batch(next, &out, reclaims)?;
812            let batch = &self.job.units[next..end];
813
814            let Some(links) = self.extract_batch(batch, &out)? else {
815                return Ok(Outcome::Paused);
816            };
817            self.commit(next, end, links, &out)?;
818            next = end;
819        }
820
821        self.finish(&out)?;
822        Ok(Outcome::Finished)
823    }
824
825    /// Commits `units[start..end]`, all extracted, and truncates the archive
826    /// behind them.
827    fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
828        let batch = &self.job.units[start..end];
829        // The journal must never claim a file that a power cut could still
830        // take back, since its archive bytes are about to be truncated.
831        platform::sync_batch(out).context("flushing extracted files to disk")?;
832        if platform::SYNC_EACH_FILE {
833            // Links are only recorded here and made at the end, so their
834            // folders may not exist yet.
835            let dirs: HashSet<PathBuf> = batch
836                .iter()
837                .flat_map(|u| &u.items)
838                .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
839                .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
840                .collect();
841            for d in &dirs {
842                fsutil::sync_dir(d)?;
843            }
844        }
845        crash_point("after-extract");
846
847        let new_len = batch.last().expect("batches are never empty").start;
848        self.journal.committed_len = new_len;
849        self.journal.links.extend(links);
850        // A streamed unit's point is spent once the unit itself is claimed;
851        // both change in the same atomic write.
852        self.journal.resume = None;
853        self.job.resume = None;
854        self.journal.save(&self.paths)?;
855        crash_point("after-journal");
856
857        if self.journal.keep {
858            return Ok(());
859        }
860        self.job
861            .storage
862            .set_len(new_len)
863            .context("shrinking the archive")?;
864        (self.progress.on_commit)(new_len);
865        Ok(())
866    }
867
868    /// Whether `units[i]` is extracted by streaming: always if it is half
869    /// streamed already, otherwise if it can be and its output wouldn't fit
870    /// whole in the space there is right now. When it fits, the ordinary
871    /// path is faster, since it extracts many units in parallel.
872    fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
873        if self.job.resumed(i).is_some() {
874            return match self.job.stream_of(i) {
875                Some(s) => Ok(Some(s)),
876                None => bail!(
877                    "the journal records '{}' as partially extracted, but it cannot be resumed",
878                    self.job.units[i].items[0].path.display()
879                ),
880            };
881        }
882        let Some(stream) = self.job.streams(i, reclaims) else {
883            return Ok(None);
884        };
885        if always_stream() {
886            return Ok(Some(stream));
887        }
888        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
889        Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
890    }
891
892    /// Extracts the one file of `units[i]` while freeing the archive bytes
893    /// behind it. Returns false if a stop request interrupted it; the last
894    /// resume point stays in the journal and the next run continues there.
895    ///
896    /// The order at every point is what makes a crash harmless: the output
897    /// up to the point is flushed, then the point is journaled, and only then
898    /// is the archive punched, never past the byte the point restarts in. A
899    /// crash before the journal write leaves the previous point in force,
900    /// and everything it needs is still in the archive.
901    fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
902        let unit_start = self.job.units[i].start;
903        let item = self.job.units[i].items[0].clone();
904        let dest = out.join(&item.path);
905        let part = part_path(&dest);
906        let at = self.job.resumed(i).cloned().unwrap_or(Resume {
907            unit: unit_start,
908            written: 0,
909            bit: stream.data_start * 8,
910            crc: 0,
911            stream: None,
912        });
913        let started_here = at.written == 0;
914        let result = self
915            .stream_file(&item, stream, at, &dest, &part, out)
916            .with_context(|| format!("extracting '{}'", item.path.display()));
917        if result.is_err() && started_here && self.journal.resume.is_none() {
918            // Nothing was punched yet, so the next run starts this file over.
919            let _ = fs::remove_file(&part);
920        }
921        result
922    }
923
924    fn stream_file(
925        &mut self,
926        item: &Item,
927        stream: &Stream,
928        at: Resume,
929        dest: &Path,
930        part: &Path,
931        out: &Path,
932    ) -> Result<bool> {
933        if let Some(parent) = dest.parent() {
934            fs::create_dir_all(parent)?;
935        }
936        let mut file = open_part(dest, part, at.written)?;
937        let window = match stream.codec {
938            Codec::Stored => Vec::new(),
939            Codec::Deflate => read_window(&mut file, at.written)?,
940        };
941        let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
942        let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
943        let mut written = at.written;
944        let mut since_point = 0;
945        let step = stream_step();
946        let mut punching = self.job.punch_support();
947        let what = format!("'{}'", item.path.display());
948        self.ensure_room(out, &what, item.size - written, punching)?;
949
950        let mut buf = vec![0; BUF_SIZE];
951        loop {
952            if self.stop.load(Ordering::Relaxed) {
953                return Ok(false);
954            }
955            let n = decoder.read(&mut buf)?;
956            if n == 0 {
957                break;
958            }
959            written += n as u64;
960            if written > item.size {
961                bail!("it is larger than the archive records");
962            }
963            file.write_all(&buf[..n])?;
964            crc.update(&buf[..n]);
965            (self.progress.on_bytes)(n as u64);
966            since_point += n as u64;
967
968            if since_point < step || written == item.size {
969                continue;
970            }
971            match decoder.restart_point() {
972                Some(bit) => {
973                    let point = Resume {
974                        unit: at.unit,
975                        written,
976                        bit,
977                        crc: crc.clone().finalize(),
978                        stream: None,
979                    };
980                    punching = self.save_point(&file, part, out, point, stream, punching)?;
981                    since_point = 0;
982                    self.ensure_room(out, &what, item.size - written, punching)?;
983                }
984                // A deflate block runs as long as its encoder likes; zlib-ng
985                // and zlib-rs write level 1 as a single block. Until it ends
986                // there is nowhere to resume from, so nothing can be freed,
987                // and the run has to stop before the disk fills.
988                None => {
989                    let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
990                    if avail < 2 * BUF_SIZE as u64 {
991                        bail!(
992                            "not enough disk space to continue: the compressed data of this entry has \
993                             no resume point in the last {}, so its archive space cannot be \
994                             released yet. {} more is required (the remainder of this file). \
995                             Progress is saved; free up space and resume the extraction.",
996                            human(since_point),
997                            human(item.size - written),
998                        );
999                    }
1000                }
1001            }
1002        }
1003        if written != item.size {
1004            bail!("it is smaller than the archive records");
1005        }
1006        if let Some(expected) = stream.crc
1007            && crc.finalize() != expected
1008        {
1009            bail!("its data is damaged (CRC mismatch)");
1010        }
1011        if let Some(t) = item.mtime {
1012            file.set_modified(t)?;
1013        }
1014        platform::apply_mode(&file, item.mode)?;
1015        file.sync_all()?;
1016        drop(file);
1017        // From here a crash leaves the finished file under its real name
1018        // while the journal still holds the last point; `open_part` takes it
1019        // back as the part file.
1020        fs::rename(part, dest)?;
1021        Ok(true)
1022    }
1023
1024    /// Makes `point` the one a crash resumes from, then frees the archive
1025    /// bytes it no longer needs. Returns whether to keep punching.
1026    fn save_point(
1027        &mut self,
1028        file: &File,
1029        part: &Path,
1030        out: &Path,
1031        point: Resume,
1032        stream: &Stream,
1033        punching: Option<u64>,
1034    ) -> Result<Option<u64>> {
1035        file.sync_all()
1036            .context("flushing the extracted file to disk")?;
1037        // The part file and the folders above it may be new; a point that
1038        // outlives its file would resume into nothing.
1039        let mut dir = part.parent();
1040        while let Some(d) = dir {
1041            fsutil::sync_dir(d)?;
1042            if d == out {
1043                break;
1044            }
1045            dir = d.parent();
1046        }
1047        crash_point("stream-after-sync");
1048
1049        self.journal.resume = Some(point.clone());
1050        self.journal.save(&self.paths)?;
1051        self.job.resume = Some(point.clone());
1052        crash_point("stream-after-journal");
1053
1054        // Decoding restarts inside the byte holding `point.bit`, so that byte
1055        // and everything after it must stay.
1056        if punching.is_some()
1057            && !self
1058                .job
1059                .storage
1060                .punch(stream.data_start, point.bit / 8)
1061                .context("freeing extracted archive bytes")?
1062        {
1063            // The probe said this works; if the filesystem disagrees after
1064            // all, the run continues without freeing anything mid-file.
1065            return Ok(None);
1066        }
1067        crash_point("stream-after-punch");
1068        Ok(punching)
1069    }
1070
1071    /// Extracts a compressed tar, `units[i]`, front to back from `walk`,
1072    /// freeing the compressed bytes behind the decoder. Returns the links
1073    /// found since the last resume point, for the commit, or `None` if a
1074    /// stop request interrupted it; the last point stays in the journal and
1075    /// the next run continues there.
1076    ///
1077    /// Each point follows the order of [`stream_unit`](Self::stream_unit):
1078    /// every file written before it is flushed, then the point is journaled,
1079    /// with the links found so far, and only then is the archive punched up
1080    /// to the byte it restarts in. Files finished after the last point are
1081    /// written again on resume, the half-written one is cut back to the
1082    /// point.
1083    fn stream_solid(
1084        &mut self,
1085        i: usize,
1086        mut walk: Walker,
1087        reclaims: bool,
1088        out: &Path,
1089    ) -> Result<Option<Vec<Link>>> {
1090        let unit = self.job.units[i].start;
1091        let step = stream_step();
1092        // With the output on another disk, freeing the archive's space
1093        // doesn't help it, and the space check didn't count on it.
1094        let mut punching = self.job.punch_support().filter(|_| reclaims);
1095        let profile = match self.job.format.solid() {
1096            Some(s) => s.profile.clone(),
1097            None => bail!("the archive is not a compressed stream"),
1098        };
1099        let mut left = profile.files;
1100        // This run hasn't punched anything yet. Its first punch starts at 0,
1101        // in case the last run stopped between journaling a point and
1102        // punching up to it.
1103        let mut punched = 0;
1104        let mut since_point = 0u64;
1105        let mut checked = 0u64;
1106        let mut open: Option<OpenFile> = None;
1107        let mut links = Vec::new();
1108        let mut dirs = HashSet::new();
1109        self.ensure_room(out, "the archive", left, punching)?;
1110
1111        loop {
1112            if self.stop.load(Ordering::Relaxed) {
1113                return Ok(None);
1114            }
1115            match walk.next(BUF_SIZE)? {
1116                Event::Entry { item, link, done } => {
1117                    let dest = out.join(&item.path);
1118                    let what = || format!("extracting '{}'", item.path.display());
1119                    match &item.kind {
1120                        Kind::Dir => {
1121                            fs::create_dir_all(&dest).with_context(what)?;
1122                            dirs.insert(dest);
1123                        }
1124                        Kind::Symlink => {
1125                            let target = String::from_utf8(link.unwrap_or_default())
1126                                .map_err(|_| anyhow!("the link target is not valid UTF-8"))
1127                                .with_context(what)?;
1128                            links.push(Link {
1129                                path: item.path.clone(),
1130                                target: PathBuf::from(target),
1131                                hard: false,
1132                            });
1133                        }
1134                        Kind::HardLink(target) => links.push(Link {
1135                            path: item.path.clone(),
1136                            target: target.clone(),
1137                            hard: true,
1138                        }),
1139                        Kind::File => {
1140                            if let Some(parent) = dest.parent() {
1141                                fs::create_dir_all(parent).with_context(what)?;
1142                            }
1143                            let part = part_path(&dest);
1144                            let file = open_part(&dest, &part, done).with_context(what)?;
1145                            open = Some(OpenFile {
1146                                item,
1147                                dest,
1148                                part,
1149                                file,
1150                                written: done,
1151                            });
1152                        }
1153                    }
1154                }
1155                Event::Data(bytes) => {
1156                    let f = open
1157                        .as_mut()
1158                        .ok_or_else(|| anyhow!("the tar stream holds data outside a file"))?;
1159                    f.file
1160                        .write_all(bytes)
1161                        .with_context(|| format!("extracting '{}'", f.item.path.display()))?;
1162                    let n = bytes.len() as u64;
1163                    f.written += n;
1164                    since_point += n;
1165                    left = left.saturating_sub(n);
1166                    (self.progress.on_bytes)(n);
1167                    // A deflate block runs as long as its encoder likes, and
1168                    // until it ends there is nowhere to resume from, so nothing
1169                    // can be freed: stop before the disk fills.
1170                    if punching.is_some()
1171                        && since_point >= step
1172                        && since_point - checked >= BUF_SIZE as u64
1173                    {
1174                        checked = since_point;
1175                        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1176                        if avail < 2 * BUF_SIZE as u64 {
1177                            bail!(
1178                                "not enough disk space to continue: the compressed data has no \
1179                                 resume point in the last {}, so its space cannot be released \
1180                                 yet. {} more is required (the remainder of the archive). \
1181                                 Progress is saved; free up space and resume the extraction.",
1182                                human(since_point),
1183                                human(left),
1184                            );
1185                        }
1186                    }
1187                }
1188                Event::FileEnd => {
1189                    let f = open
1190                        .take()
1191                        .ok_or_else(|| anyhow!("the tar stream ends a file it never began"))?;
1192                    let pad = f.item.size.next_multiple_of(4096) - f.item.size;
1193                    let path = f.item.path.clone();
1194                    let parent = f.dest.parent().map(Path::to_path_buf);
1195                    f.finish()
1196                        .with_context(|| format!("extracting '{}'", path.display()))?;
1197                    dirs.extend(parent);
1198                    since_point += pad;
1199                    left = left.saturating_sub(pad);
1200                }
1201                Event::Point => {
1202                    if since_point < step {
1203                        continue;
1204                    }
1205                    let mut point = walk.point()?;
1206                    point.unit = unit;
1207                    punching = self.solid_point(
1208                        point,
1209                        open.as_ref(),
1210                        &mut links,
1211                        &mut dirs,
1212                        out,
1213                        punching,
1214                        &mut punched,
1215                    )?;
1216                    since_point = 0;
1217                    checked = 0;
1218                    self.ensure_room(out, "the archive", left, punching)?;
1219                }
1220                Event::End => break,
1221            }
1222        }
1223        if open.is_some() {
1224            bail!("the tar stream ended inside a file");
1225        }
1226        Ok(Some(links))
1227    }
1228
1229    /// Makes `point` the one a crash resumes from, then frees the archive
1230    /// bytes before it. Returns whether to keep punching.
1231    #[allow(clippy::too_many_arguments)]
1232    fn solid_point(
1233        &mut self,
1234        point: Resume,
1235        open: Option<&OpenFile>,
1236        links: &mut Vec<Link>,
1237        dirs: &mut HashSet<PathBuf>,
1238        out: &Path,
1239        punching: Option<u64>,
1240        punched: &mut u64,
1241    ) -> Result<Option<u64>> {
1242        if let Some(f) = open {
1243            f.file
1244                .sync_all()
1245                .context("flushing the extracted file to disk")?;
1246            dirs.extend(f.part.parent().map(Path::to_path_buf));
1247        }
1248        platform::sync_batch(out).context("flushing extracted files to disk")?;
1249        if platform::SYNC_EACH_FILE {
1250            // Files were flushed as they were finished; their names live in
1251            // the folders, which may be new themselves.
1252            let mut done = HashSet::new();
1253            for d in dirs.drain() {
1254                let mut dir = Some(d.as_path());
1255                while let Some(d) = dir {
1256                    if !done.insert(d.to_path_buf()) {
1257                        break;
1258                    }
1259                    fsutil::sync_dir(d)?;
1260                    if d == out {
1261                        break;
1262                    }
1263                    dir = d.parent();
1264                }
1265            }
1266        }
1267        dirs.clear();
1268        crash_point("stream-after-sync");
1269
1270        let byte = point.bit / 8;
1271        self.journal.links.append(links);
1272        self.journal.resume = Some(point.clone());
1273        self.journal.save(&self.paths)?;
1274        self.job.resume = Some(point);
1275        crash_point("stream-after-journal");
1276
1277        if punching.is_some() {
1278            if !self
1279                .job
1280                .storage
1281                .punch(*punched, byte)
1282                .context("freeing extracted archive bytes")?
1283            {
1284                return Ok(None);
1285            }
1286            *punched = byte;
1287            (self.progress.on_commit)(self.job.top - byte);
1288        }
1289        crash_point("stream-after-punch");
1290        Ok(punching)
1291    }
1292
1293    /// Stops a stream at a resume point, before it writes what doesn't fit.
1294    /// `left` is the output still to write.
1295    fn ensure_room(&self, out: &Path, what: &str, left: u64, punching: Option<u64>) -> Result<()> {
1296        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1297        let left = left.next_multiple_of(4096);
1298        let need = match punching {
1299            Some(granule) => (stream_step() + BUF_SIZE as u64 + 2 * granule).min(left),
1300            None => left,
1301        };
1302        if need > avail {
1303            bail!(
1304                "not enough disk space to continue: the next part of {} requires {} and {} is \
1305                 available ({} reserved).\n{} more is required. Progress is saved; free up space \
1306                 and resume the extraction.",
1307                what,
1308                human(need),
1309                human(avail),
1310                human(self.keep_free),
1311                human(need - avail),
1312            );
1313        }
1314        Ok(())
1315    }
1316
1317    /// Pick units starting at `start` whose output fits in the space there is
1318    /// right now. Always takes at least one, or explains why it can't.
1319    fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
1320        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1321        let units = &self.job.units;
1322        let need = on_disk;
1323        let first = need(&units[start]);
1324        if first > avail {
1325            // The upfront check makes this rare: it takes something else on
1326            // the machine filling the disk while we run.
1327            let what = match units[start].items.as_slice() {
1328                [one] => format!("'{}'", one.path.display()),
1329                many => format!("the next block of {} files", many.len()),
1330            };
1331            bail!(
1332                "not enough disk space to continue: {what} requires {} and {} is available \
1333                 ({} reserved).\n{} more is required. Progress is saved; free up space and \
1334                 resume the extraction.",
1335                human(first),
1336                human(avail),
1337                human(self.keep_free),
1338                human(first - avail),
1339            );
1340        }
1341        let budget = avail.min(BATCH_MAX_BYTES.max(first));
1342        let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
1343        let mut used = 0;
1344        let mut end = start;
1345        while end < units.len() && end - start < max_units {
1346            let size = need(&units[end]);
1347            if end > start && used + size > budget {
1348                break;
1349            }
1350            if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
1351                break;
1352            }
1353            used += size;
1354            end += 1;
1355        }
1356        Ok(end)
1357    }
1358
1359    /// Returns `None` if a stop request interrupted the batch. Nothing in the
1360    /// archive has been touched at that point, so the batch simply reruns.
1361    fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
1362        let on_bytes = &*self.progress.on_bytes;
1363        if self.job.format.serial() {
1364            let mut sink = DiskSink {
1365                out,
1366                stop: self.stop,
1367                on_bytes,
1368                buf: vec![0; BUF_SIZE],
1369                links: Vec::new(),
1370            };
1371            let mut worker = self
1372                .job
1373                .format
1374                .worker(1)
1375                .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1376            // Lowest first, so the worker reads the archive front to back.
1377            for unit in batch.iter().rev() {
1378                match worker.extract(unit, &mut sink) {
1379                    Ok(()) => {}
1380                    Err(e) if is_interrupt(&e) => return Ok(None),
1381                    Err(e) => return Err(e),
1382                }
1383            }
1384            return Ok(Some(sink.links));
1385        }
1386        let threads = threads_per_unit(batch.len());
1387        let results: Vec<Result<Vec<Link>>> = batch
1388            .par_iter()
1389            .map_init(
1390                || {
1391                    let sink = DiskSink {
1392                        out,
1393                        stop: self.stop,
1394                        on_bytes,
1395                        buf: vec![0; BUF_SIZE],
1396                        links: Vec::new(),
1397                    };
1398                    (self.job.format.worker(threads), sink)
1399                },
1400                |(worker, sink), unit| {
1401                    let w = worker
1402                        .as_mut()
1403                        .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1404                    w.extract(unit, sink)?;
1405                    Ok(std::mem::take(&mut sink.links))
1406                },
1407            )
1408            .collect();
1409
1410        let mut links = Vec::new();
1411        let mut interrupted = false;
1412        for r in results {
1413            match r {
1414                Ok(l) => links.extend(l),
1415                Err(e) if is_interrupt(&e) => interrupted = true,
1416                Err(e) => return Err(e),
1417            }
1418        }
1419        Ok((!interrupted).then_some(links))
1420    }
1421
1422    fn finish(self, out: &Path) -> Result<()> {
1423        make_final_links(&self.journal.links, out)?;
1424        if self.journal.keep {
1425            // The archive stays as it was; only the progress files go.
1426            return self.paths.remove();
1427        }
1428        let Self { job, paths, .. } = self;
1429        let Job {
1430            storage, format, ..
1431        } = job;
1432        // The format holds its own handle on the storage; it has to go first.
1433        drop(format);
1434        let storage = Arc::try_unwrap(storage)
1435            .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
1436        // What is left is at most a self-extractor stub in front of the
1437        // first entry. The saved index goes with it.
1438        storage.remove()?;
1439        paths.remove()
1440    }
1441}
1442
1443/// A run that crashed after deleting the archive but before cleaning up only
1444/// has its links and side files left to deal with.
1445pub fn finish_orphaned(journal: &Journal, paths: &Paths) -> Result<()> {
1446    make_final_links(&journal.links, &journal.output)?;
1447    paths.remove()
1448}
1449
1450/// The last step of a run, when every file is extracted and the archive is
1451/// gone: a link that can't be made is all that is left. The journal keeps
1452/// the links, so once the cause is fixed a resumed run makes them and
1453/// finishes.
1454fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
1455    make_links(links, out).map_err(|e| {
1456        anyhow!(
1457            "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
1458             each one, for example by moving or renaming a folder that is in the way, then \
1459             resume the extraction to create them"
1460        )
1461    })
1462}
1463
1464/// Makes `links`. Each one is tried, and the error lists every one that
1465/// failed and why. Links that were made are made again by the next call,
1466/// replacing themselves.
1467pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
1468    let failed: Vec<(&Link, anyhow::Error)> = links
1469        .iter()
1470        .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
1471        .collect();
1472    if failed.is_empty() {
1473        return Ok(());
1474    }
1475    let mut msg = match failed.len() {
1476        1 => "1 link could not be created:".to_string(),
1477        n => format!("{n} links could not be created:"),
1478    };
1479    for (link, e) in failed.iter().take(10) {
1480        let kind = if link.hard {
1481            "hard link"
1482        } else {
1483            "symbolic link"
1484        };
1485        msg.push_str(&format!(
1486            "\n  '{}' ({kind} to '{}'): {e:#}",
1487            link.path.display(),
1488            link.target.display()
1489        ));
1490    }
1491    if failed.len() > 10 {
1492        msg.push_str(&format!("\n  and {} more", failed.len() - 10));
1493    }
1494    Err(anyhow!(msg))
1495}
1496
1497fn make_link(link: &Link, out: &Path) -> Result<()> {
1498    // A run an older release started may hold a link inside another link.
1499    // Going through it would write outside the output folder.
1500    if let Some(via) = link_on_the_way(out, &link.path) {
1501        bail!(
1502            "'{}' is a link, and this one would be created through it",
1503            via.display()
1504        );
1505    }
1506    let path = out.join(&link.path);
1507    if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
1508        bail!("a folder already exists at this location");
1509    }
1510    if let Some(parent) = path.parent() {
1511        fs::create_dir_all(parent)?;
1512    }
1513    if link.hard {
1514        if let Some(via) = link_on_the_way(out, &link.target) {
1515            bail!(
1516                "'{}' is a link, and the target would be reached through it",
1517                via.display()
1518            );
1519        }
1520        let target = out.join(&link.target);
1521        let _ = fs::remove_file(&path);
1522        // FAT32 and exFAT have no hard links; a copy is the next best thing.
1523        fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
1524    } else {
1525        platform::create_symlink(&path, &link.target)?;
1526    }
1527    Ok(())
1528}
1529
1530/// The first folder on the way to `rel` inside `out` that is really a link.
1531fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
1532    let mut ancestors: Vec<&Path> = rel
1533        .ancestors()
1534        .skip(1)
1535        .filter(|p| !p.as_os_str().is_empty())
1536        .collect();
1537    ancestors.reverse();
1538    ancestors
1539        .into_iter()
1540        .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
1541        .map(Path::to_path_buf)
1542}
1543
1544struct DiskSink<'a> {
1545    out: &'a Path,
1546    stop: &'a AtomicBool,
1547    on_bytes: &'a (dyn Fn(u64) + Sync),
1548    buf: Vec<u8>,
1549    links: Vec<Link>,
1550}
1551
1552impl Sink for DiskSink<'_> {
1553    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1554        self.write(item, data)
1555            .with_context(|| format!("extracting '{}'", item.path.display()))
1556    }
1557}
1558
1559impl DiskSink<'_> {
1560    fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1561        let dest = self.out.join(&item.path);
1562        match &item.kind {
1563            Kind::Dir => {
1564                fs::create_dir_all(&dest)?;
1565                return Ok(());
1566            }
1567            Kind::Symlink => {
1568                let mut target = Vec::new();
1569                data.take(MAX_SYMLINK).read_to_end(&mut target)?;
1570                let target = PathBuf::from(String::from_utf8(target)?);
1571                self.links.push(Link {
1572                    path: item.path.clone(),
1573                    target,
1574                    hard: false,
1575                });
1576                return Ok(());
1577            }
1578            Kind::HardLink(target) => {
1579                self.links.push(Link {
1580                    path: item.path.clone(),
1581                    target: target.clone(),
1582                    hard: true,
1583                });
1584                return Ok(());
1585            }
1586            Kind::File => {}
1587        }
1588
1589        if let Some(parent) = dest.parent() {
1590            fs::create_dir_all(parent)?;
1591        }
1592        let part = part_path(&dest);
1593        let result = self.copy(item, data, &part);
1594        if result.is_err() {
1595            let _ = fs::remove_file(&part);
1596            return result;
1597        }
1598        fs::rename(&part, &dest)?;
1599        Ok(())
1600    }
1601
1602    fn copy(&mut self, item: &Item, data: &mut dyn Read, part: &Path) -> Result<()> {
1603        let mut dst = File::create(part)?;
1604        let mut written = 0u64;
1605        loop {
1606            if self.stop.load(Ordering::Relaxed) {
1607                return Err(io::Error::from(io::ErrorKind::Interrupted).into());
1608            }
1609            // Decoders check their CRC when the stream ends, so a read error
1610            // here is how corruption surfaces.
1611            let n = data.read(&mut self.buf)?;
1612            if n == 0 {
1613                break;
1614            }
1615            written += n as u64;
1616            if written > item.size {
1617                bail!("it is larger than the archive records");
1618            }
1619            dst.write_all(&self.buf[..n])?;
1620            (self.on_bytes)(n as u64);
1621        }
1622        if written != item.size {
1623            bail!("it is smaller than the archive records");
1624        }
1625        if let Some(t) = item.mtime {
1626            dst.set_modified(t)?;
1627        }
1628        platform::apply_mode(&dst, item.mode)?;
1629        if platform::SYNC_EACH_FILE {
1630            dst.sync_all()?;
1631        }
1632        Ok(())
1633    }
1634}
1635
1636/// Reads at most `left` bytes, then stops the decoder with [`ProbeDone`].
1637struct ProbeSink {
1638    left: u64,
1639    buf: Vec<u8>,
1640}
1641
1642#[derive(Debug)]
1643struct ProbeDone;
1644
1645impl std::fmt::Display for ProbeDone {
1646    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1647        f.write_str("read enough to prove the password")
1648    }
1649}
1650
1651impl std::error::Error for ProbeDone {}
1652
1653impl Sink for ProbeSink {
1654    fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
1655        loop {
1656            let n = data.read(&mut self.buf)?;
1657            if n == 0 {
1658                return Ok(());
1659            }
1660            self.left = self.left.saturating_sub(n as u64);
1661            if self.left == 0 {
1662                return Err(ProbeDone.into());
1663            }
1664        }
1665    }
1666}
1667
1668struct VerifySink<'a> {
1669    on_bytes: &'a (dyn Fn(u64) + Sync),
1670    buf: Vec<u8>,
1671}
1672
1673impl Sink for VerifySink<'_> {
1674    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1675        let mut read = 0;
1676        loop {
1677            let n = data
1678                .read(&mut self.buf)
1679                .with_context(|| format!("'{}'", item.path.display()))?;
1680            if n == 0 {
1681                break;
1682            }
1683            read += n as u64;
1684            (self.on_bytes)(n as u64);
1685        }
1686        if item.kind == Kind::File && read != item.size {
1687            bail!(
1688                "'{}' is shorter than the archive records",
1689                item.path.display()
1690            );
1691        }
1692        Ok(())
1693    }
1694}
1695
1696fn is_interrupt(e: &anyhow::Error) -> bool {
1697    e.chain()
1698        .filter_map(|c| c.downcast_ref::<io::Error>())
1699        .any(|io| io.kind() == io::ErrorKind::Interrupted)
1700}
1701
1702/// Settings only the test suite uses. Release builds ignore them.
1703fn test_knob(name: &str) -> Option<u32> {
1704    if !cfg!(debug_assertions) {
1705        return None;
1706    }
1707    std::env::var(name).ok()?.parse().ok()
1708}
1709
1710/// Lets the test suite kill the process at the two moments that matter for
1711/// crash safety: after a batch is on disk, and after it is journaled.
1712pub(crate) fn crash_point(name: &str) {
1713    if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
1714        return;
1715    }
1716    static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1717    if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
1718        std::process::abort();
1719    }
1720}
1721
1722pub fn human(bytes: u64) -> String {
1723    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
1724    let mut v = bytes as f64;
1725    let mut unit = 0;
1726    while v >= 1000.0 && unit < UNITS.len() - 1 {
1727        v /= 1000.0;
1728        unit += 1;
1729    }
1730    if unit == 0 {
1731        format!("{bytes} B")
1732    } else {
1733        format!("{v:.1} {}", UNITS[unit])
1734    }
1735}