diff --git a/rust/src/parchecker.rs b/rust/src/parchecker.rs index 1efadfef6..efc7e2a8c 100644 --- a/rust/src/parchecker.rs +++ b/rust/src/parchecker.rs @@ -1183,10 +1183,10 @@ impl ActiveStreamingSession { drop(queue); // The first article: bind the file by its 16k hash, never by one several share. let hint = first_article_hash16k(&bytes); - let bound = live_hash16k(hint.as_bytes()) + let bound = live_hint_hash16k(&hint) .filter(|hash| !self.shared_hash16k.contains(hash)) .and_then(|_| { - resolve_live_source_id(self, Some(queue_id), identity.1, hint.as_bytes()).ok() + resolve_live_source_id(self, Some(queue_id), identity.1, &hint).ok() }) .filter(|id| { let length = self.file_lengths[id]; @@ -3252,7 +3252,7 @@ fn resolve_live_source_id( entry .session .file_id_by_name(name) - .or_else(|| live_hash16k(hash16k).and_then(|hash| entry.session.file_id_by_hash16k(&hash))) + .or_else(|| live_hint_hash16k(hash16k).and_then(|hash| entry.session.file_id_by_hash16k(&hash))) .or_else(|| { // Bound earlier by its first article's 16k hash (an obfuscated name). let queue_id = queue_id?; @@ -3266,31 +3266,24 @@ fn resolve_live_source_id( .ok_or(RepairError::UnknownFile(FileId([0; 16]))) } -/// The par2 16k hash (hex) of a file whose first article is `bytes`: the MD5 of its first -/// 16 KiB, or of the whole article when shorter (then right only for a file that short). -fn first_article_hash16k(bytes: &[u8]) -> String { +/// The par2 16k hash of a file whose first article is `bytes` (the MD5 of its first 16 KiB, +/// or of the whole article when shorter: then right only for a file that short), printed the +/// way the queue stores `Hash16k` (`renameanalyzer::print`), so every hint live PAR gets is +/// in one form and read by one parser, [`live_hint_hash16k`]. +fn first_article_hash16k(bytes: &[u8]) -> [u8; 32] { use md5::{Digest, Md5}; let digest = Md5::digest(&bytes[..bytes.len().min(16 * 1024)]); - digest.iter().map(|b| format!("{b:02x}")).collect() + let printed = crate::renameanalyzer::print(&digest); + printed[..32].try_into().expect("32 hex digits") } -fn live_hash16k(bytes: &[u8]) -> Option<[u8; 16]> { - fn digit(n: u8) -> Option { - match n { - b'0'..=b'9' => Some(n - b'0'), - b'a'..=b'f' => Some(n - b'a' + 10), - b'A'..=b'F' => Some(n - b'A' + 10), - _ => None, - } - } - if bytes.len() != 32 { - return None; - } - let mut hash = [0; 16]; - for (i, pair) in bytes.chunks_exact(2).enumerate() { - hash[i] = digit(pair[0])? * 16 + digit(pair[1])?; - } - Some(hash) +/// The digest (par2 byte order) of a 16k hash hint handed to live PAR: the queue's +/// `Hash16k` text or [`first_article_hash16k`], both printed nzbget-style (bytes last to +/// first). Before, live PAR read the queue's text in digest order, so a hash never matched +/// its par2 entry: renamed or obfuscated files could not bind by hash, and a file bound by +/// its first article then failed "bound source hash identity changed" on its next write. +pub(crate) fn live_hint_hash16k(hint: &[u8]) -> Option<[u8; 16]> { + crate::parrenamer::parse_printed_hash16k(hint) } #[cfg(test)] @@ -4067,7 +4060,7 @@ pub(crate) fn streaming_session_source_length( ) -> Option { let entry = active_streaming_session(nzb_id)?; let id = entry.session.file_id_by_name(name).or_else(|| { - live_hash16k(hash16k).and_then(|hash| entry.session.file_id_by_hash16k(&hash)) + live_hint_hash16k(hash16k).and_then(|hash| entry.session.file_id_by_hash16k(&hash)) })?; entry.file_lengths.get(&id).copied() } diff --git a/rust/src/parchecker/live_lifecycle_tests.rs b/rust/src/parchecker/live_lifecycle_tests.rs index 178e4a561..8145f7ab2 100644 --- a/rust/src/parchecker/live_lifecycle_tests.rs +++ b/rust/src/parchecker/live_lifecycle_tests.rs @@ -482,7 +482,7 @@ fn live_obfuscated_article_uses_checked_hash_mapping_and_owned_ram() { let desc = &set.file_descs[&fid]; let data = std::fs::read(fx.0.join(desc.local_name())).unwrap(); let bytes = data.len() as u64; - let hash: String = desc.hash_16k.iter().map(|b| format!("{b:02x}")).collect(); + let hash: String = queue_hash16k(&desc.hash_16k); streaming_session_defer_article( id, (b"obfuscated-name", hash.as_bytes()), @@ -514,7 +514,7 @@ fn live_obfuscated_completed_source_reads_its_committed_path() { let desc = &set.file_descs[&fid]; let path = fx.0.join("obfuscated.dat"); std::fs::rename(fx.0.join(desc.local_name()), &path).unwrap(); - let hash: String = desc.hash_16k.iter().map(|b| format!("{b:02x}")).collect(); + let hash: String = queue_hash16k(&desc.hash_16k); let source = LiveCompletedFile { nzb_id: id, base_dir: fx.0.clone(), @@ -646,7 +646,7 @@ fn live_repair_takes_an_obfuscated_target_and_certifies_it_through_par_rename() drop(disk); assert!(streaming_session_status(id).unwrap().early_cutover_possible); // Its queue file (id 40) is matched to the par2 file by its 16k hash. - let hash: String = desc.hash_16k.iter().map(|b| format!("{b:02x}")).collect(); + let hash: String = queue_hash16k(&desc.hash_16k); assert_eq!( streaming_session_par_name_of(id, (Some(40), b"a8f3k2q9z", hash.as_bytes())).as_deref(), Some(desc.name.as_slice()) @@ -697,7 +697,7 @@ fn live_repair_refuses_a_target_whose_name_and_binding_disagree() { return; } let (a, b) = (&set.file_descs[&ids[0]], &set.file_descs[&ids[1]]); - let hash_b: String = b.hash_16k.iter().map(|x| format!("{x:02x}")).collect(); + let hash_b: String = queue_hash16k(&b.hash_16k); // Queue file 41 holds b's bytes but sits under a's name. assert!(streaming_session_par_name_of(id, (Some(41), b"zz-unknown", hash_b.as_bytes())).is_some()); let result = streaming_session_prepare_repair( @@ -2306,3 +2306,76 @@ fn live_cache_miss_with_wrong_downloaded_bytes_is_damage() { assert!(streaming_session_status(id).unwrap().damaged > 0); streaming_session_forget(id); } + +/// A 16k hash as the queue stores it (`FileStr::Hash16k`): printed nzbget-style, bytes +/// last to first in upper-case hex. +fn queue_hash16k(digest: &[u8; 16]) -> String { + String::from_utf8(crate::renameanalyzer::print(digest)[..32].to_vec()).unwrap() +} + +#[test] +fn live_hint_hash16k_reads_printed_known_vectors() { + // MD5("") = d41d8cd98f00b204e9800998ecf8427e; nzbget prints it bytes last to first. + let empty: [u8; 16] = [ + 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, + 0x7e, + ]; + assert_eq!(queue_hash16k(&empty), "7E42F8EC980980E904B2008FD98C1DD4"); + assert_eq!(live_hint_hash16k(b"7E42F8EC980980E904B2008FD98C1DD4"), Some(empty)); + assert_eq!(live_hint_hash16k(b"7e42f8ec980980e904b2008fd98c1dd4"), Some(empty)); + // The digest-order text is another hash, not this one (the old misreading). + assert_ne!(live_hint_hash16k(b"d41d8cd98f00b204e9800998ecf8427e"), Some(empty)); + // The first article's own hint is printed the same way. + assert_eq!(&first_article_hash16k(b""), b"7E42F8EC980980E904B2008FD98C1DD4"); + for bad in [ + &b""[..], + b"7E42F8EC980980E904B2008FD98C1DD", + b"7E42F8EC980980E904B2008FD98C1DD4A", + b"7E42F8EC980980E904B2008FD98C1DDG", + ] { + assert_eq!(live_hint_hash16k(bad), None, "{}", String::from_utf8_lossy(bad)); + } +} + +#[test] +fn live_hint_hash16k_round_trips_printed_and_first_article() { + use md5::{Digest, Md5}; + for seed in 0u8..=255 { + let digest: [u8; 16] = + std::array::from_fn(|i| seed.wrapping_mul(31).wrapping_add(i as u8 * 17)); + assert_eq!(live_hint_hash16k(queue_hash16k(&digest).as_bytes()), Some(digest)); + } + // Longer than 16 KiB: only the first 16 KiB count, as in a par2 file description. + let article: Vec = (0..40_000u32).map(|i| (i * 7 % 251) as u8).collect(); + let digest: [u8; 16] = Md5::digest(&article[..16 * 1024]).into(); + assert_eq!(live_hint_hash16k(&first_article_hash16k(&article)), Some(digest)); + let short = &article[..1000]; + let digest: [u8; 16] = Md5::digest(short).into(); + assert_eq!(live_hint_hash16k(&first_article_hash16k(short)), Some(digest)); +} + +/// The queue's printed hash binds an obfuscated file to its par2 entry and gives its length; +/// the digest-order text names none (before, live PAR read the queue's text that way, so +/// no queue hash ever matched). +#[test] +fn live_queue_printed_hash_binds_an_obfuscated_file() { + let fx = Fixture::new(); + let set = fx.set(); + let id = -1900119; + streaming_session_start_bounded(id, &fx.0.join("testfile.par2"), &fx.0, 500 << 20).unwrap(); + let fid = set.main.as_ref().unwrap().recoverable_file_ids[0]; + let desc = &set.file_descs[&fid]; + let printed = queue_hash16k(&desc.hash_16k); + assert_eq!( + streaming_session_par_name_of(id, (Some(40), b"x9q2obf", printed.as_bytes())).as_deref(), + Some(desc.name.as_slice()) + ); + assert_eq!( + streaming_session_source_length(id, b"x9q2obf", printed.as_bytes()), + Some(desc.file_length) + ); + // The digest-order text names no par2 file. + let digest_order: String = desc.hash_16k.iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(streaming_session_source_length(id, b"x9q2obf", digest_order.as_bytes()), None); + streaming_session_forget(id); +} diff --git a/rust/src/parchecker/live_namespace.rs b/rust/src/parchecker/live_namespace.rs index 6072b29bd..de3042e4d 100644 --- a/rust/src/parchecker/live_namespace.rs +++ b/rust/src/parchecker/live_namespace.rs @@ -1,5 +1,5 @@ //! Bounded source namespace identity, independent of source I/O and GF work. -use super::{live_error, live_hash16k, FileId, PacketSet, RepairError}; +use super::{live_error, live_hint_hash16k, FileId, PacketSet, RepairError}; use crate::parlive::ControlLease; use std::cmp::Ordering; use std::mem::size_of; @@ -351,7 +351,7 @@ impl NamespaceProof { // the article itself; the hashed first bytes were damaged or not // the file's start), so the name stands and slice CRCs verify it. let known = if hint.is_empty() { &self.facts.rows[row].hash16k[..] } else { hint }; - if let Some(hash) = live_hash16k(known) { + if let Some(hash) = live_hint_hash16k(known) { let matches = self .hash_order .iter() @@ -413,7 +413,7 @@ impl NamespaceProof { if hint.is_empty() { return Ok(None); } - let hash = live_hash16k(hint).ok_or_else(|| invalid("malformed hash hint"))?; + let hash = live_hint_hash16k(hint).ok_or_else(|| invalid("malformed hash hint"))?; let Ok(at) = self .hash_order .binary_search_by_key(&hash, |&i| self.catalog[i].hash) @@ -472,7 +472,7 @@ impl NamespaceProof { if let Some(bound) = self.bindings[row] { if !hint.is_empty() && candidate.is_none() - && live_hash16k(hint) != Some(self.catalog[bound].hash) + && live_hint_hash16k(hint) != Some(self.catalog[bound].hash) { return Err(invalid("bound source hash identity changed")); } diff --git a/tests/functional/dupefallback/harness.py b/tests/functional/dupefallback/harness.py index d99e7e9d5..8ed27a722 100755 --- a/tests/functional/dupefallback/harness.py +++ b/tests/functional/dupefallback/harness.py @@ -12938,7 +12938,7 @@ def scenario_livepardecodeahead(daemon, t): return ('livepardecodeahead', ok, 'status=%s intact=%s rebuilt_ahead=%s end_repaired=%s ' 'before_end=%s before_last_data=%s batch_repairs=%d io=%s' % (h['Status'], intact, rebuilt, ended, before_end, before_last, batch, io)) -def _livepar_rar_run(daemon, t, tag, seed, missing, corrupt=None, recovery=24): +def _livepar_rar_run(daemon, t, tag, seed, missing, corrupt=None, recovery=24, obfuscate=False): """A RAR set under the production options with live PAR: 8 store-mode volumes of movie.mkv (real CRCs, so direct unpack extracts it while it downloads) and a par2 set of 64 KiB blocks with recovery blocks in two volumes. maps a volume @@ -12946,8 +12946,11 @@ def _livepar_rar_run(daemon, t, tag, seed, missing, corrupt=None, recovery=24): copy of the volume with 4 KiB XOR-ed, its yEnc CRC still valid (a provider's bad copy: only par2 or the archive checksums catch it). Returns (history, extracted intact, post-processing par-check lines, par-rename missing lines, post-processing loads of the - par2 index, seconds from the end of the download to the history entry).""" + par2 index, seconds from the end of the download to the history entry). With + the volumes are posted under random names without an extension (the par2 + files keep theirs).""" import subprocess as _sp + import zlib seg = 100_000 movie = _payload(6_000_000, seed) vols = generators.rar3_store_volumes_valid('movie.mkv', movie, 800_000) @@ -12962,8 +12965,11 @@ def _livepar_rar_run(daemon, t, tag, seed, missing, corrupt=None, recovery=24): 'Rel.par2'] + names, cwd=work, check=True, capture_output=True) members = [('%s/%s' % (tag, n), n, os.path.getsize(os.path.join(work, n)), seg, set()) for n in sorted(n for n in os.listdir(work) if n.endswith('.par2'))] - members += [('%s/%s' % (tag, n), n, len(vols[i]), seg, set(missing.get(i, ()))) - for i, n in enumerate(names)] + posted = (lambda n: 'x%07x' % (zlib.crc32((tag + n).encode()) & 0xfffffff)) if obfuscate \ + else (lambda n: n) + data_members = [('%s/%s' % (tag, n), posted(n), len(vols[i]), seg, set(missing.get(i, ()))) + for i, n in enumerate(names)] + members += data_members nzb = build_multi_nzb(members) if corrupt: vol, part = corrupt @@ -13046,6 +13052,44 @@ def scenario_liveparrartrust(daemon, t): loads, end_s)) +def _livepar_rar_obfuscated(daemon, t, tag): + """liveparrartrust with the volumes posted under random names, no extension + (DirectRename=yes: the queue stores each volume's first-16-KiB MD5 printed nzbget-style, + bytes last to first, and live PAR gets that text with every write). Live PAR binds the + volumes, repairs the damage as the download ends, never stops on a source identity + (only the end-of-job cancel), and post-processing trusts it: no par-check, par-rename + finds no volume missing. (The direct rename gives the volumes their par2 names by the + same hashes, so this passes on main too; the byte-order fix itself is proved by the + parchecker live_lifecycle_tests, which fail on main.)""" + h, intact, verify, missing, loads, end_s = _livepar_rar_run( + daemon, t, tag, 13740, {1: {3}, 4: {2, 6}}, corrupt=(6, 4), obfuscate=True) + live = _grep_log(t, 'Live par-repair for Rel%s' % tag) + trusted = _grep_log(t, 'live PAR verified every file') + # A stop other than the end of the job (its history entry cancels the session). + stopped = len(re.findall(r'Live PAR \(job \d+\) stopped: (?!cancelled from )', + t.read_file('nzbget.log').decode(errors='replace'))) + ok = (h['Status'].startswith('SUCCESS') and intact and verify == 0 and missing == 0 + and live >= 1 and trusted == 1 and stopped == 0 + and h['ParStatus'] == 'SUCCESS' and h['UnpackStatus'] == 'SUCCESS') + return ok, ('status=%s par=%s unpack=%s intact=%s live_repairs=%d trusted=%d stopped=%d ' + 'par_check_lines=%d missing_lines=%d par2_loads=%d end_to_history_s=%s' + % (h['Status'], h['ParStatus'], h['UnpackStatus'], intact, live, trusted, stopped, + verify, missing, loads, end_s)) + + +def scenario_liveparrarobfuscated(daemon, t): + """_livepar_rar_obfuscated.""" + ok, detail = _livepar_rar_obfuscated(daemon, t, 'lrb') + return ('liveparrarobfuscated', ok, detail) + + +def scenario_liveparrarobfuscatedslow(daemon, t): + """liveparrarobfuscated on a slow line (DownloadRate=1000), so the direct rename, live + PAR's capture and the volumes' writes interleave differently.""" + ok, detail = _livepar_rar_obfuscated(daemon, t, 'lrs') + return ('liveparrarobfuscatedslow', ok, detail) + + def scenario_liveparraroff(daemon, t): """The control for liveparrartrust: the same damaged RAR set with live PAR off. The par-check runs and the counters see it (its "Verifying"/"Repair..." lines, the par2 index @@ -15737,6 +15781,8 @@ def scenario_dupausedunpack(daemon, t): 'livepardecodeahead': scenario_livepardecodeahead, 'liveparrarclean': scenario_liveparrarclean, 'liveparrartrust': scenario_liveparrartrust, + 'liveparrarobfuscated': scenario_liveparrarobfuscated, + 'liveparrarobfuscatedslow': scenario_liveparrarobfuscatedslow, 'liveparraroff': scenario_liveparraroff, 'livepartrusted': scenario_livepartrusted, 'livepartrustedtemp': scenario_livepartrustedtemp, @@ -16215,6 +16261,9 @@ def scenario_dupausedunpack(daemon, t): 'livepartrustedtemp': ['ParCheck=auto', 'LiveParRepair=yes', 'ArticleCache=0', 'DirectWrite=no'], 'liveparrarclean': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], 'liveparrartrust': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], + 'liveparrarobfuscated': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], + 'liveparrarobfuscatedslow': PROD_OPTIONS + ['LiveParRepair=yes', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no', + 'DownloadRate=1000'], 'liveparraroff': PROD_OPTIONS + ['LiveParRepair=no', 'ArticleCache=256', 'DirectWrite=yes', 'UnpackCleanupDisk=no'], 'parinplace': ['ParCheck=auto', 'LiveParRepair=no'], 'parlesscritical': ['HealthCheck=dupe', 'DupeArticleFallback=no'],