use super::common::*;
use crate::{
BlockFrame, COMMIT_HEADER_FIXED_SIZE, CONTAINER_HEADER_SIZE, CommitHeader,
CommitValidationLimits, ContainerHeader, HEADER_OFFSET_SIZE, HeaderFrame, Toc, TocChange,
ValidatedCommit,
};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{self, Read, Seek};
use xxhash_rust::xxh3::Xxh3;
#[cfg(not(target_os = "wasi"))]
use super::worker_priority::{worker_pool, worker_priority};
#[cfg(not(target_os = "wasi"))]
use rayon::prelude::*;
pub fn check_archive_with_recovery(
path: &str,
recover: bool,
password: Option<&[u8]>,
) -> Result<CheckReport, Box<dyn std::error::Error>> {
check_archive_with_recovery_progress(path, recover, password, None)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckReport {
pub commits: u64,
pub checked_blocks: u64,
pub encrypted_blocks: u64,
pub recoveries: u64,
pub logical_state_readable: bool,
pub recovery_messages: Vec<String>,
}
pub fn check_archive_with_recovery_progress(
path: &str,
recover: bool,
password: Option<&[u8]>,
progress: Option<&dyn Progress>,
) -> Result<CheckReport, Box<dyn std::error::Error>> {
let passwords = PasswordSet::new(password.map(<[u8]>::to_vec));
check_archive_with_recovery_and_passwords_progress(path, recover, &passwords, progress)
}
pub fn check_archive_with_recovery_and_passwords(
path: &str,
recover: bool,
passwords: &PasswordSet,
) -> Result<CheckReport, Box<dyn std::error::Error>> {
check_archive_with_recovery_and_passwords_progress(path, recover, passwords, None)
}
pub fn check_archive_with_recovery_and_passwords_progress(
path: &str,
recover: bool,
passwords: &PasswordSet,
progress: Option<&dyn Progress>,
) -> Result<CheckReport, Box<dyn std::error::Error>> {
let progress = ProgressReporter::new(progress);
progress.check_cancelled()?;
let mut file = File::open(path)?;
let container = ContainerHeader::read_from(&mut file)?;
if let Some(callback) = progress.0 {
callback.set_total(file.metadata()?.len().saturating_sub(CONTAINER_HEADER_SIZE));
}
let limits = CommitValidationLimits::default();
let mut toc = Toc::default();
let mut logical_state_readable = true;
let mut commits = 0_u64;
let mut checked_blocks = 0_u64;
let mut encrypted_blocks = 0_u64;
let mut recoveries = 0_u64;
let mut recovery_messages = Vec::new();
let mut visited_offsets = HashSet::new();
#[cfg(not(target_os = "wasi"))]
let workers = available_compression_workers();
#[cfg(target_os = "wasi")]
let workers = 1;
#[cfg(not(target_os = "wasi"))]
let pool = worker_pool(workers, "zarc-check", worker_priority())?;
let mut header_offset = container.first_header_offset;
while header_offset != 0 {
progress.check_cancelled()?;
if !visited_offsets.insert(header_offset) {
return Err("archive commit chain contains a cycle".into());
}
let mut commit_start = header_offset;
let (commit_header, mut data_start, mut next_header_offset) =
match read_commit_at_offset(&mut file, header_offset, limits) {
Ok(entry) => entry,
Err(error) if recover => {
let Some((offset, ch, ds, next)) = find_next_valid_commit(
&mut file,
commit_start.saturating_add(1),
limits,
progress,
)?
else {
return Err(error);
};
if !visited_offsets.insert(offset) {
return Err("archive commit chain contains a cycle".into());
}
recovery_messages.push(format!(
"warning: recovered commit framing at offset {offset}"
));
recoveries += 1;
toc = Toc::default();
logical_state_readable = false;
commit_start = offset;
(ch, ds, next)
}
Err(error) => return Err(error),
};
let checked = match read_checked_commit(
&mut file,
commit_header.clone(),
limits,
passwords,
progress,
workers,
#[cfg(not(target_os = "wasi"))]
&pool,
) {
Ok(commit) => commit,
Err(error) if recover => {
let Some((offset, ch, ds, next)) = find_next_valid_commit(
&mut file,
data_start.saturating_add(1),
limits,
progress,
)?
else {
return Err(error);
};
if !visited_offsets.insert(offset) {
return Err("archive commit chain contains a cycle".into());
}
recovery_messages.push(format!(
"warning: recovered commit framing at offset {offset}"
));
recoveries += 1;
toc = Toc::default();
logical_state_readable = false;
commit_start = offset;
data_start = ds;
next_header_offset = next;
read_checked_commit(
&mut file,
ch,
limits,
passwords,
progress,
workers,
#[cfg(not(target_os = "wasi"))]
&pool,
)?
}
Err(error) => return Err(error),
};
let CheckedCommit {
validated,
dek,
block_sizes,
block_offsets,
single_checksums,
multi_checksums,
} = checked;
let commit_end = data_start + validated.commit_header.data_section_size;
progress.inc(commit_end.saturating_sub(commit_start));
progress.set_message(format!(
"Checking commit {:08x}",
u32::from_le_bytes(validated.commit_header.commit_id)
));
for size in block_sizes.values() {
if size.is_some() {
checked_blocks += 1;
} else {
encrypted_blocks += 1;
}
}
if let Some(header) = &validated.logical_header {
if logical_state_readable {
for (change_index, change) in header.changes.iter().enumerate() {
if let TocChange::PutFile { path, entry } = change {
if entry.source_commit.is_some() {
continue;
}
let mut decoded_size = 0_u64;
let mut all_blocks_readable = true;
for index in &entry.block_indices {
progress.check_cancelled()?;
match block_sizes.get(index) {
Some(Some(size)) => {
if let Some(offset) = entry.offset_in_block {
if entry.block_indices.as_slice() != [*index] {
return Err(crate::FramingError::InvalidSize.into());
}
let start = usize::try_from(offset)
.map_err(|_| "packed file offset overflow")?;
let file_size = usize::try_from(entry.size)
.map_err(|_| "packed file size overflow")?;
start
.checked_add(file_size)
.filter(|&end| end <= *size)
.ok_or(crate::FramingError::InvalidSize)?;
decoded_size = decoded_size
.checked_add(entry.size)
.ok_or("decoded file size overflow")?;
} else {
decoded_size = decoded_size
.checked_add(*size as u64)
.ok_or("decoded file size overflow")?;
}
}
Some(None) => all_blocks_readable = false,
None => {
return Err(format!(
"TOC references unavailable block {index} for {path}"
)
.into());
}
}
}
if all_blocks_readable && decoded_size != entry.size {
return Err(format!(
"decoded size mismatch for {path}: expected {} bytes, got {decoded_size}",
entry.size
)
.into());
}
if all_blocks_readable && let Some(expected) = entry.checksum {
let actual = if entry.block_indices.len() == 1 {
single_checksums
.get(&change_index)
.ok_or(crate::FramingError::InvalidSize)?
.clone()?
} else if let Some(actual) = multi_checksums.get(&change_index) {
*actual
} else if entry.block_indices.is_empty() {
Xxh3::new().digest()
} else {
checksum_reordered_blocks(
&mut file,
&ReorderedChecksum {
validated: &validated,
dek: dek.as_deref(),
block_offsets: &block_offsets,
limits,
progress,
workers,
#[cfg(not(target_os = "wasi"))]
pool: &pool,
},
&entry.block_indices,
)?
};
if expected != actual {
return Err(format!("file checksum mismatch for {path}").into());
}
}
}
}
Toc::check_available_blocks(&header.changes, &validated.block_indices)?;
toc.apply_archive_commit(validated.commit_header.commit_id, &header.changes)?;
}
} else {
logical_state_readable = false;
}
file.seek(io::SeekFrom::Start(commit_end))?;
commits += 1;
header_offset = next_header_offset;
}
Ok(CheckReport {
commits,
checked_blocks,
encrypted_blocks,
recoveries,
logical_state_readable,
recovery_messages,
})
}
struct CheckedCommit {
validated: ValidatedCommit,
dek: Option<zeroize::Zeroizing<[u8; crate::DEK_SIZE]>>,
block_sizes: HashMap<u32, Option<usize>>,
block_offsets: HashMap<u32, u64>,
single_checksums: HashMap<usize, Result<u64, crate::FramingError>>,
multi_checksums: HashMap<usize, u64>,
}
struct CheckedBlock {
index: u32,
offset: u64,
size: Option<usize>,
checksums: Vec<(usize, Result<u64, crate::FramingError>)>,
contents: Option<Vec<u8>>,
}
struct ReorderedChecksum<'a> {
validated: &'a ValidatedCommit,
dek: Option<&'a [u8; crate::DEK_SIZE]>,
block_offsets: &'a HashMap<u32, u64>,
limits: CommitValidationLimits,
progress: ProgressReporter<'a>,
workers: usize,
#[cfg(not(target_os = "wasi"))]
pool: &'a rayon::ThreadPool,
}
fn checksum_reordered_blocks(
file: &mut File,
context: &ReorderedChecksum<'_>,
indices: &[u32],
) -> Result<u64, crate::FramingError> {
let mut checksum = Xxh3::new();
for batch in indices.chunks(context.workers) {
let mut blocks = Vec::with_capacity(batch.len());
for index in batch {
context.progress.check_cancelled()?;
let offset = context
.block_offsets
.get(index)
.ok_or(crate::FramingError::InvalidSize)?;
file.seek(io::SeekFrom::Start(*offset))?;
blocks.push(BlockFrame::read_from(
file,
context.limits.max_frame_payload_size,
)?);
}
let decode = |block: &BlockFrame| -> Result<Vec<u8>, crate::FramingError> {
context.progress.check_cancelled()?;
if block.flags & crate::BLOCK_FLAG_ENCRYPTED != 0 {
let key = context.dek.ok_or(crate::FramingError::InvalidDescriptor)?;
let algorithm = encryption_algorithm(&context.validated.encryption)
.ok_or(crate::FramingError::InvalidDescriptor)?;
block.uncompressed_encrypted_with_checksum_validation(
&context.validated.commit_header,
key,
algorithm,
context.limits.max_uncompressed_block_size,
false,
)
} else {
block.uncompressed_with_checksum_validation(
context.limits.max_uncompressed_block_size,
false,
)
}
};
#[cfg(not(target_os = "wasi"))]
let decoded: Result<Vec<_>, _> = context
.pool
.install(|| blocks.par_iter().map(decode).collect());
#[cfg(target_os = "wasi")]
let decoded: Result<Vec<_>, _> = blocks.iter().map(decode).collect();
for contents in decoded? {
checksum.update(&contents);
}
}
Ok(checksum.digest())
}
fn read_checked_commit(
file: &mut File,
commit_header: CommitHeader,
limits: CommitValidationLimits,
passwords: &PasswordSet,
progress: ProgressReporter<'_>,
workers: usize,
#[cfg(not(target_os = "wasi"))] pool: &rayon::ThreadPool,
) -> Result<CheckedCommit, Box<dyn std::error::Error>> {
let data_start = file.stream_position()?;
let (validated, dek) =
read_commit_framing_with_passwords(file, commit_header, limits, passwords)?;
progress.set_message(format!(
"Checking commit {:08x}",
u32::from_le_bytes(validated.commit_header.commit_id)
));
let mut references: HashMap<u32, Vec<(usize, &crate::FileEntry)>> = HashMap::new();
let mut multi_references: HashMap<u32, Vec<(usize, usize)>> = HashMap::new();
let mut multi_states: HashMap<usize, (usize, usize, Xxh3, bool)> = HashMap::new();
if let Some(header) = &validated.logical_header {
for (change_index, change) in header.changes.iter().enumerate() {
if let TocChange::PutFile { entry, .. } = change
&& entry.source_commit.is_none()
&& entry.checksum.is_some()
{
if let [index] = entry.block_indices.as_slice() {
references
.entry(*index)
.or_default()
.push((change_index, entry));
} else if entry.block_indices.len() > 1 && entry.offset_in_block.is_none() {
multi_states.insert(
change_index,
(0, entry.block_indices.len(), Xxh3::new(), true),
);
for (position, index) in entry.block_indices.iter().enumerate() {
multi_references
.entry(*index)
.or_default()
.push((change_index, position));
}
}
}
}
}
let algorithm = encryption_algorithm(&validated.encryption);
file.seek(io::SeekFrom::Start(data_start))?;
let mut reader = file.take(validated.commit_header.data_section_size);
let mut block_sizes = HashMap::with_capacity(validated.block_count as usize);
let mut block_offsets = HashMap::with_capacity(validated.block_count as usize);
let mut single_checksums = HashMap::new();
while reader.limit() != 0 {
let mut batch = Vec::with_capacity(workers);
let mut batch_bytes = 0_usize;
while reader.limit() != 0 && batch.len() < workers && batch_bytes < 128 * 1024 * 1024 {
progress.check_cancelled()?;
let offset = data_start
.checked_add(validated.commit_header.data_section_size - reader.limit())
.ok_or("block offset overflow")?;
let block = BlockFrame::read_from(&mut reader, limits.max_frame_payload_size)?;
batch_bytes = batch_bytes.saturating_add(block.payload.len());
batch.push((offset, block));
}
let check =
|(offset, block): &(u64, BlockFrame)| -> Result<CheckedBlock, crate::FramingError> {
progress.check_cancelled()?;
let contents = if block.flags & crate::BLOCK_FLAG_ENCRYPTED != 0 {
match (dek.as_ref(), algorithm) {
(Some(key), Some(algorithm)) => {
Some(block.uncompressed_encrypted_with_checksum_validation(
&validated.commit_header,
key,
algorithm,
limits.max_uncompressed_block_size,
false,
)?)
}
_ => None,
}
} else {
Some(block.uncompressed_with_checksum_validation(
limits.max_uncompressed_block_size,
false,
)?)
};
let mut checksums = Vec::new();
if let Some(contents) = &contents
&& let Some(entries) = references.get(&block.block_index)
{
for (change_index, entry) in entries {
let bytes = if let Some(offset) = entry.offset_in_block {
usize::try_from(entry.size)
.ok()
.and_then(|size| (offset as usize).checked_add(size))
.and_then(|end| contents.get(offset as usize..end))
.ok_or(crate::FramingError::InvalidSize)
} else {
Ok(contents.as_slice())
};
checksums.push((*change_index, bytes.map(xxhash_rust::xxh3::xxh3_64)));
}
}
Ok(CheckedBlock {
index: block.block_index,
offset: *offset,
size: contents.as_ref().map(Vec::len),
checksums,
contents,
})
};
#[cfg(not(target_os = "wasi"))]
let results: Result<Vec<_>, _> = pool.install(|| batch.par_iter().map(check).collect());
#[cfg(target_os = "wasi")]
let results: Result<Vec<_>, _> = batch.iter().map(check).collect();
for result in results? {
progress.inc(result.size.map_or(1, |size| size as u64));
if let Some(entries) = multi_references.get(&result.index) {
for (change_index, position) in entries {
let (next, _, checksum, valid) = multi_states
.get_mut(change_index)
.expect("multi-block reference has a checksum state");
if *next == *position
&& let Some(contents) = &result.contents
{
checksum.update(contents);
*next += 1;
} else {
*valid = false;
}
}
}
block_sizes.insert(result.index, result.size);
block_offsets.insert(result.index, result.offset);
single_checksums.extend(result.checksums);
}
}
Ok(CheckedCommit {
validated,
dek,
block_sizes,
block_offsets,
single_checksums,
multi_checksums: multi_states
.into_iter()
.filter_map(|(index, (next, total, checksum, valid))| {
(valid && next == total).then(|| (index, checksum.digest()))
})
.collect(),
})
}
fn find_next_valid_commit(
file: &mut File,
start: u64,
limits: CommitValidationLimits,
progress: ProgressReporter<'_>,
) -> io::Result<Option<(u64, CommitHeader, u64, u64)>> {
let file_len = file.metadata()?.len();
let min_size = COMMIT_HEADER_FIXED_SIZE as u64 + HEADER_OFFSET_SIZE;
if start.saturating_add(min_size) > file_len {
return Ok(None);
}
let mut offset = start;
while offset.saturating_add(min_size) <= file_len {
progress.check_cancelled()?;
file.seek(io::SeekFrom::Start(offset))?;
let header_frame = match HeaderFrame::read_from(file, limits.max_frame_payload_size) {
Ok(frame) => frame,
Err(_) => {
offset += 1;
continue;
}
};
let commit_header = header_frame.commit_header.clone();
if commit_header.validate().is_err() {
offset += 1;
continue;
}
let data_start = match offset.checked_sub(commit_header.data_section_size) {
Some(ds) => ds,
None => {
offset += 1;
continue;
}
};
let next_offset_pos = match data_start.checked_sub(HEADER_OFFSET_SIZE) {
Some(pos) => pos,
None => {
offset += 1;
continue;
}
};
let commit_end = offset
.checked_add(u64::from(commit_header.header_frame_size))
.and_then(|size| size.checked_add(HEADER_OFFSET_SIZE));
if !commit_end.is_some_and(|end| end <= file_len) {
offset += 1;
continue;
}
file.seek(io::SeekFrom::Start(data_start))?;
if ValidatedCommit::read_body(file, commit_header.clone(), limits).is_err() {
offset += 1;
continue;
}
file.seek(io::SeekFrom::Start(next_offset_pos))?;
let mut next_bytes = [0u8; 8];
file.read_exact(&mut next_bytes)?;
let next_header_offset = u64::from_le_bytes(next_bytes);
if next_header_offset != 0 && next_header_offset >= file_len {
offset += 1;
continue;
}
file.seek(io::SeekFrom::Start(data_start))?;
return Ok(Some((
offset,
commit_header,
data_start,
next_header_offset,
)));
}
Ok(None)
}
#[cfg(all(test, not(target_os = "wasi")))]
mod tests {
use super::*;
use std::io::Write;
use std::sync::Mutex;
use std::time::Duration;
struct WorkerProgress(Mutex<HashSet<String>>);
impl Progress for WorkerProgress {
fn message(&self, _: &str) {}
fn advance(&self, _: u64) {}
fn is_cancelled(&self) -> bool {
if let Some(name) = std::thread::current().name()
&& name.starts_with("check-test-")
{
self.0.lock().unwrap().insert(name.to_owned());
std::thread::sleep(Duration::from_millis(5));
}
false
}
}
fn write_fixture(path: &std::path::Path, corrupt_checksum: bool) -> (u64, CommitHeader) {
let contents: Vec<Vec<u8>> = (0..16).map(|index| vec![index as u8; 256 * 1024]).collect();
let blocks: Vec<_> = contents
.iter()
.enumerate()
.map(|(index, bytes)| BlockFrame::from_stored(index as u32, bytes).unwrap())
.collect();
let data_size = blocks
.iter()
.map(|block| block.encoded_size().unwrap() as u64)
.sum();
let hash = xxhash_rust::xxh3::xxh3_64;
let multi = [contents[1].as_slice(), contents[2].as_slice()].concat();
let reversed = [contents[2].as_slice(), contents[1].as_slice()].concat();
let entries = [
(
"packed-a",
crate::FileEntry::new(20, vec![0])
.unwrap()
.with_block_offset(0)
.with_checksum(hash(&contents[0][..20])),
),
(
"packed-b",
crate::FileEntry::new(20, vec![0])
.unwrap()
.with_block_offset(20)
.with_checksum(hash(&contents[0][20..40]) ^ u64::from(corrupt_checksum)),
),
(
"ordered",
crate::FileEntry::new(multi.len() as u64, vec![1, 2])
.unwrap()
.with_checksum(hash(&multi)),
),
(
"reversed",
crate::FileEntry::new(reversed.len() as u64, vec![2, 1])
.unwrap()
.with_checksum(hash(&reversed)),
),
];
let logical = crate::LogicalHeader::new(
entries
.into_iter()
.map(|(name, entry)| TocChange::PutFile {
path: crate::ArchivePath::new(name).unwrap(),
entry,
})
.collect(),
);
let bytes = logical.encode().unwrap();
let provisional = CommitHeader::new(0, [1, 0, 0, 0], data_size, 0).unwrap();
let probe = HeaderFrame::from_uncompressed(
provisional,
&bytes,
crate::UNENCRYPTED_DESCRIPTOR.to_vec(),
1,
)
.unwrap();
let header = CommitHeader::new(
0,
[1, 0, 0, 0],
data_size,
probe.encoded_size().unwrap() as u32,
)
.unwrap();
let frame = HeaderFrame::from_uncompressed(
header.clone(),
&bytes,
crate::UNENCRYPTED_DESCRIPTOR.to_vec(),
1,
)
.unwrap();
let offset = CONTAINER_HEADER_SIZE + HEADER_OFFSET_SIZE + data_size;
let mut file = File::create(path).unwrap();
ContainerHeader::new(offset).write_to(&mut file).unwrap();
file.write_all(&0_u64.to_le_bytes()).unwrap();
for block in blocks {
block.write_to(&mut file).unwrap();
}
frame.write_to(&mut file).unwrap();
file.write_all(&offset.to_le_bytes()).unwrap();
(offset, header)
}
#[test]
fn checks_blocks_in_parallel_and_handles_packed_and_reordered_files() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("check.zar");
let (offset, header) = write_fixture(&path, false);
let progress = WorkerProgress(Mutex::new(HashSet::new()));
let pool = worker_pool(4, "check-test", None).unwrap();
let limits = CommitValidationLimits::default();
let mut file = File::open(&path).unwrap();
read_commit_at_offset(&mut file, offset, limits).unwrap();
let checked = read_checked_commit(
&mut file,
header,
limits,
&PasswordSet::default(),
ProgressReporter::new(Some(&progress)),
4,
&pool,
)
.unwrap();
assert_eq!(checked.block_sizes.len(), 16);
assert_eq!(checked.single_checksums.len(), 2);
assert!(checked.multi_checksums.contains_key(&2));
assert!(!checked.multi_checksums.contains_key(&3));
assert_eq!(progress.0.lock().unwrap().len(), 4);
let report = check_archive_with_recovery(path.to_str().unwrap(), false, None).unwrap();
assert_eq!(report.checked_blocks, 16);
write_fixture(&path, true);
let error = check_archive_with_recovery(path.to_str().unwrap(), false, None).unwrap_err();
assert!(
error
.to_string()
.contains("file checksum mismatch for packed-b")
);
}
}