Skip to main content

qualia_core_db/net/dns/
archive.rs

1//! Zero-Copy Binary Archive Format for DNS & SDN Records.
2//!
3//! Provides persistent cold-storage serialization and memory-mapped reader
4//! for archived DNS `NQuin` statements, supporting long-term compliance,
5//! DNSSEC provenance tracking, and forensic network audits.
6//!
7//! Conforms to QualiaDB Rule 0-A (zero heap in hot paths) and Rule 0-B (< 500 lines).
8
9#![allow(dead_code)]
10
11use crate::NQuin;
12use std::io;
13
14/// 4-byte magic identifier for Qualia DNS Archive files: "QDNS".
15pub const QDNS_MAGIC: [u8; 4] = [0x51, 0x44, 0x4E, 0x53];
16
17/// Fixed 64-byte Preamble for `.qdns` archive files.
18#[repr(C)]
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct DnsArchiveHeader {
21    pub magic: [u8; 4],
22    pub version: u16,
23    pub reserved_u16: u16,
24    pub record_count: u32,
25    pub clock_start: u32,
26    pub clock_end: u32,
27    pub reserved: [u8; 44],
28}
29
30impl DnsArchiveHeader {
31    pub const SIZE: usize = 64;
32
33    /// Creates a default `DnsArchiveHeader`.
34    pub fn new(record_count: u32, clock_start: u32, clock_end: u32) -> Self {
35        Self {
36            magic: QDNS_MAGIC,
37            version: 1,
38            reserved_u16: 0,
39            record_count,
40            clock_start,
41            clock_end,
42            reserved: [0u8; 44],
43        }
44    }
45
46    /// Validates internal consistency; error on violation.
47    pub fn validate(&self) -> io::Result<()> {
48        if self.magic != QDNS_MAGIC {
49            return Err(io::Error::new(
50                io::ErrorKind::InvalidData,
51                "invalid QDNS archive magic",
52            ));
53        }
54        if self.version != 1 {
55            return Err(io::Error::new(
56                io::ErrorKind::InvalidData,
57                "unsupported QDNS archive version",
58            ));
59        }
60        Ok(())
61    }
62}
63
64/// Write a batch of archived `NQuin` records to an output stream.
65///
66/// Writes the 64-byte header followed by contiguous 48-byte records.
67/// Returns the total bytes written.
68pub fn write_dns_archive<W: io::Write>(
69    writer: &mut W,
70    quins: &[NQuin],
71    clock_start: u32,
72    clock_end: u32,
73) -> io::Result<usize> {
74    let header = DnsArchiveHeader::new(quins.len() as u32, clock_start, clock_end);
75    let header_bytes = unsafe {
76        std::slice::from_raw_parts(&header as *const _ as *const u8, DnsArchiveHeader::SIZE)
77    };
78    writer.write_all(header_bytes)?;
79
80    let record_bytes = bytemuck::cast_slice(quins);
81    writer.write_all(record_bytes)?;
82
83    Ok(DnsArchiveHeader::SIZE + record_bytes.len())
84}
85
86/// Read archived `NQuin` records from an input stream into caller-supplied `out_quins`.
87///
88/// Returns the header and count of records read. Zero heap allocation.
89pub fn read_dns_archive<R: io::Read>(
90    reader: &mut R,
91    out_quins: &mut [NQuin],
92) -> io::Result<(DnsArchiveHeader, usize)> {
93    let mut header_buf = [0u8; DnsArchiveHeader::SIZE];
94    reader.read_exact(&mut header_buf)?;
95
96    let header: DnsArchiveHeader =
97        unsafe { std::ptr::read_unaligned(header_buf.as_ptr() as *const DnsArchiveHeader) };
98    header.validate()?;
99
100    let to_read = core::cmp::min(header.record_count as usize, out_quins.len());
101    let target_bytes = bytemuck::cast_slice_mut(&mut out_quins[..to_read]);
102    reader.read_exact(target_bytes)?;
103
104    Ok((header, to_read))
105}
106
107#[cfg(not(target_arch = "wasm32"))]
108/// Zero-deserialization memory-mapped reader for `.qdns` archive files.
109pub struct DnsArchiveMmap {
110    mmap: memmap2::Mmap,
111}
112
113#[cfg(not(target_arch = "wasm32"))]
114impl DnsArchiveMmap {
115    /// Memory-maps an archive file, validating the magic preamble immediately.
116    pub fn open<P: AsRef<std::path::Path>>(path: P) -> io::Result<Self> {
117        let file = std::fs::File::open(path)?;
118        let mmap = unsafe { memmap2::MmapOptions::new().map(&file)? };
119
120        if mmap.len() < DnsArchiveHeader::SIZE {
121            return Err(io::Error::new(
122                io::ErrorKind::UnexpectedEof,
123                "file too small for QDNS header",
124            ));
125        }
126
127        let archive = Self { mmap };
128        archive.header().validate()?;
129        Ok(archive)
130    }
131
132    /// Casts the 64-byte preamble directly from mapped memory.
133    pub fn header(&self) -> &DnsArchiveHeader {
134        unsafe { &*(self.mmap.as_ptr() as *const DnsArchiveHeader) }
135    }
136
137    /// Returns a zero-copy slice of all `NQuin` records in the archive.
138    pub fn records(&self) -> &[NQuin] {
139        let payload = &self.mmap[DnsArchiveHeader::SIZE..];
140        let record_size = std::mem::size_of::<NQuin>();
141        let count = payload.len() / record_size;
142        unsafe { std::slice::from_raw_parts(payload.as_ptr() as *const NQuin, count) }
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::net::dns::quin_records::*;
150    use crate::PermissiveRoutingLane;
151    use std::io::Cursor;
152
153    #[test]
154    fn header_size_and_alignment() {
155        assert_eq!(std::mem::size_of::<DnsArchiveHeader>(), 64);
156    }
157
158    #[test]
159    fn archive_roundtrip_stream() {
160        let q1 = encode_a_record(
161            "arch1.lan",
162            [192, 168, 1, 10],
163            3600,
164            PermissiveRoutingLane::PassthroughStandard,
165        );
166        let q2 = encode_aaaa_record(
167            "arch2.lan",
168            [0x20; 16],
169            7200,
170            PermissiveRoutingLane::EnforcePermissiveCommons,
171        );
172        let quins = [q1, q2];
173
174        let mut buf = Vec::new();
175        let bytes_written = write_dns_archive(&mut buf, &quins, 100, 200).unwrap();
176        assert_eq!(bytes_written, 64 + 48 * 2);
177
178        let mut cursor = Cursor::new(buf);
179        let mut out_quins = [NQuin::default(); 4];
180        let (header, count) = read_dns_archive(&mut cursor, &mut out_quins).unwrap();
181
182        assert_eq!(header.magic, QDNS_MAGIC);
183        assert_eq!(header.version, 1);
184        assert_eq!(header.record_count, 2);
185        assert_eq!(header.clock_start, 100);
186        assert_eq!(header.clock_end, 200);
187        assert_eq!(count, 2);
188
189        assert_eq!(out_quins[0].subject, q1.subject);
190        assert_eq!(out_quins[1].subject, q2.subject);
191        assert!(out_quins[0].verify_ecc_parity());
192        assert!(out_quins[1].verify_ecc_parity());
193    }
194
195    #[test]
196    fn archive_mmap_file_roundtrip() {
197        use tempfile::NamedTempFile;
198
199        let q1 = encode_a_record(
200            "file.lan",
201            [1, 2, 3, 4],
202            300,
203            PermissiveRoutingLane::PassthroughStandard,
204        );
205        let quins = [q1];
206
207        let mut temp_file = NamedTempFile::new().unwrap();
208        write_dns_archive(&mut temp_file, &quins, 50, 150).unwrap();
209
210        let mmap_archive = DnsArchiveMmap::open(temp_file.path()).unwrap();
211        assert_eq!(mmap_archive.header().record_count, 1);
212        assert_eq!(mmap_archive.records().len(), 1);
213        assert_eq!(mmap_archive.records()[0].subject, q1.subject);
214        assert!(mmap_archive.records()[0].verify_ecc_parity());
215    }
216}