Skip to main content

bgpkit_parser/parser/mrt/
mrt_header.rs

1use crate::models::{CommonHeader, EntryType};
2use crate::ParserError;
3use bytes::Bytes;
4use std::io::Read;
5use zerocopy::big_endian::{U16, U32};
6use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
7
8/// On-wire MRT common header layout (12 bytes, network byte order).
9#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
10#[repr(C)]
11struct RawMrtCommonHeader {
12    timestamp: U32,
13    entry_type: U16,
14    entry_subtype: U16,
15    length: U32,
16}
17
18const _: () = assert!(size_of::<RawMrtCommonHeader>() == 12);
19
20/// On-wire MRT header with microseconds included (16 bytes, network byte order)
21#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
22#[repr(C)]
23struct RawMrtEtCommonHeader {
24    timestamp: U32,
25    entry_type: U16,
26    entry_subtype: U16,
27    length: U32,
28    microseconds: U32,
29}
30
31const _: () = assert!(size_of::<RawMrtEtCommonHeader>() == 16);
32
33enum RawMrtHeader {
34    Standard(RawMrtCommonHeader),
35    Et(RawMrtEtCommonHeader),
36}
37
38impl From<&CommonHeader> for RawMrtHeader {
39    fn from(header: &CommonHeader) -> Self {
40        match header.microsecond_timestamp {
41            None => RawMrtHeader::Standard(RawMrtCommonHeader {
42                timestamp: U32::new(header.timestamp),
43                entry_type: U16::new(header.entry_type as u16),
44                entry_subtype: U16::new(header.entry_subtype),
45                length: U32::new(header.length),
46            }),
47            Some(microseconds) => RawMrtHeader::Et(RawMrtEtCommonHeader {
48                timestamp: U32::new(header.timestamp),
49                entry_type: U16::new(header.entry_type as u16),
50                entry_subtype: U16::new(header.entry_subtype),
51                // Internally, we use the length of the MRT payload.
52                // However in the header, the length includes the space used by the extra timestamp
53                // data.
54                length: U32::new(header.length + 4),
55                microseconds: U32::new(microseconds),
56            }),
57        }
58    }
59}
60
61impl RawMrtHeader {
62    fn as_bytes(&self) -> &[u8] {
63        match self {
64            RawMrtHeader::Standard(raw) => raw.as_bytes(),
65            RawMrtHeader::Et(raw) => raw.as_bytes(),
66        }
67    }
68}
69
70/// Result of parsing a common header, including the raw bytes.
71pub struct ParsedHeader {
72    pub header: CommonHeader,
73    pub raw_bytes: Bytes,
74}
75
76/// MRT common header [RFC6396][header].
77///
78/// [header]: https://tools.ietf.org/html/rfc6396#section-4.1
79///
80/// A MRT record is constructed as the following:
81/// ```text
82///  0                   1                   2                   3
83///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
84/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
85/// |                           Timestamp                           |
86/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
87/// |             Type              |            Subtype            |
88/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
89/// |                             Length                            |
90/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
91/// |                      Message... (variable)
92/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
93///
94/// ```
95///
96/// Or with extended timestamp:
97/// ```text
98///  0                   1                   2                   3
99///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
100/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101/// |                           Timestamp                           |
102/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103/// |             Type              |            Subtype            |
104/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105/// |                             Length                            |
106/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107/// |                      Microsecond Timestamp                    |
108/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109/// |                      Message... (variable)
110/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111/// ```
112pub fn parse_common_header<T: Read>(input: &mut T) -> Result<CommonHeader, ParserError> {
113    Ok(parse_common_header_with_bytes(input)?.header)
114}
115
116/// Parse the MRT common header and return both the parsed header and raw bytes.
117///
118/// This is useful when you need to preserve the original bytes for debugging
119/// or exporting problematic records without re-encoding.
120pub fn parse_common_header_with_bytes<T: Read>(input: &mut T) -> Result<ParsedHeader, ParserError> {
121    let framed = frame_common_header(input)?;
122    Ok(ParsedHeader {
123        header: framed.header?,
124        raw_bytes: framed.raw_bytes,
125    })
126}
127
128/// A common header as read from the wire, with its contents validated separately
129/// from its framing.
130pub(crate) struct FramedHeader {
131    /// The parsed header, or why its contents were rejected.
132    pub(crate) header: Result<CommonHeader, ParserError>,
133    /// The header bytes as read from the wire.
134    pub(crate) raw_bytes: Bytes,
135}
136
137/// A common header read from the wire, with its raw bytes kept in a fixed buffer.
138///
139/// The default parse path only needs the raw header bytes when something goes wrong, so capturing
140/// them on the stack avoids one small heap allocation per record.
141#[derive(Clone, Copy)]
142pub(crate) struct HeaderBuf {
143    bytes: [u8; 16],
144    len: usize,
145}
146
147impl Default for HeaderBuf {
148    fn default() -> Self {
149        HeaderBuf::new()
150    }
151}
152
153impl HeaderBuf {
154    pub(crate) fn new() -> Self {
155        HeaderBuf {
156            bytes: [0u8; 16],
157            len: 0,
158        }
159    }
160
161    pub(crate) fn as_slice(&self) -> &[u8] {
162        &self.bytes[..self.len]
163    }
164}
165
166/// A common header as read from the wire, borrowing its raw bytes from the caller's buffer.
167pub(crate) struct FramedHeaderRef<'a> {
168    /// The parsed header, or why its contents were rejected.
169    pub(crate) header: Result<CommonHeader, ParserError>,
170    /// The header bytes as read from the wire.
171    pub(crate) raw_bytes: &'a [u8],
172    /// Length of the record body following `raw_bytes`.
173    pub(crate) body_length: u32,
174}
175
176/// Read a common header into `header`, keeping its body length even when the contents are
177/// rejected. Only I/O failures are returned as `Err`.
178pub(crate) fn frame_common_header_captured<'a, T: Read>(
179    input: &mut T,
180    header: &'a mut HeaderBuf,
181) -> std::io::Result<FramedHeaderRef<'a>> {
182    header.len = 0;
183    read_header_upto(input, header, 12)?;
184    if header.len < 12 {
185        return Err(std::io::Error::new(
186            std::io::ErrorKind::UnexpectedEof,
187            "failed to fill whole buffer",
188        ));
189    }
190
191    // Single bounds check via zerocopy instead of four sequential cursor reads.
192    let raw = RawMrtCommonHeader::ref_from_bytes(&header.bytes[..12])
193        .expect("base_bytes is exactly 12 bytes with no alignment requirement");
194
195    let timestamp = raw.timestamp.get();
196    let entry_subtype = raw.entry_subtype.get();
197    // the length field does not include the length of the common header
198    let length = raw.length.get();
199
200    // The on-wire length counts every byte after the 12-byte base header, so it
201    // frames the record even when the header contents are invalid.
202    let entry_type = match EntryType::try_from(raw.entry_type.get()) {
203        Ok(entry_type) => entry_type,
204        Err(error) => {
205            return Ok(FramedHeaderRef {
206                header: Err(error.into()),
207                raw_bytes: header.as_slice(),
208                body_length: length,
209            })
210        }
211    };
212
213    let (microsecond_timestamp, body_length) = match &entry_type {
214        EntryType::BGP4MP_ET => {
215            // For ET records, the on-wire length includes the extra 4-byte microsecond timestamp
216            // that lives in the header. Internally we store `length` as the message length only,
217            // so subtract 4 after validating to avoid underflow.
218            if length < 4 {
219                return Ok(FramedHeaderRef {
220                    header: Err(ParserError::ParseError(
221                        "invalid MRT header length for ET record: length < 4".into(),
222                    )),
223                    raw_bytes: header.as_slice(),
224                    body_length: length,
225                });
226            }
227            read_header_upto(input, header, 16)?;
228            if header.len < 16 {
229                return Err(std::io::Error::new(
230                    std::io::ErrorKind::UnexpectedEof,
231                    "failed to fill whole buffer",
232                ));
233            }
234            (
235                Some(u32::from_be_bytes(
236                    header.bytes[12..16].try_into().expect("four bytes"),
237                )),
238                length - 4,
239            )
240        }
241        _ => (None, length),
242    };
243
244    Ok(FramedHeaderRef {
245        header: Ok(CommonHeader {
246            timestamp,
247            microsecond_timestamp,
248            entry_type,
249            entry_subtype,
250            length: body_length,
251        }),
252        raw_bytes: header.as_slice(),
253        body_length,
254    })
255}
256
257/// Read into `header.bytes` until it holds `end` bytes.
258///
259/// `header.len` advances as bytes arrive, so a reader that fails part-way still leaves the bytes it
260/// did deliver in the buffer for error reporting.
261fn read_header_upto(
262    input: &mut impl Read,
263    header: &mut HeaderBuf,
264    end: usize,
265) -> std::io::Result<()> {
266    while header.len < end {
267        match input.read(&mut header.bytes[header.len..end]) {
268            Ok(0) => break,
269            Ok(read) => header.len += read,
270            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
271            Err(error) => return Err(error),
272        }
273    }
274    Ok(())
275}
276
277/// Read a common header, keeping its body length even when the contents are
278/// rejected. Only I/O failures are returned as `Err`.
279pub(crate) fn frame_common_header<T: Read>(input: &mut T) -> std::io::Result<FramedHeader> {
280    let mut header = HeaderBuf::new();
281    let framed = frame_common_header_captured(input, &mut header)?;
282    Ok(FramedHeader {
283        header: framed.header,
284        raw_bytes: Bytes::copy_from_slice(framed.raw_bytes),
285    })
286}
287
288impl CommonHeader {
289    pub fn encode(&self) -> Bytes {
290        let raw = RawMrtHeader::from(self);
291        Bytes::copy_from_slice(raw.as_bytes())
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::models::EntryType;
299    use bytes::Buf;
300
301    #[test]
302    fn test_parse_common_header_with_bytes() {
303        let input = Bytes::from_static(&[
304            0, 0, 0, 1, // timestamp
305            0, 16, // entry type
306            0, 4, // entry subtype
307            0, 0, 0, 5, // length
308        ]);
309
310        let mut reader = input.clone().reader();
311        let result = parse_common_header_with_bytes(&mut reader).unwrap();
312
313        assert_eq!(result.header.timestamp, 1);
314        assert_eq!(result.header.entry_type, EntryType::BGP4MP);
315        assert_eq!(result.header.entry_subtype, 4);
316        assert_eq!(result.header.length, 5);
317        assert_eq!(result.raw_bytes, input);
318    }
319
320    #[test]
321    fn test_parse_common_header_with_bytes_et() {
322        let input = Bytes::from_static(&[
323            0, 0, 0, 1, // timestamp
324            0, 17, // entry type = BGP4MP_ET
325            0, 4, // entry subtype
326            0, 0, 0, 9, // length (includes 4 bytes for microsecond)
327            0, 3, 130, 112, // microsecond timestamp
328        ]);
329
330        let mut reader = input.clone().reader();
331        let result = parse_common_header_with_bytes(&mut reader).unwrap();
332
333        assert_eq!(result.header.timestamp, 1);
334        assert_eq!(result.header.entry_type, EntryType::BGP4MP_ET);
335        assert_eq!(result.header.entry_subtype, 4);
336        assert_eq!(result.header.length, 5); // adjusted length
337        assert_eq!(result.header.microsecond_timestamp, Some(230_000));
338        assert_eq!(result.raw_bytes, input);
339    }
340
341    /// Test that the length is not adjusted when the microsecond timestamp is not present.
342    #[test]
343    fn test_encode_common_header() {
344        let header = CommonHeader {
345            timestamp: 1,
346            microsecond_timestamp: None,
347            entry_type: EntryType::BGP4MP,
348            entry_subtype: 4,
349            length: 5,
350        };
351
352        let expected = Bytes::from_static(&[
353            0, 0, 0, 1, // timestamp
354            0, 16, // entry type
355            0, 4, // entry subtype
356            0, 0, 0, 5, // length
357        ]);
358
359        let encoded = header.encode();
360        assert_eq!(encoded, expected);
361
362        let mut reader = expected.reader();
363        let parsed = parse_common_header(&mut reader).unwrap();
364        assert_eq!(parsed, header);
365    }
366
367    /// Test that the length is adjusted when the microsecond timestamp is present.
368    #[test]
369    fn test_encode_common_header_et() {
370        let header = CommonHeader {
371            timestamp: 1,
372            microsecond_timestamp: Some(230_000),
373            entry_type: EntryType::BGP4MP_ET,
374            entry_subtype: 4,
375            length: 5,
376        };
377
378        let expected = Bytes::from_static(&[
379            0, 0, 0, 1, // timestamp
380            0, 17, // entry type
381            0, 4, // entry subtype
382            0, 0, 0, 9, // length
383            0, 3, 130, 112, // microsecond timestamp
384        ]);
385
386        let encoded = header.encode();
387        assert_eq!(encoded, expected);
388
389        let mut reader = expected.reader();
390        let parsed = parse_common_header(&mut reader).unwrap();
391        assert_eq!(parsed, header);
392    }
393
394    /// Ensure ET header with invalid on-wire length (< 4) returns error instead of panicking.
395    #[test]
396    fn test_parse_common_header_et_invalid_length() {
397        // Construct a header with length=3 for ET (which is invalid since it must include 4 bytes of microsecond field)
398        let bytes = Bytes::from_static(&[
399            0, 0, 0, 0, // timestamp
400            0, 17, // entry type = BGP4MP_ET
401            0, 0, // subtype
402            0, 0, 0, 3, // length (invalid for ET)
403        ]);
404        let mut reader = bytes.reader();
405        let res = parse_common_header(&mut reader);
406        assert!(res.is_err());
407    }
408}