From c2265eb31b8febb3fe59027143ce79e1ed62d41c Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:49:01 +0100 Subject: [PATCH] STRA-338 size: model-format: kar verify_with, integrity pass and row reads split (fn_lines 128->30, complexity 50->10) --- .../src/kar/impl_verifiedkarpleartifact.rs | 124 +--------- .../kar/impl_verifiedkarpleartifact/verify.rs | 218 ++++++++++++++++++ .../src/kar/independent_handles.rs | 160 ++++++++----- crates/model-format/src/kar/read_region.rs | 178 +++++++------- 4 files changed, 419 insertions(+), 261 deletions(-) create mode 100644 crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs index 3f74c4d6..f4998f48 100644 --- a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs @@ -3,6 +3,9 @@ #[allow(unused_imports)] use super::*; +mod verify; +use verify::verify_archive; + impl VerifiedKarPleArtifact { pub fn verify(source: KarImmutableSource, profile: KarPleProfile) -> Result { Self::verify_with(source, profile, None) @@ -25,126 +28,17 @@ impl VerifiedKarPleArtifact { sparse_pin: Option<&[u8; 32]>, ) -> Result { let mut reader = source.inspection; - if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes - || reader.summary.archive_bytes != profile.spec.archive_bytes - || reader.summary.source_bytes != profile.spec.virtual_f32_bytes - || reader.summary.source_digest != profile.spec.virtual_f32_sha256 - { - return Err(KarError::Integrity("KAR archive/provenance identity mismatch")); - } - // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full - // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. - let identity = reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); - let stamps = crate::verify_stamp::global(); - // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). - let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); - let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); - let trusted = attested_memfd || stamped; - let trust = if sparse_pin.is_some() { - KarTrust::SparseExtents - } else if attested_memfd { - KarTrust::AttestedMemfd - } else if stamped { - KarTrust::Stamp - } else { - KarTrust::FullPass - }; - // A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. - if sparse_pin.is_none() && !trusted { - reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; - if let (Some(stamps), Some(before)) = (stamps, identity) - && reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) == Some(before) - { - let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); - } - } - let mut parts = Vec::new(); - let mut books = Vec::new(); - let mut book_at_list = Vec::new(); - parts.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; - books.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; - for p in &profile.spec.parts { - let index = reader - .sources - .iter() - .position(|s| s.name == p.name) - .ok_or(KarError::Profile("KAR PLE partition missing"))?; - let s = &reader.sources[index]; - let record = &reader.directory[index * 192..(index + 1) * 192]; - if s.dimensions != [160, p.row_count] - || s.dtype != 0 - || s.storage_class != 0 - || record[45] != 0 - || u16_at(record, 46) != 32 - || s.planes_min > 2 - || s.planes_max < 2 - || s.digest != p.derived_f32_sha256 - || s.offset != p.derived_f32_offset - { - return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); - } - let scales = u64_at(record, 64); - let planes = s.planes_offset; - let stride = u64::from(s.plane_stride_bytes); - let book_at = u64_at(record, 80).checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; - let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?; - let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); - if book.iter().any(|b| b & 0x7c00 == 0x7c00) { - return Err(KarError::Profile("KAR PLE nonfinite book")); - } - parts.push(VerifiedPart { row_base: p.row_base, row_count: p.row_count, scales, planes, stride }); - books.push(book); - book_at_list.push(book_at); - } - let serve_extents = normalize_extents( - &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, - profile.spec.archive_bytes, - )?; - if let Some(pin) = sparse_pin { - // Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no - // read can land in a hole; then the bytes of the extents must be the pinned ones. - for part in &parts { - for read in part.reads()? { - if !extents_cover(&serve_extents, read.offset, read.len) { - return Err(KarError::Range("KAR PLE read outside the sparse extents")); - } - } - } - let digest = digest_extents(&reader.file, &serve_extents, |_| {})?; - if &digest != pin { - return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); - } - } - let after = reader.file.metadata().map_err(KarError::Io)?; - if after.len() != profile.spec.archive_bytes { - return Err(KarError::Integrity("KAR archive length changed")); - } - // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. - if identity.is_some() && crate::verify_stamp::FileIdentity::of(&after) != identity { - return Err(KarError::Integrity("KAR archive file changed while it was verified")); - } - let startup = KarStartupRead { - trust, - metadata_bytes: reader.metadata_bytes, - book_bytes: 8 * parts.len() as u64, - hashed_bytes: if sparse_pin.is_some() { - extents_bytes(&serve_extents) - } else if trusted { - 0 - } else { - profile.spec.archive_bytes - }, - }; + let checked = verify_archive(&mut reader, &profile, sparse_pin)?; Ok(Self { reader, profile, - parts, - books, + parts: checked.parts, + books: checked.books, handles: std::sync::OnceLock::new(), - serve_extents, + serve_extents: checked.serve_extents, sparse: sparse_pin.is_some(), - startup, - identity: if identity_recheck_enabled() { identity } else { None }, + startup: checked.startup, + identity: checked.identity, }) } /// The ranges of the archive the serve path reads (page-aligned, sorted, merged). diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs new file mode 100644 index 00000000..a3ec4f73 --- /dev/null +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact/verify.rs @@ -0,0 +1,218 @@ +//! The checks `VerifiedKarPleArtifact::verify_with` runs on an inspected archive. + +#[allow(unused_imports)] +use super::*; + +type FileIdentity = crate::verify_stamp::FileIdentity; + +/// What a successful verification leaves behind. +pub(super) struct Checked { + pub(super) parts: Vec, + pub(super) books: Vec<[u16; 4]>, + pub(super) serve_extents: Vec, + pub(super) startup: KarStartupRead, + pub(super) identity: Option, +} + +/// How the archive is vouched for: a stamp for this very file, or the parent's attestation of a memfd. +struct Admission { + identity: Option, + stamps: Option<&'static crate::verify_stamp::VerifyStamps>, + attested_memfd: bool, + stamped: bool, +} + +fn current_identity(reader: &KarInspection) -> Option { + reader.file.metadata().ok().and_then(|m| FileIdentity::of(&m)) +} + +impl Admission { + fn decide(reader: &KarInspection, profile: &KarPleProfile) -> Self { + // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full + // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. + let identity = current_identity(reader); + let stamps = crate::verify_stamp::global(); + // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). + let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); + let stamped = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("kar", &profile.spec.archive_sha256, id)); + Self { identity, stamps, attested_memfd, stamped } + } + + fn trusted(&self) -> bool { + self.attested_memfd || self.stamped + } + + fn trust(&self, sparse: bool) -> KarTrust { + if sparse { + KarTrust::SparseExtents + } else if self.attested_memfd { + KarTrust::AttestedMemfd + } else if self.stamped { + KarTrust::Stamp + } else { + KarTrust::FullPass + } + } + + /// The whole-archive SHA-256 + CRC pass, unless a stamp or an attestation stands in for it. + /// A sparse copy never takes a stamp or an attestation: those speak for the whole archive, which it does not hold. + fn full_pass(&self, reader: &mut KarInspection, profile: &KarPleProfile, sparse: bool) -> Result<(), KarError> { + if sparse || self.trusted() { + return Ok(()); + } + reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; + if let (Some(stamps), Some(before)) = (self.stamps, self.identity) + && current_identity(reader) == Some(before) + { + let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); + } + Ok(()) + } + + fn hashed_bytes(&self, sparse: bool, serve_extents: &[Extent], archive_bytes: u64) -> u64 { + if sparse { + extents_bytes(serve_extents) + } else if self.trusted() { + 0 + } else { + archive_bytes + } + } +} + +pub(super) fn verify_archive( + reader: &mut KarInspection, + profile: &KarPleProfile, + sparse_pin: Option<&[u8; 32]>, +) -> Result { + check_archive_identity(reader, profile)?; + let admission = Admission::decide(reader, profile); + admission.full_pass(reader, profile, sparse_pin.is_some())?; + let (parts, books, book_at_list) = verified_parts(reader, profile)?; + let serve_extents = normalize_extents( + &extents::exact_reads(reader.payload_offset, &parts, &book_at_list)?, + profile.spec.archive_bytes, + )?; + if let Some(pin) = sparse_pin { + check_sparse_extents(reader, &parts, &serve_extents, pin)?; + } + check_unchanged(reader, profile, admission.identity)?; + let sparse = sparse_pin.is_some(); + let startup = KarStartupRead { + trust: admission.trust(sparse), + metadata_bytes: reader.metadata_bytes, + book_bytes: 8 * parts.len() as u64, + hashed_bytes: admission.hashed_bytes(sparse, &serve_extents, profile.spec.archive_bytes), + }; + let identity = if identity_recheck_enabled() { admission.identity } else { None }; + Ok(Checked { parts, books, serve_extents, startup, identity }) +} + +fn check_archive_identity(reader: &KarInspection, profile: &KarPleProfile) -> Result<(), KarError> { + if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes + || reader.summary.archive_bytes != profile.spec.archive_bytes + || reader.summary.source_bytes != profile.spec.virtual_f32_bytes + || reader.summary.source_digest != profile.spec.virtual_f32_sha256 + { + return Err(KarError::Integrity("KAR archive/provenance identity mismatch")); + } + Ok(()) +} + +type Parts = (Vec, Vec<[u16; 4]>, Vec); + +/// The partitions of the profile, found in the archive: their tables, their books and where each book lies. +fn verified_parts(reader: &mut KarInspection, profile: &KarPleProfile) -> Result { + let mut parts = Vec::new(); + let mut books = Vec::new(); + let mut book_at_list = Vec::new(); + parts.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; + books.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; + for p in &profile.spec.parts { + let (part, book, book_at) = verify_partition(reader, p)?; + parts.push(part); + books.push(book); + book_at_list.push(book_at); + } + Ok((parts, books, book_at_list)) +} + +fn verify_partition( + reader: &mut KarInspection, + p: &KarPlePartProvenance, +) -> Result<(VerifiedPart, [u16; 4], u64), KarError> { + let index = + reader.sources.iter().position(|s| s.name == p.name).ok_or(KarError::Profile("KAR PLE partition missing"))?; + let s = &reader.sources[index]; + let record = &reader.directory[index * 192..(index + 1) * 192]; + check_partition_mapping(s, record, p)?; + let scales = u64_at(record, 64); + let planes = s.planes_offset; + let stride = u64::from(s.plane_stride_bytes); + let book_at = u64_at(record, 80).checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; + let book = read_book(&mut reader.file, book_at)?; + let part = VerifiedPart { row_base: p.row_base, row_count: p.row_count, scales, planes, stride }; + Ok((part, book, book_at)) +} + +fn check_partition_mapping(s: &KarTensorSource, record: &[u8], p: &KarPlePartProvenance) -> Result<(), KarError> { + let layout_ok = s.dtype == 0 + && s.storage_class == 0 + && record[45] == 0 + && u16_at(record, 46) == 32 + && s.planes_min <= 2 + && s.planes_max >= 2; + let identity_ok = + s.dimensions == [160, p.row_count] && s.digest == p.derived_f32_sha256 && s.offset == p.derived_f32_offset; + if !layout_ok || !identity_ok { + return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); + } + Ok(()) +} + +fn read_book(file: &mut File, book_at: u64) -> Result<[u16; 4], KarError> { + let bytes = read_region(file, book_at, 8).map_err(typed)?; + let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); + if book.iter().any(|b| b & 0x7c00 == 0x7c00) { + return Err(KarError::Profile("KAR PLE nonfinite book")); + } + Ok(book) +} + +/// Every byte a row read can touch lies inside the extents (a row read is bounded by its partition), so no +/// read can land in a hole; then the bytes of the extents must be the pinned ones. +fn check_sparse_extents( + reader: &KarInspection, + parts: &[VerifiedPart], + serve_extents: &[Extent], + pin: &[u8; 32], +) -> Result<(), KarError> { + for part in parts { + for read in part.reads()? { + if !extents_cover(serve_extents, read.offset, read.len) { + return Err(KarError::Range("KAR PLE read outside the sparse extents")); + } + } + } + let digest = digest_extents(&reader.file, serve_extents, |_| {})?; + if &digest != pin { + return Err(KarError::Integrity("KAR sparse extents SHA-256 mismatch")); + } + Ok(()) +} + +fn check_unchanged( + reader: &KarInspection, + profile: &KarPleProfile, + identity: Option, +) -> Result<(), KarError> { + let after = reader.file.metadata().map_err(KarError::Io)?; + if after.len() != profile.spec.archive_bytes { + return Err(KarError::Integrity("KAR archive length changed")); + } + // An ordinary file must be in the very state that was verified (or stamped) at the start of this call. + if identity.is_some() && FileIdentity::of(&after) != identity { + return Err(KarError::Integrity("KAR archive file changed while it was verified")); + } + Ok(()) +} diff --git a/crates/model-format/src/kar/independent_handles.rs b/crates/model-format/src/kar/independent_handles.rs index 83c4eae2..711ad1f3 100644 --- a/crates/model-format/src/kar/independent_handles.rs +++ b/crates/model-format/src/kar/independent_handles.rs @@ -66,45 +66,65 @@ pub(super) fn read_rows_parallel( packets.resize(rows.len(), KarPleRowPacket { payload: [0; 50], partition: 0 }); // positional reads of a file that is not in the page cache are latency-bound: many in flight let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1)); - if warm_probe && workers > 1 { - use std::sync::atomic::Ordering; - if COLD_SKIP.load(Ordering::Relaxed) > 0 { - COLD_SKIP.fetch_sub(1, Ordering::Relaxed); - } else { - let started = std::time::Instant::now(); - read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; - if started.elapsed().as_nanos() <= WARM_ROW_NS { - read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; - return Ok(packets); - } - COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); - } - } - if workers == 1 { - read_rows_chunk(first, parts, rows, &mut packets)?; - } else { - let per = rows.len().div_ceil(workers); - let results: Vec> = std::thread::scope(|scope| { - let handles: Vec<_> = rows - .chunks(per) - .zip(packets.chunks_mut(per)) - .enumerate() - .map(|(i, (rows, out))| { - let file = &files[i % files.len()]; - scope.spawn(move || read_rows_chunk(file, parts, rows, out)) - }) - .collect(); - handles - .into_iter() - .map(|h| h.join().unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))) - .collect() - }); - for r in results { - r?; - } + if warm_probe && workers > 1 && read_warm(first, parts, rows, &mut packets)? { + return Ok(packets); } + read_fanned_out(files, parts, rows, &mut packets, workers)?; Ok(packets) } + +/// Reads the first row on this thread and times it; a file the page cache holds answers in about a microsecond, and +/// then the other rows are read here too (true). After a cold verdict the next calls skip the probe (false). +fn read_warm( + first: &File, + parts: &[VerifiedPart], + rows: &[u64], + packets: &mut [KarPleRowPacket], +) -> Result { + use std::sync::atomic::Ordering; + if COLD_SKIP.load(Ordering::Relaxed) > 0 { + COLD_SKIP.fetch_sub(1, Ordering::Relaxed); + return Ok(false); + } + let started = std::time::Instant::now(); + read_rows_chunk(first, parts, &rows[..1], &mut packets[..1])?; + if started.elapsed().as_nanos() <= WARM_ROW_NS { + read_rows_chunk(first, parts, &rows[1..], &mut packets[1..])?; + return Ok(true); + } + COLD_SKIP.store(COLD_SKIP_CALLS, Ordering::Relaxed); + Ok(false) +} + +/// The rows over `workers` threads (one when `workers` is 1), each on a handle of its own. +fn read_fanned_out( + files: &[File], + parts: &[VerifiedPart], + rows: &[u64], + packets: &mut [KarPleRowPacket], + workers: usize, +) -> Result<(), KarError> { + if workers == 1 { + return read_rows_chunk(&files[0], parts, rows, packets); + } + let per = rows.len().div_ceil(workers); + let results: Vec> = std::thread::scope(|scope| { + let handles: Vec<_> = rows + .chunks(per) + .zip(packets.chunks_mut(per)) + .enumerate() + .map(|(i, (rows, out))| { + let file = &files[i % files.len()]; + scope.spawn(move || read_rows_chunk(file, parts, rows, out)) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))) + .collect() + }); + results.into_iter().collect() +} /// The per-read guard of the archive: the pinned length, and for an ordinary file the state it had when it was verified. One `fstat` (the /// length check always did one); a different size, modification time or change time (any write, `touch`, `chmod`, rename or hard link made /// after verification) is refused rather than served. @@ -144,35 +164,51 @@ pub(super) fn read_rows_chunk( out: &mut [KarPleRowPacket], ) -> Result<(), KarError> { for (row, packet) in rows.iter().zip(out) { - let index = parts - .partition_point(|p| p.row_base <= *row) - .checked_sub(1) - .ok_or(KarError::Range("KAR PLE partition range"))?; - let p = &parts[index]; - let local = row - p.row_base; - if local >= p.row_count { - return Err(KarError::Range("KAR PLE local row range")); - } - let scale = p - .scales - .checked_add(local.checked_mul(10).ok_or(KarError::Range("KAR PLE scale overflow"))?) - .ok_or(KarError::Range("KAR PLE scale overflow"))?; - read_at(file, scale, &mut packet.payload[..10])?; - for plane in 0..2usize { - let at = p - .planes - .checked_add((plane as u64).checked_mul(p.stride).ok_or(KarError::Range("KAR PLE plane overflow"))?) - .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; - } - if packet.payload[..10].as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { - return Err(KarError::Profile("KAR PLE nonfinite scale")); - } - packet.partition = u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + read_row(file, parts, *row, packet)?; } Ok(()) } + +fn read_row(file: &File, parts: &[VerifiedPart], row: u64, packet: &mut KarPleRowPacket) -> Result<(), KarError> { + let index = parts + .partition_point(|p| p.row_base <= row) + .checked_sub(1) + .ok_or(KarError::Range("KAR PLE partition range"))?; + let p = &parts[index]; + let local = row - p.row_base; + if local >= p.row_count { + return Err(KarError::Range("KAR PLE local row range")); + } + read_payload(file, p, local, packet)?; + if packet.payload[..10].as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { + return Err(KarError::Profile("KAR PLE nonfinite scale")); + } + packet.partition = u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + Ok(()) +} + +/// The three positional reads of one row: its scales, then the two planes. +fn read_payload(file: &File, p: &VerifiedPart, local: u64, packet: &mut KarPleRowPacket) -> Result<(), KarError> { + read_at(file, scale_offset(p, local)?, &mut packet.payload[..10])?; + for plane in 0..2usize { + let at = plane_offset(p, plane, local)?; + read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; + } + Ok(()) +} + +fn scale_offset(p: &VerifiedPart, local: u64) -> Result { + p.scales + .checked_add(local.checked_mul(10).ok_or(KarError::Range("KAR PLE scale overflow"))?) + .ok_or(KarError::Range("KAR PLE scale overflow")) +} + +fn plane_offset(p: &VerifiedPart, plane: usize, local: u64) -> Result { + p.planes + .checked_add((plane as u64).checked_mul(p.stride).ok_or(KarError::Range("KAR PLE plane overflow"))?) + .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) + .ok_or(KarError::Range("KAR PLE plane overflow")) +} #[cfg(unix)] pub(super) fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), KarError> { use std::os::unix::fs::FileExt; diff --git a/crates/model-format/src/kar/read_region.rs b/crates/model-format/src/kar/read_region.rs index 25e424a8..79e1131b 100644 --- a/crates/model-format/src/kar/read_region.rs +++ b/crates/model-format/src/kar/read_region.rs @@ -66,6 +66,54 @@ pub(super) fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), Ok(()) } +/// The per-section CRC-32 state of an archive that is fed chunk by chunk, in order. +pub(super) struct SectionCrc<'a> { + sections: &'a [Section], + index: usize, + total: u64, + crc: u32, + failed: bool, +} + +impl<'a> SectionCrc<'a> { + fn new(sections: &'a [Section]) -> Self { + Self { sections, index: 0, total: 0, crc: !0u32, failed: false } + } + + fn feed(&mut self, chunk: &[u8]) { + let end = self.total + chunk.len() as u64; + while let Some(section) = self.sections.get(self.index) { + if section.offset >= end { + break; + } + let section_end = section.offset + section.bytes; // Checked by integrity_sections. + let start = self.total.max(section.offset); + let stop = end.min(section_end); + self.crc = crc32_step(self.crc, &chunk[(start - self.total) as usize..(stop - self.total) as usize]); + if stop != section_end { + break; + } + self.failed |= !self.crc != section.crc32; + self.crc = !0u32; + self.index += 1; + } + self.total = end; + } +} + +/// SHA first, then CRC: a CRC failure never shortcuts the full hash or changes SHA-first precedence. +fn integrity_verdict(total: u64, digest: Sha256, crc: &SectionCrc, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> { + if total != bytes || digest.finalize().as_slice() != pin { + return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + } + if crc.failed || crc.index != crc.sections.len() { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + Ok(()) +} + +type ChunkReceiver = std::sync::mpsc::Receiver>>; + /// The production form of [`verify_integrity_stream`]: one reader thread keeps chunks coming, SHA-256 of the /// whole archive runs on the calling thread and the per-section CRC-32 on a second one, so the pass costs the /// slower of the two instead of the read plus both. Same verdicts, same precedence: a SHA mismatch (or a short @@ -77,64 +125,49 @@ pub(super) fn verify_integrity_pipelined( pin: &[u8; 32], ) -> Result<(), KarError> { integrity_sections(sections, bytes)?; - let (digest, total, crc) = crate::readahead::with_read_ahead(file, 0, bytes, 2, |mut receivers| { - let crc_rx = receivers.pop().expect("two receivers"); - let sha_rx = receivers.pop().expect("two receivers"); - std::thread::scope(|scope| { - let crc_thread = scope.spawn(move || -> std::io::Result<(bool, usize)> { - let (mut index, mut total, mut crc, mut failed) = (0usize, 0u64, !0u32, false); - for item in crc_rx { - let chunk = item?; - let end = total + chunk.len() as u64; - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked by integrity_sections. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step(crc, &chunk[(start - total) as usize..(stop - total) as usize]); - if stop != section_end { - break; - } - failed |= !crc != section.crc32; - crc = !0u32; - index += 1; - } - total = end; - } - Ok((failed, index)) - }); - let mut digest = Sha256::new(); - let mut total = 0u64; - let mut read_error = None; - for item in sha_rx { - match item { - Ok(chunk) => { - digest.update(&chunk[..]); - total += chunk.len() as u64; - } - Err(error) => { - read_error = Some(error); - break; - } - } + let (digest, total, crc) = + crate::readahead::with_read_ahead(file, 0, bytes, 2, |receivers| hash_and_crc(receivers, sections))?; + integrity_verdict(total, digest, &crc, bytes, pin) +} + +/// SHA-256 on this thread and the section CRCs on a second one, over the two receivers of one read-ahead. +fn hash_and_crc<'a>( + mut receivers: Vec, + sections: &'a [Section], +) -> Result<(Sha256, u64, SectionCrc<'a>), KarError> { + let crc_rx = receivers.pop().expect("two receivers"); + let sha_rx = receivers.pop().expect("two receivers"); + std::thread::scope(|scope| { + let crc_thread = scope.spawn(move || -> std::io::Result> { + let mut crc = SectionCrc::new(sections); + for item in crc_rx { + crc.feed(&item?[..]); } - let crc = crc_thread.join().expect("the CRC thread does not panic"); - match read_error { - Some(error) => Err(KarError::Io(error)), - None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), + Ok(crc) + }); + let (digest, total, read_error) = hash_chunks(sha_rx); + let crc = crc_thread.join().expect("the CRC thread does not panic"); + match read_error { + Some(error) => Err(KarError::Io(error)), + None => crc.map(|c| (digest, total, c)).map_err(KarError::Io), + } + }) +} + +/// SHA-256 and byte count of the chunks up to the first read error (returned with them). +fn hash_chunks(receiver: ChunkReceiver) -> (Sha256, u64, Option) { + let mut digest = Sha256::new(); + let mut total = 0u64; + for item in receiver { + match item { + Ok(chunk) => { + digest.update(&chunk[..]); + total += chunk.len() as u64; } - }) - })?; - let (crc_failed, index) = crc; - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + Err(error) => return (digest, total, Some(error)), + } } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) + (digest, total, None) } /// The reference scan (kept for the tests that pin its verdicts; production uses the pipelined form above). @@ -151,42 +184,19 @@ pub(super) fn verify_integrity_stream( return Err(KarError::Range("KAR integrity buffer is empty")); } let mut digest = Sha256::new(); - let mut total = 0u64; - let mut index = 0; - let mut crc = !0u32; - let mut crc_failed = false; + let mut crc = SectionCrc::new(sections); loop { let n = file.read(buffer).map_err(KarError::Io)?; if n == 0 { break; } - let end = total.checked_add(n as u64).ok_or(KarError::Range("KAR hash length overflow"))?; - digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. - while let Some(section) = sections.get(index) { - if section.offset >= end { - break; - } - let section_end = section.offset + section.bytes; // Checked above. - let start = total.max(section.offset); - let stop = end.min(section_end); - crc = crc32_step(crc, &buffer[(start - total) as usize..(stop - total) as usize]); - if stop != section_end { - break; - } - crc_failed |= !crc != section.crc32; - crc = !0u32; - index += 1; + if crc.total.checked_add(n as u64).is_none() { + return Err(KarError::Range("KAR hash length overflow")); } - total = end; + digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. + crc.feed(&buffer[..n]); } - // A CRC failure never shortcuts the full hash or changes SHA-first precedence. - if total != bytes || digest.finalize().as_slice() != pin { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); - } - if crc_failed || index != sections.len() { - return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); - } - Ok(()) + integrity_verdict(crc.total, digest, &crc, bytes, pin) } pub(super) fn round_up(value: u64, alignment: u64) -> Option {