Skip to main content

bgpkit_parser/models/bgp/
elem.rs

1use crate::models::*;
2use itertools::Itertools;
3use std::cmp::Ordering;
4use std::fmt::{Display, Formatter};
5use std::net::IpAddr;
6use std::str::FromStr;
7use std::sync::Arc;
8
9// TODO(jmeggitt): BgpElem can be converted to an enum. Apply this change during performance PR.
10
11/// # ElemType
12///
13/// `ElemType` is an enumeration that represents the type of an element.
14/// It has two possible values:
15///
16/// - `ANNOUNCE`: Indicates an announcement/reachable prefix.
17/// - `WITHDRAW`: Indicates a withdrawn/unreachable prefix.
18///
19/// The enumeration derives the traits `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, and `Hash`.
20///
21/// It also has the following attributes:
22///
23/// - `#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]`
24///     - This attribute is conditionally applied when the `"serde"` feature is enabled. It allows
25///       the enumeration to be serialized and deserialized using serde.
26/// - `#[cfg_attr(feature = "serde", serde(rename = "lowercase"))]`
27///     - This attribute is conditionally applied when the `"serde"` feature is enabled. It specifies
28///       that the serialized form of the enumeration should be in lowercase.
29///
30/// Example usage:
31///
32/// ```
33/// use bgpkit_parser::models::ElemType;
34///
35/// let announce_type = ElemType::ANNOUNCE;
36/// let withdraw_type = ElemType::WITHDRAW;
37///
38/// assert_eq!(announce_type, ElemType::ANNOUNCE);
39/// assert_eq!(withdraw_type, ElemType::WITHDRAW);
40/// ```
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43#[cfg_attr(feature = "serde", serde(rename = "lowercase"))]
44pub enum ElemType {
45    ANNOUNCE,
46    WITHDRAW,
47}
48
49impl ElemType {
50    /// Checks if the `ElemType` is an announce.
51    ///
52    /// Returns `true` if `ElemType` is `ANNOUNCE`, and `false` if it is `WITHDRAW`.
53    ///
54    /// # Examples
55    ///
56    /// ```
57    /// use bgpkit_parser::models::ElemType;
58    ///
59    /// let elem = ElemType::ANNOUNCE;
60    /// assert_eq!(elem.is_announce(), true);
61    ///
62    /// let elem = ElemType::WITHDRAW;
63    /// assert_eq!(elem.is_announce(), false);
64    /// ```
65    pub fn is_announce(&self) -> bool {
66        match self {
67            ElemType::ANNOUNCE => true,
68            ElemType::WITHDRAW => false,
69        }
70    }
71}
72
73/// BgpElem represents a per-prefix BGP element.
74///
75/// This struct contains information about an announced/withdrawn prefix.
76///
77/// Fields:
78/// - `timestamp`: The time when the BGP element was received.
79/// - `elem_type`: The type of BGP element.
80/// - `peer_ip`: The IP address of the BGP peer.
81/// - `peer_asn`: The ASN of the BGP peer.
82/// - `prefix`: The network prefix.
83/// - `next_hop`: The next hop IP address.
84/// - `as_path`: The AS path.
85/// - `origin_asns`: The list of origin ASNs.
86/// - `origin`: The origin attribute, i.e. IGP, EGP, or INCOMPLETE.
87/// - `local_pref`: The local preference value.
88/// - `med`: The multi-exit discriminator value.
89/// - `communities`: The list of BGP communities.
90/// - `atomic`: Flag indicating if the announcement is atomic.
91/// - `aggr_asn`: The aggregated ASN.
92/// - `aggr_ip`: The aggregated IP address.
93/// - `only_to_customer`: The AS number to which the prefix is only announced.
94/// - `unknown`: Unknown attributes formatted as (TYPE, RAW_BYTES).
95/// - `deprecated`: Deprecated attributes formatted as (TYPE, RAW_BYTES).
96///
97/// Note: Constructing BGP elements consumes more memory due to duplicate information
98/// shared between multiple elements of one MRT record.
99#[derive(Debug, Clone, PartialEq)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub struct BgpElem {
102    /// The timestamp of the item in floating-point format.
103    pub timestamp: f64,
104    /// The element type of an item.
105    #[cfg_attr(feature = "serde", serde(rename = "type"))]
106    pub elem_type: ElemType,
107    /// The IP address of the peer associated with the item.
108    pub peer_ip: IpAddr,
109    /// The peer ASN (Autonomous System Number) of the item.
110    pub peer_asn: Asn,
111    /// The BGP Identifier (Router ID) of the peer, if available.
112    ///
113    /// Present in MRT TableDumpV2 records (from the PEER_INDEX_TABLE) and in BGP OPEN messages.
114    /// Not available when processing BGP UPDATE messages without an accompanying OPEN message
115    /// (e.g. Bgp4Mp records), in which case this field is `None`.
116    pub peer_bgp_id: Option<BgpIdentifier>,
117    /// The network prefix of the item.
118    pub prefix: NetworkPrefix,
119    /// The next hop IP address for the item, if available.
120    pub next_hop: Option<IpAddr>,
121    /// The optional path representation of the item.
122    ///
123    /// This field is of type `Option<AsPath>`, which means it can either contain
124    /// a value of type `AsPath` or be `None`.
125    pub as_path: Option<AsPath>,
126    /// The origin ASNs associated with the prefix, if available.
127    ///
128    /// # Remarks
129    /// An `Option` type is used to indicate that the `origin_asns` field may or may not have a value.
130    /// If it has a value, it will be a `Vec` (vector) of `Asn` objects representing the ASNs.
131    /// If it does not have a value, it will be `None`.
132    pub origin_asns: Option<Vec<Asn>>,
133    /// The origin of the item (IGP, EGP, INCOMPLETE), if known. Can be `None` if the origin is not available.
134    pub origin: Option<Origin>,
135    /// The local preference of the item, if available, represented as an option of unsigned 32-bit integer.
136    pub local_pref: Option<u32>,
137    /// The number of medical items in an option format.
138    pub med: Option<u32>,
139    /// A vector of optional `MetaCommunity` values.
140    ///
141    /// # Remarks
142    /// `MetaCommunity` represents a community metadata.
143    /// The `Option` type indicates that the vector can be empty or contain [MetaCommunity] values.
144    /// When the `Option` is `Some`, it means the vector is not empty and contains [MetaCommunity] values.
145    /// When the `Option` is `None`, it means the vector is empty.
146    pub communities: Option<Vec<MetaCommunity>>,
147    /// Indicates whether the item is atomic aggreagte or not.
148    pub atomic: bool,
149    /// The aggregated ASN of the item, represented as an optional [Asn] type.
150    pub aggr_asn: Option<Asn>,
151    /// The aggregated IP address of the item, represented as an optional [BgpIdentifier], i.e. `Ipv4Addr`.
152    pub aggr_ip: Option<BgpIdentifier>,
153    pub only_to_customer: Option<Asn>,
154    /// unknown attributes formatted as (TYPE, RAW_BYTES)
155    pub unknown: Option<Vec<AttrRaw>>,
156    /// deprecated attributes formatted as (TYPE, RAW_BYTES)
157    pub deprecated: Option<Vec<AttrRaw>>,
158}
159
160/// Lightweight per-prefix route element.
161///
162/// This struct is intended for fast scans that only need route identity,
163/// peer metadata, timestamp, and AS path. Use [`BgpElem`] when you need the
164/// full set of BGP attributes. Because route elements do not carry
165/// communities, community filters do not match [`BgpRouteElem`] values.
166#[derive(Debug, Clone, PartialEq)]
167#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
168pub struct BgpRouteElem {
169    /// The timestamp of the item in floating-point format.
170    pub timestamp: f64,
171    /// The element type of an item.
172    #[cfg_attr(feature = "serde", serde(rename = "type"))]
173    pub elem_type: ElemType,
174    /// The IP address of the peer associated with the item.
175    pub peer_ip: IpAddr,
176    /// The peer ASN of the item.
177    pub peer_asn: Asn,
178    /// The network prefix of the item.
179    pub prefix: NetworkPrefix,
180    /// The optional path representation of the item.
181    ///
182    /// Route-level parsing shares the same AS path across all announced
183    /// prefixes from a single message.
184    pub as_path: Option<Arc<AsPath>>,
185}
186
187impl Eq for BgpElem {}
188
189impl Eq for BgpRouteElem {}
190
191impl PartialOrd<Self> for BgpElem {
192    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
193        Some(self.cmp(other))
194    }
195}
196
197impl PartialOrd<Self> for BgpRouteElem {
198    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
199        Some(self.cmp(other))
200    }
201}
202
203impl Ord for BgpElem {
204    fn cmp(&self, other: &Self) -> Ordering {
205        self.timestamp
206            .partial_cmp(&other.timestamp)
207            .unwrap()
208            .then_with(|| self.peer_ip.cmp(&other.peer_ip))
209    }
210}
211
212impl Ord for BgpRouteElem {
213    fn cmp(&self, other: &Self) -> Ordering {
214        self.timestamp
215            .partial_cmp(&other.timestamp)
216            .unwrap()
217            .then_with(|| self.peer_ip.cmp(&other.peer_ip))
218    }
219}
220
221impl Default for BgpElem {
222    fn default() -> Self {
223        BgpElem {
224            timestamp: 0.0,
225            elem_type: ElemType::ANNOUNCE,
226            peer_ip: IpAddr::from_str("0.0.0.0").unwrap(),
227            peer_asn: 0.into(),
228            peer_bgp_id: None,
229            prefix: NetworkPrefix::from_str("0.0.0.0/0").unwrap(),
230            next_hop: Some(IpAddr::from_str("0.0.0.0").unwrap()),
231            as_path: None,
232            origin_asns: None,
233            origin: None,
234            local_pref: None,
235            med: None,
236            communities: None,
237            atomic: false,
238            aggr_asn: None,
239            aggr_ip: None,
240            only_to_customer: None,
241            unknown: None,
242            deprecated: None,
243        }
244    }
245}
246
247/// `OptionToStr` is a helper struct that wraps an `Option` and provides a convenient
248/// way to convert its value to a string representation.
249///
250/// # Generic Parameters
251///
252/// - `'a`: The lifetime parameter that represents the lifetime of the wrapped `Option` value.
253///
254/// # Fields
255///
256/// - `0: &'a Option<T>`: The reference to the wrapped `Option` value.
257struct OptionToStr<'a, T>(&'a Option<T>);
258
259impl<T: Display> Display for OptionToStr<'_, T> {
260    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
261        match self.0 {
262            None => Ok(()),
263            Some(x) => write!(f, "{x}"),
264        }
265    }
266}
267
268pub fn option_to_string_communities(o: &Option<Vec<MetaCommunity>>) -> String {
269    if let Some(v) = o {
270        v.iter().join(" ")
271    } else {
272        String::new()
273    }
274}
275
276impl Display for BgpElem {
277    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
278        let t = match self.elem_type {
279            ElemType::ANNOUNCE => "A",
280            ElemType::WITHDRAW => "W",
281        };
282        write!(
283            f,
284            "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
285            t,
286            self.timestamp,
287            self.peer_ip,
288            self.peer_asn,
289            self.prefix,
290            OptionToStr(&self.as_path),
291            OptionToStr(&self.origin),
292            OptionToStr(&self.next_hop),
293            OptionToStr(&self.local_pref),
294            OptionToStr(&self.med),
295            option_to_string_communities(&self.communities),
296            self.atomic,
297            OptionToStr(&self.aggr_asn),
298            OptionToStr(&self.aggr_ip),
299        )
300    }
301}
302
303impl Display for BgpRouteElem {
304    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
305        let t = match self.elem_type {
306            ElemType::ANNOUNCE => "A",
307            ElemType::WITHDRAW => "W",
308        };
309        write!(
310            f,
311            "{}|{}|{}|{}|{}|{}",
312            t,
313            self.timestamp,
314            self.peer_ip,
315            self.peer_asn,
316            self.prefix,
317            OptionToStr(&self.as_path),
318        )
319    }
320}
321
322impl BgpElem {
323    /// Returns true if the element is an announcement.
324    ///
325    /// Most of the time, users do not really need to get the type out, only needs to know if it is
326    /// an announcement or a withdrawal.
327    pub fn is_announcement(&self) -> bool {
328        self.elem_type == ElemType::ANNOUNCE
329    }
330
331    /// Returns the origin AS number as u32. Returns None if the origin AS number is not present or
332    /// it's a AS set.
333    pub fn get_origin_asn_opt(&self) -> Option<u32> {
334        let origin_asns = self.origin_asns.as_ref()?;
335        (origin_asns.len() == 1).then(|| origin_asns[0].into())
336    }
337
338    /// Returns the PSV header as a string.
339    ///
340    /// The PSV header is a pipe-separated string that represents the fields
341    /// present in PSV (Prefix Statement Format) records. PSV records are used
342    /// to describe BGP (Border Gateway Protocol) routing information.
343    ///
344    /// # Example
345    ///
346    /// ```
347    /// use bgpkit_parser::BgpElem;
348    ///
349    /// let header = BgpElem::get_psv_header();
350    /// assert_eq!(header, "type|timestamp|peer_ip|peer_asn|prefix|as_path|origin_asns|origin|next_hop|local_pref|med|communities|atomic|aggr_asn|aggr_ip|only_to_customer");
351    /// ```
352    pub fn get_psv_header() -> String {
353        let fields = [
354            "type",
355            "timestamp",
356            "peer_ip",
357            "peer_asn",
358            "prefix",
359            "as_path",
360            "origin_asns",
361            "origin",
362            "next_hop",
363            "local_pref",
364            "med",
365            "communities",
366            "atomic",
367            "aggr_asn",
368            "aggr_ip",
369            "only_to_customer",
370        ];
371        fields.join("|")
372    }
373
374    /// Converts the struct fields into a pipe-separated values (PSV) formatted string.
375    ///
376    /// # Returns
377    ///
378    /// Returns a `String` representing the struct fields in PSV format.
379    ///
380    /// # Example
381    ///
382    /// ```
383    /// use crate::bgpkit_parser::BgpElem;
384    ///
385    /// let psv_string = BgpElem::default().to_psv();
386    ///
387    /// println!("{}", psv_string);
388    /// ```
389    pub fn to_psv(&self) -> String {
390        let mut out = String::with_capacity(256);
391        crate::render::psv::write_elem(self, &mut out);
392        out
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399    use std::default::Default;
400    use std::str::FromStr;
401
402    #[test]
403    #[cfg(feature = "serde")]
404    fn test_default() {
405        let elem = BgpElem {
406            timestamp: 0.0,
407            elem_type: ElemType::ANNOUNCE,
408            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
409            peer_asn: 0.into(),
410            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
411            ..Default::default()
412        };
413        println!("{}", serde_json::json!(elem));
414    }
415
416    #[test]
417    fn test_sorting() {
418        let elem1 = BgpElem {
419            timestamp: 1.1,
420            elem_type: ElemType::ANNOUNCE,
421            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
422            peer_asn: 0.into(),
423            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
424            ..Default::default()
425        };
426        let elem2 = BgpElem {
427            timestamp: 1.2,
428            elem_type: ElemType::ANNOUNCE,
429            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
430            peer_asn: 0.into(),
431            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
432            ..Default::default()
433        };
434        let elem3 = BgpElem {
435            timestamp: 1.2,
436            elem_type: ElemType::ANNOUNCE,
437            peer_ip: IpAddr::from_str("192.168.1.2").unwrap(),
438            peer_asn: 0.into(),
439            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
440            ..Default::default()
441        };
442
443        assert!(elem1 < elem2);
444        assert!(elem2 < elem3);
445    }
446
447    #[test]
448    fn test_route_elem_sorting() {
449        let elem1 = BgpRouteElem {
450            timestamp: 1.1,
451            elem_type: ElemType::ANNOUNCE,
452            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
453            peer_asn: 0.into(),
454            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
455            as_path: None,
456        };
457        let elem2 = BgpRouteElem {
458            timestamp: 1.2,
459            elem_type: ElemType::ANNOUNCE,
460            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
461            peer_asn: 0.into(),
462            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
463            as_path: None,
464        };
465        let elem3 = BgpRouteElem {
466            timestamp: 1.2,
467            elem_type: ElemType::ANNOUNCE,
468            peer_ip: IpAddr::from_str("192.168.1.2").unwrap(),
469            peer_asn: 0.into(),
470            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
471            as_path: None,
472        };
473
474        assert!(elem1 < elem2);
475        assert!(elem2 < elem3);
476    }
477
478    #[test]
479    fn test_psv() {
480        assert_eq!(
481            BgpElem::get_psv_header().as_str(),
482            "type|timestamp|peer_ip|peer_asn|prefix|as_path|origin_asns|origin|next_hop|local_pref|med|communities|atomic|aggr_asn|aggr_ip|only_to_customer"
483        );
484        let elem = BgpElem::default();
485        assert_eq!(
486            elem.to_psv().as_str(),
487            "A|0|0.0.0.0|0|0.0.0.0/0||||0.0.0.0||||false|||"
488        );
489    }
490
491    #[test]
492    fn test_route_elem_display() {
493        let elem = BgpRouteElem {
494            timestamp: 1.1,
495            elem_type: ElemType::ANNOUNCE,
496            peer_ip: IpAddr::from_str("192.168.1.1").unwrap(),
497            peer_asn: 64496.into(),
498            prefix: NetworkPrefix::from_str("8.8.8.0/24").unwrap(),
499            as_path: Some(Arc::new(AsPath::from_sequence([64496, 64497]))),
500        };
501
502        assert_eq!(
503            elem.to_string().as_str(),
504            "A|1.1|192.168.1.1|64496|8.8.8.0/24|64496 64497"
505        );
506    }
507
508    #[test]
509    fn test_option_to_str() {
510        let asn_opt: Option<u32> = Some(12);
511        assert_eq!(OptionToStr(&asn_opt).to_string(), "12");
512        let none_opt: Option<u32> = None;
513        assert_eq!(OptionToStr(&none_opt).to_string(), "");
514    }
515}