Skip to main content

bgpkit_parser/parser/iters/elem_ref/
mod.rs

1#![forbid(unsafe_code)]
2/*!
3Borrowed element views over the records this path serves: `TABLE_DUMP_V2` `RIB_AFI` entries and
4`BGP4MP_AS4` updates.
5
6[`BgpkitParser::next_record_elems`](crate::BgpkitParser::next_record_elems) reads one record body
7into a reusable buffer owned by the parser and lends a [`RecordElems`] batch over its RIB entries.
8Each [`ElemRef`] yielded by [`RecordElems::iter`] borrows directly from the record body and the
9active peer index table. Its accessors decode on demand. An update's next hop is decoded once for
10the whole record; a dump entry's `MP_REACH_NLRI` next hop is decoded per call and allocates, and
11materialising an element allocates its AS path and communities.
12*/
13
14mod element;
15mod update;
16mod view;
17
18pub use element::ElemRef;
19pub use view::*;
20
21use update::{fill_update_entries, parse_peer_index_vec, update_record_elems};
22use view::{mp_reach_next_hop, scan_attr_block, AttrBlockScan};
23
24use crate::error::ParserError;
25use crate::models::{
26    get_deprecated_attr_type, Afi, AsPath, AsPathSegment, Asn, AsnLength, AttrFlags, AttrRaw,
27    AttrType, Bgp4MpType, BgpIdentifier, CommonHeader, ElemType, ExtendedCommunity, LargeCommunity,
28    MetaCommunity, NetworkPrefix, Origin, Peer, Safi,
29};
30use crate::parser::iters::handle_record_parse_error;
31use crate::parser::mrt::frame::{assemble_error_bytes, FrameError, Framer};
32use crate::parser::mrt::mrt_header::HeaderBuf;
33use crate::parser::{BgpkitParser, ElemError, ReadUtils};
34use crate::BgpElem;
35use bytes::Bytes;
36use ipnet::IpNet;
37use log::{error, warn};
38use std::cell::Cell;
39use std::io::Read;
40use std::net::IpAddr;
41use zerocopy::big_endian::U32 as BeU32;
42use zerocopy::FromBytes;
43
44const AS_PATH_AS_SET: u8 = 1;
45const AS_PATH_AS_SEQUENCE: u8 = 2;
46const AS_PATH_CONFED_SEQUENCE: u8 = 3;
47const AS_PATH_CONFED_SET: u8 = 4;
48
49use crate::parser::mrt::frame::{FLAG_ADD_PATH, FLAG_AFI_IPV6, FLAG_SAFI_MULTICAST};
50/// Set for an element of a `BGP4MP` update. A dump's entry decodes `NEXT_HOP` with the record's
51/// family; an update's `NEXT_HOP` is always the IPv4 address RFC 4271 defines.
52const FLAG_UPDATE: u8 = 1 << 3;
53
54// One `u8` carries the frame bits and the update bit, so they must not overlap.
55const _: () = assert!(FLAG_UPDATE & (FLAG_AFI_IPV6 | FLAG_SAFI_MULTICAST | FLAG_ADD_PATH) == 0);
56
57const SLOT_UNSCANNED: u64 = u64::MAX;
58const SLOT_ABSENT: u64 = u64::MAX - 1;
59const SLOT_MERGED: u64 = u64::MAX - 2;
60
61/// Reusable parser-owned state backing [`BgpkitParser::next_record_elems`].
62///
63/// All buffers start empty (`0` heap capacity) so parsers that never call `next_record_elems`
64/// pay no allocation overhead.
65#[derive(Default)]
66pub(crate) struct ElemViewState {
67    /// Reusable buffer holding the wire body of the active MRT record.
68    ///
69    /// The buffer keeps its allocation across records; the active record body is
70    /// `&body_buf[..active_len]`.
71    pub(crate) body_buf: Vec<u8>,
72    /// Shared framing: common header plus the body read into `body_buf`.
73    pub(crate) framer: Framer,
74    /// Active `TABLE_DUMP_V2` `PeerIndexTable` indexed directly by wire `peer_index`.
75    peers: Option<Vec<Peer>>,
76    /// NLRI of the `BGP4MP` update the current [`RecordElems`] batch covers.
77    pub(crate) update_entries: Vec<UpdateEntry>,
78    /// Byte range of that update's attribute block inside `body_buf`, filled by the walk that also
79    /// produced `update_entries` so no record is decoded twice.
80    pub(crate) update_attrs: (usize, usize),
81    /// The next hop that update's elements share, decoded by the same walk.
82    pub(crate) update_next_hop: Option<IpAddr>,
83    /// Elements belonging to records this view does not serve, counted by the owned path so a
84    /// caller that only counts gets the same total as `into_elem_iter`.
85    pub(crate) unserved_elems: usize,
86    /// Set once EOF or a non-recoverable framing/core-dump error ends iteration.
87    finished: bool,
88}
89
90/// Count the elements this parser reads, without materialising them.
91///
92/// A served record is counted entry by entry over the borrowed batch, which decodes no attribute.
93/// A record the view does not serve is parsed by the owned path and counted from its elements, so
94/// the total matches `into_elem_iter().count()`.
95pub(crate) fn count_elems<R: Read>(parser: &mut BgpkitParser<R>) -> Option<usize> {
96    // A text dump carries elements this path never frames.
97    if parser.text_dump_iter.is_some() {
98        return None;
99    }
100    let mut total = 0usize;
101    while let Some(batch) = next_record_elems_impl(parser) {
102        total += batch.iter().count();
103    }
104    Some(total + parser.elem_view_state.unserved_elems)
105}
106
107/// Whether a `GEO_PEER_TABLE` body decodes, decided by the owned parser so the RFC 6397 layout has
108/// one owner.
109fn validate_geo_peer_table(data: &[u8]) -> Result<(), ParserError> {
110    crate::parser::mrt::messages::table_dump_v2::geo_peer_table::parse_geo_peer_table(
111        &mut bytes::Bytes::copy_from_slice(data),
112    )
113    .map(|_| ())
114}
115
116/// Frame the next record, returning owned framing metadata and leaving the body in
117/// `elem_view_state.body_buf`, so no borrow outlives the call.
118pub(crate) fn frame_next<R: Read>(
119    parser: &mut BgpkitParser<R>,
120) -> Result<(CommonHeader, HeaderBuf, usize), FrameError> {
121    let state = &mut parser.elem_view_state;
122    let frame = state.framer.next(&mut parser.reader, &mut state.body_buf)?;
123    Ok((frame.header, frame.raw_header, frame.body.len()))
124}
125
126/// Frame the next record, consuming the peer index and geo peer tables into the state.
127///
128/// Every path that reads frames starts this way: frame a record, report a framing failure, and let
129/// the two table record kinds fill the state without reaching the caller. `None` means end of input.
130pub(crate) fn frame_body_record<R: Read>(
131    parser: &mut BgpkitParser<R>,
132) -> Option<(CommonHeader, HeaderBuf, usize)> {
133    use crate::parser::mrt::frame::{classify, RecordKind};
134
135    loop {
136        let (header, raw_header, body_len) = match frame_next(parser) {
137            Ok(framed) => framed,
138            Err(failure) => {
139                if matches!(failure.error, ParserError::EofExpected) {
140                    parser.elem_view_state.finished = true;
141                    return None;
142                }
143                if !handle_record_parse_error(parser, failure.error, failure.bytes) {
144                    parser.elem_view_state.finished = true;
145                    return None;
146                }
147                continue;
148            }
149        };
150        let body = &parser.elem_view_state.body_buf[..body_len];
151        match classify(&header, body) {
152            RecordKind::PeerIndex => match parse_peer_index_vec(body) {
153                Ok(peers) => parser.elem_view_state.peers = Some(peers),
154                Err(err) => {
155                    let raw = parser
156                        .core_dump
157                        .then(|| assemble_error_bytes(raw_header.as_slice(), body));
158                    if !handle_record_parse_error(parser, err, raw) {
159                        parser.elem_view_state.finished = true;
160                        return None;
161                    }
162                }
163            },
164            RecordKind::GeoPeer => {
165                let body = &parser.elem_view_state.body_buf[..body_len];
166                if let Err(err) = validate_geo_peer_table(body) {
167                    let raw = parser
168                        .core_dump
169                        .then(|| assemble_error_bytes(raw_header.as_slice(), body));
170                    if !handle_record_parse_error(parser, err, raw) {
171                        parser.elem_view_state.finished = true;
172                        return None;
173                    }
174                }
175            }
176            _ => return Some((header, raw_header, body_len)),
177        }
178    }
179}
180
181/// Whether a filter set proves this record yields no matching element.
182///
183/// Both record paths ask the same question of the same bytes: the header names the prefix for a dump
184/// record and the peer and time for an update, and `attr_scan` decides an origin predicate. A record
185/// this cannot decide is not excluded.
186pub(crate) fn record_excluded_by_filters<R: Read>(
187    parser: &BgpkitParser<R>,
188    header: &CommonHeader,
189    body_len: usize,
190) -> bool {
191    use crate::parser::mrt::frame::{classify, RecordKind};
192
193    let body = &parser.elem_view_state.body_buf[..body_len];
194    match classify(header, body) {
195        RecordKind::Rib {
196            prefix,
197            flags,
198            entries_offset,
199            ..
200        } => {
201            crate::parser::filter::rib_record_excluded(&parser.filters, &prefix)
202                || crate::parser::attr_scan::rib_record_excluded(
203                    &parser.filters,
204                    body,
205                    entries_offset,
206                    flags,
207                )
208        }
209        RecordKind::Bgp4Mp {
210            peer_ip,
211            peer_asn,
212            timestamp,
213        } => {
214            crate::parser::filter::peer_excludes_record(&parser.filters, &peer_ip, &peer_asn)
215                || crate::parser::filter::timestamp_excludes_record(&parser.filters, timestamp)
216                || crate::parser::attr_scan::bgp4mp_record_excluded(
217                    &parser.filters,
218                    body,
219                    header.entry_subtype,
220                )
221        }
222        RecordKind::PeerIndex | RecordKind::GeoPeer | RecordKind::Other => false,
223    }
224}
225
226/// What the borrowed element engine produced for the next record.
227pub(crate) enum NextBatch<'a> {
228    /// A RIB record's elements, borrowed from the parser's record buffer.
229    Rib(RecordElems<'a>),
230    /// A record this engine does not serve. Its body is still in the parser's buffer, untouched.
231    Other {
232        header: CommonHeader,
233        raw_header: crate::parser::mrt::mrt_header::HeaderBuf,
234        body_len: usize,
235    },
236    /// End of input.
237    End,
238}
239
240/// Advance to the next record and report whether the borrowed element engine can serve it.
241///
242/// Unlike [`next_record_elems_impl`], this stops at the first record the engine cannot serve
243/// instead of skipping it, so a caller can hand that record to the owned path.
244pub(crate) fn next_batch<R: Read>(parser: &mut BgpkitParser<R>) -> NextBatch<'_> {
245    use crate::parser::mrt::frame::{classify, RecordKind};
246
247    if parser.text_dump_iter.is_some() || parser.elem_view_state.finished {
248        return NextBatch::End;
249    }
250
251    loop {
252        let (header, raw_header, body_len) = match frame_body_record(parser) {
253            Some(framed) => framed,
254            None => return NextBatch::End,
255        };
256        // The same predicates the owned path applies, so a filtered run keeps the skips it had
257        // before it moved onto the framed path.
258        if record_excluded_by_filters(parser, &header, body_len) {
259            continue;
260        }
261        match classify(&header, &parser.elem_view_state.body_buf[..body_len]) {
262            RecordKind::Rib {
263                prefix,
264                entry_count,
265                flags,
266                entries_offset,
267            } => {
268                if parser.elem_view_state.peers.is_none() {
269                    error!("{}", ElemError::MissingPeerTable);
270                    continue;
271                }
272                let state = &mut parser.elem_view_state;
273                let peers = state.peers.as_deref().expect("checked peers is_some");
274                let entries_bytes = &state.body_buf[entries_offset..body_len];
275                return NextBatch::Rib(RecordElems::rib(
276                    header,
277                    entries_bytes,
278                    peers,
279                    prefix.prefix,
280                    entry_count,
281                    flags,
282                ));
283            }
284            // Hand the record back untouched: the caller owns the fallback and its error handling.
285            RecordKind::Bgp4Mp { .. } | RecordKind::Other => {
286                return NextBatch::Other {
287                    header,
288                    raw_header,
289                    body_len,
290                }
291            }
292            // `frame_body_record` consumes both table kinds before returning.
293            RecordKind::PeerIndex | RecordKind::GeoPeer => continue,
294        }
295    }
296}
297
298pub(crate) fn next_record_elems_impl<R: Read>(
299    parser: &mut BgpkitParser<R>,
300) -> Option<RecordElems<'_>> {
301    use crate::parser::mrt::frame::{bgp4mp_is_update, classify, RecordKind};
302
303    if parser.text_dump_iter.is_some() || parser.elem_view_state.finished {
304        return None;
305    }
306    if !parser.filters.is_empty() {
307        parser.options.warn_view_filters_once();
308        return None;
309    }
310
311    enum Framed {
312        Rib {
313            header: CommonHeader,
314            prefix: IpNet,
315            entry_count: u16,
316            flags: u8,
317            entries_offset: usize,
318            body_len: usize,
319        },
320        Update {
321            header: CommonHeader,
322            peer_ip: IpAddr,
323            peer_asn: Asn,
324            timestamp: f64,
325            body_len: usize,
326        },
327    }
328
329    let framed = loop {
330        let (common_header, raw_header, body_len) = frame_body_record(parser)?;
331        let kind = classify(&common_header, &parser.elem_view_state.body_buf[..body_len]);
332        match kind {
333            RecordKind::Rib {
334                prefix,
335                entry_count,
336                flags,
337                entries_offset,
338            } => {
339                if parser.elem_view_state.peers.is_none() {
340                    error!("{}", ElemError::MissingPeerTable);
341                    continue;
342                }
343                break Framed::Rib {
344                    header: common_header,
345                    prefix: prefix.prefix,
346                    entry_count,
347                    flags,
348                    entries_offset,
349                    body_len,
350                };
351            }
352            RecordKind::Bgp4Mp {
353                peer_ip,
354                peer_asn,
355                timestamp,
356            } => {
357                // Support is decided from the header. The walk then runs here, once, and its result
358                // is kept in the state so the batch can be built without decoding again.
359                let subtype = common_header.entry_subtype;
360                let as4 = matches!(
361                    Bgp4MpType::try_from(subtype),
362                    Ok(Bgp4MpType::MessageAs4)
363                        | Ok(Bgp4MpType::MessageAs4Local)
364                        | Ok(Bgp4MpType::MessageAs4Addpath)
365                        | Ok(Bgp4MpType::MessageLocalAs4Addpath)
366                );
367                let would_yield =
368                    bgp4mp_is_update(subtype, &parser.elem_view_state.body_buf[..body_len]);
369                let walked = if as4 && would_yield {
370                    let state = &mut parser.elem_view_state;
371                    let body = &state.body_buf[..body_len];
372                    let outcome = fill_update_entries(body, subtype, &mut state.update_entries);
373                    outcome.map(|(attrs, next_hop)| {
374                        let offset = attrs.as_ptr() as usize - state.body_buf.as_ptr() as usize;
375                        state.update_attrs = (offset, attrs.len());
376                        state.update_next_hop = next_hop;
377                    })
378                } else {
379                    None
380                };
381                if walked.is_none() {
382                    // A record the view cannot read is either a parse error or a record kind it
383                    // does not serve. The owned parser answers which: its error goes through the
384                    // same handler, and only a record it parses cleanly is a scope limit.
385                    match parser.parse_framed_record(common_header, raw_header.as_slice(), body_len)
386                    {
387                        Ok(record) if as4 && would_yield => {
388                            parser.elem_view_state.unserved_elems +=
389                                crate::Elementor::default().record_to_elems(record).len();
390                            // The owned path parses it, so the failure is in this walk; say so
391                            // rather than drop the record in silence.
392                            error!(
393                                "next_record_elems could not read a BGP4MP update the parser accepts; use into_elem_iter for this file"
394                            );
395                        }
396                        Ok(record) if !as4 && would_yield => {
397                            parser
398                                .options
399                                .warn_view_scope_once("BGP4MP record with 2-byte AS numbers");
400                            parser.elem_view_state.unserved_elems +=
401                                crate::Elementor::default().record_to_elems(record).len();
402                        }
403                        Ok(_) => {}
404                        Err(failure) => {
405                            if !handle_record_parse_error(parser, failure.error, failure.bytes) {
406                                parser.elem_view_state.finished = true;
407                                return None;
408                            }
409                        }
410                    }
411                    continue;
412                }
413                break Framed::Update {
414                    header: common_header,
415                    peer_ip,
416                    peer_asn,
417                    timestamp,
418                    body_len,
419                };
420            }
421            // `frame_body_record` consumes both table kinds before returning.
422            RecordKind::PeerIndex | RecordKind::GeoPeer => continue,
423            RecordKind::Other => {
424                match parser.parse_framed_record(common_header, raw_header.as_slice(), body_len) {
425                    Ok(record) => {
426                        parser.options.warn_view_scope_once("other");
427                        parser.elem_view_state.unserved_elems +=
428                            crate::Elementor::default().record_to_elems(record).len();
429                    }
430                    Err(failure) => {
431                        if !handle_record_parse_error(parser, failure.error, failure.bytes) {
432                            parser.elem_view_state.finished = true;
433                            return None;
434                        }
435                    }
436                }
437                continue;
438            }
439        }
440    };
441
442    match framed {
443        Framed::Rib {
444            header,
445            prefix,
446            entry_count,
447            flags,
448            entries_offset,
449            body_len,
450        } => {
451            let state = &mut parser.elem_view_state;
452            let peers = state
453                .peers
454                .as_deref()
455                .expect("checked peers is_some before breaking");
456            let entries_bytes = &state.body_buf[entries_offset..body_len];
457            Some(RecordElems::rib(
458                header,
459                entries_bytes,
460                peers,
461                prefix,
462                entry_count,
463                flags,
464            ))
465        }
466        Framed::Update {
467            header,
468            peer_ip,
469            peer_asn,
470            timestamp,
471            body_len,
472        } => {
473            let record = update_record_elems(
474                &mut parser.elem_view_state,
475                body_len,
476                header,
477                peer_ip,
478                peer_asn,
479                timestamp,
480            );
481            if record.is_none() {
482                // The header said this record yields elements but the walk could not read it, so it
483                // is reported once instead of dropped in silence.
484                error!(
485                    "next_record_elems could not read a BGP4MP update the parser accepts; use into_elem_iter for this file"
486                );
487            }
488            record
489        }
490    }
491}
492
493/// A borrowed batch of elements from one MRT record.
494///
495/// Holds a mutable borrow of the [`BgpkitParser`] (its reusable record buffer, and the active peer
496/// table for a dump); drop it before advancing the parser to the next record.
497pub struct RecordElems<'a> {
498    header: CommonHeader,
499    source: RecordSource<'a>,
500}
501
502/// Where a [`RecordElems`] batch takes its elements from.
503enum RecordSource<'a> {
504    /// `TABLE_DUMP_V2` `RIB_AFI`: one prefix, and entries that name a peer and carry attributes.
505    Rib {
506        entries_bytes: &'a [u8],
507        peers: &'a [Peer],
508        prefix: IpNet,
509        entry_count: u16,
510        flags: u8,
511    },
512    /// `BGP4MP` update: one attribute block, the NLRI this record announced or withdrew, and the
513    /// next hop every element of it shares.
514    Update {
515        entries: &'a [UpdateEntry],
516        attrs: &'a [u8],
517        next_hop: Option<IpAddr>,
518        peer_ip: IpAddr,
519        peer_asn: Asn,
520        timestamp: f64,
521    },
522}
523
524impl<'a> RecordElems<'a> {
525    #[inline]
526    pub(crate) fn rib(
527        header: CommonHeader,
528        entries_bytes: &'a [u8],
529        peers: &'a [Peer],
530        prefix: IpNet,
531        entry_count: u16,
532        flags: u8,
533    ) -> Self {
534        RecordElems {
535            header,
536            source: RecordSource::Rib {
537                entries_bytes,
538                peers,
539                prefix,
540                entry_count,
541                flags,
542            },
543        }
544    }
545
546    #[inline]
547    pub(crate) fn update(
548        header: CommonHeader,
549        entries: &'a [UpdateEntry],
550        attrs: &'a [u8],
551        peer_ip: IpAddr,
552        peer_asn: Asn,
553        timestamp: f64,
554        next_hop: Option<IpAddr>,
555    ) -> Self {
556        RecordElems {
557            header,
558            source: RecordSource::Update {
559                entries,
560                attrs,
561                peer_ip,
562                peer_asn,
563                timestamp,
564                next_hop,
565            },
566        }
567    }
568
569    /// Returns the MRT [`CommonHeader`] of this record.
570    #[inline]
571    pub fn header(&self) -> &CommonHeader {
572        &self.header
573    }
574
575    /// The number of entries the record declares: the RIB entry count, or the number of NLRI this
576    /// update announced and withdrew.
577    ///
578    /// This is what the header says, not a promise about how many elements the iterator yields: an
579    /// entry naming a peer outside the table, or one the record cannot decode, produces fewer.
580    /// Never size a buffer from it without a ceiling, since the count comes from the input.
581    #[inline]
582    pub fn len(&self) -> usize {
583        match &self.source {
584            RecordSource::Rib { entry_count, .. } => *entry_count as usize,
585            RecordSource::Update { entries, .. } => entries.len(),
586        }
587    }
588
589    /// Returns `true` when the record declares no elements.
590    #[inline]
591    pub fn is_empty(&self) -> bool {
592        self.len() == 0
593    }
594
595    /// Returns an iterator yielding borrowed [`ElemRef`] views over the record's elements.
596    #[inline]
597    pub fn iter(&self) -> ElemRefIter<'a> {
598        let source = match &self.source {
599            RecordSource::Rib {
600                entries_bytes,
601                peers,
602                prefix,
603                entry_count,
604                flags,
605            } => IterSource::Rib {
606                data: entries_bytes,
607                peers,
608                prefix: *prefix,
609                remaining: *entry_count,
610                flags: *flags,
611            },
612            RecordSource::Update {
613                entries,
614                attrs,
615                peer_ip,
616                peer_asn,
617                timestamp,
618                next_hop,
619            } => IterSource::Update {
620                entries,
621                attrs,
622                peer_ip: *peer_ip,
623                peer_asn: *peer_asn,
624                timestamp: *timestamp,
625                next: 0,
626                next_hop: *next_hop,
627            },
628        };
629        ElemRefIter { source }
630    }
631}
632
633impl<'a> IntoIterator for &RecordElems<'a> {
634    type Item = ElemRef<'a>;
635    type IntoIter = ElemRefIter<'a>;
636
637    #[inline]
638    fn into_iter(self) -> Self::IntoIter {
639        self.iter()
640    }
641}
642
643/// One element of a `BGP4MP` update, as the record declared it.
644#[derive(Clone, Copy, Debug)]
645pub(crate) struct UpdateEntry {
646    prefix: NetworkPrefix,
647    elem_type: ElemType,
648    flags: u8,
649}
650
651/// Iterator over borrowed [`ElemRef`]s within a single [`RecordElems`] record.
652pub struct ElemRefIter<'a> {
653    source: IterSource<'a>,
654}
655
656enum IterSource<'a> {
657    Rib {
658        data: &'a [u8],
659        peers: &'a [Peer],
660        prefix: IpNet,
661        remaining: u16,
662        flags: u8,
663    },
664    Update {
665        entries: &'a [UpdateEntry],
666        attrs: &'a [u8],
667        peer_ip: IpAddr,
668        peer_asn: Asn,
669        timestamp: f64,
670        next: usize,
671        next_hop: Option<IpAddr>,
672    },
673}
674
675impl<'a> Iterator for ElemRefIter<'a> {
676    type Item = ElemRef<'a>;
677
678    #[inline]
679    fn next(&mut self) -> Option<Self::Item> {
680        match &mut self.source {
681            IterSource::Rib {
682                data,
683                peers,
684                prefix,
685                remaining,
686                flags,
687            } => {
688                if *remaining == 0 {
689                    return None;
690                }
691                let with_path_id = (*flags & FLAG_ADD_PATH) != 0;
692                let header_len = if with_path_id { 12 } else { 8 };
693                if data.len() < header_len {
694                    warn!("early break due to error Truncated message: truncated msg while parsing RIB AFI entries");
695                    *remaining = 0;
696                    return None;
697                }
698                let peer_index = u16::from_be_bytes([data[0], data[1]]);
699                let originated_time = u32::from_be_bytes([data[2], data[3], data[4], data[5]]);
700                // With add-path, bytes 6..10 carry this entry's path identifier: two entries of one
701                // prefix differ only by it, so the element keeps it.
702                // With add-path, bytes 6..10 hold the path id; the element keeps the record's prefix.
703                let attr_len =
704                    u16::from_be_bytes([data[header_len - 2], data[header_len - 1]]) as usize;
705                let end = header_len + attr_len;
706                if data.len() < end {
707                    warn!(
708                        "early break due to error Truncated message: not enough bytes to read. remaining: {}, required: {} while parsing RIB AFI entries",
709                        data.len() - header_len,
710                        attr_len
711                    );
712                    *remaining = 0;
713                    return None;
714                }
715                let attrs = &data[header_len..end];
716                *data = &data[end..];
717                *remaining -= 1;
718                let Some(peer) = peers.get(peer_index as usize) else {
719                    error!("peer ID {} not found in peer_index table", peer_index);
720                    *remaining = 0;
721                    return None;
722                };
723                // One walk decides both questions: whether the record survives (an unreadable header
724                // fails it, as it does on the owned path) and where its attributes end (a value that
725                // runs past the block stops the decode there, which is what the owned walker does
726                // with the attributes it already read).
727                let (usable_len, truncated) = match scan_attr_block(attrs) {
728                    AttrBlockScan::Usable {
729                        usable_len,
730                        truncated,
731                    } => (
732                        usable_len,
733                        truncated.map(|(code, declared, available)| {
734                            (code, declared as u16, available as u32)
735                        }),
736                    ),
737                    AttrBlockScan::Unreadable => {
738                        *remaining = 0;
739                        return None;
740                    }
741                };
742                Some(ElemRef::new(
743                    *prefix,
744                    peer,
745                    originated_time,
746                    *flags,
747                    &attrs[..usable_len],
748                    truncated,
749                ))
750            }
751            IterSource::Update {
752                entries,
753                attrs,
754                peer_ip,
755                peer_asn,
756                timestamp,
757                next,
758                next_hop,
759            } => {
760                let entry = entries.get(*next)?;
761                *next += 1;
762                // A withdrawal carries no attributes, exactly as the owned path leaves them unset.
763                let attr_bytes: &[u8] = match entry.elem_type {
764                    ElemType::ANNOUNCE => attrs,
765                    ElemType::WITHDRAW => &[],
766                };
767                Some(ElemRef::new_update(
768                    entry, *peer_ip, *peer_asn, *timestamp, attr_bytes, *next_hop,
769                ))
770            }
771        }
772    }
773
774    #[inline]
775    fn size_hint(&self) -> (usize, Option<usize>) {
776        let remaining = match &self.source {
777            IterSource::Rib { remaining, .. } => *remaining as usize,
778            IterSource::Update { entries, next, .. } => entries.len().saturating_sub(*next),
779        };
780        (0, Some(remaining))
781    }
782}
783
784/// Whether a 4-byte-ASN `AS_PATH` / `AS4_PATH` attribute payload is well formed.
785///
786/// The owned segment parser decides this: a segment type it rejects, or a count that runs past the
787/// payload, fails there exactly as it must here.
788fn validate_as_path_wire(wire: &[u8]) -> bool {
789    crate::parser::bgp::attributes::validate_as_path_slice(wire, &AsnLength::Bits32)
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795
796    #[test]
797    fn test_bytes_as_be_u32_words_alignment_and_length_check() {
798        // Unaligned subslice (offset 1) with valid multiple-of-4 length decodes big-endian u32s.
799        let backing = [0xAA, 0x00, 0x00, 0xFD, 0xE8, 0xFF, 0xFF, 0xFF, 0x01];
800        let unaligned = &backing[1..9];
801        let words = bytes_as_be_u32_words(unaligned);
802        assert_eq!(words.len(), 2);
803        assert_eq!(words[0].get(), 65_000);
804        // NO_EXPORT, written out because the wire value belongs to the attribute module.
805        assert_eq!(words[1].get(), 0xFFFF_FF01);
806
807        // Non-multiple-of-4 length is rejected cleanly as empty rather than panicking.
808        assert!(bytes_as_be_u32_words(&backing[1..8]).is_empty());
809        assert!(bytes_as_be_u32_words(&[]).is_empty());
810    }
811}
812
813#[cfg(test)]
814mod materialise_tests {
815    use super::*;
816
817    /// A real TABLE_DUMP_V2 slice: one PEER_INDEX_TABLE followed by 399 RIB records.
818    const RIB_FIXTURE: &str = "tests/fixtures/routeviews/bview.slice.gz";
819
820    /// The borrowed view serves updates as well as dumps, and must produce the same elements the
821    /// owned record path produces for the same file.
822    #[test]
823    fn borrowed_update_elems_match_owned_elems() {
824        // A 15-minute RIPE update file: BGP4MP messages with 4-byte AS numbers.
825        let fixture = "tests/fixtures/ripe/rrc15/2010.02/updates.20100227.1600.gz";
826        // The borrowed view serves the AS4 message subtypes; the fixture also carries 2-byte ASN
827        // records from 2010, which stay on the owned path and are excluded from the comparison.
828        let (owned, legacy_records): (Vec<_>, usize) = {
829            let mut elementor = crate::parser::mrt::mrt_elem::Elementor::new();
830            let mut owned = Vec::new();
831            let mut legacy = 0;
832            for record in BgpkitParser::new(fixture)
833                .expect("open fixture")
834                .into_record_iter()
835            {
836                if !matches!(record.common_header.entry_subtype, 4 | 5 | 9 | 10) {
837                    legacy += 1;
838                    continue;
839                }
840                owned.extend(elementor.record_to_elems(record));
841            }
842            (owned, legacy)
843        };
844        assert!(!owned.is_empty(), "fixture produced no elems");
845        assert!(
846            legacy_records > 0,
847            "fixture should exercise the 2-byte skip"
848        );
849
850        let mut parser = BgpkitParser::new(fixture).expect("open fixture");
851        let mut borrowed = Vec::new();
852        while let Some(record) = parser.next_record_elems() {
853            assert!(!record.is_empty(), "an update record declared no elements");
854            for elem in record.iter() {
855                borrowed.push(elem.to_bgp_elem());
856            }
857        }
858        assert_eq!(owned.len(), borrowed.len(), "element count differs");
859        for (index, (owned_elem, borrowed_elem)) in owned.iter().zip(&borrowed).enumerate() {
860            assert_eq!(owned_elem, borrowed_elem, "element {index} differs");
861        }
862    }
863
864    /// Every field of a materialised element must equal what the owned record path produces for
865    /// the same entry. The reference is the record iterator plus `Elementor`, not `into_elem_iter`,
866    /// which now goes through this same borrowed engine.
867    #[test]
868    fn borrowed_elems_match_owned_elems() {
869        let owned: Vec<_> = {
870            let mut elementor = crate::parser::mrt::mrt_elem::Elementor::new();
871            BgpkitParser::new(RIB_FIXTURE)
872                .expect("open fixture")
873                .into_record_iter()
874                .flat_map(|record| elementor.record_to_elems(record))
875                .collect()
876        };
877        assert!(!owned.is_empty(), "fixture produced no elems");
878
879        let mut parser = BgpkitParser::new(RIB_FIXTURE).expect("open fixture");
880        let mut borrowed = Vec::new();
881        while let Some(record) = parser.next_record_elems() {
882            for elem in record.iter() {
883                borrowed.push(elem.to_bgp_elem());
884            }
885        }
886
887        assert_eq!(owned.len(), borrowed.len(), "element count differs");
888        for (index, (owned_elem, borrowed_elem)) in owned.iter().zip(borrowed.iter()).enumerate() {
889            assert_eq!(owned_elem, borrowed_elem, "elem {index} differs");
890        }
891    }
892}
893
894#[cfg(test)]
895mod wire_parity_tests {
896    use crate::models::*;
897    use std::io::Cursor;
898    use std::str::FromStr;
899
900    /// Wrap a BGP4MP body in an MRT common header.
901    fn mrt(subtype: Bgp4MpType, body: Vec<u8>) -> Vec<u8> {
902        let mut wire = Vec::new();
903        wire.extend_from_slice(&1_600_000_000u32.to_be_bytes());
904        wire.extend_from_slice(&(EntryType::BGP4MP as u16).to_be_bytes());
905        wire.extend_from_slice(&(subtype as u16).to_be_bytes());
906        wire.extend_from_slice(&(body.len() as u32).to_be_bytes());
907        wire.extend_from_slice(&body);
908        wire
909    }
910
911    /// A BGP4MP message body: envelope, then a BGP message of the given type.
912    fn bgp4mp_body(asn_len: AsnLength, afi: Afi, msg_type: u8, payload: &[u8]) -> Vec<u8> {
913        let mut body = Vec::new();
914        match asn_len {
915            AsnLength::Bits16 => {
916                body.extend_from_slice(&64496u16.to_be_bytes());
917                body.extend_from_slice(&64497u16.to_be_bytes());
918            }
919            AsnLength::Bits32 => {
920                body.extend_from_slice(&64496u32.to_be_bytes());
921                body.extend_from_slice(&64497u32.to_be_bytes());
922            }
923        }
924        body.extend_from_slice(&0u16.to_be_bytes());
925        body.extend_from_slice(&u16::from(afi).to_be_bytes());
926        match afi {
927            Afi::Ipv4 => {
928                body.extend_from_slice(&[192, 0, 2, 1]);
929                body.extend_from_slice(&[192, 0, 2, 2]);
930            }
931            Afi::Ipv6 => {
932                body.extend_from_slice(&[
933                    0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
934                ]);
935                body.extend_from_slice(&[
936                    0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
937                ]);
938            }
939            other => panic!("test does not build BGP4MP records for {other:?}"),
940        }
941        let mut message = vec![0xFF; 16];
942        message.extend_from_slice(&((19 + payload.len()) as u16).to_be_bytes());
943        message.push(msg_type);
944        message.extend_from_slice(payload);
945        body.extend_from_slice(&message);
946        body
947    }
948
949    /// An UPDATE payload: withdrawn NLRI, attribute block, announced NLRI.
950    fn update_payload(withdrawn: &[u8], attributes: &[u8], announced: &[u8]) -> Vec<u8> {
951        let mut payload = Vec::new();
952        payload.extend_from_slice(&(withdrawn.len() as u16).to_be_bytes());
953        payload.extend_from_slice(withdrawn);
954        payload.extend_from_slice(&(attributes.len() as u16).to_be_bytes());
955        payload.extend_from_slice(attributes);
956        payload.extend_from_slice(announced);
957        payload
958    }
959
960    /// One path attribute with a one-octet length. Optional attributes need the optional bit, or
961    /// the parser treats the flag byte as a validation finding and drops the attribute.
962    fn attr(code: u8, body: &[u8]) -> Vec<u8> {
963        let optional = matches!(code, 14 | 15);
964        let flags = if optional { 0x80 } else { 0x40 };
965        let mut out = vec![flags, code, body.len() as u8];
966        out.extend_from_slice(body);
967        out
968    }
969
970    fn origin_igp() -> Vec<u8> {
971        attr(1, &[0])
972    }
973
974    fn next_hop() -> Vec<u8> {
975        attr(3, &[192, 0, 2, 254])
976    }
977
978    /// AS_SEQUENCE of length zero followed by a real one: the owned renderer writes a separator for
979    /// the empty segment, so a view that skipped it would compare positions differently.
980    fn as_path_with_empty_segment() -> Vec<u8> {
981        let mut body = vec![2u8, 0];
982        body.extend_from_slice(&[2u8, 2]);
983        body.extend_from_slice(&3356u32.to_be_bytes());
984        body.extend_from_slice(&174u32.to_be_bytes());
985        attr(2, &body)
986    }
987
988    fn as_path(asns: &[u32], width: AsnLength) -> Vec<u8> {
989        let mut body = vec![2u8, asns.len() as u8];
990        for asn in asns {
991            match width {
992                AsnLength::Bits16 => body.extend_from_slice(&(*asn as u16).to_be_bytes()),
993                AsnLength::Bits32 => body.extend_from_slice(&asn.to_be_bytes()),
994            }
995        }
996        attr(2, &body)
997    }
998
999    /// MP_UNREACH_NLRI for AFI 1, SAFI 4 (labelled unicast): one NLRI whose first 24 of 48 bits are
1000    /// the compatibility field, leaving 203.0.113.0/24.
1001    fn labelled_withdrawal_attr() -> Vec<u8> {
1002        let mut body = Vec::new();
1003        body.extend_from_slice(&1u16.to_be_bytes());
1004        body.push(4);
1005        body.push(48);
1006        body.extend_from_slice(&[0x00, 0x01, 0x02]);
1007        body.extend_from_slice(&[203, 0, 113]);
1008        attr(15, &body)
1009    }
1010
1011    /// A one-octet NLRI encoding of an IPv4 prefix.
1012    fn nlri(prefix: &str) -> Vec<u8> {
1013        let network = NetworkPrefix::from_str(prefix).expect("parse prefix");
1014        let bits = network.prefix.prefix_len();
1015        let mut out = vec![bits];
1016        match network.prefix {
1017            ipnet::IpNet::V4(v4) => {
1018                let octets = v4.addr().octets();
1019                out.extend_from_slice(&octets[..usize::from(bits).div_ceil(8)]);
1020            }
1021            ipnet::IpNet::V6(_) => panic!("test builds IPv4 NLRI here"),
1022        }
1023        out
1024    }
1025
1026    fn owned_elems(wire: &[u8]) -> Vec<BgpElem> {
1027        crate::BgpkitParser::from_reader(Cursor::new(wire.to_vec()))
1028            .into_elem_iter()
1029            .collect()
1030    }
1031
1032    fn borrowed_elems(wire: &[u8]) -> Vec<BgpElem> {
1033        let mut parser = crate::BgpkitParser::from_reader(Cursor::new(wire.to_vec()));
1034        let mut elems = Vec::new();
1035        while let Some(record) = parser.next_record_elems() {
1036            for elem in &record {
1037                elems.push(elem.to_bgp_elem());
1038            }
1039        }
1040        elems
1041    }
1042
1043    /// Wrap a body in an MRT header of an explicit entry type and subtype.
1044    fn mrt_typed(entry: EntryType, subtype: u16, body: Vec<u8>) -> Vec<u8> {
1045        let mut wire = Vec::new();
1046        wire.extend_from_slice(&1_600_000_000u32.to_be_bytes());
1047        wire.extend_from_slice(&(entry as u16).to_be_bytes());
1048        wire.extend_from_slice(&subtype.to_be_bytes());
1049        wire.extend_from_slice(&(body.len() as u32).to_be_bytes());
1050        wire.extend_from_slice(&body);
1051        wire
1052    }
1053
1054    /// A `PEER_INDEX_TABLE` record with one peer, then one `RIB_AFI` record for the prefix, mirroring
1055    /// what a dump carries.
1056    fn rib_record(
1057        rib_subtype: u16,
1058        prefix_len: u8,
1059        prefix_bytes: &[u8],
1060        attributes: &[u8],
1061    ) -> Vec<u8> {
1062        let mut peer_table = Vec::new();
1063        peer_table.extend_from_slice(&[192, 0, 2, 10]); // collector BGP id
1064        peer_table.extend_from_slice(&0u16.to_be_bytes()); // empty view name
1065        peer_table.extend_from_slice(&1u16.to_be_bytes()); // one peer
1066        peer_table.push(0); // peer type
1067        peer_table.extend_from_slice(&[192, 0, 2, 20]); // peer BGP id
1068        peer_table.extend_from_slice(&[192, 0, 2, 30]); // peer address
1069        peer_table.extend_from_slice(&64496u32.to_be_bytes()); // peer ASN
1070        let mut wire = mrt_typed(
1071            EntryType::TABLE_DUMP_V2,
1072            TableDumpV2Type::PeerIndexTable as u16,
1073            peer_table,
1074        );
1075
1076        let mut body = Vec::new();
1077        body.extend_from_slice(&1u32.to_be_bytes()); // sequence number
1078        body.push(prefix_len);
1079        body.extend_from_slice(prefix_bytes);
1080        body.extend_from_slice(&1u16.to_be_bytes()); // one entry
1081        body.extend_from_slice(&0u16.to_be_bytes()); // peer index
1082        body.extend_from_slice(&1_600_000_000u32.to_be_bytes()); // originated time
1083        body.extend_from_slice(&(attributes.len() as u16).to_be_bytes());
1084        body.extend_from_slice(attributes);
1085        wire.extend_from_slice(&mrt_typed(EntryType::TABLE_DUMP_V2, rib_subtype, body));
1086        wire
1087    }
1088
1089    /// Both paths must produce the same elements for a shape that is legal but rare in real traffic.
1090    fn assert_same(wire: &[u8]) -> Vec<BgpElem> {
1091        let owned = owned_elems(wire);
1092        let borrowed = borrowed_elems(wire);
1093        assert_eq!(owned, borrowed, "owned and borrowed elements differ");
1094        owned
1095    }
1096
1097    #[test]
1098    fn empty_as_path_segment() {
1099        let attributes: Vec<u8> = [origin_igp(), as_path_with_empty_segment(), next_hop()].concat();
1100        let wire = mrt(
1101            Bgp4MpType::MessageAs4,
1102            bgp4mp_body(
1103                AsnLength::Bits32,
1104                Afi::Ipv4,
1105                2,
1106                &update_payload(&[], &attributes, &nlri("198.51.100.0/24")),
1107            ),
1108        );
1109        let elems = assert_same(&wire);
1110        assert_eq!(elems.len(), 1);
1111        let rendered = elems[0].as_path.as_ref().map(|path| path.to_string());
1112        assert!(
1113            rendered
1114                .as_deref()
1115                .is_some_and(|path| path.contains(" 3356 174")),
1116            "as_path was {rendered:?}"
1117        );
1118    }
1119
1120    #[test]
1121    fn labelled_withdrawal() {
1122        let attributes: Vec<u8> = [
1123            origin_igp(),
1124            as_path(&[3356, 174], AsnLength::Bits32),
1125            labelled_withdrawal_attr(),
1126        ]
1127        .concat();
1128        let wire = mrt(
1129            Bgp4MpType::MessageAs4,
1130            bgp4mp_body(
1131                AsnLength::Bits32,
1132                Afi::Ipv4,
1133                2,
1134                &update_payload(&[], &attributes, &[]),
1135            ),
1136        );
1137        let elems = assert_same(&wire);
1138        assert_eq!(elems.len(), 1);
1139        assert_eq!(elems[0].prefix.prefix.to_string(), "203.0.113.0/24");
1140        assert_eq!(elems[0].elem_type, ElemType::WITHDRAW);
1141    }
1142
1143    /// A dump's `NEXT_HOP` is encoded with the record's family, so an IPv6 entry carries sixteen
1144    /// bytes. Reading it as IPv4 would report the first four octets as the next hop.
1145    #[test]
1146    fn ipv6_dump_entry_reads_a_sixteen_byte_next_hop() {
1147        let next_hop = [0x20u8, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
1148        let attributes: Vec<u8> = [
1149            origin_igp(),
1150            as_path(&[3356, 174], AsnLength::Bits32),
1151            attr(3, &next_hop),
1152        ]
1153        .concat();
1154        // RIB_IPV6_UNICAST, 2001:db8::/32
1155        let wire = rib_record(4, 32, &[0x20, 0x01, 0x0d, 0xb8], &attributes);
1156        let elems = assert_same(&wire);
1157        assert_eq!(elems.len(), 1);
1158        assert_eq!(elems[0].next_hop, Some("2001:db8::1".parse().unwrap()));
1159    }
1160
1161    /// The prefix accessor must carry the ADD-PATH identifier the record declared.
1162    #[test]
1163    fn add_path_identifier_survives_the_prefix_accessor() {
1164        let attributes: Vec<u8> = [
1165            origin_igp(),
1166            as_path(&[3356, 174], AsnLength::Bits32),
1167            next_hop(),
1168        ]
1169        .concat();
1170        let mut announced = 7u32.to_be_bytes().to_vec();
1171        announced.extend_from_slice(&nlri("203.0.113.0/24"));
1172        let wire = mrt(
1173            Bgp4MpType::MessageAs4Addpath,
1174            bgp4mp_body(
1175                AsnLength::Bits32,
1176                Afi::Ipv4,
1177                2,
1178                &update_payload(&[], &attributes, &announced),
1179            ),
1180        );
1181        let elems = assert_same(&wire);
1182        assert_eq!(elems.len(), 1);
1183        assert_eq!(elems[0].prefix.path_id, Some(7));
1184
1185        let mut parser = crate::BgpkitParser::from_reader(Cursor::new(wire));
1186        let mut seen = 0;
1187        while let Some(record) = parser.next_record_elems() {
1188            for elem in &record {
1189                assert_eq!(elem.prefix().path_id, Some(7));
1190                seen += 1;
1191            }
1192        }
1193        assert_eq!(seen, 1);
1194    }
1195
1196    /// A 2-byte-ASN BGP4MP record is outside the borrowed view's scope: it produces no elements
1197    /// there while the owned path parses it. This pins the documented boundary.
1198    #[test]
1199    fn two_byte_asn_record_is_not_served_by_the_view() {
1200        let attributes: Vec<u8> = [
1201            origin_igp(),
1202            as_path(&[3356, 174], AsnLength::Bits16),
1203            next_hop(),
1204        ]
1205        .concat();
1206        let wire = mrt(
1207            Bgp4MpType::Message,
1208            bgp4mp_body(
1209                AsnLength::Bits16,
1210                Afi::Ipv4,
1211                2,
1212                &update_payload(&[], &attributes, &nlri("198.51.100.0/24")),
1213            ),
1214        );
1215        assert_eq!(owned_elems(&wire).len(), 1);
1216        assert!(borrowed_elems(&wire).is_empty());
1217    }
1218
1219    /// An IPv6 announcement in a record that also carries an IPv4 NEXT_HOP: the owned path prefers
1220    /// the attribute, so the view must read it as IPv4 rather than with the entry's family.
1221    #[test]
1222    fn ipv6_announcement_with_ipv4_next_hop_attribute() {
1223        let mut mp_reach = Vec::new();
1224        mp_reach.extend_from_slice(&2u16.to_be_bytes());
1225        mp_reach.push(1);
1226        mp_reach.push(16);
1227        mp_reach.extend_from_slice(&[
1228            0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xfe,
1229        ]);
1230        mp_reach.push(0);
1231        mp_reach.push(32);
1232        mp_reach.extend_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
1233        let attributes: Vec<u8> = [
1234            origin_igp(),
1235            as_path(&[3356, 174], AsnLength::Bits32),
1236            next_hop(),
1237            attr(14, &mp_reach),
1238        ]
1239        .concat();
1240        let wire = mrt(
1241            Bgp4MpType::MessageAs4,
1242            bgp4mp_body(
1243                AsnLength::Bits32,
1244                Afi::Ipv4,
1245                2,
1246                &update_payload(&[], &attributes, &[]),
1247            ),
1248        );
1249        let elems = assert_same(&wire);
1250        assert_eq!(elems.len(), 1);
1251        assert_eq!(elems[0].next_hop, Some("192.0.2.254".parse().unwrap()));
1252    }
1253}