1#![deny(missing_docs)]
11
12#[cfg(feature = "io")]
13use crate::error::{Error, Result};
14#[cfg(feature = "io")]
15use crate::manifest::Manifest;
16#[cfg(feature = "io")]
17use std::fs;
18#[cfg(feature = "io")]
19use std::io::{Read, Write};
20#[cfg(feature = "io")]
21use std::path::{Component, Path, PathBuf};
22#[cfg(feature = "io")]
23use std::sync::atomic::{AtomicU64, Ordering};
24#[cfg(feature = "io")]
25use tracing::{debug, error, warn};
26
27#[cfg(feature = "io")]
31const EXTRACT_CHUNK_SIZE: usize = 64 * 1024;
32
33#[derive(Debug, Clone, Copy)]
43pub struct ExtractLimits {
44 pub max_entries: u64,
46 pub max_file_bytes: u64,
48 pub max_total_bytes: u64,
50}
51
52impl Default for ExtractLimits {
53 fn default() -> Self {
54 Self {
55 max_entries: 100_000,
56 max_file_bytes: 1 << 30, max_total_bytes: 4 << 30, }
59 }
60}
61
62#[cfg(feature = "io")]
66fn temp_sibling_path(path: &Path) -> PathBuf {
67 static COUNTER: AtomicU64 = AtomicU64::new(0);
68
69 let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
70 let pid = std::process::id();
71 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("entry");
72 let tmp_name = format!(".{name}.{pid}.{seq}.partial");
73
74 match path.parent() {
75 Some(parent) => parent.join(tmp_name),
76 None => PathBuf::from(tmp_name),
77 }
78}
79
80#[cfg(feature = "io")]
93fn write_entry<R: Read>(
94 entry: &mut R,
95 buffer: &mut [u8],
96 tmp_path: &Path,
97 expected_crc32: u32,
98 dest: &Path,
99 limits: &ExtractLimits,
100 total_written: &mut u64,
101) -> Result<()> {
102 let mut outfile = fs::File::create(tmp_path)?;
103 let mut hasher = crc32fast::Hasher::new();
104 let mut file_written: u64 = 0;
105
106 loop {
107 let read = entry.read(&mut buffer[..])?;
108
109 if read == 0 {
110 break;
111 }
112
113 file_written += read as u64;
114 *total_written += read as u64;
115
116 check_extract_size(dest, file_written, *total_written, limits)?;
117
118 hasher.update(&buffer[..read]);
119 outfile.write_all(&buffer[..read])?;
120 }
121
122 let actual_crc32 = hasher.finalize();
123
124 if actual_crc32 != expected_crc32 {
125 error!(
126 "CRC32 verification failed for {}: expected {:08x}, got {:08x}",
127 dest.display(),
128 expected_crc32,
129 actual_crc32
130 );
131
132 return Err(Error::ChecksumMismatch {
133 path: dest.display().to_string(),
134 expected: expected_crc32,
135 actual: actual_crc32,
136 });
137 }
138
139 outfile.flush()?;
140
141 Ok(())
142}
143
144#[cfg(feature = "io")]
153fn check_extract_size(
154 dest: &Path,
155 file_written: u64,
156 total_written: u64,
157 limits: &ExtractLimits,
158) -> Result<()> {
159 if file_written > limits.max_file_bytes {
160 return Err(Error::ExtractLimitExceeded(format!(
161 "entry {} exceeds max file size of {} bytes",
162 dest.display(),
163 limits.max_file_bytes
164 )));
165 }
166
167 if total_written > limits.max_total_bytes {
168 return Err(Error::ExtractLimitExceeded(format!(
169 "archive exceeds max total uncompressed size of {} bytes",
170 limits.max_total_bytes
171 )));
172 }
173
174 Ok(())
175}
176
177#[cfg(feature = "io")]
186fn safe_join(dest_dir: &Path, entry: Option<&Path>) -> Option<PathBuf> {
187 let entry = entry?;
188
189 for component in entry.components() {
190 match component {
191 Component::Normal(_) | Component::CurDir => {}
192 Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
193 }
194 }
195
196 Some(dest_dir.join(entry))
197}
198
199#[cfg(all(unix, feature = "io"))]
216fn entry_permissions(unix_mode: Option<u32>) -> Option<fs::Permissions> {
217 use std::os::unix::fs::PermissionsExt;
218
219 let mode = unix_mode?;
220
221 if mode & 0o111 == 0 {
222 return None;
223 }
224
225 Some(fs::Permissions::from_mode(0o755))
226}
227
228#[cfg(feature = "io")]
233fn apply_entry_mode(path: &Path, unix_mode: Option<u32>) -> Result<()> {
234 #[cfg(unix)]
235 if let Some(permissions) = entry_permissions(unix_mode) {
236 fs::set_permissions(path, permissions)?;
237 }
238
239 #[cfg(not(unix))]
240 let _ = (path, unix_mode);
241
242 Ok(())
243}
244
245#[cfg(feature = "io")]
258pub fn extract_zip(zip_path: &Path, dest_dir: &Path) -> Result<()> {
259 extract_zip_with_limits(zip_path, dest_dir, &ExtractLimits::default())
260}
261
262#[cfg(feature = "io")]
278pub fn extract_zip_with_limits(
279 zip_path: &Path,
280 dest_dir: &Path,
281 limits: &ExtractLimits,
282) -> Result<()> {
283 extract_zip_reporting(zip_path, dest_dir, limits, &mut |_, _| {})
284}
285
286#[cfg(feature = "io")]
289pub(crate) fn extract_zip_reporting(
290 zip_path: &Path,
291 dest_dir: &Path,
292 limits: &ExtractLimits,
293 on_progress: &mut dyn FnMut(u64, u64),
294) -> Result<()> {
295 let file = fs::File::open(zip_path)?;
296 let mut archive = zip::ZipArchive::new(file)?;
297
298 if archive.len() as u64 > limits.max_entries {
299 return Err(Error::ExtractLimitExceeded(format!(
300 "archive has {} entries, exceeding the limit of {}",
301 archive.len(),
302 limits.max_entries
303 )));
304 }
305
306 fs::create_dir_all(dest_dir)?;
307
308 let mut total_written: u64 = 0;
309 let mut buffer = vec![0u8; EXTRACT_CHUNK_SIZE];
310 let entries = archive.len() as u64;
311
312 for i in 0..archive.len() {
313 on_progress(i as u64, entries);
314
315 let mut file_in_archive = archive.by_index(i)?;
316 let enclosed = file_in_archive.enclosed_name();
317 let outpath = match safe_join(dest_dir, enclosed.as_deref()) {
318 Some(path) => path,
319 None => {
320 warn!("Invalid file path in zip: {:?}", file_in_archive.name());
321 continue;
322 }
323 };
324
325 let comment = file_in_archive.comment();
326
327 if !comment.is_empty() {
328 debug!("File {} comment: {:?}", i, comment);
329 }
330
331 if file_in_archive.name().ends_with('/') {
332 debug!("Creating directory {}", outpath.display());
333 fs::create_dir_all(&outpath)?;
334 } else {
335 debug!("Extracting file {} to {}", i, outpath.display());
336
337 if let Some(parent) = outpath.parent()
338 && !parent.exists()
339 {
340 fs::create_dir_all(parent)?;
341 }
342
343 let expected_crc32 = file_in_archive.crc32();
344 let unix_mode = file_in_archive.unix_mode();
347 let tmp_path = temp_sibling_path(&outpath);
348
349 match write_entry(
353 &mut file_in_archive,
354 &mut buffer,
355 &tmp_path,
356 expected_crc32,
357 &outpath,
358 limits,
359 &mut total_written,
360 ) {
361 Ok(()) => {
362 if let Err(err) = apply_entry_mode(&tmp_path, unix_mode) {
368 let _ = fs::remove_file(&tmp_path);
369
370 return Err(err);
371 }
372
373 if let Err(err) = fs::rename(&tmp_path, &outpath) {
376 let _ = fs::remove_file(&tmp_path);
377
378 return Err(err.into());
379 }
380
381 debug!("CRC32 verification successful for {}", outpath.display());
382 }
383 Err(err) => {
384 let _ = fs::remove_file(&tmp_path);
385
386 return Err(err);
387 }
388 }
389 }
390 }
391
392 on_progress(entries, entries);
393
394 Ok(())
395}
396
397#[cfg(all(test, feature = "io"))]
399fn calculate_crc32(data: &[u8]) -> u32 {
400 let mut hasher = crc32fast::Hasher::new();
401 hasher.update(data);
402
403 hasher.finalize()
404}
405
406#[cfg(feature = "io")]
413pub fn should_extract(mod_dir: &Path, version: &str) -> Result<bool> {
414 let manifest_path = mod_dir.join("manifest.json");
415
416 let existing_version = if manifest_path.exists() {
417 match Manifest::from_file(&manifest_path) {
418 Ok(manifest) => Some(manifest.version_number),
419 Err(err) => {
420 warn!(
421 "Failed to parse manifest in {}: {}; re-extracting",
422 mod_dir.display(),
423 err
424 );
425
426 None
427 }
428 }
429 } else {
430 debug!(
431 "No manifest in {}, extracting version {}",
432 mod_dir.display(),
433 version
434 );
435
436 None
437 };
438
439 let reextract = should_reextract(existing_version.as_deref(), version);
440
441 if let Some(existing) = &existing_version {
442 if reextract {
443 debug!(
444 "{} version changed from {} to {}, extracting",
445 mod_dir.display(),
446 existing,
447 version
448 );
449 } else {
450 debug!(
451 "{} already has version {}, skipping",
452 mod_dir.display(),
453 version
454 );
455 }
456 }
457
458 Ok(reextract)
459}
460
461#[cfg(feature = "io")]
469fn should_reextract(existing_version: Option<&str>, requested: &str) -> bool {
470 match existing_version {
471 Some(existing) => existing != requested,
472 None => true,
473 }
474}
475
476pub fn parse_package_filename(file_name: &str) -> Option<(String, String)> {
487 let stem = file_name.strip_suffix(".zip").unwrap_or(file_name);
488 let parts: Vec<&str> = stem.splitn(3, '-').collect();
489
490 if parts.len() < 3 {
491 return None;
492 }
493
494 let full_name = format!("{}-{}", parts[0], parts[1]);
495 let version = parts[2].to_string();
496
497 Some((full_name, version))
498}
499
500#[cfg(all(test, feature = "io"))]
501mod tests {
502 use super::*;
503 use std::fs::File;
504 use std::io::Write;
505 use tempfile::tempdir;
506 use zip::write::{FileOptions, ZipWriter};
507
508 #[test]
509 fn test_calculate_crc32() {
510 let data = b"test data for crc32 calculation";
511 let crc = calculate_crc32(data);
512
513 let expected_crc: u32 = 1707861357;
514
515 assert_eq!(crc, expected_crc);
516 }
517
518 #[test]
519 fn safe_join_rejects_traversal_and_absolute() {
520 let base = Path::new("/dest");
521
522 assert_eq!(safe_join(base, None), None);
523 assert_eq!(safe_join(base, Some(Path::new("../escape"))), None);
524 assert_eq!(safe_join(base, Some(Path::new("a/../../b"))), None);
525 assert_eq!(safe_join(base, Some(Path::new("/etc/passwd"))), None);
526
527 assert_eq!(
528 safe_join(base, Some(Path::new("plugins/mod.dll"))),
529 Some(PathBuf::from("/dest/plugins/mod.dll"))
530 );
531 assert!(safe_join(base, Some(Path::new("./ok.txt"))).is_some());
532 }
533
534 #[test]
537 #[cfg(windows)]
538 fn safe_join_rejects_drive_and_unc_prefixes() {
539 let base = Path::new(r"C:\dest");
540
541 assert_eq!(
542 safe_join(base, Some(Path::new(r"C:\Windows\evil.dll"))),
543 None
544 );
545 assert_eq!(safe_join(base, Some(Path::new("C:evil.dll"))), None);
546 assert_eq!(
547 safe_join(base, Some(Path::new(r"\\server\share\evil.dll"))),
548 None
549 );
550 }
551
552 #[test]
553 fn should_reextract_truth_table() {
554 assert!(should_reextract(None, "1.0.0"));
556 assert!(!should_reextract(Some("1.0.0"), "1.0.0"));
558 assert!(should_reextract(Some("1.0.0"), "1.0.1"));
560 }
561
562 #[test]
563 fn check_extract_size_enforces_both_caps() {
564 let limits = ExtractLimits {
565 max_entries: 1,
566 max_file_bytes: 10,
567 max_total_bytes: 20,
568 };
569
570 assert!(check_extract_size(Path::new("f"), 10, 20, &limits).is_ok());
572
573 assert!(matches!(
575 check_extract_size(Path::new("f"), 11, 11, &limits).unwrap_err(),
576 Error::ExtractLimitExceeded(_)
577 ));
578
579 assert!(matches!(
581 check_extract_size(Path::new("f"), 5, 21, &limits).unwrap_err(),
582 Error::ExtractLimitExceeded(_)
583 ));
584 }
585
586 #[test]
587 fn temp_sibling_path_is_unique_and_sibling() {
588 let base = Path::new("/tmp/x/file.dll");
589
590 let a = temp_sibling_path(base);
591 let b = temp_sibling_path(base);
592
593 assert_ne!(a, b);
594 assert_eq!(a.parent(), Some(Path::new("/tmp/x")));
595 }
596
597 #[test]
598 fn write_entry_streams_verifies_crc_and_enforces_cap() {
599 let dir = tempdir().unwrap();
600 let data = b"hello world, this is a streamed entry";
601 let crc = calculate_crc32(data);
602 let limits = ExtractLimits::default();
603
604 let tmp = dir.path().join("ok.partial");
607 let mut reader = std::io::Cursor::new(data.to_vec());
608 let mut buffer = vec![0u8; 4];
609 let mut total = 0u64;
610
611 write_entry(
612 &mut reader,
613 &mut buffer,
614 &tmp,
615 crc,
616 Path::new("ok"),
617 &limits,
618 &mut total,
619 )
620 .unwrap();
621
622 assert_eq!(std::fs::read(&tmp).unwrap(), data);
623 assert_eq!(total, data.len() as u64);
624
625 let tmp2 = dir.path().join("bad.partial");
627 let mut reader = std::io::Cursor::new(data.to_vec());
628 let mut buffer = vec![0u8; 64];
629 let mut total = 0u64;
630
631 let err = write_entry(
632 &mut reader,
633 &mut buffer,
634 &tmp2,
635 0xDEAD_BEEF,
636 Path::new("bad"),
637 &limits,
638 &mut total,
639 )
640 .unwrap_err();
641
642 assert!(matches!(err, Error::ChecksumMismatch { .. }));
643
644 let tmp3 = dir.path().join("big.partial");
646 let tight = ExtractLimits {
647 max_file_bytes: 4,
648 ..ExtractLimits::default()
649 };
650 let mut reader = std::io::Cursor::new(vec![0u8; 10]);
651 let mut buffer = vec![0u8; 64];
652 let mut total = 0u64;
653
654 let err = write_entry(
655 &mut reader,
656 &mut buffer,
657 &tmp3,
658 0,
659 Path::new("big"),
660 &tight,
661 &mut total,
662 )
663 .unwrap_err();
664
665 assert!(matches!(err, Error::ExtractLimitExceeded(_)));
666 }
667
668 #[test]
669 fn test_parse_package_filename() {
670 assert_eq!(
671 parse_package_filename("Owner-ModName-1.0.0.zip"),
672 Some(("Owner-ModName".to_string(), "1.0.0".to_string()))
673 );
674
675 assert_eq!(parse_package_filename("InvalidFile.zip"), None);
676 }
677
678 #[test]
679 fn test_parse_package_filename_preserves_hyphenated_version() {
680 assert_eq!(
681 parse_package_filename("Owner-ModName-1.0.0-beta.1.zip"),
682 Some(("Owner-ModName".to_string(), "1.0.0-beta.1".to_string()))
683 );
684 }
685
686 #[test]
687 fn test_extract_zip_with_valid_paths() {
688 let temp_dir = tempdir().unwrap();
689 let output_dir = temp_dir.path().join("output");
690 fs::create_dir_all(&output_dir).unwrap();
691
692 let zip_path = temp_dir.path().join("test_invalid_paths.zip");
693 let file = File::create(&zip_path).unwrap();
694 let mut zip = ZipWriter::new(file);
695
696 let options: FileOptions<'_, ()> =
697 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
698
699 zip.start_file("valid_file.txt", options).unwrap();
700 zip.write_all(b"Valid file content").unwrap();
701
702 zip.finish().unwrap();
703
704 let result = extract_zip(&zip_path, &output_dir);
705
706 assert!(result.is_ok());
707
708 let valid_file = output_dir.join("valid_file.txt");
709 assert!(valid_file.exists());
710 }
711
712 #[test]
718 #[cfg(unix)]
719 fn test_extract_zip_preserves_the_executable_bit() {
720 use std::os::unix::fs::PermissionsExt;
721
722 let temp_dir = tempdir().unwrap();
723 let output_dir = temp_dir.path().join("output");
724
725 let zip_path = temp_dir.path().join("test_modes.zip");
726 let file = File::create(&zip_path).unwrap();
727 let mut zip = ZipWriter::new(file);
728
729 let executable: FileOptions<'_, ()> = FileOptions::default()
730 .compression_method(zip::CompressionMethod::Stored)
731 .unix_permissions(0o755);
732 let plain: FileOptions<'_, ()> = FileOptions::default()
733 .compression_method(zip::CompressionMethod::Stored)
734 .unix_permissions(0o644);
735
736 zip.start_file("start_game_bepinex.sh", executable).unwrap();
737 zip.write_all(b"#!/bin/sh\n").unwrap();
738
739 zip.start_file("mods.yml", plain).unwrap();
740 zip.write_all(b"[]").unwrap();
741
742 zip.finish().unwrap();
743
744 extract_zip(&zip_path, &output_dir).unwrap();
745
746 let script_mode = fs::metadata(output_dir.join("start_game_bepinex.sh"))
747 .unwrap()
748 .permissions()
749 .mode();
750
751 assert!(
752 script_mode & 0o111 != 0,
753 "executable entry extracted without an execute bit: {script_mode:o}"
754 );
755
756 let plain_mode = fs::metadata(output_dir.join("mods.yml"))
759 .unwrap()
760 .permissions()
761 .mode();
762
763 assert!(
764 plain_mode & 0o111 == 0,
765 "plain entry gained an execute bit: {plain_mode:o}"
766 );
767 }
768
769 #[test]
773 #[cfg(unix)]
774 fn test_extract_zip_handles_entries_with_no_unix_mode() {
775 use std::os::unix::fs::PermissionsExt;
776
777 let temp_dir = tempdir().unwrap();
778 let output_dir = temp_dir.path().join("output");
779
780 let zip_path = temp_dir.path().join("test_no_mode.zip");
781 let file = File::create(&zip_path).unwrap();
782 let mut zip = ZipWriter::new(file);
783
784 let options: FileOptions<'_, ()> =
785 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
786
787 zip.start_file("plugin.dll", options).unwrap();
788 zip.write_all(b"bytes").unwrap();
789
790 zip.finish().unwrap();
791
792 extract_zip(&zip_path, &output_dir).unwrap();
793
794 let mode = fs::metadata(output_dir.join("plugin.dll"))
795 .unwrap()
796 .permissions()
797 .mode();
798
799 assert!(
800 mode & 0o111 == 0,
801 "entry with no mode made executable: {mode:o}"
802 );
803 }
804
805 #[test]
808 #[cfg(unix)]
809 fn test_extract_zip_drops_setuid_bits() {
810 use std::os::unix::fs::PermissionsExt;
811
812 let temp_dir = tempdir().unwrap();
813 let output_dir = temp_dir.path().join("output");
814
815 let zip_path = temp_dir.path().join("test_setuid.zip");
816 let file = File::create(&zip_path).unwrap();
817 let mut zip = ZipWriter::new(file);
818
819 let options: FileOptions<'_, ()> = FileOptions::default()
820 .compression_method(zip::CompressionMethod::Stored)
821 .unix_permissions(0o4755);
822
823 zip.start_file("evil.sh", options).unwrap();
824 zip.write_all(b"#!/bin/sh\n").unwrap();
825
826 zip.finish().unwrap();
827
828 extract_zip(&zip_path, &output_dir).unwrap();
829
830 let mode = fs::metadata(output_dir.join("evil.sh"))
831 .unwrap()
832 .permissions()
833 .mode();
834
835 assert!(
836 mode & 0o7000 == 0,
837 "setuid/setgid/sticky survived: {mode:o}"
838 );
839 assert!(mode & 0o111 != 0, "execute bit lost: {mode:o}");
840 }
841
842 #[test]
843 fn test_extract_zip_with_directory() {
844 let temp_dir = tempdir().unwrap();
845 let output_dir = temp_dir.path().join("output");
846 fs::create_dir_all(&output_dir).unwrap();
847
848 let zip_path = temp_dir.path().join("test_with_dir.zip");
849 let file = File::create(&zip_path).unwrap();
850 let mut zip = ZipWriter::new(file);
851
852 let options: FileOptions<'_, ()> =
853 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
854
855 zip.add_directory("test_dir/", options).unwrap();
856
857 zip.start_file("test_dir/file_in_dir.txt", options).unwrap();
858 zip.write_all(b"File in directory").unwrap();
859
860 zip.finish().unwrap();
861
862 let result = extract_zip(&zip_path, &output_dir);
863
864 assert!(result.is_ok());
865
866 let dir_path = output_dir.join("test_dir");
867 assert!(dir_path.exists());
868 assert!(dir_path.is_dir());
869
870 let file_in_dir = dir_path.join("file_in_dir.txt");
871 assert!(file_in_dir.exists());
872
873 let content = fs::read_to_string(&file_in_dir).unwrap();
874 assert_eq!(content, "File in directory");
875 }
876
877 #[test]
878 fn test_extract_zip_with_nested_directories() {
879 let temp_dir = tempdir().unwrap();
880 let output_dir = temp_dir.path().join("output");
881
882 let zip_path = temp_dir.path().join("test_nested.zip");
883 let file = File::create(&zip_path).unwrap();
884 let mut zip = ZipWriter::new(file);
885
886 let options: FileOptions<'_, ()> =
887 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
888
889 zip
890 .start_file("deep/nested/path/file.txt", options)
891 .unwrap();
892 zip.write_all(b"Deep nested file").unwrap();
893
894 zip.finish().unwrap();
895
896 let result = extract_zip(&zip_path, &output_dir);
897
898 assert!(result.is_ok());
899
900 let nested_file = output_dir.join("deep/nested/path/file.txt");
901 assert!(nested_file.exists());
902
903 let content = fs::read_to_string(&nested_file).unwrap();
904 assert_eq!(content, "Deep nested file");
905 }
906
907 #[test]
908 fn test_extract_zip_streams_large_file() {
909 let temp_dir = tempdir().unwrap();
910 let output_dir = temp_dir.path().join("output");
911
912 let zip_path = temp_dir.path().join("test_large.zip");
913 let file = File::create(&zip_path).unwrap();
914 let mut zip = ZipWriter::new(file);
915
916 let options: FileOptions<'_, ()> =
917 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
918
919 let payload: Vec<u8> = (0..(64 * 1024 * 3 + 17)).map(|i| (i % 251) as u8).collect();
921
922 zip.start_file("big.bin", options).unwrap();
923 zip.write_all(&payload).unwrap();
924
925 zip.finish().unwrap();
926
927 let result = extract_zip(&zip_path, &output_dir);
928
929 assert!(result.is_ok());
930
931 let extracted = output_dir.join("big.bin");
932 let content = fs::read(&extracted).unwrap();
933
934 assert_eq!(content, payload);
935
936 let leftover = fs::read_dir(&output_dir)
938 .unwrap()
939 .filter_map(|e| e.ok())
940 .any(|e| e.file_name().to_string_lossy().contains(".partial"));
941
942 assert!(!leftover, "no .partial temp files should remain");
943 }
944
945 #[test]
946 fn test_extract_zip_reuses_buffer_across_entries() {
947 let temp_dir = tempdir().unwrap();
948 let output_dir = temp_dir.path().join("output");
949
950 let big: Vec<u8> = (0..(64 * 1024 * 2 + 5)).map(|i| (i % 251) as u8).collect();
953 let small = b"tiny".to_vec();
954 let zip_path = temp_dir.path().join("multi.zip");
955 write_stored_zip(&zip_path, &[("big.bin", &big), ("small.txt", &small)]);
956
957 let result = extract_zip(&zip_path, &output_dir);
958
959 assert!(result.is_ok());
960
961 let big_out = fs::read(output_dir.join("big.bin")).unwrap();
962 let small_out = fs::read(output_dir.join("small.txt")).unwrap();
963
964 assert_eq!(big_out, big);
965 assert_eq!(small_out, small);
966 assert!(no_partial_files(&output_dir));
967 }
968
969 #[test]
970 fn test_extract_zip_leaves_no_file_on_crc_mismatch() {
971 let temp_dir = tempdir().unwrap();
972 let output_dir = temp_dir.path().join("output");
973
974 let zip_path = temp_dir.path().join("test_corrupt.zip");
975 let file = File::create(&zip_path).unwrap();
976 let mut zip = ZipWriter::new(file);
977
978 let options: FileOptions<'_, ()> =
979 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
980
981 let marker = b"UNIQUEMARKERPAYLOAD";
984 let mut payload = marker.to_vec();
985 payload.extend_from_slice(&[7u8; 64]);
986
987 zip.start_file("data.bin", options).unwrap();
988 zip.write_all(&payload).unwrap();
989
990 zip.finish().unwrap();
991
992 let mut bytes = fs::read(&zip_path).unwrap();
993 let pos = bytes
994 .windows(marker.len())
995 .position(|w| w == marker)
996 .expect("payload marker present in archive");
997
998 bytes[pos + marker.len()] ^= 0xFF;
1000 fs::write(&zip_path, &bytes).unwrap();
1001
1002 let result = extract_zip(&zip_path, &output_dir);
1003
1004 assert!(result.is_err());
1009
1010 assert!(!output_dir.join("data.bin").exists());
1012
1013 let leftover = fs::read_dir(&output_dir)
1014 .unwrap()
1015 .filter_map(|e| e.ok())
1016 .any(|e| e.file_name().to_string_lossy().contains(".partial"));
1017
1018 assert!(!leftover, "no .partial temp files should remain");
1019 }
1020
1021 fn write_stored_zip(zip_path: &Path, entries: &[(&str, &[u8])]) {
1022 let file = File::create(zip_path).unwrap();
1023 let mut zip = ZipWriter::new(file);
1024
1025 let options: FileOptions<'_, ()> =
1026 FileOptions::default().compression_method(zip::CompressionMethod::Stored);
1027
1028 for (name, contents) in entries {
1029 zip.start_file(*name, options).unwrap();
1030 zip.write_all(contents).unwrap();
1031 }
1032
1033 zip.finish().unwrap();
1034 }
1035
1036 fn no_partial_files(dir: &Path) -> bool {
1037 !fs::read_dir(dir)
1038 .unwrap()
1039 .filter_map(|e| e.ok())
1040 .any(|e| e.file_name().to_string_lossy().contains(".partial"))
1041 }
1042
1043 #[test]
1044 fn test_extract_zip_rejects_too_many_entries() {
1045 let temp_dir = tempdir().unwrap();
1046 let output_dir = temp_dir.path().join("output");
1047
1048 let zip_path = temp_dir.path().join("many_entries.zip");
1049 write_stored_zip(
1050 &zip_path,
1051 &[("a.txt", b"a"), ("b.txt", b"b"), ("c.txt", b"c")],
1052 );
1053
1054 let limits = ExtractLimits {
1055 max_entries: 2,
1056 ..Default::default()
1057 };
1058
1059 let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1060
1061 assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1062 }
1063
1064 #[test]
1065 fn test_extract_zip_rejects_oversized_entry() {
1066 let temp_dir = tempdir().unwrap();
1067 let output_dir = temp_dir.path().join("output");
1068
1069 let zip_path = temp_dir.path().join("big_entry.zip");
1070 let payload = vec![0u8; 100];
1071 write_stored_zip(&zip_path, &[("big.bin", &payload)]);
1072
1073 let limits = ExtractLimits {
1074 max_file_bytes: 8,
1075 ..Default::default()
1076 };
1077
1078 let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1079
1080 assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1081 assert!(!output_dir.join("big.bin").exists());
1082 assert!(no_partial_files(&output_dir));
1083 }
1084
1085 #[test]
1086 fn test_extract_zip_rejects_exceeding_total() {
1087 let temp_dir = tempdir().unwrap();
1088 let output_dir = temp_dir.path().join("output");
1089
1090 let zip_path = temp_dir.path().join("total.zip");
1091 let chunk = vec![7u8; 80];
1092 write_stored_zip(&zip_path, &[("one.bin", &chunk), ("two.bin", &chunk)]);
1093
1094 let limits = ExtractLimits {
1096 max_file_bytes: 1_000,
1097 max_total_bytes: 100,
1098 ..Default::default()
1099 };
1100
1101 let result = extract_zip_with_limits(&zip_path, &output_dir, &limits);
1102
1103 assert!(matches!(result, Err(Error::ExtractLimitExceeded(_))));
1104 assert!(no_partial_files(&output_dir));
1105 }
1106
1107 #[test]
1108 fn test_extract_zip_within_default_limits_succeeds() {
1109 let temp_dir = tempdir().unwrap();
1110 let output_dir = temp_dir.path().join("output");
1111
1112 let zip_path = temp_dir.path().join("normal.zip");
1113 write_stored_zip(&zip_path, &[("plugin.dll", b"content")]);
1114
1115 let result = extract_zip_with_limits(&zip_path, &output_dir, &ExtractLimits::default());
1116
1117 assert!(result.is_ok());
1118 assert!(output_dir.join("plugin.dll").exists());
1119 }
1120
1121 #[test]
1122 fn test_extract_zip_rejects_path_traversal() {
1123 let temp_dir = tempdir().unwrap();
1124 let output_dir = temp_dir.path().join("output");
1125 fs::create_dir_all(&output_dir).unwrap();
1126
1127 let zip_path = temp_dir.path().join("traversal.zip");
1130 write_stored_zip(
1131 &zip_path,
1132 &[("../escaped.txt", b"malicious"), ("safe.txt", b"benign")],
1133 );
1134
1135 let result = extract_zip(&zip_path, &output_dir);
1136
1137 assert!(result.is_ok());
1140 assert!(output_dir.join("safe.txt").exists());
1141 assert!(!temp_dir.path().join("escaped.txt").exists());
1142 assert!(no_partial_files(&output_dir));
1143 }
1144
1145 #[test]
1146 fn test_should_extract() {
1147 let temp_dir = tempdir().unwrap();
1148 let mod_dir = temp_dir.path().join("Owner-ModName");
1149 fs::create_dir_all(&mod_dir).unwrap();
1150
1151 let result = should_extract(&mod_dir, "1.0.0");
1152 assert!(result.unwrap());
1153
1154 let manifest_content = r#"{
1155 "version_number": "1.0.0",
1156 "name": "TestMod",
1157 "description": "Test mod description"
1158 }"#;
1159
1160 let manifest_path = mod_dir.join("manifest.json");
1161 let mut file = File::create(&manifest_path).unwrap();
1162 file.write_all(manifest_content.as_bytes()).unwrap();
1163
1164 let result = should_extract(&mod_dir, "1.0.0");
1165 assert!(!result.unwrap());
1166
1167 let result = should_extract(&mod_dir, "2.0.0");
1168 assert!(result.unwrap());
1169
1170 let mut file = File::create(&manifest_path).unwrap();
1171 file.write_all(b"invalid json content").unwrap();
1172
1173 let result = should_extract(&mod_dir, "1.0.0");
1174 assert!(result.unwrap());
1175 }
1176}