Skip to main content

hatchzip_core/
engine.rs

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