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
5pub mod resumable;
6mod sevenz;
7pub mod storage;
8mod tar;
9mod zip;
10
11use std::io::Read;
12use std::path::{Component, Path, PathBuf};
13use std::sync::Arc;
14use std::time::SystemTime;
15
16use anyhow::{Result, bail};
17
18use storage::{Storage, Tail};
19
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Kind {
22    File,
23    Dir,
24    /// The link target is the item's data.
25    Symlink,
26    /// Hard links point at an earlier entry, which is extracted later than
27    /// the link when going from the end, so they are made at the very end.
28    HardLink(PathBuf),
29}
30
31#[derive(Clone, Debug)]
32pub struct Item {
33    pub path: PathBuf,
34    pub size: u64,
35    pub kind: Kind,
36    pub mode: Option<u32>,
37    pub mtime: Option<SystemTime>,
38}
39
40pub struct Unit {
41    /// Where the unit's bytes begin. Once it is committed the archive is
42    /// truncated to this offset.
43    pub start: u64,
44    /// The format's own handle for the unit: a ZIP entry index, a 7z block.
45    pub key: usize,
46    pub items: Vec<Item>,
47    /// Decoding it needs the archive's password.
48    pub encrypted: bool,
49}
50
51/// The archive is encrypted and nothing can be read without its password.
52/// Front ends look for this error to ask for one.
53#[derive(Debug)]
54pub struct PasswordNeeded;
55
56impl std::fmt::Display for PasswordNeeded {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.write_str("this archive is password protected")
59    }
60}
61
62impl std::error::Error for PasswordNeeded {}
63
64/// The password doesn't open the archive.
65#[derive(Debug)]
66pub struct WrongPassword;
67
68impl std::fmt::Display for WrongPassword {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.write_str("that password doesn't open this archive")
71    }
72}
73
74impl std::error::Error for WrongPassword {}
75
76impl Unit {
77    pub fn size(&self) -> u64 {
78        self.items.iter().map(|i| i.size).sum()
79    }
80}
81
82pub trait Format: Send + Sync {
83    /// A worker decodes units on one thread. `threads` is a hint for codecs
84    /// that can decode a single stream on several cores.
85    fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
86
87    /// For a unit holding one file whose data [`resumable`] can decode from
88    /// the middle: where that data lies. Such units can free their archive
89    /// bytes while they are extracted instead of only once they are done.
90    fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
91        Ok(None)
92    }
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub enum Codec {
97    Stored,
98    /// Raw deflate, as ZIP stores it.
99    Deflate,
100}
101
102#[derive(Clone, Debug)]
103pub struct Stream {
104    /// Where the file's data begins. The headers before it stay untouched
105    /// until the unit is committed, so the archive still parses on resume.
106    pub data_start: u64,
107    /// Length of the data in the archive.
108    pub packed: u64,
109    pub codec: Codec,
110    /// CRC-32 of the output, if the format records one.
111    pub crc: Option<u32>,
112}
113
114pub trait Worker {
115    /// Decodes `unit`, handing each item to `sink` in order.
116    fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
117}
118
119pub trait Sink {
120    fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
121}
122
123pub struct Opened {
124    pub name: &'static str,
125    pub format: Box<dyn Format>,
126    pub units: Vec<Unit>,
127    /// Everything from here to the end is saved before anything is reclaimed.
128    pub tail_start: u64,
129}
130
131/// Parses the archive. `resume` carries the format recorded by an earlier
132/// run and the tail it saved; a fresh run sniffs the format instead. The
133/// password is only needed for encrypted archives; whether it is right is
134/// found out when a unit is decoded (see `Job::check_password`).
135pub fn open(
136    storage: &Arc<Storage>,
137    resume: Option<(&str, Arc<Tail>)>,
138    password: Option<&str>,
139) -> Result<Opened> {
140    let (name, tail) = match resume {
141        Some((name, tail)) => (name.to_string(), Some(tail)),
142        None => (sniff(storage)?.to_string(), None),
143    };
144    match name.as_str() {
145        "zip" => zip::open(storage, tail, password),
146        "7z" => sevenz::open(storage, tail, password),
147        "tar" => tar::open(storage, tail),
148        other => bail!("unknown archive format '{other}' in the journal"),
149    }
150}
151
152/// What turns the first `keep` bytes of a half-extracted archive back into an
153/// archive any tool opens.
154pub struct NewIndex {
155    /// Written at `keep`.
156    pub append: Vec<u8>,
157    /// Written over bytes below `keep`: the 7z start header, which has to
158    /// point at the new header.
159    pub patches: Vec<(u64, Vec<u8>)>,
160}
161
162/// Builds the [`NewIndex`] for the entries that start below `keep`, from
163/// the tail an earlier run saved. `hard_links` are tar links already cut off
164/// whose targets are still in the archive.
165pub fn rebuild_index(
166    format: &str,
167    storage: &Storage,
168    tail: Arc<Tail>,
169    keep: u64,
170    hard_links: &[(&Path, &Path)],
171) -> Result<NewIndex> {
172    let (append, patches) = match format {
173        "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
174        "tar" => (tar::closing(hard_links)?, Vec::new()),
175        "7z" => {
176            let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
177            (header, vec![(0, start)])
178        }
179        other => bail!("unknown archive format '{other}' in the journal"),
180    };
181    Ok(NewIndex { append, patches })
182}
183
184fn sniff(storage: &Storage) -> Result<&'static str> {
185    let mut head = [0u8; 512];
186    let mut r = storage.reader(None);
187    let n = read_up_to(&mut r, &mut head)?;
188    let head = &head[..n];
189    let starts = |magic: &[u8]| head.starts_with(magic);
190    if starts(b"7z\xBC\xAF\x27\x1C") {
191        return Ok("7z");
192    }
193    if head.len() >= 263 && &head[257..262] == b"ustar" {
194        return Ok("tar");
195    }
196    if starts(b"\x1F\x8B")
197        || starts(b"\x28\xB5\x2F\xFD")
198        || starts(b"\xFD7zXZ\x00")
199        || starts(b"BZh")
200    {
201        bail!(
202            "this is a compressed stream (.gz, .zst, .xz or .bz2). In-place extraction of those \
203             needs a different technique that HatchZip doesn't have yet"
204        );
205    }
206    if starts(b"Rar!\x1A\x07") {
207        bail!("RAR archives aren't supported yet");
208    }
209    let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
210    if ext.ends_with(".tar") || ext.contains(".tar.") {
211        return Ok("tar");
212    }
213    // Anything else gets a ZIP parse: self-extracting archives put an
214    // executable in front, so the signature isn't at the start.
215    Ok("zip")
216}
217
218fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
219    let mut n = 0;
220    while n < buf.len() {
221        match r.read(&mut buf[n..])? {
222            0 => break,
223            k => n += k,
224        }
225    }
226    Ok(n)
227}
228
229/// Turns an archive member name into a relative path that can't leave the
230/// output folder. Leading slashes are dropped, as tar does; `..`, drive
231/// letters and NUL bytes are refused.
232pub fn safe_path(name: &str) -> Option<PathBuf> {
233    if name.contains('\0') {
234        return None;
235    }
236    let mut out = PathBuf::new();
237    for part in name.split(['/', '\\']) {
238        match part {
239            "" | "." => {}
240            ".." => return None,
241            p if p.contains(':') => return None,
242            p => out.push(p),
243        }
244    }
245    let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
246    (clean && !out.as_os_str().is_empty()).then_some(out)
247}
248
249/// Unix permission bits as 7-Zip and Info-ZIP store them in the high half of
250/// the Windows attributes.
251fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
252    (attrs & 0x8000 != 0).then_some(attrs >> 16)
253}
254
255const S_IFMT: u32 = 0o170000;
256const S_IFLNK: u32 = 0o120000;
257
258fn is_symlink_mode(mode: Option<u32>) -> bool {
259    mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
260}