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//!
30//! An extraction of some entries only ([`Job::select`]) must keep the
31//! archive, since truncating it would destroy the entries left out. Units
32//! with nothing selected are dropped from the job; a unit that holds both,
33//! such as a solid 7z block, is still decoded whole, and what was not
34//! selected is read and discarded.
35
36use std::collections::{BTreeMap, HashMap, HashSet};
37use std::fs::{self, File};
38use std::io::{self, Read, Seek, SeekFrom, Write};
39use std::path::{Component, Path, PathBuf};
40use std::sync::atomic::{AtomicBool, Ordering};
41use std::sync::{Arc, OnceLock};
42
43use anyhow::{Context, Result, anyhow, bail};
44use rayon::prelude::*;
45
46use crate::archive::resumable::{self, Decoder};
47use crate::archive::storage::{Reads, Storage, Tail};
48use crate::archive::targz::{Event, Profile};
49use crate::archive::{
50    self, Codec, Format, Item, Kind, PasswordCheck, Sink, SolidWalker, Stream, Unit,
51};
52use crate::journal::{Journal, Link, Paths, Resume, TarAt};
53use crate::{folders, fsutil, platform, replace};
54
55/// Larger batches extract in parallel better, smaller ones redo less work
56/// after a crash and keep the archive shrinking in fine steps.
57const BATCH_MAX_UNITS: usize = 512;
58const BATCH_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
59const BUF_SIZE: usize = 1024 * 1024;
60const MAX_SYMLINK: u64 = 64 * 1024;
61
62/// Output written between two resume points of a streamed unit. Each point
63/// costs a flush and a journal write; the space check counts one step as the
64/// most a streamed unit holds that its archive bytes don't offset.
65const STREAM_STEP: u64 = 256 * 1024 * 1024;
66
67fn stream_step() -> u64 {
68    test_knob("HATCHZIP_STREAM_STEP").map_or(STREAM_STEP, u64::from)
69}
70
71/// Units smaller than this are always extracted whole: streaming one would
72/// save less than a couple of steps.
73fn stream_threshold() -> u64 {
74    2 * stream_step()
75}
76
77/// The test suite streams every unit it can, whether it fits or not, so the
78/// streaming path runs on small archives.
79fn always_stream() -> bool {
80    test_knob("HATCHZIP_STREAM_STEP").is_some()
81}
82
83/// More than any disk holds. An archive whose files add up to more is
84/// refused, so the space check's sums of sizes stay far from overflowing.
85const MAX_TOTAL_SIZE: u64 = 1 << 62;
86
87/// The most an archive may hold after its last unit: the index and whatever
88/// else is saved before the extraction starts.
89fn max_tail() -> u64 {
90    test_knob("HATCHZIP_MAX_TAIL").map_or(1_000_000_000, u64::from)
91}
92
93fn on_disk(u: &Unit) -> u64 {
94    u.items.iter().fold(0u64, |sum, i| {
95        let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
96        sum.saturating_add(size)
97    })
98}
99
100pub struct Job {
101    pub storage: Arc<Storage>,
102    pub format_name: &'static str,
103    format: Box<dyn Format>,
104    /// Units still to do, highest offset first.
105    pub units: Vec<Unit>,
106    pub tail_start: u64,
107    /// Where the archive currently ends: its original length, or wherever
108    /// the last commit truncated it.
109    pub top: u64,
110    /// Whether the archive's filesystem can free bytes inside a file, and
111    /// what punching costs around a range there. Probed once, on first use.
112    punch: OnceLock<Option<Punch>>,
113    /// The streamed unit a previous run left half done, if any.
114    resume: Option<Resume>,
115    /// Whether a run may have extracted anything yet. Until it has, what
116    /// sits at the paths of entries belongs to the person: a fresh archive,
117    /// or a run still moving the files it replaces aside.
118    started: bool,
119    /// Entries whose paths differ only in case. A filesystem that ignores
120    /// case would put both in one place, so these depend on the destination:
121    /// see [`Job::check_case`]. A resumed run goes by what its journal
122    /// recorded when it began, since a tar no longer lists the entries it
123    /// has extracted.
124    case_clashes: Box<CaseClashes>,
125    /// The entries chosen, when only some are extracted.
126    only: Option<Only>,
127}
128
129/// The entries an extraction is limited to. `units` then holds only units
130/// with something selected, and their items only what is selected.
131struct Only {
132    /// As the journal records them: every path chosen, and the targets of
133    /// the hard links among them.
134    paths: Vec<PathBuf>,
135    /// The unit as the archive has it, for each unit that also holds entries
136    /// left out: a solid block decodes only whole, in order.
137    whole: HashMap<u64, Unit>,
138}
139
140/// Whether `path` is one of `only` or lies inside a folder among them.
141pub fn picks(only: &[PathBuf], path: &Path) -> bool {
142    only.iter().any(|p| path.starts_with(p))
143}
144
145/// A path to select, as typed: `docs`, `docs/` and `./docs` are the same
146/// folder. Anything that could not be a path inside the archive is refused.
147pub fn selection_path(given: &Path) -> Result<PathBuf> {
148    let mut path = PathBuf::new();
149    for c in given.components() {
150        match c {
151            Component::Normal(n) => path.push(n),
152            Component::CurDir => {}
153            _ => bail!(
154                "'{}' is not a path inside the archive. Give it as the archive lists it, such as \
155                 docs/readme.txt. Nothing was modified",
156                given.display()
157            ),
158        }
159    }
160    if path.as_os_str().is_empty() {
161        bail!(
162            "'{}' names no entry. Give a path as the archive lists it, such as docs/readme.txt. \
163             Nothing was modified",
164            given.display()
165        );
166    }
167    Ok(path)
168}
169
170/// How many folders of one archive may hold names that differ only in case.
171/// A run lists them in its journal, which is rewritten at every commit, and a
172/// real tree has a handful.
173const MAX_CASE_FOLDERS: usize = 1000;
174
175/// The entries of a fresh archive whose paths differ only in case.
176#[derive(Default)]
177struct CaseClashes {
178    /// One pair for each folder where such names meet, as a path inside the
179    /// output folder.
180    met_in: BTreeMap<PathBuf, (PathBuf, PathBuf)>,
181    /// A pair outside plain ASCII, which a system that normalizes names may
182    /// make one file wherever it lands.
183    beyond_ascii: Option<(PathBuf, PathBuf)>,
184    /// A resumed run has no list of its own, only what its journal recorded.
185    recorded: Vec<PathBuf>,
186    recorded_beyond_ascii: bool,
187}
188
189impl CaseClashes {
190    /// `names` is every file, link and folder, sorted: the path with case
191    /// folded, the path, and whether it is a file or link.
192    fn of(names: &[(String, &Path, bool)]) -> Self {
193        let mut clashes = Self::default();
194        for group in names.chunk_by(|a, b| a.0 == b.0) {
195            // Folders alone just merge on a filesystem that ignores case.
196            if !group.iter().any(|n| n.2) {
197                continue;
198            }
199            // A path shares the most components with the nearest file on
200            // either side. These pairs cover every meeting folder without
201            // imposing case separation between folders alone in a branch.
202            let mut previous_file = None;
203            for (_, path, is_file) in group {
204                if let Some(file) = previous_file {
205                    clashes.add_pair(file, path);
206                }
207                if *is_file {
208                    previous_file = Some(*path);
209                }
210            }
211            let mut next_file = None;
212            for (_, path, is_file) in group.iter().rev() {
213                if *is_file {
214                    next_file = Some(*path);
215                } else if let Some(file) = next_file {
216                    clashes.add_pair(path, file);
217                }
218            }
219        }
220        clashes
221    }
222
223    fn add_pair(&mut self, a: &Path, b: &Path) {
224        self.met_in
225            .entry(meeting_folder(a, b))
226            .or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
227        if !(a.to_string_lossy().is_ascii() && b.to_string_lossy().is_ascii()) {
228            self.beyond_ascii
229                .get_or_insert_with(|| (a.to_path_buf(), b.to_path_buf()));
230        }
231    }
232}
233
234/// The folder holding the first names that differ between `a` and `b`, as a
235/// path inside the output folder. That one decides: if it keeps them apart,
236/// everything below is in two different folders.
237fn meeting_folder(a: &Path, b: &Path) -> PathBuf {
238    a.components()
239        .zip(b.components())
240        .take_while(|(x, y)| x == y)
241        .map(|(x, _)| x)
242        .collect()
243}
244
245/// Whether `dir` is known to keep apart names that differ only in case. A
246/// debug build can be told it isn't, anywhere or at one folder, so that tests
247/// reach the refusals on a disk that does.
248pub(crate) fn keeps_case_apart(dir: &Path) -> bool {
249    let at = std::env::var_os("HATCHZIP_IGNORE_CASE_AT").filter(|_| cfg!(debug_assertions));
250    test_knob("HATCHZIP_IGNORE_CASE").is_none()
251        && at.is_none_or(|at| Path::new(&at) != dir)
252        && platform::case_sensitive(dir)
253}
254
255/// Whether this system can make one file of different names even where case
256/// is kept. Likewise, so that tests reach the refusal everywhere.
257fn normalizes_names() -> bool {
258    platform::NORMALIZES_NAMES || test_knob("HATCHZIP_NORMALIZE_NAMES").is_some()
259}
260
261/// What a run recorded when it began, asked again: the output folder can have
262/// moved to a filesystem that ignores case, or to a system that normalizes
263/// names, and a tar no longer lists the entries it has extracted. There, an
264/// entry left to do resolves to its twin that is already out, which a resume
265/// would overwrite and a restore would delete as its own.
266pub(crate) fn check_case_record(out: &Path, folders: &[PathBuf], beyond_ascii: bool) -> Result<()> {
267    if beyond_ascii && normalizes_names() {
268        bail!(
269            "this extraction has names that differ only in case with characters outside ASCII, \
270             which this system may treat as one file, so going on here could lose files. Go on \
271             where it started"
272        );
273    }
274    let folders = folders.iter().map(PathBuf::as_path);
275    if let Some((_, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
276        bail!(
277            "this extraction has names that differ only in case, and {} is not known to keep \
278             such names apart, so going on here could lose files. Move the output folder back \
279             to a case-sensitive filesystem and run the command again",
280            nearest.display()
281        );
282    }
283    Ok(())
284}
285
286/// The first of `folders`, paths inside `out`, whose names `apart` can't
287/// vouch for, with the folder it asked. A folder that doesn't exist yet takes
288/// after the nearest one above it that does, which can be a mount of its own.
289fn first_not_apart<'a>(
290    out: &Path,
291    folders: impl IntoIterator<Item = &'a Path>,
292    apart: impl Fn(&Path) -> bool,
293) -> Option<(&'a Path, PathBuf)> {
294    let mut known = HashMap::new();
295    for folder in folders {
296        let nearest = if folder.as_os_str().is_empty() {
297            fsutil::existing_ancestor(out)
298        } else {
299            fsutil::existing_ancestor(&out.join(folder))
300        };
301        let ok = match known.get(&nearest) {
302            Some(ok) => *ok,
303            None => {
304                let ok = apart(&nearest);
305                known.insert(nearest.clone(), ok);
306                ok
307            }
308        };
309        if !ok {
310            return Some((folder, nearest));
311        }
312    }
313    None
314}
315
316/// What freeing an archive's bytes costs around a punched range: `margin` is
317/// the most the filesystem may keep allocated at each end, which the space
318/// estimate reserves; `overlap` is how far before the last punch ended the
319/// next one starts, to free the block it kept. They differ by orders of
320/// magnitude on btrfs, where an extent is 128 MiB but a block is 4 KiB.
321#[derive(Clone, Copy, Debug)]
322pub struct Punch {
323    pub margin: u64,
324    pub overlap: u64,
325}
326
327impl Job {
328    /// `password` is only needed for encrypted archives. A missing one shows
329    /// up as [`archive::PasswordNeeded`], from here or from
330    /// [`Job::check_password`]. What opening reads is counted in `reads`.
331    pub fn open(
332        path: &Path,
333        writable: bool,
334        password: Option<&str>,
335        reads: Arc<Reads>,
336    ) -> Result<Self> {
337        let mut job = Self::open_as_is(path, writable, password, reads)?;
338        job.case_clashes = Box::new(job.check_layout()?);
339        Ok(job)
340    }
341
342    /// [`Job::open`] without [`Job::check_layout`]. Restore checks what it
343    /// rebuilt with this: an archive an older release started on may hold
344    /// entries that collide, and giving it back is still the right thing to
345    /// do. A later extraction of it is refused as usual.
346    pub(crate) fn open_as_is(
347        path: &Path,
348        writable: bool,
349        password: Option<&str>,
350        reads: Arc<Reads>,
351    ) -> Result<Self> {
352        let mut storage = Storage::open(path, writable)?;
353        storage.count_reads(reads);
354        let storage = Arc::new(storage);
355        let opened = archive::open(&storage, None, password)?;
356        let top = storage.original_len();
357        // The tail is read into memory when the extraction begins and stays
358        // there until it ends. An index is nowhere near this big. A run
359        // that already began has it loaded, so only a new one is refused.
360        if top.saturating_sub(opened.tail_start) > max_tail() {
361            bail!(
362                "this archive holds more than {} after its last entry, which HatchZip would \
363                 have to keep in memory for the whole extraction. The archive was not modified",
364                human(max_tail())
365            );
366        }
367        Self::build(storage, opened, top)
368    }
369
370    /// Reopens an archive a previous run already started on. A read-only
371    /// open leaves a pending truncation for the next writable one. The
372    /// password is never stored, so an encrypted archive needs it again.
373    pub fn resume(
374        journal: &Journal,
375        tail: Arc<Tail>,
376        writable: bool,
377        password: Option<&str>,
378        reads: Arc<Reads>,
379    ) -> Result<Self> {
380        let mut storage = Storage::from_parts(&journal.parts, writable)?;
381        storage.count_reads(reads);
382        let storage = Arc::new(storage);
383        let current = storage.current_len()?;
384        if journal.keep {
385            // Never truncated, so `committed_len` only marks progress and
386            // the whole archive must still be there.
387            storage.protect();
388            if current != storage.original_len() {
389                bail!(
390                    "{} has changed since the extraction started. Put the original archive back \
391                     to resume, or run restore to discard the progress",
392                    storage.primary().display()
393                );
394            }
395        }
396        if current < journal.committed_len {
397            bail!(
398                "{} is shorter than HatchZip left it and will not be modified",
399                storage.primary().display()
400            );
401        }
402        let point = journal.resume.as_ref();
403        let opened = archive::open(&storage, Some((&journal.format, tail, point)), password)?;
404        let mut job = Self::build(storage, opened, journal.committed_len)?;
405        if let Some(only) = &journal.only {
406            // The selection never streams, so it never leaves a point.
407            if journal.resume.is_some() {
408                bail!(
409                    "the journal of {} records a partially extracted file in an extraction of \
410                     selected entries, which never has one. The archive will not be modified",
411                    job.storage.primary().display()
412                );
413            }
414            job.restrict(only.clone());
415        }
416        job.started = journal.replace.as_ref().is_none_or(|r| r.moved);
417        job.case_clashes.recorded.clone_from(&journal.case_folders);
418        job.case_clashes.recorded_beyond_ascii = journal.case_beyond_ascii;
419        if let Some(r) = &journal.resume {
420            // Only the highest uncommitted unit is ever streamed, so a point
421            // for any other one means the journal and archive disagree.
422            if job.units.first().map(|u| u.start) != Some(r.unit) {
423                bail!(
424                    "the journal of {} records a partially extracted file that is not the next one \
425                     in the archive. The archive will not be modified",
426                    job.storage.primary().display()
427                );
428            }
429            job.resume = Some(r.clone());
430        }
431        // The last run committed a batch but stopped before truncating. Cut
432        // only once everything above agrees with the journal: one that does
433        // not belong to this archive must leave it as it was.
434        if current > journal.committed_len && writable && !journal.keep {
435            job.storage.set_len(journal.committed_len)?;
436        }
437        Ok(job)
438    }
439
440    fn build(storage: Arc<Storage>, opened: archive::Opened, top: u64) -> Result<Self> {
441        let mut units = opened.units;
442        // Units from `top` up were extracted by an earlier run. Ones that
443        // start at or past the end of the file never existed, and dropping
444        // them quietly would lose their files with the archive.
445        let len = storage.original_len();
446        if opened.tail_start > len || units.iter().any(|u| u.start >= len) {
447            return Err(archive::Damaged(anyhow!(
448                "this archive records data past the end of the file, so it is damaged or \
449                 incomplete. Nothing was modified"
450            ))
451            .into());
452        }
453        units.retain(|u| u.start < top);
454        units.sort_by_key(|u| std::cmp::Reverse(u.start));
455        // A unit owns its bytes up to the next one's start. Two that start
456        // at the same offset can't both own them: committing one would
457        // truncate the other before it is extracted.
458        if units.windows(2).any(|w| w[0].start == w[1].start) {
459            bail!(
460                "two parts of this archive start at the same offset, so extracting it in place \
461                 could destroy data before it is extracted; extraction refused"
462            );
463        }
464        let total = units
465            .iter()
466            .flat_map(|u| &u.items)
467            .try_fold(0u64, |sum, i| sum.checked_add(i.size));
468        if total.is_none_or(|t| t > MAX_TOTAL_SIZE) {
469            return Err(archive::Damaged(anyhow!(
470                "the file sizes recorded in this archive add up to more than any disk can hold, \
471                 so the archive is damaged. Nothing was modified"
472            ))
473            .into());
474        }
475
476        let mut seen = HashSet::new();
477        for item in units.iter().flat_map(|u| &u.items) {
478            for part in item.path.iter() {
479                if let Some(why) = platform::name_problem(&part.to_string_lossy()) {
480                    bail!(
481                        "'{}' cannot be created at this location: {why}. The archive was not modified",
482                        item.path.display()
483                    );
484                }
485            }
486            if item.kind != Kind::Dir && !seen.insert(item.path.as_path()) {
487                bail!(
488                    "'{}' appears more than once in the archive; extraction refused",
489                    item.path.display()
490                );
491            }
492        }
493        Ok(Self {
494            storage,
495            format_name: opened.name,
496            format: opened.format,
497            units,
498            tail_start: opened.tail_start,
499            top,
500            punch: OnceLock::new(),
501            resume: None,
502            started: false,
503            case_clashes: Box::default(),
504            only: None,
505        })
506    }
507
508    /// Limits a fresh job to the entries at `given` and everything inside
509    /// the folders among them. Every path must name something in the
510    /// archive. A hard link brings its target along, since the link is made
511    /// from the extracted target and would otherwise point at whatever is at
512    /// that path in the output folder, or at nothing. Symbolic links are
513    /// extracted as they are, whether their targets are selected or not: a
514    /// link is only text and never reaches outside what it names.
515    ///
516    /// Nothing is touched here. Such a job may only be extracted while the
517    /// archive is kept, which [`crate::session::begin`] enforces.
518    pub fn select(&mut self, given: &[PathBuf]) -> Result<()> {
519        if self.only.is_some() {
520            bail!("the entries to extract were already chosen");
521        }
522        if given.is_empty() {
523            bail!("no entries were selected. Nothing was modified");
524        }
525        let mut paths: Vec<PathBuf> = Vec::new();
526        for g in given {
527            let p = selection_path(g)?;
528            if !paths.contains(&p) {
529                paths.push(p);
530            }
531        }
532        let items = || self.units.iter().flat_map(|u| &u.items);
533        for p in &paths {
534            if !items().any(|i| i.path.starts_with(p)) {
535                bail!(
536                    "'{}' is not in the archive. Run `hatchzip list` on it to see its paths, and \
537                     give one as listed. Nothing was modified",
538                    p.display()
539                );
540            }
541        }
542        let targets: Vec<PathBuf> = items()
543            .filter(|i| picks(&paths, &i.path))
544            .filter_map(|i| match &i.kind {
545                Kind::HardLink(t) if !picks(&paths, t) => Some(t.clone()),
546                _ => None,
547            })
548            .collect();
549        for t in targets {
550            if !paths.contains(&t) {
551                paths.push(t);
552            }
553        }
554        self.restrict(paths);
555        Ok(())
556    }
557
558    /// Drops every unit with nothing in `paths`, and every item outside it
559    /// from the units left, keeping the whole of a unit that loses some.
560    fn restrict(&mut self, paths: Vec<PathBuf>) {
561        let mut whole = HashMap::new();
562        self.units.retain_mut(|u| {
563            let picked = u.items.iter().filter(|i| picks(&paths, &i.path)).count();
564            if picked == 0 {
565                return false;
566            }
567            if picked < u.items.len() {
568                whole.insert(u.start, u.clone());
569                u.items.retain(|i| picks(&paths, &i.path));
570            }
571            true
572        });
573        self.only = Some(Only { paths, whole });
574    }
575
576    /// The entries this job is limited to, if it is: what the journal
577    /// records.
578    pub fn selection(&self) -> Option<&[PathBuf]> {
579        self.only.as_ref().map(|o| o.paths.as_slice())
580    }
581
582    /// `unit` as the decoder needs it: whole, with the entries left out of
583    /// the selection, which a sink then skips.
584    fn decodable<'a>(&'a self, unit: &'a Unit) -> &'a Unit {
585        self.only
586            .as_ref()
587            .and_then(|o| o.whole.get(&unit.start))
588            .unwrap_or(unit)
589    }
590
591    /// Refuses entries that differ only in case, unless the folder where
592    /// their names meet is known to keep them apart. Anywhere else they
593    /// would be one file, and would race inside a parallel batch.
594    pub(crate) fn check_case(&self, out: &Path) -> Result<()> {
595        let clashes = &self.case_clashes;
596        check_case_record(out, &clashes.recorded, clashes.recorded_beyond_ascii)?;
597        if let Some((a, b)) = clashes.beyond_ascii.as_ref().filter(|_| normalizes_names()) {
598            bail!(
599                "'{}' and '{}' differ only in case, and with characters outside ASCII this \
600                 system may treat them as one file on any volume; extraction refused. Extract \
601                 this archive with another program",
602                a.display(),
603                b.display()
604            );
605        }
606        let met_in = &clashes.met_in;
607        if met_in.len() > MAX_CASE_FOLDERS {
608            bail!(
609                "this archive has names that differ only in case in {} folders, more than \
610                 HatchZip can keep track of; extraction refused. Extract this archive with \
611                 another program",
612                met_in.len()
613            );
614        }
615        let folders = met_in.keys().map(PathBuf::as_path);
616        if let Some((met, nearest)) = first_not_apart(out, folders, keeps_case_apart) {
617            let (a, b) = &met_in[met];
618            bail!(
619                "'{}' and '{}' differ only in case, and {} is not known to keep such names \
620                 apart; extraction refused. Extract to a folder on a case-sensitive filesystem, \
621                 or with another program",
622                a.display(),
623                b.display(),
624                nearest.display()
625            );
626        }
627        Ok(())
628    }
629
630    /// What a run has to record: see [`Journal::case_folders`].
631    pub(crate) fn case_folders(&self) -> Vec<PathBuf> {
632        self.case_clashes.met_in.keys().cloned().collect()
633    }
634
635    pub(crate) fn case_beyond_ascii(&self) -> bool {
636        self.case_clashes.beyond_ascii.is_some()
637    }
638
639    /// Refuses entries that can't all be created where the archive puts
640    /// them: a file or link at a path where another entry needs a folder,
641    /// which includes any entry inside a link, and a hard link to anything
642    /// but a file in the archive. Links are only made at the very end, once
643    /// the archive is gone, so without this such an archive fails after it
644    /// has been consumed. Paths that differ only in case depend on the
645    /// destination, so they are returned for [`Job::check_case`]. Names
646    /// ending in [`PART_SUFFIX`] or a [`PROGRESS_SUFFIXES`] one are compared
647    /// ignoring case everywhere.
648    ///
649    /// Only a fresh archive is checked: a resumed run no longer lists the
650    /// entries it has extracted, and one an older release started on has to
651    /// stay resumable and restorable.
652    fn check_layout(&self) -> Result<CaseClashes> {
653        let key = |p: &Path| crate::fsutil::fold_name(&p.to_string_lossy());
654        let items = || self.units.iter().flat_map(|u| &u.items);
655        // Every file is first written under its name plus the suffix. An
656        // entry named so would share that name with another entry's file,
657        // and which of the two is lost would depend on timing.
658        if let Some(item) = items().find(|i| {
659            i.path
660                .iter()
661                .any(|c| c.to_string_lossy().to_lowercase().ends_with(PART_SUFFIX))
662        }) {
663            bail!(
664                "'{}' uses a name ending in {PART_SUFFIX}, which HatchZip gives a file while it \
665                 writes it, so extraction is refused. Extract this archive with another program. \
666                 Nothing was modified",
667                item.path.display()
668            );
669        }
670        // HatchZip keeps an extraction's progress in files named after the
671        // archive, and resumes from whatever it finds there. An archive that
672        // brought its own would have them trusted for an archive next to
673        // them, the person's or one it also holds.
674        if let Some((item, suffix)) = items().find_map(|i| {
675            i.path.iter().find_map(|c| {
676                let name = c.to_string_lossy().to_lowercase();
677                PROGRESS_SUFFIXES
678                    .into_iter()
679                    .find(|s| name.ends_with(*s))
680                    .map(|s| (i, s))
681            })
682        }) {
683            bail!(
684                "'{}' uses a name ending in {suffix}, which HatchZip gives the progress files of \
685                 an extraction, so extraction is refused. Extract this archive with another \
686                 program. Nothing was modified",
687                item.path.display()
688            );
689        }
690        // Every folder the extraction creates, with the first entry inside
691        // that needs it, or `None` if it has an entry of its own.
692        let mut folders: HashMap<&Path, Option<&Path>> = HashMap::new();
693        for item in items() {
694            if item.kind == Kind::Dir {
695                folders.insert(&item.path, None);
696            }
697            for parent in item.path.ancestors().skip(1) {
698                if parent.as_os_str().is_empty() {
699                    break;
700                }
701                folders.entry(parent).or_insert(Some(&item.path));
702            }
703        }
704        let files: HashSet<&Path> = items()
705            .filter(|i| i.kind == Kind::File)
706            .map(|i| i.path.as_path())
707            .collect();
708        for item in items() {
709            let what = match &item.kind {
710                Kind::Dir => continue,
711                Kind::File => "a file",
712                Kind::Symlink => "a symbolic link",
713                Kind::HardLink(_) => "a hard link",
714            };
715            match folders.get(item.path.as_path()) {
716                Some(None) => bail!(
717                    "'{}' is both {what} and a folder in the archive; extraction refused",
718                    item.path.display()
719                ),
720                Some(Some(inside)) => bail!(
721                    "'{}' is {what}, but '{}' requires a folder at that location; extraction \
722                     refused",
723                    item.path.display(),
724                    inside.display()
725                ),
726                None => {}
727            }
728            if let Kind::HardLink(target) = &item.kind
729                && !files.contains(target.as_path())
730            {
731                bail!(
732                    "hard link '{}' points to '{}', which is not a file in the archive; \
733                     extraction refused",
734                    item.path.display(),
735                    target.display()
736                );
737            }
738        }
739        let mut names: Vec<(String, &Path, bool)> = items()
740            .filter(|i| i.kind != Kind::Dir)
741            .map(|i| (key(&i.path), i.path.as_path(), true))
742            .chain(folders.keys().map(|f| (key(f), *f, false)))
743            .collect();
744        names.sort_unstable();
745        Ok(CaseClashes::of(&names))
746    }
747
748    /// `Some(punch)` if holes punched in the archive give its space back.
749    /// `None` on filesystems that can only truncate, such as FAT32 and
750    /// exFAT, which keep today's whole-unit behavior.
751    pub fn punch_support(&self) -> Option<Punch> {
752        *self.punch.get_or_init(|| {
753            if test_knob("HATCHZIP_NO_PUNCH").is_some() {
754                return None;
755            }
756            let dir = match self.storage.primary().parent() {
757                Some(d) if !d.as_os_str().is_empty() => d,
758                _ => Path::new("."),
759            };
760            fsutil::can_punch(dir).then(|| Punch {
761                margin: platform::punch_margin(dir),
762                overlap: platform::punch_overlap(dir),
763            })
764        })
765    }
766
767    pub fn encrypted(&self) -> bool {
768        self.units.iter().any(|u| u.encrypted)
769    }
770
771    /// The archive is one compressed stream, extracted front to back.
772    pub fn is_stream(&self) -> bool {
773        self.format.solid().is_some()
774    }
775
776    /// The archive is one compressed stream that stays whole until the run
777    /// ends, because the filesystem can't free space inside it: the disk
778    /// has to hold the archive and every extracted file at once.
779    pub fn kept_whole(&self, reclaims: bool) -> bool {
780        self.is_stream() && reclaims && self.punch_support().is_none()
781    }
782
783    /// Proves the password before anything is deleted: decrypts the smallest
784    /// encrypted unit, which checks its CRC, up to a limit so a huge solid
785    /// block doesn't stall. ZipCrypto accepts about one wrong password in 256
786    /// at first sight; reading the data catches those.
787    pub fn check_password(&self) -> Result<()> {
788        const ENOUGH: u64 = 64 * 1024 * 1024;
789        let Some(unit) = self.smallest_encrypted() else {
790            return Ok(());
791        };
792        let left = match self.format.password_check() {
793            PasswordCheck::Headers => return self.format.prove_password(),
794            PasswordCheck::Sample => ENOUGH,
795            // A wrong password only shows in the checksum at the end, so a
796            // sample would let it through and the run would fail later, after
797            // the archive is partly gone.
798            PasswordCheck::WholeUnit => u64::MAX,
799        };
800        let mut worker = self.format.worker(1)?;
801        let mut sink = ProbeSink {
802            left,
803            buf: vec![0; BUF_SIZE],
804        };
805        match worker.extract(self.decodable(unit), &mut sink) {
806            Ok(()) => Ok(()),
807            Err(e) if e.chain().any(|c| c.is::<ProbeDone>()) => Ok(()),
808            Err(e) if e.chain().any(|c| c.is::<archive::PasswordNeeded>()) => Err(e),
809            Err(_) => Err(archive::WrongPassword.into()),
810        }
811    }
812
813    /// The smallest encrypted unit with data: an empty file decodes with
814    /// any password in formats whose only check is the file's checksum.
815    fn smallest_encrypted(&self) -> Option<&Unit> {
816        self.units
817            .iter()
818            .filter(|u| u.encrypted)
819            .min_by_key(|u| (u.size() == 0, u.size()))
820    }
821
822    /// When [`check_password`](Self::check_password) has to decode a whole
823    /// file to prove the password, as for RAR 4: that file and its size, so
824    /// a front end can say the check may take a while.
825    pub fn slow_password_check(&self) -> Option<(&Path, u64)> {
826        if !self.encrypted() || self.format.password_check() != PasswordCheck::WholeUnit {
827            return None;
828        }
829        let unit = self.smallest_encrypted()?;
830        Some((unit.items.first()?.path.as_path(), unit.size()))
831    }
832
833    /// Why the archive can't be extracted in place, if it can't. It can
834    /// still be extracted while it is kept.
835    pub fn in_place_refusal(&self) -> Option<String> {
836        self.format.refuses_in_place().or_else(|| {
837            self.storage.hard_linked().map(|path| {
838                format!(
839                    "{} has another hard link, which extracting in place would empty as well",
840                    path.display()
841                )
842            })
843        })
844    }
845
846    pub fn item_count(&self) -> usize {
847        self.units.iter().map(|u| u.items.len()).sum()
848    }
849
850    pub fn remaining_size(&self) -> u64 {
851        let done = self.resume.as_ref().map_or(0, |r| r.written);
852        self.units
853            .iter()
854            .fold(0u64, |sum, u| sum.saturating_add(u.size()))
855            .saturating_sub(done)
856    }
857
858    /// The resume point recorded for `units[i]`, if it is half streamed.
859    fn resumed(&self, i: usize) -> Option<&Resume> {
860        self.resume
861            .as_ref()
862            .filter(|r| r.unit == self.units[i].start)
863    }
864
865    /// Where the data of `units[i]` lies, if it is one file whose decoding
866    /// can be resumed from the middle.
867    fn stream_of(&self, i: usize) -> Option<Stream> {
868        let unit = &self.units[i];
869        match unit.items.as_slice() {
870            [item] if item.kind == Kind::File && !unit.encrypted => {
871                self.format.stream(unit).ok().flatten()
872            }
873            _ => None,
874        }
875    }
876
877    /// Whether `units[i]` may free its own archive bytes while it is
878    /// extracted. A half-streamed unit always continues streaming: the bytes
879    /// before its resume point may be gone.
880    fn streams(&self, i: usize, reclaims: bool) -> Option<Stream> {
881        if self.resumed(i).is_some() {
882            return self.stream_of(i);
883        }
884        if !reclaims || self.units[i].size() < stream_threshold() {
885            return None;
886        }
887        self.punch_support()?;
888        self.stream_of(i)
889    }
890
891    /// Bytes freed once `units[i]` is committed: everything from its start up
892    /// to whatever came after it.
893    fn span(&self, i: usize) -> u64 {
894        let end = if i == 0 {
895            self.top
896        } else {
897            self.units[i - 1].start
898        };
899        end - self.units[i].start
900    }
901
902    /// Replays the extraction one unit at a time and returns `(peak, end)`:
903    /// the most free space it ever consumes beyond what is free now, and how
904    /// much it consumes once finished. `fresh` means the tail hasn't been
905    /// saved yet; `reclaims` that freed archive space lands on the output's
906    /// disk.
907    pub fn space_needed(&self, fresh: bool, reclaims: bool) -> (u64, i128) {
908        let tail = self.storage.original_len().saturating_sub(self.tail_start) as i128;
909        let mut extra: i128 = if fresh { tail } else { 0 };
910        let mut peak = extra;
911        for (i, u) in self.units.iter().enumerate() {
912            let span = self.span(i) as i128;
913            if let Some(solid) = self.format.solid() {
914                let (rise, net) = self.solid_cost(i, solid.profile(), span, reclaims);
915                peak = peak.max(extra + rise);
916                extra += net;
917                continue;
918            }
919            if let Some(s) = self.streams(i, reclaims) {
920                let (rise, net) = self.stream_cost(i, &s, span, reclaims);
921                peak = peak.max(extra + rise);
922                extra += net;
923                continue;
924            }
925            let on_disk = on_disk(u) as i128;
926            peak = peak.max(extra + on_disk);
927            extra += on_disk;
928            if reclaims {
929                extra -= span;
930            }
931        }
932        if reclaims {
933            // Whatever precedes the first unit is deleted at the very end,
934            // along with the saved tail.
935            let stub = self.units.last().map_or(self.top, |u| u.start);
936            extra -= stub as i128 + tail;
937        }
938        (peak.max(0) as u64, extra)
939    }
940
941    /// What streaming `units[i]` costs in free space: `(rise, net)`, the most
942    /// it consumes at any moment and what it consumes once committed.
943    ///
944    /// At any moment the unit holds the output written since the last resume
945    /// point (at most a step, plus one read buffer or deflate block), the
946    /// archive bytes at either end of the punched range the filesystem keeps
947    /// (a margin each), and however far the output so far has outgrown the
948    /// input it came from. For stored data that last part is zero. For
949    /// deflate it only grows as decoding goes on, since encoders fall back to
950    /// stored blocks rather than expand data, so the end state bounds it; a
951    /// 1/1024 margin covers block headers.
952    ///
953    /// Without punching (the filesystem stopped supporting it after a run
954    /// began), the unit holds all of its remaining output until it commits.
955    fn stream_cost(&self, i: usize, s: &Stream, span: i128, reclaims: bool) -> (i128, i128) {
956        let at = self.resumed(i);
957        // What a crashed run already wrote is on disk, so the free space
958        // measured now has paid for it.
959        let done = at.map_or(0, |r| r.written / 4096 * 4096);
960        let out_left = on_disk(&self.units[i]).saturating_sub(done) as i128;
961        let read_to = at.map_or(s.data_start, |r| r.bit / 8);
962        let data_left = (s.data_start + s.packed).saturating_sub(read_to) as i128;
963        // At most this much was punched already. It is free now, so the
964        // final truncation gives back that much less; assuming the most
965        // keeps the estimate on the safe side.
966        let freed = read_to.saturating_sub(s.data_start) as i128;
967        let net = if reclaims {
968            out_left - (span - freed)
969        } else {
970            out_left
971        };
972        let rise = match self.punch_support() {
973            Some(punch) if reclaims => {
974                let slack = match s.codec {
975                    Codec::Stored => 0,
976                    Codec::Deflate => out_left / 1024,
977                };
978                let step = (stream_step() + BUF_SIZE as u64 + 2 * punch.margin) as i128;
979                ((out_left - data_left).max(0) + slack + step).min(out_left)
980            }
981            _ => out_left,
982        };
983        (rise, net)
984    }
985
986    /// What streaming a compressed tar, `units[i]`, costs in free space:
987    /// `(rise, net)` as for [`stream_cost`](Self::stream_cost).
988    ///
989    /// Before each resume point is taken, the files hold what they held at
990    /// the point before, `lead` at most ahead of the compressed bytes freed
991    /// up to it, plus what was written since: under a step, plus the output
992    /// to the next point after the step is full, at most `gap`. The scan
993    /// measured both at the very points the run will meet. A read buffer
994    /// and a margin at each end of the punched range come on top. Links are
995    /// made at the end, once the archive is gone.
996    fn solid_cost(&self, i: usize, p: &Profile, span: i128, reclaims: bool) -> (i128, i128) {
997        // The profile measured every file; a selection writes its own.
998        let out_left = match self.only {
999            Some(_) => on_disk(&self.units[i]),
1000            None => p.files + p.links,
1001        } as i128;
1002        // Assumed punched already, as for a single streamed file.
1003        let freed = self.resumed(i).map_or(0, |r| r.bit / 8) as i128;
1004        let net = if reclaims {
1005            out_left - (span - freed)
1006        } else {
1007            out_left
1008        };
1009        let rise = match self.punch_support() {
1010            Some(punch) if reclaims => {
1011                let ahead = stream_step() + p.gap + BUF_SIZE as u64 + 2 * punch.margin;
1012                (p.lead.max(0) + ahead as i128).min(p.files as i128)
1013            }
1014            // Nothing is freed until the run commits, so every file is on
1015            // disk next to the whole archive.
1016            _ => out_left,
1017        };
1018        (rise.max(net), net)
1019    }
1020
1021    /// The entry a resume point stopped inside of, if any: the first item of
1022    /// the first unit, whose part file holds `written` bytes.
1023    fn open_entry(&self) -> Option<&Item> {
1024        let r = self.resume.as_ref()?;
1025        let inside = match &r.stream {
1026            Some(s) => matches!(s.at, TarAt::File { .. }),
1027            None => true,
1028        };
1029        if !inside {
1030            return None;
1031        }
1032        self.units.first().and_then(|u| u.items.first())
1033    }
1034
1035    /// Output a crashed run wrote for units it never committed. Nothing was
1036    /// at those paths when it started, or it was moved aside before the
1037    /// first entry was extracted, so anything there now is ours. A
1038    /// half-streamed file is not in the list: its archive bytes may be gone,
1039    /// so it is the only copy of its first part. For a compressed tar that
1040    /// is the entry its point is in; the files after the point are still in
1041    /// the archive.
1042    pub fn uncommitted(&self, out: &Path) -> Vec<(PathBuf, u64)> {
1043        self.uncommitted_files(out, true)
1044    }
1045
1046    /// A kept run being discarded has the whole archive, so its open file
1047    /// can go too. Earlier files committed by a stream point stay out of
1048    /// this list, just as they do on resume.
1049    pub(crate) fn discarded_output(&self, out: &Path) -> Vec<(PathBuf, u64)> {
1050        self.uncommitted_files(out, false)
1051    }
1052
1053    fn uncommitted_files(&self, out: &Path, preserve_open: bool) -> Vec<(PathBuf, u64)> {
1054        if !self.started {
1055            return Vec::new();
1056        }
1057        let open = preserve_open && self.open_entry().is_some();
1058        let mut found = Vec::new();
1059        for (i, u) in self.units.iter().enumerate() {
1060            for (k, item) in u.items.iter().enumerate() {
1061                if item.kind != Kind::File || (open && i == 0 && k == 0) {
1062                    continue;
1063                }
1064                let dest = out.join(&item.path);
1065                for p in [part_path(&dest), dest] {
1066                    if let Ok(m) = fs::symlink_metadata(&p)
1067                        && m.is_file()
1068                    {
1069                        found.push((p, m.len().next_multiple_of(4096)));
1070                    }
1071                }
1072            }
1073        }
1074        found
1075    }
1076
1077    /// Output a crashed stream wrote past its last resume point. It is cut
1078    /// off before the stream continues, so it counts as free.
1079    pub fn past_resume_point(&self, out: &Path) -> u64 {
1080        let (Some(r), Some(item)) = (self.resume.as_ref(), self.open_entry()) else {
1081            return 0;
1082        };
1083        let dest = out.join(&item.path);
1084        [part_path(&dest), dest]
1085            .iter()
1086            .find_map(|p| fs::metadata(p).ok())
1087            .map_or(0, |m| {
1088                (m.len().next_multiple_of(4096)).saturating_sub(r.written.next_multiple_of(4096))
1089            })
1090    }
1091
1092    /// Reads every unit and lets the decoders check their checksums,
1093    /// writing nothing.
1094    pub fn verify(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<()> {
1095        let failures = if self.format.serial() {
1096            self.verify_serial(on_bytes)?
1097        } else {
1098            self.verify_parallel(on_bytes)
1099        };
1100        if failures.is_empty() {
1101            return Ok(());
1102        }
1103        let mut msg = format!("{} damaged:", failures.len());
1104        for f in failures.iter().take(10) {
1105            msg.push_str("\n  ");
1106            msg.push_str(f);
1107        }
1108        Err(anyhow!(msg))
1109    }
1110
1111    /// One worker walks every unit from the lowest up.
1112    fn verify_serial(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Result<Vec<String>> {
1113        let mut worker = self.format.worker(1)?;
1114        let mut sink = VerifySink {
1115            on_bytes,
1116            buf: vec![0; BUF_SIZE],
1117        };
1118        Ok(self
1119            .units
1120            .iter()
1121            .rev()
1122            .filter_map(|u| worker.extract(self.decodable(u), &mut sink).err())
1123            .map(|e| format!("{e:#}"))
1124            .collect())
1125    }
1126
1127    fn verify_parallel(&self, on_bytes: &(dyn Fn(u64) + Sync)) -> Vec<String> {
1128        let threads = threads_per_unit(self.units.len());
1129        self.units
1130            .par_iter()
1131            .map_init(
1132                || {
1133                    (
1134                        self.format.worker(threads),
1135                        VerifySink {
1136                            on_bytes,
1137                            buf: vec![0; BUF_SIZE],
1138                        },
1139                    )
1140                },
1141                |(worker, sink), unit| {
1142                    let mut run = || -> Result<()> {
1143                        let w = worker.as_mut().map_err(|e| anyhow!("{e:#}"))?;
1144                        w.extract(self.decodable(unit), sink)
1145                    };
1146                    run().err().map(|e| format!("{e:#}"))
1147                },
1148            )
1149            .flatten()
1150            .collect()
1151    }
1152}
1153
1154fn threads_per_unit(units: usize) -> u32 {
1155    let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
1156    (cores / units.max(1)).max(1) as u32
1157}
1158
1159/// Added to a file's name while it is written.
1160const PART_SUFFIX: &str = ".hatchzip-part";
1161
1162/// Added to an archive's name for its journal, saved tail and folder list,
1163/// and to a split ZIP's `.zip` for its stub; see [`crate::journal::Paths`].
1164const PROGRESS_SUFFIXES: [&str; 3] = [".hatchzip", ".hatchzip-tail", ".hatchzip-folders"];
1165
1166pub(crate) fn part_path(dest: &Path) -> PathBuf {
1167    let mut part = dest.as_os_str().to_owned();
1168    part.push(PART_SUFFIX);
1169    PathBuf::from(part)
1170}
1171
1172/// Creates the part file a new file is first written to. Whatever is
1173/// already at that name was not made by this run: a file there is someone
1174/// else's to keep, and a link there would send the data wherever it points.
1175/// Fresh runs refuse both before the archive is touched.
1176fn create_part(part: &Path) -> Result<File> {
1177    platform::create_new_no_follow(part).map_err(|e| {
1178        if e.kind() == io::ErrorKind::AlreadyExists {
1179            anyhow!(
1180                "{} already exists, and HatchZip does not replace a file it did not create. \
1181                 Move it, then run the extraction again",
1182                part.display()
1183            )
1184        } else {
1185            anyhow::Error::new(e).context(format!("creating {}", part.display()))
1186        }
1187    })
1188}
1189
1190/// Opens a streamed file's part file positioned at `written`, cutting off
1191/// anything written after that point.
1192fn open_part(dest: &Path, part: &Path, written: u64) -> Result<File> {
1193    if written == 0 {
1194        return create_part(part);
1195    }
1196    if fs::symlink_metadata(part).is_err() && fs::symlink_metadata(dest).is_ok() {
1197        // The previous run finished the file and renamed it, then stopped
1198        // before committing. The point it journaled still holds.
1199        fs::rename(dest, part).with_context(|| format!("reopening {}", dest.display()))?;
1200    }
1201    let mut file = match platform::open_existing_no_follow(part) {
1202        Ok(f) => f,
1203        Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
1204            "{} is missing, and the archive data it was extracted from is already released, so \
1205             this file cannot be completed",
1206            part.display()
1207        ),
1208        Err(e) => return Err(e).with_context(|| format!("reopening {}", part.display())),
1209    };
1210    if file.metadata()?.len() < written {
1211        bail!(
1212            "{} is shorter than when its progress was saved; the extraction cannot continue",
1213            part.display()
1214        );
1215    }
1216    file.set_len(written)?;
1217    file.seek(SeekFrom::Start(written))?;
1218    Ok(file)
1219}
1220
1221/// A file of a compressed tar being written to its part file.
1222struct OpenFile {
1223    item: Item,
1224    dest: PathBuf,
1225    part: PathBuf,
1226    file: File,
1227    written: u64,
1228}
1229
1230impl OpenFile {
1231    /// Gives the finished file its metadata and its real name.
1232    fn finish(self) -> Result<()> {
1233        if self.written != self.item.size {
1234            bail!("it is smaller than the archive records");
1235        }
1236        if let Some(t) = self.item.mtime {
1237            self.file.set_modified(t)?;
1238        }
1239        platform::apply_mode(&self.file, self.item.mode)?;
1240        if platform::SYNC_EACH_FILE {
1241            self.file.sync_all()?;
1242        }
1243        drop(self.file);
1244        fs::rename(&self.part, &self.dest)?;
1245        Ok(())
1246    }
1247}
1248
1249/// The output just before `written`, which a deflate stream may refer back
1250/// to. It is on disk, flushed before the point was journaled, so the
1251/// journal doesn't have to carry it.
1252fn read_window(file: &mut File, written: u64) -> Result<Vec<u8>> {
1253    let n = written.min(resumable::WINDOW as u64);
1254    let mut window = vec![0; n as usize];
1255    file.seek(SeekFrom::Start(written - n))?;
1256    file.read_exact(&mut window)?;
1257    file.seek(SeekFrom::Start(written))?;
1258    Ok(window)
1259}
1260
1261pub struct Progress {
1262    pub on_bytes: Box<dyn Fn(u64) + Sync>,
1263    pub on_commit: Box<dyn Fn(u64) + Sync>,
1264}
1265
1266pub enum Outcome {
1267    /// With a warning for the person if the folders could not be set.
1268    Finished(Option<String>),
1269    Paused,
1270}
1271
1272pub struct Run<'a> {
1273    pub job: Job,
1274    pub journal: Journal,
1275    pub paths: Paths,
1276    pub stop: &'a AtomicBool,
1277    pub progress: Progress,
1278    /// Free space the run must never eat into.
1279    pub keep_free: u64,
1280}
1281
1282impl Run<'_> {
1283    pub fn execute(mut self) -> Result<Outcome> {
1284        let out = self.journal.output.clone();
1285        fs::create_dir_all(&out)
1286            .with_context(|| format!("creating output folder {}", out.display()))?;
1287
1288        // Keeping the archive frees nothing, which is exactly the case of an
1289        // output on another disk: nothing is streamed or punched.
1290        if self.job.only.is_some() && !self.journal.keep {
1291            bail!(
1292                "only some entries are selected, which are extracted only while the archive is \
1293                 kept. Nothing was modified"
1294            );
1295        }
1296        let reclaims =
1297            !self.journal.keep && fsutil::same_filesystem(self.job.storage.primary(), &out);
1298        if self.journal.keep {
1299            self.job.storage.protect();
1300        }
1301        if let Some(r) = self.journal.replace.as_mut()
1302            && !r.moved
1303        {
1304            replace::set_aside(&self.job, &out)?;
1305            r.moved = true;
1306            self.journal.save(&self.paths)?;
1307            self.job.started = true;
1308        }
1309        let mut next = 0;
1310        while next < self.job.units.len() {
1311            if self.stop.load(Ordering::Relaxed) {
1312                return Ok(Outcome::Paused);
1313            }
1314            if let Some(solid) = self.job.format.solid() {
1315                let walk = solid.walk(self.job.resumed(next))?;
1316                let what = describe(std::slice::from_ref(&self.job.units[next]));
1317                let Some(links) = self
1318                    .stream_solid(next, walk, reclaims, &out)
1319                    .map_err(|e| out_of_space(e, &what))?
1320                else {
1321                    return Ok(Outcome::Paused);
1322                };
1323                self.commit(next, next + 1, links, &out)?;
1324                next += 1;
1325                continue;
1326            }
1327            if let Some(stream) = self.stream_now(next, reclaims, &out)? {
1328                let what = describe(std::slice::from_ref(&self.job.units[next]));
1329                if !self
1330                    .stream_unit(next, &stream, &out)
1331                    .map_err(|e| out_of_space(e, &what))?
1332                {
1333                    return Ok(Outcome::Paused);
1334                }
1335                self.commit(next, next + 1, Vec::new(), &out)?;
1336                next += 1;
1337                continue;
1338            }
1339            let end = self.next_batch(next, &out, reclaims)?;
1340            let batch = &self.job.units[next..end];
1341            let what = describe(batch);
1342
1343            let Some(links) = self
1344                .extract_batch(batch, &out)
1345                .map_err(|e| out_of_space(e, &what))?
1346            else {
1347                return Ok(Outcome::Paused);
1348            };
1349            self.commit(next, end, links, &out)?;
1350            next = end;
1351        }
1352
1353        Ok(Outcome::Finished(self.finish(&out)?))
1354    }
1355
1356    /// Commits `units[start..end]`, all extracted, and truncates the archive
1357    /// behind them.
1358    fn commit(&mut self, start: usize, end: usize, links: Vec<Link>, out: &Path) -> Result<()> {
1359        let batch = &self.job.units[start..end];
1360        // The journal must never claim a file that a power cut could still
1361        // take back, since its archive bytes are about to be truncated.
1362        platform::sync_batch(out).context("flushing extracted files to disk")?;
1363        if platform::SYNC_EACH_FILE {
1364            // Links are only recorded here and made at the end, so their
1365            // folders may not exist yet.
1366            let dirs: HashSet<PathBuf> = batch
1367                .iter()
1368                .flat_map(|u| &u.items)
1369                .filter(|it| matches!(it.kind, Kind::File | Kind::Dir))
1370                .filter_map(|it| out.join(&it.path).parent().map(Path::to_path_buf))
1371                .collect();
1372            for d in &dirs {
1373                fsutil::sync_dir(d)?;
1374            }
1375        }
1376        crash_point("after-extract");
1377
1378        // Other programs on the computer, antivirus software above all, can
1379        // remove a file after it is written. Claiming one in the journal
1380        // would shorten the archive behind the only copy left. A streamed
1381        // unit with a resume point is skipped: some of its archive is
1382        // already freed, so some of its output may have no other copy, and
1383        // a rerun resumes past it.
1384        if self.journal.resume.is_none() {
1385            remove_after_extract(batch, out);
1386            verify_extracted(batch, out)?;
1387        }
1388
1389        let new_len = batch.last().expect("batches are never empty").start;
1390        self.journal.committed_len = new_len;
1391        self.journal.links.extend(links);
1392        // A streamed unit's point is spent once the unit itself is claimed;
1393        // both change in the same atomic write.
1394        self.journal.resume = None;
1395        self.journal.done = end == self.job.units.len();
1396        self.job.resume = None;
1397        self.journal.save(&self.paths)?;
1398        crash_point("after-journal");
1399
1400        if self.journal.keep {
1401            return Ok(());
1402        }
1403        self.job
1404            .storage
1405            .set_len(new_len)
1406            .context("shrinking the archive")?;
1407        (self.progress.on_commit)(new_len);
1408        Ok(())
1409    }
1410
1411    /// Whether `units[i]` is extracted by streaming: always if it is half
1412    /// streamed already, otherwise if it can be and its output wouldn't fit
1413    /// whole in the space there is right now. When it fits, the ordinary
1414    /// path is faster, since it extracts many units in parallel.
1415    fn stream_now(&self, i: usize, reclaims: bool, out: &Path) -> Result<Option<Stream>> {
1416        if self.job.resumed(i).is_some() {
1417            return match self.job.stream_of(i) {
1418                Some(s) => Ok(Some(s)),
1419                None => bail!(
1420                    "the journal records '{}' as partially extracted, but it cannot be resumed",
1421                    self.job.units[i].items[0].path.display()
1422                ),
1423            };
1424        }
1425        let Some(stream) = self.job.streams(i, reclaims) else {
1426            return Ok(None);
1427        };
1428        if always_stream() {
1429            return Ok(Some(stream));
1430        }
1431        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1432        Ok((on_disk(&self.job.units[i]) > avail).then_some(stream))
1433    }
1434
1435    /// Extracts the one file of `units[i]` while freeing the archive bytes
1436    /// behind it. Returns false if a stop request interrupted it; the last
1437    /// resume point stays in the journal and the next run continues there.
1438    ///
1439    /// The order at every point is what makes a crash harmless: the output
1440    /// up to the point is flushed, then the point is journaled, and only then
1441    /// is the archive punched, never past the byte the point restarts in. A
1442    /// crash before the journal write leaves the previous point in force,
1443    /// and everything it needs is still in the archive.
1444    fn stream_unit(&mut self, i: usize, stream: &Stream, out: &Path) -> Result<bool> {
1445        let unit_start = self.job.units[i].start;
1446        let item = self.job.units[i].items[0].clone();
1447        let dest = out.join(&item.path);
1448        let part = part_path(&dest);
1449        let at = self.job.resumed(i).cloned().unwrap_or(Resume {
1450            unit: unit_start,
1451            written: 0,
1452            bit: stream.data_start * 8,
1453            crc: 0,
1454            stream: None,
1455        });
1456        let started_here = at.written == 0;
1457        let what = || format!("extracting '{}'", item.path.display());
1458        if let Some(parent) = dest.parent() {
1459            fs::create_dir_all(parent).with_context(what)?;
1460        }
1461        // Opened before anything below may delete it: if something is in the
1462        // way of a new part file, it is not ours to remove.
1463        let file = open_part(&dest, &part, at.written).with_context(what)?;
1464        let result = self
1465            .stream_file(&item, stream, at, file, &dest, &part, out)
1466            .with_context(what);
1467        if result.is_err() && started_here && self.journal.resume.is_none() {
1468            // Nothing was punched yet, so the next run starts this file over.
1469            let _ = fs::remove_file(&part);
1470        }
1471        result
1472    }
1473
1474    #[allow(clippy::too_many_arguments)]
1475    fn stream_file(
1476        &mut self,
1477        item: &Item,
1478        stream: &Stream,
1479        at: Resume,
1480        mut file: File,
1481        dest: &Path,
1482        part: &Path,
1483        out: &Path,
1484    ) -> Result<bool> {
1485        let window = match stream.codec {
1486            Codec::Stored => Vec::new(),
1487            Codec::Deflate => read_window(&mut file, at.written)?,
1488        };
1489        let mut decoder = Decoder::new(self.job.storage.reader(None), stream, at.bit, &window)?;
1490        let mut crc = crc32fast::Hasher::new_with_initial(at.crc);
1491        let mut written = at.written;
1492        let mut since_point = 0;
1493        let step = stream_step();
1494        let mut punching = self.job.punch_support();
1495        let what = format!("'{}'", item.path.display());
1496        self.ensure_room(out, &what, item.size - written, punching)?;
1497
1498        let mut buf = vec![0; BUF_SIZE];
1499        loop {
1500            if self.stop.load(Ordering::Relaxed) {
1501                return Ok(false);
1502            }
1503            let n = decoder.read(&mut buf)?;
1504            if n == 0 {
1505                break;
1506            }
1507            written += n as u64;
1508            if written > item.size {
1509                bail!("it is larger than the archive records");
1510            }
1511            file.write_all(&buf[..n])?;
1512            crc.update(&buf[..n]);
1513            (self.progress.on_bytes)(n as u64);
1514            since_point += n as u64;
1515
1516            if since_point < step || written == item.size {
1517                continue;
1518            }
1519            match decoder.restart_point() {
1520                Some(bit) => {
1521                    let point = Resume {
1522                        unit: at.unit,
1523                        written,
1524                        bit,
1525                        crc: crc.clone().finalize(),
1526                        stream: None,
1527                    };
1528                    punching = self.save_point(&file, part, out, point, stream, punching)?;
1529                    since_point = 0;
1530                    self.ensure_room(out, &what, item.size - written, punching)?;
1531                }
1532                // A deflate block runs as long as its encoder likes; zlib-ng
1533                // and zlib-rs write level 1 as a single block. Until it ends
1534                // there is nowhere to resume from, so nothing can be freed,
1535                // and the run has to stop before the disk fills.
1536                None => {
1537                    let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1538                    if avail < 2 * BUF_SIZE as u64 {
1539                        bail!(
1540                            "not enough disk space to continue: the compressed data of this entry has \
1541                             no resume point in the last {}, so its archive space cannot be \
1542                             released yet. {} more is required (the remainder of this file). \
1543                             Progress is saved; free up space and resume the extraction.",
1544                            human(since_point),
1545                            human(item.size - written),
1546                        );
1547                    }
1548                }
1549            }
1550        }
1551        if written != item.size {
1552            bail!("it is smaller than the archive records");
1553        }
1554        if let Some(expected) = stream.crc
1555            && crc.finalize() != expected
1556        {
1557            bail!("its data is damaged (CRC mismatch)");
1558        }
1559        if let Some(t) = item.mtime {
1560            file.set_modified(t)?;
1561        }
1562        platform::apply_mode(&file, item.mode)?;
1563        file.sync_all()?;
1564        drop(file);
1565        // From here a crash leaves the finished file under its real name
1566        // while the journal still holds the last point; `open_part` takes it
1567        // back as the part file.
1568        fs::rename(part, dest)?;
1569        Ok(true)
1570    }
1571
1572    /// Makes `point` the one a crash resumes from, then frees the archive
1573    /// bytes it no longer needs. Returns whether to keep punching.
1574    fn save_point(
1575        &mut self,
1576        file: &File,
1577        part: &Path,
1578        out: &Path,
1579        point: Resume,
1580        stream: &Stream,
1581        punching: Option<Punch>,
1582    ) -> Result<Option<Punch>> {
1583        file.sync_all()
1584            .context("flushing the extracted file to disk")?;
1585        // The part file and the folders above it may be new; a point that
1586        // outlives its file would resume into nothing.
1587        let mut dir = part.parent();
1588        while let Some(d) = dir {
1589            fsutil::sync_dir(d)?;
1590            if d == out {
1591                break;
1592            }
1593            dir = d.parent();
1594        }
1595        crash_point("stream-after-sync");
1596
1597        self.journal.resume = Some(point.clone());
1598        self.journal.save(&self.paths)?;
1599        self.job.resume = Some(point.clone());
1600        crash_point("stream-after-journal");
1601
1602        // Decoding restarts inside the byte holding `point.bit`, so that byte
1603        // and everything after it must stay.
1604        if punching.is_some()
1605            && !self
1606                .job
1607                .storage
1608                .punch(stream.data_start, point.bit / 8)
1609                .context("freeing extracted archive bytes")?
1610        {
1611            // The probe said this works; if the filesystem disagrees after
1612            // all, the run continues without freeing anything mid-file.
1613            return Ok(None);
1614        }
1615        crash_point("stream-after-punch");
1616        Ok(punching)
1617    }
1618
1619    /// Extracts a compressed tar, `units[i]`, front to back from `walk`,
1620    /// freeing the compressed bytes behind the decoder. Returns the links
1621    /// found since the last resume point, for the commit, or `None` if a
1622    /// stop request interrupted it; the last point stays in the journal and
1623    /// the next run continues there.
1624    ///
1625    /// Each point follows the order of [`stream_unit`](Self::stream_unit):
1626    /// every file written before it is flushed, then the point is journaled,
1627    /// with the links found so far, and only then is the archive punched up
1628    /// to the byte it restarts in. Files finished after the last point are
1629    /// written again on resume, the half-written one is cut back to the
1630    /// point.
1631    fn stream_solid(
1632        &mut self,
1633        i: usize,
1634        mut walk: Box<dyn SolidWalker>,
1635        reclaims: bool,
1636        out: &Path,
1637    ) -> Result<Option<Vec<Link>>> {
1638        let unit = self.job.units[i].start;
1639        let step = stream_step();
1640        // With the output on another disk, freeing the archive's space
1641        // doesn't help it, and the space check didn't count on it.
1642        let mut punching = self.job.punch_support().filter(|_| reclaims);
1643        let profile = match self.job.format.solid() {
1644            Some(s) => s.profile().clone(),
1645            None => bail!("the archive is not a compressed stream"),
1646        };
1647        let mut left = match self.job.only {
1648            Some(_) => on_disk(&self.job.units[i]),
1649            None => profile.files,
1650        };
1651        // A file left out of the selection is read past, not written.
1652        let mut skipping = false;
1653        // This run hasn't punched anything yet. Its first punch starts at 0,
1654        // in case the last run stopped between journaling a point and
1655        // punching up to it.
1656        let mut punched = 0;
1657        let mut since_point = 0u64;
1658        let mut checked = 0u64;
1659        let mut open: Option<OpenFile> = None;
1660        let mut links = Vec::new();
1661        let mut dirs = HashSet::new();
1662        self.ensure_room(out, "the archive", left, punching)?;
1663
1664        loop {
1665            if self.stop.load(Ordering::Relaxed) {
1666                return Ok(None);
1667            }
1668            match walk.next(BUF_SIZE)? {
1669                Event::Entry { item, link, done } => {
1670                    if self.job.selection().is_some_and(|o| !picks(o, &item.path)) {
1671                        skipping = item.kind == Kind::File;
1672                        continue;
1673                    }
1674                    let dest = out.join(&item.path);
1675                    let what = || format!("extracting '{}'", item.path.display());
1676                    match &item.kind {
1677                        Kind::Dir => {
1678                            fs::create_dir_all(&dest).with_context(what)?;
1679                            dirs.insert(dest);
1680                        }
1681                        Kind::Symlink => {
1682                            let target = String::from_utf8(link.unwrap_or_default())
1683                                .map_err(|_| anyhow!("the link target is not valid UTF-8"))
1684                                .with_context(what)?;
1685                            links.push(Link {
1686                                path: item.path.clone(),
1687                                target: PathBuf::from(target),
1688                                hard: false,
1689                            });
1690                        }
1691                        Kind::HardLink(target) => links.push(Link {
1692                            path: item.path.clone(),
1693                            target: target.clone(),
1694                            hard: true,
1695                        }),
1696                        Kind::File => {
1697                            if let Some(parent) = dest.parent() {
1698                                fs::create_dir_all(parent).with_context(what)?;
1699                            }
1700                            let part = part_path(&dest);
1701                            let file = open_part(&dest, &part, done).with_context(what)?;
1702                            open = Some(OpenFile {
1703                                item,
1704                                dest,
1705                                part,
1706                                file,
1707                                written: done,
1708                            });
1709                        }
1710                    }
1711                }
1712                Event::Data(_) if skipping => {}
1713                Event::Data(bytes) => {
1714                    let f = open
1715                        .as_mut()
1716                        .ok_or_else(|| anyhow!("the tar stream holds data outside a file"))?;
1717                    f.file
1718                        .write_all(bytes)
1719                        .with_context(|| format!("extracting '{}'", f.item.path.display()))?;
1720                    let n = bytes.len() as u64;
1721                    f.written += n;
1722                    since_point += n;
1723                    left = left.saturating_sub(n);
1724                    (self.progress.on_bytes)(n);
1725                    // A deflate block runs as long as its encoder likes, and
1726                    // until it ends there is nowhere to resume from, so nothing
1727                    // can be freed: stop before the disk fills.
1728                    if punching.is_some()
1729                        && since_point >= step
1730                        && since_point - checked >= BUF_SIZE as u64
1731                    {
1732                        checked = since_point;
1733                        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1734                        if avail < 2 * BUF_SIZE as u64 {
1735                            bail!(
1736                                "not enough disk space to continue: the compressed data has no \
1737                                 resume point in the last {}, so its space cannot be released \
1738                                 yet. {} more is required (the remainder of the archive). \
1739                                 Progress is saved; free up space and resume the extraction.",
1740                                human(since_point),
1741                                human(left),
1742                            );
1743                        }
1744                    }
1745                }
1746                Event::FileEnd if skipping => {
1747                    skipping = false;
1748                    // Inside the stream, past a file left out.
1749                    crash_point("stream-skipped");
1750                }
1751                Event::FileEnd => {
1752                    let f = open
1753                        .take()
1754                        .ok_or_else(|| anyhow!("the tar stream ends a file it never began"))?;
1755                    let pad = f.item.size.next_multiple_of(4096) - f.item.size;
1756                    let path = f.item.path.clone();
1757                    let parent = f.dest.parent().map(Path::to_path_buf);
1758                    f.finish()
1759                        .with_context(|| format!("extracting '{}'", path.display()))?;
1760                    dirs.extend(parent);
1761                    since_point += pad;
1762                    left = left.saturating_sub(pad);
1763                }
1764                Event::Point => {
1765                    // A selection is extracted while the archive is kept, so
1766                    // nothing is freed at a point, and a crash starts the
1767                    // stream over: a point inside a file left out would name
1768                    // a file the run never writes.
1769                    if since_point < step || self.job.only.is_some() {
1770                        continue;
1771                    }
1772                    let mut point = walk.point()?;
1773                    point.unit = unit;
1774                    punching = self.solid_point(
1775                        point,
1776                        open.as_ref(),
1777                        &mut links,
1778                        &mut dirs,
1779                        out,
1780                        punching,
1781                        &mut punched,
1782                    )?;
1783                    since_point = 0;
1784                    checked = 0;
1785                    self.ensure_room(out, "the archive", left, punching)?;
1786                }
1787                Event::End => break,
1788            }
1789        }
1790        if open.is_some() {
1791            bail!("the tar stream ended inside a file");
1792        }
1793        Ok(Some(links))
1794    }
1795
1796    /// Makes `point` the one a crash resumes from, then frees the archive
1797    /// bytes before it. Returns whether to keep punching.
1798    #[allow(clippy::too_many_arguments)]
1799    fn solid_point(
1800        &mut self,
1801        point: Resume,
1802        open: Option<&OpenFile>,
1803        links: &mut Vec<Link>,
1804        dirs: &mut HashSet<PathBuf>,
1805        out: &Path,
1806        punching: Option<Punch>,
1807        punched: &mut u64,
1808    ) -> Result<Option<Punch>> {
1809        if let Some(f) = open {
1810            f.file
1811                .sync_all()
1812                .context("flushing the extracted file to disk")?;
1813            dirs.extend(f.part.parent().map(Path::to_path_buf));
1814        }
1815        platform::sync_batch(out).context("flushing extracted files to disk")?;
1816        if platform::SYNC_EACH_FILE {
1817            // Files were flushed as they were finished; their names live in
1818            // the folders, which may be new themselves.
1819            let mut done = HashSet::new();
1820            for d in dirs.drain() {
1821                let mut dir = Some(d.as_path());
1822                while let Some(d) = dir {
1823                    if !done.insert(d.to_path_buf()) {
1824                        break;
1825                    }
1826                    fsutil::sync_dir(d)?;
1827                    if d == out {
1828                        break;
1829                    }
1830                    dir = d.parent();
1831                }
1832            }
1833        }
1834        dirs.clear();
1835        crash_point("stream-after-sync");
1836
1837        let byte = point.bit / 8;
1838        self.journal.links.append(links);
1839        self.journal.resume = Some(point.clone());
1840        self.journal.save(&self.paths)?;
1841        self.job.resume = Some(point);
1842        crash_point("stream-after-journal");
1843
1844        if let Some(punch) = punching {
1845            if !self
1846                .job
1847                .storage
1848                .punch(*punched, byte)
1849                .context("freeing extracted archive bytes")?
1850            {
1851                return Ok(None);
1852            }
1853            // A filesystem that rounds a punch inwards keeps the block
1854            // holding `byte` allocated. Starting the next punch one overlap
1855            // earlier covers it; it still never reaches `byte`, the point a
1856            // resume parses.
1857            *punched = byte.saturating_sub(punch.overlap);
1858            (self.progress.on_commit)(self.job.top - byte);
1859        }
1860        crash_point("stream-after-punch");
1861        Ok(punching)
1862    }
1863
1864    /// Stops a stream at a resume point, before it writes what doesn't fit.
1865    /// `left` is the output still to write.
1866    fn ensure_room(
1867        &self,
1868        out: &Path,
1869        what: &str,
1870        left: u64,
1871        punching: Option<Punch>,
1872    ) -> Result<()> {
1873        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1874        let left = left.next_multiple_of(4096);
1875        let need = match punching {
1876            Some(punch) => (stream_step() + BUF_SIZE as u64 + 2 * punch.margin).min(left),
1877            None => left,
1878        };
1879        if need > avail {
1880            bail!(
1881                "not enough disk space to continue: the next part of {} requires {} and {} is \
1882                 available ({} reserved).\n{} more is required. Progress is saved; free up space \
1883                 and resume the extraction.",
1884                what,
1885                human(need),
1886                human(avail),
1887                human(self.keep_free),
1888                human(need - avail),
1889            );
1890        }
1891        Ok(())
1892    }
1893
1894    /// Pick units starting at `start` whose output fits in the space there is
1895    /// right now. Always takes at least one, or explains why it can't.
1896    fn next_batch(&self, start: usize, out: &Path, reclaims: bool) -> Result<usize> {
1897        let avail = fsutil::available_space(out)?.saturating_sub(self.keep_free);
1898        let units = &self.job.units;
1899        let need = on_disk;
1900        let first = need(&units[start]);
1901        if first > avail {
1902            // The upfront check makes this rare: it takes something else on
1903            // the machine filling the disk while we run.
1904            let what = describe(std::slice::from_ref(&units[start]));
1905            bail!(
1906                "not enough disk space to continue: {what} requires {} and {} is available \
1907                 ({} reserved).\n{} more is required. Progress is saved; free up space and \
1908                 resume the extraction.",
1909                human(first),
1910                human(avail),
1911                human(self.keep_free),
1912                human(first - avail),
1913            );
1914        }
1915        let budget = avail.min(BATCH_MAX_BYTES.max(first));
1916        let max_units = test_knob("HATCHZIP_BATCH_ENTRIES").map_or(BATCH_MAX_UNITS, |n| n as usize);
1917        let mut used = 0u64;
1918        let mut end = start;
1919        while end < units.len() && end - start < max_units {
1920            let size = need(&units[end]);
1921            if end > start && used.saturating_add(size) > budget {
1922                break;
1923            }
1924            if end > start && always_stream() && self.job.streams(end, reclaims).is_some() {
1925                break;
1926            }
1927            used += size;
1928            end += 1;
1929        }
1930        Ok(end)
1931    }
1932
1933    /// Returns `None` if a stop request interrupted the batch. Nothing in the
1934    /// archive has been touched at that point, so the batch simply reruns.
1935    fn extract_batch(&self, batch: &[Unit], out: &Path) -> Result<Option<Vec<Link>>> {
1936        let on_bytes = &*self.progress.on_bytes;
1937        if self.job.format.serial() {
1938            let mut sink = DiskSink {
1939                out,
1940                stop: self.stop,
1941                on_bytes,
1942                buf: vec![0; BUF_SIZE],
1943                links: Vec::new(),
1944                only: self.job.selection(),
1945            };
1946            let mut worker = self
1947                .job
1948                .format
1949                .worker(1)
1950                .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1951            // Lowest first, so the worker reads the archive front to back.
1952            for unit in batch.iter().rev() {
1953                match worker.extract(self.job.decodable(unit), &mut sink) {
1954                    Ok(()) => {}
1955                    Err(e) if is_interrupt(&e) => return Ok(None),
1956                    Err(e) => return Err(e),
1957                }
1958            }
1959            return Ok(Some(sink.links));
1960        }
1961        let threads = threads_per_unit(batch.len());
1962        let results: Vec<Result<Vec<Link>>> = batch
1963            .par_iter()
1964            .map_init(
1965                || {
1966                    let sink = DiskSink {
1967                        out,
1968                        stop: self.stop,
1969                        on_bytes,
1970                        buf: vec![0; BUF_SIZE],
1971                        links: Vec::new(),
1972                        only: self.job.selection(),
1973                    };
1974                    (self.job.format.worker(threads), sink)
1975                },
1976                |(worker, sink), unit| {
1977                    let w = worker
1978                        .as_mut()
1979                        .map_err(|e| anyhow!("opening the archive: {e:#}"))?;
1980                    w.extract(self.job.decodable(unit), sink)?;
1981                    Ok(std::mem::take(&mut sink.links))
1982                },
1983            )
1984            .collect();
1985
1986        let mut links = Vec::new();
1987        let mut interrupted = false;
1988        for r in results {
1989            match r {
1990                Ok(l) => links.extend(l),
1991                Err(e) if is_interrupt(&e) => interrupted = true,
1992                Err(e) => return Err(e),
1993            }
1994        }
1995        Ok((!interrupted).then_some(links))
1996    }
1997
1998    fn finish(mut self, out: &Path) -> Result<Option<String>> {
1999        make_links_and_settle(&mut self.journal, &self.paths, out)?;
2000        // Last, since every file, link and put-back file changes its
2001        // folder's time.
2002        let warning = set_folders(&self.journal, &self.paths, out)?;
2003        if self.journal.keep {
2004            // The archive stays as it was; only the progress files go.
2005            self.paths.remove()?;
2006            return Ok(warning);
2007        }
2008        let Self { job, paths, .. } = self;
2009        let Job {
2010            storage, format, ..
2011        } = job;
2012        // The format holds its own handle on the storage; it has to go first.
2013        drop(format);
2014        let storage = Arc::try_unwrap(storage)
2015            .map_err(|_| anyhow!("archive still in use at the end of extraction"))?;
2016        // What is left is at most a self-extractor stub in front of the
2017        // first entry. The saved index goes with it.
2018        storage.remove()?;
2019        paths.remove()?;
2020        Ok(warning)
2021    }
2022}
2023
2024/// Checks that every file `batch` extracted is whole on disk under its final
2025/// name. The journal is about to claim them and free the archive bytes
2026/// behind them, so a file that another program removed or changed has to
2027/// stop the run here: its unit keeps its place in the journal and the
2028/// archive still holds it, and a rerun extracts it again.
2029///
2030/// Links are made at the very end, once the archive is gone, so link
2031/// entries have nothing on disk yet.
2032fn verify_extracted(batch: &[Unit], out: &Path) -> Result<()> {
2033    for item in batch.iter().flat_map(|u| &u.items) {
2034        if item.kind != Kind::File {
2035            continue;
2036        }
2037        let dest = out.join(&item.path);
2038        // Never follows a link: what matters is what sits at the name.
2039        let meta = match fs::symlink_metadata(&dest) {
2040            Ok(meta) => meta,
2041            Err(e) if e.kind() == io::ErrorKind::NotFound => bail!(
2042                "'{}' disappeared while it was extracted. Antivirus software sometimes removes \
2043                 files as they are written. The archive still holds it ({} bytes), so running \
2044                 the same command again extracts it",
2045                item.path.display(),
2046                item.size
2047            ),
2048            Err(e) => {
2049                return Err(e).with_context(|| {
2050                    format!("checking '{}' after extracting it", item.path.display())
2051                });
2052            }
2053        };
2054        if !meta.is_file() {
2055            bail!(
2056                "'{}' is no longer a file after it was extracted, but the archive has a file \
2057                 there. The archive still holds it, so move what is in its place away and run \
2058                 the same command again",
2059                item.path.display()
2060            );
2061        }
2062        if meta.len() != item.size {
2063            bail!(
2064                "'{}' changed while it was extracted: the archive records {} bytes, but the \
2065                 file has {}. The archive still holds it, so move it away and run the same \
2066                 command again",
2067                item.path.display(),
2068                item.size,
2069                meta.len()
2070            );
2071        }
2072    }
2073    Ok(())
2074}
2075
2076/// Lets the test suite remove an extracted file between the batch reaching
2077/// the disk and the journal claiming it, as antivirus software might.
2078fn remove_after_extract(batch: &[Unit], out: &Path) {
2079    if !cfg!(debug_assertions) {
2080        return;
2081    }
2082    let Ok(rel) = std::env::var("HATCHZIP_REMOVE_AFTER_EXTRACT") else {
2083        return;
2084    };
2085    let rel = Path::new(&rel);
2086    let extracted = batch
2087        .iter()
2088        .flat_map(|u| &u.items)
2089        .any(|item| item.kind == Kind::File && item.path == rel);
2090    if extracted {
2091        let _ = fs::remove_file(out.join(rel));
2092    }
2093}
2094
2095/// A run that crashed after deleting the archive but before cleaning up only
2096/// has its links and side files left to deal with. Returns a warning for the
2097/// person if the folders could not be set.
2098pub fn finish_orphaned(journal: &mut Journal, paths: &Paths) -> Result<Option<String>> {
2099    let out = journal.output.clone();
2100    make_links_and_settle(journal, paths, &out)?;
2101    let warning = set_folders(journal, paths, &out)?;
2102    // The final commit was interrupted before the archive was removed, and
2103    // all of it is free to go now. A kept archive stays.
2104    if journal.done && !journal.keep {
2105        for (part, _) in &journal.parts {
2106            match fs::remove_file(part) {
2107                Err(e) if e.kind() != io::ErrorKind::NotFound => {
2108                    return Err(e).with_context(|| format!("deleting {}", part.display()));
2109                }
2110                _ => {}
2111            }
2112        }
2113    }
2114    paths.remove()?;
2115    Ok(warning)
2116}
2117
2118/// Makes the links and puts the replaced files back, unless an earlier run
2119/// got past them. With folders still to set, the journal then says only
2120/// they are left, so a resume never makes a link again inside a folder
2121/// whose mode no longer lets it.
2122fn make_links_and_settle(journal: &mut Journal, paths: &Paths, out: &Path) -> Result<()> {
2123    if journal.folders_left {
2124        return Ok(());
2125    }
2126    make_final_links(&journal.links, out)?;
2127    // Before the journal goes, so a crash in between deletes the rest on
2128    // resume rather than leaving it.
2129    if let Some(r) = &journal.replace {
2130        replace::settle(out, r)?;
2131        replace::remove(out)?;
2132    }
2133    if journal.folders.is_some() {
2134        journal.folders_left = true;
2135        journal.save(paths)?;
2136    }
2137    Ok(())
2138}
2139
2140/// Sets the saved folders' permissions and times. The journal stays until
2141/// they are set, so a crash before the end sets them again on resume. Every
2142/// file is safe by now, so a list that can't be read doesn't stop the run: it
2143/// gets a warning, which can only count the folders, since only the list names
2144/// them.
2145fn set_folders(journal: &Journal, paths: &Paths, out: &Path) -> Result<Option<String>> {
2146    let Some(saved) = journal.folders else {
2147        return Ok(None);
2148    };
2149    crash_point("before-folders");
2150    let list = match folders::load(&paths.folders, saved) {
2151        Ok(list) => list,
2152        Err(e) => {
2153            let folders = match saved.count {
2154                1 => "1 folder".to_string(),
2155                n => format!("{n} folders"),
2156            };
2157            return Ok(Some(format!(
2158                "{e:#}, so {folders} in {} kept the default permissions and modified times",
2159                out.display()
2160            )));
2161        }
2162    };
2163    folders::apply(&list, out)?;
2164    crash_point("after-folders");
2165    Ok(None)
2166}
2167
2168/// The last step of a run, when every file is extracted and the archive is
2169/// gone: a link that can't be made is all that is left. The journal keeps
2170/// the links, so once the cause is fixed a resumed run makes them and
2171/// finishes.
2172fn make_final_links(links: &[Link], out: &Path) -> Result<()> {
2173    make_links(links, out).map_err(|e| {
2174        anyhow!(
2175            "every file is extracted, but {e:#}\nThe links are kept. Resolve the problem shown for \
2176             each one, for example by moving or renaming a folder that is in the way, then \
2177             resume the extraction to create them"
2178        )
2179    })
2180}
2181
2182/// Makes `links`. Each one is tried, and the error lists every one that
2183/// failed and why. Links that were made are made again by the next call,
2184/// replacing themselves.
2185pub(crate) fn make_links(links: &[Link], out: &Path) -> Result<()> {
2186    let failed: Vec<(&Link, anyhow::Error)> = links
2187        .iter()
2188        .filter_map(|link| make_link(link, out).err().map(|e| (link, e)))
2189        .collect();
2190    if failed.is_empty() {
2191        return Ok(());
2192    }
2193    let mut msg = match failed.len() {
2194        1 => "1 link could not be created:".to_string(),
2195        n => format!("{n} links could not be created:"),
2196    };
2197    for (link, e) in failed.iter().take(10) {
2198        let kind = if link.hard {
2199            "hard link"
2200        } else {
2201            "symbolic link"
2202        };
2203        msg.push_str(&format!(
2204            "\n  '{}' ({kind} to '{}'): {e:#}",
2205            link.path.display(),
2206            link.target.display()
2207        ));
2208    }
2209    if failed.len() > 10 {
2210        msg.push_str(&format!("\n  and {} more", failed.len() - 10));
2211    }
2212    Err(anyhow!(msg))
2213}
2214
2215fn make_link(link: &Link, out: &Path) -> Result<()> {
2216    // A run an older release started may hold a link inside another link.
2217    // Going through it would write outside the output folder.
2218    if let Some(via) = link_on_the_way(out, &link.path) {
2219        bail!(
2220            "'{}' is a link, and this one would be created through it",
2221            via.display()
2222        );
2223    }
2224    let path = out.join(&link.path);
2225    if fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) {
2226        bail!("a folder already exists at this location");
2227    }
2228    if let Some(parent) = path.parent() {
2229        fs::create_dir_all(parent)?;
2230    }
2231    if link.hard {
2232        if let Some(via) = link_on_the_way(out, &link.target) {
2233            bail!(
2234                "'{}' is a link, and the target would be reached through it",
2235                via.display()
2236            );
2237        }
2238        let target = out.join(&link.target);
2239        let _ = fs::remove_file(&path);
2240        // FAT32 and exFAT have no hard links; a copy is the next best thing.
2241        fs::hard_link(&target, &path).or_else(|_| fs::copy(&target, &path).map(|_| ()))?;
2242    } else {
2243        platform::create_symlink(&path, &link.target)?;
2244    }
2245    Ok(())
2246}
2247
2248/// The first folder on the way to `rel` inside `out` that is really a link.
2249pub(crate) fn link_on_the_way(out: &Path, rel: &Path) -> Option<PathBuf> {
2250    let mut ancestors: Vec<&Path> = rel
2251        .ancestors()
2252        .skip(1)
2253        .filter(|p| !p.as_os_str().is_empty())
2254        .collect();
2255    ancestors.reverse();
2256    ancestors
2257        .into_iter()
2258        .find(|p| fs::symlink_metadata(out.join(p)).is_ok_and(|m| m.is_symlink()))
2259        .map(Path::to_path_buf)
2260}
2261
2262struct DiskSink<'a> {
2263    out: &'a Path,
2264    stop: &'a AtomicBool,
2265    on_bytes: &'a (dyn Fn(u64) + Sync),
2266    buf: Vec<u8>,
2267    links: Vec<Link>,
2268    /// The selection, if only some entries are extracted.
2269    only: Option<&'a [PathBuf]>,
2270}
2271
2272impl Sink for DiskSink<'_> {
2273    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2274        if self.only.is_some_and(|o| !picks(o, &item.path)) {
2275            return self
2276                .skip(data)
2277                .with_context(|| format!("reading past '{}'", item.path.display()));
2278        }
2279        self.write(item, data)
2280            .with_context(|| format!("extracting '{}'", item.path.display()))
2281    }
2282}
2283
2284impl DiskSink<'_> {
2285    /// Reads an entry left out of the selection to its end, so the decoder
2286    /// still checks it and reaches the next one, and writes nothing.
2287    fn skip(&mut self, data: &mut dyn Read) -> Result<()> {
2288        loop {
2289            if self.stop.load(Ordering::Relaxed) {
2290                return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2291            }
2292            if data.read(&mut self.buf)? == 0 {
2293                return Ok(());
2294            }
2295        }
2296    }
2297
2298    fn write(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2299        let dest = self.out.join(&item.path);
2300        match &item.kind {
2301            Kind::Dir => {
2302                fs::create_dir_all(&dest)?;
2303                return Ok(());
2304            }
2305            Kind::Symlink => {
2306                let mut target = Vec::new();
2307                data.take(MAX_SYMLINK).read_to_end(&mut target)?;
2308                let target = PathBuf::from(String::from_utf8(target)?);
2309                self.links.push(Link {
2310                    path: item.path.clone(),
2311                    target,
2312                    hard: false,
2313                });
2314                return Ok(());
2315            }
2316            Kind::HardLink(target) => {
2317                self.links.push(Link {
2318                    path: item.path.clone(),
2319                    target: target.clone(),
2320                    hard: true,
2321                });
2322                return Ok(());
2323            }
2324            Kind::File => {}
2325        }
2326
2327        if let Some(parent) = dest.parent() {
2328            fs::create_dir_all(parent)?;
2329        }
2330        let part = part_path(&dest);
2331        // Only a part file this call created is removed on failure.
2332        let dst = create_part(&part)?;
2333        let result = self.copy(item, data, dst);
2334        if result.is_err() {
2335            let _ = fs::remove_file(&part);
2336            return result;
2337        }
2338        fs::rename(&part, &dest)?;
2339        Ok(())
2340    }
2341
2342    fn copy(&mut self, item: &Item, data: &mut dyn Read, mut dst: File) -> Result<()> {
2343        let mut written = 0u64;
2344        loop {
2345            if self.stop.load(Ordering::Relaxed) {
2346                return Err(io::Error::from(io::ErrorKind::Interrupted).into());
2347            }
2348            // Decoders check their CRC when the stream ends, so a read error
2349            // here is how corruption surfaces.
2350            let n = data.read(&mut self.buf)?;
2351            if n == 0 {
2352                break;
2353            }
2354            written += n as u64;
2355            if written > item.size {
2356                bail!("it is larger than the archive records");
2357            }
2358            dst.write_all(&self.buf[..n])?;
2359            (self.on_bytes)(n as u64);
2360        }
2361        if written != item.size {
2362            bail!("it is smaller than the archive records");
2363        }
2364        if let Some(t) = item.mtime {
2365            dst.set_modified(t)?;
2366        }
2367        platform::apply_mode(&dst, item.mode)?;
2368        if platform::SYNC_EACH_FILE {
2369            dst.sync_all()?;
2370        }
2371        Ok(())
2372    }
2373}
2374
2375/// Reads at most `left` bytes, then stops the decoder with [`ProbeDone`].
2376struct ProbeSink {
2377    left: u64,
2378    buf: Vec<u8>,
2379}
2380
2381#[derive(Debug)]
2382struct ProbeDone;
2383
2384impl std::fmt::Display for ProbeDone {
2385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2386        f.write_str("read enough to prove the password")
2387    }
2388}
2389
2390impl std::error::Error for ProbeDone {}
2391
2392impl Sink for ProbeSink {
2393    fn item(&mut self, _item: &Item, data: &mut dyn Read) -> Result<()> {
2394        loop {
2395            let n = data.read(&mut self.buf)?;
2396            if n == 0 {
2397                return Ok(());
2398            }
2399            self.left = self.left.saturating_sub(n as u64);
2400            if self.left == 0 {
2401                return Err(ProbeDone.into());
2402            }
2403        }
2404    }
2405}
2406
2407struct VerifySink<'a> {
2408    on_bytes: &'a (dyn Fn(u64) + Sync),
2409    buf: Vec<u8>,
2410}
2411
2412impl Sink for VerifySink<'_> {
2413    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()> {
2414        let mut read = 0;
2415        loop {
2416            let n = data
2417                .read(&mut self.buf)
2418                .with_context(|| format!("'{}'", item.path.display()))?;
2419            if n == 0 {
2420                break;
2421            }
2422            read += n as u64;
2423            (self.on_bytes)(n as u64);
2424        }
2425        if item.kind == Kind::File && read != item.size {
2426            bail!(
2427                "'{}' is shorter than the archive records",
2428                item.path.display()
2429            );
2430        }
2431        Ok(())
2432    }
2433}
2434
2435fn is_interrupt(e: &anyhow::Error) -> bool {
2436    e.chain()
2437        .filter_map(|c| c.downcast_ref::<io::Error>())
2438        .any(|io| io.kind() == io::ErrorKind::Interrupted)
2439}
2440
2441/// A write error that means the volume ran out of room, however deep the
2442/// decoder wrapped it. The next batch's pre-check can only see the space
2443/// there was when it started, so a program filling the disk in between shows
2444/// up here instead. Matched by kind, which std maps from `ENOSPC`,
2445/// `ERROR_DISK_FULL` and `ERROR_HANDLE_DISK_FULL`; the raw numbers for those
2446/// differ per system and clash with unrelated errors elsewhere.
2447fn is_disk_full(e: &anyhow::Error) -> bool {
2448    e.chain()
2449        .filter_map(|c| c.downcast_ref::<io::Error>())
2450        .any(|io| {
2451            matches!(
2452                io.kind(),
2453                io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded
2454            )
2455        })
2456}
2457
2458/// The batch never reached a commit, so its units are still whole in the
2459/// archive and a rerun picks them up where this one stopped.
2460fn out_of_space(e: anyhow::Error, what: &str) -> anyhow::Error {
2461    if !is_disk_full(&e) {
2462        return e;
2463    }
2464    e.context(format!(
2465        "not enough disk space to continue: {what} could not be written because the disk filled \
2466         up.\nProgress is saved; free up space and resume the extraction"
2467    ))
2468}
2469
2470fn describe(units: &[Unit]) -> String {
2471    let items: usize = units.iter().map(|u| u.items.len()).sum();
2472    match units {
2473        [one] if one.items.len() == 1 => format!("'{}'", one.items[0].path.display()),
2474        _ => format!("the next block of {items} files"),
2475    }
2476}
2477
2478/// Settings only the test suite uses. Release builds ignore them.
2479fn test_knob(name: &str) -> Option<u32> {
2480    if !cfg!(debug_assertions) {
2481        return None;
2482    }
2483    std::env::var(name).ok()?.parse().ok()
2484}
2485
2486/// Lets the test suite kill the process at the two moments that matter for
2487/// crash safety: after a batch is on disk, and after it is journaled.
2488pub(crate) fn crash_point(name: &str) {
2489    if !cfg!(debug_assertions) || std::env::var("HATCHZIP_CRASH_AT").map_or(true, |v| v != name) {
2490        return;
2491    }
2492    static PASSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2493    if PASSED.fetch_add(1, Ordering::Relaxed) >= test_knob("HATCHZIP_CRASH_AFTER").unwrap_or(0) {
2494        std::process::abort();
2495    }
2496}
2497
2498pub fn human(bytes: u64) -> String {
2499    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
2500    let mut v = bytes as f64;
2501    let mut unit = 0;
2502    while v >= 1000.0 && unit < UNITS.len() - 1 {
2503        v /= 1000.0;
2504        unit += 1;
2505    }
2506    if unit == 0 {
2507        format!("{bytes} B")
2508    } else {
2509        format!("{v:.1} {}", UNITS[unit])
2510    }
2511}
2512
2513#[cfg(test)]
2514mod tests {
2515    use super::*;
2516    use crate::archive::{Opened, Worker};
2517
2518    /// Stands in for a format: these tests only plan, they never decode.
2519    struct NoFormat;
2520
2521    impl Format for NoFormat {
2522        fn worker(&self, _threads: u32) -> Result<Box<dyn Worker + '_>> {
2523            bail!("nothing is decoded in these tests")
2524        }
2525    }
2526
2527    /// The folder that decides is the one holding the first names to differ.
2528    #[test]
2529    fn names_meet_where_they_first_differ() {
2530        for (a, b, folder) in [
2531            ("a/Makefile", "a/makefile", "a"),
2532            ("Makefile", "makefile", ""),
2533            ("D/x", "d/x", ""),
2534            ("D", "d/inner.txt", ""),
2535            ("a/B/c/F", "a/b/c/f", "a"),
2536        ] {
2537            assert_eq!(
2538                meeting_folder(Path::new(a), Path::new(b)),
2539                Path::new(folder),
2540                "{a} and {b}"
2541            );
2542        }
2543    }
2544
2545    fn clashes(paths: &[&'static str]) -> CaseClashes {
2546        let mut names: Vec<(String, &Path, bool)> = paths
2547            .iter()
2548            .map(|p| (crate::fsutil::fold_name(p), Path::new(*p), true))
2549            .collect();
2550        names.sort_unstable();
2551        CaseClashes::of(&names)
2552    }
2553
2554    /// Names that only full case folding or normalization makes one, which
2555    /// lowercasing alone misses, still pair up, and outside ASCII.
2556    #[test]
2557    fn names_a_filesystem_folds_together_pair_up() {
2558        for pair in [
2559            ["stra\u{df}e.txt", "STRASSE.txt"],
2560            ["s.txt", "\u{17f}.txt"],
2561            ["\u{3c3}.txt", "\u{3c2}.txt"],
2562            ["fi.txt", "\u{fb01}.txt"],
2563            ["caf\u{e9}.txt", "cafe\u{301}.txt"],
2564        ] {
2565            let c = clashes(&pair);
2566            assert_eq!(c.met_in.len(), 1, "{pair:?}");
2567            assert!(c.beyond_ascii.is_some(), "{pair:?}");
2568        }
2569        assert!(clashes(&["\u{65e5}.txt", "\u{4e2d}.txt"]).met_in.is_empty());
2570    }
2571
2572    /// Three that clash have to name every folder where any two meet, here
2573    /// `x` as well as the top, or a casefolded `x` would go unnoticed.
2574    #[test]
2575    fn clashes_cover_every_folder_where_names_meet() {
2576        let met = clashes(&["X/a/f", "x/A/f", "x/a/f", "other", "OTHER2"]).met_in;
2577        assert_eq!(
2578            met.keys().collect::<Vec<_>>(),
2579            [Path::new(""), Path::new("x")]
2580        );
2581    }
2582
2583    /// A file in a separate case-sensitive branch does not stop folders
2584    /// inside the other branch from merging on a case-insensitive mount.
2585    #[test]
2586    fn directory_aliases_need_no_case_separation_in_a_fileless_branch() {
2587        let tmp = tempfile::tempdir().unwrap();
2588        let path = tmp.path().join("archive.bin");
2589        fs::write(&path, [0u8; 64]).unwrap();
2590        let storage = Arc::new(Storage::open(&path, false).unwrap());
2591        let units = ["A/f", "a/F/one.txt", "a/f/two.txt"]
2592            .iter()
2593            .enumerate()
2594            .map(|(i, name)| unit(i as u64, name, 1))
2595            .collect();
2596        let job = Job::build(storage, opened(units, 64), 64).unwrap();
2597        let clashes = job.check_layout().unwrap();
2598        assert_eq!(clashes.met_in.keys().collect::<Vec<_>>(), [Path::new("")]);
2599    }
2600
2601    /// Folders between files must still meet the file on each side. Compare
2602    /// every mixture of absent paths, folders and files with all real pairs
2603    /// across three levels, including fileless branches between two files.
2604    #[test]
2605    fn case_folders_match_every_file_file_and_file_folder_pair() {
2606        let paths = [
2607            "A/B/C", "A/B/c", "A/b/C", "A/b/c", "a/B/C", "a/B/c", "a/b/C", "a/b/c",
2608        ];
2609        for mut choices in 0..3usize.pow(paths.len() as u32) {
2610            let mut names = Vec::new();
2611            for path in paths {
2612                let kind = choices % 3;
2613                choices /= 3;
2614                if kind != 0 {
2615                    names.push((path.to_lowercase(), Path::new(path), kind == 2));
2616                }
2617            }
2618            let mut expected = std::collections::BTreeSet::new();
2619            for (i, a) in names.iter().enumerate() {
2620                for b in &names[i + 1..] {
2621                    if a.2 || b.2 {
2622                        expected.insert(meeting_folder(a.1, b.1));
2623                    }
2624                }
2625            }
2626            let clashes = CaseClashes::of(&names);
2627            assert_eq!(
2628                clashes.met_in.keys().collect::<Vec<_>>(),
2629                expected.iter().collect::<Vec<_>>(),
2630                "{names:?}"
2631            );
2632        }
2633    }
2634
2635    /// A file against thousands of folders is a pair for each neighbour, not
2636    /// one for each combination, or a small archive could exhaust memory.
2637    #[test]
2638    fn clashes_stay_linear_in_the_names() {
2639        let paths: Vec<String> = (0..4096u32)
2640            .map(|bits| {
2641                (0..12)
2642                    .map(|i| if bits >> i & 1 == 1 { 'A' } else { 'a' })
2643                    .collect()
2644            })
2645            .collect();
2646        let mut names: Vec<(String, &Path, bool)> = paths
2647            .iter()
2648            .enumerate()
2649            .map(|(i, p)| (p.to_lowercase(), Path::new(p), i % 2 == 0))
2650            .collect();
2651        names.sort_unstable();
2652        assert_eq!(CaseClashes::of(&names).met_in.len(), 1);
2653    }
2654
2655    /// U+212A KELVIN SIGN lowercases to `k`, and APFS takes it for `K` even
2656    /// on a case-sensitive volume. Noted everywhere, since a run can go on
2657    /// from one system on another.
2658    #[test]
2659    fn names_beyond_ascii_are_noted_on_every_system() {
2660        assert!(clashes(&["K.txt", "\u{212a}.txt"]).beyond_ascii.is_some());
2661        assert!(clashes(&["Makefile", "makefile"]).beyond_ascii.is_none());
2662    }
2663
2664    /// The folder asked is the one that exists nearest to where the names
2665    /// meet, not the output folder, which an earlier check would have passed.
2666    #[test]
2667    fn the_nearest_existing_folder_decides() {
2668        let tmp = tempfile::TempDir::new().unwrap();
2669        let out = tmp.path().join("out");
2670        fs::create_dir_all(out.join("mounted")).unwrap();
2671        let asked = std::cell::RefCell::new(Vec::new());
2672        let result = first_not_apart(
2673            &out,
2674            [
2675                Path::new(""),
2676                Path::new("new/deep"),
2677                Path::new("mounted/new"),
2678            ],
2679            |dir| {
2680                asked.borrow_mut().push(dir.to_path_buf());
2681                dir != out.join("mounted")
2682            },
2683        );
2684        assert_eq!(
2685            result,
2686            Some((Path::new("mounted/new"), out.join("mounted")))
2687        );
2688        assert_eq!(*asked.borrow(), [out.clone(), out.join("mounted")]);
2689    }
2690
2691    fn unit(start: u64, name: &str, size: u64) -> Unit {
2692        Unit {
2693            start,
2694            key: 0,
2695            items: vec![Item {
2696                path: name.into(),
2697                size,
2698                kind: Kind::File,
2699                mode: None,
2700                mtime: None,
2701            }],
2702            encrypted: false,
2703        }
2704    }
2705
2706    /// A 64 byte file standing in for an archive, in its own folder.
2707    fn storage(test: &str) -> (PathBuf, Arc<Storage>) {
2708        let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2709        fs::create_dir_all(&dir).unwrap();
2710        let path = dir.join("archive.bin");
2711        fs::write(&path, [0u8; 64]).unwrap();
2712        let storage = Arc::new(Storage::open(&path, false).unwrap());
2713        (dir, storage)
2714    }
2715
2716    fn opened(units: Vec<Unit>, tail_start: u64) -> Opened {
2717        Opened {
2718            name: "test",
2719            format: Box::new(NoFormat),
2720            units,
2721            tail_start,
2722        }
2723    }
2724
2725    /// An empty folder of this test's own, under the system's temporary one.
2726    fn scratch(test: &str) -> PathBuf {
2727        let dir = std::env::temp_dir().join(format!("hatchzip-{test}-{}", std::process::id()));
2728        let _ = fs::remove_dir_all(&dir);
2729        fs::create_dir_all(&dir).unwrap();
2730        dir
2731    }
2732
2733    /// What a batch claims must be on disk, whole, or the journal would
2734    /// truncate the archive behind a file that another program took away.
2735    #[test]
2736    fn a_batch_that_is_all_on_disk_verifies() {
2737        let out = scratch("verify-complete");
2738        fs::create_dir_all(out.join("game")).unwrap();
2739        fs::write(out.join("game/a"), b"hello").unwrap();
2740        fs::write(out.join("game/empty"), b"").unwrap();
2741        let batch = [unit(10, "game/a", 5), unit(20, "game/empty", 0)];
2742        assert!(verify_extracted(&batch, &out).is_ok());
2743        fs::remove_dir_all(&out).unwrap();
2744    }
2745
2746    #[test]
2747    fn a_missing_file_fails_verification() {
2748        let out = scratch("verify-missing");
2749        let err = verify_extracted(&[unit(0, "game/gone", 12)], &out)
2750            .err()
2751            .unwrap();
2752        let text = err.to_string();
2753        assert!(text.contains("game/gone"), "{text}");
2754        assert!(text.contains("disappeared"), "{text}");
2755        assert!(text.contains("12 bytes"), "{text}");
2756        fs::remove_dir_all(&out).unwrap();
2757    }
2758
2759    #[test]
2760    fn a_file_of_the_wrong_size_fails_verification() {
2761        let out = scratch("verify-size");
2762        fs::create_dir_all(out.join("game")).unwrap();
2763        fs::write(out.join("game/a"), b"abc").unwrap();
2764        let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2765            .err()
2766            .unwrap();
2767        let text = err.to_string();
2768        assert!(text.contains("game/a"), "{text}");
2769        assert!(text.contains("records 5 bytes"), "{text}");
2770        assert!(text.contains("has 3"), "{text}");
2771        fs::remove_dir_all(&out).unwrap();
2772    }
2773
2774    #[test]
2775    fn a_folder_at_the_name_of_a_file_fails_verification() {
2776        let out = scratch("verify-folder");
2777        fs::create_dir_all(out.join("game/a")).unwrap();
2778        let err = verify_extracted(&[unit(0, "game/a", 5)], &out)
2779            .err()
2780            .unwrap();
2781        assert!(err.to_string().contains("no longer a file"), "{err}");
2782        fs::remove_dir_all(&out).unwrap();
2783    }
2784
2785    /// The link points at a file of exactly the recorded size, so only a
2786    /// check that never follows links can refuse it.
2787    #[cfg(unix)]
2788    #[test]
2789    fn a_link_at_the_name_of_a_file_fails_verification() {
2790        let out = scratch("verify-link");
2791        fs::write(out.join("real"), b"hello").unwrap();
2792        std::os::unix::fs::symlink("real", out.join("link")).unwrap();
2793        let err = verify_extracted(&[unit(0, "link", 5)], &out).err().unwrap();
2794        assert!(err.to_string().contains("no longer a file"), "{err}");
2795        fs::remove_dir_all(&out).unwrap();
2796    }
2797
2798    /// Folders and links are not on disk yet when a batch commits; links are
2799    /// made at the very end.
2800    #[test]
2801    fn other_kinds_of_entries_are_not_verified() {
2802        let out = scratch("verify-kinds");
2803        let item = |kind: Kind| Item {
2804            path: "absent".into(),
2805            size: 0,
2806            kind,
2807            mode: None,
2808            mtime: None,
2809        };
2810        let batch = Unit {
2811            start: 0,
2812            key: 0,
2813            items: vec![
2814                item(Kind::Dir),
2815                item(Kind::Symlink),
2816                item(Kind::HardLink("absent".into())),
2817            ],
2818            encrypted: false,
2819        };
2820        assert!(verify_extracted(&[batch], &out).is_ok());
2821        fs::remove_dir_all(&out).unwrap();
2822    }
2823
2824    /// Committing one of two units that start at the same offset would
2825    /// truncate the other before it is extracted.
2826    #[test]
2827    fn units_sharing_a_start_are_refused() {
2828        let (dir, storage) = storage("shared-start");
2829        let shared = vec![unit(10, "a", 1), unit(30, "b", 1), unit(10, "c", 1)];
2830        let err = Job::build(storage.clone(), opened(shared, 40), 64)
2831            .err()
2832            .unwrap();
2833        assert!(err.to_string().contains("same offset"), "{err:#}");
2834        let apart = vec![unit(10, "a", 1), unit(30, "b", 1)];
2835        assert!(Job::build(storage, opened(apart, 40), 64).is_ok());
2836        fs::remove_dir_all(&dir).unwrap();
2837    }
2838
2839    /// A unit at or past the end of the file used to be dropped as if an
2840    /// earlier run had extracted it, and a tail past the end can't be saved.
2841    #[test]
2842    fn data_past_the_end_of_the_file_is_refused() {
2843        let (dir, storage) = storage("past-the-end");
2844        for (starts, tail_start) in [(vec![10, 64], 40), (vec![10, 70], 40), (vec![10], 65)] {
2845            let units = starts
2846                .iter()
2847                .map(|&s| unit(s, &format!("f{s}"), 1))
2848                .collect();
2849            let err = Job::build(storage.clone(), opened(units, tail_start), 64)
2850                .err()
2851                .unwrap();
2852            assert!(err.is::<archive::Damaged>(), "{starts:?}: {err:#}");
2853        }
2854        // Resumed with the end already truncated away, it is simply done.
2855        let job = Job::build(
2856            storage,
2857            opened(vec![unit(10, "a", 1), unit(50, "b", 1)], 60),
2858            40,
2859        );
2860        assert_eq!(job.unwrap().units.len(), 1);
2861        fs::remove_dir_all(&dir).unwrap();
2862    }
2863
2864    /// Sizes come from the archive's headers. Summed or rounded up to whole
2865    /// blocks in 64 bits they could wrap, and the space check would count
2866    /// next to nothing.
2867    #[test]
2868    fn sizes_too_large_to_add_up_are_refused() {
2869        let (dir, storage) = storage("huge-sizes");
2870        let half = 1u64 << 63;
2871        for sizes in [vec![half, half], vec![u64::MAX - 10], vec![(1 << 62) + 1]] {
2872            let units = sizes
2873                .iter()
2874                .enumerate()
2875                .map(|(i, &s)| unit(10 + i as u64, &format!("f{i}"), s))
2876                .collect();
2877            let err = Job::build(storage.clone(), opened(units, 40), 64)
2878                .err()
2879                .unwrap();
2880            assert!(err.is::<archive::Damaged>(), "{sizes:?}: {err:#}");
2881        }
2882        assert_eq!(on_disk(&unit(0, "f", u64::MAX - 10)), u64::MAX);
2883        let mut two = unit(0, "f", half);
2884        two.items.extend(unit(0, "g", half).items);
2885        assert_eq!(two.size(), u64::MAX);
2886        assert_eq!(on_disk(&two), u64::MAX);
2887        fs::remove_dir_all(&dir).unwrap();
2888    }
2889}
2890
2891#[cfg(test)]
2892mod space_errors {
2893    use super::{is_disk_full, out_of_space};
2894    use anyhow::Context;
2895    use std::io;
2896
2897    #[test]
2898    fn disk_full_errors_become_the_resume_stop() {
2899        for kind in [io::ErrorKind::StorageFull, io::ErrorKind::QuotaExceeded] {
2900            let e: anyhow::Error = Err::<(), _>(io::Error::from(kind))
2901                .context("extracting 'game/a'")
2902                .unwrap_err();
2903            assert!(is_disk_full(&e), "{kind:?} not recognized as full");
2904            let e = out_of_space(e, "'game/a'");
2905            let msg = e.to_string();
2906            assert!(msg.contains("not enough disk space to continue"), "{msg}");
2907            assert!(msg.contains("Progress is saved"), "{msg}");
2908            // The original error stays in the chain, so the OS text shows.
2909            let full = format!("{e:#}");
2910            assert!(full.contains("extracting 'game/a'"), "{full}");
2911        }
2912    }
2913
2914    #[test]
2915    fn other_write_errors_pass_through() {
2916        for kind in [
2917            io::ErrorKind::PermissionDenied,
2918            io::ErrorKind::AlreadyExists,
2919        ] {
2920            let e: anyhow::Error = Err::<(), _>(io::Error::from(kind))
2921                .context("extracting 'game/a'")
2922                .unwrap_err();
2923            assert!(!is_disk_full(&e), "{kind:?} taken for a full disk");
2924            let msg = out_of_space(e, "'game/a'").to_string();
2925            assert!(msg.contains("extracting 'game/a'"), "{msg}");
2926            assert!(!msg.contains("Progress is saved"), "{msg}");
2927        }
2928    }
2929}