1use std::path::Path;
4use std::str::FromStr;
5
6use crate::ArchiveError;
7use crate::ConfigProblem;
8use crate::ConfigSetting;
9use crate::Result;
10use crate::closed_enum::ClosedEnum;
11use crate::closed_enum::closed_enum;
12use crate::formats::compression::CompressionCodec;
13use crate::formats::sevenz::SEVENZ_MAGIC;
14
15const MAGIC_READ_LEN: usize = 512;
19
20const TAR_BLOCK_LEN: usize = 512;
21const USTAR_MAGIC_OFFSET: usize = 257;
22const TAR_CKSUM_FIELD: std::ops::Range<usize> = 148..156;
23
24const MAGIC_SIGNATURES: &[(usize, &[u8], ArchiveType)] = &[
31 (0, b"\x1f\x8b", ArchiveType::TarGz),
32 (0, b"\x28\xb5\x2f\xfd", ArchiveType::TarZst),
33 (0, b"\x42\x5a\x68", ArchiveType::TarBz2),
34 (0, b"\x50\x4b\x03\x04", ArchiveType::Zip),
35 (0, b"\x50\x4b\x05\x06", ArchiveType::Zip),
36 (0, b"\x50\x4b\x07\x08", ArchiveType::Zip),
37 (0, &SEVENZ_MAGIC, ArchiveType::SevenZ),
38 (0, b"\xfd\x37\x7a\x58\x5a\x00", ArchiveType::TarXz),
39 (257, b"ustar", ArchiveType::Tar),
40];
41
42pub const ZIP_FAMILY_ALIASES: &[&str] = &[
49 "jar", "war", "ear", "nar", "nbm", "apk", "aab", "ipa", "appx", "msix", "whl", "vsix", "xpi",
50 "epub",
51];
52
53pub(crate) fn is_zip_family_alias(ext: &str) -> bool {
58 ZIP_FAMILY_ALIASES
59 .iter()
60 .any(|alias| ext.eq_ignore_ascii_case(alias))
61}
62
63closed_enum! {
64 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
69 #[non_exhaustive]
70 pub enum ArchiveType {
71 Tar => "Tar",
73 TarGz => "TarGz",
75 TarBz2 => "TarBz2",
77 TarXz => "TarXz",
79 TarZst => "TarZst",
81 Zip => "Zip",
83 SevenZ => "SevenZ",
85 }
86}
87
88closed_enum! {
89 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
108 #[non_exhaustive]
109 pub enum CreatableFormat {
110 Tar => "Tar",
112 TarGz => "TarGz",
114 TarBz2 => "TarBz2",
116 TarXz => "TarXz",
118 TarZst => "TarZst",
120 Zip => "Zip",
122 }
123}
124
125closed_enum! {
126 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
139 #[non_exhaustive]
140 pub enum ExtractOnlyFormat {
141 SevenZ => "SevenZ",
143 }
144}
145
146impl ExtractOnlyFormat {
147 #[must_use]
149 pub const fn extension(self) -> &'static str {
150 match self {
151 Self::SevenZ => "7z",
152 }
153 }
154
155 fn not_creatable(self) -> ArchiveError {
156 ArchiveError::InvalidConfiguration {
157 setting: ConfigSetting::CreationFormat,
158 problem: ConfigProblem::NotCreatable { format: self },
159 }
160 }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub(crate) enum CreationFamily {
167 Tar(Option<CompressionCodec>),
168 Zip,
169}
170
171impl CreatableFormat {
172 pub(crate) const fn tar_with(codec: Option<CompressionCodec>) -> Self {
174 match codec {
175 None => Self::Tar,
176 Some(CompressionCodec::Gzip) => Self::TarGz,
177 Some(CompressionCodec::Bzip2) => Self::TarBz2,
178 Some(CompressionCodec::Xz) => Self::TarXz,
179 Some(CompressionCodec::Zstd) => Self::TarZst,
180 }
181 }
182
183 pub(crate) const fn family(self) -> CreationFamily {
185 match self {
186 Self::Tar => CreationFamily::Tar(None),
187 Self::TarGz => CreationFamily::Tar(Some(CompressionCodec::Gzip)),
188 Self::TarBz2 => CreationFamily::Tar(Some(CompressionCodec::Bzip2)),
189 Self::TarXz => CreationFamily::Tar(Some(CompressionCodec::Xz)),
190 Self::TarZst => CreationFamily::Tar(Some(CompressionCodec::Zstd)),
191 Self::Zip => CreationFamily::Zip,
192 }
193 }
194}
195
196impl From<CreatableFormat> for ArchiveType {
197 fn from(format: CreatableFormat) -> Self {
198 match format {
199 CreatableFormat::Tar => Self::Tar,
200 CreatableFormat::TarGz => Self::TarGz,
201 CreatableFormat::TarBz2 => Self::TarBz2,
202 CreatableFormat::TarXz => Self::TarXz,
203 CreatableFormat::TarZst => Self::TarZst,
204 CreatableFormat::Zip => Self::Zip,
205 }
206 }
207}
208
209impl TryFrom<ArchiveType> for CreatableFormat {
210 type Error = ArchiveError;
211
212 fn try_from(format: ArchiveType) -> Result<Self> {
217 match format {
218 ArchiveType::Tar => Ok(Self::Tar),
219 ArchiveType::TarGz => Ok(Self::TarGz),
220 ArchiveType::TarBz2 => Ok(Self::TarBz2),
221 ArchiveType::TarXz => Ok(Self::TarXz),
222 ArchiveType::TarZst => Ok(Self::TarZst),
223 ArchiveType::Zip => Ok(Self::Zip),
224 ArchiveType::SevenZ => Err(ExtractOnlyFormat::SevenZ.not_creatable()),
225 }
226 }
227}
228
229impl FromStr for CreatableFormat {
230 type Err = ArchiveError;
231
232 fn from_str(value: &str) -> Result<Self> {
258 if let Some(format) = ExtractOnlyFormat::ALL
259 .iter()
260 .find(|format| format.as_str() == value)
261 {
262 return Err(format.not_creatable());
263 }
264 <Self as ClosedEnum>::parse_for(ConfigSetting::CreationFormat, value)
265 }
266}
267
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub(crate) enum FormatFamily {
272 Tar(Option<CompressionCodec>),
273 Seekable(crate::SeekableFormat),
274}
275
276impl ArchiveType {
277 pub(crate) const fn tar_with(codec: Option<CompressionCodec>) -> Self {
279 match codec {
280 None => Self::Tar,
281 Some(CompressionCodec::Gzip) => Self::TarGz,
282 Some(CompressionCodec::Bzip2) => Self::TarBz2,
283 Some(CompressionCodec::Xz) => Self::TarXz,
284 Some(CompressionCodec::Zstd) => Self::TarZst,
285 }
286 }
287
288 #[must_use]
301 pub const fn extension(self) -> &'static str {
302 match self {
303 Self::Tar => "tar",
304 Self::TarGz => "tar.gz",
305 Self::TarBz2 => "tar.bz2",
306 Self::TarXz => "tar.xz",
307 Self::TarZst => "tar.zst",
308 Self::Zip => "zip",
309 Self::SevenZ => "7z",
310 }
311 }
312
313 #[must_use]
324 pub const fn is_tar(self) -> bool {
325 match self.family() {
326 FormatFamily::Tar(_) => true,
327 FormatFamily::Seekable(_) => false,
328 }
329 }
330
331 pub(crate) const fn family(self) -> FormatFamily {
333 match self {
334 Self::Tar => FormatFamily::Tar(None),
335 Self::TarGz => FormatFamily::Tar(Some(CompressionCodec::Gzip)),
336 Self::TarBz2 => FormatFamily::Tar(Some(CompressionCodec::Bzip2)),
337 Self::TarXz => FormatFamily::Tar(Some(CompressionCodec::Xz)),
338 Self::TarZst => FormatFamily::Tar(Some(CompressionCodec::Zstd)),
339 Self::Zip => FormatFamily::Seekable(crate::SeekableFormat::Zip),
340 Self::SevenZ => FormatFamily::Seekable(crate::SeekableFormat::SevenZ),
341 }
342 }
343}
344
345pub fn detect_format(path: &Path) -> Result<ArchiveType> {
391 let ext_result = detect_format_from_extension(path);
392
393 match ext_result {
394 Ok(ext_type) => {
395 if let Some(magic_type) = detect_format_from_magic(path)
398 && magic_type != ext_type
399 {
400 return Ok(magic_type);
401 }
402 Ok(ext_type)
403 }
404 Err(_) => {
405 detect_format_from_magic(path).ok_or_else(|| ArchiveError::UnknownFormat {
407 path: path.to_path_buf(),
408 })
409 }
410 }
411}
412
413pub(crate) fn detect_format_from_extension(path: &Path) -> Result<ArchiveType> {
419 let extension =
420 path.extension()
421 .and_then(|e| e.to_str())
422 .ok_or_else(|| ArchiveError::UnknownFormat {
423 path: path.to_path_buf(),
424 })?;
425
426 let ext_lower = extension.to_ascii_lowercase();
427 match ext_lower.as_str() {
428 "tar" => Ok(ArchiveType::Tar),
429 "tgz" => Ok(ArchiveType::TarGz),
430 "gz" => {
431 if let Some(stem) = path.file_stem()
432 && stem
433 .as_encoded_bytes()
434 .last_chunk::<4>()
435 .is_some_and(|tail| tail.eq_ignore_ascii_case(b".tar"))
436 {
437 Ok(ArchiveType::TarGz)
438 } else {
439 Err(ArchiveError::UnknownFormat {
440 path: path.to_path_buf(),
441 })
442 }
443 }
444 "bz2" | "tbz" | "tbz2" => Ok(ArchiveType::TarBz2),
445 "xz" | "txz" => Ok(ArchiveType::TarXz),
446 "zst" | "tzst" => Ok(ArchiveType::TarZst),
447 "zip" => Ok(ArchiveType::Zip),
448 "7z" => Ok(ArchiveType::SevenZ),
449 ext if is_zip_family_alias(ext) => Ok(ArchiveType::Zip),
453 _ => Err(ArchiveError::UnknownFormat {
454 path: path.to_path_buf(),
455 }),
456 }
457}
458
459fn detect_format_from_magic(path: &Path) -> Option<ArchiveType> {
467 let mut file = std::fs::File::open(path).ok()?;
468 let header = peek_header(&mut file).ok()?;
469 match_signature(header.as_slice())
470}
471
472pub(crate) struct Header {
474 buf: [u8; MAGIC_READ_LEN],
475 filled: usize,
476}
477
478impl Header {
479 pub(crate) fn as_slice(&self) -> &[u8] {
481 &self.buf[..self.filled]
482 }
483}
484
485pub(crate) fn peek_header<R: std::io::Read + ?Sized>(reader: &mut R) -> std::io::Result<Header> {
492 let mut header = Header {
493 buf: [0; MAGIC_READ_LEN],
494 filled: 0,
495 };
496 while header.filled < MAGIC_READ_LEN {
497 match reader.read(&mut header.buf[header.filled..]) {
498 Ok(0) => break,
499 Ok(n) => header.filled += n,
500 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
501 Err(e) => return Err(e),
502 }
503 }
504 Ok(header)
505}
506
507fn is_ustar_header(header: &[u8]) -> bool {
511 let Some(block) = header.first_chunk::<TAR_BLOCK_LEN>() else {
512 return false;
513 };
514 if !block[USTAR_MAGIC_OFFSET..].starts_with(b"ustar") {
515 return false;
516 }
517 let sum: u32 = block
518 .iter()
519 .enumerate()
520 .map(|(i, &b)| {
521 if TAR_CKSUM_FIELD.contains(&i) {
522 u32::from(b' ')
523 } else {
524 u32::from(b)
525 }
526 })
527 .sum();
528 tar::Header::from_byte_slice(block)
529 .cksum()
530 .is_ok_and(|stored| stored == sum)
531}
532
533fn is_bzip2_stream_start(header: &[u8]) -> bool {
536 const BLOCK_MAGIC: &[u8; 6] = b"1AY&SY";
537 const END_MAGIC: &[u8; 6] = &[0x17, 0x72, 0x45, 0x38, 0x50, 0x90];
538 header.starts_with(b"BZh")
539 && header
540 .get(3)
541 .is_some_and(|level| (b'1'..=b'9').contains(level))
542 && header
543 .get(4..10)
544 .is_some_and(|marker| marker == BLOCK_MAGIC || marker == END_MAGIC)
545}
546
547pub(crate) fn match_signature(header: &[u8]) -> Option<ArchiveType> {
557 let table_match = MAGIC_SIGNATURES
558 .iter()
559 .find(|&&(offset, sig, _)| {
560 offset
561 .checked_add(sig.len())
562 .and_then(|end| header.get(offset..end))
563 .is_some_and(|window| window == sig)
564 })
565 .map(|&(_, _, archive_type)| archive_type);
566 match table_match {
567 Some(ArchiveType::TarBz2) if !is_bzip2_stream_start(header) && is_ustar_header(header) => {
568 Some(ArchiveType::Tar)
569 }
570 _ => table_match,
571 }
572}
573
574#[cfg(test)]
575#[allow(clippy::unwrap_used)]
576mod tests {
577 use super::*;
578 use std::assert_matches;
579 use std::path::PathBuf;
580
581 #[test]
582 fn a_creatable_format_parses_from_its_name() {
583 for &format in CreatableFormat::ALL {
584 assert_eq!(format.as_str().parse::<CreatableFormat>().unwrap(), format);
585 }
586 }
587
588 #[test]
589 fn an_unknown_creation_format_lists_the_creatable_formats_only() {
590 for text in ["zip", "ZIP", "tar.gz", "bogus", "", "7z"] {
591 let err = text.parse::<CreatableFormat>().unwrap_err();
592 assert_eq!(
593 err.to_string(),
594 "invalid configuration: creation format is not one of the allowed values: \
595 Tar, TarGz, TarBz2, TarXz, TarZst, Zip",
596 "{text:?}"
597 );
598 }
599 }
600
601 #[test]
602 fn an_extract_only_format_is_not_creatable() {
603 let from_name = "SevenZ".parse::<CreatableFormat>().unwrap_err();
604 let from_type = CreatableFormat::try_from(ArchiveType::SevenZ).unwrap_err();
605 for err in [from_name, from_type] {
606 assert_matches!(
607 err,
608 ArchiveError::InvalidConfiguration {
609 setting: ConfigSetting::CreationFormat,
610 problem: ConfigProblem::NotCreatable {
611 format: ExtractOnlyFormat::SevenZ
612 },
613 }
614 );
615 }
616 }
617
618 #[test]
619 fn creatable_and_extract_only_formats_partition_the_archive_types() {
620 let mut names: Vec<&str> = CreatableFormat::NAMES
621 .iter()
622 .chain(ExtractOnlyFormat::NAMES)
623 .copied()
624 .collect();
625 names.sort_unstable();
626 let mut all: Vec<&str> = ArchiveType::NAMES.to_vec();
627 all.sort_unstable();
628 assert_eq!(names, all);
629 }
630
631 #[test]
632 fn test_archive_type_as_str_matches_display_and_is_unique() {
633 let names: Vec<&str> = ArchiveType::ALL.iter().map(|t| t.as_str()).collect();
634 assert_eq!(
635 names,
636 ["Tar", "TarGz", "TarBz2", "TarXz", "TarZst", "Zip", "SevenZ"]
637 );
638 for t in ArchiveType::ALL {
639 assert_eq!(t.to_string(), t.as_str());
640 }
641 }
642
643 #[test]
644 fn test_archive_type_extension_round_trips_through_detection() {
645 for &t in ArchiveType::ALL {
646 let name = format!("archive.{}", t.extension());
647 assert_eq!(detect_format_from_extension(Path::new(&name)).unwrap(), t);
648 }
649 }
650
651 #[test]
652 fn test_creatable_format_round_trips_through_archive_type() {
653 for &format in CreatableFormat::ALL {
654 let archive_type = ArchiveType::from(format);
655 assert_eq!(CreatableFormat::try_from(archive_type).unwrap(), format);
656 assert_eq!(archive_type.as_str(), format.as_str());
657 }
658 assert_eq!(CreatableFormat::ALL.len(), ArchiveType::ALL.len() - 1);
659 assert_matches!(
660 CreatableFormat::try_from(ArchiveType::SevenZ),
661 Err(ArchiveError::InvalidConfiguration { .. })
662 );
663 }
664
665 #[test]
666 fn test_family_maps_tar_codecs() {
667 assert_eq!(ArchiveType::Tar.family(), FormatFamily::Tar(None));
668 assert_eq!(
669 ArchiveType::TarGz.family(),
670 FormatFamily::Tar(Some(CompressionCodec::Gzip))
671 );
672 assert_eq!(
673 ArchiveType::TarBz2.family(),
674 FormatFamily::Tar(Some(CompressionCodec::Bzip2))
675 );
676 assert_eq!(
677 ArchiveType::TarXz.family(),
678 FormatFamily::Tar(Some(CompressionCodec::Xz))
679 );
680 assert_eq!(
681 ArchiveType::TarZst.family(),
682 FormatFamily::Tar(Some(CompressionCodec::Zstd))
683 );
684 assert_eq!(
685 ArchiveType::Zip.family(),
686 FormatFamily::Seekable(crate::SeekableFormat::Zip)
687 );
688 assert_eq!(
689 ArchiveType::SevenZ.family(),
690 FormatFamily::Seekable(crate::SeekableFormat::SevenZ)
691 );
692 }
693
694 #[test]
695 fn test_detect_tar() {
696 let path = PathBuf::from("archive.tar");
697 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
698 }
699
700 #[test]
701 fn test_detect_tar_gz_still_works() {
702 let path = PathBuf::from("archive.tar.gz");
703 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
704
705 let path2 = PathBuf::from("archive.tgz");
706 assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarGz);
707 }
708
709 #[test]
710 fn test_detect_tar_gz_stem_is_case_insensitive() {
711 for name in ["a.TAR.gz", "a.Tar.GZ", "A.TAR.GZ"] {
712 assert_eq!(
713 detect_format(&PathBuf::from(name)).unwrap(),
714 ArchiveType::TarGz,
715 "{name}"
716 );
717 }
718 }
719
720 #[test]
721 fn test_detect_bare_dot_tar_gz_still_matches() {
722 assert_eq!(
723 detect_format_from_extension(Path::new(".tar.gz")).unwrap(),
724 ArchiveType::TarGz
725 );
726 }
727
728 #[test]
729 fn test_detect_bare_gz_returns_unknown_format() {
730 let path = PathBuf::from("archive.gz");
731 assert_matches!(
732 detect_format(&path),
733 Err(ArchiveError::UnknownFormat { .. })
734 );
735 }
736
737 #[test]
738 fn test_detect_bare_gz_error_carries_path() {
739 let path = PathBuf::from("archive.gz");
740 let err = detect_format(&path).unwrap_err();
741 assert_matches!(
742 err,
743 ArchiveError::UnknownFormat { path: ref p } if p == &PathBuf::from("archive.gz")
744 );
745 }
746
747 #[test]
748 fn test_detect_tar_bz2() {
749 let path = PathBuf::from("archive.tar.bz2");
750 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarBz2);
751
752 let path2 = PathBuf::from("archive.tbz");
753 assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarBz2);
754
755 let path3 = PathBuf::from("archive.tbz2");
756 assert_eq!(detect_format(&path3).unwrap(), ArchiveType::TarBz2);
757 }
758
759 #[test]
760 fn test_detect_tar_xz() {
761 let path = PathBuf::from("archive.tar.xz");
762 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarXz);
763
764 let path2 = PathBuf::from("archive.txz");
765 assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarXz);
766 }
767
768 #[test]
769 fn test_detect_tar_zst() {
770 let path = PathBuf::from("archive.tar.zst");
771 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarZst);
772
773 let path2 = PathBuf::from("archive.tzst");
774 assert_eq!(detect_format(&path2).unwrap(), ArchiveType::TarZst);
775 }
776
777 #[test]
778 fn test_detect_zip() {
779 let path = PathBuf::from("archive.zip");
780 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
781 }
782
783 #[test]
784 fn test_detect_zip_family_extensions() {
785 for ext in ZIP_FAMILY_ALIASES {
790 let path = PathBuf::from(format!("archive.{ext}"));
791 assert_eq!(
792 detect_format(&path).unwrap(),
793 ArchiveType::Zip,
794 "{ext} should detect as ZIP",
795 );
796
797 let upper = PathBuf::from(format!("archive.{}", ext.to_ascii_uppercase()));
798 assert_eq!(
799 detect_format(&upper).unwrap(),
800 ArchiveType::Zip,
801 "{ext} uppercase should detect as ZIP",
802 );
803 }
804 }
805
806 #[test]
807 fn test_detect_7z() {
808 let path = PathBuf::from("archive.7z");
809 assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
810 }
811
812 #[test]
813 fn test_detect_7z_case_insensitive() {
814 let path = PathBuf::from("ARCHIVE.7Z");
815 assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
816
817 let path2 = PathBuf::from("Archive.7Z");
818 assert_eq!(detect_format(&path2).unwrap(), ArchiveType::SevenZ);
819 }
820
821 #[test]
822 fn test_detect_unknown_format() {
823 let path = PathBuf::from("archive.rar");
824 assert_matches!(
825 detect_format(&path),
826 Err(ArchiveError::UnknownFormat { .. })
827 );
828 }
829
830 #[test]
831 fn test_detect_unknown_format_error_carries_path() {
832 let path = PathBuf::from("archive.rar");
833 let err = detect_format(&path).unwrap_err();
834 assert_matches!(
835 err,
836 ArchiveError::UnknownFormat { path: ref p } if p == &PathBuf::from("archive.rar")
837 );
838 }
839
840 #[test]
841 fn test_archive_type_sevenz_equality() {
842 assert_eq!(ArchiveType::SevenZ, ArchiveType::SevenZ);
843 assert_ne!(ArchiveType::SevenZ, ArchiveType::Zip);
844 }
845
846 #[test]
847 fn test_archive_type_sevenz_debug() {
848 let format = ArchiveType::SevenZ;
849 let debug_str = format!("{format:?}");
850 assert_eq!(debug_str, "SevenZ");
851 }
852
853 fn write_magic_file(dir: &tempfile::TempDir, name: &str, header: &[u8]) -> PathBuf {
856 let path = dir.path().join(name);
857 let mut data = vec![0u8; MAGIC_READ_LEN];
859 let n = header.len().min(data.len());
860 data[..n].copy_from_slice(&header[..n]);
861 std::fs::write(&path, &data).unwrap();
862 path
863 }
864
865 fn write_magic_file_at_offset(
866 dir: &tempfile::TempDir,
867 name: &str,
868 offset: usize,
869 sig: &[u8],
870 ) -> PathBuf {
871 let path = dir.path().join(name);
872 let mut data = vec![0u8; MAGIC_READ_LEN];
873 let end = offset + sig.len();
874 if end <= data.len() {
875 data[offset..end].copy_from_slice(sig);
876 }
877 std::fs::write(&path, &data).unwrap();
878 path
879 }
880
881 #[test]
882 fn test_magic_zip_no_extension() {
883 let dir = tempfile::tempdir().unwrap();
884 let path = write_magic_file(&dir, "data", b"\x50\x4b\x03\x04");
885 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
886 }
887
888 #[test]
889 fn test_magic_gzip_no_extension() {
890 let dir = tempfile::tempdir().unwrap();
891 let path = write_magic_file(&dir, "data", b"\x1f\x8b\x00");
892 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
893 }
894
895 #[test]
896 fn test_magic_bz2_no_extension() {
897 let dir = tempfile::tempdir().unwrap();
898 let path = write_magic_file(&dir, "data", b"\x42\x5a\x68");
899 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarBz2);
900 }
901
902 #[test]
903 fn test_magic_xz_no_extension() {
904 let dir = tempfile::tempdir().unwrap();
905 let path = write_magic_file(&dir, "data", b"\xfd\x37\x7a\x58\x5a\x00");
906 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarXz);
907 }
908
909 #[test]
910 fn test_magic_zstd_no_extension() {
911 let dir = tempfile::tempdir().unwrap();
912 let path = write_magic_file(&dir, "data", b"\x28\xb5\x2f\xfd");
913 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarZst);
914 }
915
916 #[test]
917 fn test_magic_sevenz_no_extension() {
918 let dir = tempfile::tempdir().unwrap();
919 let path = write_magic_file(&dir, "data", b"\x37\x7a\xbc\xaf\x27\x1c");
920 assert_eq!(detect_format(&path).unwrap(), ArchiveType::SevenZ);
921 }
922
923 #[test]
924 fn test_magic_tar_ustar_no_extension() {
925 let dir = tempfile::tempdir().unwrap();
926 let path = write_magic_file_at_offset(&dir, "data", 257, b"ustar");
927 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
928 }
929
930 #[test]
931 fn test_magic_wins_over_wrong_extension() {
932 let dir = tempfile::tempdir().unwrap();
934 let path = write_magic_file(&dir, "archive.zip", b"\x1f\x8b\x00");
935 assert_eq!(detect_format(&path).unwrap(), ArchiveType::TarGz);
936 }
937
938 #[test]
939 fn test_extension_wins_when_no_magic_mismatch() {
940 let dir = tempfile::tempdir().unwrap();
943 let path = dir.path().join("archive.zip");
944 std::fs::write(&path, b"\x00\x00\x00\x00").unwrap();
945 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
946 }
947
948 #[test]
949 fn test_nonexistent_file_without_extension_returns_unknown() {
950 let path = PathBuf::from("/nonexistent/path/to/archive");
951 assert_matches!(
952 detect_format(&path),
953 Err(ArchiveError::UnknownFormat { .. })
954 );
955 }
956
957 #[test]
958 fn test_nonexistent_file_with_known_extension_uses_extension() {
959 let path = PathBuf::from("/nonexistent/archive.zip");
962 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
963 }
964
965 #[test]
967 fn test_magic_empty_zip_eocd_no_extension() {
968 let dir = tempfile::tempdir().unwrap();
969 let path = write_magic_file(&dir, "empty", b"\x50\x4b\x05\x06");
970 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
971 }
972
973 #[test]
974 fn test_magic_split_zip_no_extension() {
975 let dir = tempfile::tempdir().unwrap();
976 let path = write_magic_file(&dir, "split", b"\x50\x4b\x07\x08");
977 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Zip);
978 }
979
980 #[test]
985 fn test_magic_tar_ustar_exact_boundary_file() {
986 let dir = tempfile::tempdir().unwrap();
987 let path = dir.path().join("minimal.tar");
988 let mut data = vec![0u8; MAGIC_READ_LEN];
991 data[257..262].copy_from_slice(b"ustar");
992 std::fs::write(&path, &data).unwrap();
993 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
995 }
996
997 #[test]
1002 fn test_magic_tar_ustar_minimal_263_byte_file() {
1003 let dir = tempfile::tempdir().unwrap();
1004 let path = dir.path().join("data");
1005 let mut data = vec![0u8; 263];
1006 data[257..262].copy_from_slice(b"ustar");
1007 std::fs::write(&path, &data).unwrap();
1008 assert_eq!(detect_format(&path).unwrap(), ArchiveType::Tar);
1009 }
1010
1011 #[test]
1012 fn match_signature_prefers_offset_zero_magic_over_ustar() {
1013 let mut header = [0u8; MAGIC_READ_LEN];
1014 header[257..262].copy_from_slice(b"ustar");
1015 assert_eq!(match_signature(&header), Some(ArchiveType::Tar));
1016 header[..4].copy_from_slice(b"PK\x03\x04");
1017 assert_eq!(match_signature(&header), Some(ArchiveType::Zip));
1018 }
1019
1020 fn sealed_block(name: &[u8]) -> [u8; TAR_BLOCK_LEN] {
1021 let mut header = tar::Header::new_ustar();
1022 header.as_old_mut().name[..name.len()].copy_from_slice(name);
1023 header.set_size(0);
1024 header.set_cksum();
1025 *header.as_bytes()
1026 }
1027
1028 #[test]
1029 fn is_ustar_header_accepts_only_a_sealed_block() {
1030 let block = sealed_block(b"a.txt");
1031 assert!(is_ustar_header(&block));
1032
1033 let mut off_by_one = block;
1034 off_by_one[0] ^= 1;
1035 assert!(!is_ustar_header(&off_by_one));
1036
1037 let mut non_numeric = block;
1038 non_numeric[TAR_CKSUM_FIELD].copy_from_slice(b"xxxxxxx\0");
1039 assert!(!is_ustar_header(&non_numeric));
1040
1041 assert!(!is_ustar_header(&block[..TAR_BLOCK_LEN - 1]));
1042 assert!(!is_ustar_header(&[]));
1043
1044 let mut v7 = sealed_block(b"a.txt");
1045 v7[USTAR_MAGIC_OFFSET..USTAR_MAGIC_OFFSET + 5].fill(0);
1046 assert!(!is_ustar_header(&v7));
1047 }
1048
1049 #[test]
1050 fn only_a_bzip2_looking_name_loses_to_a_sealed_ustar_block() {
1051 let cases: [(&[u8], Option<ArchiveType>); 8] = [
1052 (b"BZhfoo.txt", Some(ArchiveType::Tar)),
1053 (b"BZh91AY&SYfoo", Some(ArchiveType::TarBz2)),
1054 (b"\x1f\x8bfoo", Some(ArchiveType::TarGz)),
1055 (b"\x28\xb5\x2f\xfdfoo", Some(ArchiveType::TarZst)),
1056 (b"\xfd7zXZ\0foo", Some(ArchiveType::TarXz)),
1057 (b"PK\x03\x04foo", Some(ArchiveType::Zip)),
1058 (b"7z\xbc\xaf\x27\x1cfoo", Some(ArchiveType::SevenZ)),
1059 (b"plain.txt", Some(ArchiveType::Tar)),
1060 ];
1061 for (name, expected) in cases {
1062 assert_eq!(match_signature(&sealed_block(name)), expected, "{name:?}");
1063 }
1064 }
1065
1066 #[test]
1067 fn a_v7_tar_with_a_gzip_magic_name_stays_gzip() {
1068 let mut block = sealed_block(b"\x1f\x8bfoo");
1069 block[USTAR_MAGIC_OFFSET..USTAR_MAGIC_OFFSET + 5].fill(0);
1070 assert_eq!(match_signature(&block), Some(ArchiveType::TarGz));
1071 }
1072
1073 #[test]
1074 fn match_signature_handles_short_and_empty_headers() {
1075 assert_eq!(match_signature(&[]), None);
1076 assert_eq!(match_signature(b"\x1f"), None);
1077 assert_eq!(match_signature(b"\x1f\x8b"), Some(ArchiveType::TarGz));
1078 assert_eq!(match_signature(&[0; 261]), None);
1079 }
1080}