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
15use std::collections::HashSet;
16use std::fs::{self, File, OpenOptions};
17use std::io::{self, Read, Seek, SeekFrom, Write};
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::{Arc, OnceLock};
21
22use anyhow::{Context, Result, anyhow, bail};
23use rayon::prelude::*;
24
25use crate::archive::resumable::{self, Decoder};
26use crate::archive::storage::{Storage, Tail};
27use crate::archive::{self, Codec, Format, Item, Kind, Sink, Stream, Unit};
28use crate::journal::{Journal, Link, Paths, Resume};
29use crate::{fsutil, platform};
30
31/// Larger batches extract in parallel better, smaller ones redo less work
32/// after a crash and keep the archive shrinking in fine steps.
33const BATCH_MAX_UNITS: usize = 512;
34const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
35const BUF_SIZE: usize = 1024 * 1024;
36const MAX_SYMLINK: u64 = 64 * 1024;
37
38/// Output written between two resume points of a streamed unit. Each point
39/// costs a flush and a journal write; the space check counts one step as the
40/// most a streamed unit holds that its archive bytes don't offset.
41const STREAM_STEP: u64 = 256 * 1024 * 1024;
42
43fn stream_step() -> u64 {
44    test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
45}
46
47/// Units smaller than this are always extracted whole: streaming one would
48/// save less than a couple of steps.
49fn stream_threshold() -> u64 {
50    2 * stream_step()
51}
52
53/// The test suite streams every unit it can, whether it fits or not, so the
54/// streaming path runs on small archives.
55fn always_stream() -> bool {
56    test_knob("HATCHZIP_STREAM_STEP").is_some()
57}
58
59fn on_disk(u: &Unit) -> u64 {
60    u.items.iter().map(|i| i.size.next_multiple_of(4096)).sum()
61}
62
63pub struct Job {
64    pub storage: Arc<Storage>,
65    pub format_name: &'static str,
66    format: Box<dyn Format>,
67    /// Units still to do, highest offset first.
68    pub units: Vec<Unit>,
69    pub tail_start: u64,
70    /// Where the archive currently ends: its original length, or wherever
71    /// the last commit truncated it.
72    pub top: u64,
73    /// Whether the archive's filesystem can free bytes inside a file, and
74    /// how much of a punched range it may keep allocated at each end. Probed
75    /// once, on first use.
76    punch: OnceLock<Option<u64>>,
77    /// The streamed unit a previous run left half done, if any.
78    resume: Option<Resume>,
79}
80
81impl Job {
82    /// `password` is only needed for encrypted archives. A missing one shows
83    /// up as [`archive::PasswordNeeded`], from here or from
84    /// [`Job::check_password`].
85    pub fn open(path: &Path, writable: bool, password: Option<&str>) -> Result<Self> {
86        let storage = Arc::new(Storage::open(path, writable)?);
87        let opened = archive::open(&storage, None, password)?;
88        let top = storage.original_len();
89        Self::build(storage, opened, top)
90    }
91
92    /// Reopens an archive a previous run already started on. A read-only
93    /// open leaves a pending truncation for the next writable one. The
94    /// password is never stored, so an encrypted archive needs it again.
95    pub fn resume(
96        journal: &Journal,
97        tail: Arc<Tail>,
98        writable: bool,
99        password: Option<&str>,
100    ) -> Result<Self> {
101        let storage = Arc::new(Storage::from_parts(&journal.parts, writable)?);
102        let current = storage.current_len()?;
103        if current < journal.committed_len {
104            bail!(
105                "{} is shorter than HatchZip left it and will not be modified",
106                storage.primary().display()
107            );
108        }
109        if current > journal.committed_len && writable {
110            // The last run committed a batch but stopped before truncating.
111            storage.set_len(journal.committed_len)?;
112        }
113        let opened = archive::open(&storage, Some((&journal.format, tail)), password)?;
114        let mut job = Self::build(storage, opened, journal.committed_len)?;
115        if let Some(r) = &journal.resume {
116            // Only the highest uncommitted unit is ever streamed, so a point
117            // for any other one means the journal and archive disagree.
118            if job.units.first().map(|u| u.start) != Some(r.unit) {
119                bail!(
120                    "the journal of {} records a partially extracted file that is not the next one \
121                     in the archive. The archive will not be modified",
122                    job.storage.primary().display()
123                );
124            }
125            job.resume = Some(r.clone());
126        }
127        Ok(job)
128    }
129
130    fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
131        let mut units = opened.units;
132        units.retain(|u| u.start < top);
133        units.sort_by_key(|u| std::cmp::Reverse(u.start));
134
135        let mut seen = HashSet::new();
136        for item in units.iter().flat_map(|u| &u.items) {
137            for part in item.path.iter() {
138                if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
139                    bail!(
140                        "'{}' cannot be created at this location: {why}. The archive was not modified",
141                        item.path.display()
142                    );
143                }
144            }
145            // Case-insensitive filesystems would let two items race for one
146            // file inside a parallel batch.
147            if item.kind != Kind::Dir && !seen.insert(item.path.to_string_lossy().to_lowercase()) {
148                bail!(
149                    "'{}' appears more than once in the archive (ignoring case); extraction refused",
150                    item.path.display()
151                );
152            }
153        }
154        Ok(Self {
155            storage,
156            format_name: opened.name,
157            format: opened.format,
158            units,
159            tail_start: opened.tail_start,
160            top,
161            punch: OnceLock::new(),
162            resume: None,
163        })
164    }
165
166    /// `Some(granule)` if holes punched in the archive give its space back,
167    /// where `granule` is how much may stay allocated at each end of a
168    /// punched range. `None` on filesystems that can only truncate, such as
169    /// FAT32 and exFAT, which keep today's whole-unit behavior.
170    pub fn punch_support(&self) -> Option<u64> {
171        *self.punch.get_or_init(|| {
172            if test_knob("HATCHZIP_NO_PUNCH").is_some() {
173                return None;
174            }
175            let dir = match self.storage.primary().parent() {
176                Some(d) if !d.as_os_str().is_empty() => d,
177                _ => Path::new("."),
178            };
179            fsutil::can_punch(dir).then(|| platform::punch_granule(dir))
180        })
181    }
182
183    pub fn encrypted(&self) -> bool {
184        self.units.iter().any(|u| u.encrypted)
185    }
186
187    /// Proves the password before anything is deleted: decrypts the smallest
188    /// encrypted unit, which checks its CRC, up to a limit so a huge solid
189    /// block doesn't stall. ZipCrypto accepts about one wrong password in 256
190    /// at first sight; reading the data catches those.
191    pub fn check_password(&self) -> Result<()> {
192        const ENOUGH: u64 = 64 * 1024 * 1024;
193        let Some(unit) = self
194            .units
195            .iter()
196            .filter(|u| u.encrypted)
197            .min_by_key(|u| u.size())
198        else {
199            return Ok(());
200        };
201        let mut worker = self.format.worker(1)?;
202        let mut sink = ProbeSink {
203            left: ENOUGH,
204            buf: vec![0; BUF_SIZE],
205        };
206        match worker.extract(unit, &mut sink) {
207            Ok(()) => Ok(()),
208            Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
209            Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
210            Err(_) => Err(archive::WrongPassword.into()),
211        }
212    }
213
214    pub fn item_count(&self) -> usize {
215        self.units.iter().map(|u| u.items.len()).sum()
216    }
217
218    pub fn remaining_size(&self) -> u64 {
219        let done = self.resume.as_ref().map_or(0, |r| r.written);
220        self.units.iter().map(Unit::size).sum::<u64>() - done
221    }
222
223    /// The resume point recorded for `units[i]`, if it is half streamed.
224    fn resumed(&self, i: usize) -> Option<&Resume> {
225        self.resume
226            .as_ref()
227            .filter(|r| r.unit == self.units[i].start)
228    }
229
230    /// Where the data of `units[i]` lies, if it is one file whose decoding
231    /// can be resumed from the middle.
232    fn stream_of(&self, i: usize) -> Option<Stream> {
233        let unit = &self.units[i];
234        match unit.items.as_slice() {
235            [item] if item.kind == Kind::File && !unit.encrypted => {
236                self.format.stream(unit).ok().flatten()
237            }
238            _ => None,
239        }
240    }
241
242    /// Whether `units[i]` may free its own archive bytes while it is
243    /// extracted. A half-streamed unit always continues streaming: the bytes
244    /// before its resume point may be gone.
245    fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
246        if self.resumed(i).is_some() {
247            return self.stream_of(i);
248        }
249        if !reclaims || self.units[i].size() < stream_threshold() {
250            return None;
251        }
252        self.punch_support()?;
253        self.stream_of(i)
254    }
255
256    /// Bytes freed once `units[i]` is committed: everything from its start up
257    /// to whatever came after it.
258    fn span(&self, i: usize) -> u64 {
259        let end = if i == 0 {
260            self.top
261        } else {
262            self.units[i - 1].start
263        };
264        end - self.units[i].start
265    }
266
267    /// Replays the extraction one unit at a time and returns `(peak, end)`:
268    /// the most free space it ever consumes beyond what is free now, and how
269    /// much it consumes once finished. `fresh` means the tail hasn't been
270    /// saved yet; `reclaims` that freed archive space lands on the output's
271    /// disk.
272    pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
273        let tail = (self.storage.original_len() - self.tail_start) as i128;
274        let mut extra: i128 = if fresh { tail } else { 0 };
275        let mut peak = extra;
276        for (i, u) in self.units.iter().enumerate() {
277            let span = self.span(i) as i128;
278            if let Some(s) = self.streams(i, reclaims) {
279                let (rise, net) = self.stream_cost(i, &s, span, reclaims);
280                peak = peak.max(extra + rise);
281                extra += net;
282                continue;
283            }
284            let on_disk = on_disk(u) as i128;
285            peak = peak.max(extra + on_disk);
286            extra += on_disk;
287            if reclaims {
288                extra -= span;
289            }
290        }
291        if reclaims {
292            // Whatever precedes the first unit is deleted at the very end,
293            // along with the saved tail.
294            let stub = self.units.last().map_or(self.top, |u| u.start);
295            extra -= stub as i128 + tail;
296        }
297        (peak.max(0) as u64, extra)
298    }
299
300    /// What streaming `units[i]` costs in free space: `(rise, net)`, the most
301    /// it consumes at any moment and what it consumes once committed.
302    ///
303    /// At any moment the unit holds the output written since the last resume
304    /// point (at most a step, plus one read buffer or deflate block), the
305    /// archive bytes at either end of the punched range the filesystem keeps
306    /// (a granule each), and however far the output so far has outgrown the
307    /// input it came from. For stored data that last part is zero. For
308    /// deflate it only grows as decoding goes on, since encoders fall back to
309    /// stored blocks rather than expand data, so the end state bounds it; a
310    /// 1/1024 margin covers block headers.
311    ///
312    /// Without punching (the filesystem stopped supporting it after a run
313    /// began), the unit holds all of its remaining output until it commits.
314    fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
315        let at = self.resumed(i);
316        // What a crashed run already wrote is on disk, so the free space
317        // measured now has paid for it.
318        let done = at.map_or(0, |r| r.written / 4096 * 4096);
319        let out_left = (on_disk(&self.units[i]) - done) as i128;
320        let read_to = at.map_or(s.data_start, |r| r.bit / 8);
321        let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
322        // At most this much was punched already. It is free now, so the
323        // final truncation gives back that much less; assuming the most
324        // keeps the estimate on the safe side.
325        let freed = read_to.saturating_sub(s.data_start) as i128;
326        let net = if reclaims {
327            out_left - (span - freed)
328        } else {
329            out_left
330        };
331        let rise = match self.punch_support() {
332            Some(granule) if reclaims => {
333                let slack = match s.codec {
334                    Codec::Stored => 0,
335                    Codec::Deflate => out_left / 1024,
336                };
337                let step = (stream_step() + BUF_SIZE as u64 + 2 * granule) as i128;
338                ((out_left - data_left).max(0) + slack + step).min(out_left)
339            }
340            _ => out_left,
341        };
342        (rise, net)
343    }
344
345    /// Output a crashed run wrote for units it never committed. The output
346    /// folder started empty, so anything at those paths is ours. A
347    /// half-streamed file is not in the list: its archive bytes may be gone,
348    /// so it is the only copy of its first part.
349    pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
350        let mut found = Vec::new();
351        for (i, u) in self.units.iter().enumerate() {
352            if self.resumed(i).is_some() {
353                continue;
354            }
355            for item in &u.items {
356                if item.kind != Kind::File {
357                    continue;
358                }
359                let dest = out.join(&item.path);
360                for p in [part_path(&dest), dest] {
361                    if let Ok(m) = fs::symlink_metadata(&p)
362                        && m.is_file()
363                    {
364                        found.push((p, m.len().next_multiple_of(4096)));
365                    }
366                }
367            }
368        }
369        found
370    }
371
372    /// Output a crashed stream wrote past its last resume point. It is cut
373    /// off before the stream continues, so it counts as free.
374    pub fn past_resume_point(&self, out: &Path) -> u64 {
375        let Some(r) = self.resume.as_ref() else {
376            return 0;
377        };
378        let Some(item) = self.units.first().and_then(|u| u.items.first()) else {
379            return 0;
380        };
381        let dest = out.join(&item.path);
382        [part_path(&dest), dest]
383            .iter()
384            .find_map(|p| fs::metadata(p).ok())
385            .map_or(0, |m| {
386                (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
387            })
388    }
389
390    /// Reads every unit and lets the decoders check their checksums,
391    /// writing nothing.
392    pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
393        let threads = threads_per_unit(self.units.len());
394        let failures: Vec<String> = self
395            .units
396            .par_iter()
397            .map_init(
398                || {
399                    (
400                        self.format.worker(threads),
401                        VerifySink {
402                            on_bytes,
403                            buf: vec![0; BUF_SIZE],
404                        },
405                    )
406                },
407                |(worker, sink), unit| {
408                    let mut run = || -> Result<()> {
409                        let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
410                        w.extract(unit, sink)
411                    };
412                    run().err().map(|e| format!("{e:#}"))
413                },
414            )
415            .flatten()
416            .collect();
417        if failures.is_empty() {
418            return Ok(());
419        }
420        let mut msg = format!("{} damaged:", failures.len());
421        for f in failures.iter().take(10) {
422            msg.push_str("\n  ");
423            msg.push_str(f);
424        }
425        Err(anyhow!(msg))
426    }
427}
428
429fn threads_per_unit(units: usize) -> u32 {
430    let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
431    (cores / units.max(1)).max(1) as u32
432}
433
434fn part_path(dest: &Path) -> PathBuf {
435    let mut part = dest.as_os_str().to_owned();
436    part.push(".hatchzip-part");
437    PathBuf::from(part)
438}
439
440/// Opens a streamed file's part file positioned at `written`, cutting off
441/// anything written after that point.
442fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
443    if written == 0 {
444        return OpenOptions::new()
445            .read(true)
446            .write(true)
447            .create(true)
448            .truncate(true)
449            .open(part)
450            .with_context(|| format!("creating {}", part.display()));
451    }
452    if !part.exists() && dest.exists() {
453        // The previous run finished the file and renamed it, then stopped
454        // before committing. The point it journaled still holds.
455        fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
456    }
457    let mut file = OpenOptions::new()
458        .read(true)
459        .write(true)
460        .open(part)
461        .with_context(|| {
462            format!(
463                "{} is missing, and the archive data it was extracted from is already \
464                 released, so this file cannot be completed",
465                part.display()
466            )
467        })?;
468    if file.metadata()?.len() < written {
469        bail!(
470            "{} is shorter than when its progress was saved; the extraction cannot continue",
471            part.display()
472        );
473    }
474    file.set_len(written)?;
475    file.seek(SeekFrom::Start(written))?;
476    Ok(file)
477}
478
479/// The output just before `written`, which a deflate stream may refer back
480/// to. It is on disk, flushed before the point was journaled, so the
481/// journal doesn't have to carry it.
482fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
483    let n = written.min(resumable::WINDOW as u64);
484    let mut window = vec![0; n as usize];
485    file.seek(SeekFrom::Start(written - n))?;
486    file.read_exact(&mut window)?;
487    file.seek(SeekFrom::Start(written))?;
488    Ok(window)
489}
490
491pub struct Progress {
492    pub on_bytes: Box<dyn Fn(u64) + Sync>,
493    pub on_commit: Box<dyn Fn(u64) + Sync>,
494}
495
496pub enum Outcome {
497    Finished,
498    Paused,
499}
500
501pub struct Run<'a> {
502    pub job: Job,
503    pub journal: Journal,
504    pub paths: Paths,
505    pub stop: &'a AtomicBool,
506    pub progress: Progress,
507    /// Free space the run must never eat into.
508    pub keep_free: u64,
509}
510
511impl Run<'_> {
512    pub fn execute(mut self) -> Result<Outcome> {
513        let out = self.journal.output.clone();
514        fs::create_dir_all(&out)
515            .with_context(|| format!("creating output folder {}", out.display()))?;
516
517        let reclaims = fsutil::same_filesystem(self.job.storage.primary(), &out);
518        let mut next = 0;
519        while next < self.job.units.len() {
520            if self.stop.load(Ordering::Relaxed) {
521                return Ok(Outcome::Paused);
522            }
523            if let Some(stream) = self.stream_now(next, reclaims, &out)? {
524                if !self.stream_unit(next, &stream, &out)? {
525                    return Ok(Outcome::Paused);
526                }
527                self.commit(next, next + 1, Vec::new(), &out)?;
528                next += 1;
529                continue;
530            }
531            let end = self.next_batch(next, &out, reclaims)?;
532            let batch = &self.job.units[next..end];
533
534            let Some(links) = self.extract_batch(batch, &out)? else {
535                return Ok(Outcome::Paused);
536            };
537            self.commit(next, end, links, &out)?;
538            next = end;
539        }
540
541        self.finish(&out)?;
542        Ok(Outcome::Finished)
543    }
544
545    /// Commits `units[start..end]`, all extracted, and truncates the archive
546    /// behind them.
547    fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
548        let batch = &self.job.units[start..end];
549        // The journal must never claim a file that a power cut could still
550        // take back, since its archive bytes are about to be truncated.
551        platform::sync_batch(out).context("flushing extracted files to disk")?;
552        if platform::SYNC_EACH_FILE {
553            // Links are only recorded here and made at the end, so their
554            // folders may not exist yet.
555            let dirs: HashSet<PathBuf> = batch
556                .iter()
557                .flat_map(|u| &u.items)
558                .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
559                .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
560                .collect();
561            for d in &dirs {
562                fsutil::sync_dir(d)?;
563            }
564        }
565        crash_point("after-extract");
566
567        let new_len = batch.last().expect("batches are never empty").start;
568        self.journal.committed_len = new_len;
569        self.journal.links.extend(links);
570        // A streamed unit's point is spent once the unit itself is claimed;
571        // both change in the same atomic write.
572        self.journal.resume = None;
573        self.job.resume = None;
574        self.journal.save(&self.paths)?;
575        crash_point("after-journal");
576
577        self.job
578            .storage
579            .set_len(new_len)
580            .context("shrinking the archive")?;
581        (self.progress.on_commit)(new_len);
582        Ok(())
583    }
584
585    /// Whether `units[i]` is extracted by streaming: always if it is half
586    /// streamed already, otherwise if it can be and its output wouldn't fit
587    /// whole in the space there is right now. When it fits, the ordinary
588    /// path is faster, since it extracts many units in parallel.
589    fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
590        if self.job.resumed(i).is_some() {
591            return match self.job.stream_of(i) {
592                Some(s) => Ok(Some(s)),
593                None => bail!(
594                    "the journal records '{}' as partially extracted, but it cannot be resumed",
595                    self.job.units[i].items[0].path.display()
596                ),
597            };
598        }
599        let Some(stream) = self.job.streams(i, reclaims) else {
600            return Ok(None);
601        };
602        if always_stream() {
603            return Ok(Some(stream));
604        }
605        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
606        Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
607    }
608
609    /// Extracts the one file of `units[i]` while freeing the archive bytes
610    /// behind it. Returns false if a stop request interrupted it; the last
611    /// resume point stays in the journal and the next run continues there.
612    ///
613    /// The order at every point is what makes a crash harmless: the output
614    /// up to the point is flushed, then the point is journaled, and only then
615    /// is the archive punched, never past the byte the point restarts in. A
616    /// crash before the journal write leaves the previous point in force,
617    /// and everything it needs is still in the archive.
618    fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
619        let unit_start = self.job.units[i].start;
620        let item = self.job.units[i].items[0].clone();
621        let dest = out.join(&item.path);
622        let part = part_path(&dest);
623        let at = self.job.resumed(i).cloned().unwrap_or(Resume {
624            unit: unit_start,
625            written: 0,
626            bit: stream.data_start * 8,
627            crc: 0,
628        });
629        let started_here = at.written == 0;
630        let result = self
631            .stream_file(&item, stream, at, &dest, &part, out)
632            .with_context(|| format!("extracting '{}'", item.path.display()));
633        if result.is_err() && started_here && self.journal.resume.is_none() {
634            // Nothing was punched yet, so the next run starts this file over.
635            let _ = fs::remove_file(&part);
636        }
637        result
638    }
639
640    fn stream_file(
641        &mut self,
642        item: &Item,
643        stream: &Stream,
644        at: Resume,
645        dest: &Path,
646        part: &Path,
647        out: &Path,
648    ) -> Result<bool> {
649        if let Some(parent) = dest.parent() {
650            fs::create_dir_all(parent)?;
651        }
652        let mut file = open_part(dest, part, at.written)?;
653        let window = match stream.codec {
654            Codec::Stored => Vec::new(),
655            Codec::Deflate => read_window(&mut file, at.written)?,
656        };
657        let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
658        let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
659        let mut written = at.written;
660        let mut since_point = 0;
661        let step = stream_step();
662        let mut punching = self.job.punch_support();
663        self.ensure_room(out, item, written, punching)?;
664
665        let mut buf = vec![0; BUF_SIZE];
666        loop {
667            if self.stop.load(Ordering::Relaxed) {
668                return Ok(false);
669            }
670            let n = decoder.read(&mut buf)?;
671            if n == 0 {
672                break;
673            }
674            written += n as u64;
675            if written > item.size {
676                bail!("it is larger than the archive records");
677            }
678            file.write_all(&buf[..n])?;
679            crc.update(&buf[..n]);
680            (self.progress.on_bytes)(n as u64);
681            since_point += n as u64;
682
683            if since_point < step || written == item.size {
684                continue;
685            }
686            match decoder.restart_point() {
687                Some(bit) => {
688                    let point = Resume {
689                        unit: at.unit,
690                        written,
691                        bit,
692                        crc: crc.clone().finalize(),
693                    };
694                    punching = self.save_point(&file, part, out, point, stream, punching)?;
695                    since_point = 0;
696                    self.ensure_room(out, item, written, punching)?;
697                }
698                // A deflate block runs as long as its encoder likes; zlib-ng
699                // and zlib-rs write level 1 as a single block. Until it ends
700                // there is nowhere to resume from, so nothing can be freed,
701                // and the run has to stop before the disk fills.
702                None => {
703                    let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
704                    if avail < 2 * BUF_SIZE as u64 {
705                        bail!(
706                            "not enough disk space to continue: the compressed data of this entry has \
707                             no resume point in the last {}, so its archive space cannot be \
708                             released yet. {} more is required (the remainder of this file). \
709                             Progress is saved; free up space and resume the extraction.",
710                            human(since_point),
711                            human(item.size - written),
712                        );
713                    }
714                }
715            }
716        }
717        if written != item.size {
718            bail!("it is smaller than the archive records");
719        }
720        if let Some(expected) = stream.crc
721            && crc.finalize() != expected
722        {
723            bail!("its data is damaged (CRC mismatch)");
724        }
725        if let Some(t) = item.mtime {
726            file.set_modified(t)?;
727        }
728        platform::apply_mode(&file, item.mode)?;
729        file.sync_all()?;
730        drop(file);
731        // From here a crash leaves the finished file under its real name
732        // while the journal still holds the last point; `open_part` takes it
733        // back as the part file.
734        fs::rename(part, dest)?;
735        Ok(true)
736    }
737
738    /// Makes `point` the one a crash resumes from, then frees the archive
739    /// bytes it no longer needs. Returns whether to keep punching.
740    fn save_point(
741        &mut self,
742        file: &File,
743        part: &Path,
744        out: &Path,
745        point: Resume,
746        stream: &Stream,
747        punching: Option<u64>,
748    ) -> Result<Option<u64>> {
749        file.sync_all()
750            .context("flushing the extracted file to disk")?;
751        // The part file and the folders above it may be new; a point that
752        // outlives its file would resume into nothing.
753        let mut dir = part.parent();
754        while let Some(d) = dir {
755            fsutil::sync_dir(d)?;
756            if d == out {
757                break;
758            }
759            dir = d.parent();
760        }
761        crash_point("stream-after-sync");
762
763        self.journal.resume = Some(point.clone());
764        self.journal.save(&self.paths)?;
765        self.job.resume = Some(point.clone());
766        crash_point("stream-after-journal");
767
768        // Decoding restarts inside the byte holding `point.bit`, so that byte
769        // and everything after it must stay.
770        if punching.is_some()
771            && !self
772                .job
773                .storage
774                .punch(stream.data_start, point.bit / 8)
775                .context("freeing extracted archive bytes")?
776        {
777            // The probe said this works; if the filesystem disagrees after
778            // all, the run continues without freeing anything mid-file.
779            return Ok(None);
780        }
781        crash_point("stream-after-punch");
782        Ok(punching)
783    }
784
785    /// Stops a stream at a resume point, before it writes what doesn't fit.
786    fn ensure_room(
787        &self,
788        out: &Path,
789        item: &Item,
790        written: u64,
791        punching: Option<u64>,
792    ) -> Result<()> {
793        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
794        let left = (item.size - written).next_multiple_of(4096);
795        let need = match punching {
796            Some(granule) => (stream_step() + BUF_SIZE as u64 + 2 * granule).min(left),
797            None => left,
798        };
799        if need > avail {
800            bail!(
801                "not enough disk space to continue: the next part of '{}' requires {} and {} is \
802                 available ({} reserved).\n{} more is required. Progress is saved; free up space \
803                 and resume the extraction.",
804                item.path.display(),
805                human(need),
806                human(avail),
807                human(self.keep_free),
808                human(need - avail),
809            );
810        }
811        Ok(())
812    }
813
814    /// Pick units starting at `start` whose output fits in the space there is
815    /// right now. Always takes at least one, or explains why it can't.
816    fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
817        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
818        let units = &self.job.units;
819        let need = on_disk;
820        let first = need(&units[start]);
821        if first > avail {
822            // The upfront check makes this rare: it takes something else on
823            // the machine filling the disk while we run.
824            let what = match units[start].items.as_slice() {
825                [one] => format!("'{}'", one.path.display()),
826                many => format!("the next block of {} files", many.len()),
827            };
828            bail!(
829                "not enough disk space to continue: {what} requires {} and {} is available \
830                 ({} reserved).\n{} more is required. Progress is saved; free up space and \
831                 resume the extraction.",
832                human(first),
833                human(avail),
834                human(self.keep_free),
835                human(first - avail),
836            );
837        }
838        let budget = avail.min(BATCH_MAX_BYTES.max(first));
839        let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
840        let mut used = 0;
841        let mut end = start;
842        while end < units.len() && end - start < max_units {
843            let size = need(&units[end]);
844            if end > start && used + size > budget {
845                break;
846            }
847            if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
848                break;
849            }
850            used += size;
851            end += 1;
852        }
853        Ok(end)
854    }
855
856    /// Returns `None` if a stop request interrupted the batch. Nothing in the
857    /// archive has been touched at that point, so the batch simply reruns.
858    fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
859        let threads = threads_per_unit(batch.len());
860        let on_bytes = &*self.progress.on_bytes;
861        let results: Vec<Result<Vec<Link>>> = batch
862            .par_iter()
863            .map_init(
864                || {
865                    let sink = DiskSink {
866                        out,
867                        stop: self.stop,
868                        on_bytes,
869                        buf: vec![0; BUF_SIZE],
870                        links: Vec::new(),
871                    };
872                    (self.job.format.worker(threads), sink)
873                },
874                |(worker, sink), unit| {
875                    let w = worker
876                        .as_mut()
877                        .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
878                    w.extract(unit, sink)?;
879                    Ok(std::mem::take(&mut sink.links))
880                },
881            )
882            .collect();
883
884        let mut links = Vec::new();
885        let mut interrupted = false;
886        for r in results {
887            match r {
888                Ok(l) => links.extend(l),
889                Err(e) if is_interrupt(&e) => interrupted = true,
890                Err(e) => return Err(e),
891            }
892        }
893        Ok((!interrupted).then_some(links))
894    }
895
896    fn finish(self, out: &Path) -> Result<()> {
897        make_links(&self.journal.links, out)?;
898        let Self { job, paths, .. } = self;
899        let Job {
900            storage, format, ..
901        } = job;
902        // The format holds its own handle on the storage; it has to go first.
903        drop(format);
904        let storage = Arc::try_unwrap(storage)
905            .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
906        // What is left is at most a self-extractor stub in front of the
907        // first entry. The saved index goes with it.
908        storage.remove()?;
909        paths.remove()
910    }
911}
912
913/// A run that crashed after deleting the archive but before cleaning up only
914/// has its links and side files left to deal with.
915pub fn finish_orphaned(journal: &Journal, paths: &Paths) -> Result<()> {
916    make_links(&journal.links, &journal.output)?;
917    paths.remove()
918}
919
920pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
921    for link in links {
922        let path = out.join(&link.path);
923        if let Some(parent) = path.parent() {
924            fs::create_dir_all(parent)?;
925        }
926        let made = if link.hard {
927            let target = out.join(&link.target);
928            let _ = fs::remove_file(&path);
929            // FAT32 and exFAT have no hard links; a copy is the next best thing.
930            fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))
931        } else {
932            platform::create_symlink(&path, &link.target)
933        };
934        made.with_context(|| format!("creating link '{}'", link.path.display()))?;
935    }
936    Ok(())
937}
938
939struct DiskSink<'a> {
940    out: &'a Path,
941    stop: &'a AtomicBool,
942    on_bytes: &'a (dyn Fn(u64) + Sync),
943    buf: Vec<u8>,
944    links: Vec<Link>,
945}
946
947impl Sink for DiskSink<'_> {
948    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
949        self.write(item, data)
950            .with_context(|| format!("extracting '{}'", item.path.display()))
951    }
952}
953
954impl DiskSink<'_> {
955    fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
956        let dest = self.out.join(&item.path);
957        match &item.kind {
958            Kind::Dir => {
959                fs::create_dir_all(&dest)?;
960                return Ok(());
961            }
962            Kind::Symlink => {
963                let mut target = Vec::new();
964                data.take(MAX_SYMLINK).read_to_end(&mut target)?;
965                let target = PathBuf::from(String::from_utf8(target)?);
966                self.links.push(Link {
967                    path: item.path.clone(),
968                    target,
969                    hard: false,
970                });
971                return Ok(());
972            }
973            Kind::HardLink(target) => {
974                self.links.push(Link {
975                    path: item.path.clone(),
976                    target: target.clone(),
977                    hard: true,
978                });
979                return Ok(());
980            }
981            Kind::File => {}
982        }
983
984        if let Some(parent) = dest.parent() {
985            fs::create_dir_all(parent)?;
986        }
987        let part = part_path(&dest);
988        let result = self.copy(item, data, &part);
989        if result.is_err() {
990            let _ = fs::remove_file(&part);
991            return result;
992        }
993        fs::rename(&part, &dest)?;
994        Ok(())
995    }
996
997    fn copy(&mut self, item: &Item, data: &mut dyn Read, part: &Path) -> Result<()> {
998        let mut dst = File::create(part)?;
999        let mut written = 0u64;
1000        loop {
1001            if self.stop.load(Ordering::Relaxed) {
1002                return Err(io::Error::from(io::ErrorKind::Interrupted).into());
1003            }
1004            // Decoders check their CRC when the stream ends, so a read error
1005            // here is how corruption surfaces.
1006            let n = data.read(&mut self.buf)?;
1007            if n == 0 {
1008                break;
1009            }
1010            written += n as u64;
1011            if written > item.size {
1012                bail!("it is larger than the archive records");
1013            }
1014            dst.write_all(&self.buf[..n])?;
1015            (self.on_bytes)(n as u64);
1016        }
1017        if written != item.size {
1018            bail!("it is smaller than the archive records");
1019        }
1020        if let Some(t) = item.mtime {
1021            dst.set_modified(t)?;
1022        }
1023        platform::apply_mode(&dst, item.mode)?;
1024        if platform::SYNC_EACH_FILE {
1025            dst.sync_all()?;
1026        }
1027        Ok(())
1028    }
1029}
1030
1031/// Reads at most `left` bytes, then stops the decoder with [`ProbeDone`].
1032struct ProbeSink {
1033    left: u64,
1034    buf: Vec<u8>,
1035}
1036
1037#[derive(Debug)]
1038struct ProbeDone;
1039
1040impl std::fmt::Display for ProbeDone {
1041    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1042        f.write_str("read enough to prove the password")
1043    }
1044}
1045
1046impl std::error::Error for ProbeDone {}
1047
1048impl Sink for ProbeSink {
1049    fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
1050        loop {
1051            let n = data.read(&mut self.buf)?;
1052            if n == 0 {
1053                return Ok(());
1054            }
1055            self.left = self.left.saturating_sub(n as u64);
1056            if self.left == 0 {
1057                return Err(ProbeDone.into());
1058            }
1059        }
1060    }
1061}
1062
1063struct VerifySink<'a> {
1064    on_bytes: &'a (dyn Fn(u64) + Sync),
1065    buf: Vec<u8>,
1066}
1067
1068impl Sink for VerifySink<'_> {
1069    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
1070        let mut read = 0;
1071        loop {
1072            let n = data
1073                .read(&mut self.buf)
1074                .with_context(|| format!("'{}'", item.path.display()))?;
1075            if n == 0 {
1076                break;
1077            }
1078            read += n as u64;
1079            (self.on_bytes)(n as u64);
1080        }
1081        if item.kind == Kind::File && read != item.size {
1082            bail!(
1083                "'{}' is shorter than the archive records",
1084                item.path.display()
1085            );
1086        }
1087        Ok(())
1088    }
1089}
1090
1091fn is_interrupt(e: &anyhow::Error) -> bool {
1092    e.chain()
1093        .filter_map(|c| c.downcast_ref::<io::Error>())
1094        .any(|io| io.kind() == io::ErrorKind::Interrupted)
1095}
1096
1097/// Settings only the test suite uses. Release builds ignore them.
1098fn test_knob(name: &str) -> Option<u32> {
1099    if !cfg!(debug_assertions) {
1100        return None;
1101    }
1102    std::env::var(name).ok()?.parse().ok()
1103}
1104
1105/// Lets the test suite kill the process at the two moments that matter for
1106/// crash safety: after a batch is on disk, and after it is journaled.
1107pub(crate) fn crash_point(name: &str) {
1108    if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
1109        return;
1110    }
1111    static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1112    if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
1113        std::process::abort();
1114    }
1115}
1116
1117pub fn human(bytes: u64) -> String {
1118    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
1119    let mut v = bytes as f64;
1120    let mut unit = 0;
1121    while v >= 1000.0 && unit < UNITS.len() - 1 {
1122        v /= 1000.0;
1123        unit += 1;
1124    }
1125    if unit == 0 {
1126        format!("{bytes} B")
1127    } else {
1128        format!("{v:.1} {}", UNITS[unit])
1129    }
1130}