Skip to main content

hatchzip_core/archive/
mod.rs

1//! What the engine needs from an archive format: the archive split into
2//! units, byte ranges that can be truncated away once every file in them is
3//! safely on disk, and a way to decode one unit.
4
5#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11pub mod targz;
12pub mod tarxz;
13mod xz;
14mod zip;
15
16use std::io::Read;
17use std::path::{Component, Path, PathBuf};
18use std::sync::Arc;
19use std::time::SystemTime;
20
21use anyhow::{Context, Result, bail};
22
23use crate::journal::Resume;
24use storage::{Storage, Tail};
25use targz::Event;
26use targz::Profile;
27
28/// An archive that is one compressed stream, decodable only from the front:
29/// everything it holds is inside one decode pass, so instead of units
30/// extracted from the end, the whole archive is one unit extracted front to
31/// back, and the engine frees the compressed bytes behind the decoder. See
32/// `targz` and `tarxz`.
33pub trait SolidStream: Send + Sync {
34    /// What a scan measured about the output: see [`targz::Profile`].
35    fn profile(&self) -> &targz::Profile;
36    /// Walks the archive from `from`, or from its start. The walk depends
37    /// on nothing but the archive, so the box outlives the cloneable
38    /// handle it came from.
39    fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
40}
41
42/// The walk a [`SolidStream`] produces: the tar's events and, at the
43/// [`Event::Point`] ones, how decoding can restart.
44pub trait SolidWalker {
45    /// The next event. `Data` is at most `max` bytes, borrowed until the
46    /// next call.
47    fn next(&mut self, max: usize) -> Result<Event<'_>>;
48    /// The resume point at the `Point` event just returned. Its `unit` is
49    /// left for the engine to fill in.
50    fn point(&self) -> Result<Resume>;
51    /// The archive byte a resume point here would restart in. Cheap: for
52    /// measuring only.
53    fn point_byte(&self) -> Option<u64>;
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub enum Kind {
58    File,
59    Dir,
60    /// The link target is the item's data.
61    Symlink,
62    /// Hard links point at an earlier entry, which is extracted later than
63    /// the link when going from the end, so they are made at the very end.
64    HardLink(PathBuf),
65}
66
67#[derive(Clone, Debug)]
68pub struct Item {
69    pub path: PathBuf,
70    pub size: u64,
71    pub kind: Kind,
72    pub mode: Option<u32>,
73    pub mtime: Option<SystemTime>,
74}
75
76pub struct Unit {
77    /// Where the unit's bytes begin. Once it is committed the archive is
78    /// truncated to this offset.
79    pub start: u64,
80    /// The format's own handle for the unit: a ZIP entry index, a 7z block.
81    pub key: usize,
82    pub items: Vec<Item>,
83    /// Decoding it needs the archive's password.
84    pub encrypted: bool,
85}
86
87/// The archive is encrypted and nothing can be read without its password.
88/// Front ends look for this error to ask for one.
89#[derive(Debug)]
90pub struct PasswordNeeded;
91
92impl std::fmt::Display for PasswordNeeded {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.write_str("this archive is password protected")
95    }
96}
97
98impl std::error::Error for PasswordNeeded {}
99
100/// The password doesn't open the archive.
101#[derive(Debug)]
102pub struct WrongPassword;
103
104impl std::fmt::Display for WrongPassword {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.write_str("incorrect password")
107    }
108}
109
110impl std::error::Error for WrongPassword {}
111
112/// The archive is damaged, found while opening it and before anything was
113/// touched. Front ends look for this error to report damage as such.
114#[derive(Debug)]
115pub struct Damaged(pub anyhow::Error);
116
117impl std::fmt::Display for Damaged {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        write!(f, "{:#}", self.0)
120    }
121}
122
123impl std::error::Error for Damaged {}
124
125/// The archive is valid but uses something this build does not extract: an
126/// unknown or unprovided check, an unknown filter, several xz streams, or a
127/// dictionary too large to hold. Front ends report it as unsupported, never
128/// as damage.
129#[derive(Debug)]
130pub struct Unsupported(pub anyhow::Error);
131
132impl std::fmt::Display for Unsupported {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "{:#}", self.0)
135    }
136}
137
138impl std::error::Error for Unsupported {}
139
140/// The format name of RAR archives in the journal.
141pub const RAR: &str = "rar";
142
143/// Whether this build extracts RAR archives. Builds without UnRAR refuse
144/// them before anything is touched.
145pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
146
147/// Why a build without UnRAR refuses a RAR archive.
148pub fn no_rar() -> anyhow::Error {
149    anyhow::anyhow!(
150        "this build of HatchZip does not include RAR support, and the archive was not \
151         modified. Download the release build from hatchzip.dev or \
152         github.com/xevrion/hatchzip/releases"
153    )
154}
155
156/// How the password of an encrypted archive is proven before anything is
157/// touched.
158#[derive(Clone, Copy, Debug, PartialEq, Eq)]
159pub enum PasswordCheck {
160    /// Decode the start of the smallest encrypted unit: a wrong password
161    /// fails at once, or within the first blocks.
162    Sample,
163    /// The headers hold a check value for the password, so
164    /// [`Format::prove_password`] answers without decoding anything.
165    Headers,
166    /// Only the checksum at the end of a file can tell, so the smallest
167    /// encrypted unit is decoded whole, writing nothing.
168    WholeUnit,
169}
170
171impl Unit {
172    /// Saturates instead of wrapping: sizes come straight from the archive.
173    pub fn size(&self) -> u64 {
174        self.items
175            .iter()
176            .fold(0u64, |sum, i| sum.saturating_add(i.size))
177    }
178}
179
180pub trait Format: Send + Sync {
181    /// A worker decodes units on one thread. `threads` is a hint for codecs
182    /// that can decode a single stream on several cores.
183    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
184
185    /// For a unit holding one file whose data [`resumable`] can decode from
186    /// the middle: where that data lies. Such units can free their archive
187    /// bytes while they are extracted instead of only once they are done.
188    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
189        Ok(None)
190    }
191
192    /// For an archive that is one compressed stream, decodable only from the
193    /// front: its single unit, extracted front to back while the bytes behind
194    /// the decoder are freed.
195    fn solid(&self) -> Option<&dyn SolidStream> {
196        None
197    }
198
199    /// The decoder finds a unit only by reading everything before it, and
200    /// one handle can't be shared between threads. A batch is then decoded
201    /// on one thread by one worker, lowest unit first, so the worker can
202    /// walk forward instead of starting over for every unit.
203    fn serial(&self) -> bool {
204        false
205    }
206
207    /// Why the archive can't be extracted in place, if it can't: it can
208    /// still be extracted while it is kept.
209    fn refuses_in_place(&self) -> Option<String> {
210        None
211    }
212
213    fn password_check(&self) -> PasswordCheck {
214        PasswordCheck::Sample
215    }
216
217    /// Proves the password from the headers alone; only called when
218    /// [`password_check`](Self::password_check) says it can.
219    fn prove_password(&self) -> Result<()> {
220        Ok(())
221    }
222}
223
224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
225pub enum Codec {
226    Stored,
227    /// Raw deflate, as ZIP stores it.
228    Deflate,
229}
230
231#[derive(Clone, Debug)]
232pub struct Stream {
233    /// Where the file's data begins. The headers before it stay untouched
234    /// until the unit is committed, so the archive still parses on resume.
235    pub data_start: u64,
236    /// Length of the data in the archive.
237    pub packed: u64,
238    pub codec: Codec,
239    /// CRC-32 of the output, if the format records one.
240    pub crc: Option<u32>,
241}
242
243pub trait Worker {
244    /// Decodes `unit`, handing each item to `sink` in order.
245    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
246}
247
248pub trait Sink {
249    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
250}
251
252pub struct Opened {
253    pub name: &'static str,
254    pub format: Box<dyn Format>,
255    pub units: Vec<Unit>,
256    /// Everything from here to the end is saved before anything is reclaimed.
257    pub tail_start: u64,
258}
259
260/// Parses the archive. `resume` carries the format recorded by an earlier
261/// run, the tail it saved and its resume point, which a compressed tar is
262/// read from; a fresh run sniffs the format instead. The password is only
263/// needed for encrypted archives; whether it is right is found out when a
264/// unit is decoded (see `Job::check_password`).
265pub fn open(
266    storage: &Arc<Storage>,
267    resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
268    password: Option<&str>,
269) -> Result<Opened> {
270    let (name, tail, point) = match resume {
271        Some((name, tail, point)) => (name.to_string(), Some(tail), point),
272        None => (sniff(storage)?.to_string(), None, None),
273    };
274    match name.as_str() {
275        "zip" => zip::open(storage, tail, password),
276        "7z" => sevenz::open(storage, tail, password),
277        "tar" => tar::open(storage, tail),
278        #[cfg(feature = "rar")]
279        RAR => rar::open(storage, tail.is_some(), password),
280        #[cfg(not(feature = "rar"))]
281        RAR => Err(no_rar()),
282        targz::NAME => targz::open(storage, point),
283        tarxz::NAME => tarxz::open(storage, point),
284        other => bail!("unknown archive format '{other}' in the journal"),
285    }
286}
287
288/// What turns the first `keep` bytes of a half-extracted archive back into an
289/// archive any tool opens.
290pub struct NewIndex {
291    /// Written at `keep`.
292    pub append: Vec<u8>,
293    /// Written over bytes below `keep`: the 7z start header, which has to
294    /// point at the new header.
295    pub patches: Vec<(u64, Vec<u8>)>,
296}
297
298/// Lists the entries of a [`SolidStream`]'s walk from `from` once to the
299/// end, and measures how the output runs ahead of the decoded bytes, which
300/// the space check needs. Damage found here, in the pass that runs before
301/// anything is touched and again from the resume point of a resumed run,
302/// stops the run.
303fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
304    let from_byte = from.map_or(0, |r| r.bit / 8);
305    let mut w = solid.walk(from)?;
306    let mut items = Vec::new();
307    let mut p = Profile::default();
308    let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
309    loop {
310        match w.next(usize::MAX)? {
311            Event::Entry { item, .. } => {
312                if item.kind == Kind::File {
313                    size = item.size;
314                }
315                items.push(item);
316            }
317            Event::Data(d) => out += d.len() as u64,
318            Event::FileEnd => out += size.next_multiple_of(4096) - size,
319            Event::Point => {
320                let consumed = w
321                    .point_byte()
322                    .unwrap_or(from_byte)
323                    .saturating_sub(from_byte);
324                p.lead = p.lead.max(out as i128 - consumed as i128);
325                p.gap = p.gap.max(out - last);
326                last = out;
327            }
328            Event::End => break,
329        }
330    }
331    p.gap = p.gap.max(out - last);
332    p.files = out;
333    tar::size_links(&mut items);
334    p.links = items
335        .iter()
336        .filter(|i| i.kind != Kind::File)
337        .fold(0u64, |sum, i| {
338            let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
339            sum.saturating_add(size)
340        });
341    Ok((items, p))
342}
343
344/// Builds the [`NewIndex`] for the entries that start below `keep`, from
345/// the tail an earlier run saved. `hard_links` are tar links already cut off
346/// whose targets are still in the archive.
347pub fn rebuild_index(
348    format: &str,
349    storage: &Storage,
350    tail: Arc<Tail>,
351    keep: u64,
352    hard_links: &[(&Path, &Path)],
353) -> Result<NewIndex> {
354    let (append, patches) = match format {
355        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
356        "tar" => (tar::closing(hard_links)?, Vec::new()),
357        "7z" => {
358            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
359            (header, vec![(0, start)])
360        }
361        // No index: the last volume left only needs its end header back.
362        #[cfg(feature = "rar")]
363        RAR => (rar::closing(storage, keep)?, Vec::new()),
364        #[cfg(not(feature = "rar"))]
365        RAR => return Err(no_rar()),
366        other => bail!("unknown archive format '{other}' in the journal"),
367    };
368    Ok(NewIndex { append, patches })
369}
370
371fn sniff(storage: &Storage) -> Result<&'static str> {
372    let mut head = [0u8; 512];
373    let mut r = storage.reader(None);
374    let n = read_up_to(&mut r, &mut head)?;
375    let head = &head[..n];
376    let starts = |magic: &[u8]| head.starts_with(magic);
377    if starts(b"7z\xBC\xAF\x27\x1C") {
378        return Ok("7z");
379    }
380    let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
381    if is_tar(head) {
382        return Ok("tar");
383    }
384    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
385    if starts(b"\x1F\x8B") {
386        // Look inside: a plain .gz of one file is not an archive.
387        let mut gz = resumable::Gzip::new(
388            storage.reader(None),
389            storage.original_len(),
390            &resumable::GzPoint::start(),
391        )?;
392        let mut first = [0u8; 512];
393        let mut n = 0;
394        while n < first.len() {
395            match gz
396                .read(&mut first[n..])
397                .context("reading the start of the compressed stream")?
398            {
399                0 => break,
400                k => n += k,
401            }
402        }
403        let named = [".tar.gz", ".tgz", ".taz"]
404            .iter()
405            .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
406        if is_tar(&first[..n]) || named {
407            return Ok(targz::NAME);
408        }
409        bail!(
410            "this is a gzip-compressed file that does not contain a tar archive. Only \
411             compressed tar archives (.tar.gz) can be extracted"
412        );
413    }
414    if starts(b"\xFD7zXZ\x00") {
415        // A .xz only ever comes as a compressed tar here; anything else is
416        // refused once the stream opens.
417        return Ok(tarxz::NAME);
418    }
419    if starts(b"\x28\xB5\x2F\xFD") || starts(b"BZh") {
420        bail!(
421            "this is a compressed stream (.zst or .bz2). In-place extraction of these \
422             compressed streams is not supported yet"
423        );
424    }
425    if starts(b"Rar!\x1A\x07") {
426        return Ok(RAR);
427    }
428    if ext.ends_with(".tar") || ext.contains(".tar.") {
429        return Ok("tar");
430    }
431    // Anything else gets a ZIP parse: self-extracting archives put an
432    // executable in front, so the signature isn't at the start.
433    Ok("zip")
434}
435
436fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
437    let mut n = 0;
438    while n < buf.len() {
439        match r.read(&mut buf[n..])? {
440            0 => break,
441            k => n += k,
442        }
443    }
444    Ok(n)
445}
446
447/// Turns an archive member name into a relative path that can't leave the
448/// output folder. Leading slashes are dropped, as tar does; `..`, NUL bytes
449/// and drive letters are refused.
450pub fn safe_path(name: &str) -> Option<PathBuf> {
451    if name.contains('\0') {
452        return None;
453    }
454    let mut out = PathBuf::new();
455    for part in name.split(['/', '\\']) {
456        match part {
457            "" | "." => {}
458            ".." => return None,
459            // A leading `C:` names a drive. Any other `:` is left to
460            // `platform::name_problem`, as it is a normal name character
461            // outside Windows, like in `10:30.txt`.
462            p if out.as_os_str().is_empty()
463                && p.len() == 2
464                && p.as_bytes()[0].is_ascii_alphabetic()
465                && p.ends_with(':') =>
466            {
467                return None;
468            }
469            p => out.push(p),
470        }
471    }
472    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
473    (clean && !out.as_os_str().is_empty()).then_some(out)
474}
475
476/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
477/// the Windows attributes.
478fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
479    (attrs & 0x8000 != 0).then_some(attrs >> 16)
480}
481
482const S_IFMT: u32 = 0o170000;
483const S_IFLNK: u32 = 0o120000;
484
485fn is_symlink_mode(mode: Option<u32>) -> bool {
486    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
487}