Skip to main content

bgpkit_parser/parser/mrt/
mrt_record.rs

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