use std::collections::BTreeMap;
use std::io;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::paths::{
archive_path_bytes_to_display, archive_path_bytes_to_hex, validate_target_components,
};
use crate::{ArchiveFormat, Result};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct VerifyOptions {
pub read_payloads: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VerifyReport {
pub path: String,
pub format: ArchiveFormat,
pub file_count: usize,
pub named_entry_count: usize,
pub unnameable_entries: usize,
pub rewritable: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub rewrite_blocker: Option<String>,
pub duplicate_normalized_paths: Vec<VerifyPathIssue>,
pub unsafe_paths: Vec<VerifyPathIssue>,
pub payloads_read: Option<usize>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VerifyPathIssue {
pub path: String,
pub path_bytes_hex: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub raw_path_bytes_hex: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub colliding_raw_path_bytes_hex: Option<String>,
}
pub fn verify_archive(path: &Path, options: &VerifyOptions) -> Result<VerifyReport> {
let archive = crate::loaded::LoadedArchive::open(path)?;
verify_loaded_archive(&path.display().to_string(), archive.as_ref(), *options)
}
pub(crate) fn verify_loaded_archive(
label: &str,
archive: crate::loaded::LoadedArchiveRef<'_>,
options: VerifyOptions,
) -> Result<VerifyReport> {
let info = crate::archive::archive_info_ref(label, archive);
let entries = archive.list_loaded_entries()?;
let mut seen: BTreeMap<&[u8], &[u8]> = BTreeMap::new();
let mut duplicate_normalized_paths = Vec::new();
let mut unsafe_paths = Vec::new();
for entry in &entries {
if let Some(previous_raw_path) = seen.get(entry.path.as_slice()) {
duplicate_normalized_paths.push(duplicate_path_issue(
&entry.path,
previous_raw_path,
&entry.raw_path,
));
} else {
seen.insert(&entry.path, &entry.raw_path);
}
if crate::paths::validate_archive_path_bytes_for_extraction(&entry.raw_path).is_err()
|| validate_target_components(&entry.path).is_err()
{
unsafe_paths.push(unsafe_path_issue(&entry.path, &entry.raw_path));
}
}
let payloads_read = if options.read_payloads && duplicate_normalized_paths.is_empty() {
let mut sink = io::sink();
for entry in &entries {
archive.extract_normalized_entry_path_to_writer(&entry.path, &mut sink)?;
}
Some(entries.len())
} else {
None
};
let mut warnings = Vec::new();
if info.has_unnameable_entries {
warnings.push("archive contains entries without recoverable path names".to_string());
}
if !duplicate_normalized_paths.is_empty() {
warnings.push("archive contains duplicate normalized paths".to_string());
}
if options.read_payloads && !duplicate_normalized_paths.is_empty() {
warnings.push(
"payload read verification skipped because duplicate normalized paths prevent per-entry coverage"
.to_string(),
);
}
if !unsafe_paths.is_empty() {
warnings.push("archive contains paths unsafe to extract directly".to_string());
}
Ok(VerifyReport {
path: info.path,
format: info.format,
file_count: info.file_count,
named_entry_count: info.named_entry_count,
unnameable_entries: info.file_count.saturating_sub(info.named_entry_count),
rewritable: info.rewritable,
rewrite_blocker: info.rewrite_blocker,
duplicate_normalized_paths,
unsafe_paths,
payloads_read,
warnings,
})
}
fn unsafe_path_issue(path: &[u8], raw_path: &[u8]) -> VerifyPathIssue {
VerifyPathIssue {
path: archive_path_bytes_to_display(path),
path_bytes_hex: archive_path_bytes_to_hex(path),
raw_path_bytes_hex: Some(archive_path_bytes_to_hex(raw_path)),
colliding_raw_path_bytes_hex: None,
}
}
fn duplicate_path_issue(
path: &[u8],
first_raw_path: &[u8],
duplicate_raw_path: &[u8],
) -> VerifyPathIssue {
VerifyPathIssue {
path: archive_path_bytes_to_display(path),
path_bytes_hex: archive_path_bytes_to_hex(path),
raw_path_bytes_hex: Some(archive_path_bytes_to_hex(duplicate_raw_path)),
colliding_raw_path_bytes_hex: Some(archive_path_bytes_to_hex(first_raw_path)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unsafe_paths_report_the_normalized_key_beside_the_stored_bytes() {
let dir = std::env::temp_dir().join(format!(
"dream_archivetool-verify-unsafe-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let archive = dir.join("unsafe.bsa");
let mut builder = dream_archive::Tes3BsaBuilder::new();
builder.add_bytes(br"ab\cd\C.dds", b"payload").unwrap();
let mut bytes = builder.to_vec().unwrap();
let name = bytes
.windows(11)
.position(|window| window.eq_ignore_ascii_case(br"ab\cd\c.dds"))
.unwrap();
bytes[name..name + 11].copy_from_slice(br"..\..\C.dds");
std::fs::write(&archive, bytes).unwrap();
let report = verify_archive(&archive, &VerifyOptions::default()).unwrap();
assert_eq!(
report.unsafe_paths,
vec![VerifyPathIssue {
path: "../../c.dds".to_string(),
path_bytes_hex: archive_path_bytes_to_hex(b"../../c.dds"),
raw_path_bytes_hex: Some(archive_path_bytes_to_hex(br"..\..\C.dds")),
colliding_raw_path_bytes_hex: None,
}]
);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn duplicate_path_issue_reports_duplicate_then_previous_raw_path() {
let issue = duplicate_path_issue(
b"textures/example.dds",
b"Textures/Example.dds",
b"textures/example.dds",
);
assert_eq!(
issue.path_bytes_hex,
"74657874757265732f6578616d706c652e646473"
);
assert_eq!(
issue.raw_path_bytes_hex.as_deref(),
Some("74657874757265732f6578616d706c652e646473")
);
assert_eq!(
issue.colliding_raw_path_bytes_hex.as_deref(),
Some("54657874757265732f4578616d706c652e646473")
);
}
}