Skip to main content

bgpkit_parser/models/bgp/
mod.rs

1//! BGP messages and relevant structs.
2
3pub mod attributes;
4pub mod capabilities;
5pub mod community;
6pub mod elem;
7pub mod error;
8pub mod evpn;
9pub mod flowspec;
10pub mod linkstate;
11pub mod role;
12pub mod tunnel_encap;
13
14pub use attributes::*;
15pub use community::*;
16pub use elem::*;
17pub use error::*;
18pub use evpn::*;
19pub use flowspec::*;
20pub use linkstate::*;
21pub use role::*;
22pub use tunnel_encap::*;
23
24use crate::models::network::*;
25use capabilities::{
26    AddPathCapability, BgpCapabilityType, BgpExtendedMessageCapability, BgpRoleCapability,
27    ExtendedNextHopCapability, FourOctetAsCapability, GracefulRestartCapability,
28    MultiprotocolExtensionsCapability, RouteRefreshCapability,
29};
30use num_enum::{IntoPrimitive, TryFromPrimitive};
31use std::net::Ipv4Addr;
32
33pub type BgpIdentifier = Ipv4Addr;
34
35#[allow(non_camel_case_types)]
36#[derive(Debug, TryFromPrimitive, IntoPrimitive, Copy, Clone, PartialEq, Hash)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38#[repr(u8)]
39pub enum BgpMessageType {
40    OPEN = 1,
41    UPDATE = 2,
42    NOTIFICATION = 3,
43    KEEPALIVE = 4,
44    ROUTE_REFRESH = 5,
45}
46
47// https://tools.ietf.org/html/rfc4271#section-4
48#[derive(Debug, Clone, PartialEq, Eq)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
50pub enum BgpMessage {
51    Open(BgpOpenMessage),
52    Update(BgpUpdateMessage),
53    Notification(BgpNotificationMessage),
54    KeepAlive,
55    RouteRefresh(BgpRouteRefreshMessage),
56}
57
58impl BgpMessage {
59    pub const fn msg_type(&self) -> BgpMessageType {
60        match self {
61            BgpMessage::Open(_) => BgpMessageType::OPEN,
62            BgpMessage::Update(_) => BgpMessageType::UPDATE,
63            BgpMessage::Notification(_) => BgpMessageType::NOTIFICATION,
64            BgpMessage::KeepAlive => BgpMessageType::KEEPALIVE,
65            BgpMessage::RouteRefresh(_) => BgpMessageType::ROUTE_REFRESH,
66        }
67    }
68}
69
70/// BGP ROUTE-REFRESH Message - RFC 2918
71///
72/// ```text
73///  0                   1                   2                   3
74///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
75///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
76///  |          AFI                  |    Res./Subt. |     SAFI      |
77///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
78/// ```
79///
80/// AFI and SAFI are kept as raw integers so refreshes for address families
81/// outside the [Afi]/[Safi] enums still parse and re-encode byte-for-byte.
82#[derive(Debug, Clone, PartialEq, Eq)]
83#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
84pub struct BgpRouteRefreshMessage {
85    pub afi: u16,
86    /// Reserved in RFC 2918; message subtype in RFC 7313
87    /// (0 = normal route refresh, 1 = BoRR, 2 = EoRR).
88    pub subtype: u8,
89    pub safi: u8,
90    /// Trailing bytes such as ORF entries (RFC 5291), kept raw.
91    pub data: Vec<u8>,
92}
93
94impl BgpRouteRefreshMessage {
95    /// The AFI as a typed [Afi], if it is a known address family.
96    pub fn afi(&self) -> Option<Afi> {
97        Afi::try_from(self.afi).ok()
98    }
99
100    /// The SAFI as a typed [Safi], if it is a known subsequent address family.
101    pub fn safi(&self) -> Option<Safi> {
102        Safi::try_from(self.safi).ok()
103    }
104
105    /// RFC 7313 Section 5 validation findings for this message.
106    ///
107    /// A subtype other than 0-2 MUST be ignored (and SHOULD be logged) by a
108    /// live speaker, and a BoRR/EoRR message (subtype 1 or 2) whose body is
109    /// not exactly 4 bytes is an "Invalid Message Length" error. Both rules
110    /// only apply when the Enhanced Route Refresh capability was negotiated,
111    /// which MRT data cannot show, so the parser reports them as warnings
112    /// while retaining the message.
113    pub fn validation_warnings(&self) -> Vec<crate::error::BgpValidationWarning> {
114        use crate::error::BgpValidationWarning;
115        let mut warnings = Vec::new();
116        match self.subtype {
117            0 => {}
118            1 | 2 => {
119                if !self.data.is_empty() {
120                    warnings.push(BgpValidationWarning::InvalidRouteRefreshLength {
121                        subtype: self.subtype,
122                        length: 4 + self.data.len(),
123                    });
124                }
125            }
126            subtype => {
127                warnings.push(BgpValidationWarning::UnknownRouteRefreshSubtype { subtype });
128            }
129        }
130        warnings
131    }
132}
133
134/// BGP Open Message
135///
136/// ```text
137///  0                   1                   2                   3
138///  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
139///  +-+-+-+-+-+-+-+-+
140///  |    Version    |
141///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
142///  |     My Autonomous System      |
143///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
144///  |           Hold Time           |
145///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
146///  |                         BGP Identifier                        |
147///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
148///  | Opt Parm Len  |
149///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
150///  |                                                               |
151///  |             Optional Parameters (variable)                    |
152///  |                                                               |
153///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
154/// ```
155#[derive(Debug, Clone, PartialEq, Eq)]
156#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
157pub struct BgpOpenMessage {
158    pub version: u8,
159    pub asn: Asn,
160    pub hold_time: u16,
161    pub bgp_identifier: BgpIdentifier,
162    pub extended_length: bool,
163    pub opt_params: Vec<OptParam>,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
167#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
168pub struct OptParam {
169    pub param_type: u8,
170    pub param_value: ParamValue,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
174#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
175pub enum ParamValue {
176    Raw(Vec<u8>),
177    Capacities(Vec<Capability>),
178}
179
180/// BGP Capability.
181///
182/// - RFC3392: <https://datatracker.ietf.org/doc/html/rfc3392>
183/// - Capability codes: <https://www.iana.org/assignments/capability-codes/capability-codes.xhtml#capability-codes-2>
184#[derive(Debug, Clone, PartialEq, Eq)]
185#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
186pub struct Capability {
187    pub ty: BgpCapabilityType,
188    pub value: CapabilityValue,
189}
190
191/// Parsed BGP capability values
192#[derive(Debug, Clone, PartialEq, Eq)]
193#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
194pub enum CapabilityValue {
195    /// Raw unparsed capability data
196    Raw(Vec<u8>),
197    /// Multiprotocol Extensions capability - RFC 2858, Section 7
198    MultiprotocolExtensions(MultiprotocolExtensionsCapability),
199    /// Route Refresh capability - RFC 2918
200    RouteRefresh(RouteRefreshCapability),
201    /// Extended Next Hop capability - RFC 8950, Section 3
202    ExtendedNextHop(ExtendedNextHopCapability),
203    /// Graceful Restart capability - RFC 4724
204    GracefulRestart(GracefulRestartCapability),
205    /// 4-octet AS number capability - RFC 6793
206    FourOctetAs(FourOctetAsCapability),
207    /// ADD-PATH capability - RFC 7911
208    AddPath(AddPathCapability),
209    /// BGP Role capability - RFC 9234
210    BgpRole(BgpRoleCapability),
211    /// BGP Extended Message capability - RFC 8654
212    BgpExtendedMessage(BgpExtendedMessageCapability),
213}
214
215#[derive(Debug, Clone, PartialEq, Default, Eq)]
216#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
217/// BGP Update Message.
218///
219/// Corresponding RFC section: <https://datatracker.ietf.org/doc/html/rfc4271#section-4.3>
220pub struct BgpUpdateMessage {
221    /// Withdrawn prefixes in this update message.
222    ///
223    /// **IMPORTANT:** Do **not** access this field directly in order to get all withdrawn prefixes.
224    /// Some withdrawn prefixes may be present in the [`AttributeValue::MpUnreachNlri`] attribute,
225    /// and will **not** be included here. Accessing this field directly may cause you to miss
226    /// IPv6 or multi-protocol prefixes.
227    ///
228    /// Instead, use [`Elementor::bgp_update_to_elems`](crate::Elementor::bgp_update_to_elems) to reliably extract all withdrawn prefixes from the update,
229    /// or combine this field with prefixes found in the `MpUnreachNlri` attribute manually.
230    ///
231    /// See
232    /// * RFC4271 Section 4.3: <https://datatracker.ietf.org/doc/html/rfc4271#section-4.3>
233    /// * RFC4760 Section 4: <https://datatracker.ietf.org/doc/html/rfc4760#section-4>
234    pub withdrawn_prefixes: Vec<NetworkPrefix>,
235
236    /// BGP path attributes.
237    pub attributes: Attributes,
238
239    /// Network prefixes that are being advertised in this update message.
240    ///
241    /// **IMPORTANT:** Do **not** access this field directly in order to get all announced prefixes.
242    /// Some advertised prefixes may be present in the [`AttributeValue::MpReachNlri`] attribute,
243    /// and will **not** be included here. Accessing this field directly may cause you to miss
244    /// IPv6 or multi-protocol prefixes.
245    ///
246    /// Instead, use [`Elementor::bgp_update_to_elems`](crate::Elementor::bgp_update_to_elems) to reliably extract all announced prefixes from the update,
247    /// or combine this field with prefixes found in the `MpReachNlri` attribute manually.
248    ///
249    /// See
250    ///
251    /// * RFC4271 Section 4.3: <https://datatracker.ietf.org/doc/html/rfc4271#section-4.3>
252    /// * RFC4760 Section 3: <https://datatracker.ietf.org/doc/html/rfc4760#section-3>
253    pub announced_prefixes: Vec<NetworkPrefix>,
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
257#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
258pub struct BgpNotificationMessage {
259    pub error: BgpError,
260    pub data: Vec<u8>,
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::error::BgpValidationWarning;
267
268    fn route_refresh(subtype: u8, data: Vec<u8>) -> BgpRouteRefreshMessage {
269        BgpRouteRefreshMessage {
270            afi: 1,
271            subtype,
272            safi: 1,
273            data,
274        }
275    }
276
277    #[test]
278    fn test_route_refresh_validation_warnings() {
279        // Normal refreshes carry no findings, with or without ORF data
280        assert!(route_refresh(0, vec![]).validation_warnings().is_empty());
281        assert!(route_refresh(0, vec![0x01])
282            .validation_warnings()
283            .is_empty());
284
285        // BoRR/EoRR with an exactly 4-byte body are clean
286        assert!(route_refresh(1, vec![]).validation_warnings().is_empty());
287        assert!(route_refresh(2, vec![]).validation_warnings().is_empty());
288
289        // BoRR/EoRR with trailing bytes violate the RFC 7313 length rule
290        assert_eq!(
291            route_refresh(2, vec![0xDE, 0xAD, 0xBE]).validation_warnings(),
292            vec![BgpValidationWarning::InvalidRouteRefreshLength {
293                subtype: 2,
294                length: 7
295            }]
296        );
297
298        // Subtypes outside 0-2 are unknown
299        assert_eq!(
300            route_refresh(3, vec![]).validation_warnings(),
301            vec![BgpValidationWarning::UnknownRouteRefreshSubtype { subtype: 3 }]
302        );
303    }
304
305    #[test]
306    fn test_message_type() {
307        let open = BgpMessage::Open(BgpOpenMessage {
308            version: 4,
309            asn: Asn::new_32bit(1),
310            hold_time: 180,
311            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
312            extended_length: false,
313            opt_params: vec![],
314        });
315        assert_eq!(open.msg_type(), BgpMessageType::OPEN);
316
317        let update = BgpMessage::Update(BgpUpdateMessage::default());
318        assert_eq!(update.msg_type(), BgpMessageType::UPDATE);
319
320        let notification = BgpMessage::Notification(BgpNotificationMessage {
321            error: BgpError::Unknown(0, 0),
322            data: vec![],
323        });
324        assert_eq!(notification.msg_type(), BgpMessageType::NOTIFICATION);
325
326        let keepalive = BgpMessage::KeepAlive;
327        assert_eq!(keepalive.msg_type(), BgpMessageType::KEEPALIVE);
328    }
329
330    #[test]
331    #[cfg(feature = "serde")]
332    fn test_serde() {
333        let open = BgpMessage::Open(BgpOpenMessage {
334            version: 4,
335            asn: Asn::new_32bit(1),
336            hold_time: 180,
337            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
338            extended_length: false,
339            opt_params: vec![],
340        });
341        let serialized = serde_json::to_string(&open).unwrap();
342        let deserialized: BgpMessage = serde_json::from_str(&serialized).unwrap();
343        assert_eq!(open, deserialized);
344
345        let update = BgpMessage::Update(BgpUpdateMessage::default());
346        let serialized = serde_json::to_string(&update).unwrap();
347        let deserialized: BgpMessage = serde_json::from_str(&serialized).unwrap();
348        assert_eq!(update, deserialized);
349
350        let notification = BgpMessage::Notification(BgpNotificationMessage {
351            error: BgpError::Unknown(0, 0),
352            data: vec![],
353        });
354        let serialized = serde_json::to_string(&notification).unwrap();
355        let deserialized: BgpMessage = serde_json::from_str(&serialized).unwrap();
356        assert_eq!(notification, deserialized);
357
358        let keepalive = BgpMessage::KeepAlive;
359        let serialized = serde_json::to_string(&keepalive).unwrap();
360        let deserialized: BgpMessage = serde_json::from_str(&serialized).unwrap();
361        assert_eq!(keepalive, deserialized);
362    }
363}