Skip to main content

onelf_format/
footer.rs

1//! Footer structure and serialization
2//!
3//! The footer is located at the end of every ONELF package and contains:
4//! - Magic bytes for identification
5//! - Format version
6//! - Offsets to manifest, payload, and optional dictionary
7//! - Checksums for integrity verification
8//!
9//! # Structure
10//!
11//! The footer is exactly 76 bytes and is organized as follows:
12//!
13//! ```text
14//! Offset  Size    Field
15//! ------  -------  -------------------
16//! 0      8        Magic: "ONELF\0\x01\x00"
17//! 8      2        Format version (u16)
18//! 10     2        Flags (u16)
19//! 12     8        Manifest offset (u64)
20//! 20     8        Manifest compressed size (u64)
21//! 28     8        Manifest original size (u64)
22//! 36     8        Payload offset (u64)
23//! 44     8        Payload total size (u64)
24//! 52     8        Dictionary offset (u64)
25//! 60     4        Dictionary size (u32)
26//! 64     4        Manifest checksum (xxh32)
27//! 68     8        End magic: "FLENONE\x00"
28//! ```
29//!
30//! # Example
31//!
32//! ```ignore
33//! use onelf_format::Footer;
34//!
35//! let footer = Footer {
36//!     format_version: 1,
37//!     // ... other fields
38//! };
39//! ```
40
41use std::io::{self, Read, Write};
42
43pub const FOOTER_SIZE: usize = 76;
44pub const MAGIC: [u8; 8] = *b"ONELF\x00\x01\x00";
45pub const END_MAGIC: [u8; 8] = *b"FLENONE\x00";
46
47bitflags! {
48    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49    pub struct Flags: u16 {
50        const HAS_DICT       = 1 << 0;
51        const MEMFD_HINT     = 1 << 1;
52        const SHARUN_COMPAT  = 1 << 2;
53        /// Payload blocks are stored raw (no zstd). `compressed_size`
54        /// equals `original_size` for every block; the runtime reads
55        /// payload bytes directly without decompression.
56        const STORED         = 1 << 3;
57    }
58}
59
60#[derive(Debug, Clone)]
61pub struct Footer {
62    /// Format version number (currently 1).
63    pub format_version: u16,
64    /// Feature flags describing optional sections and capabilities.
65    pub flags: Flags,
66    /// Byte offset where the compressed manifest begins.
67    pub manifest_offset: u64,
68    /// Size of the manifest after compression.
69    pub manifest_compressed: u64,
70    /// Size of the manifest before compression.
71    pub manifest_original: u64,
72    /// Byte offset where the payload section begins.
73    pub payload_offset: u64,
74    /// Total size of the payload section in bytes.
75    pub payload_size: u64,
76    /// Byte offset of the zstd dictionary, or 0 if absent.
77    pub dict_offset: u64,
78    /// Size of the zstd dictionary in bytes, or 0 if absent.
79    pub dict_size: u32,
80    /// xxHash32 checksum of the *uncompressed* manifest bytes, verified
81    /// before the manifest is trusted.
82    pub manifest_checksum: [u8; 4],
83}
84
85impl Footer {
86    /// Whether the payload is stored raw (no zstd). When true the runtime
87    /// must skip decompression and use payload bytes directly.
88    pub fn is_stored(&self) -> bool {
89        self.flags.contains(Flags::STORED)
90    }
91
92    pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
93        w.write_all(&MAGIC)?; // 8
94        w.write_all(&self.format_version.to_le_bytes())?; // 2
95        w.write_all(&self.flags.bits().to_le_bytes())?; // 2
96        w.write_all(&self.manifest_offset.to_le_bytes())?; // 8
97        w.write_all(&self.manifest_compressed.to_le_bytes())?; // 8
98        w.write_all(&self.manifest_original.to_le_bytes())?; // 8
99        w.write_all(&self.payload_offset.to_le_bytes())?; // 8
100        w.write_all(&self.payload_size.to_le_bytes())?; // 8
101        w.write_all(&self.dict_offset.to_le_bytes())?; // 8
102        w.write_all(&self.dict_size.to_le_bytes())?; // 4
103        w.write_all(&self.manifest_checksum)?; // 4
104        w.write_all(&END_MAGIC)?; // 8
105        Ok(()) // = 76
106    }
107
108    pub fn read_from<R: Read>(r: &mut R) -> io::Result<Self> {
109        let mut buf = [0u8; FOOTER_SIZE];
110        r.read_exact(&mut buf)?;
111        Self::from_bytes(&buf)
112    }
113
114    pub fn from_bytes(buf: &[u8; FOOTER_SIZE]) -> io::Result<Self> {
115        if &buf[0..8] != &MAGIC {
116            return Err(io::Error::new(
117                io::ErrorKind::InvalidData,
118                "invalid onelf magic",
119            ));
120        }
121        if &buf[68..76] != &END_MAGIC {
122            return Err(io::Error::new(
123                io::ErrorKind::InvalidData,
124                "invalid onelf end magic",
125            ));
126        }
127
128        let format_version = u16::from_le_bytes(buf[8..10].try_into().unwrap());
129        if format_version != 1 {
130            return Err(io::Error::new(
131                io::ErrorKind::InvalidData,
132                format!("unsupported format version: {}", format_version),
133            ));
134        }
135
136        let flags_raw = u16::from_le_bytes(buf[10..12].try_into().unwrap());
137        let flags = Flags::from_bits_retain(flags_raw);
138
139        Ok(Footer {
140            format_version,
141            flags,
142            manifest_offset: u64::from_le_bytes(buf[12..20].try_into().unwrap()),
143            manifest_compressed: u64::from_le_bytes(buf[20..28].try_into().unwrap()),
144            manifest_original: u64::from_le_bytes(buf[28..36].try_into().unwrap()),
145            payload_offset: u64::from_le_bytes(buf[36..44].try_into().unwrap()),
146            payload_size: u64::from_le_bytes(buf[44..52].try_into().unwrap()),
147            dict_offset: u64::from_le_bytes(buf[52..60].try_into().unwrap()),
148            dict_size: u32::from_le_bytes(buf[60..64].try_into().unwrap()),
149            manifest_checksum: buf[64..68].try_into().unwrap(),
150        })
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157
158    fn sample() -> Footer {
159        Footer {
160            format_version: 1,
161            flags: Flags::HAS_DICT | Flags::STORED,
162            manifest_offset: 0x1122,
163            manifest_compressed: 0x33,
164            manifest_original: 0x44,
165            payload_offset: 0x55,
166            payload_size: 0x66,
167            dict_offset: 0x77,
168            dict_size: 0x88,
169            manifest_checksum: [1, 2, 3, 4],
170        }
171    }
172
173    #[test]
174    fn footer_roundtrips() {
175        let f = sample();
176        let mut buf = Vec::new();
177        f.write_to(&mut buf).unwrap();
178        assert_eq!(buf.len(), FOOTER_SIZE);
179        let back = Footer::from_bytes(&buf.try_into().unwrap()).unwrap();
180        assert_eq!(back.format_version, f.format_version);
181        assert_eq!(back.flags, f.flags);
182        assert_eq!(back.manifest_offset, f.manifest_offset);
183        assert_eq!(back.dict_size, f.dict_size);
184        assert_eq!(back.manifest_checksum, f.manifest_checksum);
185    }
186
187    #[test]
188    fn malformed_footers_error_without_panic() {
189        let mut buf = Vec::new();
190        sample().write_to(&mut buf).unwrap();
191
192        // Bad start magic.
193        let mut bad = buf.clone();
194        bad[0] ^= 0xff;
195        assert!(Footer::from_bytes(&bad.clone().try_into().unwrap()).is_err());
196
197        // Bad end magic.
198        let mut bad = buf.clone();
199        bad[68] ^= 0xff;
200        assert!(Footer::from_bytes(&bad.clone().try_into().unwrap()).is_err());
201
202        // Unsupported version.
203        let mut bad = buf.clone();
204        bad[8..10].copy_from_slice(&2u16.to_le_bytes());
205        assert!(Footer::from_bytes(&bad.try_into().unwrap()).is_err());
206    }
207}