From 4921580d09f3deefd75cf4576e7a7bcc9cfc78f9 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:59:50 -0800 Subject: [PATCH 1/5] Progressive sessions honour damaged_input: Salvage and Resync read past damaged RAR headers, reported as HeaderDamaged ProgressiveOptions::extract.damaged_input now reads past damaged RAR 4.x / 5.0 headers in ProgressiveSession::new and from_sealed_memory as the whole-archive runners do (same members, bytes and HeaderDamage records), and reports each as the new ProgressiveEvent::HeaderDamaged { volume, damage }. Refuse (the default) is unchanged. Only delivered bytes are judged: a header still to come (NotYet) is waited for, one inside a Hole answer is HeaderHole as before (repair may fill it), and a resync never searches across a hole. Under salvage the parser takes the volume's known length so a cut header or data is UnexpectedEnd. Resync runs as an incremental phase over the source with #310's candidate filter and a per-volume linear work bound; its window is charged to MetadataBytes. Bytes passed over break the solid history. Persistent-partial sessions keep refusing (follow-up: the journal binds members to header bytes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- docs/compat-options.md | 38 +- docs/persistent-partials.md | 2 +- docs/progressive-archives.md | 9 + src/extract.rs | 9 +- src/progressive/session.rs | 81 ++- src/progressive/session/partial.rs | 2 + src/progressive/session/salvage.rs | 326 ++++++++++++ src/rar5/framing.rs | 83 ++- src/rar5/reader.rs | 12 +- tests/progressive_salvage.rs | 778 +++++++++++++++++++++++++++++ 10 files changed, 1312 insertions(+), 28 deletions(-) create mode 100644 src/progressive/session/salvage.rs create mode 100644 tests/progressive_salvage.rs diff --git a/docs/compat-options.md b/docs/compat-options.md index 3ed6d823..a7c090c2 100644 --- a/docs/compat-options.md +++ b/docs/compat-options.md @@ -285,12 +285,42 @@ Where it applies: - `RarSession`, through `RarSessionOptions::damaged_input`: the catalogue reads past the damage, its members list and extract (`extract_selected`, `extract_selected_controlled`, printing) as any other, and `RarArchiveMetadata::damaged_headers()` says what was read past; -- `Volume::open_damaged` and `Volume::take_damage` for callers walking blocks themselves. - -Progressive and persistent-partial sessions still refuse a damaged header whatever `damaged_input` says; listings that -take no `Options` (`extract::list`, `list_detailed`, `inspect*`) refuse it too. The CLI takes `--salvage` and +- `Volume::open_damaged` and `Volume::take_damage` for callers walking blocks themselves; +- progressive sessions (`ProgressiveSession::new`, `from_sealed_memory`), through `ProgressiveOptions::extract`: each + damaged header is a `ProgressiveEvent::HeaderDamaged { volume, damage }`, delivered before anything read from that + header (so just before the `MemberStarted` of a member whose header failed its checksum). See "Damaged headers in a + progressive session" below. + +Persistent-partial sessions (`ProgressiveSession::new_partial`) still refuse a damaged header whatever `damaged_input` +says: their journal binds each member to the header bytes it was read from, and a header repaired later would no longer +match. Listings that take no `Options` (`extract::list`, `list_detailed`, `inspect*`) refuse it too. The CLI takes `--salvage` and `--resync` (for `l`, `t`, `x`, `e`; a listing of anything but RAR stays as it is), prints each damaged header and a warning, and exits 1. `tests/rar_salvage.rs` checks each point. + +### Damaged headers in a progressive session + +A progressive session reads bytes as its source delivers them, and a range that is missing now may be filled later +(an article fetched again, PAR2 repair, another copy). So only bytes the source has delivered are ever judged damaged: + +- A header the source has not delivered yet (`RangeRead::NotYet`, or a volume not there yet) is waited on, as under + `Refuse`; it is never damage. When it arrives it is read as any other header. +- A header inside a range the source answers as a `Hole` is not damage either: the session stops with `HeaderHole`, as + under `Refuse`, since the bytes may yet be repaired. Run the session again once they are. +- A resync never searches across a `Hole`: the next header may be inside it, so the search stops with `HeaderHole`. + On a source whose end isn't known yet (`GrowingFileVolumes`) a search that has not found a header waits for more + bytes, as reading a header does. +- Only a header whose bytes were delivered and are wrong (a checksum that fails, fields that don't parse, a header or + data running past the volume's known end) is salvaged, exactly as the whole-archive runners do: the same members, + the same bytes and the same `HeaderDamage` records (`volume` is the volume's name as the session asked for it). + +Under salvage the session takes the volume's length from the source (`SourceInfo::length`, unless it is +`Advertised(u64::MAX)`), so a header or data running past it is a volume cut short (`UnexpectedEnd`). The rest of a +damaged volume is passed over as in the whole-archive runners: a volume set goes on with its next volume (a sealed set, +or a declared last volume, may end there), anything else ends. A folder whose damaged header claims data is created and +its data passed over. A resync's work is bounded as the whole-archive one's, by 16 times the furthest offset read in +the volume plus 1 MiB, and it charges its window (at most a chunk and one candidate header) to `MetadataBytes`. Bytes +passed over break a solid archive's history: the next solid member stops with `SolidHistoryUnavailable`. +`tests/progressive_salvage.rs` checks each point. ## `unsupported_filters`: a RAR 3.x/4.x member using a VM filter zipfast doesn't run RAR 3.x/4.x carries filters as programs for its virtual machine. zipfast runs the standard ones (E8, E8E9, ITANIUM, diff --git a/docs/persistent-partials.md b/docs/persistent-partials.md index 19b30577..ba14a087 100644 --- a/docs/persistent-partials.md +++ b/docs/persistent-partials.md @@ -6,7 +6,7 @@ This H2 path accepts RAR5 Stored members with known sizes and a Complete source `PartialReady` follows durable genesis and precedes payload reads. Retain its `MemberKey` and obtain a handle with `partial_file`. Once a member has finished and its handle has been taken with `partial_file`, the session drops its own reference: the member's state pages, descriptors and `open_partials` lease are freed when the caller drops its last handle, so a set's member count is not bounded by `state_pages` or `open_files`. Drop each handle when done with it. The session never verifies or extracts a released member again; `partial_file` returns another handle while one lives, and `BindingMismatch(Member)` after the last is dropped (reopen it with `PartialFile::open`). Damage that `declare_hole` maps to a released member whose handles were all dropped is listed in `DamageReceipt::released` as `(MemberKey, PackedSpan)`, never in `unmapped`: reopen that member with `PartialFile::open` and declare the span there with `PartialFile::declare_hole`. While a handle lives, the damage is applied to it as before. `PartialFile::relative_output_path` returns the sanitized output path relative to the output root (normal components only) and `PartialFile::output_path` the absolute path (the root made absolute joined with it), so a caller need not walk the output tree to find it. Each `Hole` describes an observed output range and exact packed spans; waiting for a provider is never damage. A persistent session lets a source answer one `RangeRead::Hole` longer than the read buffer while it extracts a member's data: up to the end of that member's packed data in the volume and at most 256 MiB, and not past the start of a range declared with `declare_hole`. A longer answer inside the volume is accepted up to that limit and the rest is read again (the source cannot see where the part ends, how much the read needs or what was declared); on the session's other reads (headers, and the walk that resumes an adopted member, such as an AES member's 16-byte previous ciphertext block) a longer answer inside the volume is trimmed to the read in the same way, so a source may answer every hole whole. One past the volume's length is a `SourceContract` failure, as is any answer longer than the buffer outside persistent sessions. Such an answer is recorded as one hole, in one transaction, and delivered as one `Hole` event (an encrypted member also reports the block after it as a `CipherNeighbour` hole when that block's ciphertext is read later), so a dead volume answered once costs one record and one journal transaction per 256 MiB; refill it later in as many `refill_from_packed` pieces as you like. A source that answers one buffer per `Hole` still works: the run arrives as one `Hole` event per buffer, and the state stores it as one record: a hole that continues the last recorded one (same cause, the next output, packed bytes running on in the same volume) extends it, so `ProgressiveLimits::hole_intervals` counts unread ranges per volume, not buffers. Copies of the member's index, hole list and kept ciphertext blocks made while a hole is recorded are charged only while it is recorded, so recording a hole costs the same however much output and however many earlier holes came before it. What stays charged for the session is the record (when the hole starts a new one, a few hundred bytes) and each transaction's journal bookkeeping (about 4 KiB). So a contiguous range is stored as one record, but each of its `Hole` events still adds that bookkeeping: at the default `metadata_bytes` that is a few tens of GiB of unread data per session in 1 MiB holes, and holes scattered between data cost in proportion to their number. `Hole` and `BytesWritten` events arrive in output order: every hole below a `BytesWritten`'s `logical_end` has been delivered before it. A fill cannot target unproduced preallocation, except a tail abandoned with `abandon_tail` (see "Taking over an unfinished member" below). Known overlaps must match before any write. The handle can fill and poll verification while another member progresses, and survives session cancellation/drop. Whole-member `Ok` and archive metadata require the canonical member finish to be durably committed, even when every output byte is already known. A handle paused or closed before that finish returns `Incomplete` (possibly with no holes); reopen preserves this distinction. Deferred part checks appear in `Verdict::Incomplete.parts` as well as `Ok.parts`; a live `PartVerified` event is a mirror. -Damage can also be declared late, for example when an article's yEnc CRC turns out wrong after zipfast consumed it. `ProgressiveSession::declare_hole(volume, range)` takes zero-based volume and archive byte offsets at any time. Output already written from those bytes becomes `DeclaredBad` holes in each affected member; the returned `DamageReceipt` lists them, plus `unmapped` spans (header or padding bytes with no output) and `pending` spans not read yet. Pending bytes are skipped without asking the provider and reported as `Hole` events with cause `DeclaredBad` when reached. A finished member's handle sees the new holes, verifies `Incomplete` until they are filled, and then verifies `Ok` again. After the session ends, `PartialFile::declare_hole` does the same for one member. Declaring damage on a header that has not been read yet is not supported yet: the session stops with `HeaderHole` when it reaches it. Each member's holes are committed one durable run at a time, so if `declare_hole` returns an error part way, earlier runs may already be holes; `PartialFile::remaining` shows the current state and repeating the call reports only what is left. Pending ranges past the end of a volume are never reached and so never reported. Hole causes are kept in the durable state; states written before causes were recorded reopen with every hole as `Missing`, and a build from before causes were recorded cannot open a state that holds declared damage. +Damage can also be declared late, for example when an article's yEnc CRC turns out wrong after zipfast consumed it. `ProgressiveSession::declare_hole(volume, range)` takes zero-based volume and archive byte offsets at any time. Output already written from those bytes becomes `DeclaredBad` holes in each affected member; the returned `DamageReceipt` lists them, plus `unmapped` spans (header or padding bytes with no output) and `pending` spans not read yet. Pending bytes are skipped without asking the provider and reported as `Hole` events with cause `DeclaredBad` when reached. A finished member's handle sees the new holes, verifies `Incomplete` until they are filled, and then verifies `Ok` again. After the session ends, `PartialFile::declare_hole` does the same for one member. Declaring damage on a header that has not been read yet is not supported yet: the session stops with `HeaderHole` when it reaches it. A header whose bytes are present but damaged (failing its checksum or not parsing) stops a persistent session too, whatever `extract::Options::damaged_input` says: the journal binds each member to the header bytes it was read from, so salvaging (which ordinary progressive sessions do, see `docs/compat-options.md`) is not offered here yet. Each member's holes are committed one durable run at a time, so if `declare_hole` returns an error part way, earlier runs may already be holes; `PartialFile::remaining` shows the current state and repeating the call reports only what is left. Pending ranges past the end of a volume are never reached and so never reported. Hole causes are kept in the durable state; states written before causes were recorded reopen with every hole as `Missing`, and a build from before causes were recorded cannot open a state that holds declared damage. Large plaintext ranges can be streamed instead of passed as one slice. `PartialFile::fill_writer(offset)` returns a `FillWriter` (`std::io::Write`) that buffers at most `PartialLimits::fill_bytes` and writes each full buffer into a group commit (see below), so it commits once per `group_commit_bytes` rather than once per buffer; `finish()` writes the rest, commits, and returns the combined `applied` ranges. This suits RustyGet's alt switch, where `[offset_reached, end)` of the member comes from another copy and known bytes in that range must simply match. A failed write poisons the writer: `write` returns an `io::Error` with the message, and `finish` returns the typed `PartialError`. The writer then commits what earlier buffers wrote, if it can, and `position()` is the end of the committed bytes; ranges committed before stay filled. `PartialFile::fill_from(offset, len, reader)` does the same from an `io::Read` and fails with `FillRead` (with `output.completed`, the committed bytes) if the input errors or ends early. `fill_bytes` (default 1 MiB, at most 64 MiB) also bounds one `fill` or `fill_packed` call, one `refill_from_packed` step and each write of the extraction itself, so keep it at least `ProgressiveLimits::read_chunk`; a `FillWriter` buffer above 1 MiB is charged to the metadata budget while the writer lives. diff --git a/docs/progressive-archives.md b/docs/progressive-archives.md index 6ae93c97..25cc39f2 100644 --- a/docs/progressive-archives.md +++ b/docs/progressive-archives.md @@ -136,6 +136,15 @@ the complete extractor; this entrypoint creates no links. Stored recovery is available for the admitted RAR4 and RAR5 subsets below. Full original compatibility remains open. +## Damaged headers + +`ProgressiveOptions::extract.damaged_input` (`Salvage`, `Resync`) reads past damaged RAR headers as the whole-archive +runners do, and reports each as `ProgressiveEvent::HeaderDamaged { volume, damage }`. The default `Refuse` fails as +before. The rule with holes: only delivered bytes are judged. A header the source has not delivered yet is waited on, +one inside a `Hole` answer stops the session with `HeaderHole` (repair may still fill it), and a resync never searches +across a hole. See `docs/compat-options.md` ("Damaged headers in a progressive session"). Persistent-partial sessions +keep refusing damaged headers. + ## RAR4 capability boundary | Progressive RAR4 case | Current admission | diff --git a/src/extract.rs b/src/extract.rs index cf9de4d5..a3787dc7 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -241,9 +241,12 @@ pub struct Options { /// 7-Zip would ("Corrupt header is found", "Headers Error"). /// /// Honoured by the whole-archive RAR runners ([`run`], [`run_with_password`], [`run_rar_with_outcomes`], the - /// checked dispatchers), by [`list_detailed_with_options`], and by [`crate::rar5::session::RarSession`] through - /// [`crate::rar5::session::RarSessionOptions::damaged_input`]. Progressive and persistent-partial sessions refuse a - /// damaged header whatever this says. 7z and ZIP ignore it. + /// checked dispatchers), by [`list_detailed_with_options`], by [`crate::rar5::session::RarSession`] through + /// [`crate::rar5::session::RarSessionOptions::damaged_input`], and by progressive sessions through + /// [`crate::progressive::ProgressiveOptions::extract`] (reported as + /// [`crate::progressive::ProgressiveEvent::HeaderDamaged`]; only bytes the source delivered are judged, a header + /// still to come is waited on and one in a hole is `HeaderHole`). Persistent-partial sessions refuse a damaged + /// header whatever this says. 7z and ZIP ignore it. pub damaged_input: DamagedInput, } diff --git a/src/progressive/session.rs b/src/progressive/session.rs index 51152e1c..30bd5966 100644 --- a/src/progressive/session.rs +++ b/src/progressive/session.rs @@ -21,6 +21,7 @@ mod partial; mod rar4; #[path = "recovery.rs"] pub(crate) mod recovery; +mod salvage; use super::{ output::{Capacity, DirectoryVerdict, OutputContext, Publication, Stage, Target}, source::{SourceDriver, SourceStep}, @@ -73,6 +74,16 @@ pub enum ProgressiveEvent { index: u32, id: SourceId, }, + /// A damaged header of zero-based `volume` was read past under + /// [`crate::extract::Options::damaged_input`] (`Salvage` or `Resync`; never under the default `Refuse`, which + /// fails the session as before). Delivered before anything read from the header, so a member whose header + /// failed its checksum but parsed has this event just before its `MemberStarted`. Only bytes the source + /// delivered are judged: a header still to come is waited on and one in a `Hole` answer is `HeaderHole`. Non-empty + /// means the headers are damaged, as [`crate::extract::Summary::damaged_headers`] does for a whole archive. + HeaderDamaged { + volume: u32, + damage: crate::extract::HeaderDamage, + }, MemberStarted { member: MemberId, name: Arc>, @@ -197,6 +208,8 @@ enum Phase { Finish, Verdict, NextVolume, + /// A [`crate::extract::DamagedInput::Resync`] search past an unreadable header. + Resync(Box), Done, } /// The longest `Hole` answer a persistent session accepts in one read (see `SourceDriver::allow_long_hole`): @@ -231,9 +244,16 @@ pub struct ProgressiveSession { rar4_history: Option, /// every member so far was written by an archiver older than RAR 2.9, which writes no end-of-archive block pre_29: bool, - /// A pre-2.9 volume that names itself part of a set ended between members: the next volume is asked for, and - /// only a sealed in-memory set (every volume given up front) may end there when it has no next volume. + /// A pre-2.9 volume that names itself part of a set ended between members (or the rest of a damaged one was + /// passed over under [`crate::extract::Options::damaged_input`]): the next volume is asked for, and only a sealed + /// in-memory set (every volume given up front) or a declared last volume may end there with no next volume. pre_29_open_end: bool, + /// Damaged headers read past, each delivered as a [`ProgressiveEvent::HeaderDamaged`]. + damage: std::collections::VecDeque<(u32, crate::extract::HeaderDamage)>, + /// The bytes a resync searched, kept for the next one. + resync_window: Vec, + /// The resync work done in the current volume. + resync_work: salvage::ResyncWork, solid_archive: Option, archive_format: Option, disposition: Disposition, @@ -342,6 +362,7 @@ impl ProgressiveSession { let expected = options.first_name.clone(); let mut parser = HeaderParser::from_start(expected.clone().into(), usage.clone()); parser.set_rar4_unknown_part_crc(options.rar4_unknown_part_crc); + parser.set_salvage(options.extract.damaged_input); let mut buffer = Vec::new(); buffer .try_reserve_exact(chunk as usize) @@ -374,6 +395,9 @@ impl ProgressiveSession { rar4_history: None, pre_29: true, pre_29_open_end: false, + damage: Default::default(), + resync_window: Vec::new(), + resync_work: Default::default(), solid_archive: None, archive_format: None, disposition: Disposition::Write, @@ -540,8 +564,16 @@ impl ProgressiveSession { if let Some(event) = self.partial.as_mut().and_then(|p| p.written.take()) { return Ok(Poll::Ready(Ok(Some(event)))); } + if let Some((volume, damage)) = self.damage.pop_front() { + return Ok(Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { volume, damage })))); + } match &self.phase { Phase::Done => return Ok(Poll::Ready(Ok(None))), + Phase::Resync(_) => { + if let Some(poll) = self.poll_resync(cx, &mut work)? { + return Ok(poll); + } + } Phase::NextVolume if self.pre_29_open_end && (self.driver.sealed_volume_count().is_some_and(|n| n <= self.volume as usize + 1) @@ -570,6 +602,8 @@ impl ProgressiveSession { self.usage.charge(Resource::MetadataBytes, self.expected.capacity() as u64)?; self.parser = HeaderParser::from_start(self.expected.clone().into(), self.usage.clone()); self.parser.set_rar4_unknown_part_crc(self.options.rar4_unknown_part_crc); + self.parser.set_salvage(self.damaged_input()); + self.resync_work = Default::default(); self.cursor = 0; self.main_seen = false; self.phase = Phase::Header; @@ -671,7 +705,13 @@ impl ProgressiveSession { return self.finish().map(|e| Poll::Ready(Ok(Some(e)))); } Phase::Header => { - let (_, step) = self.parser.advance(&[])?; + let (_, step) = match self.parser.advance_salvaging(&[])? { + Ok(step) => step, + Err(kind) => { + self.salvage_header(kind)?; + continue; + } + }; let (offset, len) = match step { ParserStep::LegacyKeyRequired { salt } => { let password = self @@ -689,6 +729,11 @@ impl ProgressiveSession { continue; } ParserStep::Need { offset, len } => (offset, len), + // only a salvaging parser knows the volume's length: it ends here without its end header + ParserStep::End if self.parser.salvages() => { + self.salvage_volume_end()?; + continue; + } ParserStep::End => return Err(self.parser.truncated()), ParserStep::Frame(_) => unreachable!("frames require input"), }; @@ -707,6 +752,14 @@ impl ProgressiveSession { Poll::Ready(Err(e)) => return Err(e), Poll::Ready(Ok(SourceStep::VolumeOpened { index, id })) => { self.driver.validate_step()?; + // Under salvage a header or data running past a volume's known end is a volume cut + // short, as for a whole volume. An open-ended source (a growing file) has no known end. + if self.parser.salvages() + && let Some(info) = self.driver.observed_info(index) + && info.length.value() != u64::MAX + { + self.parser.set_complete_len(info.length.value()); + } return Ok(Poll::Ready(Ok(Some(ProgressiveEvent::VolumeOpened { index, id })))); } Poll::Ready(Ok(SourceStep::EndOfVolume)) @@ -733,6 +786,9 @@ impl ProgressiveSession { self.phase = Phase::Done; } } + Poll::Ready(Ok(SourceStep::EndOfVolume)) if self.parser.salvages() => { + self.salvage_volume_end()?; + } Poll::Ready(Ok(SourceStep::EndOfVolume)) => { return Err(self.parser.truncated()); } @@ -753,12 +809,21 @@ impl ProgressiveSession { if let Some(partial) = &mut self.partial { partial.record_header(offset, &self.buffer[..count], &self.usage)?; } - let (used, step) = self.parser.advance(&self.buffer[..count])?; + let (used, step) = match self.parser.advance_salvaging(&self.buffer[..count])? { + Ok(step) => step, + Err(kind) => { + self.driver.validate_step()?; + self.salvage_header(kind)?; + continue; + } + }; if used != count { return Err(ProgressiveFailure::new(FailureKind::SourceContract)); } self.driver.validate_step()?; - if let ParserStep::Frame(frame) = step { + if let ParserStep::Frame(frame) = step + && (!frame.damaged || self.damaged_frame(&frame)?) + { #[cfg(feature = "persistent-partials")] if let Some(partial) = &mut self.partial { partial.frame_header(self.volume, &frame, &self.usage)?; @@ -1111,6 +1176,8 @@ impl ProgressiveSession { Ok(()) } fn start(&mut self, frame: PhysicalFrame) -> ProgressiveResult { + // a folder whose damaged header claims data is created and its data passed over, as UnRAR 7.30 does + let damaged = frame.damaged; let Block::File(header) = frame.block else { unreachable!() }; #[cfg(feature = "persistent-partials")] let refusal = self.partial.as_ref().and_then(|_| partial::refusal(&header)); @@ -1216,7 +1283,9 @@ impl ProgressiveSession { } Disposition::Skip(crate::extract::RarSkipReason::OlderVersion(version)) } else if header.is_dir() { - if header.split_after() || header.packed_size != 0 || header.size_unknown() || header.unpacked_size != 0 { + if header.split_after() + || (!damaged && (header.packed_size != 0 || header.size_unknown() || header.unpacked_size != 0)) + { return Err(ProgressiveFailure::new(FailureKind::Malformed("directory payload or continuation"))); } Disposition::Directory diff --git a/src/progressive/session/partial.rs b/src/progressive/session/partial.rs index 01247976..28bf7a87 100644 --- a/src/progressive/session/partial.rs +++ b/src/progressive/session/partial.rs @@ -230,6 +230,8 @@ impl ProgressiveSession { directories: Vec::new(), created: Vec::new(), }); + // a persistent session refuses damaged headers whatever `damaged_input` says (see `damaged_input()`) + session.parser.set_salvage(crate::extract::DamagedInput::Refuse); Ok(session) } #[allow(clippy::result_large_err, reason = "preserve the public typed partial receipt API")] diff --git a/src/progressive/session/salvage.rs b/src/progressive/session/salvage.rs new file mode 100644 index 00000000..64b6ba3b --- /dev/null +++ b/src/progressive/session/salvage.rs @@ -0,0 +1,326 @@ +// Copyright (C) 2026 xbmc4lyfe +// SPDX-License-Identifier: RPL-1.5 +// +// Unless explicitly acquired and licensed from Licensor under another license, +// the contents of this file are subject to the Reciprocal Public License +// ("RPL") Version 1.5, or subsequent versions as allowed by the RPL, and You +// may not copy or use this file in either source code or executable form, +// except in compliance with the terms and conditions of the RPL. +// +// All software distributed under the RPL is provided strictly on an "AS IS" +// basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND LICENSOR +// HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET +// ENJOYMENT, OR NON-INFRINGEMENT. See the RPL for specific language governing +// rights and limitations under the RPL. + +//! [`crate::extract::Options::damaged_input`] in a progressive session: damaged headers read past as the whole-archive +//! runners do, reported as [`ProgressiveEvent::HeaderDamaged`]. Only bytes the source delivered are judged: a header +//! the source has not delivered yet is waited on, and one inside a `Hole` answer stops the session with +//! `HeaderHole` as before (repair may still fill it); a resync never searches across a hole either. +use super::*; +use crate::extract::{HeaderDamage, HeaderDamageKind}; +use crate::rar5::reader::{ + RESYNC_CHUNK, RESYNC_FIRST_CHUNK, RESYNC_LOOKAHEAD, RESYNC_WORK_PER_BYTE, resync_checks, resync_shape, +}; + +/// The longest member name a [`HeaderDamage`] keeps, as the whole-archive runners keep it. +const MAX_DAMAGE_NAME: usize = 1024; +/// The longest header a resync candidate can be ([`resync_shape`]): an 8 KiB RAR 5.0 header and its prefix. +const RESYNC_CANDIDATE_MAX: usize = (8 << 10) + 8; + +/// A [`crate::extract::DamagedInput::Resync`] search for the next header that passes its checksum, held across +/// polls: the bytes read so far from `start`, and the next position to try. +pub(super) struct Resync { + /// Where the unreadable header starts, and what was wrong with it. + damage_at: u64, + kind: HeaderDamageKind, + /// The next candidate position. + pos: u64, + /// Bytes of the volume from `start` on, as read. + window: Vec, + start: u64, + /// The source said the volume ends at `start + window.len()`. + eof: bool, + /// The next read's size: small first, so that resyncs close together read little. + chunk: usize, +} + +/// Per-volume resync work: bytes read and checksummed by every resync in the volume together, bounded by +/// [`RESYNC_WORK_PER_BYTE`] times the furthest offset read in the volume (plus 1 MiB), so the search stays linear in +/// the bytes the source delivered whatever they are. +#[derive(Default)] +pub(super) struct ResyncWork { + spent: u64, + furthest: u64, +} +impl ResyncWork { + fn charge(&mut self, work: u64) -> bool { + let bound = self.furthest.saturating_mul(RESYNC_WORK_PER_BYTE).saturating_add(1 << 20); + match self.spent.checked_add(work).filter(|&spent| spent <= bound) { + Some(spent) => { + self.spent = spent; + true + } + None => false, + } + } +} + +impl ProgressiveSession { + /// The damaged-input choice the parsers of this session take. A persistent session refuses damaged headers + /// whatever the options say (its journal binds a member to the header bytes it was read from). + pub(super) fn damaged_input(&self) -> crate::extract::DamagedInput { + #[cfg(feature = "persistent-partials")] + if self.partial.is_some() { + return crate::extract::DamagedInput::Refuse; + } + self.options.extract.damaged_input + } + /// Queues the event for one damaged header of the current volume. + pub(super) fn header_damage( + &mut self, + offset: u64, + kind: HeaderDamageKind, + name: Option<&str>, + resumed_at: Option, + passed_over: bool, + ) -> ProgressiveResult<()> { + let name = name.map(|name| { + let mut end = name.len().min(MAX_DAMAGE_NAME); + while !name.is_char_boundary(end) { + end -= 1; + } + &name[..end] + }); + let charge = std::mem::size_of::() + + self.expected.len() + + name.map_or(0, str::len) + + std::mem::size_of::<(u32, HeaderDamage)>(); + self.usage.charge(Resource::MetadataBytes, charge as u64)?; + self.damage.try_reserve(1).map_err(|_| ProgressiveFailure::new(FailureKind::Malformed("damage allocation")))?; + let damage = HeaderDamage { + volume: std::path::PathBuf::from(self.expected.clone()), + offset, + kind, + name: name.map(str::to_owned), + resumed_at, + passed_over, + }; + if passed_over && self.member.is_none() { + // Bytes that may hold a member's compressed stream were passed over: a solid member after the gap fails as + // lacking its history instead of decoding against the history from before the gap. A member still being + // continued keeps its decoder: its own checks decide. + self.history.take(); + self.rar4_history.take(); + self.history_failure = None; + } + self.damage.push_back((self.volume, damage)); + Ok(()) + } + /// A header that failed its checksum but parsed, read as it stands. False when the frame is to be dropped: a + /// damaged main header past the first volume's (or a second one in a volume, which only damage produces), which + /// holds nothing to read. The first volume's damaged main header describes the archive, as for a whole archive; + /// a later volume's is taken as present without checking its now unreliable identity against the first. + pub(super) fn damaged_frame(&mut self, frame: &PhysicalFrame) -> ProgressiveResult { + let name = match &frame.block { + Block::File(h) | Block::Service(h) => Some(h.name.as_str()), + _ => None, + }; + // As the whole-archive runners: the history survives only a header read as a compressed file, whose data is + // decoded into it in turn. Read as anything else its data, which may be a member's compressed stream, is + // skipped unread. + let carries_data = frame.data_end > frame.extent.end; + let passed_over = match &frame.block { + Block::File(h) => carries_data && (h.method == 0 || h.is_dir() || h.redirection.is_some()), + Block::Main(_) | Block::End { .. } => carries_data, + _ => true, + }; + self.header_damage(frame.extent.start, HeaderDamageKind::ChecksumMismatch, name, None, passed_over)?; + if matches!(frame.block, Block::Main(_)) && (self.main_seen || self.volume > 0) { + self.main_seen = true; + return Ok(false); + } + Ok(true) + } + /// The header at the parser's offset is damage of `kind`: searched past under `Resync`, else the rest of the + /// volume is passed over. + pub(super) fn salvage_header(&mut self, kind: HeaderDamageKind) -> ProgressiveResult<()> { + let at = self.parser.header_offset(); + if self.parser.resyncs() { + let mut window = std::mem::take(&mut self.resync_window); + window.clear(); + self.phase = Phase::Resync(Box::new(Resync { + damage_at: at, + kind, + pos: at.saturating_add(1), + window, + start: at.saturating_add(1), + eof: false, + chunk: RESYNC_FIRST_CHUNK, + })); + return Ok(()); + } + self.header_damage(at, kind, None, None, true)?; + self.end_damaged_volume() + } + /// The volume ended at a block boundary without its end header. A RAR 5.0 volume is cut short there (7-Zip 26.06: + /// "Unexpected end of archive"); a RAR 4.x one may end so (archives older than RAR 2.9 write no end block). + pub(super) fn salvage_volume_end(&mut self) -> ProgressiveResult<()> { + if !self.parser.at_block_start() { + return self.salvage_header(HeaderDamageKind::UnexpectedEnd); + } + if self.parser.format() == crate::rar5::RarFormat::Rar5 { + self.header_damage(self.parser.header_offset(), HeaderDamageKind::UnexpectedEnd, None, None, true)?; + } + self.end_damaged_volume() + } + /// The rest of the volume is passed over: a set goes on with its next volume, as the whole-archive runners do, and + /// may end there when no next volume follows; otherwise the session is done. + fn end_damaged_volume(&mut self) -> ProgressiveResult<()> { + if self.volume_set == Some(true) { + // a member split into the next volume needs it; between members the set may end here + self.pre_29_open_end = self.member.is_none(); + self.phase = Phase::NextVolume; + return Ok(()); + } + if self.member.is_some() { + return Err(ProgressiveFailure::new(FailureKind::Truncated)); + } + if let Some(output) = &mut self.output { + output.finish_directories(&mut self.driver)?; + } + self.phase = Phase::Done; + Ok(()) + } + /// One step of a resync: reads the volume on from where it got to and tries every position for a header that + /// passes its checksum. `Ok(None)` to go on polling (the phase may have changed), or the poll result to return. + pub(super) fn poll_resync( + &mut self, + cx: &mut Context<'_>, + work: &mut u64, + ) -> ProgressiveResult>>>> { + let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; + let format = self.parser.format(); + let end = self.parser.complete_len(); + // try the positions the window shows whole + let mut found = None; + let mut exhausted = false; + loop { + let held_end = scan.start + scan.window.len() as u64; + let limit = if scan.eof { held_end } else { end.unwrap_or(u64::MAX) }; + if scan.pos >= limit { + exhausted = true; + break; + } + let i = (scan.pos - scan.start) as usize; + let shown = &scan.window[i..]; + if !scan.eof && shown.len() < RESYNC_LOOKAHEAD && held_end < limit { + break; + } + if let Some(total) = resync_shape(shown, format) { + let fits = scan.pos.checked_add(total as u64).is_some_and(|candidate_end| candidate_end <= limit); + if fits { + if shown.len() < total { + break; + } + if !self.resync_work.charge(total as u64) { + exhausted = true; + break; + } + if resync_checks(&shown[..total], format) { + found = Some(scan.pos); + break; + } + } + } + scan.pos += 1; + } + if found.is_some() || exhausted { + let Phase::Resync(scan) = std::mem::replace(&mut self.phase, Phase::Header) else { unreachable!() }; + let Resync { damage_at, kind, window, .. } = *scan; + self.resync_window = window; + self.header_damage(damage_at, kind, None, found, true)?; + match found { + Some(at) => { + self.parser.resume_at(at); + // a resync past an unreadable main header lands on a member: read on with an empty main header, + // as the whole-archive runners do + self.main_seen = true; + } + None => self.end_damaged_volume()?, + } + return Ok(None); + } + // more bytes: drop what no candidate needs any more, then read on + let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; + let drop = (scan.pos - scan.start) as usize; + scan.window.drain(..drop); + scan.start = scan.pos; + let at = scan.start + scan.window.len() as u64; + let full = scan.chunk.min(end.map_or(usize::MAX, |end| end.saturating_sub(at).min(usize::MAX as u64) as usize)); + if full == 0 { + scan.eof = true; + return Ok(None); + } + let budget = (self.options.limits.packed_work_per_poll.min(1 << 20) - *work) as usize; + let n = match self.parked_read.take() { + Some(parked) if parked <= full.min(self.buffer.len()) => parked, + _ => full.min(self.buffer.len()).min(budget).max(1), + }; + if !self.resync_work.charge(n as u64) { + let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; + scan.eof = true; + scan.window.truncate((scan.pos - scan.start) as usize); + return Ok(None); + } + if at != self.cursor { + self.driver.seek(at)?; + self.cursor = at; + } + match self.driver.poll_step(cx, &mut self.buffer[..n]) { + Poll::Pending => { + self.parked_read = Some(n); + Ok(Some(Poll::Pending)) + } + Poll::Ready(Err(e)) => Err(e), + Poll::Ready(Ok(SourceStep::VolumeOpened { .. })) => { + Err(ProgressiveFailure::new(FailureKind::SourceContract)) + } + Poll::Ready(Ok(SourceStep::EndOfVolume)) => { + let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; + scan.eof = true; + Ok(None) + } + Poll::Ready(Ok(SourceStep::Hole { offset, .. })) => { + // the next header may be in it, and repair may still fill it: never searched across + let mut failure = ProgressiveFailure::new(FailureKind::HeaderHole); + failure.context.packed_offset = Some(offset); + Err(failure) + } + Poll::Ready(Ok(SourceStep::Filled { offset, count })) => { + self.cursor = offset + count as u64; + *work += count as u64; + self.resync_work.furthest = self.resync_work.furthest.max(self.cursor); + let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; + if offset != scan.start + scan.window.len() as u64 { + return Err(ProgressiveFailure::new(FailureKind::SourceContract)); + } + // the window holds at most a candidate's bytes and one chunk: its capacity is charged as it grows + let before = scan.window.capacity(); + if scan.window.len() + count > before { + let wanted = (scan.window.len() + count).max(RESYNC_CANDIDATE_MAX + RESYNC_CHUNK.min(1 << 16)); + self.usage.charge(Resource::MetadataBytes, (wanted - before) as u64)?; + scan.window + .try_reserve_exact(wanted - scan.window.len()) + .map_err(|_| ProgressiveFailure::new(FailureKind::Malformed("resync allocation")))?; + self.usage.charge(Resource::MetadataBytes, scan.window.capacity().saturating_sub(wanted) as u64)?; + } + scan.window.extend_from_slice(&self.buffer[..count]); + scan.chunk = scan.chunk.saturating_mul(2).min(RESYNC_CHUNK); + self.driver.validate_step()?; + Ok(None) + } + } + } +} diff --git a/src/rar5/framing.rs b/src/rar5/framing.rs index c4c0f4c4..a7fd11a4 100644 --- a/src/rar5/framing.rs +++ b/src/rar5/framing.rs @@ -293,14 +293,64 @@ impl HeaderParser { }; } pub(crate) fn advance(&mut self, bytes: &[u8]) -> ProgressiveResult<(usize, ParserStep)> { - self.advance_core(bytes).map_err(|error| { - let mut failure = error.progressive(); - failure.context.packed_offset = Some(self.at); - if !self.path.as_os_str().is_empty() { - failure.context.expected = Some(std::mem::take(&mut self.path).into_os_string()); - } - failure - }) + self.advance_core(bytes).map_err(|error| self.progressive_error(error)) + } + fn progressive_error(&mut self, error: FramingError) -> ProgressiveFailure { + let mut failure = error.progressive(); + failure.context.packed_offset = Some(self.at); + if !self.path.as_os_str().is_empty() { + failure.context.expected = Some(std::mem::take(&mut self.path).into_os_string()); + } + failure + } + /// [`Self::advance`] for a progressive session under [`crate::extract::DamagedInput::Salvage`] or `Resync`: a + /// failure that is header damage (a header that fails its checksum and doesn't parse, doesn't frame, or runs + /// past the end of the volume) is `Ok(Err(kind))`, the header starting at [`Self::header_offset`], and the + /// parser stays stopped until [`Self::resume_at`]. As [`crate::rar5::reader::Volume`] decides it; never with + /// encrypted headers, where a failed checksum is how a wrong password shows. Every other failure is `Err`. + pub(crate) fn advance_salvaging( + &mut self, + bytes: &[u8], + ) -> ProgressiveResult> { + if !self.salvage || self.encrypted() { + return self.advance(bytes).map(Ok); + } + match self.advance_core(bytes) { + Ok(step) => Ok(Ok(step)), + Err(error) => match salvage_kind(&error) { + Some(kind) => Ok(Err(kind)), + None => Err(self.progressive_error(error)), + }, + } + } + /// Whether damaged headers are read past ([`Self::set_salvage`]). + pub(crate) fn salvages(&self) -> bool { + self.salvage + } + /// Whether an unreadable header is searched past ([`crate::extract::DamagedInput::Resync`]). + pub(crate) fn resyncs(&self) -> bool { + self.resync + } + /// The volume's length, once a progressive session under salvage knows it: a header or data running past it is + /// a volume cut short ([`crate::extract::HeaderDamageKind::UnexpectedEnd`]) and reading stops there, as for a + /// whole volume. + pub(crate) fn set_complete_len(&mut self, len: u64) { + self.complete_len = Some(len); + } + pub(crate) fn complete_len(&self) -> Option { + self.complete_len + } + /// At a block boundary, with nothing of the next header read. + pub(crate) fn at_block_start(&self) -> bool { + self.signature.is_none() && self.buffer.is_empty() && matches!(self.phase, Phase::Prefix | Phase::Rar4Prefix) + } + /// Reading goes on at `at`, where a resync found a header whose checksum passes: a stopped parser starts again, + /// keeping its format and the volume's header byte count. Never used with encrypted headers. + pub(crate) fn resume_at(&mut self, at: u64) { + self.at = at; + self.failed = false; + self.ended = false; + self.reset(); } fn scope(&self) -> RarScope { RarScope::Header { volume: self.path.clone() } @@ -650,6 +700,23 @@ impl HeaderParser { } } +/// What a salvaging run reads past ([`crate::extract::DamagedInput::Salvage`]): a header failure that is damage, as +/// [`crate::rar5::reader::Volume`] tells it apart. +fn salvage_kind(error: &FramingError) -> Option { + use crate::extract::HeaderDamageKind; + let (FramingError::Rar(fault) | FramingError::Checksum { fault, .. }) = error else { return None }; + match fault.failure.as_ref() { + RarFailure::Integrity { scope: RarScope::Header { .. }, reason, .. } => match reason { + RarIntegrityReason::TruncatedHeader | RarIntegrityReason::TruncatedData => { + Some(HeaderDamageKind::UnexpectedEnd) + } + RarIntegrityReason::HeaderCrc | RarIntegrityReason::HeaderFraming(_) => Some(HeaderDamageKind::Unreadable), + _ => None, + }, + _ => None, + } +} + pub(crate) fn progressive_fault(fault: RarFault) -> ProgressiveFailure { let kind = match *fault.failure { RarFailure::PasswordRequired { .. } => FailureKind::PasswordRequired, diff --git a/src/rar5/reader.rs b/src/rar5/reader.rs index 63614bdb..df911a72 100644 --- a/src/rar5/reader.rs +++ b/src/rar5/reader.rs @@ -57,11 +57,11 @@ type ParsedBlock = (Block, MemberCrypt, Option); const MAX_DAMAGE_NAME: usize = 1024; /// [`Volume::resync`] reads the volume this many bytes at a time. -const RESYNC_CHUNK: usize = 1 << 20; +pub(crate) const RESYNC_CHUNK: usize = 1 << 20; /// The first chunk a resync reads: most land on a header within it, and a run of resyncs close together reads little. -const RESYNC_FIRST_CHUNK: usize = 64; +pub(crate) const RESYNC_FIRST_CHUNK: usize = 64; /// Bytes past each chunk a resync reads, so that every position in the chunk shows its header's fixed fields. -const RESYNC_LOOKAHEAD: usize = 32; +pub(crate) const RESYNC_LOOKAHEAD: usize = 32; /// The longest RAR 5.0 file or service header a resync checks: real ones, names and extra records included, are far /// shorter. An end header is at most [`RESYNC_END_MAX`]. const RESYNC_HEADER_MAX: usize = 8 << 10; @@ -71,13 +71,13 @@ const RESYNC_END_MAX: usize = 32; const RESYNC_RAR4_HEADER_MAX: usize = 32 + 2048 + 64; /// Work (bytes read and checksummed) all the resyncs in a volume may do per byte of the volume (plus 1 MiB), keeping /// them linear. -const RESYNC_WORK_PER_BYTE: u64 = 16; +pub(crate) const RESYNC_WORK_PER_BYTE: u64 = 16; /// The length of the header [`Volume::resync`] would check at the start of `b` (up to [`RESYNC_LOOKAHEAD`] bytes of /// it), from its fixed fields alone: a file, service or end header of a plausible size and with plausible fields. None /// when it is none. Random bytes pass about once in a few thousand positions, with a short header, so that checking /// what passes costs about a byte per byte scanned. -fn resync_shape(b: &[u8], format: RarFormat) -> Option { +pub(crate) fn resync_shape(b: &[u8], format: RarFormat) -> Option { if b.len() < 7 { return None; } @@ -136,7 +136,7 @@ fn resync_shape(b: &[u8], format: RarFormat) -> Option { } /// Whether the whole header `h` (as long as [`resync_shape`] said) passes its checksum. -fn resync_checks(h: &[u8], format: RarFormat) -> bool { +pub(crate) fn resync_checks(h: &[u8], format: RarFormat) -> bool { match format { RarFormat::Rar5 => crate::crc32::hash(&h[4..]) == u32::from_le_bytes([h[0], h[1], h[2], h[3]]), RarFormat::Rar4 => crate::crc32::hash(&h[2..]) as u16 == u16::from_le_bytes([h[0], h[1]]), diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs new file mode 100644 index 00000000..c0b797e3 --- /dev/null +++ b/tests/progressive_salvage.rs @@ -0,0 +1,778 @@ +// Copyright (C) 2026 xbmc4lyfe +// SPDX-License-Identifier: RPL-1.5 +// +// Unless explicitly acquired and licensed from Licensor under another license, +// the contents of this file are subject to the Reciprocal Public License +// ("RPL") Version 1.5, or subsequent versions as allowed by the RPL, and You +// may not copy or use this file in either source code or executable form, +// except in compliance with the terms and conditions of the RPL. +// +// All software distributed under the RPL is provided strictly on an "AS IS" +// basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND LICENSOR +// HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY +// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET +// ENJOYMENT, OR NON-INFRINGEMENT. See the RPL for specific language governing +// rights and limitations under the RPL. + +//! `Options::damaged_input` in a progressive session (`ProgressiveOptions::extract`): damaged RAR headers read past +//! as the whole-archive runners read them (`tests/rar_salvage.rs`), over sealed memory and over a source that +//! delivers its bytes a few at a time, and reported as `ProgressiveEvent::HeaderDamaged`. A header the source has +//! not delivered yet is waited on, never damage. + +#![cfg(unix)] + +mod common; + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::fs; +use std::ops::Range; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::task::{Context, Poll, Waker}; +use std::time::{Duration, Instant}; + +use common::{FileSpec, SIG, end_block, file_block, main_block}; +use zipfast::crc32::hash; +use zipfast::extract::{self, DamagedInput, HeaderDamageKind, Mode, Overwrite}; +use zipfast::progressive::*; + +const A: &[u8] = b"alpha alpha alpha alpha alpha alpha alpha alpha alpha alpha"; +const B: &[u8] = b"bravo bravo bravo bravo bravo bravo bravo bravo bravo bravo bravo bravo"; +const C: &[u8] = b"charlie charlie charlie charlie charlie charlie charlie charlie charlie charlie"; +const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/rar-salvage"); + +fn extract_options(dest: &Path, mode: Mode, damaged: DamagedInput) -> extract::Options { + extract::Options { + mode, + dest: dest.to_path_buf(), + overwrite: Overwrite::Always, + flatten: false, + threads: Some(1), + protected_paths: Default::default(), + parallel_min: None, + select: None, + windows_safe_names: false, + special_entries: Default::default(), + fallback_mtime: None, + compressed_tar: Default::default(), + version_naming: Default::default(), + preexisting_links: Default::default(), + refused_link_placeholder: false, + restart_from_first_volume: false, + replace_placed_links: false, + keep_broken: false, + attempt_continued_members: false, + damaged_input: damaged, + unsupported_filters: Default::default(), + salvage_truncated_zip: false, + unix_modes: Default::default(), + backslashes: Default::default(), + } +} + +/// A RAR 5.0 archive of a.txt, b.txt, c.txt stored, and where each header starts. +fn rar5() -> (Vec, [usize; 4]) { + let mut out = SIG.to_vec(); + out.extend(main_block(false, None)); + let mut at = [0; 4]; + for (i, (name, data)) in [("a.txt", A), ("b.txt", B), ("c.txt", C)].into_iter().enumerate() { + at[i] = out.len(); + out.extend(file_block(&FileSpec::new(name, data), data, hash(data), false, false)); + } + at[3] = out.len(); + out.extend(end_block(false)); + (out, at) +} + +fn rar4_block(kind: u8, flags: u16, body: &[u8]) -> Vec { + let mut bytes = vec![0, 0, kind]; + bytes.extend(flags.to_le_bytes()); + bytes.extend(((body.len() + 7) as u16).to_le_bytes()); + bytes.extend(body); + let crc = hash(&bytes[2..]) as u16; + bytes[..2].copy_from_slice(&crc.to_le_bytes()); + bytes +} + +fn rar4_member(name: &[u8], data: &[u8]) -> Vec { + let mut body = Vec::new(); + body.extend((data.len() as u32).to_le_bytes()); + body.extend((data.len() as u32).to_le_bytes()); + body.push(3); + body.extend(hash(data).to_le_bytes()); + body.extend(0x50221884u32.to_le_bytes()); + body.extend([20, 0x30]); + body.extend((name.len() as u16).to_le_bytes()); + body.extend(0o100644u32.to_le_bytes()); + body.extend(name); + let mut bytes = rar4_block(0x74, 0x8000, &body); + bytes.extend(data); + bytes +} + +/// A RAR 4.x archive of a.txt, b.txt, c.txt stored, and where each header starts. +fn rar4() -> (Vec, [usize; 4]) { + let mut out = b"Rar!\x1a\x07\0".to_vec(); + out.extend(rar4_block(0x73, 0, &[0; 6])); + let mut at = [0; 4]; + for (i, (name, data)) in [(&b"a.txt"[..], A), (b"b.txt", B), (b"c.txt", C)].into_iter().enumerate() { + at[i] = out.len(); + out.extend(rar4_member(name, data)); + } + at[3] = out.len(); + out.extend(rar4_block(0x7b, 0x4000, &[])); + (out, at) +} + +fn garbage(len: usize) -> Vec { + (0..len).map(|i| (i * 37 + 11) as u8).collect() +} + +/// How the session gets its bytes. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Route { + /// `ProgressiveSession::from_sealed_memory`: every volume up front, published as verified. + Sealed, + /// A provider that delivers a few bytes a call and `NotYet` past what it has so far, as a download does; its + /// members end as provisional artifacts. + Pieces, +} + +/// A volume revealed a few bytes at a time: `NotYet` past `revealed`, and bytes in `gate` held back (`NotYet`, or a +/// `Hole` when `hole`) until `open`. +struct Trickle { + data: Vec, + revealed: Arc, + gate: Range, + open: Arc, + hole: bool, +} +impl RangeSource for Trickle { + fn info(&self) -> SourceInfo { + SourceInfo { + id: SourceId(self.data.len() as u128 + 1), + generation: 0, + extent: self.data.len() as u64, + length: SourceLength::Final(self.data.len() as u64), + } + } + fn backing_files(&self) -> &[fs::File] { + &[] + } + fn read_at(&mut self, at: u64, buf: &mut [u8], cx: &mut Context<'_>) -> ProgressiveResult { + let shut = !self.open.load(Ordering::SeqCst); + if shut && self.gate.contains(&at) { + if self.hole { + return Ok(RangeRead::Hole { len: (self.gate.end - at).min(buf.len() as u64) }); + } + cx.waker().wake_by_ref(); + return Ok(RangeRead::NotYet); + } + let revealed = self.revealed.load(Ordering::SeqCst).min(self.data.len() as u64); + if at >= revealed { + cx.waker().wake_by_ref(); + return Ok(RangeRead::NotYet); + } + let mut end = revealed.min(at + buf.len() as u64).min(at + 13); + if shut && self.gate.start > at { + end = end.min(self.gate.start); + } + let n = (end - at) as usize; + buf[..n].copy_from_slice(&self.data[at as usize..end as usize]); + Ok(RangeRead::Filled { count: n }) + } +} +struct Provider { + volumes: Vec>, + revealed: Arc, + gate: Range, + open: Arc, + hole: bool, +} +impl VolumeSource for Provider { + fn volume(&mut self, request: &VolumeRequest, _: &mut Context<'_>) -> ProgressiveResult { + let Some(data) = self.volumes.get(request.index as usize) else { return Ok(VolumeAnswer::Missing) }; + Ok(VolumeAnswer::Ready(Box::new(Trickle { + data: data.clone(), + revealed: self.revealed.clone(), + gate: if request.index == 0 { self.gate.clone() } else { 0..0 }, + open: self.open.clone(), + hole: self.hole, + }))) + } +} + +/// One damage record, as compared across routes: (volume index, offset, kind, name, resumed at). +type Damage = (u32, u64, HeaderDamageKind, Option, Option); + +#[derive(Debug, Default)] +struct Outcome { + /// How the session ended: `None` when it ran to its end, else the failure kind. + failure: Option, + /// Files written whole, by name. + files: BTreeMap>, + dirs: Vec, + /// Members that stopped, by name, with why. + stopped: Vec<(String, String)>, + damage: Vec, +} + +/// Knobs for one progressive run. +struct Run<'a> { + volumes: &'a [(&'a str, Vec)], + damaged: DamagedInput, + route: Route, + gate: Range, + hole: bool, + /// Called on every `Pending` with the outcome so far; returns whether to open the gate. + on_pending: &'a mut dyn FnMut(&Outcome) -> bool, +} + +fn progressive(run: Run<'_>) -> Outcome { + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("out"); + fs::create_dir(&dest).unwrap(); + let mut options = + ProgressiveOptions::new(extract_options(&dest, Mode::Extract, run.damaged), OsString::from(run.volumes[0].0)); + options.artifact_aftermath = ArtifactAftermath::RetainProvisional; + let revealed = Arc::new(AtomicU64::new(0)); + let open = Arc::new(AtomicBool::new(run.gate.is_empty())); + let session = match run.route { + Route::Sealed => ProgressiveSession::from_sealed_memory( + run.volumes.iter().map(|(name, bytes)| (OsString::from(*name), bytes.clone().into_boxed_slice())).collect(), + options, + ), + Route::Pieces => ProgressiveSession::new( + Box::new(Provider { + volumes: run.volumes.iter().map(|(_, bytes)| bytes.clone()).collect(), + revealed: revealed.clone(), + gate: run.gate.clone(), + open: open.clone(), + hole: run.hole, + }), + options, + ), + }; + let mut out = Outcome::default(); + let mut session = match session { + Ok(session) => session, + Err(failure) => { + out.failure = Some(format!("{:?}", failure.kind)); + return out; + } + }; + let mut names: std::collections::HashMap = Default::default(); + let mut cx = Context::from_waker(Waker::noop()); + let started = Instant::now(); + loop { + assert!(started.elapsed() < Duration::from_secs(60), "the session never ended"); + match session.poll_event(&mut cx) { + Poll::Pending => { + revealed.fetch_add(7, Ordering::SeqCst); + if (run.on_pending)(&out) { + open.store(true, Ordering::SeqCst); + } + } + Poll::Ready(Ok(None)) => break, + Poll::Ready(Err(failure)) => { + out.failure = Some(format!("{:?}", failure.kind)); + break; + } + Poll::Ready(Ok(Some(event))) => match event { + ProgressiveEvent::HeaderDamaged { volume, damage } => { + assert_eq!(damage.volume, Path::new(run.volumes[volume as usize].0)); + out.damage.push((volume, damage.offset, damage.kind, damage.name.clone(), damage.resumed_at)); + } + ProgressiveEvent::MemberStarted { member, name, .. } => { + names.insert(member, String::from_utf8_lossy(&name).into_owned()); + } + ProgressiveEvent::MemberFinished { member, outcome } => { + let name = names[&member].clone(); + match outcome { + MemberOutcome::Verified(_) => { + // a damaged name may be written under another (sanitized) path: then it reads empty + out.files.insert(name.clone(), fs::read(dest.join(&name)).unwrap_or_default()); + } + MemberOutcome::Provisional(mut artifact) => { + let mut bytes = vec![0; artifact.produced_extent() as usize]; + let mut at = 0; + while at < bytes.len() { + match artifact.read_at(at as u64, &mut bytes[at..]).unwrap() { + ArtifactRead::Filled { count } => at += count, + other => panic!("{name}: {other:?}"), + } + } + out.files.insert(name, bytes); + artifact.discard().unwrap(); + } + MemberOutcome::Directory { .. } => out.dirs.push(name), + MemberOutcome::Stopped { failure, artifact, .. } => { + if let Some(mut artifact) = artifact { + artifact.discard().unwrap(); + } + out.stopped.push((name, format!("{:?}", failure.kind))); + } + _ => panic!("{name}: unexpected outcome"), + } + } + ProgressiveEvent::SessionTerminated { failure, artifact, .. } => { + if let Some(mut artifact) = artifact { + artifact.discard().unwrap(); + } + out.failure = Some(format!("{:?}", failure.kind)); + break; + } + _ => {} + }, + } + } + out +} + +fn run_simple(volumes: &[(&str, Vec)], damaged: DamagedInput, route: Route) -> Outcome { + progressive(Run { volumes, damaged, route, gate: 0..0, hole: false, on_pending: &mut |_| false }) +} + +/// What `extract::run` makes of the same volumes: files and bytes, folders, and the damage list. +fn whole(volumes: &[(&str, Vec)], damaged: DamagedInput) -> Option { + let dir = tempfile::tempdir().unwrap(); + for (name, bytes) in volumes { + fs::write(dir.path().join(name), bytes).unwrap(); + } + let dest = dir.path().join("out"); + let summary = + extract::run(&dir.path().join(volumes[0].0), &extract_options(&dest, Mode::Extract, damaged), |_| {}).ok()?; + let mut out = Outcome::default(); + if dest.exists() { + for entry in fs::read_dir(&dest).unwrap() { + let entry = entry.unwrap(); + let name = entry.file_name().into_string().unwrap(); + if entry.file_type().unwrap().is_dir() { + out.dirs.push(name); + } else { + out.files.insert(name, fs::read(entry.path()).unwrap()); + } + } + } + out.dirs.sort(); + for damage in &summary.damaged_headers { + let name = damage.volume.file_name().unwrap(); + let volume = volumes.iter().position(|(v, _)| name == *v).unwrap() as u32; + out.damage.push((volume, damage.offset, damage.kind, damage.name.clone(), damage.resumed_at)); + } + Some(out) +} + +/// The damaged archives of `tests/rar_salvage.rs`, each a set of named volumes. +/// Named volumes, in order. +type Volumes = Vec<(&'static str, Vec)>; + +fn cases() -> Vec<(&'static str, Volumes)> { + let one = |bytes: Vec| vec![("a.rar", bytes)]; + let mut cases = Vec::new(); + for (format, (bytes, at)) in [("rar5", rar5()), ("rar4", rar4())] { + let mut crc = bytes.clone(); + crc[at[1]] ^= 0x5a; + cases.push((if format == "rar5" { "rar5 header crc" } else { "rar4 header crc" }, one(crc))); + let main = if format == "rar5" { 8 } else { 7 }; + let mut damaged_main = bytes.clone(); + damaged_main[main] ^= 0x5a; + cases.push((if format == "rar5" { "rar5 main crc" } else { "rar4 main crc" }, one(damaged_main))); + let mut junk = bytes[..at[1]].to_vec(); + junk.extend(garbage(300)); + junk.extend(&bytes[at[1]..]); + cases.push((if format == "rar5" { "rar5 garbage" } else { "rar4 garbage" }, one(junk))); + let mut zeros = bytes.clone(); + zeros[at[1]..at[1] + 20].fill(0); + cases.push((if format == "rar5" { "rar5 zeroed header" } else { "rar4 zeroed header" }, one(zeros))); + cases.push(( + if format == "rar5" { "rar5 cut in header" } else { "rar4 cut in header" }, + one(bytes[..at[1] + 9].to_vec()), + )); + } + let (bytes, at) = rar5(); + let mut renamed = bytes.clone(); + let name = at[1] + bytes[at[1]..].windows(5).position(|w| w == b"b.txt").unwrap(); + renamed[name + 1] = b't'; + cases.push(("rar5 damaged name", one(renamed))); + cases.push(("rar5 without end", one(bytes[..at[3]].to_vec()))); + let (mut typed, at4) = rar4(); + typed[at4[1] + 2] ^= 0x5a; + cases.push(("rar4 damaged type", one(typed))); + for file in [ + "salvage-rar5-dir-crc.rar", + "salvage-rar5-main-and-dir-crc.rar", + "list-rar4-cut-in-main.rar", + "list-rar4-cut-at-main.rar", + "hdrerr-rar5-no-end.rar", + "hdrerr-rar4-cut-in-file.rar", + ] { + cases.push((file, one(fs::read(Path::new(FIXTURES).join(file)).unwrap()))); + } + let mut first = SIG.to_vec(); + first.extend(main_block(true, None)); + first.extend(file_block(&FileSpec::new("a.txt", A), A, hash(A), false, false)); + first.extend(garbage(64)); + let mut second = SIG.to_vec(); + second.extend(main_block(true, Some(1))); + second.extend(file_block(&FileSpec::new("c.txt", C), C, hash(C), false, false)); + second.extend(end_block(false)); + cases.push(("two volumes", vec![("set.part1.rar", first), ("set.part2.rar", second.clone())])); + // the second volume's main header fails its checksum: read on as present + let mut ended = SIG.to_vec(); + ended.extend(main_block(true, None)); + ended.extend(file_block(&FileSpec::new("a.txt", A), A, hash(A), false, false)); + ended.extend(end_block(true)); + let mut second_main = second; + second_main[SIG.len()] ^= 0x5a; + cases.push(("second main crc", vec![("set.part1.rar", ended), ("set.part2.rar", second_main)])); + cases +} + +/// The default refuses every damaged archive as before: no `HeaderDamaged` event, the session fails at the damage. +#[test] +fn refuse_fails_at_the_damage_as_before() { + for (case, volumes) in cases() { + for route in [Route::Sealed, Route::Pieces] { + let out = run_simple(&volumes, DamagedInput::Refuse, route); + assert!(out.damage.is_empty(), "{case} {route:?}"); + assert!(out.failure.is_some(), "{case} {route:?}: {out:?}"); + } + } +} + +/// `Salvage` and `Resync` extract what `extract::run` extracts from the same damaged archive under the same choice: +/// the same members, the same bytes, the same folders and the same damage list, over sealed memory and fed in pieces. +#[test] +fn salvage_and_resync_extract_what_the_whole_archive_runner_does() { + for (case, volumes) in cases() { + for damaged in [DamagedInput::Salvage, DamagedInput::Resync] { + let expected = + whole(&volumes, damaged).unwrap_or_else(|| panic!("{case} {damaged:?}: extract::run failed")); + assert!(!expected.damage.is_empty(), "{case} {damaged:?}: not damaged"); + for route in [Route::Sealed, Route::Pieces] { + let out = run_simple(&volumes, damaged, route); + let at = format!("{case} {damaged:?} {route:?}"); + assert_eq!(out.failure, None, "{at}: {out:?}"); + assert!(out.stopped.is_empty(), "{at}: {out:?}"); + assert_eq!(out.files, expected.files, "{at}"); + let mut dirs = out.dirs.clone(); + dirs.sort(); + assert_eq!(dirs, expected.dirs, "{at}"); + assert_eq!(out.damage, expected.damage, "{at}"); + } + } + } +} + +/// b.txt's header is still to come (`NotYet`) while everything around it is there: under `Salvage` and `Resync` the +/// session waits for it, reports nothing, and extracts all three members once it arrives. The same header answered +/// as a `Hole` (lost, maybe to be repaired) is `HeaderHole`, as under `Refuse`: neither read past nor searched across. +#[test] +fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_is_not_damage() { + for (format, (bytes, at)) in [("rar5", rar5()), ("rar4", rar4())] { + let gate = at[1] as u64..at[1] as u64 + 12; + let volumes = [("a.rar", bytes.clone())]; + for damaged in [DamagedInput::Salvage, DamagedInput::Resync] { + let mut waits = 0; + let out = progressive(Run { + volumes: &volumes, + damaged, + route: Route::Pieces, + gate: gate.clone(), + hole: false, + on_pending: &mut |seen| { + assert!(seen.damage.is_empty(), "{format} {damaged:?}: {:?}", seen.damage); + assert!(!seen.files.contains_key("b.txt")); + waits += 1; + waits > 400 + }, + }); + assert!(waits > 400, "{format} {damaged:?}: the session did not wait for the header"); + assert_eq!(out.failure, None, "{format} {damaged:?}"); + assert!(out.damage.is_empty(), "{format} {damaged:?}: {:?}", out.damage); + assert_eq!(out.files.keys().collect::>(), ["a.txt", "b.txt", "c.txt"], "{format} {damaged:?}"); + assert_eq!(out.files["b.txt"], B); + assert_eq!(out.files["c.txt"], C); + + let out = progressive(Run { + volumes: &volumes, + damaged, + route: Route::Pieces, + gate: gate.clone(), + hole: true, + on_pending: &mut |_| false, + }); + assert_eq!(out.failure.as_deref(), Some("HeaderHole"), "{format} {damaged:?}"); + assert!(out.damage.is_empty(), "{format} {damaged:?}: {:?}", out.damage); + assert_eq!(out.files.keys().collect::>(), ["a.txt"], "{format} {damaged:?}"); + } + } +} + +/// A hole answered inside the stretch a resync searches stops it with `HeaderHole`: the next header may be in it. +#[test] +fn a_resync_never_searches_across_a_hole() { + let (bytes, at) = rar5(); + let mut damaged = bytes[..at[1]].to_vec(); + damaged.extend(garbage(300)); + damaged.extend(&bytes[at[1]..]); + let gate = at[1] as u64 + 200..at[1] as u64 + 260; + let out = progressive(Run { + volumes: &[("a.rar", damaged)], + damaged: DamagedInput::Resync, + route: Route::Pieces, + gate, + hole: true, + on_pending: &mut |_| false, + }); + assert_eq!(out.failure.as_deref(), Some("HeaderHole")); + assert!(out.damage.is_empty(), "{:?}", out.damage); + assert_eq!(out.files.keys().collect::>(), ["a.txt"]); +} + +/// A solid archive whose middle member's header is lost (zeroed and searched past, or read as a service, a main header +/// or a folder whose data is skipped): the member after it must fail as lacking its history, never decode against +/// the history from before the gap. Its header carries no CRC32, so only that rule stands between it and wrong bytes. +#[test] +fn solid_history_after_a_skipped_header_fails_the_next_solid_member() { + use zipfast::rar5::testenc::{self, Op}; + let ops: [Vec; 3] = [vec![Op::Lit(b'a'); 100], vec![Op::Lit(b'b'); 100], vec![Op::Match(100, 100)]]; + let mut all = Vec::new(); + let mut plain = Vec::new(); + let mut at = 0; + for o in &ops { + all.extend(o.iter().cloned()); + let model = testenc::model(&all); + plain.push(model[at..].to_vec()); + at = model.len(); + } + let streams: Vec> = ops.iter().map(|o| testenc::block(o, true, true)).collect(); + let names = ["a.bin", "b.bin", "c.bin"]; + let mut bytes = SIG.to_vec(); + bytes.extend(common::main_block_flags(false, None, true)); + let mut offsets = Vec::new(); + for i in 0..3 { + offsets.push(bytes.len()); + let spec = FileSpec { + method: 3, + size: Some(plain[i].len() as u64), + solid: i > 0, + no_crc: i == 2, + ..FileSpec::new(names[i], &streams[i]) + }; + bytes.extend(file_block(&spec, &streams[i], hash(&plain[i]), false, false)); + } + bytes.extend(end_block(false)); + for route in [Route::Sealed, Route::Pieces] { + let out = run_simple(&[("a.rar", bytes.clone())], DamagedInput::Resync, route); + assert_eq!(out.files["c.bin"], plain[2], "intact {route:?}"); + } + + let mut hole = bytes.clone(); + hole[offsets[1]..offsets[1] + 16].fill(0); + let mut service = bytes.clone(); + service[offsets[1] + 5] = 3; + let mut main = bytes.clone(); + main[offsets[1] + 5] = 1; + let mut folder = bytes.clone(); + let flags = { + let mut at = offsets[1] + 4; + for _ in 0..4 { + while bytes[at] & 0x80 != 0 { + at += 1; + } + at += 1; + } + at + }; + assert_eq!(folder[flags], 0x06, "b.bin's file flags (CRC32, mtime)"); + folder[flags] |= 0x01; + for (what, damaged) in [("hole", hole), ("service", service), ("main", main), ("folder", folder)] { + for choice in [DamagedInput::Salvage, DamagedInput::Resync] { + if what == "hole" && choice == DamagedInput::Salvage { + continue; // the volume ends at the hole: nothing after it is read + } + for route in [Route::Sealed, Route::Pieces] { + let at = format!("{what} {choice:?} {route:?}"); + let out = run_simple(&[("a.rar", damaged.clone())], choice, route); + assert_eq!(out.failure, None, "{at}: {out:?}"); + assert_eq!(out.files.get("a.bin"), Some(&plain[0]), "{at}"); + assert!(!out.files.contains_key("c.bin"), "{at}: c.bin decoded against stale history"); + assert_eq!(out.stopped.len(), 1, "{at}: {out:?}"); + assert_eq!(out.stopped[0].0, "c.bin", "{at}"); + assert!(out.stopped[0].1.contains("SolidHistoryUnavailable"), "{at}: {:?}", out.stopped); + assert_eq!(out.damage.len(), 1, "{at}: {:?}", out.damage); + assert_eq!(out.dirs, if what == "folder" { vec!["b.bin".to_owned()] } else { vec![] }, "{at}"); + } + } + } +} + +/// Hostile input: every 37th byte of a three-member archive changed, under each salvaging choice and over both +/// routes: nothing panics and every session ends. +#[test] +fn corrupting_every_37th_offset_never_panics() { + let started = Instant::now(); + for (bytes, _) in [rar5(), rar4()] { + for offset in (0..bytes.len()).step_by(37) { + for value in [0x00, 0xff, bytes[offset] ^ 0x5a] { + let mut damaged = bytes.clone(); + damaged[offset] = value; + for choice in [DamagedInput::Salvage, DamagedInput::Resync] { + for route in [Route::Sealed, Route::Pieces] { + let out = run_simple(&[("a.rar", damaged.clone())], choice, route); + if out.failure.is_none() && damaged != bytes { + // whatever was read past is reported, or the damage was in a member's data + assert!(!out.damage.is_empty() || !out.stopped.is_empty() || out.files.len() == 3); + } + } + } + } + } + } + assert!(started.elapsed() < Duration::from_secs(60), "took {:?}", started.elapsed()); +} + +fn noise(len: usize, mut seed: u64) -> Vec { + (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }) + .collect() +} + +/// Megabytes of random bytes, and a stretch packed with headers whose fixed fields look right but whose checksums +/// fail, between a.txt and b.txt: a progressive resync crosses both in bounded, linear work and recovers b.txt and +/// c.txt. +#[test] +fn resync_crosses_random_data_and_false_headers_in_bounded_work() { + let (bytes, at) = rar5(); + let mut fake = Vec::new(); + for _ in 0..20_000 { + // a RAR 5.0 end header shape (size 3, type 5) with a wrong CRC32 + fake.extend([0xde, 0xad, 0xbe, 0xef, 3, 5, 0, 0]); + } + for (what, filler) in [("noise", noise(4 << 20, 0x9e37_79b9_7f4a_7c15)), ("false headers", fake)] { + let mut damaged = bytes[..at[1]].to_vec(); + // a header of size 0: unreadable, so the search starts here + damaged.extend([0; 5]); + damaged.extend(&filler); + damaged.extend(&bytes[at[1]..]); + let started = Instant::now(); + let out = run_simple(&[("a.rar", damaged)], DamagedInput::Resync, Route::Sealed); + assert!(started.elapsed() < Duration::from_secs(20), "{what}: took {:?}", started.elapsed()); + assert_eq!(out.failure, None, "{what}: {out:?}"); + assert_eq!(out.files.keys().collect::>(), ["a.txt", "b.txt", "c.txt"], "{what}"); + assert_eq!(out.damage.len(), 1, "{what}: {:?}", out.damage); + assert_eq!(out.damage[0].4, Some((at[1] + 5 + filler.len()) as u64), "{what}"); + } +} + +/// A persistent session refuses a damaged header whatever `damaged_input` says: its journal binds each member to +/// the header bytes it was read from, so salvage there is a follow-up. +#[cfg(feature = "persistent-partials")] +#[test] +fn a_persistent_session_still_refuses_damaged_headers() { + use std::sync::Mutex; + use zipfast::partial::*; + + struct Source(Vec); + impl RangeSource for Source { + fn info(&self) -> SourceInfo { + SourceInfo { + id: SourceId(1), + generation: 0, + extent: self.0.len() as u64, + length: SourceLength::Final(self.0.len() as u64), + } + } + fn backing_files(&self) -> &[fs::File] { + &[] + } + fn read_at(&mut self, at: u64, buf: &mut [u8], _: &mut Context<'_>) -> ProgressiveResult { + let end = (at as usize + buf.len()).min(self.0.len()); + buf[..end - at as usize].copy_from_slice(&self.0[at as usize..end]); + Ok(RangeRead::Filled { count: end - at as usize }) + } + } + struct Set(Option>); + impl VolumeSource for Set { + fn protection(&mut self) -> ProgressiveResult { + Ok(ProtectionDeclaration::Complete { + epoch: 1, + inventory: ProtectionInventory { + volumes: vec![ProtectedVolume { index: 0, name: "a.rar".into(), backing: VolumeBacking::NonFile }], + auxiliary_paths: Vec::new(), + }, + }) + } + fn volume(&mut self, request: &VolumeRequest, _: &mut Context<'_>) -> ProgressiveResult { + match self.0.take().filter(|_| request.index == 0) { + Some(bytes) => Ok(VolumeAnswer::Ready(Box::new(Source(bytes)))), + None => Ok(VolumeAnswer::Missing), + } + } + } + #[derive(Default)] + struct Anchors(Mutex>); + impl StateAnchorStore for Anchors { + fn current(&self, member: &MemberKey) -> PartialResult> { + Ok(self.0.lock().unwrap().iter().find(|a| a.member() == member).cloned()) + } + fn compare_exchange( + &self, + member: &MemberKey, + expected: Option<&StateAnchor>, + next: &StateAnchor, + ) -> PartialResult<()> { + let mut anchors = self.0.lock().unwrap(); + let index = anchors.iter().position(|a| a.member() == member); + if index.map(|i| &anchors[i]) != expected { + return Err(PartialError::new(PartialErrorKind::AnchorConflict)); + } + match index { + Some(index) => anchors[index] = next.clone(), + None => anchors.push(next.clone()), + } + Ok(()) + } + } + + let (mut bytes, at) = rar5(); + bytes[at[1]] ^= 0x5a; + let dir = tempfile::tempdir().unwrap(); + let mut options = ProgressiveOptions::new( + extract_options(&dir.path().join("out"), Mode::Extract, DamagedInput::Resync), + OsString::from("a.rar"), + ); + options.hole_policy = HolePolicy::PartialStored { fill: HoleFill::Sparse }; + let partial = PartialOptions { + binding: ArchiveBinding { job: [1; 16], archive: [2; 32] }, + naming: PartialNaming::ArchivePath, + state_dir: dir.path().join("state"), + limits: PartialLimits::default(), + anchors: Arc::new(Anchors::default()), + control: SessionControl::default(), + }; + let mut session = ProgressiveSession::new_partial(Box::new(Set(Some(bytes))), options, partial).unwrap(); + let mut failed = false; + for _ in 0..100_000 { + match session.poll_event(&mut Context::from_waker(Waker::noop())) { + Poll::Pending => {} + Poll::Ready(Ok(None)) => break, + Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { .. }))) => panic!("a persistent session salvaged"), + Poll::Ready(Ok(Some(ProgressiveEvent::SessionTerminated { .. }))) | Poll::Ready(Err(_)) => { + failed = true; + break; + } + Poll::Ready(Ok(Some(_))) => {} + } + } + assert!(failed, "the damaged header did not stop the persistent session"); +} From 346db4586b69448b31a0d6686b86d59b193dbf1c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:06:29 -0800 Subject: [PATCH 2/5] Progressive salvage review fixes: resync charges delivered bytes only, no salvage before a signature or with encrypted headers - A resync charges its work allowance for bytes a read delivered, not for the buffer it asked for: a source delivering a few bytes a call (or waiting) no longer runs the allowance out while crossing a long stretch. - A source that ends before a RAR signature is refused as before instead of reading as a damaged empty archive. - An encrypted-header archive cut at a header boundary is a truncation, not damage: the parser salvages nothing once headers are encrypted, at the end of a volume too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/progressive/session/salvage.rs | 16 +++++---- src/rar5/framing.rs | 5 +-- tests/progressive_salvage.rs | 58 +++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 9 deletions(-) diff --git a/src/progressive/session/salvage.rs b/src/progressive/session/salvage.rs index 64b6ba3b..ba81da71 100644 --- a/src/progressive/session/salvage.rs +++ b/src/progressive/session/salvage.rs @@ -167,6 +167,10 @@ impl ProgressiveSession { /// The volume ended at a block boundary without its end header. A RAR 5.0 volume is cut short there (7-Zip 26.06: /// "Unexpected end of archive"); a RAR 4.x one may end so (archives older than RAR 2.9 write no end block). pub(super) fn salvage_volume_end(&mut self) -> ProgressiveResult<()> { + // a source that ends before a RAR signature was found is not a RAR volume, damaged or not + if self.parser.scanning() { + return Err(self.parser.truncated()); + } if !self.parser.at_block_start() { return self.salvage_header(HeaderDamageKind::UnexpectedEnd); } @@ -268,12 +272,6 @@ impl ProgressiveSession { Some(parked) if parked <= full.min(self.buffer.len()) => parked, _ => full.min(self.buffer.len()).min(budget).max(1), }; - if !self.resync_work.charge(n as u64) { - let Phase::Resync(scan) = &mut self.phase else { unreachable!() }; - scan.eof = true; - scan.window.truncate((scan.pos - scan.start) as usize); - return Ok(None); - } if at != self.cursor { self.driver.seek(at)?; self.cursor = at; @@ -306,6 +304,12 @@ impl ProgressiveSession { if offset != scan.start + scan.window.len() as u64 { return Err(ProgressiveFailure::new(FailureKind::SourceContract)); } + // only the bytes delivered count as work: a short read or a wait costs nothing + if !self.resync_work.charge(count as u64) { + scan.eof = true; + self.driver.validate_step()?; + return Ok(None); + } // the window holds at most a candidate's bytes and one chunk: its capacity is charged as it grows let before = scan.window.capacity(); if scan.window.len() + count > before { diff --git a/src/rar5/framing.rs b/src/rar5/framing.rs index a7fd11a4..94d564e1 100644 --- a/src/rar5/framing.rs +++ b/src/rar5/framing.rs @@ -323,9 +323,10 @@ impl HeaderParser { }, } } - /// Whether damaged headers are read past ([`Self::set_salvage`]). + /// Whether damaged headers are read past ([`Self::set_salvage`]): never once the archive is recognised as having + /// encrypted headers, where a failed checksum or a cut header is how a wrong password or a truncation shows. pub(crate) fn salvages(&self) -> bool { - self.salvage + self.salvage && !self.encrypted() } /// Whether an unreadable header is searched past ([`crate::extract::DamagedInput::Resync`]). pub(crate) fn resyncs(&self) -> bool { diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs index c0b797e3..9eac86c3 100644 --- a/tests/progressive_salvage.rs +++ b/tests/progressive_salvage.rs @@ -228,6 +228,7 @@ struct Run<'a> { hole: bool, /// Called on every `Pending` with the outcome so far; returns whether to open the gate. on_pending: &'a mut dyn FnMut(&Outcome) -> bool, + password: Option<&'a str>, } fn progressive(run: Run<'_>) -> Outcome { @@ -237,6 +238,7 @@ fn progressive(run: Run<'_>) -> Outcome { let mut options = ProgressiveOptions::new(extract_options(&dest, Mode::Extract, run.damaged), OsString::from(run.volumes[0].0)); options.artifact_aftermath = ArtifactAftermath::RetainProvisional; + options.set_password(run.password.map(str::to_owned)).unwrap(); let revealed = Arc::new(AtomicU64::new(0)); let open = Arc::new(AtomicBool::new(run.gate.is_empty())); let session = match run.route { @@ -332,7 +334,7 @@ fn progressive(run: Run<'_>) -> Outcome { } fn run_simple(volumes: &[(&str, Vec)], damaged: DamagedInput, route: Route) -> Outcome { - progressive(Run { volumes, damaged, route, gate: 0..0, hole: false, on_pending: &mut |_| false }) + progressive(Run { volumes, damaged, route, gate: 0..0, hole: false, on_pending: &mut |_| false, password: None }) } /// What `extract::run` makes of the same volumes: files and bytes, folders, and the damage list. @@ -489,6 +491,7 @@ fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_is_not_damage() { waits += 1; waits > 400 }, + password: None, }); assert!(waits > 400, "{format} {damaged:?}: the session did not wait for the header"); assert_eq!(out.failure, None, "{format} {damaged:?}"); @@ -504,6 +507,7 @@ fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_is_not_damage() { gate: gate.clone(), hole: true, on_pending: &mut |_| false, + password: None, }); assert_eq!(out.failure.as_deref(), Some("HeaderHole"), "{format} {damaged:?}"); assert!(out.damage.is_empty(), "{format} {damaged:?}: {:?}", out.damage); @@ -527,6 +531,7 @@ fn a_resync_never_searches_across_a_hole() { gate, hole: true, on_pending: &mut |_| false, + password: None, }); assert_eq!(out.failure.as_deref(), Some("HeaderHole")); assert!(out.damage.is_empty(), "{:?}", out.damage); @@ -674,6 +679,57 @@ fn resync_crosses_random_data_and_false_headers_in_bounded_work() { } } +/// A source that delivers a few bytes a call and waits in between: a resync charges only the bytes delivered, so +/// crossing a long garbage stretch in tiny pieces (and many waits) never runs out of its allowance. +#[test] +fn a_resync_fed_in_pieces_charges_only_the_bytes_delivered() { + let (bytes, at) = rar5(); + let filler = noise(256 << 10, 0x2545_f491_4f6c_dd1d); + let mut damaged = bytes[..at[1]].to_vec(); + damaged.extend([0; 5]); + damaged.extend(&filler); + damaged.extend(&bytes[at[1]..]); + let out = run_simple(&[("a.rar", damaged)], DamagedInput::Resync, Route::Pieces); + assert_eq!(out.failure, None, "{out:?}"); + assert_eq!(out.files.keys().collect::>(), ["a.txt", "b.txt", "c.txt"]); + assert_eq!(out.damage.len(), 1, "{:?}", out.damage); + assert_eq!(out.damage[0].4, Some((at[1] + 5 + filler.len()) as u64)); +} + +/// What isn't salvage: a source that ends before any RAR signature (empty, or a few bytes of something else) is +/// refused as before, and an archive with encrypted headers cut at a header boundary is a truncation, not damage +/// (encrypted headers are never salvaged). +#[test] +fn no_signature_and_encrypted_headers_are_not_salvaged() { + let mut fields = Vec::new(); + common::vint(0, &mut fields); // encryption version + common::vint(0, &mut fields); // flags: no password check + fields.push(15); // KDF count + fields.extend([7; 16]); // salt + let mut encrypted = SIG.to_vec(); + encrypted.extend(common::block(4, 0, &fields, &[], &[], false)); + for (what, bytes, password) in + [("empty", Vec::new(), None), ("not rar", b"hello".to_vec(), None), ("encrypted", encrypted, Some("pw"))] + { + for damaged in [DamagedInput::Refuse, DamagedInput::Salvage, DamagedInput::Resync] { + for route in [Route::Sealed, Route::Pieces] { + let volumes = [("a.rar", bytes.clone())]; + let out = progressive(Run { + volumes: &volumes, + damaged, + route, + gate: 0..0, + hole: false, + on_pending: &mut |_| false, + password, + }); + assert!(out.failure.is_some(), "{what} {damaged:?} {route:?}: {out:?}"); + assert!(out.damage.is_empty(), "{what} {damaged:?} {route:?}: {:?}", out.damage); + } + } + } +} + /// A persistent session refuses a damaged header whatever `damaged_input` says: its journal binds each member to /// the header bytes it was read from, so salvage there is a follow-up. #[cfg(feature = "persistent-partials")] From 9c628f5cd12e84a4bbb35b8c1a52346d2a2c372a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:12:17 -0800 Subject: [PATCH 3/5] Progressive salvage: a damaged first header that no longer reads as a main header reads on with an empty one As Volume::initialize_held does: a main header whose type byte was hit reads as a block of an unknown type, and the session now takes the main header as present (defaults) instead of failing with 'block before main'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/progressive/session/salvage.rs | 5 +++++ tests/progressive_salvage.rs | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/src/progressive/session/salvage.rs b/src/progressive/session/salvage.rs index ba81da71..bfc643fa 100644 --- a/src/progressive/session/salvage.rs +++ b/src/progressive/session/salvage.rs @@ -141,6 +141,11 @@ impl ProgressiveSession { self.main_seen = true; return Ok(false); } + if !self.main_seen && !matches!(frame.block, Block::Main(_)) { + // the volume's first header is damaged and reads as something else (a main header whose type byte was + // hit): read on with an empty main header, as the whole-archive runners do + self.main_seen = true; + } Ok(true) } /// The header at the parser's offset is damage of `kind`: searched past under `Resync`, else the rest of the diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs index 9eac86c3..d4faee1b 100644 --- a/tests/progressive_salvage.rs +++ b/tests/progressive_salvage.rs @@ -382,6 +382,10 @@ fn cases() -> Vec<(&'static str, Volumes)> { let mut damaged_main = bytes.clone(); damaged_main[main] ^= 0x5a; cases.push((if format == "rar5" { "rar5 main crc" } else { "rar4 main crc" }, one(damaged_main))); + // the main header's type byte hit: it reads as a block of an unknown type + let mut retyped = bytes.clone(); + retyped[if format == "rar5" { main + 5 } else { main + 2 }] = if format == "rar5" { 6 } else { 0x70 }; + cases.push((if format == "rar5" { "rar5 main type" } else { "rar4 main type" }, one(retyped))); let mut junk = bytes[..at[1]].to_vec(); junk.extend(garbage(300)); junk.extend(&bytes[at[1]..]); From 187c0c1c1b90711f1b1c3e484a8d61f6b7c7fe23 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:20:52 -0800 Subject: [PATCH 4/5] Progressive salvage review fixes: damage found by the session's last read is delivered; replacement replay reads salvaged headers - A HeaderDamaged queued by the read that also ends the session or uses up the poll's work is delivered before the end (poll_event drains the queue before its Done fast path and before yielding). - Strict replacement verification replays the header witnesses under the damaged-input choice they were read with: a damaged header is read as it stands (its bytes still compared with the witness) and the replay resumes where a resync did, so a member read past damage can still reach Strict. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/progressive/recovery.rs | 41 +++++++++++++++++++++++++-------- src/progressive/session.rs | 10 +++++--- src/rar5/framing.rs | 8 +++++++ tests/progressive_holes.rs | 39 ++++++++++++++++++++++++++++++++ tests/progressive_salvage.rs | 44 +++++++++++++++++++++++++++++++++++- 5 files changed, 128 insertions(+), 14 deletions(-) diff --git a/src/progressive/recovery.rs b/src/progressive/recovery.rs index 2fcbeaa1..48d95117 100644 --- a/src/progressive/recovery.rs +++ b/src/progressive/recovery.rs @@ -57,6 +57,9 @@ pub(crate) struct Record { wires: Vec, epoch: Arc, part_evidence: Vec, + /// The damaged-input choice the headers were read under: a replay reads the same damaged headers as they stand + /// and resumes where a resync did. + damaged_input: crate::extract::DamagedInput, } impl Record { pub(crate) fn required_volumes(&self) -> impl Iterator + '_ { @@ -75,6 +78,7 @@ impl Record { part_evidence: Vec, ) -> Self { Self { + damaged_input: crate::extract::DamagedInput::Refuse, model, target, key: machine.cipher.as_ref().and_then(|c| c.checksum_key().copied()), @@ -129,7 +133,7 @@ impl ProgressiveSession { wires.push(WireSnapshot { volume: volume.volume, witnesses: volume.witnesses.clone(), count }); } } - Ok(Record::new( + let mut record = Record::new( std::mem::take(&mut self.model), self.target.take().ok_or_else(invalid)?, machine, @@ -137,7 +141,9 @@ impl ProgressiveSession { wires, self.replacement_epoch.clone(), std::mem::take(&mut self.part_evidence), - )) + ); + record.damaged_input = self.damaged_input(); + Ok(record) } /// Admit an explicit verification generation (a replacement lane) for `volume`. /// @@ -903,12 +909,20 @@ impl Replay { return Ok(Poll::Pending); } if self.parser.is_none() { - self.parser = Some(HeaderParser::from_start( - format!("verification-volume-{}", volume.volume).into(), - usage.clone(), - )); + let mut parser = + HeaderParser::from_start(format!("verification-volume-{}", volume.volume).into(), usage.clone()); + parser.set_salvage(record.damaged_input); + self.parser = Some(parser); } let witness = volume.witnesses.lock().unwrap()[self.witness]; + if self.witness_offset == 0 && record.damaged_input.salvages() { + // Extraction read past damage here: a header it gave up on (the rest of its witness bytes are + // still compared) or one it searched past, so the next witness starts elsewhere. Read on from it. + let parser = self.parser.as_mut().unwrap(); + if parser.stopped() || parser.next_offset().is_some_and(|next| next != witness.offset) { + parser.resume_at(witness.offset); + } + } let n = (witness.len - self.witness_offset).min(buffer.len() as u64) as usize; let offset = witness.offset + self.witness_offset; let count = match driver.poll_replacement(volume.volume, offset, cx, &mut buffer[..n]) { @@ -926,10 +940,17 @@ impl Replay { return Err(ProgressiveFailure::new(FailureKind::SourceChanged)); } let parser = self.parser.as_mut().unwrap(); - let (used, step) = parser.advance(&buffer[..count]).map_err(|e| match e.kind { - FailureKind::Limit { .. } | FailureKind::Canceled => e, - _ => ProgressiveFailure::new(FailureKind::SourceChanged), - })?; + let advanced = if parser.stopped() && record.damaged_input.salvages() { + // the rest of a witness extraction read past as damage + Err(crate::extract::HeaderDamageKind::Unreadable) + } else { + parser.advance_salvaging(&buffer[..count]).map_err(|e| match e.kind { + FailureKind::Limit { .. } | FailureKind::Canceled => e, + _ => ProgressiveFailure::new(FailureKind::SourceChanged), + })? + }; + // a header extraction read past as damage: its bytes are checked against the witness all the same + let (used, step) = advanced.unwrap_or((count, ParserStep::Need { offset: 0, len: 0 })); if used != count { return Err(ProgressiveFailure::new(FailureKind::SourceChanged)); } diff --git a/src/progressive/session.rs b/src/progressive/session.rs index 7c8656c3..a501d68e 100644 --- a/src/progressive/session.rs +++ b/src/progressive/session.rs @@ -453,6 +453,10 @@ impl ProgressiveSession { if self.verify_job.is_some() { return Poll::Ready(Err(ProgressiveFailure::new(FailureKind::InvalidCapability))); } + // damage found by the last read is delivered even when that read ended the session + if let Some((volume, damage)) = self.damage.pop_front() { + return Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { volume, damage }))); + } if matches!(self.phase, Phase::Done) { return Poll::Ready(Ok(None)); } @@ -539,6 +543,9 @@ impl ProgressiveSession { if self.control.is_canceled() { return Err(ProgressiveFailure::new(FailureKind::Canceled)); } + if let Some((volume, damage)) = self.damage.pop_front() { + return Ok(Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { volume, damage })))); + } if work >= self.options.limits.packed_work_per_poll.min(1 << 20) { cx.waker().wake_by_ref(); return Ok(Poll::Pending); @@ -564,9 +571,6 @@ impl ProgressiveSession { if let Some(event) = self.partial.as_mut().and_then(|p| p.written.take()) { return Ok(Poll::Ready(Ok(Some(event)))); } - if let Some((volume, damage)) = self.damage.pop_front() { - return Ok(Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { volume, damage })))); - } match &self.phase { Phase::Done => return Ok(Poll::Ready(Ok(None))), Phase::Resync(_) => { diff --git a/src/rar5/framing.rs b/src/rar5/framing.rs index 94d564e1..827ebd46 100644 --- a/src/rar5/framing.rs +++ b/src/rar5/framing.rs @@ -338,6 +338,14 @@ impl HeaderParser { pub(crate) fn set_complete_len(&mut self, len: u64) { self.complete_len = Some(len); } + /// Where the parser's next byte comes from, once the signature is found. + pub(crate) fn next_offset(&self) -> Option { + self.signature.is_none().then(|| self.at.saturating_add(self.buffer.len() as u64)) + } + /// Whether the parser stopped at a failure ([`Self::resume_at`] starts it again). + pub(crate) fn stopped(&self) -> bool { + self.failed + } pub(crate) fn complete_len(&self) -> Option { self.complete_len } diff --git a/tests/progressive_holes.rs b/tests/progressive_holes.rs index 729ad460..4d882dc1 100644 --- a/tests/progressive_holes.rs +++ b/tests/progressive_holes.rs @@ -582,6 +582,15 @@ impl VolumeSource for NativeProvider { } } fn native_session(dir: &std::path::Path, data: Vec, holes: Vec>, encrypted: bool) -> ProgressiveSession { + native_session_with(dir, data, holes, encrypted, Default::default()) +} +fn native_session_with( + dir: &std::path::Path, + data: Vec, + holes: Vec>, + encrypted: bool, + damaged: zipfast::extract::DamagedInput, +) -> ProgressiveSession { let path = dir.join("source.rar"); std::fs::write(&path, &data).unwrap(); let file = File::open(&path).unwrap(); @@ -600,6 +609,7 @@ fn native_session(dir: &std::path::Path, data: Vec, holes: Vec>, }, }; let mut opts = options(&dir.join("out")); + opts.extract.damaged_input = damaged; opts.recovery_publication = RecoveryPublication::VerifiedInner; if encrypted { opts.set_password(Some("pw".into())).unwrap(); @@ -633,6 +643,35 @@ fn recovered_inner_keeps_missing_cipher_evidence() { drop(a); assert!(dir.path().join("out/inner").exists()); } +/// A member read past damaged headers (`damaged_input`: a main header failing its checksum under `Salvage`, garbage +/// before the member searched past under `Resync`) still verifies Strict from a replacement holding the same bytes: +/// the replay reads the damaged headers as extraction did. +#[test] +fn strict_replacement_replays_headers_read_past_as_damage() { + let plain: Vec = (0..79).collect(); + let (data, start) = encrypted(&plain); + let member = common::SIG.len() + common::main_block(false, None).len(); + let mut main_crc = data.clone(); + main_crc[common::SIG.len()] ^= 0x5a; + let mut garbage = data[..member].to_vec(); + garbage.extend([0; 5]); + garbage.extend(&data[member..]); + for (what, data, start, damaged) in [ + ("main crc", main_crc, start, zipfast::extract::DamagedInput::Salvage), + ("resync", garbage, start + 5, zipfast::extract::DamagedInput::Resync), + ] { + let dir = tempfile::tempdir().unwrap(); + let mut s = native_session_with(dir.path(), data.clone(), one(start + 17..start + 18), true, damaged); + let mut a = artifact(&mut s); + s.patch(&mut a, 16, &plain[16..48]).unwrap(); + let replacement = dir.path().join("replacement.rar"); + std::fs::write(&replacement, &data).unwrap(); + s.supply_verification_source(0, Box::new(ImmutableFileSource::open(&replacement).unwrap())).unwrap(); + let v = verify(&mut s, &mut a).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(v.level(), VerificationLevel::Strict, "{what}"); + assert_eq!(std::fs::read(dir.path().join("out/inner")).unwrap(), plain, "{what}"); + } +} #[test] fn strict_native_replacement_publishes_and_custom_replacement_cannot() { for native in [false, true] { diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs index d4faee1b..a60bdda5 100644 --- a/tests/progressive_salvage.rs +++ b/tests/progressive_salvage.rs @@ -229,6 +229,8 @@ struct Run<'a> { /// Called on every `Pending` with the outcome so far; returns whether to open the gate. on_pending: &'a mut dyn FnMut(&Outcome) -> bool, password: Option<&'a str>, + /// `ProgressiveLimits::packed_work_per_poll`, when not the default. + work: Option, } fn progressive(run: Run<'_>) -> Outcome { @@ -239,6 +241,9 @@ fn progressive(run: Run<'_>) -> Outcome { ProgressiveOptions::new(extract_options(&dest, Mode::Extract, run.damaged), OsString::from(run.volumes[0].0)); options.artifact_aftermath = ArtifactAftermath::RetainProvisional; options.set_password(run.password.map(str::to_owned)).unwrap(); + if let Some(work) = run.work { + options.limits.packed_work_per_poll = work; + } let revealed = Arc::new(AtomicU64::new(0)); let open = Arc::new(AtomicBool::new(run.gate.is_empty())); let session = match run.route { @@ -334,7 +339,16 @@ fn progressive(run: Run<'_>) -> Outcome { } fn run_simple(volumes: &[(&str, Vec)], damaged: DamagedInput, route: Route) -> Outcome { - progressive(Run { volumes, damaged, route, gate: 0..0, hole: false, on_pending: &mut |_| false, password: None }) + progressive(Run { + volumes, + damaged, + route, + gate: 0..0, + hole: false, + on_pending: &mut |_| false, + password: None, + work: None, + }) } /// What `extract::run` makes of the same volumes: files and bytes, folders, and the damage list. @@ -496,6 +510,7 @@ fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_is_not_damage() { waits > 400 }, password: None, + work: None, }); assert!(waits > 400, "{format} {damaged:?}: the session did not wait for the header"); assert_eq!(out.failure, None, "{format} {damaged:?}"); @@ -512,6 +527,7 @@ fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_is_not_damage() { hole: true, on_pending: &mut |_| false, password: None, + work: None, }); assert_eq!(out.failure.as_deref(), Some("HeaderHole"), "{format} {damaged:?}"); assert!(out.damage.is_empty(), "{format} {damaged:?}: {:?}", out.damage); @@ -536,6 +552,7 @@ fn a_resync_never_searches_across_a_hole() { hole: true, on_pending: &mut |_| false, password: None, + work: None, }); assert_eq!(out.failure.as_deref(), Some("HeaderHole")); assert!(out.damage.is_empty(), "{:?}", out.damage); @@ -726,6 +743,7 @@ fn no_signature_and_encrypted_headers_are_not_salvaged() { hole: false, on_pending: &mut |_| false, password, + work: None, }); assert!(out.failure.is_some(), "{what} {damaged:?} {route:?}: {out:?}"); assert!(out.damage.is_empty(), "{what} {damaged:?} {route:?}: {:?}", out.damage); @@ -836,3 +854,27 @@ fn a_persistent_session_still_refuses_damaged_headers() { } assert!(failed, "the damaged header did not stop the persistent session"); } + +/// The read that finds damage may also use up the poll's work and end the session (a damaged end header read one +/// byte a poll): its `HeaderDamaged` is still delivered before the end. +#[test] +fn damage_found_by_the_last_read_is_delivered() { + let (mut bytes, at) = rar5(); + bytes[at[3]] ^= 0x5a; + for route in [Route::Sealed, Route::Pieces] { + let volumes = [("a.rar", bytes.clone())]; + let out = progressive(Run { + volumes: &volumes, + damaged: DamagedInput::Salvage, + route, + gate: 0..0, + hole: false, + on_pending: &mut |_| false, + password: None, + work: Some(1), + }); + assert_eq!(out.failure, None, "{route:?}: {out:?}"); + assert_eq!(out.files.len(), 3, "{route:?}"); + assert_eq!(out.damage, [(0, at[3] as u64, HeaderDamageKind::ChecksumMismatch, None, None)], "{route:?}"); + } +} From adb8d470c869dc7b0196c37ded2463f2bb5ff879 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:26:32 -0800 Subject: [PATCH 5/5] Progressive salvage review fix: a session that ended is no longer extracting, whatever its last event A HeaderDamaged delivered as the session reaches Done (a damaged end header) left extraction_active set, so poll_verify and publish_recovered refused the artifacts it had handed out. Done now always clears it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/progressive/session.rs | 6 ++++- tests/progressive_salvage.rs | 48 ++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/progressive/session.rs b/src/progressive/session.rs index a501d68e..d3a09f27 100644 --- a/src/progressive/session.rs +++ b/src/progressive/session.rs @@ -458,6 +458,7 @@ impl ProgressiveSession { return Poll::Ready(Ok(Some(ProgressiveEvent::HeaderDamaged { volume, damage }))); } if matches!(self.phase, Phase::Done) { + self.extraction_active = false; return Poll::Ready(Ok(None)); } self.control.register(cx.waker()); @@ -473,7 +474,10 @@ impl ProgressiveSession { | Ok(None | Some(ProgressiveEvent::MemberFinished { .. } | ProgressiveEvent::SessionTerminated { .. })) ) - ) { + ) || matches!(self.phase, Phase::Done) + { + // a session that reached its end is no longer extracting, whatever its last event (a damaged end + // header's HeaderDamaged, say) self.extraction_active = false; } result diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs index a60bdda5..453d553c 100644 --- a/tests/progressive_salvage.rs +++ b/tests/progressive_salvage.rs @@ -878,3 +878,51 @@ fn damage_found_by_the_last_read_is_delivered() { assert_eq!(out.damage, [(0, at[3] as u64, HeaderDamageKind::ChecksumMismatch, None, None)], "{route:?}"); } } + +/// A session whose last event is a `HeaderDamaged` (its end header failed its checksum) has ended: the artifacts it +/// handed out can be verified afterwards, not refused as if extraction were still going on. +#[test] +fn artifacts_verify_after_a_session_that_ended_on_damage() { + let (mut bytes, at) = rar5(); + bytes[at[3]] ^= 0x5a; + let dir = tempfile::tempdir().unwrap(); + let dest = dir.path().join("out"); + fs::create_dir(&dest).unwrap(); + let mut options = + ProgressiveOptions::new(extract_options(&dest, Mode::Extract, DamagedInput::Salvage), OsString::from("a.rar")); + options.artifact_aftermath = ArtifactAftermath::RetainProvisional; + let revealed = Arc::new(AtomicU64::new(u64::MAX)); + let provider = + Provider { volumes: vec![bytes], revealed, gate: 0..0, open: Arc::new(AtomicBool::new(true)), hole: false }; + let mut session = ProgressiveSession::new(Box::new(provider), options).unwrap(); + let mut cx = Context::from_waker(Waker::noop()); + let mut artifacts = Vec::new(); + let mut last = None; + loop { + match session.poll_event(&mut cx) { + Poll::Pending => {} + Poll::Ready(Ok(None)) => break, + Poll::Ready(Ok(Some(event))) => { + last = Some(matches!(event, ProgressiveEvent::HeaderDamaged { .. })); + if let ProgressiveEvent::MemberFinished { outcome: MemberOutcome::Provisional(artifact), .. } = event { + artifacts.push(artifact); + } + } + Poll::Ready(Err(failure)) => panic!("{failure}"), + } + } + assert_eq!(last, Some(true), "the last event is the end header's damage"); + assert_eq!(artifacts.len(), 3); + for mut artifact in artifacts { + let verdict = loop { + match session.poll_verify(&mut artifact, &mut cx) { + Poll::Pending => {} + Poll::Ready(verdict) => break verdict, + } + }; + if let Err(failure) = &verdict { + assert!(!matches!(failure.kind, FailureKind::InvalidCapability), "{failure}"); + } + artifact.discard().unwrap(); + } +}