Skip to main content

bgpkit_parser/parser/mrt/
mrt_elem.rs

1//! This module handles converting MRT records into individual per-prefix BGP elements.
2//!
3//! Each MRT record may contain reachability information for multiple prefixes. This module breaks
4//! down MRT records into corresponding BGP elements, and thus allowing users to more conveniently
5//! process BGP information on a per-prefix basis.
6use crate::models::*;
7use crate::ParserError;
8use crate::ParserError::ParseError;
9use log::error;
10use std::fmt::{Display, Formatter};
11use std::net::{IpAddr, Ipv4Addr};
12
13#[derive(Default, Debug, Clone)]
14pub struct Elementor {
15    pub peer_table: Option<PeerIndexTable>,
16}
17
18/// Error returned by [`Elementor::record_to_elems_iter`].
19#[derive(Debug)]
20pub enum ElemError {
21    /// The record contains a [`PeerIndexTable`]. The contained table can be
22    /// passed to [`Elementor::with_peer_table`] to create an initialized elementor.
23    UnexpectedPeerIndexTable(Box<PeerIndexTable>),
24    /// A peer table is required for processing TableDumpV2 RIB entries,
25    /// but none has been set on this elementor.
26    MissingPeerTable,
27    /// The record contains a [`RibGenericEntries`] which is not yet supported.
28    UnsupportedRibGeneric,
29}
30
31impl Display for ElemError {
32    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
33        match self {
34            ElemError::UnexpectedPeerIndexTable(_) => {
35                write!(f, "unexpected PeerIndexTable record")
36            }
37            ElemError::MissingPeerTable => {
38                write!(
39                    f,
40                    "peer table not set; call set_peer_table or use with_peer_table first"
41                )
42            }
43            ElemError::UnsupportedRibGeneric => {
44                write!(f, "RibGenericEntries not yet supported")
45            }
46        }
47    }
48}
49
50impl std::error::Error for ElemError {}
51
52/// The attribute values an elem is built from, taken out of an [`Attributes`] set.
53struct RelevantAttributes {
54    as_path: Option<AsPath>,
55    as4_path: Option<AsPath>,
56    origin: Option<Origin>,
57    next_hop: Option<IpAddr>,
58    local_pref: Option<u32>,
59    med: Option<u32>,
60    communities: Option<Vec<MetaCommunity>>,
61    atomic: bool,
62    aggregator: Option<(Asn, BgpIdentifier)>,
63    announced_prefixes: Vec<NetworkPrefix>,
64    withdrawn_prefixes: Vec<NetworkPrefix>,
65    only_to_customer: Option<Asn>,
66    unknown: Option<Vec<AttrRaw>>,
67    deprecated: Option<Vec<AttrRaw>>,
68}
69
70impl RelevantAttributes {
71    /// The effective AS path: AS_PATH merged with AS4_PATH when both are present (RFC 6793).
72    fn path(&mut self) -> Option<AsPath> {
73        match (self.as_path.take(), self.as4_path.take()) {
74            (None, None) => None,
75            (Some(v), None) => Some(v),
76            (None, Some(v)) => Some(v),
77            (Some(v1), Some(v2)) => Some(AsPath::merge_aspath_as4path(&v1, &v2)),
78        }
79    }
80}
81
82/// Take the values an elem needs out of `attributes`.
83///
84/// The values are moved out of the attribute list in place rather than by consuming it, which
85/// avoids copying every (large) [`AttributeValue`] once more on the way through.
86fn get_relevant_attributes(mut attributes: Attributes) -> RelevantAttributes {
87    let mut as_path = None;
88    let mut as4_path = None;
89    let mut origin = None;
90    let mut next_hop = None;
91    let mut local_pref = Some(0);
92    let mut med = Some(0);
93    let mut atomic = false;
94    let mut aggregator = None;
95    let mut announced_prefixes = Vec::new();
96    let mut announced_next_hop = None;
97    let mut withdrawn_prefixes = Vec::new();
98    let mut otc = None;
99    let mut unknown = vec![];
100    let mut deprecated = vec![];
101
102    let mut communities_vec: Vec<MetaCommunity> = vec![];
103
104    let take_raw = |t: &mut AttrRaw| AttrRaw {
105        code: t.code,
106        bytes: std::mem::take(&mut t.bytes),
107    };
108
109    for attr in attributes.inner.iter_mut() {
110        match &mut attr.value {
111            AttributeValue::Origin(v) => origin = Some(*v),
112            AttributeValue::AsPath(path) => as_path = Some(std::mem::take(path)),
113            AttributeValue::As4Path(path) => as4_path = Some(std::mem::take(path)),
114            AttributeValue::NextHop(v) => next_hop = Some(*v),
115            AttributeValue::MultiExitDiscriminator(v) => med = Some(*v),
116            AttributeValue::LocalPreference(v) => local_pref = Some(*v),
117            AttributeValue::AtomicAggregate => atomic = true,
118            AttributeValue::Communities(v) => {
119                communities_vec.extend(v.drain(..).map(MetaCommunity::Plain))
120            }
121            AttributeValue::ExtendedCommunities(v) => {
122                communities_vec.extend(v.drain(..).map(MetaCommunity::Extended))
123            }
124            AttributeValue::Ipv6AddressSpecificExtendedCommunities(v) => {
125                communities_vec.extend(v.drain(..).map(MetaCommunity::Ipv6Extended))
126            }
127            AttributeValue::LargeCommunities(v) => {
128                communities_vec.extend(v.drain(..).map(MetaCommunity::Large))
129            }
130            AttributeValue::Aggregator { asn, id } | AttributeValue::As4Aggregator { asn, id } => {
131                aggregator = Some((*asn, *id))
132            }
133            AttributeValue::MpReachNlri(nlri) => {
134                announced_prefixes = std::mem::take(&mut nlri.prefixes);
135                announced_next_hop = nlri.next_hop.as_ref().map(NextHopAddress::global_addr);
136            }
137            AttributeValue::MpUnreachNlri(nlri) => {
138                withdrawn_prefixes = std::mem::take(&mut nlri.prefixes)
139            }
140            AttributeValue::OnlyToCustomer(o) => otc = Some(*o),
141
142            AttributeValue::Unknown(t) | AttributeValue::Raw(t) => {
143                unknown.push(take_raw(t));
144            }
145            AttributeValue::Deprecated(t) => {
146                deprecated.push(take_raw(t));
147            }
148
149            AttributeValue::OriginatorId(_)
150            | AttributeValue::Clusters(_)
151            | AttributeValue::Development(_)
152            | AttributeValue::LinkState(_)
153            | AttributeValue::TunnelEncapsulation(_)
154            | AttributeValue::TrafficEngineering(_)
155            | AttributeValue::Aigp(_)
156            | AttributeValue::DomainPath(_)
157            | AttributeValue::BfdDiscriminator(_)
158            | AttributeValue::BgpPrefixSid(_)
159            | AttributeValue::Bier(_)
160            | AttributeValue::Sfp(_)
161            | AttributeValue::AttrSet(_) => {}
162        };
163    }
164
165    let communities = match !communities_vec.is_empty() {
166        true => Some(communities_vec),
167        false => None,
168    };
169
170    RelevantAttributes {
171        as_path,
172        as4_path,
173        origin,
174        // If the next_hop is not set, we try to get it from the announced NLRI.
175        next_hop: next_hop.or(announced_next_hop),
176        local_pref,
177        med,
178        communities,
179        atomic,
180        aggregator,
181        announced_prefixes,
182        withdrawn_prefixes,
183        only_to_customer: otc,
184        unknown: if unknown.is_empty() {
185            None
186        } else {
187            Some(unknown)
188        },
189        deprecated: if deprecated.is_empty() {
190            None
191        } else {
192            Some(deprecated)
193        },
194    }
195}
196
197fn rib_entry_to_elem(prefix: NetworkPrefix, peer: &Peer, entry: RibEntry) -> BgpElem {
198    let mut attrs = get_relevant_attributes(entry.attributes);
199    let path = attrs.path();
200
201    let origin_asns = path
202        .as_ref()
203        .map(|as_path| as_path.iter_origins().collect());
204
205    BgpElem {
206        timestamp: entry.originated_time as f64,
207        elem_type: ElemType::ANNOUNCE,
208        peer_ip: peer.peer_ip,
209        peer_asn: peer.peer_asn,
210        peer_bgp_id: Some(peer.peer_bgp_id),
211        prefix,
212        next_hop: attrs.next_hop,
213        as_path: path,
214        origin: attrs.origin,
215        origin_asns,
216        local_pref: attrs.local_pref,
217        med: attrs.med,
218        communities: attrs.communities,
219        atomic: attrs.atomic,
220        aggr_asn: attrs.aggregator.map(|v| v.0),
221        aggr_ip: attrs.aggregator.map(|v| v.1),
222        only_to_customer: attrs.only_to_customer,
223        unknown: attrs.unknown,
224        deprecated: attrs.deprecated,
225    }
226}
227
228/// Iterator over [`BgpElem`]s produced from a single [`MrtRecord`],
229/// without requiring a mutable reference to the [`Elementor`].
230///
231/// This avoids allocating a `Vec` for the common RIB table dump case
232/// by lazily converting each [`RibEntry`] into a [`BgpElem`] on demand.
233pub enum RecordElemIter<'a> {
234    #[doc(hidden)]
235    Empty,
236    #[doc(hidden)]
237    TableDump(Option<BgpElem>),
238    #[doc(hidden)]
239    TableDumpBatch(std::vec::IntoIter<TableDumpMessage>),
240    #[doc(hidden)]
241    RibAfi {
242        peer_table: &'a PeerIndexTable,
243        prefix: NetworkPrefix,
244        entries: std::vec::IntoIter<RibEntry>,
245    },
246    #[doc(hidden)]
247    Bgp4Mp(BgpUpdateElemIter),
248}
249
250/// Convert the next RIB entry into an elem.
251///
252/// `Err` means the entry names a peer the table does not have; iteration over the record stops
253/// there.
254fn next_rib_elem(
255    peer_table: &PeerIndexTable,
256    prefix: NetworkPrefix,
257    entries: &mut std::vec::IntoIter<RibEntry>,
258) -> Result<Option<BgpElem>, ()> {
259    let Some(entry) = entries.next() else {
260        return Ok(None);
261    };
262    let pid = entry.peer_index;
263    match peer_table.get_peer_by_id(&pid) {
264        Some(peer) => Ok(Some(rib_entry_to_elem(prefix, peer, entry))),
265        None => {
266            error!("peer ID {} not found in peer_index table", pid);
267            Err(())
268        }
269    }
270}
271
272/// The elems a record has yet to yield, without a borrow of the peer table.
273///
274/// This is [`RecordElemIter`] with the peer table passed to each
275/// [`next_elem`](PendingElems::next_elem) call instead of held, so an iterator that owns an
276/// [`Elementor`] can keep one next to it and stream elems instead of collecting them.
277pub(crate) enum PendingElems {
278    Empty,
279    TableDump(Option<BgpElem>),
280    TableDumpBatch(std::vec::IntoIter<TableDumpMessage>),
281    RibAfi {
282        prefix: NetworkPrefix,
283        entries: std::vec::IntoIter<RibEntry>,
284    },
285    Bgp4Mp(BgpUpdateElemIter),
286}
287
288impl PendingElems {
289    /// The next elem, given the peer table of the [`Elementor`] that produced these elems.
290    pub(crate) fn next_elem(&mut self, peer_table: Option<&PeerIndexTable>) -> Option<BgpElem> {
291        match self {
292            PendingElems::Empty => None,
293            PendingElems::TableDump(elem) => elem.take(),
294            PendingElems::TableDumpBatch(entries) => entries.next().map(table_dump_to_elem),
295            PendingElems::Bgp4Mp(iter) => iter.next(),
296            PendingElems::RibAfi { prefix, entries } => {
297                // a RIB record only becomes pending while a peer table is set
298                let next = peer_table
299                    .ok_or(())
300                    .and_then(|t| next_rib_elem(t, *prefix, entries));
301                next.unwrap_or_else(|()| {
302                    *self = PendingElems::Empty;
303                    None
304                })
305            }
306        }
307    }
308}
309
310impl Iterator for RecordElemIter<'_> {
311    type Item = BgpElem;
312
313    fn next(&mut self) -> Option<BgpElem> {
314        match self {
315            RecordElemIter::Empty => None,
316            RecordElemIter::TableDump(elem) => elem.take(),
317            RecordElemIter::TableDumpBatch(entries) => entries.next().map(table_dump_to_elem),
318            RecordElemIter::Bgp4Mp(iter) => iter.next(),
319            RecordElemIter::RibAfi {
320                peer_table,
321                prefix,
322                entries,
323            } => next_rib_elem(peer_table, *prefix, entries).unwrap_or_else(|()| {
324                *self = RecordElemIter::Empty;
325                None
326            }),
327        }
328    }
329
330    fn size_hint(&self) -> (usize, Option<usize>) {
331        match self {
332            RecordElemIter::Empty => (0, Some(0)),
333            RecordElemIter::TableDump(elem) => {
334                let n = elem.is_some() as usize;
335                (n, Some(n))
336            }
337            RecordElemIter::TableDumpBatch(entries) => {
338                let len = entries.len();
339                (len, Some(len))
340            }
341            RecordElemIter::Bgp4Mp(iter) => iter.size_hint(),
342            RecordElemIter::RibAfi { entries, .. } => {
343                let len = entries.len();
344                (len, Some(len))
345            }
346        }
347    }
348}
349
350/// Iterator over [`BgpElem`]s produced from a [`BgpUpdateMessage`],
351/// avoiding allocation by lazily yielding elements from announced and
352/// withdrawn prefixes in two phases.
353pub struct BgpUpdateElemIter {
354    timestamp: f64,
355    peer_ip: IpAddr,
356    peer_asn: Asn,
357    peer_bgp_id: Option<BgpIdentifier>,
358    only_to_customer: Option<Asn>,
359    // Announce-specific shared attributes
360    path: Option<AsPath>,
361    origin_asns: Option<Vec<Asn>>,
362    origin: Option<Origin>,
363    next_hop: Option<IpAddr>,
364    local_pref: Option<u32>,
365    med: Option<u32>,
366    communities: Option<Vec<MetaCommunity>>,
367    atomic: bool,
368    aggr_asn: Option<Asn>,
369    aggr_ip: Option<BgpIdentifier>,
370    unknown: Option<Vec<AttrRaw>>,
371    deprecated: Option<Vec<AttrRaw>>,
372    // Prefix iterators (two chained sources each)
373    announced:
374        std::iter::Chain<std::vec::IntoIter<NetworkPrefix>, std::vec::IntoIter<NetworkPrefix>>,
375    withdrawn:
376        std::iter::Chain<std::vec::IntoIter<NetworkPrefix>, std::vec::IntoIter<NetworkPrefix>>,
377    in_withdrawn_phase: bool,
378}
379
380impl Iterator for BgpUpdateElemIter {
381    type Item = BgpElem;
382
383    fn next(&mut self) -> Option<BgpElem> {
384        if !self.in_withdrawn_phase {
385            if let Some(prefix) = self.announced.next() {
386                // The shared attributes are only used for announcements, so the last one can
387                // take them instead of cloning, which saves every clone for a single-prefix UPDATE.
388                let last = self.announced.size_hint().1 == Some(0);
389                let (as_path, origin_asns, communities, unknown, deprecated) = if last {
390                    (
391                        self.path.take(),
392                        self.origin_asns.take(),
393                        self.communities.take(),
394                        self.unknown.take(),
395                        self.deprecated.take(),
396                    )
397                } else {
398                    (
399                        self.path.clone(),
400                        self.origin_asns.clone(),
401                        self.communities.clone(),
402                        self.unknown.clone(),
403                        self.deprecated.clone(),
404                    )
405                };
406                return Some(BgpElem {
407                    timestamp: self.timestamp,
408                    elem_type: ElemType::ANNOUNCE,
409                    peer_ip: self.peer_ip,
410                    peer_asn: self.peer_asn,
411                    peer_bgp_id: self.peer_bgp_id,
412                    prefix,
413                    next_hop: self.next_hop,
414                    as_path,
415                    origin: self.origin,
416                    origin_asns,
417                    local_pref: self.local_pref,
418                    med: self.med,
419                    communities,
420                    atomic: self.atomic,
421                    aggr_asn: self.aggr_asn,
422                    aggr_ip: self.aggr_ip,
423                    only_to_customer: self.only_to_customer,
424                    unknown,
425                    deprecated,
426                });
427            }
428            self.in_withdrawn_phase = true;
429        }
430
431        self.withdrawn.next().map(|prefix| BgpElem {
432            timestamp: self.timestamp,
433            elem_type: ElemType::WITHDRAW,
434            peer_ip: self.peer_ip,
435            peer_asn: self.peer_asn,
436            peer_bgp_id: self.peer_bgp_id,
437            prefix,
438            next_hop: None,
439            as_path: None,
440            origin: None,
441            origin_asns: None,
442            local_pref: None,
443            med: None,
444            communities: None,
445            atomic: false,
446            aggr_asn: None,
447            aggr_ip: None,
448            only_to_customer: None,
449            unknown: None,
450            deprecated: None,
451        })
452    }
453
454    fn size_hint(&self) -> (usize, Option<usize>) {
455        let (ann_lo, ann_hi) = if self.in_withdrawn_phase {
456            (0, Some(0))
457        } else {
458            self.announced.size_hint()
459        };
460        let (wd_lo, wd_hi) = self.withdrawn.size_hint();
461        (ann_lo + wd_lo, ann_hi.and_then(|a| wd_hi.map(|w| a + w)))
462    }
463}
464
465impl Elementor {
466    pub fn new() -> Elementor {
467        Self::default()
468    }
469
470    /// Sets the peer index table for the elementor.
471    ///
472    /// This method takes an MRT record and extracts the peer index table from it if the record contains one.
473    /// The peer index table is required for processing TableDumpV2 records, as it contains the mapping between
474    /// peer indices and their corresponding IP addresses and ASNs.
475    ///
476    /// # Arguments
477    ///
478    /// * `record` - An MRT record that should contain a peer index table
479    ///
480    /// # Returns
481    ///
482    /// * `Ok(())` - If the peer table was successfully extracted and set
483    /// * `Err(ParserError)` - If the record does not contain a peer index table
484    ///
485    /// # Example
486    ///
487    /// ```no_run
488    /// use bgpkit_parser::{BgpkitParser, Elementor};
489    ///
490    /// let mut parser = BgpkitParser::new("rib.dump.bz2").unwrap();
491    /// let mut elementor = Elementor::new();
492    ///
493    /// // Get the first record which should be the peer index table
494    /// if let Ok(record) = parser.next_record() {
495    ///     elementor.set_peer_table(record).unwrap();
496    /// }
497    /// ```
498    pub fn set_peer_table(&mut self, record: MrtRecord) -> Result<(), ParserError> {
499        if let MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(p)) =
500            record.message
501        {
502            self.peer_table = Some(p);
503            Ok(())
504        } else {
505            Err(ParseError("peer_table is not a PeerIndexTable".to_string()))
506        }
507    }
508
509    /// Creates an [`Elementor`] with the given [`PeerIndexTable`] already set.
510    pub fn with_peer_table(peer_table: PeerIndexTable) -> Elementor {
511        Elementor {
512            peer_table: Some(peer_table),
513        }
514    }
515
516    /// Convert a [`MrtRecord`] into an iterator of [`BgpElem`]s without
517    /// requiring `&mut self`.
518    ///
519    /// Unlike [`record_to_elems`](Elementor::record_to_elems), this method:
520    /// - Takes `&self` instead of `&mut self`, since the peer table must
521    ///   already be set via [`set_peer_table`](Elementor::set_peer_table) or
522    ///   [`with_peer_table`](Elementor::with_peer_table).
523    /// - Returns an error if the record contains a [`PeerIndexTable`] (which
524    ///   would require mutation).
525    /// - Returns a lazy [`RecordElemIter`] instead of collecting into a `Vec`,
526    ///   avoiding allocation for the common RIB table dump case.
527    ///
528    /// # Errors
529    ///
530    /// - [`ElemError::UnexpectedPeerIndexTable`] if the record is a PeerIndexTable message.
531    /// - [`ElemError::MissingPeerTable`] if the record requires a peer table but none is set.
532    pub fn record_to_elems_iter(&self, record: MrtRecord) -> Result<RecordElemIter<'_>, ElemError> {
533        Ok(match self.pending_elems(record)? {
534            PendingElems::Empty => RecordElemIter::Empty,
535            PendingElems::TableDump(elem) => RecordElemIter::TableDump(elem),
536            PendingElems::TableDumpBatch(entries) => RecordElemIter::TableDumpBatch(entries),
537            PendingElems::RibAfi {
538                prefix, entries, ..
539            } => RecordElemIter::RibAfi {
540                peer_table: self
541                    .peer_table
542                    .as_ref()
543                    .ok_or(ElemError::MissingPeerTable)?,
544                prefix,
545                entries,
546            },
547            PendingElems::Bgp4Mp(iter) => RecordElemIter::Bgp4Mp(iter),
548        })
549    }
550
551    /// The elems of `record`, for [`record_to_elems_iter`](Elementor::record_to_elems_iter) and
552    /// [`ingest`](Elementor::ingest).
553    fn pending_elems(&self, record: MrtRecord) -> Result<PendingElems, ElemError> {
554        let timestamp = {
555            let t = record.common_header.timestamp;
556            if let Some(micro) = &record.common_header.microsecond_timestamp {
557                let m = (*micro as f64) / 1000000.0;
558                t as f64 + m
559            } else {
560                f64::from(t)
561            }
562        };
563
564        match record.message {
565            MrtMessage::TableDumpMessage(msg) => {
566                Ok(PendingElems::TableDump(Some(table_dump_to_elem(msg))))
567            }
568            MrtMessage::TableDumpMessageBatch(messages) => {
569                Ok(PendingElems::TableDumpBatch(messages.into_iter()))
570            }
571
572            MrtMessage::TableDumpV2Message(msg) => match msg {
573                TableDumpV2Message::PeerIndexTable(p) => {
574                    Err(ElemError::UnexpectedPeerIndexTable(Box::new(p)))
575                }
576                TableDumpV2Message::RibAfi(t) => {
577                    if self.peer_table.is_none() {
578                        return Err(ElemError::MissingPeerTable);
579                    }
580                    Ok(PendingElems::RibAfi {
581                        prefix: t.prefix,
582                        entries: t.rib_entries.into_iter(),
583                    })
584                }
585                TableDumpV2Message::RibGeneric(_) => Err(ElemError::UnsupportedRibGeneric),
586                TableDumpV2Message::GeoPeerTable(_) => Ok(PendingElems::Empty),
587            },
588
589            MrtMessage::Bgp4Mp(msg) => match msg {
590                Bgp4MpEnum::StateChange(_) => Ok(PendingElems::Empty),
591                Bgp4MpEnum::Message(v) => {
592                    match Elementor::bgp_to_elems_iter(
593                        v.bgp_message,
594                        timestamp,
595                        &v.peer_ip,
596                        &v.peer_asn,
597                    ) {
598                        Some(iter) => Ok(PendingElems::Bgp4Mp(iter)),
599                        None => Ok(PendingElems::Empty),
600                    }
601                }
602            },
603            MrtMessage::LegacyBgp(msg) => match msg {
604                LegacyBgp::StateChange(_) => Ok(PendingElems::Empty),
605                LegacyBgp::Message(message) => match Elementor::bgp_to_elems_iter(
606                    message.bgp_message,
607                    timestamp,
608                    &message.peer_ip,
609                    &message.peer_asn,
610                ) {
611                    Some(iter) => Ok(PendingElems::Bgp4Mp(iter)),
612                    None => Ok(PendingElems::Empty),
613                },
614            },
615        }
616    }
617
618    /// Take in a record the way [`record_to_elems`](Elementor::record_to_elems) does, returning
619    /// its elems for lazy draining with [`PendingElems::next_elem`] instead of a `Vec`.
620    ///
621    /// A [`PeerIndexTable`] record sets the peer table; errors are logged.
622    pub(crate) fn ingest(&mut self, record: MrtRecord) -> PendingElems {
623        match record.message {
624            MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_)) => {
625                if let Err(e) = self.set_peer_table(record) {
626                    error!("{}", e);
627                }
628                PendingElems::Empty
629            }
630            _ => self.pending_elems(record).unwrap_or_else(|e| {
631                error!("{}", e);
632                PendingElems::Empty
633            }),
634        }
635    }
636
637    /// Convert a [BgpMessage] to a vector of [BgpElem]s.
638    ///
639    /// A [BgpMessage] may include `Update`, `Open`, `Notification` or `KeepAlive` messages,
640    /// and only `Update` message contains [BgpElem]s.
641    pub fn bgp_to_elems(
642        msg: BgpMessage,
643        timestamp: f64,
644        peer_ip: &IpAddr,
645        peer_asn: &Asn,
646    ) -> Vec<BgpElem> {
647        Elementor::bgp_to_elems_iter(msg, timestamp, peer_ip, peer_asn)
648            .map(|iter| iter.collect())
649            .unwrap_or_default()
650    }
651
652    /// Convert a [BgpMessage] into an iterator of [BgpElem]s.
653    ///
654    /// Returns `None` for non-Update messages (Open, Notification, KeepAlive, RouteRefresh).
655    pub fn bgp_to_elems_iter(
656        msg: BgpMessage,
657        timestamp: f64,
658        peer_ip: &IpAddr,
659        peer_asn: &Asn,
660    ) -> Option<BgpUpdateElemIter> {
661        match msg {
662            BgpMessage::Update(msg) => Some(Elementor::bgp_update_to_elems_iter(
663                msg, timestamp, peer_ip, peer_asn,
664            )),
665            BgpMessage::Open(_)
666            | BgpMessage::Notification(_)
667            | BgpMessage::KeepAlive
668            | BgpMessage::RouteRefresh(_) => None,
669        }
670    }
671
672    /// Convert a [BgpUpdateMessage] to a vector of [BgpElem]s.
673    pub fn bgp_update_to_elems(
674        msg: BgpUpdateMessage,
675        timestamp: f64,
676        peer_ip: &IpAddr,
677        peer_asn: &Asn,
678    ) -> Vec<BgpElem> {
679        Elementor::bgp_update_to_elems_iter(msg, timestamp, peer_ip, peer_asn).collect()
680    }
681
682    /// Convert a [BgpUpdateMessage] into a [`BgpUpdateElemIter`] that lazily
683    /// yields [BgpElem]s without allocating a `Vec`.
684    pub fn bgp_update_to_elems_iter(
685        msg: BgpUpdateMessage,
686        timestamp: f64,
687        peer_ip: &IpAddr,
688        peer_asn: &Asn,
689    ) -> BgpUpdateElemIter {
690        let mut attrs = get_relevant_attributes(msg.attributes);
691        let path = attrs.path();
692
693        let origin_asns = path
694            .as_ref()
695            .map(|as_path| as_path.iter_origins().collect());
696
697        BgpUpdateElemIter {
698            timestamp,
699            peer_ip: *peer_ip,
700            peer_asn: *peer_asn,
701            peer_bgp_id: None,
702            only_to_customer: attrs.only_to_customer,
703            path,
704            origin_asns,
705            origin: attrs.origin,
706            next_hop: attrs.next_hop,
707            local_pref: attrs.local_pref,
708            med: attrs.med,
709            communities: attrs.communities,
710            atomic: attrs.atomic,
711            aggr_asn: attrs.aggregator.map(|v| v.0),
712            aggr_ip: attrs.aggregator.map(|v| v.1),
713            unknown: attrs.unknown,
714            deprecated: attrs.deprecated,
715            announced: msg
716                .announced_prefixes
717                .into_iter()
718                .chain(attrs.announced_prefixes),
719            withdrawn: msg
720                .withdrawn_prefixes
721                .into_iter()
722                .chain(attrs.withdrawn_prefixes),
723            in_withdrawn_phase: false,
724        }
725    }
726
727    /// Convert a [MrtRecord] to a vector of [BgpElem]s.
728    ///
729    /// If the record is a [`PeerIndexTable`], it is consumed to set the internal
730    /// peer table. Errors are logged.
731    ///
732    /// For a non-mutating, lazy alternative, see
733    /// [`record_to_elems_iter`](Elementor::record_to_elems_iter).
734    pub fn record_to_elems(&mut self, record: MrtRecord) -> Vec<BgpElem> {
735        match record.message {
736            MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_)) => {
737                if let Err(e) = self.set_peer_table(record) {
738                    error!("{}", e);
739                }
740                vec![]
741            }
742            _ => match self.record_to_elems_iter(record) {
743                Ok(iter) => iter.collect(),
744                Err(e) => {
745                    error!("{}", e);
746                    vec![]
747                }
748            },
749        }
750    }
751}
752
753fn table_dump_to_elem(msg: TableDumpMessage) -> BgpElem {
754    let attrs = get_relevant_attributes(msg.attributes);
755
756    let origin_asns = attrs
757        .as_path
758        .as_ref()
759        .map(|as_path| as_path.iter_origins().collect());
760
761    BgpElem {
762        timestamp: msg.originated_time as f64,
763        elem_type: ElemType::ANNOUNCE,
764        peer_ip: msg.peer_ip,
765        peer_asn: msg.peer_asn,
766        peer_bgp_id: None,
767        prefix: msg.prefix,
768        next_hop: attrs.next_hop,
769        as_path: attrs.as_path,
770        origin: attrs.origin,
771        origin_asns,
772        local_pref: attrs.local_pref,
773        med: attrs.med,
774        communities: attrs.communities,
775        atomic: attrs.atomic,
776        aggr_asn: attrs.aggregator.map(|v| v.0),
777        aggr_ip: attrs.aggregator.map(|v| v.1),
778        only_to_customer: attrs.only_to_customer,
779        unknown: attrs.unknown,
780        deprecated: attrs.deprecated,
781    }
782}
783
784#[inline(always)]
785pub fn option_to_string<T>(o: &Option<T>) -> String
786where
787    T: Display,
788{
789    if let Some(v) = o {
790        v.to_string()
791    } else {
792        String::new()
793    }
794}
795
796impl From<&BgpElem> for Attributes {
797    fn from(value: &BgpElem) -> Self {
798        let mut values = Vec::<AttributeValue>::new();
799        let mut attributes = Attributes::default();
800        let prefix = value.prefix;
801
802        if value.elem_type == ElemType::WITHDRAW {
803            values.push(AttributeValue::MpUnreachNlri(Nlri::new_unreachable(prefix)));
804            attributes.extend(values);
805            return attributes;
806        }
807
808        values.push(AttributeValue::MpReachNlri(Nlri::new_reachable(
809            prefix,
810            value.next_hop,
811        )));
812
813        if let Some(v) = value.next_hop {
814            values.push(AttributeValue::NextHop(v));
815        }
816
817        if let Some(v) = value.as_path.as_ref() {
818            // The elem path is the RFC 6793 merged (effective) path, so it
819            // always maps to the plain AS_PATH attribute; the segment width is
820            // decided by the session's `asn_len` at encode time.
821            values.push(AttributeValue::AsPath(v.clone()));
822        }
823
824        if let Some(v) = value.origin {
825            values.push(AttributeValue::Origin(v));
826        }
827
828        if let Some(v) = value.local_pref {
829            values.push(AttributeValue::LocalPreference(v));
830        }
831
832        if let Some(v) = value.med {
833            values.push(AttributeValue::MultiExitDiscriminator(v));
834        }
835
836        if let Some(v) = value.communities.as_ref() {
837            let mut communites = vec![];
838            let mut extended_communities = vec![];
839            let mut ipv6_extended_communities = vec![];
840            let mut large_communities = vec![];
841            for c in v {
842                match c {
843                    MetaCommunity::Plain(v) => communites.push(*v),
844                    MetaCommunity::Extended(v) => extended_communities.push(*v),
845                    MetaCommunity::Large(v) => large_communities.push(*v),
846                    MetaCommunity::Ipv6Extended(v) => ipv6_extended_communities.push(*v),
847                }
848            }
849            if !communites.is_empty() {
850                values.push(AttributeValue::Communities(communites));
851            }
852            if !extended_communities.is_empty() {
853                values.push(AttributeValue::ExtendedCommunities(extended_communities));
854            }
855            if !large_communities.is_empty() {
856                values.push(AttributeValue::LargeCommunities(large_communities));
857            }
858            if !ipv6_extended_communities.is_empty() {
859                values.push(AttributeValue::Ipv6AddressSpecificExtendedCommunities(
860                    ipv6_extended_communities,
861                ));
862            }
863        }
864
865        if let Some(v) = value.aggr_asn {
866            let aggregator_id = match value.aggr_ip {
867                Some(v) => v,
868                None => Ipv4Addr::UNSPECIFIED,
869            };
870            values.push(AttributeValue::Aggregator {
871                asn: v,
872                id: aggregator_id,
873            });
874        }
875
876        if let Some(v) = value.only_to_customer {
877            values.push(AttributeValue::OnlyToCustomer(v));
878        }
879
880        if let Some(v) = value.unknown.as_ref() {
881            for t in v {
882                values.push(AttributeValue::Unknown(t.clone()));
883            }
884        }
885
886        if let Some(v) = value.deprecated.as_ref() {
887            for t in v {
888                values.push(AttributeValue::Deprecated(t.clone()));
889            }
890        }
891
892        attributes.extend(values);
893        attributes
894    }
895}
896
897#[cfg(test)]
898mod tests {
899    use super::*;
900    use crate::BgpkitParser;
901    use bytes::Bytes;
902    use std::net::{Ipv4Addr, Ipv6Addr};
903    use std::str::FromStr;
904
905    #[test]
906    fn test_option_to_string() {
907        let o1 = Some(1);
908        let o2: Option<u32> = None;
909        assert_eq!(option_to_string(&o1), "1");
910        assert_eq!(option_to_string(&o2), "");
911    }
912
913    #[test]
914    fn test_record_to_elems() {
915        let url_table_dump_v1 = "https://data.ris.ripe.net/rrc00/2003.01/bview.20030101.0000.gz";
916        let url_table_dump_v2 = "https://data.ris.ripe.net/rrc00/2023.01/bview.20230101.0000.gz";
917        let url_bgp4mp = "https://data.ris.ripe.net/rrc00/2021.10/updates.20211001.0000.gz";
918
919        let mut elementor = Elementor::new();
920        let parser = BgpkitParser::new(url_table_dump_v1).unwrap();
921        let mut record_iter = parser.into_record_iter();
922        let record = record_iter.next().unwrap();
923        let elems = elementor.record_to_elems(record);
924        assert_eq!(elems.len(), 1);
925
926        let parser = BgpkitParser::new(url_table_dump_v2).unwrap();
927        let mut record_iter = parser.into_record_iter();
928        let peer_index_table = record_iter.next().unwrap();
929        let _elems = elementor.record_to_elems(peer_index_table);
930        let record = record_iter.next().unwrap();
931        let elems = elementor.record_to_elems(record);
932        assert!(!elems.is_empty());
933
934        let parser = BgpkitParser::new(url_bgp4mp).unwrap();
935        let mut record_iter = parser.into_record_iter();
936        let record = record_iter.next().unwrap();
937        let elems = elementor.record_to_elems(record);
938        assert!(!elems.is_empty());
939    }
940
941    #[test]
942    fn test_attributes_from_bgp_elem() {
943        let mut elem = BgpElem {
944            timestamp: 0.0,
945            elem_type: ElemType::ANNOUNCE,
946            peer_ip: IpAddr::from_str("10.0.0.1").unwrap(),
947            peer_asn: Asn::new_32bit(65000),
948            peer_bgp_id: None,
949            prefix: NetworkPrefix::from_str("10.0.1.0/24").unwrap(),
950            next_hop: Some(IpAddr::from_str("10.0.0.2").unwrap()),
951            as_path: Some(AsPath::from_sequence([65000, 65001, 65002])),
952            origin: Some(Origin::EGP),
953            origin_asns: Some(vec![Asn::new_32bit(65000)]),
954            local_pref: Some(100),
955            med: Some(200),
956            communities: Some(vec![
957                MetaCommunity::Plain(Community::NoAdvertise),
958                MetaCommunity::Extended(ExtendedCommunity::Raw([0, 0, 0, 0, 0, 0, 0, 0])),
959                MetaCommunity::Large(LargeCommunity {
960                    global_admin: 0,
961                    local_data: [0, 0],
962                }),
963                MetaCommunity::Ipv6Extended(Ipv6AddrExtCommunity {
964                    community_type: ExtendedCommunityType::TransitiveTwoOctetAs,
965                    subtype: 0,
966                    global_admin: Ipv6Addr::from_str("2001:db8::").unwrap(),
967                    local_admin: [0, 0],
968                }),
969            ]),
970            atomic: false,
971            aggr_asn: Some(Asn::new_32bit(65000)),
972            aggr_ip: Some(Ipv4Addr::from_str("10.2.0.0").unwrap()),
973            only_to_customer: Some(Asn::new_32bit(65000)),
974            unknown: Some(vec![AttrRaw {
975                code: AttrType::RESERVED.into(),
976                bytes: Bytes::new(),
977            }]),
978            deprecated: Some(vec![AttrRaw {
979                code: AttrType::RESERVED.into(),
980                bytes: Bytes::new(),
981            }]),
982        };
983
984        let _attributes = Attributes::from(&elem);
985        elem.elem_type = ElemType::WITHDRAW;
986        let _attributes = Attributes::from(&elem);
987    }
988
989    #[test]
990    fn test_get_relevant_attributes() {
991        let attributes = vec![
992            AttributeValue::Origin(Origin::IGP),
993            AttributeValue::As4Path(AsPath::from_sequence([65000, 65001, 65002])),
994            AttributeValue::NextHop(IpAddr::from_str("10.0.0.1").unwrap()),
995            AttributeValue::MultiExitDiscriminator(100),
996            AttributeValue::LocalPreference(200),
997            AttributeValue::AtomicAggregate,
998            AttributeValue::Aggregator {
999                asn: Asn::new_32bit(65000),
1000                id: Ipv4Addr::from_str("10.0.0.1").unwrap(),
1001            },
1002            AttributeValue::Communities(vec![Community::NoExport]),
1003            AttributeValue::ExtendedCommunities(vec![ExtendedCommunity::Raw([
1004                0, 0, 0, 0, 0, 0, 0, 0,
1005            ])]),
1006            AttributeValue::LargeCommunities(vec![LargeCommunity {
1007                global_admin: 0,
1008                local_data: [0, 0],
1009            }]),
1010            AttributeValue::Ipv6AddressSpecificExtendedCommunities(vec![Ipv6AddrExtCommunity {
1011                community_type: ExtendedCommunityType::TransitiveTwoOctetAs,
1012                subtype: 0,
1013                global_admin: Ipv6Addr::from_str("2001:db8::").unwrap(),
1014                local_admin: [0, 0],
1015            }]),
1016            AttributeValue::MpReachNlri(Nlri::new_reachable(
1017                NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1018                Some(IpAddr::from_str("10.0.0.1").unwrap()),
1019            )),
1020            AttributeValue::MpUnreachNlri(Nlri::new_unreachable(
1021                NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1022            )),
1023            AttributeValue::OnlyToCustomer(Asn::new_32bit(65000)),
1024            AttributeValue::Unknown(AttrRaw {
1025                code: AttrType::RESERVED.into(),
1026                bytes: Bytes::new(),
1027            }),
1028            AttributeValue::Deprecated(AttrRaw {
1029                code: AttrType::RESERVED.into(),
1030                bytes: Bytes::new(),
1031            }),
1032        ]
1033        .into_iter()
1034        .map(Attribute::from)
1035        .collect::<Vec<Attribute>>();
1036
1037        let attributes = Attributes::from(attributes);
1038
1039        let attrs = get_relevant_attributes(attributes);
1040
1041        assert_eq!(attrs.origin, Some(Origin::IGP));
1042        assert_eq!(
1043            attrs.as4_path,
1044            Some(AsPath::from_sequence([65000, 65001, 65002]))
1045        );
1046        assert_eq!(attrs.next_hop, Some(IpAddr::from_str("10.0.0.1").unwrap()));
1047        assert_eq!((attrs.med, attrs.local_pref), (Some(100), Some(200)));
1048        assert!(attrs.atomic);
1049        // one community of each of the four kinds, in attribute order
1050        let communities = attrs.communities.unwrap();
1051        assert_eq!(communities.len(), 4);
1052        assert_eq!(communities[0], MetaCommunity::Plain(Community::NoExport));
1053        let prefix = NetworkPrefix::from_str("10.0.0.0/24").unwrap();
1054        assert_eq!(attrs.announced_prefixes, vec![prefix]);
1055        assert_eq!(attrs.withdrawn_prefixes, vec![prefix]);
1056        assert_eq!(attrs.only_to_customer, Some(Asn::new_32bit(65000)));
1057        assert_eq!(attrs.unknown.map(|v| v.len()), Some(1));
1058        assert_eq!(attrs.deprecated.map(|v| v.len()), Some(1));
1059    }
1060
1061    #[test]
1062    fn test_next_hop_from_nlri() {
1063        let attributes = vec![AttributeValue::NextHop(
1064            IpAddr::from_str("10.0.0.1").unwrap(),
1065        )]
1066        .into_iter()
1067        .map(Attribute::from)
1068        .collect::<Vec<Attribute>>();
1069
1070        let attributes = Attributes::from(attributes);
1071
1072        let next_hop = get_relevant_attributes(attributes).next_hop;
1073
1074        assert_eq!(next_hop, Some(IpAddr::from_str("10.0.0.1").unwrap()));
1075
1076        let attributes = vec![AttributeValue::MpReachNlri(Nlri::new_reachable(
1077            NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1078            Some(IpAddr::from_str("10.0.0.2").unwrap()),
1079        ))]
1080        .into_iter()
1081        .map(Attribute::from)
1082        .collect::<Vec<Attribute>>();
1083
1084        let attributes = Attributes::from(attributes);
1085
1086        let next_hop = get_relevant_attributes(attributes).next_hop;
1087
1088        assert_eq!(next_hop, Some(IpAddr::from_str("10.0.0.2").unwrap()));
1089    }
1090
1091    #[test]
1092    fn test_record_to_elems_iter_equivalence_tabledumpv2_small() {
1093        // rib-example-small.bz2 is a TableDumpV2 file (starts with PeerIndexTable)
1094        let url = "https://spaces.bgpkit.org/parser/rib-example-small.bz2";
1095
1096        let mut elementor = Elementor::new();
1097        let parser = BgpkitParser::new(url).unwrap();
1098        let mut record_iter = parser.into_record_iter();
1099
1100        // Skip the PeerIndexTable
1101        let peer_index_table = record_iter.next().unwrap();
1102        let _ = elementor.record_to_elems(peer_index_table);
1103
1104        // Process the first RIB entry
1105        let record = record_iter.next().unwrap();
1106        let elems_vec = elementor.record_to_elems(record.clone());
1107        let elems_iter: Vec<BgpElem> = elementor.record_to_elems_iter(record).unwrap().collect();
1108        assert_eq!(elems_vec, elems_iter);
1109        assert!(!elems_vec.is_empty());
1110    }
1111
1112    #[test]
1113    fn test_record_to_elems_iter_equivalence_bgp4mp() {
1114        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
1115
1116        let mut elementor = Elementor::new();
1117        let parser = BgpkitParser::new(url).unwrap();
1118        let mut record_iter = parser.into_record_iter();
1119        let record = record_iter.next().unwrap();
1120
1121        let elems_vec = elementor.record_to_elems(record.clone());
1122        let elems_iter: Vec<BgpElem> = elementor.record_to_elems_iter(record).unwrap().collect();
1123        assert_eq!(elems_vec, elems_iter);
1124        assert!(!elems_vec.is_empty());
1125    }
1126
1127    #[test]
1128    #[ignore = "requires large RIB file download"]
1129    fn test_record_to_elems_iter_equivalence_tabledumpv2() {
1130        let url = "https://data.ris.ripe.net/rrc00/2023.01/bview.20230101.0000.gz";
1131
1132        let mut elementor = Elementor::new();
1133        let parser = BgpkitParser::new(url).unwrap();
1134        let mut record_iter = parser.into_record_iter();
1135
1136        let peer_index_table = record_iter.next().unwrap();
1137        let _ = elementor.record_to_elems(peer_index_table);
1138
1139        let record = record_iter.next().unwrap();
1140        let elems_vec = elementor.record_to_elems(record.clone());
1141        let elems_iter: Vec<BgpElem> = elementor.record_to_elems_iter(record).unwrap().collect();
1142        assert_eq!(elems_vec, elems_iter);
1143        assert!(!elems_vec.is_empty());
1144    }
1145
1146    #[test]
1147    fn test_record_to_elems_iter_tabledumpv2_with_peer_table() {
1148        let url = "https://spaces.bgpkit.org/parser/rib-example-small.bz2";
1149
1150        let parser = BgpkitParser::new(url).unwrap();
1151        let mut record_iter = parser.into_record_iter();
1152
1153        let peer_index_table = record_iter.next().unwrap();
1154        let mut elementor = Elementor::with_peer_table(
1155            if let MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(pit)) =
1156                peer_index_table.message
1157            {
1158                pit
1159            } else {
1160                panic!("Expected PeerIndexTable");
1161            },
1162        );
1163
1164        let record = record_iter.next().unwrap();
1165        let elems_vec = elementor.record_to_elems(record.clone());
1166        let elems_iter: Vec<BgpElem> = elementor.record_to_elems_iter(record).unwrap().collect();
1167        assert_eq!(elems_vec, elems_iter);
1168        assert!(!elems_vec.is_empty());
1169    }
1170
1171    #[test]
1172    fn test_record_to_elems_iter_error_unexpected_peer_index_table() {
1173        let url = "https://spaces.bgpkit.org/parser/rib-example-small.bz2";
1174
1175        let elementor = Elementor::new();
1176        let parser = BgpkitParser::new(url).unwrap();
1177        let mut record_iter = parser.into_record_iter();
1178        let record = record_iter.next().unwrap();
1179
1180        let result = elementor.record_to_elems_iter(record);
1181        assert!(matches!(
1182            result,
1183            Err(ElemError::UnexpectedPeerIndexTable(_))
1184        ));
1185    }
1186
1187    #[test]
1188    fn test_record_to_elems_iter_error_missing_peer_table() {
1189        // rib-example-small.bz2 is a TableDumpV2 file (starts with PeerIndexTable)
1190        let url = "https://spaces.bgpkit.org/parser/rib-example-small.bz2";
1191
1192        let elementor = Elementor::new();
1193        let parser = BgpkitParser::new(url).unwrap();
1194        let mut record_iter = parser.into_record_iter();
1195
1196        // Skip the PeerIndexTable without consuming it via record_to_elems
1197        // which would set the peer table in the elementor
1198        let _peer_index_table = record_iter.next().unwrap();
1199
1200        // Now try to process a RIB entry without having set the peer table
1201        let record = record_iter.next().unwrap();
1202        let result = elementor.record_to_elems_iter(record);
1203        assert!(matches!(result, Err(ElemError::MissingPeerTable)));
1204    }
1205
1206    #[test]
1207    fn test_bgp_to_elems_iter_equivalence() {
1208        let timestamp = 0.0;
1209        let peer_ip = IpAddr::from_str("10.0.0.1").unwrap();
1210        let peer_asn = Asn::new_32bit(65000);
1211
1212        let attributes = vec![
1213            AttributeValue::Origin(Origin::IGP),
1214            AttributeValue::AsPath(AsPath::from_sequence([65000, 65001, 65002])),
1215            AttributeValue::NextHop(peer_ip),
1216        ]
1217        .into_iter()
1218        .map(Attribute::from)
1219        .collect::<Vec<Attribute>>();
1220        let attributes = Attributes::from(attributes);
1221
1222        let announced_prefixes = vec![NetworkPrefix::from_str("10.0.0.0/24").unwrap()];
1223
1224        let bgp_message = BgpMessage::Update(BgpUpdateMessage {
1225            attributes,
1226            announced_prefixes,
1227            withdrawn_prefixes: vec![],
1228        });
1229
1230        let elems_vec =
1231            Elementor::bgp_to_elems(bgp_message.clone(), timestamp, &peer_ip, &peer_asn);
1232        let elems_iter: Vec<BgpElem> =
1233            Elementor::bgp_to_elems_iter(bgp_message, timestamp, &peer_ip, &peer_asn)
1234                .unwrap()
1235                .collect();
1236        assert_eq!(elems_vec, elems_iter);
1237        assert_eq!(elems_vec.len(), 1);
1238    }
1239
1240    #[test]
1241    fn test_bgp_to_elems_iter_non_update_messages() {
1242        use std::net::Ipv4Addr;
1243
1244        let timestamp = 0.0;
1245        let peer_ip = IpAddr::from_str("10.0.0.1").unwrap();
1246        let peer_asn = Asn::new_32bit(65000);
1247
1248        let open_msg = BgpOpenMessage {
1249            version: 4,
1250            asn: Asn::new_32bit(1),
1251            hold_time: 180,
1252            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1253            extended_length: false,
1254            opt_params: vec![],
1255        };
1256        assert!(Elementor::bgp_to_elems_iter(
1257            BgpMessage::Open(open_msg),
1258            timestamp,
1259            &peer_ip,
1260            &peer_asn
1261        )
1262        .is_none());
1263
1264        let notification_msg = BgpNotificationMessage {
1265            error: BgpError::Unknown(0, 0),
1266            data: vec![],
1267        };
1268        assert!(Elementor::bgp_to_elems_iter(
1269            BgpMessage::Notification(notification_msg),
1270            timestamp,
1271            &peer_ip,
1272            &peer_asn
1273        )
1274        .is_none());
1275
1276        assert!(Elementor::bgp_to_elems_iter(
1277            BgpMessage::KeepAlive,
1278            timestamp,
1279            &peer_ip,
1280            &peer_asn
1281        )
1282        .is_none());
1283    }
1284
1285    #[test]
1286    fn test_bgp_update_to_elems_iter_equivalence() {
1287        let timestamp = 0.0;
1288        let peer_ip = IpAddr::from_str("10.0.0.1").unwrap();
1289        let peer_asn = Asn::new_32bit(65000);
1290
1291        let attributes = vec![
1292            AttributeValue::Origin(Origin::IGP),
1293            AttributeValue::AsPath(AsPath::from_sequence([65000, 65001, 65002])),
1294            AttributeValue::NextHop(peer_ip),
1295        ]
1296        .into_iter()
1297        .map(Attribute::from)
1298        .collect::<Vec<Attribute>>();
1299        let attributes = Attributes::from(attributes);
1300
1301        let announced_prefixes = vec![NetworkPrefix::from_str("10.0.0.0/24").unwrap()];
1302        let withdrawn_prefixes = vec![NetworkPrefix::from_str("10.0.1.0/24").unwrap()];
1303
1304        let update = BgpUpdateMessage {
1305            attributes,
1306            announced_prefixes,
1307            withdrawn_prefixes,
1308        };
1309
1310        let elems_vec =
1311            Elementor::bgp_update_to_elems(update.clone(), timestamp, &peer_ip, &peer_asn);
1312        let elems_iter: Vec<BgpElem> =
1313            Elementor::bgp_update_to_elems_iter(update, timestamp, &peer_ip, &peer_asn).collect();
1314        assert_eq!(elems_vec, elems_iter);
1315        assert_eq!(elems_vec.len(), 2);
1316    }
1317
1318    #[test]
1319    fn test_bgp_update_to_elems_iter_shares_attributes_across_prefixes() {
1320        let peer_ip = IpAddr::from_str("10.0.0.1").unwrap();
1321        let peer_asn = Asn::new_32bit(65000);
1322        let as_path = AsPath::from_sequence([65000, 65001, 65002]);
1323        let unknown = AttrRaw {
1324            code: 254,
1325            bytes: Bytes::from_static(&[1, 2]),
1326        };
1327
1328        let attributes = vec![
1329            AttributeValue::AsPath(as_path.clone()),
1330            AttributeValue::Communities(vec![Community::NoExport]),
1331            AttributeValue::Unknown(unknown.clone()),
1332            AttributeValue::MpReachNlri(Nlri::new_reachable(
1333                NetworkPrefix::from_str("2001:db8::/32").unwrap(),
1334                Some(IpAddr::from_str("2001:db8::1").unwrap()),
1335            )),
1336        ]
1337        .into_iter()
1338        .map(Attribute::from)
1339        .collect::<Vec<Attribute>>();
1340
1341        let update = BgpUpdateMessage {
1342            attributes: Attributes::from(attributes),
1343            announced_prefixes: vec![
1344                NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1345                NetworkPrefix::from_str("10.0.2.0/24").unwrap(),
1346            ],
1347            withdrawn_prefixes: vec![NetworkPrefix::from_str("10.0.1.0/24").unwrap()],
1348        };
1349
1350        let mut iter = Elementor::bgp_update_to_elems_iter(update, 0.0, &peer_ip, &peer_asn);
1351        assert_eq!(iter.size_hint(), (4, Some(4)));
1352        let elems: Vec<BgpElem> = iter.by_ref().collect();
1353        assert_eq!(iter.size_hint(), (0, Some(0)));
1354
1355        // the classic NLRI first, then the MP_REACH_NLRI prefix; the last announcement takes
1356        // the shared attributes rather than cloning them, so it must match the others
1357        let announced: Vec<&BgpElem> = elems.iter().filter(|e| e.elem_type.is_announce()).collect();
1358        assert_eq!(announced.len(), 3);
1359        assert_eq!(
1360            announced[2].prefix,
1361            NetworkPrefix::from_str("2001:db8::/32").unwrap()
1362        );
1363        for elem in &announced {
1364            assert_eq!(elem.as_path.as_ref(), Some(&as_path));
1365            assert_eq!(elem.origin_asns, Some(vec![Asn::new_32bit(65002)]));
1366            assert_eq!(
1367                elem.communities,
1368                Some(vec![MetaCommunity::Plain(Community::NoExport)])
1369            );
1370            assert_eq!(elem.unknown, Some(vec![unknown.clone()]));
1371        }
1372
1373        let withdrawn = elems.last().unwrap();
1374        assert_eq!(withdrawn.elem_type, ElemType::WITHDRAW);
1375        assert_eq!(withdrawn.as_path, None);
1376        assert_eq!(withdrawn.communities, None);
1377    }
1378
1379    #[test]
1380    fn test_record_elem_iter_size_hint() {
1381        use std::collections::HashMap;
1382
1383        let peer_table = PeerIndexTable {
1384            collector_bgp_id: BgpIdentifier::from_str("10.0.0.1").unwrap(),
1385            view_name: "".to_string(),
1386            id_peer_map: HashMap::new(),
1387            peer_ip_id_map: HashMap::new(),
1388        };
1389
1390        let entries: Vec<RibEntry> = vec![];
1391        let iter = RecordElemIter::RibAfi {
1392            peer_table: &peer_table,
1393            prefix: NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1394            entries: entries.into_iter(),
1395        };
1396        assert_eq!(iter.size_hint(), (0, Some(0)));
1397
1398        let entries: Vec<RibEntry> = (0..5)
1399            .map(|i| RibEntry {
1400                peer_index: i as u16,
1401                originated_time: 0,
1402                path_id: None,
1403                attributes: Attributes::default(),
1404            })
1405            .collect();
1406        let iter = RecordElemIter::RibAfi {
1407            peer_table: &peer_table,
1408            prefix: NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
1409            entries: entries.into_iter(),
1410        };
1411        assert_eq!(iter.size_hint(), (5, Some(5)));
1412    }
1413
1414    #[test]
1415    fn test_pending_elems_rib_entries() {
1416        use std::collections::HashMap;
1417
1418        let peer = Peer::new(
1419            BgpIdentifier::from_str("10.0.0.2").unwrap(),
1420            IpAddr::from_str("10.0.0.2").unwrap(),
1421            Asn::new_32bit(65002),
1422        );
1423        let peer_table = PeerIndexTable {
1424            collector_bgp_id: BgpIdentifier::from_str("10.0.0.1").unwrap(),
1425            view_name: "".to_string(),
1426            id_peer_map: HashMap::from([(0, peer)]),
1427            peer_ip_id_map: HashMap::new(),
1428        };
1429        let prefix = NetworkPrefix::from_str("10.0.0.0/24").unwrap();
1430        // peer 0 is in the table, peer 7 is not
1431        let pending = || PendingElems::RibAfi {
1432            prefix,
1433            entries: [0, 0, 7, 0]
1434                .map(|peer_index| RibEntry {
1435                    peer_index,
1436                    originated_time: 0,
1437                    path_id: None,
1438                    attributes: Attributes::default(),
1439                })
1440                .to_vec()
1441                .into_iter(),
1442        };
1443
1444        // an unknown peer ends the record, like RecordElemIter does
1445        let mut elems = pending();
1446        let first = elems.next_elem(Some(&peer_table)).unwrap();
1447        assert_eq!(first.prefix, prefix);
1448        assert_eq!(first.peer_asn, Asn::new_32bit(65002));
1449        assert!(elems.next_elem(Some(&peer_table)).is_some());
1450        assert!(elems.next_elem(Some(&peer_table)).is_none());
1451        assert!(matches!(elems, PendingElems::Empty));
1452
1453        // without a peer table nothing is produced
1454        let mut elems = pending();
1455        assert!(elems.next_elem(None).is_none());
1456        assert!(matches!(elems, PendingElems::Empty));
1457    }
1458}