Skip to main content

bgpkit_parser/parser/mrt/messages/
bgp4mp.rs

1use crate::error::{EncodingError, ParserError};
2use crate::models::*;
3use crate::parser::bgp::messages::parse_bgp_message;
4use crate::parser::{encode_asn, encode_ipaddr, ReadUtils};
5use bytes::{Buf, BufMut, Bytes, BytesMut};
6use std::convert::TryFrom;
7use std::net::{IpAddr, Ipv4Addr};
8
9pub(crate) fn is_short_zebra_open(data: &Bytes, asn_len: &AsnLength) -> bool {
10    if !matches!(asn_len, AsnLength::Bits16) {
11        return false;
12    }
13
14    let asn_bytes = asn_len.bytes() * 2;
15    data.len() >= asn_bytes + 19
16        && data[asn_bytes..asn_bytes + 16] == [0xff; 16]
17        && data[asn_bytes + 18] == BgpMessageType::OPEN as u8
18}
19
20pub(crate) fn uses_zebra_compat(sub_type: u16, data: &Bytes) -> bool {
21    match Bgp4MpType::try_from(sub_type) {
22        Ok(Bgp4MpType::StateChange) => data.len() == 8,
23        Ok(
24            Bgp4MpType::Message
25            | Bgp4MpType::MessageLocal
26            | Bgp4MpType::MessageAddpath
27            | Bgp4MpType::MessageLocalAddpath,
28        ) => is_short_zebra_open(data, &AsnLength::Bits16),
29        _ => false,
30    }
31}
32
33/// Parse MRT BGP4MP type
34///
35/// RFC: <https://www.rfc-editor.org/rfc/rfc6396#section-4.4>
36///
37pub fn parse_bgp4mp(sub_type: u16, input: Bytes) -> Result<Bgp4MpEnum, ParserError> {
38    let bgp4mp_type: Bgp4MpType = Bgp4MpType::try_from(sub_type)?;
39    let msg: Bgp4MpEnum = match bgp4mp_type {
40        Bgp4MpType::StateChange => Bgp4MpEnum::StateChange(parse_bgp4mp_state_change(
41            input,
42            AsnLength::Bits16,
43            &bgp4mp_type,
44        )?),
45        Bgp4MpType::StateChangeAs4 => Bgp4MpEnum::StateChange(parse_bgp4mp_state_change(
46            input,
47            AsnLength::Bits32,
48            &bgp4mp_type,
49        )?),
50        Bgp4MpType::Message | Bgp4MpType::MessageLocal => Bgp4MpEnum::Message(
51            parse_bgp4mp_message(input, false, AsnLength::Bits16, &bgp4mp_type)?,
52        ),
53        Bgp4MpType::MessageAs4 | Bgp4MpType::MessageAs4Local => Bgp4MpEnum::Message(
54            parse_bgp4mp_message(input, false, AsnLength::Bits32, &bgp4mp_type)?,
55        ),
56        Bgp4MpType::MessageAddpath | Bgp4MpType::MessageLocalAddpath => Bgp4MpEnum::Message(
57            parse_bgp4mp_message(input, true, AsnLength::Bits16, &bgp4mp_type)?,
58        ),
59        Bgp4MpType::MessageAs4Addpath | Bgp4MpType::MessageLocalAs4Addpath => Bgp4MpEnum::Message(
60            parse_bgp4mp_message(input, true, AsnLength::Bits32, &bgp4mp_type)?,
61        ),
62    };
63
64    Ok(msg)
65}
66
67/// Return the embedded BGP message length in a BGP4MP message body.
68///
69/// The BGP4MP envelope is defined by RFC 6396 Section 4.4.2 for 16-bit ASNs
70/// and Section 4.4.3 for AS4 variants:
71/// <https://www.rfc-editor.org/rfc/rfc6396#section-4.4.2>
72/// <https://www.rfc-editor.org/rfc/rfc6396#section-4.4.3>
73///
74/// RFC 8050 Section 3 defines the ADDPATH BGP4MP subtypes that reuse the same
75/// envelope before the encapsulated BGP message:
76/// <https://www.rfc-editor.org/rfc/rfc8050#section-3>
77///
78/// `total_size` is the MRT message body length. Subtracting the peer/local ASNs,
79/// interface index, AFI, and peer/local IP addresses leaves the encapsulated BGP
80/// message length.
81/*
824.4.2.  BGP4MP_MESSAGE Subtype:
83   0                   1                   2                   3
84   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
85  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
86  |         Peer AS Number        |        Local AS Number        |
87  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
88  |        Interface Index        |        Address Family         |
89  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
90  |                      Peer IP Address (variable)               |
91  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92  |                      Local IP Address (variable)              |
93  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94  |                    BGP Message... (variable)
95  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96
974.4.3.  BGP4MP_MESSAGE_AS4 Subtype
98  0                   1                   2                   3
99   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
100  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101  |                         Peer AS Number                        |
102  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103  |                         Local AS Number                       |
104  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105  |        Interface Index        |        Address Family         |
106  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107  |                      Peer IP Address (variable)               |
108  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109  |                      Local IP Address (variable)              |
110  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111  |                    BGP Message... (variable)
112  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113*/
114pub(crate) fn validate_bgp4mp_afi(afi: &Afi) -> Result<(), ParserError> {
115    match afi {
116        Afi::Ipv4 | Afi::Ipv6 => Ok(()),
117        Afi::LinkState => Err(ParserError::ParseError(
118            "Link-State AFI is invalid in a BGP4MP envelope".to_string(),
119        )),
120        Afi::L2vpn => Err(ParserError::ParseError(
121            "L2VPN AFI is invalid in a BGP4MP envelope".to_string(),
122        )),
123    }
124}
125
126pub(crate) fn bgp4mp_message_payload_len(
127    afi: &Afi,
128    asn_len: &AsnLength,
129    total_size: usize,
130) -> Result<usize, ParserError> {
131    validate_bgp4mp_afi(afi)?;
132    let ip_size = if matches!(afi, Afi::Ipv4) {
133        4 * 2
134    } else {
135        16 * 2
136    };
137    let asn_size = match asn_len {
138        AsnLength::Bits16 => 2 * 2,
139        AsnLength::Bits32 => 2 * 4,
140    };
141    // Saturating: on a truncated/inconsistent record the caller compares the
142    // result against `data.remaining()` and rejects the mismatch, so a
143    // saturated 0 simply fails that check instead of underflowing.
144    Ok(total_size
145        .saturating_sub(asn_size)
146        .saturating_sub(2)
147        .saturating_sub(2)
148        .saturating_sub(ip_size))
149}
150/*
151   0                   1                   2                   3
152   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
153  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
154  |         Peer AS Number        |        Local AS Number        |
155  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
156  |        Interface Index        |        Address Family         |
157  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
158  |                      Peer IP Address (variable)               |
159  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
160  |                      Local IP Address (variable)              |
161  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
162  |                    BGP Message... (variable)
163  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
164*/
165pub fn parse_bgp4mp_message(
166    mut data: Bytes,
167    add_path: bool,
168    asn_len: AsnLength,
169    msg_type: &Bgp4MpType,
170) -> Result<Bgp4MpMessage, ParserError> {
171    let total_size = data.len();
172    let is_short_zebra_open = is_short_zebra_open(&data, &asn_len);
173
174    let peer_asn: Asn = data.read_asn(asn_len)?;
175    let local_asn: Asn = data.read_asn(asn_len)?;
176
177    // Old Zebra versions omitted the interface index, AFI, and peer/local IP
178    // addresses from some BGP OPEN records. The BGP marker therefore follows
179    // the two 16-bit ASNs immediately. Limit this compatibility path to that
180    // exact signature so other malformed envelopes still fail normally.
181    if is_short_zebra_open {
182        let bgp_message = parse_bgp_message(&mut data, add_path, &asn_len)?;
183        return Ok(Bgp4MpMessage {
184            msg_type: *msg_type,
185            peer_asn,
186            local_asn,
187            interface_index: 0,
188            peer_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
189            local_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
190            bgp_message,
191        });
192    }
193
194    let interface_index: u16 = data.read_u16()?;
195    let afi: Afi = data.read_afi()?;
196    let should_read = bgp4mp_message_payload_len(&afi, &asn_len, total_size)?;
197    let peer_ip = data.read_address(&afi)?;
198    let local_ip = data.read_address(&afi)?;
199
200    if should_read != data.remaining() {
201        return Err(ParserError::TruncatedMsg(format!(
202            "truncated bgp4mp message: should read {} bytes, have {} bytes available",
203            should_read,
204            data.remaining()
205        )));
206    }
207    let bgp_message: BgpMessage = parse_bgp_message(&mut data, add_path, &asn_len)?;
208
209    Ok(Bgp4MpMessage {
210        msg_type: *msg_type,
211        peer_asn,
212        local_asn,
213        interface_index,
214        peer_ip,
215        local_ip,
216        bgp_message,
217    })
218}
219
220/// Whether any route in this update carries an ADD-PATH identifier (RFC 7911).
221pub(crate) fn carries_path_ids(message: &BgpMessage) -> bool {
222    let BgpMessage::Update(update) = message else {
223        return false;
224    };
225
226    update
227        .announced_prefixes
228        .iter()
229        .chain(update.withdrawn_prefixes.iter())
230        .any(|prefix| prefix.path_id.is_some())
231        || update.attributes.iter().any(|attribute| {
232            let (AttributeValue::MpReachNlri(nlri) | AttributeValue::MpUnreachNlri(nlri)) =
233                attribute
234            else {
235                return false;
236            };
237            nlri.prefixes.iter().any(|prefix| prefix.path_id.is_some())
238                || nlri
239                    .labeled_prefixes
240                    .as_ref()
241                    .is_some_and(|prefixes| prefixes.iter().any(|p| p.path_id.is_some()))
242                || nlri
243                    .evpn_nlris
244                    .as_ref()
245                    .is_some_and(|routes| routes.iter().any(|r| r.path_id.is_some()))
246        })
247}
248
249/// Whether the update carries any route at all, in any family.
250fn carries_routes(update: &BgpUpdateMessage) -> bool {
251    !update.announced_prefixes.is_empty()
252        || !update.withdrawn_prefixes.is_empty()
253        || update.attributes.iter().any(|attribute| {
254            let (AttributeValue::MpReachNlri(nlri) | AttributeValue::MpUnreachNlri(nlri)) =
255                attribute
256            else {
257                return false;
258            };
259            !nlri.prefixes.is_empty()
260                || nlri
261                    .labeled_prefixes
262                    .as_ref()
263                    .is_some_and(|p| !p.is_empty())
264                || nlri.evpn_nlris.as_ref().is_some_and(|r| !r.is_empty())
265        })
266}
267
268/// ADD-PATH is a property of the record subtype (RFC 8050), not of the message,
269/// so the payload and the subtype have to agree: encoding route identifiers
270/// under `MessageAs4` publishes bytes a reader decodes as NLRI.
271fn check_add_path_consistency(
272    msg_type: Bgp4MpType,
273    message: &BgpMessage,
274) -> Result<(), EncodingError> {
275    let BgpMessage::Update(update) = message else {
276        return Ok(());
277    };
278    if !carries_routes(update) {
279        return Ok(());
280    }
281
282    let add_path_subtype = matches!(
283        msg_type,
284        Bgp4MpType::MessageAddpath
285            | Bgp4MpType::MessageAs4Addpath
286            | Bgp4MpType::MessageLocalAddpath
287            | Bgp4MpType::MessageLocalAs4Addpath
288    );
289
290    if add_path_subtype != carries_path_ids(message) {
291        return Err(EncodingError::unencodable(
292            "BGP4MP message",
293            format!(
294                "subtype {msg_type:?} does not match the ADD-PATH identifiers present in the update"
295            ),
296        ));
297    }
298
299    Ok(())
300}
301
302impl Bgp4MpMessage {
303    pub fn encode(&self, asn_len: AsnLength) -> Result<Bytes, EncodingError> {
304        check_add_path_consistency(self.msg_type, &self.bgp_message)?;
305        let mut bytes = BytesMut::new();
306        bytes.extend(encode_asn(&self.peer_asn, &asn_len));
307        bytes.extend(encode_asn(&self.local_asn, &asn_len));
308        bytes.put_u16(self.interface_index);
309        bytes.put_u16(address_family(&self.peer_ip));
310        bytes.extend(encode_ipaddr(&self.peer_ip));
311        bytes.extend(encode_ipaddr(&self.local_ip));
312        bytes.put_slice(&self.bgp_message.encode(asn_len)?);
313        Ok(bytes.freeze())
314    }
315}
316
317/*
318   0                   1                   2                   3
319   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
320  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
321  |         Peer AS Number        |        Local AS Number        |
322  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
323  |        Interface Index        |        Address Family         |
324  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
325  |                      Peer IP Address (variable)               |
326  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
327  |                      Local IP Address (variable)              |
328  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
329  |            Old State          |          New State            |
330  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
331
332   0                   1                   2                   3
333   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
334  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
335  |                         Peer AS Number                        |
336  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
337  |                         Local AS Number                       |
338  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
339  |        Interface Index        |        Address Family         |
340  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
341  |                      Peer IP Address (variable)               |
342  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
343  |                      Local IP Address (variable)              |
344  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
345  |            Old State          |          New State            |
346  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
347*/
348pub fn parse_bgp4mp_state_change(
349    mut input: Bytes,
350    asn_len: AsnLength,
351    msg_type: &Bgp4MpType,
352) -> Result<Bgp4MpStateChange, ParserError> {
353    let is_short_zebra_state_change = matches!(asn_len, AsnLength::Bits16) && input.len() == 8;
354    let peer_asn: Asn = input.read_asn(asn_len)?;
355    let local_asn: Asn = input.read_asn(asn_len)?;
356
357    // Work around a historical Zebra corruption where an 8-byte state-change
358    // record contains only the two ASNs and the old/new FSM states.
359    if is_short_zebra_state_change {
360        let old_state = BgpState::try_from(input.read_u16()?)?;
361        let new_state = BgpState::try_from(input.read_u16()?)?;
362        return Ok(Bgp4MpStateChange {
363            msg_type: *msg_type,
364            peer_asn,
365            local_asn,
366            interface_index: 0,
367            peer_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
368            local_addr: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
369            old_state,
370            new_state,
371        });
372    }
373
374    let interface_index: u16 = input.read_u16()?;
375    let address_family: Afi = input.read_afi()?;
376    validate_bgp4mp_afi(&address_family)?;
377    let peer_ip = input.read_address(&address_family)?;
378    let local_addr = input.read_address(&address_family)?;
379    let old_state = BgpState::try_from(input.read_u16()?)?;
380    let new_state = BgpState::try_from(input.read_u16()?)?;
381    Ok(Bgp4MpStateChange {
382        msg_type: *msg_type,
383        peer_asn,
384        local_asn,
385        interface_index,
386        peer_ip,
387        local_addr,
388        old_state,
389        new_state,
390    })
391}
392
393impl Bgp4MpStateChange {
394    pub fn encode(&self, asn_len: AsnLength) -> Bytes {
395        let mut bytes = BytesMut::new();
396        bytes.extend(encode_asn(&self.peer_asn, &asn_len));
397        bytes.extend(encode_asn(&self.local_asn, &asn_len));
398        bytes.put_u16(self.interface_index);
399        bytes.put_u16(address_family(&self.peer_ip));
400        bytes.extend(encode_ipaddr(&self.peer_ip));
401        bytes.extend(encode_ipaddr(&self.local_addr));
402        bytes.put_u16(self.old_state as u16);
403        bytes.put_u16(self.new_state as u16);
404        bytes.freeze()
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411    use std::net::Ipv4Addr;
412
413    fn add_path_update() -> BgpUpdateMessage {
414        let route = EvpnNlri {
415            path_id: Some(7),
416            route_type: EvpnRouteType::MacIpAdvertisement,
417            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]),
418            payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement {
419                esi: [0; 10],
420                ethernet_tag_id: 0,
421                mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d],
422                ip: None,
423                raw_label: 100,
424                raw_label2: None,
425            }),
426        };
427        BgpUpdateMessage {
428            withdrawn_prefixes: vec![],
429            attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri(
430                Nlri::new_evpn_reachable(
431                    Some(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11))),
432                    vec![route],
433                ),
434            )]),
435            announced_prefixes: vec![],
436        }
437    }
438
439    fn message(msg_type: Bgp4MpType, update: BgpUpdateMessage) -> Bgp4MpMessage {
440        Bgp4MpMessage {
441            msg_type,
442            peer_asn: Asn::new_32bit(65000),
443            local_asn: Asn::new_32bit(65000),
444            interface_index: 0,
445            peer_ip: IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11)),
446            local_ip: IpAddr::V4(Ipv4Addr::new(10, 10, 0, 254)),
447            bgp_message: BgpMessage::Update(update),
448        }
449    }
450
451    #[test]
452    fn test_add_path_payload_requires_an_add_path_subtype() {
453        let update = add_path_update();
454        assert!(carries_path_ids(&BgpMessage::Update(update.clone())));
455
456        // MessageAs4 says nothing about ADD-PATH, so the identifiers would be
457        // read back as NLRI.
458        let err = message(Bgp4MpType::MessageAs4, update.clone())
459            .encode(AsnLength::Bits32)
460            .expect_err("a plain subtype cannot carry ADD-PATH identifiers");
461        assert!(format!("{err:?}").contains("ADD-PATH"), "{err:?}");
462
463        message(Bgp4MpType::MessageAs4Addpath, update)
464            .encode(AsnLength::Bits32)
465            .expect("the ADD-PATH subtype accepts them");
466    }
467
468    #[test]
469    fn test_plain_payload_requires_a_plain_subtype() {
470        let route = EvpnNlri {
471            path_id: None,
472            route_type: EvpnRouteType::MacIpAdvertisement,
473            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]),
474            payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement {
475                esi: [0; 10],
476                ethernet_tag_id: 0,
477                mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d],
478                ip: None,
479                raw_label: 100,
480                raw_label2: None,
481            }),
482        };
483        let update = BgpUpdateMessage {
484            withdrawn_prefixes: vec![],
485            attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri(
486                Nlri::new_evpn_reachable(
487                    Some(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11))),
488                    vec![route],
489                ),
490            )]),
491            announced_prefixes: vec![],
492        };
493
494        let err = message(Bgp4MpType::MessageAs4Addpath, update.clone())
495            .encode(AsnLength::Bits32)
496            .expect_err("an ADD-PATH subtype needs identifiers");
497        assert!(format!("{err:?}").contains("ADD-PATH"), "{err:?}");
498
499        message(Bgp4MpType::MessageAs4, update)
500            .encode(AsnLength::Bits32)
501            .expect("a plain subtype accepts a plain payload");
502    }
503
504    use std::net::IpAddr;
505    use std::str::FromStr;
506
507    #[test]
508    fn test_bgp4mp_message_encode_uses_subtype_asn_width() {
509        let message = Bgp4MpMessage {
510            msg_type: Bgp4MpType::Message,
511            peer_asn: Asn::new_32bit(65000),
512            local_asn: Asn::new_32bit(65001),
513            interface_index: 1,
514            peer_ip: IpAddr::from_str("10.0.0.1").unwrap(),
515            local_ip: IpAddr::from_str("10.0.0.2").unwrap(),
516            bgp_message: BgpMessage::KeepAlive,
517        };
518
519        let encoded = message.encode(AsnLength::Bits16).unwrap();
520        let parsed = parse_bgp4mp(Bgp4MpType::Message as u16, encoded).unwrap();
521
522        match parsed {
523            Bgp4MpEnum::Message(parsed) => {
524                assert_eq!(parsed.peer_asn, Asn::new_16bit(65000));
525                assert_eq!(parsed.local_asn, Asn::new_16bit(65001));
526                assert_eq!(parsed.interface_index, 1);
527                assert_eq!(parsed.peer_ip, message.peer_ip);
528                assert_eq!(parsed.local_ip, message.local_ip);
529                assert_eq!(parsed.bgp_message, BgpMessage::KeepAlive);
530            }
531            other => panic!("unexpected BGP4MP message: {other:?}"),
532        }
533    }
534
535    #[test]
536    fn test_bgp4mp_message_rejects_link_state_envelope_afi() {
537        let mut data = BytesMut::new();
538        data.put_u16(65000);
539        data.put_u16(65001);
540        data.put_u16(0);
541        data.put_u16(Afi::LinkState as u16);
542        data.put_slice(&BgpMessage::KeepAlive.encode(AsnLength::Bits16).unwrap());
543
544        let error = match parse_bgp4mp(Bgp4MpType::Message as u16, data.freeze()) {
545            Err(error) => error,
546            Ok(message) => panic!("unexpectedly parsed BGP4MP message: {message:?}"),
547        };
548        assert!(matches!(
549            error,
550            ParserError::ParseError(message)
551                if message == "Link-State AFI is invalid in a BGP4MP envelope"
552        ));
553    }
554
555    #[test]
556    fn test_bgp4mp_state_change_rejects_link_state_envelope_afi() {
557        let mut data = BytesMut::new();
558        data.put_u16(65000);
559        data.put_u16(65001);
560        data.put_u16(0);
561        data.put_u16(Afi::LinkState as u16);
562        data.put_u16(BgpState::Idle as u16);
563        data.put_u16(BgpState::Connect as u16);
564
565        let error = match parse_bgp4mp(Bgp4MpType::StateChange as u16, data.freeze()) {
566            Err(error) => error,
567            Ok(message) => panic!("unexpectedly parsed BGP4MP state change: {message:?}"),
568        };
569        assert!(matches!(
570            error,
571            ParserError::ParseError(message)
572                if message == "Link-State AFI is invalid in a BGP4MP envelope"
573        ));
574    }
575}