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