Skip to main content

refs_core/
boot.rs

1//! ReFS boot sector / Volume Boot Record (VBR) — the file-system recognition
2//! structure at **offset 0** of the volume.
3//!
4//! Field offsets follow libyal's `libfsrefs` documentation of the ReFS
5//! `FILE_SYSTEM_RECOGNITION_STRUCTURE` (reverse-engineered — no official
6//! Microsoft spec). Every offset here was additionally byte-verified against a
7//! real ReFS v3.14 volume minted on Windows 11 (see tests/data/README.md):
8//!
9//! ```text
10//! off  size  field
11//!   0    3   boot entry point / JMP (0x00 on a data-only ReFS volume)
12//!   3    8   file-system signature "ReFS\0\0\0\0"
13//!  16    4   FS recognition-structure identifier "FSRS"
14//!  24    8   number of sectors
15//!  32    4   bytes per sector
16//!  36    4   sectors per cluster block (allocation unit)
17//!  40    1   major format version
18//!  41    1   minor format version
19//!  56    8   volume serial number
20//!  64    8   container / band size
21//! ```
22//!
23//! ReFS is little-endian.
24
25use crate::bytes::{ascii, le_u32, le_u64, u8_at};
26use crate::error::RefsError;
27use crate::superblock::REFS_SUPERBLOCK_CLUSTER;
28
29/// The ReFS file-system signature `"ReFS\0\0\0\0"` at boot offset 3.
30pub const REFS_SIGNATURE: &[u8; 8] = b"ReFS\x00\x00\x00\x00";
31
32/// The file-system recognition-structure identifier `"FSRS"` at boot offset 16.
33pub const REFS_FSRS: &[u8; 4] = b"FSRS";
34
35/// Minimum bytes required to read every field this parser extracts (through the
36/// container size at offset 64, +8 = 72).
37const BOOT_MIN_LEN: usize = 72;
38
39/// Parsed ReFS boot VBR / FS-recognition structure.
40///
41/// `#[non_exhaustive]` so later phases add fields (flags, the FSRS checksum)
42/// without a breaking change.
43#[derive(Debug, Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct BootSector {
46    /// FS signature at offset 3 — validated to equal [`REFS_SIGNATURE`].
47    pub signature: [u8; 8],
48    /// FS-recognition-structure identifier at offset 16 — validated to equal
49    /// [`REFS_FSRS`].
50    pub fsrs: [u8; 4],
51    /// `Number of sectors` (offset 24).
52    pub num_sectors: u64,
53    /// `Bytes per sector` (offset 32).
54    pub bytes_per_sector: u32,
55    /// `Sectors per cluster block` / allocation unit (offset 36).
56    pub sectors_per_cluster: u32,
57    /// `Major format version` (offset 40) — `3` for the v3.x line this reader
58    /// targets, `1` for the legacy Server 2012 / 8.1 layout.
59    pub major_version: u8,
60    /// `Minor format version` (offset 41).
61    pub minor_version: u8,
62    /// `Volume serial number` (offset 56).
63    pub volume_serial: u64,
64    /// `Container` / band size (offset 64).
65    pub container_size: u64,
66}
67
68impl BootSector {
69    /// Parse the boot VBR from the start of `data`.
70    ///
71    /// # Errors
72    ///
73    /// - [`RefsError::BadSignature`] if bytes 3..11 are not `"ReFS\0\0\0\0"` —
74    ///   the eight offending bytes are carried in the error.
75    /// - [`RefsError::BadFsrs`] if bytes 16..20 are not `"FSRS"`.
76    /// - [`RefsError::Truncated`] if `data` is shorter than the fields read.
77    ///
78    /// The version is **not** checked here (a v1 volume still has a valid
79    /// signature); call [`Self::require_v3`] to gate on version.
80    pub fn parse(data: &[u8]) -> Result<Self, RefsError> {
81        // Validate identity (signature, then FSRS) before length so a
82        // wrong-image error names the offending bytes even on a short buffer.
83        let mut signature = [0u8; 8];
84        if let Some(s) = data.get(3..11) {
85            signature.copy_from_slice(s);
86        }
87        if &signature != REFS_SIGNATURE {
88            return Err(RefsError::BadSignature { found: signature });
89        }
90
91        let mut fsrs = [0u8; 4];
92        if let Some(s) = data.get(16..20) {
93            fsrs.copy_from_slice(s);
94        }
95        if &fsrs != REFS_FSRS {
96            return Err(RefsError::BadFsrs {
97                found: fsrs,
98                found_ascii: ascii(&fsrs),
99            });
100        }
101
102        // All parsed fields lie within the first BOOT_MIN_LEN bytes; range-check
103        // once so a short buffer that passed the signature check still fails
104        // loud rather than reading zeroes for real geometry.
105        if data.len() < BOOT_MIN_LEN {
106            return Err(RefsError::Truncated {
107                structure: "boot VBR",
108                need: BOOT_MIN_LEN,
109                have: data.len(),
110            });
111        }
112
113        Ok(Self {
114            signature,
115            fsrs,
116            num_sectors: le_u64(data, 24),
117            bytes_per_sector: le_u32(data, 32),
118            sectors_per_cluster: le_u32(data, 36),
119            major_version: u8_at(data, 40),
120            minor_version: u8_at(data, 41),
121            volume_serial: le_u64(data, 56),
122            container_size: le_u64(data, 64),
123        })
124    }
125
126    /// Cluster (allocation-unit) size in bytes: `bytes_per_sector *
127    /// sectors_per_cluster`.
128    ///
129    /// Saturating so absurd geometry from a hostile image yields a clamped value
130    /// rather than an overflow panic (the Paranoid Gatekeeper standard).
131    #[must_use]
132    pub fn cluster_size(&self) -> u64 {
133        u64::from(self.bytes_per_sector).saturating_mul(u64::from(self.sectors_per_cluster))
134    }
135
136    /// True for a ReFS **v3.x** volume (`major_version == 3`) — the format this
137    /// reader targets.
138    #[must_use]
139    pub fn is_v3(&self) -> bool {
140        self.major_version == 3
141    }
142
143    /// Byte offset of the primary superblock: [`REFS_SUPERBLOCK_CLUSTER`] × the
144    /// cluster size.
145    ///
146    /// Saturating so a hostile cluster size cannot overflow.
147    #[must_use]
148    pub fn superblock_offset(&self) -> u64 {
149        REFS_SUPERBLOCK_CLUSTER.saturating_mul(self.cluster_size())
150    }
151
152    /// Reject any non-v3.x volume, naming the actual version bytes.
153    ///
154    /// This is the fail-loud version gate RESEARCH.md mandates: a v1 volume
155    /// (Server 2012 / 8.1) has a materially different on-disk layout, so parsing
156    /// it as v3 would silently misparse. Callers gate on this before trusting
157    /// any structure beyond the boot VBR.
158    ///
159    /// # Errors
160    ///
161    /// [`RefsError::UnsupportedVersion`] if `major_version != 3`.
162    pub fn require_v3(&self) -> Result<(), RefsError> {
163        if self.is_v3() {
164            Ok(())
165        } else {
166            Err(RefsError::UnsupportedVersion {
167                major: self.major_version,
168                minor: self.minor_version,
169            })
170        }
171    }
172}