1#[cfg(feature = "rar")]
6mod rar;
7pub mod resumable;
8mod sevenz;
9pub mod storage;
10mod tar;
11mod tarbz2;
12pub mod targz;
13pub mod tarxz;
14pub mod tarzst;
15mod xz;
16mod zip;
17
18use std::fs;
19use std::io::{Read, Seek, SeekFrom};
20use std::path::{Component, Path, PathBuf};
21use std::sync::Arc;
22use std::time::SystemTime;
23
24use anyhow::{Context, Result, bail};
25
26use crate::journal::Resume;
27use storage::{Storage, Tail};
28use targz::Event;
29use targz::Profile;
30
31pub trait SolidStream: Send + Sync {
37 fn profile(&self) -> &targz::Profile;
39 fn walk(&self, from: Option<&Resume>) -> Result<Box<dyn SolidWalker>>;
43}
44
45pub trait SolidWalker {
48 fn next(&mut self, max: usize) -> Result<Event<'_>>;
51 fn point(&self) -> Result<Resume>;
54 fn point_byte(&self) -> Option<u64>;
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum Kind {
61 File,
62 Dir,
63 Symlink,
65 HardLink(PathBuf),
68}
69
70#[derive(Clone, Debug)]
71pub struct Item {
72 pub path: PathBuf,
73 pub size: u64,
74 pub kind: Kind,
75 pub mode: Option<u32>,
76 pub mtime: Option<SystemTime>,
77}
78
79#[derive(Clone)]
80pub struct Unit {
81 pub start: u64,
84 pub key: usize,
86 pub items: Vec<Item>,
87 pub encrypted: bool,
89}
90
91#[derive(Debug)]
94pub struct PasswordNeeded;
95
96impl std::fmt::Display for PasswordNeeded {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.write_str("this archive is password protected")
99 }
100}
101
102impl std::error::Error for PasswordNeeded {}
103
104#[derive(Debug)]
106pub struct WrongPassword;
107
108impl std::fmt::Display for WrongPassword {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.write_str("incorrect password")
111 }
112}
113
114impl std::error::Error for WrongPassword {}
115
116#[derive(Debug)]
119pub struct Damaged(pub anyhow::Error);
120
121impl std::fmt::Display for Damaged {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 write!(f, "{:#}", self.0)
124 }
125}
126
127impl std::error::Error for Damaged {}
128
129#[derive(Debug)]
134pub struct Unsupported(pub anyhow::Error);
135
136impl std::fmt::Display for Unsupported {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 write!(f, "{:#}", self.0)
139 }
140}
141
142impl std::error::Error for Unsupported {}
143
144pub const RAR: &str = "rar";
146
147pub const SPLIT_ZIP: &str = zip::SPLIT;
149
150pub const RAR_SUPPORTED: bool = cfg!(feature = "rar");
153
154pub fn no_rar() -> anyhow::Error {
156 anyhow::anyhow!(
157 "this build of HatchZip does not include RAR support, and the archive was not \
158 modified. Download the release build from hatchzip.dev or \
159 github.com/xevrion/hatchzip/releases"
160 )
161}
162
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum PasswordCheck {
167 Sample,
170 Headers,
173 WholeUnit,
176}
177
178impl Unit {
179 pub fn size(&self) -> u64 {
181 self.items
182 .iter()
183 .fold(0u64, |sum, i| sum.saturating_add(i.size))
184 }
185}
186
187pub trait Format: Send + Sync {
188 fn worker(&self, threads: u32) -> Result<Box<dyn Worker + '_>>;
191
192 fn stream(&self, _unit: &Unit) -> Result<Option<Stream>> {
196 Ok(None)
197 }
198
199 fn solid(&self) -> Option<&dyn SolidStream> {
203 None
204 }
205
206 fn serial(&self) -> bool {
211 false
212 }
213
214 fn refuses_in_place(&self) -> Option<String> {
217 None
218 }
219
220 fn password_check(&self) -> PasswordCheck {
221 PasswordCheck::Sample
222 }
223
224 fn prove_password(&self) -> Result<()> {
227 Ok(())
228 }
229}
230
231#[derive(Clone, Copy, Debug, PartialEq, Eq)]
232pub enum Codec {
233 Stored,
234 Deflate,
236}
237
238#[derive(Clone, Debug)]
239pub struct Stream {
240 pub data_start: u64,
243 pub packed: u64,
245 pub codec: Codec,
246 pub crc: Option<u32>,
248}
249
250pub trait Worker {
251 fn extract(&mut self, unit: &Unit, sink: &mut dyn Sink) -> Result<()>;
253}
254
255pub trait Sink {
256 fn item(&mut self, item: &Item, data: &mut dyn Read) -> Result<()>;
257}
258
259pub struct Opened {
260 pub name: &'static str,
261 pub format: Box<dyn Format>,
262 pub units: Vec<Unit>,
263 pub tail_start: u64,
265}
266
267pub fn open(
273 storage: &Arc<Storage>,
274 resume: Option<(&str, Arc<Tail>, Option<&Resume>)>,
275 password: Option<&str>,
276) -> Result<Opened> {
277 let (name, tail, point) = match resume {
278 Some((name, tail, point)) => (name.to_string(), Some(tail), point),
279 None => (sniff(storage)?.to_string(), None, None),
280 };
281 match name.as_str() {
282 "zip" => zip::open(storage, tail, password),
283 zip::SPLIT => zip::open_split(storage, tail, password),
284 "7z" => sevenz::open(storage, tail, password),
285 "tar" => tar::open(storage, tail),
286 #[cfg(feature = "rar")]
287 RAR => rar::open(storage, tail.is_some(), password),
288 #[cfg(not(feature = "rar"))]
289 RAR => Err(no_rar()),
290 targz::NAME => targz::open(storage, point),
291 tarbz2::NAME => tarbz2::open(storage, point),
292 tarxz::NAME => tarxz::open(storage, point),
293 tarzst::NAME => tarzst::open(storage, point),
294 other => bail!("unknown archive format '{other}' in the journal"),
295 }
296}
297
298pub struct NewIndex {
301 pub append: Vec<u8>,
303 pub patches: Vec<(u64, Vec<u8>)>,
306 pub new_last: bool,
310}
311
312fn scan(solid: &dyn SolidStream, from: Option<&Resume>) -> Result<(Vec<Item>, Profile)> {
318 let from_byte = from.map_or(0, |r| r.bit / 8);
319 let mut w = solid.walk(from)?;
320 let mut items = Vec::new();
321 let mut p = Profile::default();
322 let (mut out, mut last, mut size) = (0u64, 0u64, 0u64);
323 loop {
324 match w.next(usize::MAX)? {
325 Event::Entry { item, .. } => {
326 if item.kind == Kind::File {
327 size = item.size;
328 }
329 items.push(item);
330 }
331 Event::Data(d) => out += d.len() as u64,
332 Event::FileEnd => out += size.next_multiple_of(4096) - size,
333 Event::Point => {
334 let consumed = w
335 .point_byte()
336 .unwrap_or(from_byte)
337 .saturating_sub(from_byte);
338 p.lead = p.lead.max(out as i128 - consumed as i128);
339 p.gap = p.gap.max(out - last);
340 last = out;
341 }
342 Event::End => break,
343 }
344 }
345 p.gap = p.gap.max(out - last);
346 p.files = out;
347 tar::size_links(&mut items);
348 p.links = items
349 .iter()
350 .filter(|i| i.kind != Kind::File)
351 .fold(0u64, |sum, i| {
352 let size = i.size.checked_next_multiple_of(4096).unwrap_or(u64::MAX);
353 sum.saturating_add(size)
354 });
355 Ok((items, p))
356}
357
358pub fn rebuild_index(
362 format: &str,
363 storage: &Storage,
364 tail: Arc<Tail>,
365 keep: u64,
366 hard_links: &[(&Path, &Path)],
367) -> Result<NewIndex> {
368 if format == zip::SPLIT {
369 let (append, new_last) = zip::rebuild_split_index(storage.parts(), &tail, keep)?;
370 return Ok(NewIndex {
371 append,
372 patches: Vec::new(),
373 new_last,
374 });
375 }
376 let (append, patches) = match format {
377 "zip" => (zip::rebuild_index(&tail, keep)?, Vec::new()),
378 "tar" => (tar::closing(hard_links)?, Vec::new()),
379 "7z" => {
380 let (header, start) = sevenz::rebuild_header(storage, tail, keep)?;
381 (header, vec![(0, start)])
382 }
383 #[cfg(feature = "rar")]
385 RAR => (rar::closing(storage, keep)?, Vec::new()),
386 #[cfg(not(feature = "rar"))]
387 RAR => return Err(no_rar()),
388 other => bail!("unknown archive format '{other}' in the journal"),
389 };
390 Ok(NewIndex {
391 append,
392 patches,
393 new_last: false,
394 })
395}
396
397fn sniff(storage: &Storage) -> Result<&'static str> {
398 if storage.parts().len() > 1 && storage::is_split_zip(storage.primary()) {
402 return Ok(zip::SPLIT);
403 }
404 let mut head = [0u8; 512];
405 let mut r = storage.reader(None);
406 let n = read_up_to(&mut r, &mut head)?;
407 let head = &head[..n];
408 let starts = |magic: &[u8]| head.starts_with(magic);
409 if starts(b"7z\xBC\xAF\x27\x1C") {
410 return Ok("7z");
411 }
412 let is_tar = |head: &[u8]| head.len() >= 263 && &head[257..262] == b"ustar";
413 if is_tar(head) {
414 return Ok("tar");
415 }
416 let ext = storage.primary().to_string_lossy().to_ascii_lowercase();
417 if starts(b"\x1F\x8B") {
418 let named = [".tar.gz", ".tgz", ".taz"]
420 .iter()
421 .any(|e| ext.ends_with(e) || ext.contains(&format!("{e}.")));
422 if gzip_holds_tar(storage)? || named {
423 return Ok(targz::NAME);
424 }
425 bail!(
426 "this is a gzip-compressed file that does not contain a tar archive. Only \
427 compressed tar archives (.tar.gz) can be extracted"
428 );
429 }
430 if starts(b"\xFD7zXZ\x00") {
431 return Ok(tarxz::NAME);
434 }
435 if starts(b"BZh") {
436 let first = (|| -> Result<_> {
437 let mut bz = tarbz2::Bzip2::new(
438 storage.reader(None),
439 storage.original_len(),
440 &tarbz2::BzPoint::start(),
441 )?;
442 let mut first = [0; 512];
443 let mut n = 0;
444 while n < first.len() {
445 let k = bz.read(&mut first[n..])?;
446 if k == 0 {
447 break;
448 }
449 n += k;
450 }
451 Ok((first, n))
452 })()
453 .map_err(|e| {
455 if e.downcast_ref::<std::io::Error>().is_some() {
456 e
457 } else {
458 anyhow::Error::new(Damaged(e))
459 }
460 })
461 .context(
462 "checking the bzip2 archive (nothing was changed); if it is damaged, download it again",
463 )?;
464 let named = named_bzip2(
467 &storage
468 .primary()
469 .file_name()
470 .unwrap_or_default()
471 .to_string_lossy(),
472 );
473 if is_tar(&first.0[..first.1]) || named {
474 return Ok(tarbz2::NAME);
475 }
476 bail!(
477 "this is a bzip2-compressed file that does not contain a tar archive; the file was not changed. Decompress it with bzip2, or use a .tar.bz2 archive"
478 );
479 }
480 let zstd_magic = head.len() >= 4 && {
481 let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
482 magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
483 };
484 if zstd_magic {
485 if named_zstd(&ext) || tarzst::holds_tar(storage)? {
489 return Ok(tarzst::NAME);
490 }
491 bail!(
492 "this is a zstd-compressed file that does not contain a tar archive. Only \
493 compressed tar archives (.tar.zst) can be extracted"
494 );
495 }
496 if starts(b"Rar!\x1A\x07") {
497 return Ok(RAR);
498 }
499 if ext.ends_with(".tar") || ext.contains(".tar.") {
500 return Ok("tar");
501 }
502 Ok("zip")
505}
506
507fn named_bzip2(name: &str) -> bool {
510 let name = name.to_ascii_lowercase();
511 let base = match name.rsplit_once('.') {
512 Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
513 _ => &name,
514 };
515 [".tar.bz2", ".tbz2", ".tbz"]
516 .iter()
517 .any(|e| base.ends_with(e))
518}
519
520fn named_zstd(name: &str) -> bool {
523 let name = name.to_ascii_lowercase();
524 let base = match name.rsplit_once('.') {
525 Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
526 _ => &name,
527 };
528 [".tar.zst", ".tzst"].iter().any(|e| base.ends_with(e))
529}
530
531fn gzip_holds_tar(storage: &Storage) -> Result<bool> {
533 let mut gz = resumable::Gzip::new(
534 storage.reader(None),
535 storage.original_len(),
536 &resumable::GzPoint::start(),
537 )?;
538 let mut first = [0u8; 512];
539 let mut n = 0;
540 while n < first.len() {
541 match gz
542 .read(&mut first[n..])
543 .context("reading the start of the compressed stream")?
544 {
545 0 => break,
546 k => n += k,
547 }
548 }
549 Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
550}
551
552fn bzip2_holds_tar(storage: &Storage) -> Result<bool> {
554 let mut bz = tarbz2::Bzip2::new(
555 storage.reader(None),
556 storage.original_len(),
557 &tarbz2::BzPoint::start(),
558 )?;
559 let mut first = [0u8; 512];
560 let mut n = 0;
561 while n < first.len() {
562 match bz.read(&mut first[n..])? {
563 0 => break,
564 k => n += k,
565 }
566 }
567 Ok(first[..n].len() >= 263 && &first[257..262] == b"ustar")
568}
569
570fn zip_has_an_index(path: &Path) -> bool {
573 const MAX: u64 = 22 + 0xFFFF;
574 let Ok(mut file) = fs::File::open(path) else {
575 return false;
576 };
577 let Ok(len) = file.metadata().map(|m| m.len()) else {
578 return false;
579 };
580 if len < 22 {
581 return false;
582 }
583 let start = len.saturating_sub(MAX);
584 if file.seek(SeekFrom::Start(start)).is_err() {
585 return false;
586 }
587 let mut tail = Vec::with_capacity((len - start) as usize);
588 if file.take(len - start).read_to_end(&mut tail).is_err() {
589 return false;
590 }
591 let has = |magic: &[u8]| tail.windows(magic.len()).any(|w| w == magic);
592 has(b"PK\x05\x06") || has(b"PK\x06\x06")
593}
594
595pub fn detect(path: &Path) -> Option<&'static str> {
598 let meta = fs::symlink_metadata(path).ok()?;
599 if !meta.is_file() {
600 return None;
601 }
602 let mut head = [0u8; 512];
603 let n = read_up_to(&mut fs::File::open(path).ok()?, &mut head).ok()?;
604 let head = &head[..n];
605 let starts = |magic: &[u8]| head.starts_with(magic);
606 if starts(b"7z\xBC\xAF\x27\x1C") {
607 return Some("7z");
608 }
609 if head.len() >= 263 && &head[257..262] == b"ustar" {
610 return Some("tar");
611 }
612 if starts(b"\xFD7zXZ\x00") {
613 let storage = Arc::new(Storage::open(path, false).ok()?);
614 return tarxz::holds_tar(&storage).then_some(tarxz::NAME);
615 }
616 if starts(b"Rar!\x1A\x07") {
617 return cfg!(feature = "rar").then_some(RAR);
618 }
619 if starts(b"\x1F\x8B") {
620 let storage = Storage::open(path, false).ok()?;
621 return gzip_holds_tar(&storage).ok()?.then_some(targz::NAME);
622 }
623 if starts(b"BZh") {
624 let storage = Storage::open(path, false).ok()?;
625 return bzip2_holds_tar(&storage).ok()?.then_some(tarbz2::NAME);
626 }
627 let zstd = head.len() >= 4 && {
628 let magic = u32::from_le_bytes([head[0], head[1], head[2], head[3]]);
629 magic == 0xFD2F_B528 || (magic & 0xFFFF_FFF0) == 0x184D_2A50
630 };
631 if zstd {
632 let storage = Arc::new(Storage::open(path, false).ok()?);
633 return tarzst::holds_tar(&storage).ok()?.then_some(tarzst::NAME);
634 }
635 if starts(b"PK\x03\x04") || starts(b"PK\x05\x06") {
636 return zip_has_an_index(path).then_some("zip");
637 }
638 None
639}
640
641pub fn nested_kind(path: &Path) -> Option<&'static str> {
649 if storage::is_split_zip(path) {
650 return starts_like_split_zip(path).then_some(SPLIT_ZIP);
651 }
652 let name = path.file_name()?.to_string_lossy().to_ascii_lowercase();
653 let expected = if name.ends_with(".zip") {
654 "zip"
655 } else if name.ends_with(".7z") {
656 "7z"
657 } else if name.ends_with(".tar") {
658 "tar"
659 } else if [".tar.gz", ".tgz", ".taz"]
660 .iter()
661 .any(|e| name.ends_with(e))
662 {
663 targz::NAME
664 } else if [".tar.xz", ".txz"].iter().any(|e| name.ends_with(e)) {
665 tarxz::NAME
666 } else if [".tar.zst", ".tzst"].iter().any(|e| name.ends_with(e)) {
667 tarzst::NAME
668 } else if [".tar.bz2", ".tbz2", ".tbz"]
669 .iter()
670 .any(|e| name.ends_with(e))
671 {
672 tarbz2::NAME
673 } else if name.ends_with(".rar") {
674 RAR
675 } else {
676 return None;
677 };
678 (detect(path)? == expected).then_some(expected)
679}
680
681fn starts_like_split_zip(path: &Path) -> bool {
686 if !fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) {
687 return false;
688 }
689 let mut head = [0u8; 8];
690 let Ok(n) = fs::File::open(path).and_then(|mut f| read_up_to(&mut f, &mut head)) else {
691 return false;
692 };
693 let head = &head[..n];
694 let local: &[u8] = b"PK\x03\x04";
695 head.starts_with(local)
696 || ((head.starts_with(b"PK\x07\x08") || head.starts_with(b"PK00")) && &head[4..] == local)
697}
698
699fn read_up_to(r: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
700 let mut n = 0;
701 while n < buf.len() {
702 match r.read(&mut buf[n..])? {
703 0 => break,
704 k => n += k,
705 }
706 }
707 Ok(n)
708}
709
710pub fn safe_path(name: &str) -> Option<PathBuf> {
714 if name.contains('\0') {
715 return None;
716 }
717 let mut out = PathBuf::new();
718 for part in name.split(['/', '\\']) {
719 match part {
720 "" | "." => {}
721 ".." => return None,
722 p if out.as_os_str().is_empty()
726 && p.len() == 2
727 && p.as_bytes()[0].is_ascii_alphabetic()
728 && p.ends_with(':') =>
729 {
730 return None;
731 }
732 p => out.push(p),
733 }
734 }
735 let clean = out.components().all(|c| matches!(c, Component::Normal(_)));
736 (clean && !out.as_os_str().is_empty()).then_some(out)
737}
738
739fn unix_mode_from_attributes(attrs: u32) -> Option<u32> {
742 (attrs & 0x8000 != 0).then_some(attrs >> 16)
743}
744
745const S_IFMT: u32 = 0o170000;
746const S_IFLNK: u32 = 0o120000;
747
748fn is_symlink_mode(mode: Option<u32>) -> bool {
749 mode.is_some_and(|m| m & S_IFMT == S_IFLNK)
750}
751
752#[cfg(test)]
753mod named_tests {
754 use super::named_bzip2;
755
756 #[test]
757 fn only_the_file_name_and_a_split_number_select_bzip2() {
758 for yes in ["a.tar.bz2", "A.TBZ2", "a.tbz", "a.tar.bz2.001", "a.tbz2.12"] {
759 assert!(named_bzip2(yes), "{yes}");
760 }
761 for no in [
762 "a.zip",
763 "a.tar.bz2.old",
764 "a.tar.bz2.",
765 "a.bz2",
766 "a.tar.gz.001",
767 ] {
768 assert!(!named_bzip2(no), "{no}");
769 }
770 }
771}