refs_core/metablock.rs
1//! ReFS v3 metadata-block (page) header and its checksum descriptor.
2//!
3//! Every ReFS metadata block is a self-describing 16 KiB page (four 4096-byte
4//! clusters). The page begins with a **format-version-3 metadata block header**
5//! (80 bytes), byte-verified against a real ReFS v3.14 volume and consistent
6//! with libyal `libfsrefs`:
7//!
8//! ```text
9//! off size field
10//! 0 4 block signature ("SUPB"/"CHKP"/"MSB+")
11//! 4 4 unknown (observed 2)
12//! c 4 volume signature
13//! 10 8 virtual allocator clock
14//! 18 8 tree update clock
15//! 20 8 first block number (== the block's SELF number)
16//! 28 8 second block number (redundancy copy)
17//! 30 8 third block number
18//! 38 8 fourth block number
19//! 40 16 128-bit table identifier
20//! ```
21//!
22//! # Checksums (CRC-32C and CRC-64/ECMA-182)
23//!
24//! ReFS protects each metadata block with a checksum recorded in the *metadata
25//! block reference* that points to it (a 48-byte structure whose checksum
26//! descriptor gives `type` — `1` = CRC-32C, `2` = CRC64-ECMA-182 — plus the
27//! stored checksum bytes). This module exposes the two checksum **algorithms**
28//! (validated against their published check values) and a range-explicit
29//! [`MetaBlock::verify_crc32c`] verifier.
30//!
31//! **Honest limitation (Tier-2 reverse-engineering).** The exact byte *range*
32//! ReFS runs the block checksum over is **not documented** in the
33//! reverse-engineered references, and an empirical search over the real v3.14
34//! volume did not reproduce the stored value from any obvious contiguous range
35//! (starts `{0, 80, 208}` × every end, checksum-field zeroed or not, both CRC
36//! init conventions). Rather than guess a range and fabricate a
37//! `Some(false)` "corruption" verdict on every clean block (the LZNT1 trap),
38//! this crate exposes the checksum *descriptor* and the checksum *algorithms*,
39//! and verifies only over a **caller-supplied explicit range** — so a future
40//! phase that pins the range (against `libfsrefs`/Prade or a larger corpus) can
41//! call [`MetaBlock::verify_crc32c`] with the correct bounds. Automatic
42//! whole-block verification stays deliberately absent until the range is
43//! confirmed.
44
45use crc::{Crc, CRC_32_ISCSI, CRC_64_ECMA_182};
46
47use crate::bytes::{ascii, le_u64};
48use crate::error::RefsError;
49
50/// The ReFS v3 metadata page (block) size in bytes: 16 KiB (four 4096-byte
51/// clusters), verified on the real v3.14 volume.
52pub const REFS_METADATA_PAGE_SIZE: usize = 16384;
53
54/// Length of the format-version-3 metadata block header.
55const V3_HEADER_LEN: usize = 80;
56
57/// Offset of the first (self) block number within the v3 header.
58const SELF_BLOCK_NUMBER_OFFSET: usize = 0x20;
59
60/// CRC-32C engine (iSCSI / Castagnoli, polynomial `0x1edc6f41`), the ReFS
61/// checksum type `1`.
62const CRC32C: Crc<u32> = Crc::<u32>::new(&CRC_32_ISCSI);
63
64/// CRC-64/ECMA-182 engine, the ReFS checksum type `2`.
65const CRC64: Crc<u64> = Crc::<u64>::new(&CRC_64_ECMA_182);
66
67/// ReFS metadata-block checksum type `1`: CRC-32C (Castagnoli).
68#[must_use]
69pub fn crc32c(data: &[u8]) -> u32 {
70 CRC32C.checksum(data)
71}
72
73/// ReFS metadata-block checksum type `2`: CRC-64/ECMA-182.
74#[must_use]
75pub fn crc64_ecma(data: &[u8]) -> u64 {
76 CRC64.checksum(data)
77}
78
79/// A ReFS v3 self-describing metadata-block header.
80///
81/// Carries the four-byte block signature and the block's own (self) block
82/// number. `#[non_exhaustive]` so later phases add the redundancy block numbers,
83/// table identifier, and clocks without a breaking change.
84#[derive(Debug, Clone, PartialEq, Eq)]
85#[non_exhaustive]
86pub struct MetaBlock {
87 /// The four-byte block signature (`SUPB`/`CHKP`/`MSB+`), validated against
88 /// the caller's `expected` signature.
89 pub signature: [u8; 4],
90 /// The block's own (self) block number, at header offset `0x20`.
91 pub block_number: u64,
92}
93
94impl MetaBlock {
95 /// Parse and validate a v3 metadata-block header at the start of `data`.
96 ///
97 /// `expected` is the signature the caller requires (`"SUPB"`, `"CHKP"`, or
98 /// `"MSB+"`); `offset` is the block's absolute byte position, carried into
99 /// the error so a mismatch names *what* was there and *where* (fail loud
100 /// with the value).
101 ///
102 /// # Errors
103 ///
104 /// - [`RefsError::BadBlockSignature`] if the first four bytes are not
105 /// `expected`.
106 /// - [`RefsError::Truncated`] if `data` is shorter than the 80-byte header.
107 pub fn parse(data: &[u8], expected: &'static str, offset: u64) -> Result<Self, RefsError> {
108 // Validate the signature before length so a wrong-block error names the
109 // offending bytes even on a short buffer (fail loud with the value).
110 let mut signature = [0u8; 4];
111 if let Some(s) = data.get(0..4) {
112 signature.copy_from_slice(s);
113 }
114 if signature.as_slice() != expected.as_bytes() {
115 return Err(RefsError::BadBlockSignature {
116 found: signature,
117 found_ascii: ascii(&signature),
118 expected,
119 offset,
120 });
121 }
122
123 if data.len() < V3_HEADER_LEN {
124 return Err(RefsError::Truncated {
125 structure: "v3 metadata-block header",
126 need: V3_HEADER_LEN,
127 have: data.len(),
128 });
129 }
130
131 Ok(Self {
132 signature,
133 block_number: le_u64(data, SELF_BLOCK_NUMBER_OFFSET),
134 })
135 }
136
137 /// Verify a CRC-32C over the explicit byte range `data[start..end]` against
138 /// a `stored` value.
139 ///
140 /// Returns `Some(true)`/`Some(false)` when the range is in bounds, or
141 /// `None` when it is not (out-of-range never panics — the Paranoid
142 /// Gatekeeper standard). The **range is the caller's responsibility**: ReFS's
143 /// own block-checksum coverage range is undetermined from the available
144 /// reverse-engineered references (see the module docs), so this crate does
145 /// not guess it.
146 #[must_use]
147 pub fn verify_crc32c(data: &[u8], start: usize, end: usize, stored: u32) -> Option<bool> {
148 if start > end {
149 return None;
150 }
151 let slice = data.get(start..end)?;
152 Some(crc32c(slice) == stored)
153 }
154}