Skip to main content

bgpkit_parser/parser/mrt/
mrt_record.rs

1use super::mrt_header::HeaderBuf;
2use crate::bmp::messages::{BmpMessage, BmpMessageBody};
3use crate::error::{check_max, EncodingError, ParserError};
4use crate::models::*;
5use crate::parser::{
6    parse_bgp4mp, parse_legacy_bgp, parse_table_dump_messages, parse_table_dump_v2_message,
7    ParserErrorWithBytes,
8};
9use crate::utils::convert_timestamp;
10use bytes::{BufMut, Bytes, BytesMut};
11use log::warn;
12use std::convert::TryFrom;
13use std::fs::File;
14use std::io::{Read, Write};
15use std::net::IpAddr;
16use std::path::Path;
17use std::str::FromStr;
18
19/// Raw MRT record containing the common header and unparsed message bytes.
20/// This allows for lazy parsing of the MRT message body, and provides
21/// utilities for debugging and exporting problematic records.
22#[derive(Debug, Clone)]
23pub struct RawMrtRecord {
24    pub common_header: CommonHeader,
25    /// The raw bytes of the MRT common header (as read from the wire).
26    pub header_bytes: Bytes,
27    /// The raw bytes of the MRT message body (excluding the common header).
28    pub message_bytes: Bytes,
29}
30
31/// Internal framing error that retains MRT header context when it was parsed.
32pub(crate) struct RawMrtRecordError {
33    pub(crate) error: ParserError,
34    pub(crate) common_header: Option<CommonHeader>,
35    pub(crate) bytes: Option<Vec<u8>>,
36    /// A rejected header's declared body was read in full, so the next read starts
37    /// after this record, though not necessarily on a true boundary.
38    pub(crate) record_consumed: bool,
39}
40
41impl RawMrtRecord {
42    /// Parse the raw MRT record into a fully parsed MrtRecord.
43    /// This consumes the RawMrtRecord and returns a MrtRecord.
44    pub fn parse(self) -> Result<MrtRecord, ParserError> {
45        let message = parse_mrt_body(
46            self.common_header.entry_type as u16,
47            self.common_header.entry_subtype,
48            self.message_bytes,
49        )?;
50
51        Ok(MrtRecord {
52            common_header: self.common_header,
53            message,
54        })
55    }
56
57    /// Returns the complete MRT record as raw bytes (header + message body).
58    ///
59    /// This returns the exact bytes as they were read from the wire,
60    /// without any re-encoding. This is useful for debugging problematic
61    /// MRT records by exporting them as-is to a file for further analysis.
62    ///
63    /// # Example
64    /// ```ignore
65    /// let raw_record = parser.into_raw_record_iter().next().unwrap();
66    /// let bytes = raw_record.raw_bytes();
67    /// std::fs::write("record.mrt", &bytes).unwrap();
68    /// ```
69    pub fn raw_bytes(&self) -> Bytes {
70        let mut bytes = BytesMut::with_capacity(self.header_bytes.len() + self.message_bytes.len());
71        bytes.put_slice(&self.header_bytes);
72        bytes.put_slice(&self.message_bytes);
73        bytes.freeze()
74    }
75
76    /// Writes the raw MRT record (header + message body) to a file.
77    ///
78    /// This is useful for extracting problematic MRT records for debugging
79    /// or further analysis with other tools.
80    ///
81    /// # Arguments
82    /// * `path` - The path to write the raw bytes to.
83    ///
84    /// # Example
85    /// ```ignore
86    /// let raw_record = parser.into_raw_record_iter().next().unwrap();
87    /// raw_record.write_raw_bytes("problematic_record.mrt").unwrap();
88    /// ```
89    pub fn write_raw_bytes<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
90        let mut file = File::create(path)?;
91        file.write_all(&self.header_bytes)?;
92        file.write_all(&self.message_bytes)?;
93        Ok(())
94    }
95
96    /// Appends the raw MRT record (header + message body) to a file.
97    ///
98    /// This is useful for collecting multiple problematic records into a single file.
99    ///
100    /// # Arguments
101    /// * `path` - The path to append the raw bytes to.
102    ///
103    /// # Example
104    /// ```ignore
105    /// for raw_record in parser.into_raw_record_iter() {
106    ///     if is_problematic(&raw_record) {
107    ///         raw_record.append_raw_bytes("problematic_records.mrt").unwrap();
108    ///     }
109    /// }
110    /// ```
111    pub fn append_raw_bytes<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
112        let mut file = std::fs::OpenOptions::new()
113            .create(true)
114            .append(true)
115            .open(path)?;
116        file.write_all(&self.header_bytes)?;
117        file.write_all(&self.message_bytes)?;
118        Ok(())
119    }
120
121    /// Returns the total length of the complete MRT record in bytes (header + body).
122    pub fn total_bytes_len(&self) -> usize {
123        self.header_bytes.len() + self.message_bytes.len()
124    }
125}
126
127pub fn chunk_mrt_record(input: &mut impl Read) -> Result<RawMrtRecord, ParserErrorWithBytes> {
128    chunk_mrt_record_with_context(input).map_err(|error| ParserErrorWithBytes {
129        error: error.error,
130        bytes: error.bytes,
131    })
132}
133
134/// One framed record whose header bytes stay in a fixed buffer.
135///
136/// The raw-record API hands back the header as `Bytes`; the default parse path only needs those
137/// bytes to report an error, so it keeps them here instead of allocating per record.
138pub(crate) struct ChunkedRecord {
139    pub(crate) common_header: CommonHeader,
140    header: HeaderBuf,
141    pub(crate) body: Vec<u8>,
142}
143
144impl ChunkedRecord {
145    fn header_bytes(&self) -> &[u8] {
146        self.header.as_slice()
147    }
148}
149
150/// Read one raw MRT record while retaining parsed header context on framing errors.
151pub(crate) fn chunk_mrt_record_with_context(
152    input: &mut impl Read,
153) -> Result<RawMrtRecord, RawMrtRecordError> {
154    let chunk = read_chunk(input)?;
155    Ok(RawMrtRecord {
156        common_header: chunk.common_header,
157        header_bytes: Bytes::copy_from_slice(chunk.header_bytes()),
158        message_bytes: Bytes::from(chunk.body),
159    })
160}
161
162/// Read one MRT record, keeping the header bytes in a stack buffer and the body in an owned `Vec`.
163fn read_chunk(input: &mut impl Read) -> Result<ChunkedRecord, RawMrtRecordError> {
164    let mut framer = crate::parser::mrt::frame::Framer::default();
165    let mut body = Vec::new();
166    let (common_header, header, body_len) = {
167        let frame = framer
168            .next(input, &mut body)
169            .map_err(|error| RawMrtRecordError {
170                error: error.error,
171                common_header: error.header,
172                bytes: error.bytes,
173                record_consumed: error.consumed,
174            })?;
175        (frame.header, frame.raw_header, frame.body.len())
176    };
177    let mut owned = std::mem::take(&mut body);
178    owned.truncate(body_len);
179    Ok(ChunkedRecord {
180        common_header,
181        header,
182        body: owned,
183    })
184}
185
186pub fn parse_mrt_record(input: &mut impl Read) -> Result<MrtRecord, ParserErrorWithBytes> {
187    parse_mrt_record_with_zebra_compat(input).map(|(record, _)| record)
188}
189
190pub(crate) fn raw_record_uses_zebra_compat(raw_record: &RawMrtRecord) -> bool {
191    matches!(
192        raw_record.common_header.entry_type,
193        EntryType::BGP4MP | EntryType::BGP4MP_ET
194    ) && crate::parser::mrt::messages::bgp4mp::uses_zebra_compat(
195        raw_record.common_header.entry_subtype,
196        &raw_record.message_bytes,
197    )
198}
199
200pub(crate) fn parse_mrt_record_with_zebra_compat(
201    input: &mut impl Read,
202) -> Result<(MrtRecord, bool), ParserErrorWithBytes> {
203    let chunk = read_chunk(input).map_err(|error| ParserErrorWithBytes {
204        error: error.error,
205        bytes: error.bytes,
206    })?;
207
208    let common_header = chunk.common_header;
209    // Only the error path needs the wire bytes; cloning the `Bytes` handle below is a refcount
210    // bump, while keeping the header on the stack avoids a per-record allocation on success.
211    let mut header = [0u8; 16];
212    let header_bytes = chunk.header_bytes();
213    let header_len = header_bytes.len();
214    header[..header_len].copy_from_slice(header_bytes);
215    let body = Bytes::from(chunk.body);
216    let wire_bytes = body.clone();
217
218    let used_zebra_compat = matches!(
219        common_header.entry_type,
220        EntryType::BGP4MP | EntryType::BGP4MP_ET
221    ) && crate::parser::mrt::messages::bgp4mp::uses_zebra_compat(
222        common_header.entry_subtype,
223        &body,
224    );
225
226    match parse_mrt_body(
227        common_header.entry_type as u16,
228        common_header.entry_subtype,
229        body,
230    ) {
231        Ok(message) => Ok((
232            MrtRecord {
233                common_header,
234                message,
235            },
236            used_zebra_compat,
237        )),
238        Err(error) => {
239            let mut bytes = Vec::with_capacity(header_len + wire_bytes.len());
240            bytes.extend_from_slice(&header[..header_len]);
241            bytes.extend_from_slice(&wire_bytes);
242            Err(ParserErrorWithBytes {
243                error,
244                bytes: Some(bytes),
245            })
246        }
247    }
248}
249
250/// Parse an already-chunked raw record instead of reading the next one.
251pub(crate) fn parse_chunked_record_with_zebra_compat(
252    raw_record: RawMrtRecord,
253) -> Result<(MrtRecord, bool), ParserErrorWithBytes> {
254    let used_zebra_compat = raw_record_uses_zebra_compat(&raw_record);
255    // Parse from a clone so the original is available for raw_bytes() on error,
256    // avoiding manual reassembly that could diverge from RawMrtRecord::raw_bytes().
257    match raw_record.clone().parse() {
258        Ok(record) => Ok((record, used_zebra_compat)),
259        Err(e) => Err(ParserErrorWithBytes {
260            error: e,
261            bytes: Some(raw_record.raw_bytes().to_vec()),
262        }),
263    }
264}
265
266/// Parse MRT message body with given entry type and subtype.
267///
268/// The entry type and subtype are parsed from the common header. The message body is parsed
269/// according to the entry type and subtype. The message body is the remaining bytes after the
270/// common header. The length of the message body is also parsed from the common header.
271pub fn parse_mrt_body(
272    entry_type: u16,
273    entry_subtype: u16,
274    data: Bytes,
275) -> Result<MrtMessage, ParserError> {
276    let etype = EntryType::try_from(entry_type)?;
277
278    let message: MrtMessage = match &etype {
279        EntryType::TABLE_DUMP => {
280            let mut messages = parse_table_dump_messages(entry_subtype, data)?;
281            if messages.len() == 1 {
282                MrtMessage::TableDumpMessage(messages.remove(0))
283            } else {
284                MrtMessage::TableDumpMessageBatch(messages)
285            }
286        }
287        EntryType::TABLE_DUMP_V2 => {
288            let msg = parse_table_dump_v2_message(entry_subtype, data);
289            match msg {
290                Ok(msg) => MrtMessage::TableDumpV2Message(msg),
291                Err(e) => {
292                    return Err(e);
293                }
294            }
295        }
296        EntryType::BGP4MP | EntryType::BGP4MP_ET => {
297            let msg = parse_bgp4mp(entry_subtype, data);
298            match msg {
299                Ok(msg) => MrtMessage::Bgp4Mp(msg),
300                Err(e) => {
301                    return Err(e);
302                }
303            }
304        }
305        EntryType::BGP => MrtMessage::LegacyBgp(parse_legacy_bgp(entry_subtype, data)?),
306        v => {
307            // deprecated
308            return Err(ParserError::Unsupported(format!(
309                "unsupported MRT type: {v:?}"
310            )));
311        }
312    };
313    Ok(message)
314}
315
316impl MrtRecord {
317    pub fn encode(&self) -> Result<Bytes, EncodingError> {
318        let message_bytes = self.message.encode(self.common_header.entry_subtype)?;
319        let mut new_header = self.common_header;
320        if message_bytes.len() != new_header.length as usize {
321            warn!(
322                "message length {} does not match the length in the header {} (encoding MRT record)",
323                message_bytes.len(),
324                new_header.length
325            );
326        }
327        check_max(
328            "MRT record message length",
329            message_bytes.len(),
330            u32::MAX as usize,
331        )?;
332        new_header.length = message_bytes.len() as u32;
333        let header_bytes = new_header.encode();
334
335        // // debug begins
336        // let parsed_body = parse_mrt_body(
337        //     self.common_header.entry_type as u16,
338        //     self.common_header.entry_subtype,
339        //     message_bytes.clone(),
340        // )
341        // .unwrap();
342        // assert!(self.message == parsed_body);
343        // // debug ends
344
345        let mut bytes = BytesMut::with_capacity(header_bytes.len() + message_bytes.len());
346        bytes.put_slice(&header_bytes);
347        bytes.put_slice(&message_bytes);
348        Ok(bytes.freeze())
349    }
350}
351
352impl TryFrom<&BmpMessage> for MrtRecord {
353    type Error = String;
354
355    fn try_from(bmp_message: &BmpMessage) -> Result<Self, Self::Error> {
356        let bgp_message = match &bmp_message.message_body {
357            BmpMessageBody::RouteMonitoring(m) => &m.bgp_message,
358            _ => return Err("unsupported bmp message type".to_string()),
359        };
360        let bmp_header = match &bmp_message.per_peer_header {
361            Some(h) => h,
362            None => return Err("missing per peer header".to_string()),
363        };
364
365        let local_ip = match bmp_header.peer_ip {
366            IpAddr::V4(_) => IpAddr::from_str("0.0.0.0").unwrap(),
367            IpAddr::V6(_) => IpAddr::from_str("::").unwrap(),
368        };
369        let local_asn = match bmp_header.peer_asn.is_four_byte() {
370            true => Asn::new_32bit(0),
371            false => Asn::new_16bit(0),
372        };
373
374        // A BMP feed cannot say whether the session negotiated ADD-PATH, but the
375        // parsed update can: pick the subtype that matches its identifiers.
376        let msg_type = if crate::parser::mrt::messages::bgp4mp::carries_path_ids(bgp_message) {
377            Bgp4MpType::MessageAs4Addpath
378        } else {
379            Bgp4MpType::MessageAs4
380        };
381
382        let bgp4mp_message = Bgp4MpMessage {
383            msg_type,
384            peer_asn: bmp_header.peer_asn,
385            local_asn,
386            interface_index: 0,
387            peer_ip: bmp_header.peer_ip,
388            local_ip,
389            bgp_message: bgp_message.clone(),
390        };
391
392        let mrt_message = MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(bgp4mp_message));
393
394        let (seconds, microseconds) = convert_timestamp(bmp_header.timestamp);
395
396        let subtype = msg_type as u16;
397        let encoded_message = mrt_message
398            .encode(subtype)
399            .map_err(|e| format!("cannot encode MRT message: {e}"))?;
400        let mrt_header = CommonHeader {
401            timestamp: seconds,
402            microsecond_timestamp: Some(microseconds),
403            entry_type: EntryType::BGP4MP_ET,
404            entry_subtype: msg_type as u16,
405            length: encoded_message.len() as u32,
406        };
407
408        Ok(MrtRecord {
409            common_header: mrt_header,
410            message: mrt_message,
411        })
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418    use crate::bmp::messages::headers::{BmpPeerType, PeerFlags, PerPeerFlags};
419    use crate::bmp::messages::{BmpCommonHeader, BmpMsgType, BmpPerPeerHeader, RouteMonitoring};
420    use crate::models::{AttributeValue, Origin};
421    use crate::parser::mrt::frame::MAX_MRT_MESSAGE_LEN;
422    use crate::parser::mrt::messages::table_dump::encode_table_dump_batch;
423    use std::io::Cursor;
424    use std::net::Ipv4Addr;
425    use tempfile::tempdir;
426
427    fn table_dump_message(prefix: &str) -> TableDumpMessage {
428        let mut attributes = Attributes::default();
429        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
430        TableDumpMessage {
431            view_number: 0,
432            sequence_number: 1,
433            prefix: prefix.parse().unwrap(),
434            status: 1,
435            originated_time: 946_684_800,
436            peer_ip: IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
437            peer_asn: Asn::new_16bit(64512),
438            attributes,
439        }
440    }
441
442    #[test]
443    fn test_raw_mrt_record_raw_bytes() {
444        let header = CommonHeader {
445            timestamp: 1609459200,
446            microsecond_timestamp: None,
447            entry_type: EntryType::BGP4MP,
448            entry_subtype: 4,
449            length: 10,
450        };
451        let header_bytes = Bytes::from_static(&[
452            0x5f, 0xee, 0x6a, 0x80, // timestamp
453            0x00, 0x10, // entry type
454            0x00, 0x04, // entry subtype
455            0x00, 0x00, 0x00, 0x0a, // length
456        ]);
457        let message_bytes = Bytes::from_static(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
458
459        let raw_record = RawMrtRecord {
460            common_header: header,
461            header_bytes,
462            message_bytes,
463        };
464
465        let mrt_bytes = raw_record.raw_bytes();
466        // Header is 12 bytes + 10 bytes body = 22 bytes total
467        assert_eq!(mrt_bytes.len(), 22);
468        assert_eq!(raw_record.total_bytes_len(), 22);
469    }
470
471    #[test]
472    fn test_raw_mrt_record_raw_bytes_with_et() {
473        let header = CommonHeader {
474            timestamp: 1609459200,
475            microsecond_timestamp: Some(500000),
476            entry_type: EntryType::BGP4MP_ET,
477            entry_subtype: 4,
478            length: 10,
479        };
480        let header_bytes = Bytes::from_static(&[
481            0x5f, 0xee, 0x6a, 0x80, // timestamp
482            0x00, 0x11, // entry type (BGP4MP_ET = 17)
483            0x00, 0x04, // entry subtype
484            0x00, 0x00, 0x00, 0x0e, // length (10 + 4 for microseconds)
485            0x00, 0x07, 0xa1, 0x20, // microsecond timestamp (500000)
486        ]);
487        let message_bytes = Bytes::from_static(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
488
489        let raw_record = RawMrtRecord {
490            common_header: header,
491            header_bytes,
492            message_bytes,
493        };
494
495        let mrt_bytes = raw_record.raw_bytes();
496        // ET Header is 16 bytes + 10 bytes body = 26 bytes total
497        assert_eq!(mrt_bytes.len(), 26);
498        assert_eq!(raw_record.total_bytes_len(), 26);
499    }
500
501    #[test]
502    fn test_raw_mrt_record_write_to_file() {
503        let dir = tempdir().unwrap();
504        let file_path = dir.path().join("test_record.mrt");
505
506        let header = CommonHeader {
507            timestamp: 1609459200,
508            microsecond_timestamp: None,
509            entry_type: EntryType::BGP4MP,
510            entry_subtype: 4,
511            length: 5,
512        };
513        let header_bytes = Bytes::from_static(&[
514            0x5f, 0xee, 0x6a, 0x80, // timestamp
515            0x00, 0x10, // entry type
516            0x00, 0x04, // entry subtype
517            0x00, 0x00, 0x00, 0x05, // length
518        ]);
519        let message_bytes = Bytes::from_static(&[1, 2, 3, 4, 5]);
520
521        let raw_record = RawMrtRecord {
522            common_header: header,
523            header_bytes,
524            message_bytes,
525        };
526
527        raw_record.write_raw_bytes(&file_path).unwrap();
528
529        let written_bytes = std::fs::read(&file_path).unwrap();
530        assert_eq!(written_bytes.len(), 17); // 12 header + 5 body
531    }
532
533    #[test]
534    fn test_raw_mrt_record_append_to_file() {
535        let dir = tempdir().unwrap();
536        let file_path = dir.path().join("test_records.mrt");
537
538        let header = CommonHeader {
539            timestamp: 1609459200,
540            microsecond_timestamp: None,
541            entry_type: EntryType::BGP4MP,
542            entry_subtype: 4,
543            length: 3,
544        };
545        let header_bytes = Bytes::from_static(&[
546            0x5f, 0xee, 0x6a, 0x80, // timestamp
547            0x00, 0x10, // entry type
548            0x00, 0x04, // entry subtype
549            0x00, 0x00, 0x00, 0x03, // length
550        ]);
551        let message_bytes = Bytes::from_static(&[1, 2, 3]);
552
553        let raw_record = RawMrtRecord {
554            common_header: header,
555            header_bytes,
556            message_bytes,
557        };
558
559        raw_record.append_raw_bytes(&file_path).unwrap();
560        raw_record.append_raw_bytes(&file_path).unwrap();
561
562        let written_bytes = std::fs::read(&file_path).unwrap();
563        assert_eq!(written_bytes.len(), 30); // (12 header + 3 body) * 2
564    }
565
566    #[test]
567    fn test_try_from_bmp_message() {
568        let bmp_message = BmpMessage {
569            common_header: BmpCommonHeader {
570                version: 0,
571                msg_len: 0,
572                msg_type: BmpMsgType::RouteMonitoring,
573            },
574            per_peer_header: Some(BmpPerPeerHeader {
575                peer_asn: Asn::new_32bit(0),
576                peer_ip: IpAddr::from_str("10.0.0.1").unwrap(),
577                peer_bgp_id: Ipv4Addr::from_str("10.0.0.2").unwrap(),
578                timestamp: 0.0,
579                peer_type: BmpPeerType::Global,
580                peer_flags: PerPeerFlags::PeerFlags(PeerFlags::empty()),
581                peer_distinguisher: 0,
582            }),
583            message_body: BmpMessageBody::RouteMonitoring(RouteMonitoring {
584                bgp_message: BgpMessage::KeepAlive,
585            }),
586        };
587
588        let mrt_record = MrtRecord::try_from(&bmp_message).unwrap();
589        assert_eq!(mrt_record.common_header.entry_type, EntryType::BGP4MP_ET);
590    }
591
592    #[test]
593    fn test_try_from_bmp_message_selects_the_add_path_subtype() {
594        // A BMP session cannot say whether ADD-PATH was negotiated, but the
595        // parsed update can: the conversion has to pick the subtype that
596        // matches its route identifiers or the record decodes into garbage.
597        let route = EvpnNlri {
598            path_id: Some(7),
599            route_type: EvpnRouteType::MacIpAdvertisement,
600            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]),
601            payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement {
602                esi: [0; 10],
603                ethernet_tag_id: 0,
604                mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d],
605                ip: None,
606                raw_label: 100,
607                raw_label2: None,
608            }),
609        };
610        let update = BgpUpdateMessage {
611            withdrawn_prefixes: vec![],
612            attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri(
613                Nlri::new_evpn_reachable(
614                    Some(IpAddr::from_str("10.10.0.11").unwrap()),
615                    vec![route],
616                ),
617            )]),
618            announced_prefixes: vec![],
619        };
620        let bmp_message = BmpMessage {
621            common_header: BmpCommonHeader {
622                version: 3,
623                msg_len: 0,
624                msg_type: BmpMsgType::RouteMonitoring,
625            },
626            per_peer_header: Some(BmpPerPeerHeader {
627                peer_asn: Asn::new_32bit(65000),
628                peer_ip: IpAddr::from_str("10.10.0.11").unwrap(),
629                peer_bgp_id: Ipv4Addr::from_str("10.10.0.11").unwrap(),
630                timestamp: 0.0,
631                peer_type: BmpPeerType::Global,
632                peer_flags: PerPeerFlags::PeerFlags(PeerFlags::empty()),
633                peer_distinguisher: 0,
634            }),
635            message_body: BmpMessageBody::RouteMonitoring(RouteMonitoring {
636                bgp_message: BgpMessage::Update(update),
637            }),
638        };
639
640        let record = MrtRecord::try_from(&bmp_message).unwrap();
641        assert_eq!(
642            record.common_header.entry_subtype,
643            Bgp4MpType::MessageAs4Addpath as u16
644        );
645        // And the result survives a round trip through its own encoding.
646        let encoded = record.encode().expect("the converted record encodes");
647        let mut cursor = std::io::Cursor::new(encoded);
648        let reparsed = crate::parse_mrt_record(&mut cursor).expect("the record parses back");
649        assert_eq!(
650            reparsed.common_header.entry_subtype,
651            Bgp4MpType::MessageAs4Addpath as u16
652        );
653    }
654
655    #[test]
656    fn test_parse_mrt_body() {
657        let mut data = BytesMut::new();
658        data.put_u16(0);
659        data.put_u16(0);
660        data.put_u32(0);
661        data.put_u16(0);
662
663        let result = parse_mrt_body(0, 0, data.freeze());
664        assert!(result.is_err());
665    }
666
667    #[test]
668    fn test_mrt_record_encode_updates_header_length() {
669        let record = MrtRecord {
670            common_header: CommonHeader {
671                timestamp: 1609459200,
672                microsecond_timestamp: None,
673                entry_type: EntryType::BGP4MP,
674                entry_subtype: Bgp4MpType::MessageAs4 as u16,
675                length: 0,
676            },
677            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
678                msg_type: Bgp4MpType::MessageAs4,
679                peer_asn: Asn::new_32bit(65000),
680                local_asn: Asn::new_32bit(65001),
681                interface_index: 1,
682                peer_ip: IpAddr::from_str("10.0.0.1").unwrap(),
683                local_ip: IpAddr::from_str("10.0.0.2").unwrap(),
684                bgp_message: BgpMessage::KeepAlive,
685            })),
686        };
687
688        let encoded = record.encode().unwrap();
689        let mut cursor = Cursor::new(encoded);
690        let parsed = parse_mrt_record(&mut cursor).unwrap();
691        let expected_len = parsed
692            .message
693            .encode(parsed.common_header.entry_subtype)
694            .unwrap()
695            .len() as u32;
696
697        assert_eq!(parsed.common_header.length, expected_len);
698    }
699
700    #[test]
701    fn chunk_recovers_four_byte_short_table_dump_and_preserves_alignment() {
702        let body = encode_table_dump_batch(
703            &[
704                table_dump_message("192.0.2.0/24"),
705                table_dump_message("198.51.100.0/24"),
706            ],
707            1,
708        )
709        .unwrap();
710        let header = CommonHeader {
711            timestamp: 946_684_800,
712            microsecond_timestamp: None,
713            entry_type: EntryType::TABLE_DUMP,
714            entry_subtype: 1,
715            length: (body.len() - 4) as u32,
716        };
717        let next_body = Bytes::from_static(&[0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2]);
718        let next_header = CommonHeader {
719            timestamp: 946_684_801,
720            microsecond_timestamp: None,
721            entry_type: EntryType::BGP,
722            entry_subtype: 7,
723            length: next_body.len() as u32,
724        };
725
726        let mut wire = BytesMut::new();
727        wire.put_slice(&header.encode());
728        wire.put_slice(&body);
729        wire.put_slice(&next_header.encode());
730        wire.put_slice(&next_body);
731        let mut cursor = Cursor::new(wire.freeze());
732
733        let first = chunk_mrt_record(&mut cursor).unwrap();
734        assert_eq!(first.message_bytes, body);
735        assert!(matches!(
736            first.parse().unwrap().message,
737            MrtMessage::TableDumpMessageBatch(messages) if messages.len() == 2
738        ));
739        let second = chunk_mrt_record(&mut cursor).unwrap();
740        assert_eq!(second.common_header, next_header);
741        assert!(matches!(
742            second.parse().unwrap().message,
743            MrtMessage::LegacyBgp(LegacyBgp::Message(LegacyBgpMessage {
744                bgp_message: BgpMessage::KeepAlive,
745                ..
746            }))
747        ));
748    }
749
750    #[test]
751    fn chunk_does_not_overread_near_match_table_dump() {
752        let body = encode_table_dump_batch(&[table_dump_message("192.0.2.0/24")], 1).unwrap();
753        let declared_length = body.len() - 3;
754        let header = CommonHeader {
755            timestamp: 946_684_800,
756            microsecond_timestamp: None,
757            entry_type: EntryType::TABLE_DUMP,
758            entry_subtype: 1,
759            length: declared_length as u32,
760        };
761        let mut wire = BytesMut::new();
762        wire.put_slice(&header.encode());
763        wire.put_slice(&body);
764        wire.put_slice(&[0xaa; 12]);
765        let mut cursor = Cursor::new(wire.freeze());
766
767        let raw = chunk_mrt_record(&mut cursor).unwrap();
768        assert_eq!(raw.message_bytes.len(), declared_length);
769        assert_eq!(cursor.position(), (12 + declared_length) as u64);
770        let error = raw.parse().unwrap_err();
771        assert!(matches!(error, ParserError::TruncatedMsg(_)));
772    }
773
774    /// A reader that returns `data` up to `fail_after` bytes and then raises an I/O error.
775    struct FailingReader {
776        data: Vec<u8>,
777        pos: usize,
778        fail_after: usize,
779    }
780
781    impl Read for FailingReader {
782        fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
783            if self.pos >= self.fail_after {
784                return Err(std::io::Error::other("reader exploded"));
785            }
786            let n = (self.fail_after - self.pos)
787                .min(out.len())
788                .min(self.data.len() - self.pos);
789            out[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
790            self.pos += n;
791            Ok(n)
792        }
793    }
794
795    /// Bytes read before a mid-header I/O error must stay in the reported error bytes, including
796    /// the microseconds of an ET header.
797    #[test]
798    fn chunk_errors_keep_partial_extended_timestamp_on_io_error() {
799        let mut wire = BytesMut::new();
800        wire.put_u32(1); // timestamp
801        wire.put_u16(EntryType::BGP4MP_ET as u16);
802        wire.put_u16(4); // subtype
803        wire.put_u32(9); // length, including the 4-byte microsecond field
804        wire.put_u32(230_000); // microseconds
805        let wire = wire.freeze();
806
807        for consumed in [13usize, 14, 15] {
808            let mut reader = FailingReader {
809                data: wire.to_vec(),
810                pos: 0,
811                fail_after: consumed,
812            };
813            let error = chunk_mrt_record(&mut reader).unwrap_err();
814            assert_eq!(
815                error.bytes.as_deref(),
816                Some(&wire[..consumed]),
817                "an I/O error after {consumed} header bytes must report those bytes"
818            );
819        }
820    }
821
822    /// A reader that yields `data` and then reports a clean end of stream.
823    struct ShortReader {
824        data: Vec<u8>,
825        pos: usize,
826    }
827
828    impl Read for ShortReader {
829        fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
830            let n = out.len().min(self.data.len() - self.pos);
831            out[..n].copy_from_slice(&self.data[self.pos..self.pos + n]);
832            self.pos += n;
833            Ok(n)
834        }
835    }
836
837    /// The same partial-header accounting applies when the stream simply ends.
838    #[test]
839    fn chunk_errors_keep_partial_extended_timestamp_on_clean_eof() {
840        let mut wire = BytesMut::new();
841        wire.put_u32(1);
842        wire.put_u16(EntryType::BGP4MP_ET as u16);
843        wire.put_u16(4);
844        wire.put_u32(9);
845        wire.put_u32(230_000);
846        let wire = wire.freeze();
847
848        for consumed in [13usize, 14, 15] {
849            let mut reader = ShortReader {
850                data: wire[..consumed].to_vec(),
851                pos: 0,
852            };
853            let error = chunk_mrt_record(&mut reader).unwrap_err();
854            assert_eq!(
855                error.bytes.as_deref(),
856                Some(&wire[..consumed]),
857                "an end of stream after {consumed} header bytes must report those bytes"
858            );
859        }
860    }
861
862    #[test]
863    fn chunk_errors_include_invalid_header_and_partial_body_bytes() {
864        let invalid_header = Bytes::from_static(&[0, 0, 0, 1, 0xff, 0xff, 0, 0, 0, 0, 0, 0]);
865        let error = chunk_mrt_record(&mut Cursor::new(invalid_header.clone())).unwrap_err();
866        assert_eq!(error.bytes.as_deref(), Some(invalid_header.as_ref()));
867
868        let header = CommonHeader {
869            timestamp: 1,
870            microsecond_timestamp: None,
871            entry_type: EntryType::BGP,
872            entry_subtype: 7,
873            length: 5,
874        };
875        let mut wire = BytesMut::new();
876        wire.put_slice(&header.encode());
877        wire.put_slice(&[1, 2]);
878        let error = chunk_mrt_record(&mut Cursor::new(wire.clone().freeze())).unwrap_err();
879        assert_eq!(error.bytes.as_deref(), Some(wire.as_ref()));
880    }
881
882    /// A record of type 0x7777 whose 20-byte body reads as a plausible common
883    /// header (timestamp 1, type BGP, subtype 7, length 32), so a reader that
884    /// skips only the 12 header bytes would treat the body as the next record.
885    fn unknown_type_record() -> Vec<u8> {
886        let mut wire = BytesMut::new();
887        wire.put_u32(946_684_800);
888        wire.put_u16(0x7777);
889        wire.put_u16(0);
890        wire.put_u32(20);
891        wire.put_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]);
892        wire.put_slice(&[0xaa; 8]);
893        wire.to_vec()
894    }
895
896    fn keepalive_record() -> (CommonHeader, Vec<u8>) {
897        let body = vec![0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2];
898        let header = CommonHeader {
899            timestamp: 946_684_801,
900            microsecond_timestamp: None,
901            entry_type: EntryType::BGP,
902            entry_subtype: 7,
903            length: body.len() as u32,
904        };
905        let mut wire = header.encode().to_vec();
906        wire.extend_from_slice(&body);
907        (header, wire)
908    }
909
910    #[test]
911    fn chunk_skips_body_of_unknown_entry_type() {
912        let unknown = unknown_type_record();
913        let (next_header, next_wire) = keepalive_record();
914        let mut wire = unknown.clone();
915        wire.extend_from_slice(&next_wire);
916        let mut cursor = Cursor::new(wire);
917
918        let error = chunk_mrt_record(&mut cursor).unwrap_err();
919        assert!(
920            matches!(&error.error, ParserError::ParseError(msg) if msg.contains("entry type")),
921            "unexpected error: {}",
922            error.error
923        );
924        assert_eq!(error.bytes.as_deref(), Some(unknown.as_slice()));
925        assert_eq!(cursor.position(), unknown.len() as u64);
926
927        let next = chunk_mrt_record(&mut cursor).unwrap();
928        assert_eq!(next.common_header, next_header);
929        assert!(matches!(
930            next.parse().unwrap().message,
931            MrtMessage::LegacyBgp(LegacyBgp::Message(LegacyBgpMessage {
932                bgp_message: BgpMessage::KeepAlive,
933                ..
934            }))
935        ));
936        assert!(matches!(
937            chunk_mrt_record(&mut cursor).unwrap_err().error,
938            ParserError::EofExpected
939        ));
940    }
941
942    #[test]
943    fn chunk_skips_body_of_et_header_with_short_length() {
944        let mut wire = BytesMut::new();
945        wire.put_u32(1);
946        wire.put_u16(EntryType::BGP4MP_ET as u16);
947        wire.put_u16(4);
948        wire.put_u32(2);
949        wire.put_slice(&[0xaa; 2]);
950        let rejected = wire.to_vec();
951        let (next_header, next_wire) = keepalive_record();
952        wire.put_slice(&next_wire);
953        let mut cursor = Cursor::new(wire.to_vec());
954
955        let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err();
956        assert!(matches!(error.error, ParserError::ParseError(_)));
957        assert!(error.record_consumed);
958        assert_eq!(error.bytes.as_deref(), Some(rejected.as_slice()));
959        assert_eq!(
960            chunk_mrt_record(&mut cursor).unwrap().common_header,
961            next_header
962        );
963    }
964
965    #[test]
966    fn chunk_reports_truncated_body_of_unknown_entry_type() {
967        let unknown = unknown_type_record();
968        let truncated = &unknown[..unknown.len() - 5];
969        let mut cursor = Cursor::new(truncated.to_vec());
970
971        let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err();
972        assert!(matches!(
973            &error.error,
974            ParserError::IoError(io_error) if io_error.kind() == std::io::ErrorKind::UnexpectedEof
975        ));
976        assert!(error.common_header.is_none());
977        assert!(!error.record_consumed);
978        assert_eq!(error.bytes.as_deref(), Some(truncated));
979        assert!(matches!(
980            chunk_mrt_record(&mut cursor).unwrap_err().error,
981            ParserError::EofExpected
982        ));
983    }
984
985    #[test]
986    fn chunk_reports_oversized_length_without_reading_body() {
987        let mut wire = BytesMut::new();
988        wire.put_u32(1);
989        wire.put_u16(EntryType::BGP as u16);
990        wire.put_u16(7);
991        wire.put_u32(MAX_MRT_MESSAGE_LEN + 1);
992        wire.put_slice(&[0xaa; 32]);
993        let mut cursor = Cursor::new(wire.to_vec());
994
995        let error = chunk_mrt_record(&mut cursor).unwrap_err();
996        assert!(matches!(
997            error.error,
998            ParserError::OversizedRecord { length } if length == MAX_MRT_MESSAGE_LEN + 1
999        ));
1000        assert_eq!(error.bytes.as_deref(), Some(&wire[..12]));
1001        assert_eq!(cursor.position(), 12);
1002    }
1003
1004    #[test]
1005    fn chunk_reports_oversized_length_for_unknown_entry_type() {
1006        let mut wire = BytesMut::new();
1007        wire.put_u32(1);
1008        wire.put_u16(0x7777);
1009        wire.put_u16(0);
1010        wire.put_u32(u32::MAX);
1011        wire.put_slice(&[0xaa; 32]);
1012        let mut cursor = Cursor::new(wire.to_vec());
1013
1014        let error = chunk_mrt_record(&mut cursor).unwrap_err();
1015        assert!(matches!(
1016            error.error,
1017            ParserError::OversizedRecord { length: u32::MAX }
1018        ));
1019        assert_eq!(error.bytes.as_deref(), Some(&wire[..12]));
1020        assert_eq!(cursor.position(), 12);
1021    }
1022}