1use std::path::Path;
4
5use crate::ArchiveError;
6use crate::ArchiveReader;
7use crate::EntrySink;
8use crate::ExtractionReport;
9use crate::ListOptions;
10use crate::NoopProgress;
11use crate::ProgressCallback;
12use crate::Result;
13use crate::SecurityConfig;
14use crate::VerificationOptions;
15use crate::config::ExtractionOptions;
16use crate::config::Validated;
17use crate::creation::CreationConfig;
18use crate::creation::CreationReport;
19use crate::formats::SevenZArchive;
20use crate::formats::ZipArchive;
21use crate::formats::compression::CompressionCodec;
22use crate::formats::detect::CreatableFormat;
23use crate::formats::detect::CreationFamily;
24use crate::formats::detect::FormatFamily;
25use crate::formats::detect::detect_format;
26use crate::formats::detect::detect_format_from_extension;
27use crate::formats::detect::is_zip_family_alias;
28use crate::inspection::ArchiveManifest;
29use crate::inspection::VerificationReport;
30use crate::inspection::list::ListPass;
31use crate::reader::SeekableFormat;
32use crate::reader::Source;
33use crate::reader::tar_archive;
34use crate::sink::SinkOptions;
35use crate::sink::SinkTarget;
36
37pub fn extract_archive<P: AsRef<Path>, Q: AsRef<Path>>(
70 archive_path: P,
71 output_dir: Q,
72 config: &SecurityConfig,
73) -> Result<ExtractionReport> {
74 let mut noop = NoopProgress;
75 extract_archive_with_progress(archive_path, output_dir, config, &mut noop)
76}
77
78pub fn extract_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
115 archive_path: P,
116 output_dir: Q,
117 config: &SecurityConfig,
118 progress: &mut dyn ProgressCallback,
119) -> Result<ExtractionReport> {
120 let options = ExtractionOptions::default();
121 extract_archive_with_options_and_progress(archive_path, output_dir, config, &options, progress)
122}
123
124fn extract_impl<P: AsRef<Path>, Q: AsRef<Path>>(
125 archive_path: P,
126 output_dir: Q,
127 config: &SecurityConfig,
128 options: &ExtractionOptions,
129 progress: &mut dyn ProgressCallback,
130) -> Result<ExtractionReport> {
131 let config = config.clone().validate()?;
132 let config = &config;
133
134 let archive_path = archive_path.as_ref();
135 let output_dir = output_dir.as_ref();
136
137 let format = detect_format(archive_path)?;
139
140 match format.family() {
142 FormatFamily::Tar(codec) => {
143 extract_tar(archive_path, output_dir, config, options, progress, codec)
144 }
145 FormatFamily::Seekable(SeekableFormat::Zip) => {
146 extract_zip(archive_path, output_dir, config, options, progress)
147 }
148 FormatFamily::Seekable(SeekableFormat::SevenZ) => {
149 extract_7z(archive_path, output_dir, config, options, progress)
150 }
151 }
152}
153
154pub fn extract_archive_with_options_and_progress<P: AsRef<Path>, Q: AsRef<Path>>(
202 archive_path: P,
203 output_dir: Q,
204 config: &SecurityConfig,
205 options: &ExtractionOptions,
206 progress: &mut dyn ProgressCallback,
207) -> Result<ExtractionReport> {
208 if options.atomic {
209 extract_atomic(archive_path, output_dir, config, options, progress)
210 } else {
211 extract_impl(archive_path, output_dir, config, options, progress)
212 }
213}
214
215pub fn extract_archive_with_options<P: AsRef<Path>, Q: AsRef<Path>>(
246 archive_path: P,
247 output_dir: Q,
248 config: &SecurityConfig,
249 options: &ExtractionOptions,
250) -> Result<ExtractionReport> {
251 let mut noop = NoopProgress;
252 extract_archive_with_options_and_progress(archive_path, output_dir, config, options, &mut noop)
253}
254
255fn extract_atomic<P: AsRef<Path>, Q: AsRef<Path>>(
256 archive_path: P,
257 output_dir: Q,
258 config: &SecurityConfig,
259 options: &ExtractionOptions,
260 progress: &mut dyn ProgressCallback,
261) -> Result<ExtractionReport> {
262 let output_dir = output_dir.as_ref();
263
264 let canonical_output = if output_dir.exists() {
268 output_dir.canonicalize().map_err(ArchiveError::Io)?
269 } else {
270 output_dir.to_path_buf()
271 };
272
273 let parent = canonical_output
274 .parent()
275 .ok_or_else(|| ArchiveError::InvalidConfiguration {
276 reason: "output directory has no parent".into(),
277 })?;
278
279 std::fs::create_dir_all(parent).map_err(ArchiveError::Io)?;
280
281 let temp_dir = tempfile::Builder::new()
282 .prefix(".exarch-")
283 .tempdir_in(parent)
284 .map_err(|e| {
285 ArchiveError::Io(std::io::Error::new(
286 e.kind(),
287 format!(
288 "failed to create temp directory in {}: {e}",
289 parent.display()
290 ),
291 ))
292 })?;
293
294 let result = extract_impl(archive_path, temp_dir.path(), config, options, progress);
295
296 match result {
297 Ok(report) => {
298 let temp_path = temp_dir.keep();
300 std::fs::rename(&temp_path, output_dir).map_err(|e| {
301 let _ = std::fs::remove_dir_all(&temp_path);
303 if e.kind() == std::io::ErrorKind::AlreadyExists {
305 ArchiveError::OutputExists {
306 path: output_dir.to_path_buf(),
307 }
308 } else {
309 ArchiveError::Io(std::io::Error::new(
310 e.kind(),
311 format!("failed to rename temp dir to {}: {e}", output_dir.display()),
312 ))
313 }
314 })?;
315
316 Ok(report)
317 }
318 Err(e) => {
319 Err(e.rolled_back())
321 }
322 }
323}
324
325fn extract_tar(
328 archive_path: &Path,
329 output_dir: &Path,
330 config: &SecurityConfig<Validated>,
331 options: &ExtractionOptions,
332 progress: &mut dyn ProgressCallback,
333 codec: Option<CompressionCodec>,
334) -> Result<ExtractionReport> {
335 use crate::formats::TarArchive;
336 use crate::formats::tar::open_tar_stream;
337 use crate::formats::traits::ArchiveFormat;
338
339 let stream = open_tar_stream(archive_path, codec, config.max_decoder_memory)?;
340 let mut archive = TarArchive::new(stream);
341 archive.extract(output_dir, config, options, progress)
342}
343
344fn extract_zip(
345 archive_path: &Path,
346 output_dir: &Path,
347 config: &SecurityConfig<Validated>,
348 options: &ExtractionOptions,
349 progress: &mut dyn ProgressCallback,
350) -> Result<ExtractionReport> {
351 use crate::formats::ZipArchive;
352 use crate::formats::traits::ArchiveFormat;
353 use std::fs::File;
354
355 let file = File::open(archive_path)?;
356 let mut archive = ZipArchive::new(file)?;
357 archive.extract(output_dir, config, options, progress)
358}
359
360fn extract_7z(
361 archive_path: &Path,
362 output_dir: &Path,
363 config: &SecurityConfig<Validated>,
364 options: &ExtractionOptions,
365 progress: &mut dyn ProgressCallback,
366) -> Result<ExtractionReport> {
367 use crate::formats::SevenZArchive;
368 use crate::formats::traits::ArchiveFormat;
369 use std::fs::File;
370
371 let file = File::open(archive_path)?;
372 let mut archive = SevenZArchive::new(file)?;
373 archive.extract(output_dir, config, options, progress)
374}
375
376pub fn create_archive<P: AsRef<Path>, Q: AsRef<Path>>(
409 output_path: P,
410 sources: &[Q],
411 config: &CreationConfig,
412) -> Result<CreationReport> {
413 let mut noop = NoopProgress;
414 create_archive_with_progress(output_path, sources, config, &mut noop)
415}
416
417pub fn create_archive_with_progress<P: AsRef<Path>, Q: AsRef<Path>>(
458 output_path: P,
459 sources: &[Q],
460 config: &CreationConfig,
461 progress: &mut dyn ProgressCallback,
462) -> Result<CreationReport> {
463 let config = config.clone().validate()?;
464 let config = &config;
465
466 let output = output_path.as_ref();
467
468 if config.format.is_none() {
477 reject_zip_family_creation(output)?;
478 }
479
480 let format = determine_creation_format(output, config)?;
482
483 let source_refs: Vec<&Path> = sources.iter().map(AsRef::as_ref).collect();
484 let creator = creator_for_format(format);
485 creator.create(output, &source_refs, config, progress)
486}
487
488fn creator_for_format(format: CreatableFormat) -> Box<dyn crate::formats::traits::FormatCreator> {
489 match format.family() {
490 CreationFamily::Tar(codec) => Box::new(crate::creation::TarCreator(codec)),
491 CreationFamily::Zip => Box::new(crate::creation::ZipCreator),
492 }
493}
494
495pub fn list_archive<P: AsRef<Path>>(
531 archive_path: P,
532 config: &SecurityConfig,
533) -> Result<ArchiveManifest> {
534 crate::inspection::list_archive(archive_path, config)
535}
536
537pub fn list_archive_with_options<P: AsRef<Path>>(
567 archive_path: P,
568 config: &SecurityConfig,
569 options: &crate::ListOptions,
570) -> Result<ArchiveManifest> {
571 crate::inspection::list_archive_with_options(archive_path, config, options)
572}
573
574pub fn verify_archive<P: AsRef<Path>>(
628 archive_path: P,
629 config: &SecurityConfig,
630) -> Result<VerificationReport> {
631 crate::inspection::verify_archive(archive_path, config)
632}
633
634pub fn verify_archive_with_options<P: AsRef<Path>>(
662 archive_path: P,
663 config: &SecurityConfig,
664 options: &crate::VerificationOptions,
665) -> Result<VerificationReport> {
666 crate::inspection::verify_archive_with_options(archive_path, config, options)
667}
668
669pub fn list_reader(
702 reader: ArchiveReader<'_>,
703 config: &SecurityConfig,
704 options: &ListOptions,
705) -> Result<ArchiveManifest> {
706 list_reader_with_progress(reader, config, options, &mut NoopProgress)
707}
708
709pub fn list_reader_with_progress(
749 reader: ArchiveReader<'_>,
750 config: &SecurityConfig,
751 options: &ListOptions,
752 progress: &mut dyn ProgressCallback,
753) -> Result<ArchiveManifest> {
754 let config = config.clone().validate()?;
755 let manifest = reader.list(
756 &config,
757 &mut ListPass::strict_with(options.stored_targets).with_progress(progress),
758 )?;
759 progress.on_complete();
760 Ok(manifest)
761}
762
763pub fn verify_reader(
801 reader: ArchiveReader<'_>,
802 config: &SecurityConfig,
803 options: &VerificationOptions,
804) -> Result<VerificationReport> {
805 verify_reader_with_progress(reader, config, options, &mut NoopProgress)
806}
807
808pub fn verify_reader_with_progress(
850 reader: ArchiveReader<'_>,
851 config: &SecurityConfig,
852 options: &VerificationOptions,
853 progress: &mut dyn ProgressCallback,
854) -> Result<VerificationReport> {
855 let config = config.clone().validate()?;
856 let report = reader.verify(&config, *options, progress)?;
857 progress.on_complete();
858 Ok(report)
859}
860
861pub fn extract_to_sink<S: EntrySink>(
952 reader: ArchiveReader<'_>,
953 sink: &mut S,
954 config: &SecurityConfig,
955 options: &SinkOptions,
956) -> Result<ExtractionReport> {
957 extract_to_sink_with_progress(reader, sink, config, options, &mut NoopProgress)
958}
959
960pub fn extract_to_sink_with_progress<S: EntrySink>(
1003 reader: ArchiveReader<'_>,
1004 sink: &mut S,
1005 config: &SecurityConfig,
1006 options: &SinkOptions,
1007 progress: &mut dyn ProgressCallback,
1008) -> Result<ExtractionReport> {
1009 let config = config.clone().validate()?;
1010 match reader.into_source() {
1011 Source::Tar { stream, codec } => {
1012 let mut archive = tar_archive(stream, codec, config.max_decoder_memory)?;
1013 let mut target = SinkTarget::new(sink, &config);
1014 archive.extract_into(&mut target, &config, *options, progress)
1015 }
1016 Source::Seekable {
1017 reader,
1018 format: SeekableFormat::Zip,
1019 } => {
1020 let mut archive = ZipArchive::new(reader)?;
1021 let checked = archive.check_structure(&config)?;
1022 let mut target = SinkTarget::new(sink, &config);
1023 archive.extract_into(checked, &mut target, &config, *options, progress)
1024 }
1025 Source::Seekable {
1026 reader,
1027 format: SeekableFormat::SevenZ,
1028 } => {
1029 let mut archive = SevenZArchive::new(reader)?;
1030 let admission = archive.admit(&config)?;
1031 let mut target = SinkTarget::new(sink, &config);
1032 archive.extract_into(admission, &mut target, *options, progress)
1033 }
1034 }
1035}
1036
1037fn reject_zip_family_creation(output: &Path) -> Result<()> {
1043 let Some(ext) = output.extension().and_then(|e| e.to_str()) else {
1044 return Ok(());
1045 };
1046 if is_zip_family_alias(ext) {
1047 let ext_lower = ext.to_ascii_lowercase();
1048 return Err(ArchiveError::InvalidArchive(format!(
1049 "creation for .{ext_lower} isn't supported: the format is ZIP-based but \
1050 requires extra structure (signing, manifests, ordering) that exarch \
1051 doesn't produce. Use .zip, or set CreationConfig::format = Some(\
1052 exarch_core::formats::detect::CreatableFormat::Zip) to override."
1053 )));
1054 }
1055 Ok(())
1056}
1057
1058fn determine_creation_format<State>(
1064 output: &Path,
1065 config: &CreationConfig<State>,
1066) -> Result<CreatableFormat> {
1067 if let Some(format) = config.format {
1069 return Ok(format);
1070 }
1071
1072 CreatableFormat::try_from(detect_format_from_extension(output)?)
1074}
1075
1076#[cfg(test)]
1077#[allow(clippy::unwrap_used)]
1078mod tests {
1079 use super::*;
1080 use crate::raw_zip::RawEntry;
1081 use crate::raw_zip::RawZip;
1082 use std::assert_matches;
1083 use std::path::PathBuf;
1084
1085 #[test]
1086 fn test_extract_archive_nonexistent_file() {
1087 let config = SecurityConfig::default();
1088 let result = extract_archive(
1089 PathBuf::from("nonexistent_test.tar"),
1090 PathBuf::from("/tmp/test"),
1091 &config,
1092 );
1093 assert!(result.is_err());
1095 }
1096
1097 #[test]
1098 fn test_determine_creation_format_tar() {
1099 let config = CreationConfig::default();
1100 let path = PathBuf::from("archive.tar");
1101 let format = determine_creation_format(&path, &config).unwrap();
1102 assert_eq!(format, CreatableFormat::Tar);
1103 }
1104
1105 #[test]
1106 fn test_determine_creation_format_tar_gz() {
1107 let config = CreationConfig::default();
1108 let path = PathBuf::from("archive.tar.gz");
1109 let format = determine_creation_format(&path, &config).unwrap();
1110 assert_eq!(format, CreatableFormat::TarGz);
1111
1112 let path2 = PathBuf::from("archive.tgz");
1113 let format2 = determine_creation_format(&path2, &config).unwrap();
1114 assert_eq!(format2, CreatableFormat::TarGz);
1115 }
1116
1117 #[test]
1118 fn test_determine_creation_format_tar_bz2() {
1119 let config = CreationConfig::default();
1120 let path = PathBuf::from("archive.tar.bz2");
1121 let format = determine_creation_format(&path, &config).unwrap();
1122 assert_eq!(format, CreatableFormat::TarBz2);
1123 }
1124
1125 #[test]
1126 fn test_determine_creation_format_tar_xz() {
1127 let config = CreationConfig::default();
1128 let path = PathBuf::from("archive.tar.xz");
1129 let format = determine_creation_format(&path, &config).unwrap();
1130 assert_eq!(format, CreatableFormat::TarXz);
1131 }
1132
1133 #[test]
1134 fn test_determine_creation_format_tar_zst() {
1135 let config = CreationConfig::default();
1136 let path = PathBuf::from("archive.tar.zst");
1137 let format = determine_creation_format(&path, &config).unwrap();
1138 assert_eq!(format, CreatableFormat::TarZst);
1139 }
1140
1141 #[test]
1142 fn test_determine_creation_format_zip() {
1143 let config = CreationConfig::default();
1144 let path = PathBuf::from("archive.zip");
1145 let format = determine_creation_format(&path, &config).unwrap();
1146 assert_eq!(format, CreatableFormat::Zip);
1147 }
1148
1149 #[test]
1150 fn test_determine_creation_format_explicit() {
1151 let config = CreationConfig::default().with_format(Some(CreatableFormat::TarGz));
1152 let path = PathBuf::from("archive.xyz");
1153 let format = determine_creation_format(&path, &config).unwrap();
1154 assert_eq!(format, CreatableFormat::TarGz);
1155 }
1156
1157 #[test]
1158 fn test_determine_creation_format_unknown() {
1159 let config = CreationConfig::default();
1160 let path = PathBuf::from("archive.rar");
1161 let result = determine_creation_format(&path, &config);
1162 assert!(result.is_err());
1163 }
1164
1165 #[test]
1166 fn test_determine_creation_format_ignores_stale_magic_bytes() {
1167 let dir = tempfile::tempdir().unwrap();
1170 let path = dir.path().join("backup.zip");
1171 std::fs::write(&path, b"\x1f\x8b\x08\x00\x00\x00\x00\x00").unwrap();
1173
1174 let config = CreationConfig::default();
1175 let format = determine_creation_format(&path, &config).unwrap();
1176 assert_eq!(
1177 format,
1178 CreatableFormat::Zip,
1179 "creation format must follow extension, not stale on-disk magic bytes"
1180 );
1181 }
1182
1183 #[test]
1184 fn test_extract_archive_7z_not_implemented() {
1185 let dest = tempfile::TempDir::new().unwrap();
1186 let path = PathBuf::from("test.7z");
1187
1188 let result = extract_archive(&path, dest.path(), &SecurityConfig::default());
1189
1190 assert!(result.is_err());
1191 }
1192
1193 #[test]
1194 fn test_create_archive_invalid_compression_level_rejected_before_io() {
1195 for ext in ["tar.gz", "tar.bz2", "tar.xz", "tar.zst"] {
1196 let dest = tempfile::TempDir::new().unwrap();
1197 let archive_path = dest.path().join(format!("output.{ext}"));
1198 let mut config = CreationConfig::default();
1199 config.compression_level = Some(200);
1200 let result = create_archive(&archive_path, &[] as &[&str], &config);
1201 assert_matches!(
1202 result,
1203 Err(ArchiveError::InvalidCompressionLevel { level: 200 }),
1204 "{ext}: expected InvalidCompressionLevel, got {result:?}",
1205 );
1206 assert!(
1208 !archive_path.exists(),
1209 "{ext}: output file must not be created"
1210 );
1211 }
1212 }
1213
1214 #[test]
1215 fn test_create_archive_zip_family_not_supported() {
1216 let dest = tempfile::TempDir::new().unwrap();
1220 for ext in ["apk", "whl", "EPUB"] {
1221 let archive_path = dest.path().join(format!("output.{ext}"));
1222 let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
1223 assert_matches!(
1224 result,
1225 Err(ArchiveError::InvalidArchive(_)),
1226 ".{ext} should be rejected, got {result:?}",
1227 );
1228 }
1229 }
1230
1231 #[test]
1232 fn test_create_archive_zip_family_override_bypasses_guard() {
1233 let dest = tempfile::TempDir::new().unwrap();
1237 let src = dest.path().join("source.txt");
1238 std::fs::write(&src, b"hello").unwrap();
1239 let archive_path = dest.path().join("output.apk");
1240 let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1241 let result = create_archive(&archive_path, &[&src], &config);
1242 assert!(
1243 result.is_ok(),
1244 "explicit format override should bypass the guard, got {result:?}",
1245 );
1246 }
1247
1248 #[test]
1249 fn test_create_archive_7z_not_supported() {
1250 let dest = tempfile::TempDir::new().unwrap();
1251 let archive_path = dest.path().join("output.7z");
1252
1253 let result = create_archive(&archive_path, &[] as &[&str], &CreationConfig::default());
1254
1255 assert!(result.is_err());
1256 assert_matches!(
1257 result.unwrap_err(),
1258 ArchiveError::InvalidConfiguration { .. }
1259 );
1260 }
1261
1262 #[test]
1263 fn test_extract_archive_with_options_and_progress_non_atomic_delegates_to_normal() {
1264 let dest = tempfile::TempDir::new().unwrap();
1265 let options = ExtractionOptions {
1266 atomic: false,
1267 skip_duplicates: true,
1268 };
1269 let result = extract_archive_with_options_and_progress(
1270 PathBuf::from("nonexistent.tar.gz"),
1271 dest.path(),
1272 &SecurityConfig::default(),
1273 &options,
1274 &mut NoopProgress,
1275 );
1276 assert!(result.is_err());
1277 }
1278
1279 #[test]
1280 fn test_extract_archive_with_options_delegates() {
1281 let dest = tempfile::TempDir::new().unwrap();
1282 let options = ExtractionOptions {
1283 atomic: false,
1284 skip_duplicates: true,
1285 };
1286 let result = extract_archive_with_options(
1287 PathBuf::from("nonexistent.tar.gz"),
1288 dest.path(),
1289 &SecurityConfig::default(),
1290 &options,
1291 );
1292 assert!(result.is_err());
1293 }
1294
1295 #[test]
1296 fn test_extract_atomic_success() {
1297 use crate::create_archive;
1298 use crate::creation::CreationConfig;
1299
1300 let archive_dir = tempfile::TempDir::new().unwrap();
1302 let archive_path = archive_dir.path().join("test.tar.gz");
1303
1304 let src_dir = tempfile::TempDir::new().unwrap();
1306 std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
1307 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1308
1309 let parent = tempfile::TempDir::new().unwrap();
1310 let output_dir = parent.path().join("extracted");
1311
1312 let options = ExtractionOptions {
1313 atomic: true,
1314 skip_duplicates: true,
1315 };
1316 let result = extract_archive_with_options(
1317 &archive_path,
1318 &output_dir,
1319 &SecurityConfig::default(),
1320 &options,
1321 );
1322
1323 assert!(result.is_ok());
1324 assert!(output_dir.exists());
1325 let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
1327 assert_eq!(
1328 temp_entries.len(),
1329 1,
1330 "Expected only the output dir, found temp remnants"
1331 );
1332 }
1333
1334 #[test]
1335 fn test_extract_atomic_failure_cleans_up() {
1336 let parent = tempfile::TempDir::new().unwrap();
1337 let output_dir = parent.path().join("extracted");
1338
1339 let options = ExtractionOptions {
1340 atomic: true,
1341 skip_duplicates: true,
1342 };
1343 let result = extract_archive_with_options(
1344 PathBuf::from("nonexistent_archive.tar.gz"),
1345 &output_dir,
1346 &SecurityConfig::default(),
1347 &options,
1348 );
1349
1350 assert!(result.is_err());
1351 assert!(!output_dir.exists());
1353 let temp_entries: Vec<_> = std::fs::read_dir(parent.path()).unwrap().collect();
1355 assert!(
1356 temp_entries.is_empty(),
1357 "Temp dir not cleaned up after failure"
1358 );
1359 }
1360
1361 #[test]
1362 fn test_extract_atomic_output_already_exists_fails() {
1363 use crate::create_archive;
1364 use crate::creation::CreationConfig;
1365
1366 let parent = tempfile::TempDir::new().unwrap();
1367 let output_dir = parent.path().join("extracted");
1368 std::fs::create_dir_all(&output_dir).unwrap();
1369 std::fs::write(output_dir.join("existing.txt"), b"old content").unwrap();
1372
1373 let archive_dir = tempfile::TempDir::new().unwrap();
1374 let archive_path = archive_dir.path().join("test.tar.gz");
1375 let src_dir = tempfile::TempDir::new().unwrap();
1376 std::fs::write(src_dir.path().join("new.txt"), b"new content").unwrap();
1377 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1378
1379 let options = ExtractionOptions {
1380 atomic: true,
1381 skip_duplicates: true,
1382 };
1383 let result = extract_archive_with_options(
1384 &archive_path,
1385 &output_dir,
1386 &SecurityConfig::default(),
1387 &options,
1388 );
1389
1390 assert!(result.is_err());
1393 assert!(output_dir.join("existing.txt").exists());
1395 }
1396
1397 #[test]
1399 fn test_progress_callback_invoked_during_extraction() {
1400 use crate::ProgressCallback;
1401 use std::path::Path;
1402
1403 struct TrackingProgress {
1404 started: usize,
1405 completed: usize,
1406 finished: bool,
1407 }
1408
1409 impl ProgressCallback for TrackingProgress {
1410 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1411 self.started += 1;
1412 }
1413
1414 fn on_bytes_written(&mut self, _bytes: u64) {}
1415
1416 fn on_entry_complete(&mut self, _path: &Path) {
1417 self.completed += 1;
1418 }
1419
1420 fn on_complete(&mut self) {
1421 self.finished = true;
1422 }
1423 }
1424
1425 let archive_dir = tempfile::TempDir::new().unwrap();
1426 let archive_path = archive_dir.path().join("test.tar.gz");
1427 let src_dir = tempfile::TempDir::new().unwrap();
1428 std::fs::write(src_dir.path().join("a.txt"), b"hello").unwrap();
1429 std::fs::write(src_dir.path().join("b.txt"), b"world").unwrap();
1430 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1431
1432 let dest = tempfile::TempDir::new().unwrap();
1433 let mut progress = TrackingProgress {
1434 started: 0,
1435 completed: 0,
1436 finished: false,
1437 };
1438
1439 let report = extract_archive_with_progress(
1440 &archive_path,
1441 dest.path(),
1442 &SecurityConfig::default(),
1443 &mut progress,
1444 )
1445 .unwrap();
1446
1447 assert!(report.files_extracted >= 2, "expected at least 2 files");
1448 assert!(progress.started >= 2, "on_entry_start not called");
1449 assert!(progress.completed >= 2, "on_entry_complete not called");
1450 assert!(progress.finished, "on_complete not called");
1451 }
1452
1453 #[test]
1455 fn test_progress_callback_invoked_during_zip_extraction() {
1456 use crate::ProgressCallback;
1457 use std::path::Path;
1458
1459 struct TrackingProgress {
1460 started: usize,
1461 completed: usize,
1462 finished: bool,
1463 }
1464
1465 impl ProgressCallback for TrackingProgress {
1466 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1467 self.started += 1;
1468 }
1469
1470 fn on_bytes_written(&mut self, _bytes: u64) {}
1471
1472 fn on_entry_complete(&mut self, _path: &Path) {
1473 self.completed += 1;
1474 }
1475
1476 fn on_complete(&mut self) {
1477 self.finished = true;
1478 }
1479 }
1480
1481 let tmp = tempfile::TempDir::new().unwrap();
1482 let archive_path = tmp.path().join("test.zip");
1483 let src_dir = tempfile::TempDir::new().unwrap();
1484 std::fs::write(src_dir.path().join("x.txt"), b"foo").unwrap();
1485 std::fs::write(src_dir.path().join("y.txt"), b"bar").unwrap();
1486 let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1487 create_archive(&archive_path, &[src_dir.path()], &config).unwrap();
1488
1489 let dest = tempfile::TempDir::new().unwrap();
1490 let mut progress = TrackingProgress {
1491 started: 0,
1492 completed: 0,
1493 finished: false,
1494 };
1495 let report = extract_archive_with_progress(
1496 &archive_path,
1497 dest.path(),
1498 &SecurityConfig::default(),
1499 &mut progress,
1500 )
1501 .unwrap();
1502
1503 assert!(report.files_extracted >= 2, "expected at least 2 files");
1504 assert!(progress.started >= 2, "on_entry_start not called for ZIP");
1505 assert!(
1506 progress.completed >= 2,
1507 "on_entry_complete not called for ZIP"
1508 );
1509 assert!(progress.finished, "on_complete not called for ZIP");
1510 }
1511
1512 #[test]
1514 fn test_progress_callback_invoked_during_sevenz_extraction() {
1515 use crate::ProgressCallback;
1516 use std::path::Path;
1517
1518 struct TrackingProgress {
1519 started: usize,
1520 completed: usize,
1521 finished: bool,
1522 }
1523
1524 impl ProgressCallback for TrackingProgress {
1525 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1526 self.started += 1;
1527 }
1528
1529 fn on_bytes_written(&mut self, _bytes: u64) {}
1530
1531 fn on_entry_complete(&mut self, _path: &Path) {
1532 self.completed += 1;
1533 }
1534
1535 fn on_complete(&mut self) {
1536 self.finished = true;
1537 }
1538 }
1539
1540 let fixture =
1541 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1542
1543 let dest = tempfile::TempDir::new().unwrap();
1544 let mut progress = TrackingProgress {
1545 started: 0,
1546 completed: 0,
1547 finished: false,
1548 };
1549 let report = extract_archive_with_progress(
1550 &fixture,
1551 dest.path(),
1552 &SecurityConfig::default(),
1553 &mut progress,
1554 )
1555 .unwrap();
1556
1557 assert!(
1558 report.files_extracted >= 1,
1559 "expected at least 1 file from simple.7z"
1560 );
1561 assert!(progress.started >= 1, "on_entry_start not called for 7z");
1562 assert!(
1563 progress.completed >= 1,
1564 "on_entry_complete not called for 7z"
1565 );
1566 assert!(progress.finished, "on_complete not called for 7z");
1567 }
1568
1569 #[test]
1572 fn test_on_bytes_written_called_for_tar() {
1573 use crate::ProgressCallback;
1574 use std::path::Path;
1575
1576 struct ByteTracker {
1577 total: u64,
1578 }
1579
1580 impl ProgressCallback for ByteTracker {
1581 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1582
1583 fn on_bytes_written(&mut self, bytes: u64) {
1584 self.total += bytes;
1585 }
1586
1587 fn on_entry_complete(&mut self, _path: &Path) {}
1588
1589 fn on_complete(&mut self) {}
1590 }
1591
1592 let archive_dir = tempfile::TempDir::new().unwrap();
1593 let archive_path = archive_dir.path().join("test.tar.gz");
1594 let src_dir = tempfile::TempDir::new().unwrap();
1595 std::fs::write(src_dir.path().join("hello.txt"), b"hello world").unwrap();
1596 create_archive(&archive_path, &[src_dir.path()], &CreationConfig::default()).unwrap();
1597
1598 let dest = tempfile::TempDir::new().unwrap();
1599 let mut progress = ByteTracker { total: 0 };
1600 let report = extract_archive_with_progress(
1601 &archive_path,
1602 dest.path(),
1603 &SecurityConfig::default(),
1604 &mut progress,
1605 )
1606 .unwrap();
1607
1608 assert!(
1609 report.bytes_written > 0,
1610 "report.bytes_written must be > 0, got {}",
1611 report.bytes_written
1612 );
1613 assert!(
1614 progress.total > 0,
1615 "on_bytes_written must be called with > 0 bytes for TAR, got {}",
1616 progress.total
1617 );
1618 }
1619
1620 #[test]
1623 fn test_on_bytes_written_called_for_zip() {
1624 use crate::ProgressCallback;
1625 use std::path::Path;
1626
1627 struct ByteTracker {
1628 total: u64,
1629 }
1630
1631 impl ProgressCallback for ByteTracker {
1632 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1633
1634 fn on_bytes_written(&mut self, bytes: u64) {
1635 self.total += bytes;
1636 }
1637
1638 fn on_entry_complete(&mut self, _path: &Path) {}
1639
1640 fn on_complete(&mut self) {}
1641 }
1642
1643 let tmp = tempfile::TempDir::new().unwrap();
1644 let archive_path = tmp.path().join("test.zip");
1645 let src_dir = tempfile::TempDir::new().unwrap();
1646 std::fs::write(src_dir.path().join("data.txt"), b"hello world").unwrap();
1647 let config = CreationConfig::default().with_format(Some(CreatableFormat::Zip));
1648 create_archive(&archive_path, &[src_dir.path()], &config).unwrap();
1649
1650 let dest = tempfile::TempDir::new().unwrap();
1651 let mut progress = ByteTracker { total: 0 };
1652 let report = extract_archive_with_progress(
1653 &archive_path,
1654 dest.path(),
1655 &SecurityConfig::default(),
1656 &mut progress,
1657 )
1658 .unwrap();
1659
1660 assert!(
1661 report.bytes_written > 0,
1662 "report.bytes_written must be > 0, got {}",
1663 report.bytes_written
1664 );
1665 assert!(
1666 progress.total > 0,
1667 "on_bytes_written must be called with > 0 bytes for ZIP, got {}",
1668 progress.total
1669 );
1670 }
1671
1672 #[test]
1675 fn test_on_bytes_written_called_for_sevenz() {
1676 use crate::ProgressCallback;
1677 use std::path::Path;
1678
1679 struct ByteTracker {
1680 total: u64,
1681 }
1682
1683 impl ProgressCallback for ByteTracker {
1684 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1685
1686 fn on_bytes_written(&mut self, bytes: u64) {
1687 self.total += bytes;
1688 }
1689
1690 fn on_entry_complete(&mut self, _path: &Path) {}
1691
1692 fn on_complete(&mut self) {}
1693 }
1694
1695 let fixture =
1696 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/simple.7z");
1697
1698 let dest = tempfile::TempDir::new().unwrap();
1699 let mut progress = ByteTracker { total: 0 };
1700 let report = extract_archive_with_progress(
1701 &fixture,
1702 dest.path(),
1703 &SecurityConfig::default(),
1704 &mut progress,
1705 )
1706 .unwrap();
1707
1708 assert!(
1709 report.bytes_written > 0,
1710 "report.bytes_written must be > 0, got {}",
1711 report.bytes_written
1712 );
1713 assert!(
1714 progress.total > 0,
1715 "on_bytes_written must be called with > 0 bytes for 7z, got {}",
1716 progress.total
1717 );
1718 }
1719
1720 #[test]
1723 fn test_tar_hardlink_calls_on_bytes_written() {
1724 use crate::ProgressCallback;
1725 use crate::formats::TarArchive;
1726 use crate::formats::traits::ArchiveFormat;
1727 use std::io::Cursor;
1728 use std::path::Path;
1729
1730 struct ByteTracker {
1731 total: u64,
1732 }
1733
1734 impl ProgressCallback for ByteTracker {
1735 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {}
1736
1737 fn on_bytes_written(&mut self, bytes: u64) {
1738 self.total += bytes;
1739 }
1740
1741 fn on_entry_complete(&mut self, _path: &Path) {}
1742
1743 fn on_complete(&mut self) {}
1744 }
1745
1746 let content = b"hello hardlink";
1748 let tar_data = {
1749 let mut builder = tar::Builder::new(Vec::new());
1750
1751 let mut header = tar::Header::new_gnu();
1752 header.set_size(content.len() as u64);
1753 header.set_mode(0o644);
1754 header.set_entry_type(tar::EntryType::Regular);
1755 header.set_cksum();
1756 builder
1757 .append_data(&mut header, "original.txt", content.as_ref())
1758 .unwrap();
1759
1760 let mut hdr = tar::Header::new_gnu();
1761 hdr.set_size(0);
1762 hdr.set_mode(0o644);
1763 hdr.set_entry_type(tar::EntryType::Link);
1764 hdr.set_link_name("original.txt").unwrap();
1765 hdr.set_cksum();
1766 builder
1767 .append_data(&mut hdr, "link.txt", std::io::empty())
1768 .unwrap();
1769
1770 builder.into_inner().unwrap()
1771 };
1772
1773 let temp = tempfile::TempDir::new().unwrap();
1774 let mut config = SecurityConfig::default();
1775 config.allowed.hardlinks = true;
1776 let config = config.validate().unwrap();
1777
1778 let mut archive = TarArchive::new(Cursor::new(tar_data));
1779 let mut progress = ByteTracker { total: 0 };
1780 let report = archive
1781 .extract(
1782 temp.path(),
1783 &config,
1784 &ExtractionOptions::default(),
1785 &mut progress,
1786 )
1787 .unwrap();
1788
1789 let expected = (content.len() as u64) * 2;
1792 assert_eq!(
1793 progress.total, expected,
1794 "on_bytes_written must report bytes for both original and hardlink copy, \
1795 got {} (report.bytes_written={})",
1796 progress.total, report.bytes_written
1797 );
1798 }
1799
1800 #[test]
1803 fn test_tar_on_entry_complete_called_on_path_traversal_error() {
1804 use crate::ProgressCallback;
1805 use crate::formats::TarArchive;
1806 use crate::formats::traits::ArchiveFormat;
1807 use std::io::Cursor;
1808 use std::path::Path;
1809
1810 struct SymmetryTracker {
1811 started: usize,
1812 completed: usize,
1813 }
1814
1815 impl ProgressCallback for SymmetryTracker {
1816 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1817 self.started += 1;
1818 }
1819
1820 fn on_bytes_written(&mut self, _bytes: u64) {}
1821
1822 fn on_entry_complete(&mut self, _path: &Path) {
1823 self.completed += 1;
1824 }
1825
1826 fn on_complete(&mut self) {}
1827 }
1828
1829 let tar_data = make_raw_tar_single(b"../../etc/passwd", b"evil");
1832
1833 let temp = tempfile::TempDir::new().unwrap();
1834 let mut archive = TarArchive::new(Cursor::new(tar_data));
1835 let mut progress = SymmetryTracker {
1836 started: 0,
1837 completed: 0,
1838 };
1839 let result = archive.extract(
1840 temp.path(),
1841 &SecurityConfig::default().validate().unwrap(),
1842 &ExtractionOptions::default(),
1843 &mut progress,
1844 );
1845
1846 assert!(result.is_err(), "traversal entry must be rejected");
1847 assert_eq!(
1848 progress.started, progress.completed,
1849 "on_entry_complete must be called for every on_entry_start, \
1850 even when extraction fails: started={}, completed={}",
1851 progress.started, progress.completed
1852 );
1853 }
1854
1855 #[test]
1858 fn test_zip_on_entry_complete_called_on_path_traversal_error() {
1859 use crate::ProgressCallback;
1860 use crate::formats::ZipArchive;
1861 use crate::formats::traits::ArchiveFormat;
1862 use std::io::Cursor;
1863 use std::path::Path;
1864
1865 struct SymmetryTracker {
1866 started: usize,
1867 completed: usize,
1868 }
1869
1870 impl ProgressCallback for SymmetryTracker {
1871 fn on_entry_start(&mut self, _path: &Path, _total: usize, _current: usize) {
1872 self.started += 1;
1873 }
1874
1875 fn on_bytes_written(&mut self, _bytes: u64) {}
1876
1877 fn on_entry_complete(&mut self, _path: &Path) {
1878 self.completed += 1;
1879 }
1880
1881 fn on_complete(&mut self) {}
1882 }
1883
1884 let zip_data = make_zip_with_traversal(b"../../etc/passwd", b"evil");
1886
1887 let temp = tempfile::TempDir::new().unwrap();
1888 let mut archive = ZipArchive::new(Cursor::new(zip_data)).unwrap();
1889 let mut progress = SymmetryTracker {
1890 started: 0,
1891 completed: 0,
1892 };
1893 let result = archive.extract(
1894 temp.path(),
1895 &SecurityConfig::default().validate().unwrap(),
1896 &ExtractionOptions::default(),
1897 &mut progress,
1898 );
1899
1900 assert!(result.is_err(), "traversal entry must be rejected");
1901 assert_eq!(
1902 progress.started, progress.completed,
1903 "on_entry_complete must be called for every on_entry_start in ZIP, \
1904 even when extraction fails: started={}, completed={}",
1905 progress.started, progress.completed
1906 );
1907 }
1908
1909 fn make_raw_tar_single(path: &[u8], data: &[u8]) -> Vec<u8> {
1912 let mut out = Vec::new();
1913 let mut header = [0u8; 512];
1914
1915 let path_len = path.len().min(100);
1916 header[..path_len].copy_from_slice(&path[..path_len]);
1917 header[100..108].copy_from_slice(b"0000644\0");
1918 header[108..116].copy_from_slice(b"0000000\0");
1919 header[116..124].copy_from_slice(b"0000000\0");
1920 let size_str = format!("{:011o}\0", data.len());
1921 header[124..136].copy_from_slice(size_str.as_bytes());
1922 header[136..148].copy_from_slice(b"00000000000\0");
1923 header[156] = b'0';
1924 header[257..263].copy_from_slice(b"ustar ");
1925 header[263..265].copy_from_slice(b" \0");
1926 header[148..156].copy_from_slice(b" ");
1927 let checksum: u32 = header.iter().map(|&b| u32::from(b)).sum();
1928 let ck_str = format!("{checksum:06o}\0 ");
1929 header[148..156].copy_from_slice(ck_str.as_bytes());
1930
1931 out.extend_from_slice(&header);
1932 out.extend_from_slice(data);
1933 let rem = data.len() % 512;
1934 if rem != 0 {
1935 out.extend(std::iter::repeat_n(0u8, 512 - rem));
1936 }
1937 out.extend(std::iter::repeat_n(0u8, 1024));
1938 out
1939 }
1940
1941 fn make_zip_with_traversal(path: &[u8], data: &[u8]) -> Vec<u8> {
1944 let entry = RawEntry {
1945 name: path.to_vec(),
1946 date: 0,
1947 ..RawEntry::stored("", data)
1948 };
1949 RawZip::new(vec![entry]).build().bytes
1950 }
1951}