From 2b512c87985bb10cfcd5896f0c4eee7a75dc6a05 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:09:57 -0800 Subject: [PATCH 1/3] Persistent-partial sessions honour damaged_input (Salvage/Resync); members bound by header position ProgressiveSession::new_partial now reads past damaged RAR 4.x / 5.0 headers under ProgressiveOptions::extract.damaged_input as an ordinary progressive session does: the same members, bytes and ProgressiveEvent::HeaderDamaged events, with the same hole rule (NotYet waits, a header in a Hole is HeaderHole, no resync across a hole). Refuse (the default) is unchanged. Journal binding: a member whose first header was read as damage is keyed by its position (volume, header offset; ordinal MemberKey::POSITIONAL), and a whole header after damage in the session by position and bytes, since damage can move the ordinals of later members. A whole header is looked up under its ordinary key, then its positional key, then the salvaged-position key, so a restart over the same damaged bytes and a resume over a header repaired since both find the member. Adoption accepts a witness that differs from the recorded one only when either was salvaged and both parse to the same member (name, sizes, data offset, method, checks, split flags, encryption, host); otherwise BindingMismatch(Member), naming the header, before anything is written. State format: salvaged witnesses are listed in a new header-witness section (tag 0x5A, version 1), written only when one exists, and parsed as they stand on reopen. Every other state is byte-identical; older builds refuse a state with the section as StateVersion. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- docs/compat-options.md | 7 +- docs/persistent-partials.md | 24 +- docs/progressive-archives.md | 2 +- src/partial/mod.rs | 25 +- src/partial/state.rs | 119 +++- src/partial/tests/ledger.rs | 59 ++ src/partial/tests/state.rs | 2 + src/partial/types.rs | 8 + src/progressive/session/partial.rs | 107 +++- src/progressive/session/salvage.rs | 23 +- tests/persistent_salvage.rs | 948 +++++++++++++++++++++++++++++ tests/progressive_salvage.rs | 103 ---- 12 files changed, 1269 insertions(+), 158 deletions(-) create mode 100644 tests/persistent_salvage.rs diff --git a/docs/compat-options.md b/docs/compat-options.md index a3c8febb..d279844d 100644 --- a/docs/compat-options.md +++ b/docs/compat-options.md @@ -307,9 +307,10 @@ Where it applies: 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 +Persistent-partial sessions (`ProgressiveSession::new_partial`) honour it too, with the same events and hole rules; a +member read from a damaged header, or after one, is bound to its header's position so that a restart over the same +bytes, or over a header repaired since, finds it again (`docs/persistent-partials.md`, "Damaged headers"). 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. diff --git a/docs/persistent-partials.md b/docs/persistent-partials.md index c7dcef95..6d755369 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. 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. +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 under the default `extract::Options::damaged_input` (`Refuse`); under `Salvage` or `Resync` the session reads past it as an ordinary progressive session does (see "Damaged headers" below). 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. **A part that fails its own check.** Some damage no transport check sees: an article whose yEnc CRC passed but whose bytes are wrong (corrupted before encoding, or a posting of a damaged volume). The session finds it at the end of the part, when the part's packed CRC32 or BLAKE2sp (RAR5) or header CRC (RAR4) fails. For a plain stored member it no longer ends the session there: a part read whole, with no byte missing, that fails its check holds a wrong byte somewhere in its output, so the session declares the part's packed bytes damaged on the member, as `declare_hole` would: the part's output becomes one `DeclaredBad` hole, delivered as a `Hole` event (after the `BytesWritten` events of that output, whose bytes it now calls unknown), with the part's packed span. The member is not judged on the bad bytes: it finishes `PersistentPartial`, and every member after it is extracted as usual, each packed byte read once. The final part has no check of its own (its header holds the member's checks), so a member whose final checks fail while every part before the last passed a check of its own has the wrong byte in its last part, which becomes the `DeclaredBad` hole the same way. Refill the hole with `refill_from_packed` once the volume is repaired (par2 or another copy): it reads that part again, which the part's check cannot narrow, and nothing else. Before, the session ended with `Rar(Integrity { reason: PackedPiece | FinalChecks })` and a caller extracted the set again from its first volume. A part or member that cannot be placed keeps the earlier behaviour: an encrypted member's part (its checks cover ciphertext and its CBC chain runs across parts; it still ends the session), a part with a hole in it (judged by `poll_verify` once filled, `PartBad`), and a member in one part whose checks fail (the session ends, as before), and a final check that fails after a part before the last went unchecked (`Bad`). For those, declare the damaged volume's range with `PartialFile::declare_hole` after `PartBad` or `Bad` and refill it after the repair; only this member's output in it becomes a hole, so `refill_from_packed` over the whole volume reads only those bytes. @@ -254,6 +254,28 @@ A persistent session resumes a set after a restart. Start `new_partial` again wi Adoption is refused, with the session failing on the typed error and every file left as it is, when the member does not match: `BindingMismatch(Member)` for another output path, name or size; `BindingMismatch(Source)` for a recorded part or header witness that differs; `BindingMismatch(Output)` for a replaced output, parent or bundle (other native identities); `OutputChanged` for known output whose bytes changed; `StateUnavailable` when the anchored state is gone; `UnsafePath` for a path the current declaration names. Another archive whose members have the same names has other first headers and so other member keys, so its members are not adopted: creating them finds the existing outputs and fails with `AlreadyExists`, exactly as before, and the existing output is never overwritten. We chose failing the session over skipping the member so that a mismatch is never mistaken for a member that needs no work; per-member refusal (below) deliberately does not cover adoption mismatches. A member whose genesis was cut short before the output reached its full size cannot be adopted (`OutputChanged`); nothing was produced for it, so remove its anchor, bundle and output and restart. +## Damaged headers + +`ProgressiveOptions::extract.damaged_input` (`Salvage`, `Resync`) applies to a persistent session as to an ordinary progressive one (`docs/compat-options.md`, "Damaged headers in a progressive session"): the same members, the same bytes and the same `ProgressiveEvent::HeaderDamaged { volume, damage }` events, each delivered before anything read from that header. The hole rule is the same: only delivered bytes are judged. A header the source has not delivered yet (`NotYet`) is waited for, never damage. A header inside a `Hole` answer (including a range declared with `declare_hole` before it was read) stops the session with `HeaderHole`, so repair can still fill it and a restart read it whole. A resync never searches across a hole; it stops with `HeaderHole` too, and on a growing source an unfinished resync waits for more bytes. The default `Refuse` is unchanged: the session stops at the damage, and nothing below applies. + +Binding. A member's `MemberKey` normally holds its ordinal and a digest of its first header's bytes, and the state keeps those bytes (the header witness) and is checked against them on every adoption. Damage breaks both: a damaged header's bytes change once par2 repairs them, and damage can hide a member (a header passed over or searched past) or invent one (a header whose type byte was hit), so the ordinals of every member after it differ from those of the whole archive. A session honouring `damaged_input` therefore binds by position where damage is involved: + +| first header | key ordinal | key identity (SHA-256 over) | +|---|---|---| +| whole, no damage read before it in this session | the member's ordinal | the format's domain and the header bytes, as always | +| whole, after damage in this session | `MemberKey::POSITIONAL` (`u64::MAX`) | `.../member/at/v1`, the volume index, the header offset and the header bytes | +| read past as damage (failed its checksum, read as it stands) | `MemberKey::POSITIONAL` | `.../member/salvaged-at/v1`, the volume index and the header offset | + +Every domain is per format (`zipfast/plain-stored/member/...` for RAR 5.0, `zipfast/rar4-stored/member/...` for RAR 4.x). At a whole header the session asks the anchor store for the ordinal key, then the positional key, then the salvaged-position key, and adopts the first one found; with none it creates the member under the first row's key, or the second's after damage. At a damaged header it looks up and creates only the salvaged-position key. Lookups and keys under `Refuse` are exactly as before. + +- A restart or resume over the same damaged bytes reads the same damage at the same places, so it derives the same keys and adopts the same members, deterministically. Members before the first damage keep their ordinary keys. +- Once a damaged header is repaired (par2, another copy), the session reads it whole and finds the member's state under the salvaged-position key. Adoption then decides: the state's witness (kept as it was read, damaged) and the repaired header are parsed and must describe the same member: name, unpacked and packed size, where the data starts, method, CRC32 and BLAKE2sp, split flags, encryption parameters and host system. Times and attributes are left out, since they change no output byte; the state keeps the metadata recorded from the damaged header. The member's output path, name, size and first part must match as for any adoption. If they do, the member is rebound and resumes from what it committed. If not, the header now describes another member: the session ends with `Partial(BindingMismatch(Member))` (or `BindingMismatch(Source)` for a part whose position or geometry changed), its context naming the header's volume and offset, before anything is written for it. Data is never mixed across members. Remove that member's output and state, or start a fresh `state_dir`, and run again. +- A member after the damage is found under its positional key, which does not depend on what came before it. A member the damage hid was never created, so it is created now. +- The same holds for a later part's header: a part whose witness was read past as damage matches the repaired header when both describe the same part. A continuation header that is unreadable loses the member's later parts, as in an ordinary progressive session. +- A member first created by a run that read no damage, and later read after damage (a worse copy rather than a repair), is looked up under its ordinal and found if its ordinal did not move. If it moved, or the member's own first header is now damaged, it is not found: creation finds its output and fails with `AlreadyExists`, as for another archive whose members have the same names, and the output is left as it is. + +A state whose witness was read past as damage records it in a header-witness section of its own (tag `0x5A`, version 1: the indices of the salvaged witnesses), written only when such a witness exists; reopen (`PartialFile::open`, adoption) parses that witness as it stands and every other one strictly. All other states are byte-identical to before, so existing states and anchors load and adopt unchanged. A build from before this section refuses a state that carries it with `StateVersion`, and refuses an unknown section version the same way. Use the same `damaged_input` choice when resuming a set: a `Refuse` session does not look up positional keys. A damaged header's attributes are applied as its output's permissions once the member verifies (as the whole-archive runners apply them); a damaged mode that makes the output unreadable to its owner also stops a later adoption from reading it back. `tests/persistent_salvage.rs` checks each point. + ## Refused members and directory entries A persistent session refuses, one member at a time, what it cannot keep as a persistent partial: a compressed member (`RefusalReason::Compressed { method }`), an encrypted RAR4 member (`Encrypted`), a member of unknown size (`UnknownSize`, the RAR5 flag or an all-ones RAR4 size) and a link or file copy (`Redirection`: a RAR 5.0 redirection record or a RAR4 Unix symbolic link). The member gets its `MemberStarted` as usual, and then, with no event in between, `MemberFinished` with `MemberOutcome::Refused { reason }`. Nothing is created for it: no output, no state bundle, no anchor, no parent directory, no `PartialReady`. Its data is skipped without being read: the session seeks past each of its parts, opening later volumes only to read their headers, so a refused member costs no download of its data. The session then goes on with the next member, so RustyGet can extract a refused member afterwards with an ordinary session (for example with `Overwrite::Skip` over the same root, which skips the persistent outputs that exist). Refused members still count in the member ordinals, so `MemberKey`s of later members do not depend on whether earlier ones were refused. diff --git a/docs/progressive-archives.md b/docs/progressive-archives.md index 4eda66f1..de0239b7 100644 --- a/docs/progressive-archives.md +++ b/docs/progressive-archives.md @@ -143,7 +143,7 @@ runners do, and reports each as `ProgressiveEvent::HeaderDamaged { volume, damag 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. +follow the same rules; see `docs/persistent-partials.md` ("Damaged headers") for how their members are bound. ## RAR4 capability boundary diff --git a/src/partial/mod.rs b/src/partial/mod.rs index a7ec1c09..158d42b0 100644 --- a/src/partial/mod.rs +++ b/src/partial/mod.rs @@ -2837,13 +2837,32 @@ impl PartialCore { Ok(()) } /// Whether part `part` (with its header witness) is already recorded. A recorded part, or a witness at the same - /// archive position, that differs is a `BindingMismatch`: the archive is not the one the member came from. + /// archive position, that differs is a `BindingMismatch`: the archive is not the one the member came from. When + /// either witness was read past as damage, the two may differ in bytes as long as both describe the same member + /// ([`state::same_member_header`]): the header was repaired since, or damaged since; otherwise the member is + /// another one (`BindingMismatch(Member)`). The recorded witness is kept. pub(crate) fn recorded_part(&self, part: &PlainPart, witness: &HeaderWitness) -> PartialResult { let op = self.operation()?; let evidence = &op.snapshot.evidence; let old = evidence.headers.iter().find(|old| old.volume == witness.volume && old.packed == witness.packed); - if old.is_some_and(|old| old != witness) { - return Err(err(PartialErrorKind::BindingMismatch(BindingField::Source))); + if let Some(old) = old.filter(|old| *old != witness) { + // A header one of the readings took as damage (a run under `damaged_input` Salvage or Resync) may be + // read whole by the other, once repaired, or damaged by it: the same member only if both readings + // describe the same output. Any other difference is another archive. + if !(old.salvaged || witness.salvaged) { + return Err(err(PartialErrorKind::BindingMismatch(BindingField::Source))); + } + let expected = evidence + .admissions + .iter() + .find(|a| a.volume == witness.volume) + .map_or(std::ffi::OsStr::new(""), |a| a.expected.as_os_str()); + let recorded = state::witness_header(old, evidence.format, expected, &self.budget)?; + let read = state::witness_header(witness, evidence.format, expected, &self.budget) + .map_err(|_| err(PartialErrorKind::BindingMismatch(BindingField::Member)))?; + if !state::same_member_header(&recorded, &read) { + return Err(err(PartialErrorKind::BindingMismatch(BindingField::Member))); + } } match evidence.parts.iter().find(|old| old.ordinal == part.ordinal) { Some(recorded) if recorded == part && old.is_some() => Ok(true), diff --git a/src/partial/state.rs b/src/partial/state.rs index 51e6d9f2..f10b0bb4 100644 --- a/src/partial/state.rs +++ b/src/partial/state.rs @@ -34,6 +34,11 @@ const FORMAT_RAR4: u8 = 4; /// Header witness page tag of a direct member (created from a member map): no witnesses follow the count, and the /// tag is followed by the [`DirectFacts`]. Its validity ledger lists only known leaves; unknown output is implicit. const FORMAT_DIRECT: u8 = 0xD1; +/// Header witness page section listing the witnesses read past as damage ([`HeaderWitness::salvaged`]), version 1: +/// the tag, the version, a count and the ascending witness indices. Written only when some witness is salvaged, and +/// before the format tag, so every other state stays byte-identical and a build that predates it refuses such a +/// state with `StateVersion` (an unknown tag) instead of reading a damaged witness strictly. +const SALVAGED_WITNESSES: u8 = 0x5A; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum PageKind { Geometry = 1, @@ -722,6 +727,16 @@ pub(super) fn encode_pages(snapshot: &Snapshot, budget: &PartialBudget) -> Parti headers.range(&h.packed)?; headers.blob(&h.bytes)?; } + let salvaged = snapshot.evidence.headers.iter().filter(|h| h.salvaged).count(); + if salvaged > 0 { + headers.reserve(6 + 4 * salvaged)?; + headers.u8(SALVAGED_WITNESSES)?; + headers.u8(1)?; + headers.u32(salvaged.try_into().map_err(|_| malformed())?)?; + for (index, _) in snapshot.evidence.headers.iter().enumerate().filter(|(_, h)| h.salvaged) { + headers.u32(index.try_into().map_err(|_| malformed())?)?; + } + } // Trailing format tag, written only for RAR4 members so that RAR5 states stay byte-identical and readable by // builds that predate RAR4 support. States without it are RAR5. if let Some(direct) = &snapshot.evidence.direct { @@ -906,7 +921,26 @@ pub(super) fn decode_pages( if packed.end - packed.start != bytes.len() as u64 { return Err(malformed()); } - headers.push(HeaderWitness { volume, packed, bytes }); + headers.push(HeaderWitness { volume, packed, bytes, salvaged: false }); + } + if d.bytes.get(d.at) == Some(&SALVAGED_WITNESSES) { + d.u8()?; + if d.u8()? != 1 { + return Err(err(PartialErrorKind::StateVersion)); + } + let count = d.count(headers.len(), 4)?; + if count == 0 { + return Err(malformed()); + } + let mut next = 0; + for _ in 0..count { + let index = d.u32()? as usize; + if index < next || index >= headers.len() { + return Err(malformed()); + } + headers[index].salvaged = true; + next = index + 1; + } } let mut format = crate::rar5::RarFormat::Rar5; let mut direct = None; @@ -1067,10 +1101,6 @@ pub(super) fn validate_evidence( evidence: &InitialEvidence, budget: &PartialBudget, ) -> PartialResult> { - use crate::rar5::{ - framing::{HeaderParser, ParserStep}, - reader::Block, - }; if evidence.direct.is_some() { // One synthetic part over the whole output, no packed bytes behind it, no part checks (the member checks // are in the head), and nothing parsed from an archive. @@ -1120,25 +1150,7 @@ pub(super) fn validate_evidence( if witness.packed.end.checked_sub(witness.packed.start) != Some(witness.bytes.len() as u64) { return Err(malformed()); } - let mut parser = - HeaderParser::progressive(PathBuf::from(&admission.expected), witness.packed.start, budget.usage.clone()); - if evidence.format == crate::rar5::RarFormat::Rar4 { - parser.set_format(crate::rar5::RarFormat::Rar4); - } - let mut step = parser.advance(&[])?.1; - let frame = loop { - match step { - ParserStep::Need { offset, len } => { - let at = offset.checked_sub(witness.packed.start).ok_or_else(malformed)? as usize; - let bytes = - witness.bytes.get(at..at.checked_add(len).ok_or_else(malformed)?).ok_or_else(malformed)?; - step = parser.advance(bytes)?.1; - } - ParserStep::Frame(frame) => break frame, - _ => return Err(malformed()), - } - }; - let Block::File(header) = frame.block else { return Err(malformed()) }; + let header = witness_header(witness, evidence.format, &admission.expected, budget)?; if index == 0 { let actual = crate::extract::Meta::from(&header); if actual.mtime != evidence.metadata.mtime @@ -1208,6 +1220,65 @@ pub(super) fn validate_evidence( /// count, salt and password check. The parts are one CBC stream, so only the first part's IV is used (a later part /// restating another is accepted, as member maps accept it), and the tweaked-checksum flag may appear on the final /// part only (rar 7.00 writes it there), so neither is compared. +/// Parses a header witness again: strictly, or as it stands when it was read past as damage +/// ([`HeaderWitness::salvaged`]), as the session read it. Only a file header is a witness. +pub(super) fn witness_header( + witness: &HeaderWitness, + format: crate::rar5::RarFormat, + expected: &std::ffi::OsStr, + budget: &PartialBudget, +) -> PartialResult { + use crate::rar5::{ + framing::{HeaderParser, ParserStep}, + reader::Block, + }; + let mut parser = HeaderParser::progressive(PathBuf::from(expected), witness.packed.start, budget.usage.clone()); + if format == crate::rar5::RarFormat::Rar4 { + parser.set_format(crate::rar5::RarFormat::Rar4); + } + if witness.salvaged { + parser.set_salvage(crate::extract::DamagedInput::Salvage); + } + let mut step = parser.advance(&[])?.1; + let frame = loop { + match step { + ParserStep::Need { offset, len } => { + let at = offset.checked_sub(witness.packed.start).ok_or_else(malformed)? as usize; + let bytes = witness.bytes.get(at..at.checked_add(len).ok_or_else(malformed)?).ok_or_else(malformed)?; + step = parser.advance(bytes)?.1; + } + ParserStep::Frame(frame) => break frame, + _ => return Err(malformed()), + } + }; + let Block::File(header) = frame.block else { return Err(malformed()) }; + Ok(header) +} +/// Whether two readings of the header at one archive position describe the same member as far as its output is +/// concerned: name, sizes, where its data starts, method, checks, splitting, encryption and the host system (which +/// decides how the name is made a path). Times and attributes are left out: they change no output byte. Used when one +/// of the readings was damaged, to rebind a member to its header once the header is repaired. +pub(crate) fn same_member_header(a: &crate::rar5::FileHeader, b: &crate::rar5::FileHeader) -> bool { + let legacy = |h: &crate::rar5::FileHeader| h.rar4.map(|raw| (raw.unpack_version, raw.salt, raw.method)); + a.format == b.format + && a.name == b.name + && a.packed_size == b.packed_size + && a.data_at == b.data_at + && a.unpacked_size == b.unpacked_size + && a.size_unknown() == b.size_unknown() + && a.crc32 == b.crc32 + && a.blake2sp == b.blake2sp + && a.method == b.method + && a.is_dir() == b.is_dir() + && a.redirection.is_none() + && b.redirection.is_none() + && a.split_before() == b.split_before() + && a.split_after() == b.split_after() + && a.encrypted == b.encrypted + && a.crypt == b.crypt + && legacy(a) == legacy(b) + && a.is_unix() == b.is_unix() +} pub(crate) fn same_member_crypt( part: Option<&crate::crypto::Rar5CryptParams>, first: Option<&crate::crypto::Rar5CryptParams>, diff --git a/src/partial/tests/ledger.rs b/src/partial/tests/ledger.rs index 166bee62..f6e11a92 100644 --- a/src/partial/tests/ledger.rs +++ b/src/partial/tests/ledger.rs @@ -139,6 +139,7 @@ impl Fixture { volume: index as u32, packed: frame.extent.clone(), bytes: bytes[frame.extent.start as usize..frame.extent.end as usize].to_vec(), + salvaged: false, }); } let checks = MemberChecks { @@ -696,3 +697,61 @@ fn a_scattered_hole_costs_the_same_however_many_holes_came_before() { assert!(late <= early + 64, "a hole cost {early} bytes after 10 holes and {late} after {}", HOLES - 10); assert_eq!(file.core.operation().unwrap().snapshot.holes.len(), HOLES, "separate holes stay separate"); } + +/// A header witness read past as damage (`salvaged`) is stored in a section only such states carry, and parsed +/// again as it stands: a damaged witness decodes when marked salvaged and is refused when not. States with no +/// salvaged witness are byte-identical to before, and a section of an unknown version is `StateVersion`, as an older +/// build reports for the section itself (an unknown trailing tag). +#[test] +fn salvaged_witnesses_persist_in_their_own_section() { + use crate::partial::state::{self, PageKind}; + let f = Fixture::new(4096, false, true, false); + let file = f.create(); + let op = file.core.operation().unwrap(); + let witnesses = |pages: &[(PageKind, Vec)]| { + let (kind, bytes) = pages.iter().find(|(kind, _)| *kind == PageKind::HeaderWitnesses).unwrap(); + state::page_payload(*kind, bytes).unwrap().to_vec() + }; + let with = |witnesses: Vec, pages: &[(PageKind, Vec)]| -> Vec<(PageKind, Vec)> { + pages + .iter() + .map(|(kind, bytes)| match kind { + PageKind::HeaderWitnesses => (*kind, state::page_bytes(*kind, &witnesses).unwrap()), + _ => (*kind, bytes.clone()), + }) + .collect() + }; + let decode = |pages: Vec<(PageKind, Vec)>| { + state::decode_pages(op.snapshot.head.clone(), pages, &file.core.budget, &[]).map(|s| s.evidence.headers) + }; + let (clean, _lease) = state::encode_pages(&op.snapshot, &file.core.budget).unwrap(); + assert!(decode(clean.clone()).unwrap().iter().all(|h| !h.salvaged)); + + let (mut salvaged, _copy) = file.core.clone_snapshot(&op.snapshot).unwrap(); + salvaged.evidence.headers[0].salvaged = true; + let (pages, _lease) = state::encode_pages(&salvaged, &file.core.budget).unwrap(); + let marked = witnesses(&pages); + let plain = witnesses(&clean); + assert_eq!(marked.len(), plain.len() + 10, "tag, version, count and one index"); + assert_eq!(&marked[..plain.len()], &plain[..], "the section follows the witnesses"); + assert_eq!(marked[plain.len()], 0x5A); + assert!(decode(pages.clone()).unwrap()[0].salvaged); + + // the witness's header CRC hit (its first byte, after the count, volume, range and length): read as it stands + // only when marked so + let header_crc = 4 + 4 + 16 + 4; + let damage = |mut bytes: Vec| { + bytes[header_crc] ^= 0x5a; + bytes + }; + assert!(decode(with(damage(marked.clone()), &pages)).unwrap()[0].salvaged); + assert!(decode(with(damage(plain.clone()), &clean)).is_err(), "a damaged witness is not read strictly"); + + let mut future = marked.clone(); + future[plain.len() + 1] = 2; + assert!(matches!(decode(with(future, &pages)).unwrap_err().kind, PartialErrorKind::StateVersion)); + let mut stray = marked; + let last = stray.len() - 4; + stray[last..].copy_from_slice(&7u32.to_le_bytes()); + assert!(decode(with(stray, &pages)).is_err(), "an index past the witnesses"); +} diff --git a/src/partial/tests/state.rs b/src/partial/tests/state.rs index 2d514be8..8d12a7c8 100644 --- a/src/partial/tests/state.rs +++ b/src/partial/tests/state.rs @@ -181,6 +181,7 @@ impl Fixture { volume: 0, packed: frame.extent.clone(), bytes: bytes[frame.extent.start as usize..frame.extent.end as usize].to_vec(), + salvaged: false, }], direct: None, }; @@ -721,6 +722,7 @@ fn split_fixture() -> (Fixture, EvidenceUpdate) { volume, packed: frame.extent.clone(), bytes: bytes[..frame.extent.end as usize].to_vec(), + salvaged: false, }], direct: None, } diff --git a/src/partial/types.rs b/src/partial/types.rs index 0db25330..2d3df670 100644 --- a/src/partial/types.rs +++ b/src/partial/types.rs @@ -33,6 +33,11 @@ pub struct MemberKey { pub(super) identity: [u8; 32], } impl MemberKey { + /// The ordinal of a member bound by its header's position rather than its place in the set: a persistent session + /// that honours [`crate::extract::Options::damaged_input`] binds so a member whose first header was read past as + /// damage, and every member after damage in the session, because damage can hide or invent members and so move + /// the ordinals of those after it (see `docs/persistent-partials.md`). + pub const POSITIONAL: u64 = u64::MAX; pub fn new(binding: ArchiveBinding, ordinal: u64, identity: [u8; 32]) -> Self { Self { binding, ordinal, identity } } @@ -331,6 +336,9 @@ pub(crate) struct HeaderWitness { pub volume: u32, pub packed: Range, pub bytes: Vec, + /// The header failed its checksum and was read as it stands + /// ([`crate::extract::DamagedInput::Salvage`] or `Resync`): it is parsed again the same way. + pub salvaged: bool, } #[derive(Clone)] pub(crate) struct InitialEvidence { diff --git a/src/progressive/session/partial.rs b/src/progressive/session/partial.rs index da0a1d9f..1937e2fe 100644 --- a/src/progressive/session/partial.rs +++ b/src/progressive/session/partial.rs @@ -51,6 +51,9 @@ pub(super) struct Persistent { directories: Vec, /// Identities of every directory this session created: parents of its outputs and directory entries. created: Vec, + /// A header was read past as damage earlier in this session ([`crate::extract::Options::damaged_input`]): the + /// members after it are bound by position (see [`Self::member_keys`]). + pub(super) damaged: bool, } /// A member this session created or adopted. Its core (state pages, descriptors, `open_partials` lease) is held /// until the member has finished and the caller has taken its handle with `partial_file`; then the session keeps @@ -180,11 +183,79 @@ impl Persistent { .get(start..start + len) .ok_or_else(|| ProgressiveFailure::new(FailureKind::SourceContract))?; usage.charge(Resource::MetadataBytes, len as u64)?; - self.witness = Some(HeaderWitness { volume, packed: frame.extent.clone(), bytes: bytes.to_vec() }); + self.witness = Some(HeaderWitness { + volume, + packed: frame.extent.clone(), + bytes: bytes.to_vec(), + salvaged: frame.damaged, + }); } self.header.clear(); Ok(()) } + /// Drops the header bytes recorded so far: reading goes on elsewhere (a resync, the next volume) after a header + /// read past as damage. + pub(super) fn drop_header(&mut self) { + self.header.clear(); + } + /// The keys a member whose first header is `witness` may have in the anchor store, in the order they are looked + /// up, and the key it is created under when none has an anchor. + /// + /// - A member whose first header is whole, in a session that has read past no damage before it (or that does not + /// honour `damaged_input`): the ordinal and a digest of its header bytes, as always. + /// - After damage, ordinals may have moved (damage can hide a member or turn a header into another block), so + /// the member is bound by position: [`MemberKey::POSITIONAL`] and a digest of its volume, header offset and + /// header bytes, which the same header at the same place gives whatever came before it. + /// - A member whose first header was itself read as damage is bound by its position only: a digest of the volume + /// and header offset. A later run over the same damaged bytes finds it again; one over the repaired header + /// finds it too, and adoption decides whether the repaired header describes the same member. + /// + /// A whole header in a session honouring `damaged_input` is looked up under each form, so a member created after + /// damage, or under a header since repaired, is found again by a run that reads no damage before it. + fn member_keys( + &self, + format: crate::rar5::RarFormat, + ordinal: u64, + witness: &HeaderWitness, + honours_damage: bool, + ) -> (Vec, MemberKey) { + let rar4 = format == crate::rar5::RarFormat::Rar4; + let domain = |name: &str| { + let mut identity = + if rar4 { b"zipfast/rar4-stored/member/".to_vec() } else { b"zipfast/plain-stored/member/".to_vec() }; + identity.extend_from_slice(name.as_bytes()); + identity.push(0); + identity + }; + let binding = self.options.binding.clone(); + let positioned = |mut identity: Vec| { + identity.extend_from_slice(&witness.volume.to_le_bytes()); + identity.extend_from_slice(&witness.packed.start.to_le_bytes()); + identity + }; + let salvaged = || { + MemberKey::new( + binding.clone(), + MemberKey::POSITIONAL, + crate::crypto::sha256(&positioned(domain("salvaged-at/v1"))), + ) + }; + if witness.salvaged { + let key = salvaged(); + return (vec![key.clone()], key); + } + let mut identity = domain("v1"); + identity.extend_from_slice(&witness.bytes); + let ordered = MemberKey::new(binding.clone(), ordinal, crate::crypto::sha256(&identity)); + if !honours_damage { + return (vec![ordered.clone()], ordered); + } + let mut identity = positioned(domain("at/v1")); + identity.extend_from_slice(&witness.bytes); + let at = MemberKey::new(binding.clone(), MemberKey::POSITIONAL, crate::crypto::sha256(&identity)); + let create = if self.damaged { at.clone() } else { ordered.clone() }; + (vec![ordered, at, salvaged()], create) + } fn active(&self) -> (&MemberKey, &Arc) { let slot = &self.cores[self.current.expect("persistent member")]; (&slot.key, slot.core.as_ref().expect("the active member's core is held")) @@ -229,9 +300,8 @@ impl ProgressiveSession { resume: None, directories: Vec::new(), created: Vec::new(), + damaged: false, }); - // 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")] @@ -587,16 +657,9 @@ impl ProgressiveSession { self.usage.charge(Resource::MetadataBytes, (witness.bytes.len() + header.name.len() + 32) as u64)?; // Each format has its own identity domain, so a RAR4 and a RAR5 member never share a key or a bundle. let format = header.format; - let mut identity = match format { - crate::rar5::RarFormat::Rar5 => b"zipfast/plain-stored/member/v1\0".to_vec(), - crate::rar5::RarFormat::Rar4 => b"zipfast/rar4-stored/member/v1\0".to_vec(), - }; - identity.extend_from_slice(&witness.bytes); - let key = MemberKey::new( - persistent.options.binding.clone(), - self.member.unwrap().ordinal, - crate::crypto::sha256(&identity), - ); + let honours_damage = self.options.extract.damaged_input.salvages(); + let (lookups, key) = persistent.member_keys(format, self.member.unwrap().ordinal, &witness, honours_damage); + self.usage.charge(Resource::MetadataBytes, (lookups.len() * std::mem::size_of::()) as u64)?; let output = header.output_name().unwrap_or(std::borrow::Cow::Borrowed(&header.name)); let mut relative = crate::path::sanitize_fallible(&output, !header.is_unix()) .map_err(|_| error(PartialErrorKind::UnsafePath))?; @@ -623,8 +686,10 @@ impl ProgressiveSession { None => None, }; // A member an earlier session created has its anchor already: adopt it instead of creating it again. - if let Some(anchor) = persistent.options.anchors.current(&key).map_err(failure)? { - return self.partial_adopt(key, anchor, relative, plain, witness, keys); + for found in lookups { + if let Some(anchor) = persistent.options.anchors.current(&found).map_err(failure)? { + return self.partial_adopt(found, anchor, relative, plain, witness, keys); + } } let checks = member_checks(physical); let admission = SourceAdmission { @@ -775,8 +840,16 @@ impl ProgressiveSession { ) .map_err(failure)?; check(&mut self.driver)?; - core.check_adopted(&relative, header.name.as_bytes(), header.unpacked_size).map_err(failure)?; - if !core.recorded_part(&plain, &witness).map_err(failure)? { + // A mismatch names the header: a member bound by position whose header has been repaired into another + // member's is refused here, before anything is written. + let at = |error: PartialError| { + let mut failure = failure(error); + failure.context.volume_index = Some(witness.volume); + failure.context.packed_offset = Some(witness.packed.start); + failure + }; + core.check_adopted(&relative, header.name.as_bytes(), header.unpacked_size).map_err(at)?; + if !core.recorded_part(&plain, &witness).map_err(at)? { return Err(error(PartialErrorKind::StateMalformed)); } let (produced, finished, size) = core.resume_point().map_err(failure)?; diff --git a/src/progressive/session/salvage.rs b/src/progressive/session/salvage.rs index bfc643fa..b105bdfe 100644 --- a/src/progressive/session/salvage.rs +++ b/src/progressive/session/salvage.rs @@ -68,13 +68,9 @@ impl ResyncWork { } 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). + /// The damaged-input choice the parsers of this session take. A persistent session takes it too: a member read + /// after damage, or from a damaged header, is bound by its header's position (see `docs/persistent-partials.md`). 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. @@ -116,8 +112,19 @@ impl ProgressiveSession { self.history_failure = None; } self.damage.push_back((self.volume, damage)); + #[cfg(feature = "persistent-partials")] + if let Some(partial) = &mut self.partial { + partial.damaged = true; + } Ok(()) } + /// A persistent session drops the bytes of a header read past: reading goes on elsewhere. + fn drop_partial_header(&mut self) { + #[cfg(feature = "persistent-partials")] + if let Some(partial) = &mut self.partial { + partial.drop_header(); + } + } /// 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; @@ -151,6 +158,7 @@ impl ProgressiveSession { /// 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<()> { + self.drop_partial_header(); let at = self.parser.header_offset(); if self.parser.resyncs() { let mut window = std::mem::take(&mut self.resync_window); @@ -187,6 +195,7 @@ impl ProgressiveSession { /// 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<()> { + self.drop_partial_header(); 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(); @@ -199,6 +208,8 @@ impl ProgressiveSession { if let Some(output) = &mut self.output { output.finish_directories(&mut self.driver)?; } + #[cfg(feature = "persistent-partials")] + self.partial_finish_directories()?; self.phase = Phase::Done; Ok(()) } diff --git a/tests/persistent_salvage.rs b/tests/persistent_salvage.rs new file mode 100644 index 00000000..18c3cd61 --- /dev/null +++ b/tests/persistent_salvage.rs @@ -0,0 +1,948 @@ +// 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 persistent-partial session (`ProgressiveSession::new_partial`): damaged RAR headers +//! read past as the progressive session reads them (`tests/progressive_salvage.rs`), with the same hole rules, and +//! members bound to their header's position so that a restart over the same damaged bytes, or a resume over a +//! header repaired since, finds them again (`docs/persistent-partials.md`, "Damaged headers"). + +#![cfg(all(feature = "persistent-partials", any(target_os = "linux", target_os = "macos")))] + +mod common; + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::fs; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +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::partial::*; +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, damaged: DamagedInput) -> extract::Options { + extract::Options { + mode: Mode::Extract, + 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() +} + +type Volumes = Vec<(&'static str, Vec)>; + +/// The damaged archives of `tests/progressive_salvage.rs`, each a set of named volumes. +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 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]..]); + 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())])); + 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 +} + +/// A volume: whole reads, or a few bytes a call (`NotYet` past `revealed`, as a download); bytes in `gate` of the +/// first volume held back while `open` is false (`NotYet`, or a `Hole` when `hole`). +struct Source { + index: u32, + data: Vec, + pieces: bool, + revealed: Arc, + gate: Range, + open: Arc, + hole: bool, +} +impl RangeSource for Source { + fn info(&self) -> SourceInfo { + SourceInfo { + id: SourceId(self.index 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 len = self.data.len() as u64; + let revealed = if self.pieces { self.revealed.load(Ordering::SeqCst).min(len) } else { len }; + if at >= revealed { + if at >= len { + return Ok(RangeRead::Filled { count: 0 }); + } + cx.waker().wake_by_ref(); + return Ok(RangeRead::NotYet); + } + let mut end = revealed.min(at + buf.len() as u64); + if self.pieces { + end = end.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 { + names: Vec, + volumes: Vec>, +} +impl VolumeSource for Provider { + fn protection(&mut self) -> ProgressiveResult { + Ok(ProtectionDeclaration::Complete { + epoch: 1, + inventory: ProtectionInventory { + volumes: self + .names + .iter() + .enumerate() + .map(|(index, name)| ProtectedVolume { + index: index as u32, + name: name.clone(), + backing: VolumeBacking::NonFile, + }) + .collect(), + auxiliary_paths: Vec::new(), + }, + }) + } + fn volume(&mut self, request: &VolumeRequest, _: &mut Context<'_>) -> ProgressiveResult { + match self.volumes.get_mut(request.index as usize).and_then(Option::take) { + Some(source) => Ok(VolumeAnswer::Ready(Box::new(source))), + 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(()) + } +} + +/// The roots and anchor store a set's sessions share, run after run. +struct Job { + _dir: tempfile::TempDir, + out: PathBuf, + state: PathBuf, + anchors: Arc, +} +impl Job { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out"); + let state = dir.path().join("state"); + fs::create_dir(&out).unwrap(); + Self { _dir: dir, out, state, anchors: Arc::new(Anchors::default()) } + } +} + +/// 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 (or was stopped), else the failure kind. + failure: Option, + /// The failure's volume and packed offset. + failed_at: (Option, Option), + /// Members finished `PersistentComplete`, by name, with their output's bytes. + files: BTreeMap>, + /// Their verdicts. + verdicts: BTreeMap, + dirs: Vec, + /// Members refused or left partial, by name. + other: Vec<(String, String)>, + damage: Vec, + /// Members created, and adopted (with the produced committed and whether they were finished). + created: Vec<(String, MemberKey)>, + adopted: Vec<(String, MemberKey, u64, bool)>, + /// An output could not be read back (a damaged header's attributes, applied as its permissions, may deny it). + unreadable: bool, + /// Whether the session was dropped early by `stop`. + stopped: bool, +} + +struct Run<'a> { + job: &'a Job, + volumes: &'a [(&'a str, Vec)], + damaged: DamagedInput, + pieces: bool, + gate: Range, + hole: bool, + /// Called on every `Pending`; returns whether to open the gate. + on_pending: Option<&'a mut dyn FnMut(&Outcome) -> bool>, + /// Drops the session (a crash or a pause) once the member of this name has had this many `BytesWritten` events + /// (any member when the name is empty). + stop: Option<(&'a str, usize)>, +} +impl<'a> Run<'a> { + fn simple(job: &'a Job, volumes: &'a [(&'a str, Vec)], damaged: DamagedInput, pieces: bool) -> Self { + Self { job, volumes, damaged, pieces, gate: 0..0, hole: false, on_pending: None, stop: None } + } +} + +fn persistent(mut run: Run<'_>) -> Outcome { + let mut options = + ProgressiveOptions::new(extract_options(&run.job.out, run.damaged), OsString::from(run.volumes[0].0)); + options.hole_policy = HolePolicy::PartialStored { fill: HoleFill::Sparse }; + let revealed = Arc::new(AtomicU64::new(0)); + let open = Arc::new(AtomicBool::new(run.gate.is_empty())); + let provider = Provider { + names: run.volumes.iter().map(|(name, _)| OsString::from(*name)).collect(), + volumes: run + .volumes + .iter() + .enumerate() + .map(|(index, (_, bytes))| { + Some(Source { + index: index as u32, + data: bytes.clone(), + pieces: run.pieces, + revealed: revealed.clone(), + gate: if index == 0 { run.gate.clone() } else { 0..0 }, + open: open.clone(), + hole: run.hole, + }) + }) + .collect(), + }; + let partial = PartialOptions { + binding: ArchiveBinding { job: [1; 16], archive: [2; 32] }, + naming: PartialNaming::ArchivePath, + state_dir: run.job.state.clone(), + limits: PartialLimits::default(), + anchors: run.job.anchors.clone(), + control: SessionControl::default(), + }; + let mut out = Outcome::default(); + let mut session = match ProgressiveSession::new_partial(Box::new(provider), options, partial) { + Ok(session) => session, + Err(failure) => { + out.failure = Some(format!("{:?}", failure.kind)); + return out; + } + }; + let mut names: std::collections::HashMap = Default::default(); + let mut current = String::new(); + let mut written = 0; + let mut cx = Context::from_waker(Waker::noop()); + let started = Instant::now(); + loop { + assert!(started.elapsed() < Duration::from_secs(60), "the session never ended"); + let event = match session.poll_event(&mut cx) { + Poll::Pending => { + revealed.fetch_add(7, Ordering::SeqCst); + if run.on_pending.as_mut().is_some_and(|f| f(&out)) { + open.store(true, Ordering::SeqCst); + } + continue; + } + Poll::Ready(Ok(None)) => break, + Poll::Ready(Err(failure)) => { + out.failed_at = (failure.context.volume_index, failure.context.packed_offset); + out.failure = Some(format!("{:?}", failure.kind)); + break; + } + Poll::Ready(Ok(Some(event))) => 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, .. } => { + written = 0; + current = String::from_utf8_lossy(&name).into_owned(); + names.insert(member, current.clone()); + } + ProgressiveEvent::PartialReady { member, .. } => out.created.push((current.clone(), member)), + ProgressiveEvent::PartialAdopted { member, produced, finished, .. } => { + out.adopted.push((current.clone(), member, produced, finished)) + } + ProgressiveEvent::BytesWritten { .. } => { + written += 1; + if run.stop.is_some_and(|(name, stop)| (name.is_empty() || name == current) && written >= stop) { + out.stopped = true; + break; + } + } + ProgressiveEvent::MemberFinished { member, outcome } => { + let name = names[&member].clone(); + match outcome { + MemberOutcome::PersistentComplete { verdict, .. } => { + let label = + if matches!(verdict, Verdict::Ok { .. }) { "Ok".into() } else { format!("{verdict:?}") }; + out.verdicts.insert(name.clone(), label); + let bytes = fs::read(run.job.out.join(&name)); + out.unreadable |= bytes.is_err(); + out.files.insert(name.clone(), bytes.unwrap_or_default()); + } + MemberOutcome::Directory { .. } => out.dirs.push(name), + MemberOutcome::PersistentPartial { .. } => out.other.push((name, "partial".into())), + MemberOutcome::Refused { reason } => out.other.push((name, format!("{reason:?}"))), + MemberOutcome::Stopped { failure, .. } => out.other.push((name, format!("{:?}", failure.kind))), + _ => out.other.push((name, "other".into())), + } + } + ProgressiveEvent::SessionTerminated { failure, .. } => { + out.failed_at = (failure.context.volume_index, failure.context.packed_offset); + out.failure = Some(format!("{:?}", failure.kind)); + break; + } + _ => {} + } + } + out.dirs.sort(); + out +} + +fn run_simple(job: &Job, volumes: &[(&str, Vec)], damaged: DamagedInput, pieces: bool) -> Outcome { + persistent(Run::simple(job, volumes, damaged, pieces)) +} + +/// What a plain progressive session (`from_sealed_memory`) makes of the same volumes: the members, their bytes, the +/// folders and the damage list; and the members a persistent session refuses (compressed ones), by name. +fn progressive(volumes: &[(&str, Vec)], damaged: DamagedInput) -> 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, damaged), OsString::from(volumes[0].0)); + options.artifact_aftermath = ArtifactAftermath::RetainProvisional; + let mut session = ProgressiveSession::from_sealed_memory( + volumes.iter().map(|(name, bytes)| (OsString::from(*name), bytes.clone().into_boxed_slice())).collect(), + options, + ) + .unwrap(); + let mut out = Outcome::default(); + let mut names: std::collections::HashMap = Default::default(); + let mut cx = Context::from_waker(Waker::noop()); + loop { + match session.poll_event(&mut cx) { + Poll::Pending => {} + 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 } => { + 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(_) => { + out.files.insert(name.clone(), fs::read(dest.join(&name)).unwrap_or_default()); + } + MemberOutcome::Directory { .. } => out.dirs.push(name), + MemberOutcome::Stopped { failure, .. } => out.other.push((name, format!("{:?}", failure.kind))), + _ => out.other.push((name, "other".into())), + } + } + ProgressiveEvent::SessionTerminated { failure, .. } => { + out.failure = Some(format!("{:?}", failure.kind)); + break; + } + _ => {} + }, + } + } + out.dirs.sort(); + out +} + +/// The default refuses every damaged archive as before: no `HeaderDamaged` event, the session fails at the damage. +#[test] +fn refuse_is_unchanged_in_a_persistent_session() { + for (case, volumes) in cases() { + for pieces in [false, true] { + let job = Job::new(); + let out = run_simple(&job, &volumes, DamagedInput::Refuse, pieces); + assert!(out.damage.is_empty(), "{case} {pieces}"); + assert!(out.failure.is_some(), "{case} {pieces}: {out:?}"); + } + } +} + +/// A whole archive under `Refuse` keys each member as it always did: its ordinal and a digest of its first header's +/// bytes in the format's domain. So the states and anchors a build before this one wrote are found again. +#[test] +fn whole_headers_keep_their_keys() { + for (format, (bytes, at)) in [("rar5", rar5()), ("rar4", rar4())] { + for damaged in [DamagedInput::Refuse, DamagedInput::Salvage, DamagedInput::Resync] { + let job = Job::new(); + let volumes = [("a.rar", bytes.clone())]; + let out = run_simple(&job, &volumes, damaged, false); + assert_eq!(out.failure, None, "{format} {damaged:?}"); + assert_eq!(out.created.len(), 3); + for (i, (name, key)) in out.created.iter().enumerate() { + let end = if i == 2 { at[3] } else { at[i + 1] }; + let data = [A, B, C][i]; + let header = &bytes[at[i]..end - data.len()]; + let mut identity = if format == "rar5" { + b"zipfast/plain-stored/member/v1\0".to_vec() + } else { + b"zipfast/rar4-stored/member/v1\0".to_vec() + }; + identity.extend_from_slice(header); + assert_eq!(key.ordinal(), i as u64, "{format} {damaged:?} {name}"); + assert_eq!(key.identity(), &zipfast::crypto::sha256(&identity), "{format} {damaged:?} {name}"); + } + } + } +} + +/// `Salvage` and `Resync` in a persistent session extract what a progressive session extracts from the same damaged +/// archive under the same choice: the same members and bytes, the same folders and the same `HeaderDamaged` list, +/// read whole or a few bytes at a time. Compressed members, which a persistent session refuses, are refused here. +#[test] +fn salvage_and_resync_extract_what_the_progressive_session_does() { + for (case, volumes) in cases() { + for damaged in [DamagedInput::Salvage, DamagedInput::Resync] { + let expected = progressive(&volumes, damaged); + assert_eq!(expected.failure, None, "{case} {damaged:?}: {expected:?}"); + assert!(!expected.damage.is_empty(), "{case} {damaged:?}: not damaged"); + for pieces in [false, true] { + let at = format!("{case} {damaged:?} pieces={pieces}"); + let job = Job::new(); + let out = run_simple(&job, &volumes, damaged, pieces); + assert_eq!(out.failure, None, "{at}: {out:?}"); + assert_eq!(out.damage, expected.damage, "{at}"); + assert_eq!(out.dirs, expected.dirs, "{at}"); + let refused: Vec<&String> = out.other.iter().map(|(name, _)| name).collect(); + for (name, why) in &out.other { + assert!(why.contains("Compressed") || why.contains("Encrypted"), "{at}: {name} {why}"); + } + let kept: BTreeMap> = expected + .files + .iter() + .filter(|(name, _)| !refused.contains(name)) + .map(|(n, b)| (n.clone(), b.clone())) + .collect(); + assert_eq!(out.files, kept, "{at}"); + } + } + } +} + +/// b.txt's header still to come (`NotYet`) is waited for: no damage, and all three members once it arrives. The same +/// header answered as a `Hole` is `HeaderHole`, neither read past nor searched across; and a hole inside the stretch a +/// resync searches stops it with `HeaderHole` too. +#[test] +fn a_header_still_to_come_is_waited_for_and_one_in_a_hole_stops_the_session() { + 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 job = Job::new(); + let mut waits = 0; + let out = persistent(Run { + job: &job, + volumes: &volumes, + damaged, + pieces: true, + gate: gate.clone(), + hole: false, + on_pending: Some(&mut |seen| { + if waits <= 400 { + assert!(seen.damage.is_empty(), "{format} {damaged:?}: {:?}", seen.damage); + assert!(!seen.files.contains_key("b.txt")); + } + waits += 1; + waits > 400 + }), + stop: None, + }); + 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); + + let job = Job::new(); + let out = persistent(Run { + job: &job, + volumes: &volumes, + damaged, + pieces: true, + gate: gate.clone(), + hole: true, + on_pending: None, + stop: None, + }); + 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:?}"); + } + } + let (bytes, at) = rar5(); + let mut damaged = bytes[..at[1]].to_vec(); + damaged.extend(garbage(300)); + damaged.extend(&bytes[at[1]..]); + let job = Job::new(); + let out = persistent(Run { + job: &job, + volumes: &[("a.rar", damaged)], + damaged: DamagedInput::Resync, + pieces: true, + gate: at[1] as u64 + 200..at[1] as u64 + 260, + hole: true, + on_pending: None, + stop: None, + }); + assert_eq!(out.failure.as_deref(), Some("HeaderHole")); + assert!(out.damage.is_empty(), "{:?}", out.damage); + assert_eq!(out.files.keys().collect::>(), ["a.txt"]); +} + +/// A restart over the same damaged bytes binds to the same members: a second session adopts every member the first +/// one finished, under the same keys, creates nothing, reports the same damage and leaves the same output. And a +/// session dropped part way through (after its first few writes) is resumed by the next to the same result. +#[test] +fn a_restart_over_the_same_damaged_bytes_binds_the_same_members() { + for (case, volumes) in cases() { + for damaged in [DamagedInput::Salvage, DamagedInput::Resync] { + let at = format!("{case} {damaged:?}"); + let job = Job::new(); + let first = run_simple(&job, &volumes, damaged, false); + assert_eq!(first.failure, None, "{at}: {first:?}"); + let again = run_simple(&job, &volumes, damaged, true); + assert_eq!(again.failure, None, "{at}: {again:?} first {first:?}"); + assert!(again.created.is_empty(), "{at}: {:?}", again.created); + let keys = |o: &Outcome| o.adopted.iter().map(|(n, k, ..)| (n.clone(), k.clone())).collect::>(); + assert_eq!(keys(&again), first.created, "{at}"); + assert!(again.adopted.iter().all(|(.., finished)| *finished), "{at}"); + assert_eq!(again.damage, first.damage, "{at}"); + assert_eq!(again.files, first.files, "{at}"); + assert_eq!(again.dirs, first.dirs, "{at}"); + + // dropped after a few writes, a few bytes a call, then resumed + let job = Job::new(); + let paused = persistent(Run { stop: Some(("", 3)), ..Run::simple(&job, &volumes, damaged, true) }); + let resumed = run_simple(&job, &volumes, damaged, true); + assert_eq!(resumed.failure, None, "{at}: {resumed:?}"); + assert_eq!(resumed.damage, first.damage, "{at}"); + assert_eq!(resumed.files, first.files, "{at}: paused {paused:?}"); + } + } +} + +/// An archive of a.bin, b.bin and c.bin stored, each long enough to be written in many pieces: its bytes, where each +/// header starts, and the members' data. +fn long(rar4: bool) -> (Vec, [usize; 4], [Vec; 3]) { + let data: [Vec; 3] = std::array::from_fn(|m| (0..2000).map(|i| ((i * 7 + m * 13) % 251) as u8).collect()); + let mut out = if rar4 { b"Rar!\x1a\x07\0".to_vec() } else { SIG.to_vec() }; + out.extend(if rar4 { rar4_block(0x73, 0, &[0; 6]) } else { main_block(false, None) }); + let mut at = [0; 4]; + for (i, name) in ["a.bin", "b.bin", "c.bin"].into_iter().enumerate() { + at[i] = out.len(); + if rar4 { + out.extend(rar4_member(name.as_bytes(), &data[i])); + } else { + out.extend(file_block(&FileSpec::new(name, &data[i]), &data[i], hash(&data[i]), false, false)); + } + } + at[3] = out.len(); + out.extend(if rar4 { rar4_block(0x7b, 0x4000, &[]) } else { end_block(false) }); + (out, at, data) +} + +/// Repaired later: b.bin's header fails its checksum (its CRC field was hit), so a salvaging session reads it as it +/// stands and is dropped part way through b.bin. par2 then repairs the header. The resumed session reads no damage: +/// it finds b.bin's state under its position, sees that the repaired header describes the same member, and resumes +/// it from what the first session committed. Every member ends whole and verified, and a later run adopts them all. +#[test] +fn a_repaired_header_rebinds_to_the_same_member() { + for rar4 in [false, true] { + let (bytes, at, data) = long(rar4); + let mut damaged = bytes.clone(); + damaged[at[1]] ^= 0x5a; + for choice in [DamagedInput::Salvage, DamagedInput::Resync] { + let case = format!("rar4={rar4} {choice:?}"); + let job = Job::new(); + let volumes = [("a.rar", damaged.clone())]; + let paused = persistent(Run { stop: Some(("b.bin", 20)), ..Run::simple(&job, &volumes, choice, true) }); + assert!(paused.stopped, "{case}"); + assert_eq!(paused.damage.len(), 1, "{case}"); + assert_eq!(paused.created.iter().map(|(n, _)| n.as_str()).collect::>(), ["a.bin", "b.bin"]); + let salvaged = paused.created[1].1.clone(); + assert_eq!(salvaged.ordinal(), MemberKey::POSITIONAL, "{case}: a damaged header binds by position"); + + let repaired = [("a.rar", bytes.clone())]; + let out = run_simple(&job, &repaired, choice, true); + assert_eq!(out.failure, None, "{case}: {out:?}"); + assert!(out.damage.is_empty()); + assert_eq!(out.adopted.len(), 2, "{case}: {:?}", out.adopted); + assert_eq!(out.adopted[1].0, "b.bin"); + assert_eq!(out.adopted[1].1, salvaged, "{case}: rebound to the state read from the damaged header"); + assert!(!out.adopted[1].3 && out.adopted[1].2 > 0 && out.adopted[1].2 < 2000, "{:?}", out.adopted[1]); + assert_eq!(out.created.iter().map(|(n, _)| n.as_str()).collect::>(), ["c.bin"]); + for (i, name) in ["a.bin", "b.bin", "c.bin"].into_iter().enumerate() { + assert_eq!(out.files[name], data[i], "{case} {name}"); + assert_eq!(out.verdicts[name], "Ok", "{case} {name}"); + } + let again = run_simple(&job, &repaired, choice, false); + assert_eq!(again.failure, None); + assert!(again.created.is_empty() && again.adopted.len() == 3, "{case}: {again:?}"); + + // a whole first run: c.bin is created after the damage, by position, and found so once repaired + let job = Job::new(); + let first = run_simple(&job, &volumes, choice, false); + assert_eq!(first.created[2].1.ordinal(), MemberKey::POSITIONAL, "{case}"); + let out = run_simple(&job, &repaired, choice, false); + assert_eq!(out.failure, None, "{case}: {out:?}"); + let keys = |o: &Outcome| o.adopted.iter().map(|(n, k, ..)| (n.clone(), k.clone())).collect::>(); + assert_eq!(keys(&out), first.created, "{case}"); + } + } +} + +/// A member split over two volumes whose second part's header failed its checksum: salvaged, then repaired, the +/// part is the same part (a run over the repaired volume adopts the member and walks both parts), while a repair +/// that changes the part (its data CRC) is another archive (`BindingMismatch`). +#[test] +fn a_repaired_continuation_header_is_the_same_part() { + let data: Vec = (0..2000).map(|i| (i * 11 % 253) as u8).collect(); + let spec = FileSpec::new("split.bin", &data); + let volume = |index: usize, part: &[u8], crc: u32| { + let mut bytes = SIG.to_vec(); + bytes.extend(main_block(true, Some(index as u64))); + let header = bytes.len(); + bytes.extend(file_block(&spec, part, crc, index == 1, index == 0)); + bytes.extend(end_block(index == 0)); + (bytes, header) + }; + let (first, _) = volume(0, &data[..1000], hash(&data[..1000])); + let (second, header) = volume(1, &data[1000..], hash(&data)); + let mut damaged = second.clone(); + damaged[header] ^= 0x5a; + for choice in [DamagedInput::Salvage, DamagedInput::Resync] { + let job = Job::new(); + let volumes = [("set.part1.rar", first.clone()), ("set.part2.rar", damaged.clone())]; + let out = run_simple(&job, &volumes, choice, false); + assert_eq!(out.failure, None, "{choice:?}: {out:?}"); + assert_eq!( + out.damage, + [(1, header as u64, HeaderDamageKind::ChecksumMismatch, Some("split.bin".into()), None)] + ); + assert_eq!(out.files["split.bin"], data); + let repaired = [("set.part1.rar", first.clone()), ("set.part2.rar", second.clone())]; + let out = run_simple(&job, &repaired, choice, true); + assert_eq!(out.failure, None, "{choice:?}: {out:?}"); + assert!(out.created.is_empty() && out.adopted.len() == 1 && out.adopted[0].3, "{choice:?}: {out:?}"); + assert_eq!(out.files["split.bin"], data); + // a "repair" that makes the part another one: its header now carries another data CRC + let (other, _) = volume(1, &data[1000..], hash(&data) ^ 1); + let out = run_simple(&job, &[("set.part1.rar", first.clone()), ("set.part2.rar", other)], choice, false); + assert!(out.failure.as_deref().is_some_and(|f| f.contains("BindingMismatch")), "{choice:?}: {out:?}"); + } +} + +/// Repaired later into another member: b.txt's name was hit ("bttxt"), so the salvaged member wrote `bttxt`. Once +/// the header is repaired it names b.txt: the state found at that position is another member's, so the session +/// refuses it with `BindingMismatch(Member)`, naming the header's volume and offset, before writing anything for it. +/// The salvaged output is left as it was; nothing is mixed into b.txt. +#[test] +fn a_header_repaired_into_another_member_is_refused() { + 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'; + for choice in [DamagedInput::Salvage, DamagedInput::Resync] { + let job = Job::new(); + let first = run_simple(&job, &[("a.rar", renamed.clone())], choice, false); + assert_eq!(first.failure, None); + assert_eq!(first.files["bttxt"], B); + let out = run_simple(&job, &[("a.rar", bytes.clone())], choice, false); + assert!(out.failure.as_deref().is_some_and(|f| f.contains("BindingMismatch(Member)")), "{choice:?}: {out:?}"); + assert_eq!(out.failed_at, (Some(0), Some(at[1] as u64)), "{choice:?}"); + assert!(!job.out.join("b.txt").exists(), "nothing was written for b.txt"); + assert_eq!(fs::read(job.out.join("bttxt")).unwrap(), B); + } +} + +/// Repaired later, after a member was hidden: b.txt's header was zeroed, so a `Resync` session searched past it and +/// extracted a.txt and c.txt (c.txt by position: its ordinal is 1 here and 2 in the whole archive). Once repaired, +/// the session creates b.txt, which it has never seen, and finds c.txt under its position. +#[test] +fn a_member_found_again_after_its_ordinal_moved() { + for (format, (bytes, at)) in [("rar5", rar5()), ("rar4", rar4())] { + let mut zeros = bytes.clone(); + zeros[at[1]..at[1] + 20].fill(0); + let job = Job::new(); + let first = run_simple(&job, &[("a.rar", zeros)], DamagedInput::Resync, false); + assert_eq!(first.failure, None, "{format}"); + assert_eq!(first.files.keys().collect::>(), ["a.txt", "c.txt"], "{format}"); + let out = run_simple(&job, &[("a.rar", bytes.clone())], DamagedInput::Resync, false); + assert_eq!(out.failure, None, "{format}: {out:?}"); + assert_eq!(out.created.iter().map(|(n, _)| n.as_str()).collect::>(), ["b.txt"], "{format}"); + assert_eq!(out.adopted.iter().map(|(n, ..)| n.as_str()).collect::>(), ["a.txt", "c.txt"], "{format}"); + assert_eq!(out.files["a.txt"], A); + assert_eq!(out.files["b.txt"], B); + assert_eq!(out.files["c.txt"], C); + } +} + +/// A state holding a witness read past as damage reopens with `PartialFile::open` (the witness is parsed again as +/// it stands) and verifies; the state names the witness as salvaged in a section only such states carry. +#[test] +fn a_salvaged_state_reopens() { + let (mut bytes, at) = rar5(); + bytes[at[1]] ^= 0x5a; + let job = Job::new(); + let out = run_simple(&job, &[("a.rar", bytes)], DamagedInput::Salvage, false); + assert_eq!(out.failure, None); + let (_, key) = out.created.iter().find(|(n, _)| n == "b.txt").unwrap(); + let anchor = job.anchors.current(key).unwrap().unwrap(); + let state = PartialState::load(&job.state, &anchor, &PartialLimits::default()).unwrap(); + let mut file = PartialFile::open( + state, + PartialOpenContext { + output_root: job.out.clone(), + state_root: job.state.clone(), + expected_member: key.clone(), + expected_anchor: anchor.clone(), + protection: ProtectionDeclaration::Complete { + epoch: 1, + inventory: ProtectionInventory { + volumes: vec![ProtectedVolume { index: 0, name: "a.rar".into(), backing: VolumeBacking::NonFile }], + auxiliary_paths: Vec::new(), + }, + }, + limits: PartialLimits::default(), + progressive_limits: ProgressiveLimits::default(), + anchors: job.anchors.clone(), + control: SessionControl::default(), + password: None, + }, + ) + .unwrap(); + let verdict = loop { + if let Poll::Ready(verdict) = file.poll_verify(&mut Context::from_waker(Waker::noop())) { + break verdict.unwrap(); + } + }; + assert!(matches!(verdict, Verdict::Ok { .. }), "{verdict:?}"); +} + +/// Hostile input: every 37th byte of a three-member archive changed, under each salvaging choice, read whole and in +/// pieces, then the same bytes run again over the same roots: nothing panics, every session ends in bounded time, +/// and the restart binds the same members. +#[test] +fn corrupting_every_37th_offset_never_panics_and_restarts_the_same() { + 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] { + let volumes = [("a.rar", damaged.clone())]; + let job = Job::new(); + let first = run_simple(&job, &volumes, choice, offset % 2 == 0); + let again = run_simple(&job, &volumes, choice, offset % 2 == 1); + // a damaged mode applied to an output can make it unreadable, which no restart gets past + if first.failure.is_none() && !first.unreadable { + let at = format!("{offset} {value} {choice:?}"); + assert_eq!(again.failure, None, "{at}: {again:?} first {first:?}"); + assert!(again.created.is_empty(), "{at}: {again:?}"); + assert_eq!(again.damage, first.damage, "{at}"); + assert_eq!(again.files, first.files, "{at}"); + } + } + } + } + } + assert!(started.elapsed() < Duration::from_secs(300), "{:?}", started.elapsed()); +} diff --git a/tests/progressive_salvage.rs b/tests/progressive_salvage.rs index 453d553c..16f42600 100644 --- a/tests/progressive_salvage.rs +++ b/tests/progressive_salvage.rs @@ -752,109 +752,6 @@ fn no_signature_and_encrypted_headers_are_not_salvaged() { } } -/// 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"); -} - /// 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] From afa870a10fa4cbd56a343b13abe0315da897b316 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:23:18 -0800 Subject: [PATCH 2/3] Persistent salvage review fix: a damaged header dropped as a second main header drops its recorded bytes A file header whose type byte was hit so that it reads as a main header is dropped (its data passed over); its bytes stayed in the persistent session's header buffer, so the next header was not contiguous and the session ended with SourceContract. They are now dropped with the frame. Case "rar5 file read as main" added. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- src/progressive/session/salvage.rs | 2 ++ tests/persistent_salvage.rs | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/src/progressive/session/salvage.rs b/src/progressive/session/salvage.rs index b105bdfe..9de278d2 100644 --- a/src/progressive/session/salvage.rs +++ b/src/progressive/session/salvage.rs @@ -146,6 +146,8 @@ impl ProgressiveSession { 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; + // its bytes are recorded but no frame follows them: reading goes on past its data + self.drop_partial_header(); return Ok(false); } if !self.main_seen && !matches!(frame.block, Block::Main(_)) { diff --git a/tests/persistent_salvage.rs b/tests/persistent_salvage.rs index 18c3cd61..6222909f 100644 --- a/tests/persistent_salvage.rs +++ b/tests/persistent_salvage.rs @@ -166,6 +166,10 @@ fn cases() -> Vec<(&'static str, Volumes)> { renamed[name + 1] = b't'; cases.push(("rar5 damaged name", one(renamed))); cases.push(("rar5 without end", one(bytes[..at[3]].to_vec()))); + // b.txt's type byte hit so that it reads as a second main header, its data passed over + let mut as_main = bytes.clone(); + as_main[at[1] + 5] = 1; + cases.push(("rar5 file read as main", one(as_main))); let (mut typed, at4) = rar4(); typed[at4[1] + 2] ^= 0x5a; cases.push(("rar4 damaged type", one(typed))); From 5a0a8f8974afd685c959e6e7eb699fc8513fb338 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:25:44 -0800 Subject: [PATCH 3/3] Merge origin/main (encrypted_links) into persistent-salvage Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LG44gZ63jJDJGeNcamsGrj --- tests/persistent_salvage.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/persistent_salvage.rs b/tests/persistent_salvage.rs index 6222909f..171ef990 100644 --- a/tests/persistent_salvage.rs +++ b/tests/persistent_salvage.rs @@ -67,6 +67,7 @@ fn extract_options(dest: &Path, damaged: DamagedInput) -> extract::Options { attempt_continued_members: false, damaged_input: damaged, unsupported_filters: Default::default(), + encrypted_links: Default::default(), salvage_truncated_zip: false, unix_modes: Default::default(), backslashes: Default::default(),