1#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11pub mod targz;
12mod zip;
13
14use std::io::Read;
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17use std::time::SystemTime;
18
19use anyhow::{Context, Result, bail};
20
21use crate::journal::Resume;
22use storage::{Storage, Tail};
23use targz::Solid;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum Kind {
27 File,
28 Dir,
29 Symlink,
31 HardLink(PathBuf),
34}
35
36#[derive(Clone, Debug)]
37pub struct Item {
38 pub path: PathBuf,
39 pub size: u64,
40 pub kind: Kind,
41 pub mode: Option<u32>,
42 pub mtime: Option<SystemTime>,
43}
44
45pub struct Unit {
46 pub start: u64,
49 pub key: usize,
51 pub items: Vec<Item>,
52 pub encrypted: bool,
54}
55
56#[derive(Debug)]
59pub struct PasswordNeeded;
60
61impl std::fmt::Display for PasswordNeeded {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.write_str("this archive is password protected")
64 }
65}
66
67impl std::error::Error for PasswordNeeded {}
68
69#[derive(Debug)]
71pub struct WrongPassword;
72
73impl std::fmt::Display for WrongPassword {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.write_str("incorrect password")
76 }
77}
78
79impl std::error::Error for WrongPassword {}
80
81#[derive(Debug)]
84pub struct Damaged(pub anyhow::Error);
85
86impl std::fmt::Display for Damaged {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{:#}", self.0)
89 }
90}
91
92impl std::error::Error for Damaged {}
93
94pub const RAR: &str = "rar";
96
97pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
100
101pub fn no_rar() -> anyhow::Error {
103 anyhow::anyhow!(
104 "this build of HatchZip does not include RAR support, and the archive was not \
105 modified. Download the release build from hatchzip.dev or \
106 github.com/xevrion/hatchzip/releases"
107 )
108}
109
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub enum PasswordCheck {
114 Sample,
117 Headers,
120 WholeUnit,
123}
124
125impl Unit {
126 pub fn size(&self) -> u64 {
127 self.items.iter().map(|i| i.size).sum()
128 }
129}
130
131pub trait Format: Send + Sync {
132 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
135
136 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
140 Ok(None)
141 }
142
143 fn solid(&self) -> Option<&Solid> {
147 None
148 }
149
150 fn serial(&self) -> bool {
155 false
156 }
157
158 fn refuses_in_place(&self) -> Option<String> {
161 None
162 }
163
164 fn password_check(&self) -> PasswordCheck {
165 PasswordCheck::Sample
166 }
167
168 fn prove_password(&self) -> Result<()> {
171 Ok(())
172 }
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum Codec {
177 Stored,
178 Deflate,
180}
181
182#[derive(Clone, Debug)]
183pub struct Stream {
184 pub data_start: u64,
187 pub packed: u64,
189 pub codec: Codec,
190 pub crc: Option<u32>,
192}
193
194pub trait Worker {
195 fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
197}
198
199pub trait Sink {
200 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
201}
202
203pub struct Opened {
204 pub name: &'static str,
205 pub format: Box<dyn Format>,
206 pub units: Vec<Unit>,
207 pub tail_start: u64,
209}
210
211pub fn open(
217 storage: &Arc<Storage>,
218 resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
219 password: Option<&str>,
220) -> Result<Opened> {
221 let (name, tail, point) = match resume {
222 Some((name, tail, point)) => (name.to_string(), Some(tail), point),
223 None => (sniff(storage)?.to_string(), None, None),
224 };
225 match name.as_str() {
226 "zip" => zip::open(storage, tail, password),
227 "7z" => sevenz::open(storage, tail, password),
228 "tar" => tar::open(storage, tail),
229 #[cfg(feature = "rar")]
230 RAR => rar::open(storage, tail.is_some(), password),
231 #[cfg(not(feature = "rar"))]
232 RAR => Err(no_rar()),
233 targz::NAME => targz::open(storage, point),
234 other => bail!("unknown archive format '{other}' in the journal"),
235 }
236}
237
238pub struct NewIndex {
241 pub append: Vec<u8>,
243 pub patches: Vec<(u64, Vec<u8>)>,
246}
247
248pub fn rebuild_index(
252 format: &str,
253 storage: &Storage,
254 tail: Arc<Tail>,
255 keep: u64,
256 hard_links: &[(&Path, &Path)],
257) -> Result<NewIndex> {
258 let (append, patches) = match format {
259 "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
260 "tar" => (tar::closing(hard_links)?, Vec::new()),
261 "7z" => {
262 let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
263 (header, vec![(0, start)])
264 }
265 #[cfg(feature = "rar")]
267 RAR => (rar::closing(storage, keep)?, Vec::new()),
268 #[cfg(not(feature = "rar"))]
269 RAR => return Err(no_rar()),
270 other => bail!("unknown archive format '{other}' in the journal"),
271 };
272 Ok(NewIndex { append, patches })
273}
274
275fn sniff(storage: &Storage) -> Result<&'static str> {
276 let mut head = [0u8; 512];
277 let mut r = storage.reader(None);
278 let n = read_up_to(&mut r, &mut head)?;
279 let head = &head[..n];
280 let starts = |magic: &[u8]| head.starts_with(magic);
281 if starts(b"7z\xBC\xAF\x27\x1C") {
282 return Ok("7z");
283 }
284 let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
285 if is_tar(head) {
286 return Ok("tar");
287 }
288 let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
289 if starts(b"\x1F\x8B") {
290 let mut gz = resumable::Gzip::new(
292 storage.reader(None),
293 storage.original_len(),
294 &resumable::GzPoint::start(),
295 )?;
296 let mut first = [0u8; 512];
297 let mut n = 0;
298 while n < first.len() {
299 match gz
300 .read(&mut first[n..])
301 .context("reading the start of the compressed stream")?
302 {
303 0 => break,
304 k => n += k,
305 }
306 }
307 let named = [".tar.gz", ".tgz", ".taz"]
308 .iter()
309 .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
310 if is_tar(&first[..n]) || named {
311 return Ok(targz::NAME);
312 }
313 bail!(
314 "this is a gzip-compressed file that does not contain a tar archive. Only \
315 compressed tar archives (.tar.gz) can be extracted"
316 );
317 }
318 if starts(b"\x28\xB5\x2F\xFD") || starts(b"\xFD7zXZ\x00") || starts(b"BZh") {
319 bail!(
320 "this is a compressed stream (.zst, .xz or .bz2). In-place extraction of these \
321 compressed streams is not supported yet"
322 );
323 }
324 if starts(b"Rar!\x1A\x07") {
325 return Ok(RAR);
326 }
327 if ext.ends_with(".tar") || ext.contains(".tar.") {
328 return Ok("tar");
329 }
330 Ok("zip")
333}
334
335fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
336 let mut n = 0;
337 while n < buf.len() {
338 match r.read(&mut buf[n..])? {
339 0 => break,
340 k => n += k,
341 }
342 }
343 Ok(n)
344}
345
346pub fn safe_path(name: &str) -> Option<PathBuf> {
350 if name.contains('\0') {
351 return None;
352 }
353 let mut out = PathBuf::new();
354 for part in name.split(['/', '\\']) {
355 match part {
356 "" | "." => {}
357 ".." => return None,
358 p if p.contains(':') => return None,
359 p => out.push(p),
360 }
361 }
362 let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
363 (clean && !out.as_os_str().is_empty()).then_some(out)
364}
365
366fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
369 (attrs & 0x8000 != 0).then_some(attrs >> 16)
370}
371
372const S_IFMT: u32 = 0o170000;
373const S_IFLNK: u32 = 0o120000;
374
375fn is_symlink_mode(mode: Option<u32>) -> bool {
376 mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
377}