Skip to main content

bgpkit_parser/parser/iters/
route.rs

1use crate::error::{ParserError, ParserErrorWithBytes};
2use crate::models::*;
3use crate::parser::bgp::attributes::{parse_as_path, parse_nlri, AttributeValidationState};
4use crate::parser::bgp::messages::read_and_validate_bgp_marker;
5use crate::parser::iters::{handle_record_parse_error, write_mrt_core_dump};
6use crate::parser::mrt::messages::bgp4mp::{bgp4mp_message_payload_len, is_short_zebra_open};
7use crate::parser::mrt::messages::legacy_bgp::{
8    BGP_KEEPALIVE, BGP_NOTIFY, BGP_OPEN, BGP_STATE_CHANGE, BGP_UPDATE,
9};
10use crate::parser::mrt::messages::table_dump_v2::rib_entry_min_len;
11use crate::parser::mrt::mrt_record::raw_record_uses_zebra_compat;
12use crate::parser::{
13    chunk_mrt_record, parse_legacy_bgp, parse_nlri_list, BgpkitParser, Filterable, ReadUtils,
14};
15use bytes::{Buf, Bytes};
16use ipnet::IpNet;
17use log::{error, warn};
18use std::io::Read;
19use std::net::{IpAddr, Ipv4Addr};
20use std::sync::Arc;
21
22#[derive(Default)]
23struct RouteAttributes {
24    as_path: Option<Arc<AsPath>>,
25    announced: Vec<NetworkPrefix>,
26    withdrawn: Vec<NetworkPrefix>,
27}
28
29struct RouteAttributeContext<'a> {
30    afi: Option<Afi>,
31    safi: Option<Safi>,
32    prefixes: Option<&'a [NetworkPrefix]>,
33    is_announcement: Option<bool>,
34    has_standard_nlri: bool,
35}
36
37fn merge_as_path(as_path: Option<AsPath>, as4_path: Option<AsPath>) -> Option<Arc<AsPath>> {
38    let path = match (as_path, as4_path) {
39        (None, None) => None,
40        (Some(path), None) | (None, Some(path)) => Some(path),
41        (Some(path), Some(as4_path)) => Some(AsPath::merge_aspath_as4path(&path, &as4_path)),
42    };
43    path.map(Arc::new)
44}
45
46fn parse_route_attributes(
47    mut data: Bytes,
48    asn_len: &AsnLength,
49    add_path: bool,
50    ctx: RouteAttributeContext<'_>,
51) -> Result<RouteAttributes, ParserError> {
52    let mut validation = AttributeValidationState::new();
53    let mut as_path = None;
54    let mut as4_path = None;
55    let mut announced = Vec::new();
56    let mut withdrawn = Vec::new();
57
58    while data.remaining() >= 3 {
59        let flags = AttrFlags::from_bits_retain(data.read_u8()?);
60        let raw_attr_type = data.read_u8()?;
61        let attr_length = if flags.contains(AttrFlags::EXTENDED) {
62            data.read_u16()? as usize
63        } else {
64            data.read_u8()? as usize
65        };
66        let attr_type = AttrType::from(raw_attr_type);
67        let partial = validation.observe_header(raw_attr_type, attr_type, flags, attr_length);
68
69        if data.remaining() < attr_length {
70            warn!(
71                "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message",
72                attr_type,
73                attr_length,
74                data.remaining()
75            );
76            break;
77        }
78
79        let attr_data = data.split_to(attr_length);
80        let result = match attr_type {
81            AttrType::AS_PATH => parse_as_path(attr_data, asn_len).map(|path| {
82                as_path = Some(path);
83            }),
84            AttrType::AS4_PATH => parse_as_path(attr_data, &AsnLength::Bits32).map(|path| {
85                as4_path = Some(path);
86            }),
87            AttrType::MP_REACHABLE_NLRI => parse_nlri(
88                attr_data,
89                &ctx.afi,
90                &ctx.safi,
91                &ctx.prefixes,
92                true,
93                add_path,
94            )
95            .map(|attr| {
96                if let AttributeValue::MpReachNlri(nlri) = attr {
97                    announced = nlri.prefixes;
98                }
99            }),
100            AttrType::MP_UNREACHABLE_NLRI => parse_nlri(
101                attr_data,
102                &ctx.afi,
103                &ctx.safi,
104                &ctx.prefixes,
105                false,
106                add_path,
107            )
108            .map(|attr| {
109                if let AttributeValue::MpUnreachNlri(nlri) = attr {
110                    withdrawn = nlri.prefixes;
111                }
112            }),
113            _ => Ok(()),
114        };
115
116        if let Err(err) = result {
117            validation.observe_parse_error(attr_type, partial, &err);
118        }
119    }
120
121    let is_announcement = ctx
122        .is_announcement
123        .unwrap_or(ctx.has_standard_nlri || validation.has_attr(AttrType::MP_REACHABLE_NLRI));
124    validation.check_mandatory_attributes(is_announcement, ctx.has_standard_nlri);
125    let _warnings = validation.finish();
126    Ok(RouteAttributes {
127        as_path: merge_as_path(as_path, as4_path),
128        announced,
129        withdrawn,
130    })
131}
132
133fn record_timestamp(common_header: &CommonHeader) -> f64 {
134    match common_header.microsecond_timestamp {
135        Some(microseconds) => common_header.timestamp as f64 + microseconds as f64 / 1_000_000.0,
136        None => common_header.timestamp as f64,
137    }
138}
139
140struct RouteUpdateIter {
141    timestamp: f64,
142    peer_ip: IpAddr,
143    peer_asn: Asn,
144    as_path: Option<Arc<AsPath>>,
145    announced:
146        std::iter::Chain<std::vec::IntoIter<NetworkPrefix>, std::vec::IntoIter<NetworkPrefix>>,
147    withdrawn:
148        std::iter::Chain<std::vec::IntoIter<NetworkPrefix>, std::vec::IntoIter<NetworkPrefix>>,
149    in_withdrawn_phase: bool,
150}
151
152impl RouteUpdateIter {
153    fn next_route(&mut self) -> Option<BgpRouteElem> {
154        if !self.in_withdrawn_phase {
155            if let Some(prefix) = self.announced.next() {
156                return Some(BgpRouteElem {
157                    timestamp: self.timestamp,
158                    elem_type: ElemType::ANNOUNCE,
159                    peer_ip: self.peer_ip,
160                    peer_asn: self.peer_asn,
161                    prefix,
162                    as_path: self.as_path.clone(),
163                });
164            }
165            self.in_withdrawn_phase = true;
166        }
167
168        self.withdrawn.next().map(|prefix| BgpRouteElem {
169            timestamp: self.timestamp,
170            elem_type: ElemType::WITHDRAW,
171            peer_ip: self.peer_ip,
172            peer_asn: self.peer_asn,
173            prefix,
174            as_path: None,
175        })
176    }
177}
178
179#[derive(Clone, Default)]
180struct RoutePeerTable {
181    peers: Arc<[Peer]>,
182}
183
184impl RoutePeerTable {
185    fn get_peer_by_id(&self, peer_index: u16) -> Option<Peer> {
186        self.peers.get(peer_index as usize).copied()
187    }
188}
189
190fn parse_route_peer_table(mut data: Bytes) -> Result<RoutePeerTable, ParserError> {
191    let _collector_bgp_id = data.read_u32()?;
192    let view_name_length = data.read_u16()? as usize;
193    data.has_n_remaining(view_name_length)?;
194    data.advance(view_name_length);
195
196    let peer_count = data.read_u16()? as usize;
197    let mut peers = Vec::with_capacity(peer_count);
198    for _ in 0..peer_count {
199        let peer_type = PeerType::from_bits_retain(data.read_u8()?);
200        let afi = if peer_type.contains(PeerType::ADDRESS_FAMILY_IPV6) {
201            Afi::Ipv6
202        } else {
203            Afi::Ipv4
204        };
205        let asn_len = if peer_type.contains(PeerType::AS_SIZE_32BIT) {
206            AsnLength::Bits32
207        } else {
208            AsnLength::Bits16
209        };
210
211        let peer_bgp_id = data.read_ipv4_address()?;
212        let peer_ip = data.read_address(&afi)?;
213        let peer_asn = data.read_asn(asn_len)?;
214        peers.push(Peer {
215            peer_type,
216            peer_bgp_id,
217            peer_ip,
218            peer_asn,
219        });
220    }
221
222    Ok(RoutePeerTable {
223        peers: Arc::from(peers),
224    })
225}
226
227#[derive(Default)]
228enum RouteRecordIter {
229    #[default]
230    Empty,
231    Update(RouteUpdateIter),
232    TableDump(RouteTableDumpIter),
233    RibAfi(RouteRibAfiIter),
234}
235
236impl RouteRecordIter {
237    fn next_route(&mut self) -> Result<Option<BgpRouteElem>, ParserError> {
238        match self {
239            RouteRecordIter::Empty => Ok(None),
240            RouteRecordIter::Update(iter) => Ok(iter.next_route()),
241            RouteRecordIter::TableDump(iter) => iter.next_route(),
242            RouteRecordIter::RibAfi(iter) => iter.next_route(),
243        }
244    }
245}
246
247struct RouteTableDumpIter {
248    data: Bytes,
249    afi: Afi,
250}
251
252impl RouteTableDumpIter {
253    fn next_route(&mut self) -> Result<Option<BgpRouteElem>, ParserError> {
254        if self.data.is_empty() {
255            return Ok(None);
256        }
257
258        let prefix = match self.afi {
259            Afi::Ipv4 => self.data.read_ipv4_prefix().map(IpNet::V4),
260            Afi::Ipv6 => self.data.read_ipv6_prefix().map(IpNet::V6),
261            // `parse_table_dump_routes` only builds this iterator for subtypes 1 and 2
262            Afi::LinkState | Afi::L2vpn => {
263                unreachable!("table dumps carry IPv4 or IPv6 prefixes only")
264            }
265        }?;
266        let _status = self.data.read_u8()?;
267        let originated_time = self.data.read_u32()? as f64;
268        let peer_ip = self.data.read_address(&self.afi)?;
269        let peer_asn = Asn::new_16bit(self.data.read_u16()?);
270        let attribute_length = self.data.read_u16()? as usize;
271        self.data.has_n_remaining(attribute_length)?;
272        let attrs = parse_route_attributes(
273            self.data.split_to(attribute_length),
274            &AsnLength::Bits16,
275            false,
276            RouteAttributeContext {
277                afi: None,
278                safi: None,
279                prefixes: None,
280                is_announcement: Some(true),
281                has_standard_nlri: self.afi == Afi::Ipv4,
282            },
283        )?;
284
285        Ok(Some(BgpRouteElem {
286            timestamp: originated_time,
287            elem_type: ElemType::ANNOUNCE,
288            peer_ip,
289            peer_asn,
290            prefix: NetworkPrefix::new(prefix, None),
291            as_path: attrs.as_path,
292        }))
293    }
294}
295
296struct RouteRibAfiIter {
297    data: Bytes,
298    peer_table: RoutePeerTable,
299    afi: Afi,
300    safi: Safi,
301    is_add_path: bool,
302    prefix: NetworkPrefix,
303    remaining_entries: u16,
304}
305
306impl RouteRibAfiIter {
307    fn next_route(&mut self) -> Result<Option<BgpRouteElem>, ParserError> {
308        while self.remaining_entries > 0 {
309            if self.data.remaining() < rib_entry_min_len(self.is_add_path) {
310                warn!("early break due to truncated msg while parsing RIB AFI entries");
311                self.remaining_entries = 0;
312                return Ok(None);
313            }
314
315            self.remaining_entries -= 1;
316            let peer_index = self.data.read_u16()?;
317            let originated_time = self.data.read_u32()? as f64;
318            let _path_id = if self.is_add_path {
319                Some(self.data.read_u32()?)
320            } else {
321                None
322            };
323            let attribute_length = self.data.read_u16()? as usize;
324            if self.data.remaining() < attribute_length {
325                warn!(
326                    "early break due to truncated attribute payload while parsing RIB AFI entries: expected {} bytes, have {} bytes available",
327                    attribute_length,
328                    self.data.remaining()
329                );
330                self.remaining_entries = 0;
331                return Ok(None);
332            }
333
334            let prefixes = [self.prefix];
335            let attrs = parse_route_attributes(
336                self.data.split_to(attribute_length),
337                &AsnLength::Bits32,
338                self.is_add_path,
339                RouteAttributeContext {
340                    afi: Some(self.afi),
341                    safi: Some(self.safi),
342                    prefixes: Some(&prefixes),
343                    is_announcement: Some(true),
344                    has_standard_nlri: self.afi == Afi::Ipv4,
345                },
346            )?;
347            let Some(peer) = self.peer_table.get_peer_by_id(peer_index) else {
348                error!("peer ID {} not found in peer_index table", peer_index);
349                continue;
350            };
351
352            return Ok(Some(BgpRouteElem {
353                timestamp: originated_time,
354                elem_type: ElemType::ANNOUNCE,
355                peer_ip: peer.peer_ip,
356                peer_asn: peer.peer_asn,
357                prefix: self.prefix,
358                as_path: attrs.as_path,
359            }));
360        }
361
362        Ok(None)
363    }
364}
365
366fn parse_bgp_update_routes(
367    mut input: Bytes,
368    add_path: bool,
369    asn_len: &AsnLength,
370    timestamp: f64,
371    peer_ip: IpAddr,
372    peer_asn: Asn,
373) -> Result<RouteUpdateIter, ParserError> {
374    let withdrawn_len = input.read_u16()? as usize;
375    input.has_n_remaining(withdrawn_len)?;
376    let withdrawn_prefixes = parse_nlri_list(input.split_to(withdrawn_len), add_path, &Afi::Ipv4)?;
377
378    let attribute_length = input.read_u16()? as usize;
379    input.has_n_remaining(attribute_length)?;
380    let attribute_bytes = input.split_to(attribute_length);
381    let announced_prefixes = parse_nlri_list(input, add_path, &Afi::Ipv4)?;
382    let attributes = parse_route_attributes(
383        attribute_bytes,
384        asn_len,
385        add_path,
386        RouteAttributeContext {
387            afi: None,
388            safi: None,
389            prefixes: None,
390            is_announcement: None,
391            has_standard_nlri: !announced_prefixes.is_empty(),
392        },
393    )?;
394
395    Ok(RouteUpdateIter {
396        timestamp,
397        peer_ip,
398        peer_asn,
399        as_path: attributes.as_path,
400        announced: announced_prefixes.into_iter().chain(attributes.announced),
401        withdrawn: withdrawn_prefixes.into_iter().chain(attributes.withdrawn),
402        in_withdrawn_phase: false,
403    })
404}
405
406fn parse_bgp_message_routes(
407    mut data: Bytes,
408    add_path: bool,
409    asn_len: &AsnLength,
410    timestamp: f64,
411    peer_ip: IpAddr,
412    peer_asn: Asn,
413) -> Result<RouteRecordIter, ParserError> {
414    let total_size = data.len();
415    data.has_n_remaining(19)?;
416    read_and_validate_bgp_marker(&mut data)?;
417    let length = data.read_u16()?;
418    if !(19..=65_535).contains(&length) {
419        return Err(ParserError::ParseError(format!(
420            "invalid BGP message length {length}"
421        )));
422    }
423
424    let bgp_msg_length = if length as usize > total_size {
425        total_size - 19
426    } else {
427        length as usize - 19
428    };
429    let msg_type = BgpMessageType::try_from(data.read_u8()?)
430        .map_err(|_| ParserError::ParseError("Unknown BGP Message Type".to_string()))?;
431
432    if matches!(msg_type, BgpMessageType::OPEN | BgpMessageType::KEEPALIVE) && length > 4096 {
433        return Err(ParserError::ParseError(format!(
434            "BGP {msg_type:?} message length {length} exceeds maximum allowed 4096 bytes (RFC 8654)"
435        )));
436    }
437
438    if data.remaining() != bgp_msg_length {
439        warn!(
440            "BGP message length {} does not match the actual length {} (parsing BGP message)",
441            bgp_msg_length,
442            data.remaining()
443        );
444    }
445    data.has_n_remaining(bgp_msg_length)?;
446    let msg_data = data.split_to(bgp_msg_length);
447
448    match msg_type {
449        BgpMessageType::UPDATE => Ok(RouteRecordIter::Update(parse_bgp_update_routes(
450            msg_data, add_path, asn_len, timestamp, peer_ip, peer_asn,
451        )?)),
452        BgpMessageType::OPEN
453        | BgpMessageType::NOTIFICATION
454        | BgpMessageType::KEEPALIVE
455        | BgpMessageType::ROUTE_REFRESH => Ok(RouteRecordIter::Empty),
456    }
457}
458
459fn bgp4mp_asn_len_and_add_path(msg_type: Bgp4MpType) -> Option<(AsnLength, bool)> {
460    match msg_type {
461        Bgp4MpType::Message | Bgp4MpType::MessageLocal => Some((AsnLength::Bits16, false)),
462        Bgp4MpType::MessageAs4 | Bgp4MpType::MessageAs4Local => Some((AsnLength::Bits32, false)),
463        Bgp4MpType::MessageAddpath | Bgp4MpType::MessageLocalAddpath => {
464            Some((AsnLength::Bits16, true))
465        }
466        Bgp4MpType::MessageAs4Addpath | Bgp4MpType::MessageLocalAs4Addpath => {
467            Some((AsnLength::Bits32, true))
468        }
469        Bgp4MpType::StateChange | Bgp4MpType::StateChangeAs4 => None,
470    }
471}
472
473fn parse_bgp4mp_routes(
474    sub_type: u16,
475    mut data: Bytes,
476    timestamp: f64,
477) -> Result<RouteRecordIter, ParserError> {
478    let msg_type = Bgp4MpType::try_from(sub_type)?;
479    let Some((asn_len, add_path)) = bgp4mp_asn_len_and_add_path(msg_type) else {
480        return Ok(RouteRecordIter::Empty);
481    };
482
483    let total_size = data.len();
484    let is_short_zebra_open = is_short_zebra_open(&data, &asn_len);
485    let peer_asn = data.read_asn(asn_len)?;
486    let _local_asn = data.read_asn(asn_len)?;
487    if is_short_zebra_open {
488        return parse_bgp_message_routes(
489            data,
490            add_path,
491            &asn_len,
492            timestamp,
493            IpAddr::V4(Ipv4Addr::UNSPECIFIED),
494            peer_asn,
495        );
496    }
497    let _interface_index = data.read_u16()?;
498    let afi = data.read_afi()?;
499    let should_read = bgp4mp_message_payload_len(&afi, &asn_len, total_size)?;
500    let peer_ip = data.read_address(&afi)?;
501    let _local_ip = data.read_address(&afi)?;
502
503    if should_read != data.remaining() {
504        return Err(ParserError::TruncatedMsg(format!(
505            "truncated bgp4mp message: should read {} bytes, have {} bytes available",
506            should_read,
507            data.remaining()
508        )));
509    }
510
511    parse_bgp_message_routes(data, add_path, &asn_len, timestamp, peer_ip, peer_asn)
512}
513
514fn table_dump_v2_afi_safi(rib_type: TableDumpV2Type) -> Result<(Afi, Safi), ParserError> {
515    match rib_type {
516        TableDumpV2Type::RibIpv4Unicast | TableDumpV2Type::RibIpv4UnicastAddPath => {
517            Ok((Afi::Ipv4, Safi::Unicast))
518        }
519        TableDumpV2Type::RibIpv4Multicast | TableDumpV2Type::RibIpv4MulticastAddPath => {
520            Ok((Afi::Ipv4, Safi::Multicast))
521        }
522        TableDumpV2Type::RibIpv6Unicast | TableDumpV2Type::RibIpv6UnicastAddPath => {
523            Ok((Afi::Ipv6, Safi::Unicast))
524        }
525        TableDumpV2Type::RibIpv6Multicast | TableDumpV2Type::RibIpv6MulticastAddPath => {
526            Ok((Afi::Ipv6, Safi::Multicast))
527        }
528        _ => Err(ParserError::ParseError(format!(
529            "wrong RIB type for parsing: {rib_type:?}"
530        ))),
531    }
532}
533
534fn is_add_path_rib_type(rib_type: TableDumpV2Type) -> bool {
535    matches!(
536        rib_type,
537        TableDumpV2Type::RibIpv4UnicastAddPath
538            | TableDumpV2Type::RibIpv4MulticastAddPath
539            | TableDumpV2Type::RibIpv6UnicastAddPath
540            | TableDumpV2Type::RibIpv6MulticastAddPath
541    )
542}
543
544fn parse_table_dump_routes(sub_type: u16, mut data: Bytes) -> Result<RouteRecordIter, ParserError> {
545    let afi = match sub_type {
546        1 => Afi::Ipv4,
547        2 => Afi::Ipv6,
548        _ => {
549            return Err(ParserError::ParseError(format!(
550                "Invalid subtype found for TABLE_DUMP (V1) message: {sub_type}"
551            )))
552        }
553    };
554
555    let _view_number = data.read_u16()?;
556    let _sequence_number = data.read_u16()?;
557    if data.is_empty() {
558        return Err(ParserError::TruncatedMsg(
559            "TABLE_DUMP record contains no entries".to_string(),
560        ));
561    }
562    Ok(RouteRecordIter::TableDump(RouteTableDumpIter { data, afi }))
563}
564
565fn parse_legacy_bgp_routes(
566    sub_type: u16,
567    mut data: Bytes,
568    timestamp: f64,
569) -> Result<RouteRecordIter, ParserError> {
570    match sub_type {
571        BGP_UPDATE => {
572            let peer_asn = Asn::new_16bit(data.read_u16()?);
573            let peer_ip = IpAddr::V4(data.read_ipv4_address()?);
574            let _local_asn = data.read_u16()?;
575            let _local_ip = data.read_ipv4_address()?;
576            Ok(RouteRecordIter::Update(parse_bgp_update_routes(
577                data,
578                false,
579                &AsnLength::Bits16,
580                timestamp,
581                peer_ip,
582                peer_asn,
583            )?))
584        }
585        BGP_STATE_CHANGE | BGP_OPEN | BGP_NOTIFY | BGP_KEEPALIVE => {
586            parse_legacy_bgp(sub_type, data)?;
587            Ok(RouteRecordIter::Empty)
588        }
589        _ => Err(ParserError::Unsupported(format!(
590            "unsupported legacy BGP subtype: {sub_type}"
591        ))),
592    }
593}
594
595fn parse_table_dump_v2_routes(
596    sub_type: u16,
597    mut data: Bytes,
598    peer_table: &mut Option<RoutePeerTable>,
599) -> Result<RouteRecordIter, ParserError> {
600    let v2_type = TableDumpV2Type::try_from(sub_type)?;
601    match v2_type {
602        TableDumpV2Type::PeerIndexTable => {
603            *peer_table = Some(parse_route_peer_table(data)?);
604            Ok(RouteRecordIter::Empty)
605        }
606        TableDumpV2Type::GeoPeerTable => Ok(RouteRecordIter::Empty),
607        TableDumpV2Type::RibGeneric | TableDumpV2Type::RibGenericAddPath => Err(
608            ParserError::Unsupported("TableDumpV2 RibGeneric is not currently supported".into()),
609        ),
610        rib_type => {
611            let (afi, safi) = table_dump_v2_afi_safi(rib_type)?;
612            let is_add_path = is_add_path_rib_type(rib_type);
613            let _sequence_number = data.read_u32()?;
614            let prefix = data.read_nlri_prefix(&afi, false)?;
615            let entry_count = data.read_u16()?;
616            let Some(peer_table) = peer_table.clone() else {
617                return Err(ParserError::ParseError(
618                    "peer table not set for TableDumpV2 RIB entries".to_string(),
619                ));
620            };
621
622            Ok(RouteRecordIter::RibAfi(RouteRibAfiIter {
623                data,
624                peer_table,
625                afi,
626                safi,
627                is_add_path,
628                prefix,
629                remaining_entries: entry_count,
630            }))
631        }
632    }
633}
634
635fn parse_raw_record_route_iter(
636    raw_record: crate::RawMrtRecord,
637    peer_table: &mut Option<RoutePeerTable>,
638) -> Result<RouteRecordIter, ParserError> {
639    let timestamp = record_timestamp(&raw_record.common_header);
640    match raw_record.common_header.entry_type {
641        EntryType::TABLE_DUMP => parse_table_dump_routes(
642            raw_record.common_header.entry_subtype,
643            raw_record.message_bytes,
644        ),
645        EntryType::TABLE_DUMP_V2 => parse_table_dump_v2_routes(
646            raw_record.common_header.entry_subtype,
647            raw_record.message_bytes,
648            peer_table,
649        ),
650        EntryType::BGP4MP | EntryType::BGP4MP_ET => parse_bgp4mp_routes(
651            raw_record.common_header.entry_subtype,
652            raw_record.message_bytes,
653            timestamp,
654        ),
655        EntryType::BGP => parse_legacy_bgp_routes(
656            raw_record.common_header.entry_subtype,
657            raw_record.message_bytes,
658            timestamp,
659        ),
660        v => Err(ParserError::Unsupported(format!(
661            "unsupported MRT type: {v:?}"
662        ))),
663    }
664}
665
666pub struct RouteIterator<R> {
667    parser: BgpkitParser<R>,
668    pending_routes: RouteRecordIter,
669    peer_table: Option<RoutePeerTable>,
670    pending_raw_bytes: Option<Vec<u8>>,
671}
672
673impl<R> RouteIterator<R> {
674    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
675        Self {
676            parser,
677            pending_routes: RouteRecordIter::Empty,
678            peer_table: None,
679            pending_raw_bytes: None,
680        }
681    }
682}
683
684/// Log an error from parsing a record body into routes. Only a `ParseError` goes through the
685/// once-per-parser limiter, as in the other iterators, so that another error class cannot use up
686/// the one `error`-level parse error line.
687fn log_route_body_error<R>(parser: &mut BgpkitParser<R>, err: &ParserError) {
688    match err {
689        ParserError::ParseError(err_str) => parser.log_parse_error_once(err_str),
690        other => error!("parser error: {}", other),
691    }
692}
693
694impl<R: Read> Iterator for RouteIterator<R> {
695    type Item = BgpRouteElem;
696
697    fn next(&mut self) -> Option<Self::Item> {
698        // Text-dump parsers have no MRT-record representation; short-circuit.
699        if self.parser.text_dump_iter.is_some() {
700            return None;
701        }
702        loop {
703            match self.pending_routes.next_route() {
704                Ok(Some(route)) => {
705                    if route.match_filters(&self.parser.filters) {
706                        return Some(route);
707                    }
708                    continue;
709                }
710                Ok(None) => {
711                    self.pending_raw_bytes = None;
712                }
713                Err(err) => {
714                    log_route_body_error(&mut self.parser, &err);
715                    self.pending_routes = RouteRecordIter::Empty;
716                    write_mrt_core_dump(self.parser.core_dump, self.pending_raw_bytes.take());
717                    if self.parser.core_dump {
718                        return None;
719                    }
720                    continue;
721                }
722            }
723
724            let raw_record = match chunk_mrt_record(&mut self.parser.reader) {
725                Ok(raw_record) => raw_record,
726                Err(e) => {
727                    if !handle_record_parse_error(&mut self.parser, e.error, e.bytes) {
728                        return None;
729                    }
730                    continue;
731                }
732            };
733
734            let used_zebra_compat = raw_record_uses_zebra_compat(&raw_record);
735            let raw_bytes = raw_record.raw_bytes().to_vec();
736            match parse_raw_record_route_iter(raw_record, &mut self.peer_table) {
737                Ok(routes) => {
738                    if used_zebra_compat {
739                        self.parser.warn_zebra_compat_once();
740                    }
741                    self.pending_routes = routes;
742                    self.pending_raw_bytes = Some(raw_bytes);
743                }
744                Err(err) => {
745                    log_route_body_error(&mut self.parser, &err);
746                    write_mrt_core_dump(self.parser.core_dump, Some(raw_bytes));
747                    if self.parser.core_dump {
748                        return None;
749                    }
750                    continue;
751                }
752            }
753        }
754    }
755}
756
757pub struct FallibleRouteIterator<R> {
758    parser: BgpkitParser<R>,
759    pending_routes: RouteRecordIter,
760    peer_table: Option<RoutePeerTable>,
761    pending_raw_bytes: Option<Vec<u8>>,
762    finished: bool,
763}
764
765impl<R> FallibleRouteIterator<R> {
766    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
767        Self {
768            parser,
769            pending_routes: RouteRecordIter::Empty,
770            peer_table: None,
771            pending_raw_bytes: None,
772            finished: false,
773        }
774    }
775}
776
777impl<R: Read> Iterator for FallibleRouteIterator<R> {
778    type Item = Result<BgpRouteElem, ParserErrorWithBytes>;
779
780    fn next(&mut self) -> Option<Self::Item> {
781        // Text-dump parsers have no MRT-record representation; short-circuit.
782        if self.parser.text_dump_iter.is_some() {
783            return None;
784        }
785        loop {
786            match self.pending_routes.next_route() {
787                Ok(Some(route)) => {
788                    if route.match_filters(&self.parser.filters) {
789                        return Some(Ok(route));
790                    }
791                    continue;
792                }
793                Ok(None) => {
794                    self.pending_raw_bytes = None;
795                }
796                Err(error) => {
797                    self.pending_routes = RouteRecordIter::Empty;
798                    return Some(Err(ParserErrorWithBytes {
799                        error,
800                        bytes: self.pending_raw_bytes.take(),
801                    }));
802                }
803            }
804
805            let raw_record =
806                match super::next_fallible_raw_record(&mut self.parser.reader, &mut self.finished)?
807                {
808                    Ok(raw_record) => raw_record,
809                    Err(e) => return Some(Err(e)),
810                };
811
812            let used_zebra_compat = raw_record_uses_zebra_compat(&raw_record);
813            let raw_bytes = raw_record.raw_bytes().to_vec();
814            match parse_raw_record_route_iter(raw_record, &mut self.peer_table) {
815                Ok(routes) => {
816                    if used_zebra_compat {
817                        self.parser.warn_zebra_compat_once();
818                    }
819                    self.pending_routes = routes;
820                    self.pending_raw_bytes = Some(raw_bytes);
821                }
822                Err(error) => {
823                    return Some(Err(ParserErrorWithBytes {
824                        error,
825                        bytes: Some(raw_bytes),
826                    }))
827                }
828            }
829        }
830    }
831}
832
833#[cfg(test)]
834mod tests {
835    use super::*;
836    use crate::parser::iters::write_mrt_core_dump_to_path;
837    use bytes::{BufMut, BytesMut};
838    use std::io::Cursor;
839    use std::net::{Ipv4Addr, Ipv6Addr};
840    use std::str::FromStr;
841
842    fn route_projection(elem: BgpElem) -> BgpRouteElem {
843        BgpRouteElem {
844            timestamp: elem.timestamp,
845            elem_type: elem.elem_type,
846            peer_ip: elem.peer_ip,
847            peer_asn: elem.peer_asn,
848            prefix: elem.prefix,
849            as_path: elem.as_path.map(Arc::new),
850        }
851    }
852
853    fn collect_route_record_iter(
854        mut iter: RouteRecordIter,
855    ) -> Result<Vec<BgpRouteElem>, ParserError> {
856        let mut routes = Vec::new();
857        while let Some(route) = iter.next_route()? {
858            routes.push(route);
859        }
860        Ok(routes)
861    }
862
863    fn route_peer_table_from_peer_index(peer_table: PeerIndexTable) -> RoutePeerTable {
864        let mut peer_ids = peer_table.id_peer_map.keys().copied().collect::<Vec<_>>();
865        peer_ids.sort_unstable();
866        let peers = peer_ids
867            .into_iter()
868            .map(|peer_id| peer_table.id_peer_map[&peer_id])
869            .collect::<Vec<_>>();
870
871        RoutePeerTable {
872            peers: Arc::from(peers),
873        }
874    }
875
876    fn update_record() -> MrtRecord {
877        let mut attributes = Attributes::default();
878        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
879        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([64500, 64501])).into());
880        attributes
881            .add_attr(AttributeValue::NextHop(IpAddr::from_str("192.0.2.254").unwrap()).into());
882
883        MrtRecord {
884            common_header: CommonHeader {
885                timestamp: 1_700_000_000,
886                microsecond_timestamp: None,
887                entry_type: EntryType::BGP4MP,
888                entry_subtype: Bgp4MpType::MessageAs4 as u16,
889                length: 0,
890            },
891            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
892                msg_type: Bgp4MpType::MessageAs4,
893                peer_asn: Asn::new_32bit(64496),
894                local_asn: Asn::new_32bit(64497),
895                interface_index: 0,
896                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
897                local_ip: IpAddr::from_str("192.0.2.2").unwrap(),
898                bgp_message: BgpMessage::Update(BgpUpdateMessage {
899                    withdrawn_prefixes: vec![NetworkPrefix::from_str("198.51.100.0/24").unwrap()],
900                    attributes,
901                    announced_prefixes: vec![NetworkPrefix::from_str("203.0.113.0/24").unwrap()],
902                }),
903            })),
904        }
905    }
906
907    fn route_attributes(as_path: impl AsRef<[u32]>) -> Attributes {
908        let mut attributes = Attributes::default();
909        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
910        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence(as_path)).into());
911        attributes
912            .add_attr(AttributeValue::NextHop(IpAddr::from_str("192.0.2.254").unwrap()).into());
913        attributes
914    }
915
916    fn bgp4mp_record(msg_type: Bgp4MpType, bgp_message: BgpMessage) -> MrtRecord {
917        let asn = if matches!(
918            msg_type,
919            Bgp4MpType::Message
920                | Bgp4MpType::MessageLocal
921                | Bgp4MpType::MessageAddpath
922                | Bgp4MpType::MessageLocalAddpath
923        ) {
924            Asn::new_16bit(64496)
925        } else {
926            Asn::new_32bit(64496)
927        };
928
929        MrtRecord {
930            common_header: CommonHeader {
931                timestamp: 1_700_000_000,
932                microsecond_timestamp: None,
933                entry_type: EntryType::BGP4MP,
934                entry_subtype: msg_type as u16,
935                length: 0,
936            },
937            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
938                msg_type,
939                peer_asn: asn,
940                local_asn: Asn::new_32bit(64497),
941                interface_index: 0,
942                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
943                local_ip: IpAddr::from_str("192.0.2.2").unwrap(),
944                bgp_message,
945            })),
946        }
947    }
948
949    fn open_message() -> BgpMessage {
950        BgpMessage::Open(BgpOpenMessage {
951            version: 4,
952            asn: Asn::new_16bit(64496),
953            hold_time: 180,
954            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
955            extended_length: false,
956            opt_params: vec![],
957        })
958    }
959
960    fn raw_bgp_message(length: u16, msg_type: BgpMessageType, payload: &[u8]) -> Bytes {
961        raw_bgp_message_with_marker([0xff; 16], length, msg_type, payload)
962    }
963
964    fn raw_bgp_message_with_marker(
965        marker: [u8; 16],
966        length: u16,
967        msg_type: BgpMessageType,
968        payload: &[u8],
969    ) -> Bytes {
970        let mut bytes = BytesMut::new();
971        bytes.put_slice(&marker);
972        bytes.put_u16(length);
973        bytes.put_u8(msg_type as u8);
974        bytes.put_slice(payload);
975        bytes.freeze()
976    }
977
978    fn table_dump_record() -> MrtRecord {
979        let mut attributes = Attributes::default();
980        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
981        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([64500, 64501])).into());
982        attributes
983            .add_attr(AttributeValue::NextHop(IpAddr::from_str("192.0.2.254").unwrap()).into());
984
985        MrtRecord {
986            common_header: CommonHeader {
987                timestamp: 1_700_000_000,
988                microsecond_timestamp: None,
989                entry_type: EntryType::TABLE_DUMP,
990                entry_subtype: 1,
991                length: 0,
992            },
993            message: MrtMessage::TableDumpMessage(TableDumpMessage {
994                view_number: 0,
995                sequence_number: 1,
996                prefix: NetworkPrefix::from_str("203.0.113.0/24").unwrap(),
997                status: 1,
998                originated_time: 1_699_999_998,
999                peer_ip: IpAddr::from_str("192.0.2.20").unwrap(),
1000                peer_asn: Asn::new_16bit(64496),
1001                attributes,
1002            }),
1003        }
1004    }
1005
1006    fn table_dump_ipv6_record() -> MrtRecord {
1007        let mut attributes = Attributes::default();
1008        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
1009        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([64500, 64501])).into());
1010
1011        MrtRecord {
1012            common_header: CommonHeader {
1013                timestamp: 1_700_000_000,
1014                microsecond_timestamp: None,
1015                entry_type: EntryType::TABLE_DUMP,
1016                entry_subtype: 2,
1017                length: 0,
1018            },
1019            message: MrtMessage::TableDumpMessage(TableDumpMessage {
1020                view_number: 0,
1021                sequence_number: 1,
1022                prefix: NetworkPrefix::from_str("2001:db8::/32").unwrap(),
1023                status: 1,
1024                originated_time: 1_699_999_998,
1025                peer_ip: IpAddr::from_str("2001:db8::20").unwrap(),
1026                peer_asn: Asn::new_16bit(64496),
1027                attributes,
1028            }),
1029        }
1030    }
1031
1032    fn table_dump_v2_records_bytes() -> Vec<u8> {
1033        let peer = Peer::new(
1034            "192.0.2.10".parse().unwrap(),
1035            "192.0.2.11".parse().unwrap(),
1036            Asn::new_32bit(64496),
1037        );
1038        let mut peer_table = PeerIndexTable::default();
1039        let peer_index = peer_table.add_peer(peer).unwrap();
1040
1041        let mut attributes = Attributes::default();
1042        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
1043        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([64500, 64501])).into());
1044        attributes
1045            .add_attr(AttributeValue::NextHop(IpAddr::from_str("192.0.2.254").unwrap()).into());
1046
1047        let pit_record = MrtRecord {
1048            common_header: CommonHeader {
1049                timestamp: 1_700_000_000,
1050                microsecond_timestamp: None,
1051                entry_type: EntryType::TABLE_DUMP_V2,
1052                entry_subtype: TableDumpV2Type::PeerIndexTable as u16,
1053                length: 0,
1054            },
1055            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(peer_table)),
1056        };
1057        let rib_record = MrtRecord {
1058            common_header: CommonHeader {
1059                timestamp: 1_700_000_001,
1060                microsecond_timestamp: None,
1061                entry_type: EntryType::TABLE_DUMP_V2,
1062                entry_subtype: TableDumpV2Type::RibIpv4Unicast as u16,
1063                length: 0,
1064            },
1065            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
1066                rib_type: TableDumpV2Type::RibIpv4Unicast,
1067                sequence_number: 1,
1068                prefix: NetworkPrefix::from_str("203.0.113.0/24").unwrap(),
1069                rib_entries: vec![RibEntry {
1070                    peer_index,
1071                    originated_time: 1_699_999_999,
1072                    path_id: None,
1073                    attributes,
1074                }],
1075            })),
1076        };
1077
1078        let mut bytes = pit_record.encode().unwrap().to_vec();
1079        bytes.extend_from_slice(&rib_record.encode().unwrap());
1080        bytes
1081    }
1082
1083    fn table_dump_v2_truncated_attribute_payload() -> (Vec<u8>, Bytes, PeerIndexTable) {
1084        let peer = Peer::new(
1085            "192.0.2.10".parse().unwrap(),
1086            "192.0.2.11".parse().unwrap(),
1087            Asn::new_32bit(64496),
1088        );
1089        let mut peer_table = PeerIndexTable::default();
1090        let peer_index = peer_table.add_peer(peer).unwrap();
1091
1092        let pit_record = MrtRecord {
1093            common_header: CommonHeader {
1094                timestamp: 1_700_000_000,
1095                microsecond_timestamp: None,
1096                entry_type: EntryType::TABLE_DUMP_V2,
1097                entry_subtype: TableDumpV2Type::PeerIndexTable as u16,
1098                length: 0,
1099            },
1100            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(
1101                peer_table.clone(),
1102            )),
1103        };
1104
1105        let first_entry = RibEntry {
1106            peer_index,
1107            originated_time: 1_699_999_999,
1108            path_id: None,
1109            attributes: route_attributes([64500, 64501]),
1110        };
1111
1112        let mut rib_body = BytesMut::new();
1113        rib_body.put_u32(1);
1114        rib_body.extend(NetworkPrefix::from_str("203.0.113.0/24").unwrap().encode());
1115        rib_body.put_u16(2);
1116        rib_body.extend(first_entry.encode().unwrap());
1117        rib_body.put_u16(peer_index);
1118        rib_body.put_u32(1_699_999_998);
1119        rib_body.put_u16(32);
1120        rib_body.put_u8(0);
1121
1122        let rib_body = rib_body.freeze();
1123        let rib_header = CommonHeader {
1124            timestamp: 1_700_000_001,
1125            microsecond_timestamp: None,
1126            entry_type: EntryType::TABLE_DUMP_V2,
1127            entry_subtype: TableDumpV2Type::RibIpv4Unicast as u16,
1128            length: rib_body.len() as u32,
1129        };
1130
1131        let mut bytes = pit_record.encode().unwrap().to_vec();
1132        bytes.extend_from_slice(&rib_header.encode());
1133        bytes.extend_from_slice(&rib_body);
1134
1135        (bytes, rib_body, peer_table)
1136    }
1137
1138    fn assert_filtered_route_projection(bytes: Vec<u8>, filters: &[(&str, &str)]) {
1139        let elem_parser = filters.iter().fold(
1140            BgpkitParser::from_reader(Cursor::new(bytes.clone())),
1141            |parser, (filter_type, filter_value)| {
1142                parser.add_filter(filter_type, filter_value).unwrap()
1143            },
1144        );
1145        let route_parser = filters.iter().fold(
1146            BgpkitParser::from_reader(Cursor::new(bytes)),
1147            |parser, (filter_type, filter_value)| {
1148                parser.add_filter(filter_type, filter_value).unwrap()
1149            },
1150        );
1151
1152        let elem_projection = elem_parser
1153            .into_elem_iter()
1154            .map(route_projection)
1155            .collect::<Vec<_>>();
1156        let routes = route_parser.into_route_iter().collect::<Vec<_>>();
1157
1158        assert_eq!(routes, elem_projection, "filters: {filters:?}");
1159    }
1160
1161    fn assert_route_projection(bytes: Vec<u8>) -> Vec<BgpRouteElem> {
1162        let elem_projection = BgpkitParser::from_reader(Cursor::new(bytes.clone()))
1163            .into_elem_iter()
1164            .map(route_projection)
1165            .collect::<Vec<_>>();
1166        let routes = BgpkitParser::from_reader(Cursor::new(bytes))
1167            .into_route_iter()
1168            .collect::<Vec<_>>();
1169
1170        assert_eq!(routes, elem_projection);
1171        routes
1172    }
1173
1174    #[test]
1175    fn bgp4mp_routes_rejects_link_state_envelope_afi() {
1176        let mut data = BytesMut::new();
1177        data.put_u16(65000);
1178        data.put_u16(65001);
1179        data.put_u16(0);
1180        data.put_u16(Afi::LinkState as u16);
1181        data.put_slice(&BgpMessage::KeepAlive.encode(AsnLength::Bits16).unwrap());
1182
1183        let error =
1184            match parse_bgp4mp_routes(Bgp4MpType::Message as u16, data.freeze(), 1_700_000_000.0) {
1185                Err(error) => error,
1186                Ok(_) => panic!("unexpectedly parsed BGP4MP routes"),
1187            };
1188        assert!(matches!(
1189            error,
1190            ParserError::ParseError(message)
1191                if message == "Link-State AFI is invalid in a BGP4MP envelope"
1192        ));
1193    }
1194
1195    #[test]
1196    fn route_iterator_matches_elem_projection_for_update() {
1197        let bytes = update_record().encode().unwrap().to_vec();
1198        let routes = assert_route_projection(bytes);
1199        assert_eq!(routes.len(), 2);
1200        assert_eq!(routes[0].elem_type, ElemType::ANNOUNCE);
1201        assert_eq!(routes[1].elem_type, ElemType::WITHDRAW);
1202        assert!(routes[1].as_path.is_none());
1203    }
1204
1205    #[test]
1206    fn route_iterator_shares_as_path_for_update_announcements() {
1207        let bytes = bgp4mp_record(
1208            Bgp4MpType::MessageAs4,
1209            BgpMessage::Update(BgpUpdateMessage {
1210                withdrawn_prefixes: vec![],
1211                attributes: route_attributes([64500, 64501]),
1212                announced_prefixes: vec![
1213                    NetworkPrefix::from_str("203.0.113.0/24").unwrap(),
1214                    NetworkPrefix::from_str("198.51.100.0/24").unwrap(),
1215                ],
1216            }),
1217        )
1218        .encode()
1219        .unwrap()
1220        .to_vec();
1221
1222        let routes = BgpkitParser::from_reader(Cursor::new(bytes))
1223            .into_route_iter()
1224            .collect::<Vec<_>>();
1225
1226        assert_eq!(routes.len(), 2);
1227        assert!(Arc::ptr_eq(
1228            routes[0].as_path.as_ref().unwrap(),
1229            routes[1].as_path.as_ref().unwrap()
1230        ));
1231    }
1232
1233    #[test]
1234    fn route_iterator_uses_microsecond_timestamps() {
1235        let timestamp = record_timestamp(&CommonHeader {
1236            timestamp: 1_700_000_000,
1237            microsecond_timestamp: Some(123_456),
1238            entry_type: EntryType::BGP4MP_ET,
1239            entry_subtype: Bgp4MpType::MessageAs4 as u16,
1240            length: 0,
1241        });
1242
1243        assert_eq!(timestamp, 1_700_000_000.123_456);
1244    }
1245
1246    #[test]
1247    fn route_iterator_matches_elem_projection_for_mp_update() {
1248        let mut attributes = route_attributes([64500, 64501]);
1249        attributes.add_attr(
1250            AttributeValue::MpReachNlri(Nlri::new_reachable(
1251                NetworkPrefix::from_str("2001:db8::/32").unwrap(),
1252                Some(IpAddr::from_str("2001:db8::1").unwrap()),
1253            ))
1254            .into(),
1255        );
1256        attributes.add_attr(
1257            AttributeValue::MpUnreachNlri(Nlri::new_unreachable(
1258                NetworkPrefix::from_str("2001:db8:1::/48").unwrap(),
1259            ))
1260            .into(),
1261        );
1262
1263        let bytes = bgp4mp_record(
1264            Bgp4MpType::MessageAs4,
1265            BgpMessage::Update(BgpUpdateMessage {
1266                withdrawn_prefixes: vec![],
1267                attributes,
1268                announced_prefixes: vec![],
1269            }),
1270        )
1271        .encode()
1272        .unwrap()
1273        .to_vec();
1274
1275        let routes = assert_route_projection(bytes);
1276        assert_eq!(routes.len(), 2);
1277        assert_eq!(routes[0].elem_type, ElemType::ANNOUNCE);
1278        assert_eq!(
1279            routes[0].prefix,
1280            NetworkPrefix::from_str("2001:db8::/32").unwrap()
1281        );
1282        assert_eq!(routes[1].elem_type, ElemType::WITHDRAW);
1283        assert_eq!(
1284            routes[1].prefix,
1285            NetworkPrefix::from_str("2001:db8:1::/48").unwrap()
1286        );
1287    }
1288
1289    #[test]
1290    fn route_iterator_matches_elem_projection_for_non_update_bgp4mp_messages() {
1291        let records = [
1292            bgp4mp_record(Bgp4MpType::Message, open_message()),
1293            bgp4mp_record(
1294                Bgp4MpType::MessageAs4,
1295                BgpMessage::Notification(BgpNotificationMessage {
1296                    error: BgpError::Unknown(1, 0),
1297                    data: vec![],
1298                }),
1299            ),
1300            bgp4mp_record(Bgp4MpType::MessageAddpath, BgpMessage::KeepAlive),
1301            bgp4mp_record(Bgp4MpType::MessageAs4Addpath, BgpMessage::KeepAlive),
1302        ];
1303        let mut bytes = Vec::new();
1304        for record in records {
1305            bytes.extend_from_slice(&record.encode().unwrap());
1306        }
1307
1308        assert!(assert_route_projection(bytes).is_empty());
1309    }
1310
1311    #[test]
1312    fn route_iterator_matches_elem_projection_for_bgp4mp_16bit_update() {
1313        let bytes = bgp4mp_record(
1314            Bgp4MpType::Message,
1315            BgpMessage::Update(BgpUpdateMessage {
1316                withdrawn_prefixes: vec![],
1317                attributes: route_attributes([64500, 64501]),
1318                announced_prefixes: vec![NetworkPrefix::from_str("203.0.113.0/24").unwrap()],
1319            }),
1320        )
1321        .encode()
1322        .unwrap()
1323        .to_vec();
1324
1325        let routes = assert_route_projection(bytes);
1326        assert_eq!(routes.len(), 1);
1327        assert_eq!(routes[0].peer_asn, Asn::new_16bit(64496));
1328    }
1329
1330    #[test]
1331    fn route_iterator_filters_match_elem_projection_for_update() {
1332        let bytes = update_record().encode().unwrap().to_vec();
1333        let cases: &[&[(&str, &str)]] = &[
1334            &[("peer_ip", "192.0.2.1")],
1335            &[("peer_ip", "192.0.2.99")],
1336            &[("peer_asn", "64496")],
1337            &[("type", "a")],
1338            &[("type", "w")],
1339            &[("type", "!w")],
1340            &[("prefix", "203.0.113.0/24")],
1341            &[("prefix", "198.51.100.0/24")],
1342            &[("prefix_super", "203.0.113.128/25")],
1343            &[("origin_asn", "64501")],
1344            &[("origin_asns", "64496,64501")],
1345            &[("as_path", "64500 64501$")],
1346            &[("ip_version", "4")],
1347            &[("ts_start", "1700000000"), ("ts_end", "1700000000")],
1348            &[("peer_ip", "192.0.2.1"), ("type", "a")],
1349        ];
1350
1351        for filters in cases {
1352            assert_filtered_route_projection(bytes.clone(), filters);
1353        }
1354    }
1355
1356    #[test]
1357    fn selective_attribute_parser_merges_as4_path() {
1358        let mut attributes = Attributes::default();
1359        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([23456, 64497])).into());
1360        attributes.add_attr(AttributeValue::As4Path(AsPath::from_sequence([65536, 64497])).into());
1361
1362        let attrs = parse_route_attributes(
1363            attributes.encode(AsnLength::Bits16).unwrap(),
1364            &AsnLength::Bits16,
1365            false,
1366            RouteAttributeContext {
1367                afi: None,
1368                safi: None,
1369                prefixes: None,
1370                is_announcement: Some(true),
1371                has_standard_nlri: true,
1372            },
1373        )
1374        .unwrap();
1375
1376        assert_eq!(
1377            attrs.as_path.unwrap().to_u32_vec_opt(false).unwrap(),
1378            vec![65536, 64497]
1379        );
1380    }
1381
1382    #[test]
1383    fn selective_attribute_parser_handles_as_path_without_as4_path() {
1384        let attrs = parse_route_attributes(
1385            route_attributes([64500, 64501])
1386                .encode(AsnLength::Bits16)
1387                .unwrap(),
1388            &AsnLength::Bits16,
1389            false,
1390            RouteAttributeContext {
1391                afi: None,
1392                safi: None,
1393                prefixes: None,
1394                is_announcement: Some(true),
1395                has_standard_nlri: true,
1396            },
1397        )
1398        .unwrap();
1399
1400        assert_eq!(
1401            attrs.as_path.unwrap().to_u32_vec_opt(false).unwrap(),
1402            vec![64500, 64501]
1403        );
1404    }
1405
1406    #[test]
1407    fn selective_attribute_parser_handles_as4_path_without_as_path() {
1408        let mut attributes = Attributes::default();
1409        attributes.add_attr(AttributeValue::As4Path(AsPath::from_sequence([65536, 64497])).into());
1410
1411        let attrs = parse_route_attributes(
1412            attributes.encode(AsnLength::Bits16).unwrap(),
1413            &AsnLength::Bits16,
1414            false,
1415            RouteAttributeContext {
1416                afi: None,
1417                safi: None,
1418                prefixes: None,
1419                is_announcement: Some(false),
1420                has_standard_nlri: false,
1421            },
1422        )
1423        .unwrap();
1424
1425        assert_eq!(
1426            attrs.as_path.unwrap().to_u32_vec_opt(false).unwrap(),
1427            vec![65536, 64497]
1428        );
1429    }
1430
1431    #[test]
1432    fn selective_attribute_parser_handles_no_as_path() {
1433        let attrs = parse_route_attributes(
1434            Bytes::new(),
1435            &AsnLength::Bits16,
1436            false,
1437            RouteAttributeContext {
1438                afi: None,
1439                safi: None,
1440                prefixes: None,
1441                is_announcement: Some(false),
1442                has_standard_nlri: false,
1443            },
1444        )
1445        .unwrap();
1446
1447        assert!(attrs.as_path.is_none());
1448    }
1449
1450    #[test]
1451    fn selective_attribute_parser_handles_extended_and_truncated_attributes() {
1452        let mut extended_as_path = BytesMut::new();
1453        extended_as_path.put_u8((AttrFlags::TRANSITIVE | AttrFlags::EXTENDED).bits());
1454        extended_as_path.put_u8(u8::from(AttrType::AS_PATH));
1455        extended_as_path.put_u16(4);
1456        extended_as_path.put_u8(2);
1457        extended_as_path.put_u8(1);
1458        extended_as_path.put_u16(64500);
1459
1460        let attrs = parse_route_attributes(
1461            extended_as_path.freeze(),
1462            &AsnLength::Bits16,
1463            false,
1464            RouteAttributeContext {
1465                afi: None,
1466                safi: None,
1467                prefixes: None,
1468                is_announcement: Some(false),
1469                has_standard_nlri: false,
1470            },
1471        )
1472        .unwrap();
1473        assert_eq!(
1474            attrs.as_path.unwrap().to_u32_vec_opt(false).unwrap(),
1475            vec![64500]
1476        );
1477
1478        let attrs = parse_route_attributes(
1479            Bytes::from_static(&[0x40, 2, 5, 0]),
1480            &AsnLength::Bits16,
1481            false,
1482            RouteAttributeContext {
1483                afi: None,
1484                safi: None,
1485                prefixes: None,
1486                is_announcement: Some(false),
1487                has_standard_nlri: false,
1488            },
1489        )
1490        .unwrap();
1491        assert!(attrs.as_path.is_none());
1492    }
1493
1494    #[test]
1495    fn selective_attribute_parser_discards_malformed_as_path() {
1496        let attrs = parse_route_attributes(
1497            Bytes::from_static(&[0x40, 2, 1, 0]),
1498            &AsnLength::Bits16,
1499            false,
1500            RouteAttributeContext {
1501                afi: None,
1502                safi: None,
1503                prefixes: None,
1504                is_announcement: Some(false),
1505                has_standard_nlri: false,
1506            },
1507        )
1508        .unwrap();
1509
1510        assert!(attrs.as_path.is_none());
1511    }
1512
1513    #[test]
1514    fn route_iterator_matches_elem_projection_for_table_dump() {
1515        let bytes = table_dump_record().encode().unwrap().to_vec();
1516        let routes = assert_route_projection(bytes);
1517        assert_eq!(routes.len(), 1);
1518        assert_eq!(routes[0].timestamp, 1_699_999_998.0);
1519        assert_eq!(routes[0].peer_asn, Asn::new_16bit(64496));
1520    }
1521
1522    #[test]
1523    fn route_iterator_matches_elem_projection_for_table_dump_ipv6() {
1524        let bytes = table_dump_ipv6_record().encode().unwrap().to_vec();
1525        let routes = assert_route_projection(bytes);
1526        assert_eq!(routes.len(), 1);
1527        assert_eq!(
1528            routes[0].prefix,
1529            NetworkPrefix::from_str("2001:db8::/32").unwrap()
1530        );
1531        assert_eq!(
1532            routes[0].peer_ip,
1533            IpAddr::from(Ipv6Addr::from_str("2001:db8::20").unwrap())
1534        );
1535    }
1536
1537    #[test]
1538    fn route_iterator_matches_elem_projection_for_table_dump_v2() {
1539        let bytes = table_dump_v2_records_bytes();
1540        let routes = assert_route_projection(bytes);
1541        assert_eq!(routes.len(), 1);
1542        assert_eq!(routes[0].elem_type, ElemType::ANNOUNCE);
1543        assert_eq!(
1544            routes[0].as_path.as_ref().unwrap().to_u32_vec_opt(false),
1545            Some(vec![64500, 64501])
1546        );
1547    }
1548
1549    #[test]
1550    fn route_iterator_matches_elem_projection_for_table_dump_v2_ipv6_addpath() {
1551        let peer = Peer::new(
1552            "192.0.2.11".parse().unwrap(),
1553            "2001:db8::10".parse().unwrap(),
1554            Asn::new_32bit(64496),
1555        );
1556        let mut peer_table = PeerIndexTable::default();
1557        let peer_index = peer_table.add_peer(peer).unwrap();
1558
1559        let pit_record = MrtRecord {
1560            common_header: CommonHeader {
1561                timestamp: 1_700_000_000,
1562                microsecond_timestamp: None,
1563                entry_type: EntryType::TABLE_DUMP_V2,
1564                entry_subtype: TableDumpV2Type::PeerIndexTable as u16,
1565                length: 0,
1566            },
1567            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(peer_table)),
1568        };
1569        let rib_record = MrtRecord {
1570            common_header: CommonHeader {
1571                timestamp: 1_700_000_001,
1572                microsecond_timestamp: None,
1573                entry_type: EntryType::TABLE_DUMP_V2,
1574                entry_subtype: TableDumpV2Type::RibIpv6UnicastAddPath as u16,
1575                length: 0,
1576            },
1577            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
1578                rib_type: TableDumpV2Type::RibIpv6UnicastAddPath,
1579                sequence_number: 1,
1580                prefix: NetworkPrefix::from_str("2001:db8::/32").unwrap(),
1581                rib_entries: vec![RibEntry {
1582                    peer_index,
1583                    originated_time: 1_699_999_999,
1584                    path_id: Some(1234),
1585                    attributes: route_attributes([64500, 64501]),
1586                }],
1587            })),
1588        };
1589
1590        let mut bytes = pit_record.encode().unwrap().to_vec();
1591        bytes.extend_from_slice(&rib_record.encode().unwrap());
1592        let routes = assert_route_projection(bytes);
1593        assert_eq!(routes.len(), 1);
1594        assert_eq!(
1595            routes[0].prefix,
1596            NetworkPrefix::from_str("2001:db8::/32").unwrap()
1597        );
1598    }
1599
1600    #[test]
1601    fn route_iterator_matches_elem_projection_for_bgp4mp_ipv6_peer_update() {
1602        let record = MrtRecord {
1603            common_header: CommonHeader {
1604                timestamp: 1_700_000_000,
1605                microsecond_timestamp: None,
1606                entry_type: EntryType::BGP4MP,
1607                entry_subtype: Bgp4MpType::MessageAs4 as u16,
1608                length: 0,
1609            },
1610            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
1611                msg_type: Bgp4MpType::MessageAs4,
1612                peer_asn: Asn::new_32bit(64496),
1613                local_asn: Asn::new_32bit(64497),
1614                interface_index: 0,
1615                peer_ip: IpAddr::from_str("2001:db8::1").unwrap(),
1616                local_ip: IpAddr::from_str("2001:db8::2").unwrap(),
1617                bgp_message: BgpMessage::Update(BgpUpdateMessage {
1618                    withdrawn_prefixes: vec![],
1619                    attributes: route_attributes([64500, 64501]),
1620                    announced_prefixes: vec![NetworkPrefix::from_str("203.0.113.0/24").unwrap()],
1621                }),
1622            })),
1623        };
1624
1625        let routes = assert_route_projection(record.encode().unwrap().to_vec());
1626        assert_eq!(routes.len(), 1);
1627        assert_eq!(
1628            routes[0].peer_ip,
1629            IpAddr::from(Ipv6Addr::from_str("2001:db8::1").unwrap())
1630        );
1631    }
1632
1633    #[test]
1634    fn route_iterator_filters_match_elem_projection_for_table_dump_v2() {
1635        let bytes = table_dump_v2_records_bytes();
1636        let cases: &[&[(&str, &str)]] = &[
1637            &[("peer_ip", "192.0.2.10")],
1638            &[("peer_asn", "64496")],
1639            &[("type", "a")],
1640            &[("type", "w")],
1641            &[("prefix", "203.0.113.0/24")],
1642            &[("prefix_sub", "203.0.112.0/23")],
1643            &[("origin_asn", "64501")],
1644            &[("as_path", "64500 64501$")],
1645            &[("ts_start", "1699999999"), ("ts_end", "1699999999")],
1646            &[("peer_asn", "64496"), ("origin_asn", "64501")],
1647        ];
1648
1649        for filters in cases {
1650            assert_filtered_route_projection(bytes.clone(), filters);
1651        }
1652    }
1653
1654    #[test]
1655    fn route_parser_reports_bgp_message_shape_errors() {
1656        assert!(parse_bgp_message_routes(
1657            raw_bgp_message(18, BgpMessageType::KEEPALIVE, &[]),
1658            false,
1659            &AsnLength::Bits16,
1660            1_700_000_000.0,
1661            "192.0.2.1".parse().unwrap(),
1662            Asn::new_16bit(64496)
1663        )
1664        .is_err());
1665        assert!(parse_bgp_message_routes(
1666            raw_bgp_message(4097, BgpMessageType::OPEN, &[]),
1667            false,
1668            &AsnLength::Bits16,
1669            1_700_000_000.0,
1670            "192.0.2.1".parse().unwrap(),
1671            Asn::new_16bit(64496)
1672        )
1673        .is_err());
1674
1675        let routes = collect_route_record_iter(
1676            parse_bgp_message_routes(
1677                raw_bgp_message(30, BgpMessageType::KEEPALIVE, &[]),
1678                false,
1679                &AsnLength::Bits16,
1680                1_700_000_000.0,
1681                "192.0.2.1".parse().unwrap(),
1682                Asn::new_16bit(64496),
1683            )
1684            .unwrap(),
1685        )
1686        .unwrap();
1687        assert!(routes.is_empty());
1688
1689        let routes = collect_route_record_iter(
1690            parse_bgp_message_routes(
1691                raw_bgp_message(19, BgpMessageType::KEEPALIVE, &[0]),
1692                false,
1693                &AsnLength::Bits16,
1694                1_700_000_000.0,
1695                "192.0.2.1".parse().unwrap(),
1696                Asn::new_16bit(64496),
1697            )
1698            .unwrap(),
1699        )
1700        .unwrap();
1701        assert!(routes.is_empty());
1702
1703        let routes = collect_route_record_iter(
1704            parse_bgp_message_routes(
1705                raw_bgp_message_with_marker([0x00; 16], 19, BgpMessageType::KEEPALIVE, &[]),
1706                false,
1707                &AsnLength::Bits16,
1708                1_700_000_000.0,
1709                "192.0.2.1".parse().unwrap(),
1710                Asn::new_16bit(64496),
1711            )
1712            .unwrap(),
1713        )
1714        .unwrap();
1715        assert!(routes.is_empty());
1716    }
1717
1718    #[test]
1719    fn route_core_dump_write_respects_enabled_flag() {
1720        let dir = tempfile::tempdir().unwrap();
1721        let path = dir.path().join("mrt_core_dump");
1722
1723        write_mrt_core_dump_to_path(false, Some(vec![1, 2, 3]), &path);
1724        assert!(!path.exists());
1725
1726        write_mrt_core_dump_to_path(true, Some(vec![1, 2, 3]), &path);
1727        assert_eq!(std::fs::read(&path).unwrap(), vec![1, 2, 3]);
1728    }
1729
1730    #[test]
1731    fn route_parser_handles_table_dump_v2_error_edges() {
1732        let rib = RibAfiEntries {
1733            rib_type: TableDumpV2Type::RibIpv4Unicast,
1734            sequence_number: 1,
1735            prefix: NetworkPrefix::from_str("203.0.113.0/24").unwrap(),
1736            rib_entries: vec![RibEntry {
1737                peer_index: 99,
1738                originated_time: 1_699_999_999,
1739                path_id: None,
1740                attributes: route_attributes([64500, 64501]),
1741            }],
1742        };
1743        let mut no_peer_table = None;
1744        assert!(parse_table_dump_v2_routes(
1745            TableDumpV2Type::RibIpv4Unicast as u16,
1746            rib.encode().unwrap(),
1747            &mut no_peer_table,
1748        )
1749        .is_err());
1750
1751        let mut empty_peer_table = Some(RoutePeerTable::default());
1752        let routes = collect_route_record_iter(
1753            parse_table_dump_v2_routes(
1754                TableDumpV2Type::RibIpv4Unicast as u16,
1755                rib.encode().unwrap(),
1756                &mut empty_peer_table,
1757            )
1758            .unwrap(),
1759        )
1760        .unwrap();
1761        assert!(routes.is_empty());
1762
1763        let mut truncated = BytesMut::new();
1764        truncated.put_u32(1);
1765        truncated.extend(NetworkPrefix::from_str("203.0.113.0/24").unwrap().encode());
1766        truncated.put_u16(1);
1767        let mut empty_peer_table = Some(RoutePeerTable::default());
1768        let routes = collect_route_record_iter(
1769            parse_table_dump_v2_routes(
1770                TableDumpV2Type::RibIpv4Unicast as u16,
1771                truncated.freeze(),
1772                &mut empty_peer_table,
1773            )
1774            .unwrap(),
1775        )
1776        .unwrap();
1777        assert!(routes.is_empty());
1778
1779        let peer = Peer::new(
1780            "192.0.2.10".parse().unwrap(),
1781            "192.0.2.11".parse().unwrap(),
1782            Asn::new_32bit(64496),
1783        );
1784        let mut peer_table = PeerIndexTable::default();
1785        let peer_index = peer_table.add_peer(peer).unwrap();
1786
1787        let first_entry = RibEntry {
1788            peer_index,
1789            originated_time: 1_699_999_999,
1790            path_id: Some(1234),
1791            attributes: route_attributes([64500, 64501]),
1792        };
1793        let mut add_path_truncated = BytesMut::new();
1794        add_path_truncated.put_u32(1);
1795        add_path_truncated.extend(NetworkPrefix::from_str("203.0.113.0/24").unwrap().encode());
1796        add_path_truncated.put_u16(2);
1797        add_path_truncated.extend(first_entry.encode().unwrap());
1798        add_path_truncated.put_u16(peer_index);
1799        add_path_truncated.put_u32(1_699_999_998);
1800        add_path_truncated.put_u32(5678);
1801
1802        let mut peer_table = Some(route_peer_table_from_peer_index(peer_table));
1803        let routes = collect_route_record_iter(
1804            parse_table_dump_v2_routes(
1805                TableDumpV2Type::RibIpv4UnicastAddPath as u16,
1806                add_path_truncated.freeze(),
1807                &mut peer_table,
1808            )
1809            .unwrap(),
1810        )
1811        .unwrap();
1812        assert_eq!(routes.len(), 1);
1813        assert_eq!(
1814            routes[0].prefix,
1815            NetworkPrefix::from_str("203.0.113.0/24").unwrap()
1816        );
1817    }
1818
1819    #[test]
1820    fn route_parser_preserves_table_dump_v2_routes_before_truncated_attribute_payload() {
1821        let (_bytes, rib_body, peer_table) = table_dump_v2_truncated_attribute_payload();
1822        let mut peer_table = Some(route_peer_table_from_peer_index(peer_table));
1823
1824        let routes = collect_route_record_iter(
1825            parse_table_dump_v2_routes(
1826                TableDumpV2Type::RibIpv4Unicast as u16,
1827                rib_body,
1828                &mut peer_table,
1829            )
1830            .unwrap(),
1831        )
1832        .unwrap();
1833
1834        assert_eq!(routes.len(), 1);
1835        assert_eq!(
1836            routes[0].prefix,
1837            NetworkPrefix::from_str("203.0.113.0/24").unwrap()
1838        );
1839        assert_eq!(
1840            routes[0].as_path.as_ref().unwrap().to_u32_vec_opt(false),
1841            Some(vec![64500, 64501])
1842        );
1843    }
1844
1845    #[test]
1846    fn route_iterators_preserve_table_dump_v2_routes_before_truncated_attribute_payload() {
1847        let (bytes, _rib_body, _peer_table) = table_dump_v2_truncated_attribute_payload();
1848
1849        let routes = BgpkitParser::from_reader(Cursor::new(bytes.clone()))
1850            .into_route_iter()
1851            .collect::<Vec<_>>();
1852        assert_eq!(routes.len(), 1);
1853        assert_eq!(
1854            routes[0].prefix,
1855            NetworkPrefix::from_str("203.0.113.0/24").unwrap()
1856        );
1857
1858        let fallible_routes = BgpkitParser::from_reader(Cursor::new(bytes))
1859            .into_fallible_route_iter()
1860            .collect::<Result<Vec<_>, _>>()
1861            .unwrap();
1862        assert_eq!(fallible_routes, routes);
1863    }
1864
1865    fn table_dump_v2_rib_without_peer_table_record() -> MrtRecord {
1866        MrtRecord {
1867            common_header: CommonHeader {
1868                timestamp: 1_700_000_001,
1869                microsecond_timestamp: None,
1870                entry_type: EntryType::TABLE_DUMP_V2,
1871                entry_subtype: TableDumpV2Type::RibIpv4Unicast as u16,
1872                length: 0,
1873            },
1874            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
1875                rib_type: TableDumpV2Type::RibIpv4Unicast,
1876                sequence_number: 1,
1877                prefix: NetworkPrefix::from_str("203.0.113.0/24").unwrap(),
1878                rib_entries: vec![RibEntry {
1879                    peer_index: 0,
1880                    originated_time: 1_699_999_999,
1881                    path_id: None,
1882                    attributes: route_attributes([64500, 64501]),
1883                }],
1884            })),
1885        }
1886    }
1887
1888    #[test]
1889    fn route_iterator_skips_route_parse_errors() {
1890        let routes = BgpkitParser::from_reader(Cursor::new(
1891            table_dump_v2_rib_without_peer_table_record()
1892                .encode()
1893                .unwrap()
1894                .to_vec(),
1895        ))
1896        .into_route_iter()
1897        .collect::<Vec<_>>();
1898
1899        assert!(routes.is_empty());
1900    }
1901
1902    #[test]
1903    fn fallible_route_iterator_applies_filters_to_cached_routes() {
1904        let routes =
1905            BgpkitParser::from_reader(Cursor::new(update_record().encode().unwrap().to_vec()))
1906                .add_filter("type", "w")
1907                .unwrap()
1908                .into_fallible_route_iter()
1909                .collect::<Result<Vec<_>, _>>()
1910                .unwrap();
1911
1912        assert_eq!(routes.len(), 1);
1913        assert_eq!(routes[0].elem_type, ElemType::WITHDRAW);
1914    }
1915
1916    #[test]
1917    fn fallible_route_iterator_returns_route_parse_errors() {
1918        let bytes = table_dump_v2_rib_without_peer_table_record()
1919            .encode()
1920            .unwrap()
1921            .to_vec();
1922        let mut iter =
1923            BgpkitParser::from_reader(Cursor::new(bytes.clone())).into_fallible_route_iter();
1924
1925        let error = iter.next().unwrap().unwrap_err();
1926        assert_eq!(error.bytes.as_deref(), Some(bytes.as_slice()));
1927    }
1928
1929    #[test]
1930    fn fallible_route_iterator_yields_routes() {
1931        let bytes = update_record().encode().unwrap().to_vec();
1932        let routes = BgpkitParser::from_reader(Cursor::new(bytes))
1933            .into_fallible_route_iter()
1934            .collect::<Result<Vec<_>, _>>()
1935            .unwrap();
1936
1937        assert_eq!(routes.len(), 2);
1938        assert_eq!(routes[0].elem_type, ElemType::ANNOUNCE);
1939        assert_eq!(routes[1].elem_type, ElemType::WITHDRAW);
1940    }
1941
1942    #[test]
1943    fn fallible_route_iterator_returns_parse_errors() {
1944        let invalid_data = vec![
1945            0x00, 0x00, 0x00, 0x00, // timestamp
1946            0xFF, 0xFF, // invalid type
1947            0x00, 0x00, // subtype
1948            0x00, 0x00, 0x00, 0x04, // length
1949            0x00, 0x00, 0x00, 0x00, // dummy data
1950        ];
1951
1952        let mut iter =
1953            BgpkitParser::from_reader(Cursor::new(invalid_data.clone())).into_fallible_route_iter();
1954
1955        // The unknown-type record is skipped whole, so the error carries the
1956        // header and the declared body, and the stream ends cleanly after it.
1957        let error = iter.next().unwrap().unwrap_err();
1958        assert_eq!(error.bytes.as_deref(), Some(invalid_data.as_slice()));
1959        assert!(iter.next().is_none());
1960    }
1961}