Skip to main content

bgpkit_parser/parser/bgp/
messages.rs

1use crate::models::*;
2use bytes::{Buf, BufMut, Bytes, BytesMut};
3use std::convert::TryFrom;
4use std::net::Ipv4Addr;
5
6use crate::encoder::sink::{put_u16_len_slice, put_u8_len_slice, with_u16_len};
7use crate::error::{check_max, BgpValidationWarning, EncodingError, ParserError};
8use crate::models::capabilities::{
9    AddPathCapability, BgpCapabilityType, BgpExtendedMessageCapability, BgpRoleCapability,
10    ExtendedNextHopCapability, FourOctetAsCapability, GracefulRestartCapability,
11    MultiprotocolExtensionsCapability, RouteRefreshCapability,
12};
13use crate::models::error::BgpError;
14use crate::parser::bgp::attributes::parse_attributes;
15use crate::parser::{encode_nlri_prefixes, parse_nlri_list, ReadUtils};
16use log::warn;
17use zerocopy::big_endian::{U16, U32};
18use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
19
20/// On-wire BGP OPEN fixed header layout (10 bytes, network byte order).
21#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
22#[repr(C)]
23struct RawBgpOpenHeader {
24    version: u8,
25    asn: U16,
26    hold_time: U16,
27    bgp_identifier: U32,
28    opt_params_len: u8,
29}
30
31const _: () = assert!(size_of::<RawBgpOpenHeader>() == 10);
32
33/// On-wire BGP ROUTE-REFRESH fixed body layout (4 bytes, network byte order).
34/// RFC 2918; the reserved byte carries the message subtype per RFC 7313.
35#[derive(IntoBytes, FromBytes, KnownLayout, Immutable)]
36#[repr(C)]
37struct RawRouteRefreshHeader {
38    afi: U16,
39    subtype: u8,
40    safi: u8,
41}
42
43const _: () = assert!(size_of::<RawRouteRefreshHeader>() == 4);
44
45pub(crate) fn read_and_validate_bgp_marker(data: &mut Bytes) -> Result<(), ParserError> {
46    data.has_n_remaining(16)?;
47
48    let mut marker = [0u8; 16];
49    data.copy_to_slice(&mut marker);
50    if marker != [0xFF; 16] {
51        warn!("BGP message marker is not all 0xFF bytes (invalid per RFC 4271)");
52    }
53
54    Ok(())
55}
56
57/// BGP message
58///
59/// Format:
60/// ```text
61/// 0                   1                   2                   3
62/// 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
63/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
64/// |                                                               |
65/// +                                                               +
66/// |                                                               |
67/// +                                                               +
68/// |                           Marker                              |
69/// +                                                               +
70/// |                                                               |
71/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72/// |          Length               |      Type     |
73/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
74/// ```
75pub fn parse_bgp_message(
76    data: &mut Bytes,
77    add_path: bool,
78    asn_len: &AsnLength,
79) -> Result<BgpMessage, ParserError> {
80    let total_size = data.len();
81    data.has_n_remaining(19)?;
82    read_and_validate_bgp_marker(data)?;
83
84    /*
85    This 2-octet unsigned integer indicates the total length of the
86    message, including the header in octets.  Thus, it allows one
87    to locate the (Marker field of the) next message in the TCP
88    stream.  The value of the Length field MUST always be at least
89    19 and no greater than 4096, and MAY be further constrained,
90    depending on the message type.  "padding" of extra data after
91    the message is not allowed.  Therefore, the Length field MUST
92    have the smallest value required, given the rest of the
93    message.
94    */
95    let length = data.read_u16()?;
96
97    // Validate message length according to RFC 8654
98    // For now, we allow extended messages for all message types except when we know
99    // for certain that extended messages are not supported.
100    // RFC 8654: Extended messages up to 65535 bytes are allowed for all message types
101    // except OPEN and KEEPALIVE (which remain limited to 4096 bytes).
102    // However, since we're parsing MRT data without session context, we'll be permissive.
103    let max_length = 65535; // RFC 8654 maximum
104    if !(19..=max_length).contains(&length) {
105        return Err(ParserError::ParseError(format!(
106            "invalid BGP message length {length}"
107        )));
108    }
109
110    // Validate length >= 19 before any arithmetic to prevent underflow
111    let length_usize = length as usize;
112    let bgp_msg_length = if length_usize > total_size {
113        total_size.saturating_sub(19)
114    } else {
115        length_usize.saturating_sub(19)
116    };
117
118    let msg_type: BgpMessageType = match BgpMessageType::try_from(data.read_u8()?) {
119        Ok(t) => t,
120        Err(_) => {
121            return Err(ParserError::ParseError(
122                "Unknown BGP Message Type".to_string(),
123            ))
124        }
125    };
126
127    // Additional validation for OPEN and KEEPALIVE messages per RFC 8654
128    // These message types cannot exceed 4096 bytes even with extended message capability
129    match msg_type {
130        BgpMessageType::OPEN | BgpMessageType::KEEPALIVE => {
131            if length > 4096 {
132                return Err(ParserError::ParseError(format!(
133                    "BGP {} message length {} exceeds maximum allowed 4096 bytes (RFC 8654)",
134                    match msg_type {
135                        BgpMessageType::OPEN => "OPEN",
136                        BgpMessageType::KEEPALIVE => "KEEPALIVE",
137                        _ => unreachable!("only OPEN and KEEPALIVE take this length check"),
138                    },
139                    length
140                )));
141            }
142        }
143        BgpMessageType::UPDATE | BgpMessageType::NOTIFICATION | BgpMessageType::ROUTE_REFRESH => {
144            // These can be extended messages up to 65535 bytes when capability is negotiated
145            // Since we're parsing MRT data, we allow extended lengths
146        }
147    }
148
149    if data.remaining() != bgp_msg_length {
150        warn!(
151            "BGP message length {} does not match the actual length {} (parsing BGP message)",
152            bgp_msg_length,
153            data.remaining()
154        );
155    }
156    data.has_n_remaining(bgp_msg_length)?;
157    let mut msg_data = data.split_to(bgp_msg_length);
158
159    Ok(match msg_type {
160        BgpMessageType::OPEN => BgpMessage::Open(parse_bgp_open_message(&mut msg_data)?),
161        BgpMessageType::UPDATE => {
162            BgpMessage::Update(parse_bgp_update_message(msg_data, add_path, asn_len)?)
163        }
164        BgpMessageType::NOTIFICATION => {
165            BgpMessage::Notification(parse_bgp_notification_message(msg_data)?)
166        }
167        BgpMessageType::KEEPALIVE => BgpMessage::KeepAlive,
168        BgpMessageType::ROUTE_REFRESH => {
169            BgpMessage::RouteRefresh(parse_bgp_route_refresh_message(&mut msg_data)?)
170        }
171    })
172}
173
174/// Parse BGP ROUTE-REFRESH message.
175///
176/// RFC 2918 body: AFI (2 bytes), Reserved (1 byte), SAFI (1 byte). RFC 7313
177/// redefines the reserved byte as a message subtype. Any trailing bytes (such
178/// as ORF entries per RFC 5291) are retained raw.
179pub fn parse_bgp_route_refresh_message(
180    input: &mut Bytes,
181) -> Result<BgpRouteRefreshMessage, ParserError> {
182    input.has_n_remaining(4)?;
183    let mut header_bytes = [0u8; 4];
184    input.copy_to_slice(&mut header_bytes);
185    // Single bounds check via zerocopy instead of three sequential cursor reads.
186    let raw = RawRouteRefreshHeader::ref_from_bytes(&header_bytes)
187        .expect("header_bytes is exactly 4 bytes with no alignment requirement");
188
189    Ok(BgpRouteRefreshMessage {
190        afi: raw.afi.get(),
191        subtype: raw.subtype,
192        safi: raw.safi,
193        data: input.split_to(input.remaining()).to_vec(),
194    })
195}
196
197impl BgpRouteRefreshMessage {
198    pub fn encode(&self) -> Bytes {
199        let raw = RawRouteRefreshHeader {
200            afi: U16::new(self.afi),
201            subtype: self.subtype,
202            safi: self.safi,
203        };
204        let mut bytes = BytesMut::with_capacity(4 + self.data.len());
205        bytes.put_slice(raw.as_bytes());
206        bytes.put_slice(&self.data);
207        bytes.freeze()
208    }
209}
210
211/// Parse BGP NOTIFICATION message.
212///
213/// The BGP NOTIFICATION messages contains BGP error codes received from a connected BGP router. The
214/// error code is parsed into [BgpError] data structure and any unknown codes will produce warning
215/// messages, but not critical errors.
216///
217pub fn parse_bgp_notification_message(
218    mut input: Bytes,
219) -> Result<BgpNotificationMessage, ParserError> {
220    let error_code = input.read_u8()?;
221    let error_subcode = input.read_u8()?;
222
223    Ok(BgpNotificationMessage {
224        error: BgpError::new(error_code, error_subcode),
225        data: input.read_n_bytes(input.len())?,
226    })
227}
228
229impl BgpNotificationMessage {
230    pub fn encode(&self) -> Bytes {
231        let mut buf = BytesMut::new();
232        let (code, subcode) = self.error.get_codes();
233        buf.put_u8(code);
234        buf.put_u8(subcode);
235        buf.put_slice(&self.data);
236        buf.freeze()
237    }
238}
239
240/// Parse BGP OPEN message.
241///
242/// The parsing of BGP OPEN message also includes decoding the BGP capabilities.
243///
244/// RFC 4271: <https://datatracker.ietf.org/doc/html/rfc4271>
245/// ```text
246///       0                   1                   2                   3
247///       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
248///       +-+-+-+-+-+-+-+-+
249///       |    Version    |
250///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
251///       |     My Autonomous System      |
252///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
253///       |           Hold Time           |
254///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
255///       |                         BGP Identifier                        |
256///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
257///       | Opt Parm Len  |
258///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
259///       |                                                               |
260///       |             Optional Parameters (variable)                    |
261///       |                                                               |
262///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
263///
264///       0                   1
265///       0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
266///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
267///       |  Parm. Type   | Parm. Length  |  Parameter Value (variable)
268///       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
269/// ```
270pub fn parse_bgp_open_message(input: &mut Bytes) -> Result<BgpOpenMessage, ParserError> {
271    input.has_n_remaining(10)?;
272    let mut header_bytes = [0u8; 10];
273    input.copy_to_slice(&mut header_bytes);
274    // Single bounds check via zerocopy instead of five sequential cursor reads.
275    let raw = RawBgpOpenHeader::ref_from_bytes(&header_bytes)
276        .expect("header_bytes is exactly 10 bytes with no alignment requirement");
277
278    let version = raw.version;
279    let asn = Asn::new_16bit(raw.asn.get());
280    let hold_time = raw.hold_time.get();
281    let bgp_identifier = Ipv4Addr::from(raw.bgp_identifier.get());
282    let mut opt_params_len: u16 = raw.opt_params_len as u16;
283
284    let mut extended_length = false;
285    let mut first = true;
286
287    let mut params: Vec<OptParam> = vec![];
288    while input.remaining() >= 2 {
289        let mut param_type = input.read_u8()?;
290        if first {
291            if opt_params_len == 0 && param_type == 255 {
292                return Err(ParserError::ParseError(
293                    "RFC 9072 violation: Non-Extended Optional Parameters Length must not be 0 when using extended format".to_string()
294                ));
295            }
296            // first parameter, check if it is extended length message
297            if opt_params_len != 0 && param_type == 255 {
298                // RFC 9072: https://datatracker.ietf.org/doc/rfc9072/
299                //
300                // 0                   1                   2                   3
301                // 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
302                //     +-+-+-+-+-+-+-+-+
303                //     |    Version    |
304                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
305                //     |     My Autonomous System      |
306                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
307                //     |           Hold Time           |
308                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
309                //     |                         BGP Identifier                        |
310                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
311                //     |Non-Ext OP Len.|Non-Ext OP Type|  Extended Opt. Parm. Length   |
312                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
313                //     |                                                               |
314                //     |             Optional Parameters (variable)                    |
315                //     |                                                               |
316                //     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
317                //
318                //         Figure 1: Extended Encoding OPEN Format
319                extended_length = true;
320                opt_params_len = input.read_u16()?;
321                if opt_params_len == 0 {
322                    break;
323                }
324                // let pos_end = input.position() + opt_params_len as u64;
325                if input.remaining() != opt_params_len as usize {
326                    warn!(
327                    "BGP open message length {} does not match the actual length {} (parsing BGP OPEN message)",
328                    opt_params_len,
329                    input.remaining()
330                );
331                }
332
333                param_type = input.read_u8()?;
334            }
335            first = false;
336        }
337        // reaching here means all the remain params are regular non-extended-length parameters
338
339        let param_len = match extended_length {
340            true => input.read_u16()?,
341            false => input.read_u8()? as u16,
342        };
343
344        // https://tools.ietf.org/html/rfc3392
345        // https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml#bgp-parameters-11
346
347        let param_value = match param_type {
348            2 => {
349                let mut capacities = vec![];
350
351                // Split off only the bytes for this parameter to avoid consuming other parameters
352                input.has_n_remaining(param_len as usize)?;
353                let mut param_data = input.split_to(param_len as usize);
354
355                while param_data.remaining() >= 2 {
356                    // capability codes:
357                    // https://www.iana.org/assignments/capability-codes/capability-codes.xhtml#capability-codes-2
358                    let code = param_data.read_u8()?;
359                    let len = param_data.read_u8()? as u16; // Capability length is ALWAYS 1 byte per RFC 5492
360
361                    let capability_data = param_data.read_n_bytes(len as usize)?;
362                    let capability_type = BgpCapabilityType::from(code);
363
364                    // Parse specific capability types with fallback to raw bytes
365                    macro_rules! parse_capability {
366                        ($parser:path, $variant:ident) => {
367                            match $parser(Bytes::from(capability_data.clone())) {
368                                Ok(parsed) => CapabilityValue::$variant(parsed),
369                                Err(_) => CapabilityValue::Raw(capability_data),
370                            }
371                        };
372                    }
373
374                    let capability_value = match capability_type {
375                        BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4 => {
376                            parse_capability!(
377                                MultiprotocolExtensionsCapability::parse,
378                                MultiprotocolExtensions
379                            )
380                        }
381                        BgpCapabilityType::ROUTE_REFRESH_CAPABILITY_FOR_BGP_4 => {
382                            parse_capability!(RouteRefreshCapability::parse, RouteRefresh)
383                        }
384                        BgpCapabilityType::EXTENDED_NEXT_HOP_ENCODING => {
385                            parse_capability!(ExtendedNextHopCapability::parse, ExtendedNextHop)
386                        }
387                        BgpCapabilityType::GRACEFUL_RESTART_CAPABILITY => {
388                            parse_capability!(GracefulRestartCapability::parse, GracefulRestart)
389                        }
390                        BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY => {
391                            parse_capability!(FourOctetAsCapability::parse, FourOctetAs)
392                        }
393                        BgpCapabilityType::ADD_PATH_CAPABILITY => {
394                            parse_capability!(AddPathCapability::parse, AddPath)
395                        }
396                        BgpCapabilityType::BGP_ROLE => {
397                            parse_capability!(BgpRoleCapability::parse, BgpRole)
398                        }
399                        BgpCapabilityType::BGP_EXTENDED_MESSAGE => {
400                            parse_capability!(
401                                BgpExtendedMessageCapability::parse,
402                                BgpExtendedMessage
403                            )
404                        }
405                        _ => CapabilityValue::Raw(capability_data),
406                    };
407
408                    capacities.push(Capability {
409                        ty: capability_type,
410                        value: capability_value,
411                    });
412                }
413
414                ParamValue::Capacities(capacities)
415            }
416            _ => {
417                // unsupported param, read as raw bytes
418                let bytes = input.read_n_bytes(param_len as usize)?;
419                ParamValue::Raw(bytes)
420            }
421        };
422        params.push(OptParam {
423            param_type,
424            param_value,
425        });
426    }
427
428    Ok(BgpOpenMessage {
429        version,
430        asn,
431        hold_time,
432        bgp_identifier,
433        extended_length,
434        opt_params: params,
435    })
436}
437
438fn encode_bgp_open_param_value(param: &OptParam) -> Result<Bytes, EncodingError> {
439    let mut buf = BytesMut::new();
440    match &param.param_value {
441        ParamValue::Capacities(capacities) => {
442            for cap in capacities {
443                buf.put_u8(cap.ty.into());
444                let encoded_value = match &cap.value {
445                    CapabilityValue::MultiprotocolExtensions(mp) => mp.encode(),
446                    CapabilityValue::RouteRefresh(rr) => rr.encode(),
447                    CapabilityValue::ExtendedNextHop(enh) => enh.encode(),
448                    CapabilityValue::GracefulRestart(gr) => gr.encode(),
449                    CapabilityValue::FourOctetAs(foa) => foa.encode(),
450                    CapabilityValue::AddPath(ap) => ap.encode(),
451                    CapabilityValue::BgpRole(br) => br.encode(),
452                    CapabilityValue::BgpExtendedMessage(bem) => bem.encode(),
453                    CapabilityValue::Raw(raw) => Bytes::from(raw.clone()),
454                };
455                put_u8_len_slice(&mut buf, "BGP capability value length", &encoded_value)?;
456            }
457        }
458        ParamValue::Raw(bytes) => buf.put_slice(bytes),
459    }
460    Ok(buf.freeze())
461}
462
463impl BgpOpenMessage {
464    pub fn encode(&self) -> Result<Bytes, EncodingError> {
465        let encoded_params: Vec<(u8, Bytes)> = self
466            .opt_params
467            .iter()
468            .map(|param| {
469                // RFC 9072 reserves optional parameter type 255 as the
470                // extended-length marker; emitting it as a real parameter
471                // would be misparsed on the receiving side.
472                if param.param_type == u8::MAX {
473                    return Err(EncodingError::unencodable(
474                        "BGP OPEN optional parameter type",
475                        "type 255 is reserved by RFC 9072 as the extended-length marker",
476                    ));
477                }
478                Ok((param.param_type, encode_bgp_open_param_value(param)?))
479            })
480            .collect::<Result<_, _>>()?;
481
482        let values_len: usize = encoded_params.iter().map(|(_, value)| value.len()).sum();
483        // Non-extended framing spends 2 header octets (type + 1-octet length) per
484        // parameter; if that would overflow the single-octet aggregate length field
485        // we must switch to RFC 9072 extended framing (3 header octets each).
486        let non_extended_params_len = 2 * encoded_params.len() + values_len;
487        let use_extended_length =
488            self.extended_length || non_extended_params_len > u8::MAX as usize;
489        let per_param_header = if use_extended_length { 3 } else { 2 };
490        let encoded_params_len = per_param_header * encoded_params.len() + values_len;
491
492        let mut buf = BytesMut::with_capacity(
493            size_of::<RawBgpOpenHeader>()
494                + encoded_params_len
495                + if use_extended_length { 3 } else { 0 },
496        );
497        let raw_header = RawBgpOpenHeader {
498            version: self.version,
499            asn: U16::new(self.asn.into()),
500            hold_time: U16::new(self.hold_time),
501            bgp_identifier: U32::new(u32::from(self.bgp_identifier)),
502            opt_params_len: if use_extended_length {
503                u8::MAX
504            } else {
505                encoded_params_len as u8
506            },
507        };
508        buf.extend_from_slice(raw_header.as_bytes());
509
510        if use_extended_length {
511            // RFC 9072: type 255 signals a two-octet aggregate length and
512            // two-octet lengths for each optional parameter.
513            check_max(
514                "BGP OPEN extended optional parameters total length",
515                encoded_params_len,
516                u16::MAX as usize,
517            )?;
518            buf.put_u8(u8::MAX);
519            buf.put_u16(encoded_params_len as u16);
520        }
521
522        for (param_type, value) in encoded_params {
523            buf.put_u8(param_type);
524            if use_extended_length {
525                // Cannot overflow: the aggregate check above bounds
526                // encoded_params_len, and each value.len() <= encoded_params_len - 3.
527                debug_assert!(value.len() <= u16::MAX as usize);
528                buf.put_u16(value.len() as u16);
529            } else {
530                // Fits in a u8: use_extended_length is set above whenever the
531                // non-extended framing (2 + value.len() per param) would exceed u8::MAX.
532                buf.put_u8(value.len() as u8);
533            }
534            buf.put_slice(&value);
535        }
536        Ok(buf.freeze())
537    }
538}
539
540/// read nlri portion of a bgp update message.
541///
542/// Returns `Ok(vec![])` for empty NLRI. Returns `Err` for malformed NLRI
543/// (invalid prefix lengths, truncated data), so that the caller
544/// in `parse_bgp_update_message` can convert it to a `MalformedNlri` warning.
545fn read_nlri(input: Bytes, afi: &Afi, add_path: bool) -> Result<Vec<NetworkPrefix>, ParserError> {
546    let length = input.len();
547    if length == 0 {
548        return Ok(vec![]);
549    }
550    if length == 1 && input[0] != 0 {
551        // A single non-zero byte cannot be a valid NLRI: a valid 1-byte NLRI
552        // encodes only the default route (prefix length 0, no prefix octets).
553        warn!("seeing strange one-byte NLRI field (parsing NLRI in BGP UPDATE message)");
554        return Err(ParserError::ParseError(
555            "one-byte NLRI field with non-zero value is not a valid encoding".to_string(),
556        ));
557    }
558
559    parse_nlri_list(input, add_path, afi)
560}
561
562/// read bgp update message.
563///
564/// RFC: <https://tools.ietf.org/html/rfc4271#section-4.3>
565///
566/// Per RFC 7606, NLRI parse errors are non-fatal: the message is returned with
567/// partial data and a [`BgpValidationWarning::MalformedNlri`] appended to
568/// `attributes.validation_warnings`. Callers that want RFC 7606 treat-as-withdrawal
569/// semantics can inspect the warnings and act accordingly. Attribute-section
570/// framing errors (wrong length fields, truncated data) remain fatal.
571pub fn parse_bgp_update_message(
572    mut input: Bytes,
573    add_path: bool,
574    asn_len: &AsnLength,
575) -> Result<BgpUpdateMessage, ParserError> {
576    // NOTE: AFI for routes outside attributes are IPv4 ONLY.
577    let afi = Afi::Ipv4;
578
579    // parse withdrawn prefixes NLRI
580    let withdrawn_bytes_length_raw = input.read_u16()?;
581    let withdrawn_bytes_length = withdrawn_bytes_length_raw as usize;
582    input.has_n_remaining(withdrawn_bytes_length)?;
583    let withdrawn_bytes = input.split_to(withdrawn_bytes_length);
584    let (withdrawn_prefixes, withdrawn_nlri_error) =
585        match read_nlri(withdrawn_bytes.clone(), &afi, add_path) {
586            Ok(pfxs) => (pfxs, None),
587            Err(e) => (
588                Vec::new(),
589                Some(BgpValidationWarning::MalformedNlri {
590                    nlri_type: "withdrawn",
591                    reason: e.to_string(),
592                    raw_bytes: withdrawn_bytes.to_vec(),
593                }),
594            ),
595        };
596
597    // parse attributes
598    let attribute_length_raw = input.read_u16()?;
599    // Defensive check: ensure attribute_length fits in usize
600    // u16 to usize conversion is always safe on 32/64-bit platforms,
601    // but this check ensures safety on all architectures
602    let attribute_length = attribute_length_raw as usize;
603
604    input.has_n_remaining(attribute_length)?;
605    let attr_data_slice = input.split_to(attribute_length);
606    let mut attributes = parse_attributes(attr_data_slice, asn_len, add_path, None, None, None)?;
607
608    // parse announced prefixes nlri.
609    // the remaining bytes are announced prefixes.
610    let announced_bytes_present = !input.is_empty();
611    let (announced_prefixes, announced_nlri_error) = match read_nlri(input.clone(), &afi, add_path)
612    {
613        Ok(pfxs) => (pfxs, None),
614        Err(e) => (
615            Vec::new(),
616            Some(BgpValidationWarning::MalformedNlri {
617                nlri_type: "announced",
618                reason: e.to_string(),
619                raw_bytes: input.to_vec(),
620            }),
621        ),
622    };
623
624    // validate mandatory attributes.
625    // Use `announced_bytes_present` (wire-level) rather than
626    // `!announced_prefixes.is_empty()` (parse result) so that a malformed
627    // NLRI section still triggers mandatory-attribute validation — the
628    // UPDATE clearly intended to announce routes.
629    let is_announcement =
630        announced_bytes_present || attributes.has_attr(AttrType::MP_REACHABLE_NLRI);
631    let has_standard_nlri = announced_bytes_present;
632    attributes.check_mandatory_attributes(is_announcement, has_standard_nlri);
633    // an UPDATE can announce classic IPv4 unicast NLRI next to an MP_REACH_NLRI that carries
634    // IPVPN or EVPN routes; D-PATH is invalid on those classic announcements either way, and
635    // withdrawals carry no such attributes to judge (RFC 10039 §4)
636    attributes.check_domain_path_with_classic_nlri(has_standard_nlri);
637
638    // Attach NLRI parse warnings (RFC 7606 §5.3 treat-as-withdrawal evidence)
639    if let Some(w) = withdrawn_nlri_error {
640        attributes.add_validation_warning(w);
641    }
642    if let Some(w) = announced_nlri_error {
643        attributes.add_validation_warning(w);
644    }
645
646    Ok(BgpUpdateMessage {
647        withdrawn_prefixes,
648        attributes,
649        announced_prefixes,
650    })
651}
652
653impl BgpUpdateMessage {
654    pub fn encode(&self, asn_len: AsnLength) -> Result<Bytes, EncodingError> {
655        let mut bytes = BytesMut::new();
656
657        // withdrawn prefixes
658        let withdrawn_bytes = encode_nlri_prefixes(&self.withdrawn_prefixes);
659        put_u16_len_slice(
660            &mut bytes,
661            "BGP UPDATE withdrawn routes length",
662            &withdrawn_bytes,
663        )?;
664
665        // attributes
666        with_u16_len(&mut bytes, "BGP UPDATE total path attribute length", |b| {
667            self.attributes.encode_to(asn_len, b)
668        })?;
669
670        bytes.extend(encode_nlri_prefixes(&self.announced_prefixes));
671        Ok(bytes.freeze())
672    }
673
674    /// Check if this is an end-of-rib message.
675    ///
676    /// <https://datatracker.ietf.org/doc/html/rfc4724#section-2>
677    /// End-of-rib message is a special update message that contains no NLRI or withdrawal NLRI prefixes.
678    pub fn is_end_of_rib(&self) -> bool {
679        // there are two cases for end-of-rib message:
680        // 1. IPv4 unicast address family: no announced, no withdrawn, no attributes
681        // 2. Other cases: no announced, no withdrawal, only MP_UNREACH_NRLI with no prefixes
682
683        if !self.announced_prefixes.is_empty() || !self.withdrawn_prefixes.is_empty() {
684            // has announced or withdrawal IPv4 unicast prefixes:
685            // definitely not end-of-rib
686
687            return false;
688        }
689
690        if self.attributes.inner.is_empty() {
691            // no attributes, no prefixes:
692            // case 1 end-of-rib
693            return true;
694        }
695
696        // has some attributes, it can only be withdrawal with no prefixes
697
698        if self.attributes.inner.len() > 1 {
699            // has more than one attributes, not end-of-rib
700            return false;
701        }
702
703        // has only one attribute, check if it is withdrawal attribute
704        if let AttributeValue::MpUnreachNlri(nlri) = &self.attributes.inner.first().unwrap().value {
705            // Every family's collection has to be empty: an EVPN withdrawal
706            // carries its routes in `evpn_nlris`, not in `prefixes`.
707            if nlri.is_empty() {
708                // the only attribute is MP_UNREACH_NLRI with no prefixes:
709                // case 2 end-of-rib
710                return true;
711            }
712        }
713
714        // all other cases: not end-of-rib
715        false
716    }
717}
718
719impl BgpMessage {
720    /// BGP marker value: 16 bytes of 0xFF (RFC 4271)
721    const MARKER: [u8; 16] = [0xFF; 16];
722
723    pub fn encode(&self, asn_len: AsnLength) -> Result<Bytes, EncodingError> {
724        let mut bytes = BytesMut::new();
725        // RFC 4271: Marker is 16 bytes of 0xFF
726        bytes.put_slice(&Self::MARKER);
727
728        let (msg_type, msg_bytes) = match self {
729            BgpMessage::Open(msg) => (BgpMessageType::OPEN, msg.encode()?),
730            BgpMessage::Update(msg) => (BgpMessageType::UPDATE, msg.encode(asn_len)?),
731            BgpMessage::Notification(msg) => (BgpMessageType::NOTIFICATION, msg.encode()),
732            BgpMessage::KeepAlive => (BgpMessageType::KEEPALIVE, Bytes::new()),
733            BgpMessage::RouteRefresh(msg) => (BgpMessageType::ROUTE_REFRESH, msg.encode()),
734        };
735
736        // msg total bytes length = msg bytes + 16 bytes marker + 2 bytes length + 1 byte type
737        let total_len = msg_bytes.len() + 16 + 2 + 1;
738        check_max("BGP message total length", total_len, u16::MAX as usize)?;
739        bytes.put_u16(total_len as u16);
740        bytes.put_u8(msg_type as u8);
741        bytes.put_slice(&msg_bytes);
742        Ok(bytes.freeze())
743    }
744}
745
746impl From<&BgpElem> for BgpUpdateMessage {
747    fn from(elem: &BgpElem) -> Self {
748        BgpUpdateMessage {
749            withdrawn_prefixes: vec![],
750            attributes: Attributes::from(elem),
751            announced_prefixes: vec![],
752        }
753    }
754}
755
756impl From<BgpUpdateMessage> for BgpMessage {
757    fn from(value: BgpUpdateMessage) -> Self {
758        BgpMessage::Update(value)
759    }
760}
761
762#[cfg(test)]
763mod tests {
764    use super::*;
765    use std::net::Ipv4Addr;
766    use std::str::FromStr;
767
768    #[test]
769    fn test_end_of_rib() {
770        // No prefixes and empty attributes: end-of-rib
771        let attrs = Attributes::default();
772        let msg = BgpUpdateMessage {
773            withdrawn_prefixes: vec![],
774            attributes: attrs,
775            announced_prefixes: vec![],
776        };
777        assert!(msg.is_end_of_rib());
778
779        // single MP_UNREACH_NLRI attribute with no prefixes: end-of-rib
780        let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri(Nlri {
781            afi: Afi::Ipv4,
782            safi: Safi::Unicast,
783            next_hop: None,
784            prefixes: vec![],
785            labeled_prefixes: None,
786            link_state_nlris: None,
787            flowspec_nlris: None,
788            evpn_nlris: None,
789        })]);
790        let msg = BgpUpdateMessage {
791            withdrawn_prefixes: vec![],
792            attributes: attrs,
793            announced_prefixes: vec![],
794        };
795        assert!(msg.is_end_of_rib());
796
797        // EVPN withdrawal: the routes live in `evpn_nlris`, so an empty
798        // `prefixes` alone must not read as an end-of-rib marker.
799        let withdrawn = EvpnNlri {
800            path_id: None,
801            route_type: EvpnRouteType::MacIpAdvertisement,
802            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]),
803            payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement {
804                esi: [0; 10],
805                ethernet_tag_id: 0,
806                mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d],
807                ip: None,
808                raw_label: 100,
809                raw_label2: None,
810            }),
811        };
812        let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri(
813            Nlri::new_evpn_unreachable(vec![withdrawn.clone()]),
814        )]);
815        let msg = BgpUpdateMessage {
816            withdrawn_prefixes: vec![],
817            attributes: attrs,
818            announced_prefixes: vec![],
819        };
820        assert!(!msg.is_end_of_rib(), "an EVPN withdrawal is not an EOR");
821
822        // The same family with no routes is the actual EVPN end-of-rib marker.
823        let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri(
824            Nlri::new_evpn_unreachable(vec![]),
825        )]);
826        let msg = BgpUpdateMessage {
827            withdrawn_prefixes: vec![],
828            attributes: attrs,
829            announced_prefixes: vec![],
830        };
831        assert!(msg.is_end_of_rib());
832
833        // message with announced prefixes
834        let prefix = NetworkPrefix::from_str("192.168.1.0/24").unwrap();
835        let attrs = Attributes::default();
836        let msg = BgpUpdateMessage {
837            withdrawn_prefixes: vec![],
838            attributes: attrs,
839            announced_prefixes: vec![prefix],
840        };
841        assert!(!msg.is_end_of_rib());
842
843        // message with withdrawn prefixes
844        let prefix = NetworkPrefix::from_str("192.168.1.0/24").unwrap();
845        let attrs = Attributes::default();
846        let msg = BgpUpdateMessage {
847            withdrawn_prefixes: vec![prefix],
848            attributes: attrs,
849            announced_prefixes: vec![],
850        };
851        assert!(!msg.is_end_of_rib());
852
853        // NLRI attribute with empty prefixes: NOT end-of-rib
854        let attrs = Attributes::from_iter(vec![AttributeValue::MpReachNlri(Nlri {
855            afi: Afi::Ipv4,
856            safi: Safi::Unicast,
857            next_hop: None,
858            prefixes: vec![],
859            labeled_prefixes: None,
860            link_state_nlris: None,
861            flowspec_nlris: None,
862            evpn_nlris: None,
863        })]);
864        let msg = BgpUpdateMessage {
865            withdrawn_prefixes: vec![],
866            attributes: attrs,
867            announced_prefixes: vec![],
868        };
869        assert!(!msg.is_end_of_rib());
870
871        // NLRI attribute with non-empty prefixes
872        let attrs = Attributes::from_iter(vec![AttributeValue::MpReachNlri(Nlri {
873            afi: Afi::Ipv4,
874            safi: Safi::Unicast,
875            next_hop: None,
876            prefixes: vec![prefix],
877            labeled_prefixes: None,
878            link_state_nlris: None,
879            flowspec_nlris: None,
880            evpn_nlris: None,
881        })]);
882        let msg = BgpUpdateMessage {
883            withdrawn_prefixes: vec![],
884            attributes: attrs,
885            announced_prefixes: vec![],
886        };
887        assert!(!msg.is_end_of_rib());
888
889        // Unreachable NLRI attribute with non-empty prefixes
890        let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri(Nlri {
891            afi: Afi::Ipv4,
892            safi: Safi::Unicast,
893            next_hop: None,
894            prefixes: vec![prefix],
895            labeled_prefixes: None,
896            link_state_nlris: None,
897            flowspec_nlris: None,
898            evpn_nlris: None,
899        })]);
900        let msg = BgpUpdateMessage {
901            withdrawn_prefixes: vec![],
902            attributes: attrs,
903            announced_prefixes: vec![],
904        };
905        assert!(!msg.is_end_of_rib());
906
907        // message with more than one attributes
908        let attrs = Attributes::from_iter(vec![
909            AttributeValue::MpUnreachNlri(Nlri {
910                afi: Afi::Ipv4,
911                safi: Safi::Unicast,
912                next_hop: None,
913                prefixes: vec![],
914                labeled_prefixes: None,
915                link_state_nlris: None,
916                flowspec_nlris: None,
917                evpn_nlris: None,
918            }),
919            AttributeValue::AtomicAggregate,
920        ]);
921        let msg = BgpUpdateMessage {
922            withdrawn_prefixes: vec![],
923            attributes: attrs,
924            announced_prefixes: vec![],
925        };
926        assert!(!msg.is_end_of_rib());
927    }
928
929    #[test]
930    fn test_invalid_length() {
931        let bytes = Bytes::from_static(&[
932            0x00, 0x00, 0x00, 0x00, // marker
933            0x00, 0x00, 0x00, 0x00, // marker
934            0x00, 0x00, 0x00, 0x00, // marker
935            0x00, 0x00, 0x00, 0x00, // marker
936            0x00, 0x00, // length
937            0x05, // type
938        ]);
939        let mut data = bytes.clone();
940        assert!(parse_bgp_message(&mut data, false, &AsnLength::Bits16).is_err());
941
942        let bytes = Bytes::from_static(&[
943            0x00, 0x00, 0x00, 0x00, // marker
944            0x00, 0x00, 0x00, 0x00, // marker
945            0x00, 0x00, 0x00, 0x00, // marker
946            0x00, 0x00, 0x00, 0x00, // marker
947            0x00, 0x28, // length
948            0x05, // type
949        ]);
950        let mut data = bytes.clone();
951        assert!(parse_bgp_message(&mut data, false, &AsnLength::Bits16).is_err());
952    }
953
954    #[test]
955    fn test_invalid_type() {
956        let bytes = Bytes::from_static(&[
957            0xFF, 0xFF, 0xFF, 0xFF, // marker (valid RFC 4271)
958            0xFF, 0xFF, 0xFF, 0xFF, // marker
959            0xFF, 0xFF, 0xFF, 0xFF, // marker
960            0xFF, 0xFF, 0xFF, 0xFF, // marker
961            0x00, 0x28, // length
962            0x06, // type (unassigned)
963        ]);
964        let mut data = bytes.clone();
965        assert!(parse_bgp_message(&mut data, false, &AsnLength::Bits16).is_err());
966    }
967
968    #[test]
969    fn test_parse_bgp_route_refresh_message() {
970        // BGP portion of MRT record 4978 in
971        // https://data.ris.ripe.net/rrc00/2012.07/updates.20120718.2020.gz
972        let bytes = Bytes::from_static(&[
973            0xFF, 0xFF, 0xFF, 0xFF, // marker
974            0xFF, 0xFF, 0xFF, 0xFF, // marker
975            0xFF, 0xFF, 0xFF, 0xFF, // marker
976            0xFF, 0xFF, 0xFF, 0xFF, // marker
977            0x00, 0x17, // length = 23
978            0x05, // type = ROUTE-REFRESH
979            0x00, 0x01, // AFI = 1 (IPv4)
980            0x00, // reserved / subtype
981            0x01, // SAFI = 1 (unicast)
982        ]);
983        let mut data = bytes.clone();
984        let msg = parse_bgp_message(&mut data, false, &AsnLength::Bits32).unwrap();
985        let refresh = match &msg {
986            BgpMessage::RouteRefresh(refresh) => refresh,
987            _ => panic!("expected RouteRefresh, got {msg:?}"),
988        };
989        assert_eq!(msg.msg_type(), BgpMessageType::ROUTE_REFRESH);
990        assert_eq!(refresh.afi, 1);
991        assert_eq!(refresh.subtype, 0);
992        assert_eq!(refresh.safi, 1);
993        assert!(refresh.data.is_empty());
994        assert_eq!(refresh.afi(), Some(Afi::Ipv4));
995        assert_eq!(refresh.safi(), Some(Safi::Unicast));
996
997        // encoding must roundtrip byte-identically
998        let encoded = msg.encode(AsnLength::Bits32).unwrap();
999        assert_eq!(encoded, bytes);
1000    }
1001
1002    #[test]
1003    fn test_parse_bgp_route_refresh_message_with_orf_data() {
1004        // RFC 7313 BoRR subtype with trailing ORF bytes; unknown AFI/SAFI values
1005        // must be preserved rather than rejected.
1006        let bytes = Bytes::from_static(&[
1007            0xFF, 0xFF, 0xFF, 0xFF, // marker
1008            0xFF, 0xFF, 0xFF, 0xFF, // marker
1009            0xFF, 0xFF, 0xFF, 0xFF, // marker
1010            0xFF, 0xFF, 0xFF, 0xFF, // marker
1011            0x00, 0x1A, // length = 26
1012            0x05, // type = ROUTE-REFRESH
1013            0x00, 0x63, // AFI = 99, not in the Afi enum
1014            0x01, // subtype = BoRR
1015            0x41, // SAFI = 65 (VPLS, not in the Safi enum)
1016            0xDE, 0xAD, 0xBE, // trailing ORF bytes, kept raw
1017        ]);
1018        let mut data = bytes.clone();
1019        let msg = parse_bgp_message(&mut data, false, &AsnLength::Bits32).unwrap();
1020        let refresh = match &msg {
1021            BgpMessage::RouteRefresh(refresh) => refresh,
1022            _ => panic!("expected RouteRefresh, got {msg:?}"),
1023        };
1024        assert_eq!(refresh.afi, 99);
1025        assert_eq!(refresh.subtype, 1);
1026        assert_eq!(refresh.safi, 65);
1027        assert_eq!(refresh.data, vec![0xDE, 0xAD, 0xBE]);
1028        assert_eq!(refresh.afi(), None);
1029        assert_eq!(refresh.safi(), None);
1030
1031        let encoded = msg.encode(AsnLength::Bits32).unwrap();
1032        assert_eq!(encoded, bytes);
1033    }
1034
1035    #[test]
1036    fn test_parse_bgp_route_refresh_message_unknown_subtype() {
1037        // RFC 7313 defines subtypes 0 (normal), 1 (BoRR), and 2 (EoRR); other
1038        // values are unassigned. The parser retains an unknown subtype raw
1039        // instead of rejecting the message, so the record round-trips.
1040        let bytes = Bytes::from_static(&[
1041            0xFF, 0xFF, 0xFF, 0xFF, // marker
1042            0xFF, 0xFF, 0xFF, 0xFF, // marker
1043            0xFF, 0xFF, 0xFF, 0xFF, // marker
1044            0xFF, 0xFF, 0xFF, 0xFF, // marker
1045            0x00, 0x17, // length = 23
1046            0x05, // type = ROUTE-REFRESH
1047            0x00, 0x01, // AFI = 1 (IPv4)
1048            0x03, // subtype = 3 (unassigned)
1049            0x01, // SAFI = 1 (unicast)
1050        ]);
1051        let mut data = bytes.clone();
1052        let msg = parse_bgp_message(&mut data, false, &AsnLength::Bits32).unwrap();
1053        let refresh = match &msg {
1054            BgpMessage::RouteRefresh(refresh) => refresh,
1055            _ => panic!("expected RouteRefresh, got {msg:?}"),
1056        };
1057        assert_eq!(refresh.afi, 1);
1058        assert_eq!(refresh.subtype, 3);
1059        assert_eq!(refresh.safi, 1);
1060        assert!(refresh.data.is_empty());
1061
1062        let encoded = msg.encode(AsnLength::Bits32).unwrap();
1063        assert_eq!(encoded, bytes);
1064    }
1065
1066    #[test]
1067    fn test_parse_bgp_route_refresh_message_truncated() {
1068        // body shorter than the 4-byte fixed part must error, not panic
1069        let bytes = Bytes::from_static(&[
1070            0xFF, 0xFF, 0xFF, 0xFF, // marker
1071            0xFF, 0xFF, 0xFF, 0xFF, // marker
1072            0xFF, 0xFF, 0xFF, 0xFF, // marker
1073            0xFF, 0xFF, 0xFF, 0xFF, // marker
1074            0x00, 0x15, // length = 21 (only 2 body bytes)
1075            0x05, // type = ROUTE-REFRESH
1076            0x00, 0x01, // truncated body
1077        ]);
1078        let mut data = bytes.clone();
1079        assert!(parse_bgp_message(&mut data, false, &AsnLength::Bits32).is_err());
1080    }
1081
1082    #[test]
1083    fn test_bgp_message_length_underflow_protection() {
1084        // Test that length values less than 19 are properly rejected
1085        // without causing arithmetic underflow
1086        for len in [0u16, 1, 18] {
1087            let bytes = Bytes::from(vec![
1088                0xFF,
1089                0xFF,
1090                0xFF,
1091                0xFF, // marker
1092                0xFF,
1093                0xFF,
1094                0xFF,
1095                0xFF, // marker
1096                0xFF,
1097                0xFF,
1098                0xFF,
1099                0xFF, // marker
1100                0xFF,
1101                0xFF,
1102                0xFF,
1103                0xFF, // marker
1104                (len >> 8) as u8,
1105                (len & 0xFF) as u8, // length field
1106                0x01,               // type = OPEN
1107            ]);
1108            let mut data = bytes.clone();
1109            let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1110            assert!(
1111                result.is_err(),
1112                "Length {} should be rejected as invalid",
1113                len
1114            );
1115        }
1116    }
1117
1118    #[test]
1119    fn test_bgp_marker_encoding_rfc4271() {
1120        // Test that BgpMessage::encode produces correct RFC 4271 marker (all 0xFF)
1121        let msg = BgpMessage::KeepAlive;
1122        let encoded = msg.encode(AsnLength::Bits16).unwrap();
1123
1124        // First 16 bytes should be all 0xFF
1125        assert_eq!(
1126            &encoded[..16],
1127            &[0xFF; 16],
1128            "BGP marker should be all 0xFF bytes"
1129        );
1130    }
1131
1132    #[test]
1133    fn test_bgp_marker_validation() {
1134        // Test that message with valid marker (all 0xFF) parses correctly
1135        let valid_bytes = Bytes::from(vec![
1136            0xFF, 0xFF, 0xFF, 0xFF, // marker
1137            0xFF, 0xFF, 0xFF, 0xFF, // marker
1138            0xFF, 0xFF, 0xFF, 0xFF, // marker
1139            0xFF, 0xFF, 0xFF, 0xFF, // marker
1140            0x00, 0x13, // length = 19 (minimum)
1141            0x04, // type = KEEPALIVE
1142        ]);
1143        let mut data = valid_bytes.clone();
1144        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1145        assert!(result.is_ok(), "Valid marker should parse successfully");
1146
1147        // Test that message with invalid marker (all zeros) is handled
1148        // Parser should warn but still process (for MRT compatibility)
1149        let invalid_bytes = Bytes::from(vec![
1150            0x00, 0x00, 0x00, 0x00, // marker (invalid - should be 0xFF)
1151            0x00, 0x00, 0x00, 0x00, // marker
1152            0x00, 0x00, 0x00, 0x00, // marker
1153            0x00, 0x00, 0x00, 0x00, // marker
1154            0x00, 0x13, // length = 19
1155            0x04, // type = KEEPALIVE
1156        ]);
1157        let mut data = invalid_bytes.clone();
1158        // Should still parse (with warning) for compatibility
1159        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1160        assert!(
1161            result.is_ok(),
1162            "Invalid marker should still parse (with warning)"
1163        );
1164    }
1165
1166    #[test]
1167    fn test_attribute_length_overflow_protection() {
1168        // Test that large attribute length values are handled correctly
1169        // without causing overflow issues
1170
1171        // Create a BGP UPDATE message with attribute_length that exceeds available data
1172        let update_bytes = Bytes::from(vec![
1173            0x00, 0x00, // withdrawn length = 0
1174            0xFF,
1175            0xFF, // attribute length = 65535 (largest u16, but not enough data)
1176                  // No actual attribute data follows
1177        ]);
1178
1179        let result = parse_bgp_update_message(update_bytes, false, &AsnLength::Bits16);
1180        assert!(
1181            result.is_err(),
1182            "Should fail when attribute_length exceeds available data"
1183        );
1184        assert!(
1185            matches!(result, Err(ParserError::TruncatedMsg(_))),
1186            "Should fail with TruncatedMsg error"
1187        );
1188
1189        // Test valid attribute length parsing
1190        let valid_update = Bytes::from(vec![
1191            0x00, 0x00, // withdrawn length = 0
1192            0x00,
1193            0x00, // attribute length = 0
1194                  // No attributes, valid empty UPDATE
1195        ]);
1196        let result = parse_bgp_update_message(valid_update, false, &AsnLength::Bits16);
1197        assert!(result.is_ok(), "Should parse valid empty UPDATE");
1198    }
1199
1200    #[test]
1201    fn test_parse_bgp_notification_message() {
1202        let bytes = Bytes::from_static(&[
1203            0x01, // error code
1204            0x02, // error subcode
1205            0x00, 0x00, // data
1206        ]);
1207        let msg = parse_bgp_notification_message(bytes).unwrap();
1208        matches!(
1209            msg.error,
1210            BgpError::MessageHeaderError(MessageHeaderError::BAD_MESSAGE_LENGTH)
1211        );
1212        assert_eq!(msg.data, Bytes::from_static(&[0x00, 0x00]));
1213    }
1214
1215    #[test]
1216    fn test_encode_bgp_notification_messsage() {
1217        let msg = BgpNotificationMessage {
1218            error: BgpError::MessageHeaderError(MessageHeaderError::BAD_MESSAGE_LENGTH),
1219            data: vec![0x00, 0x00],
1220        };
1221        let bytes = msg.encode();
1222        assert_eq!(bytes, Bytes::from_static(&[0x01, 0x02, 0x00, 0x00]));
1223    }
1224
1225    #[test]
1226    fn test_parse_bgp_open_message() {
1227        let bytes = Bytes::from_static(&[
1228            0x04, // version
1229            0x00, 0x01, // asn
1230            0x00, 0xb4, // hold time
1231            0xc0, 0x00, 0x02, 0x01, // sender ip
1232            0x00, // opt params length
1233        ]);
1234        let msg = parse_bgp_open_message(&mut bytes.clone()).unwrap();
1235        assert_eq!(msg.version, 4);
1236        assert_eq!(msg.asn, Asn::new_16bit(1));
1237        assert_eq!(msg.hold_time, 180);
1238        assert_eq!(msg.bgp_identifier, Ipv4Addr::new(192, 0, 2, 1));
1239        assert!(!msg.extended_length);
1240        assert_eq!(msg.opt_params.len(), 0);
1241    }
1242
1243    #[test]
1244    fn test_encode_bgp_open_message() {
1245        let msg = BgpOpenMessage {
1246            version: 4,
1247            asn: Asn::new_16bit(1),
1248            hold_time: 180,
1249            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1250            extended_length: false,
1251            opt_params: vec![],
1252        };
1253        let bytes = msg.encode().unwrap();
1254        assert_eq!(
1255            bytes,
1256            Bytes::from_static(&[
1257                0x04, // version
1258                0x00, 0x01, // asn
1259                0x00, 0xb4, // hold time
1260                0xc0, 0x00, 0x02, 0x01, // sender ip
1261                0x00, // opt params length
1262            ])
1263        );
1264    }
1265
1266    #[test]
1267    fn test_bgp_open_wire_fixtures_round_trip_byte_identically() {
1268        // test vectors from sessions with RIS RRC00
1269        let fixtures = [
1270            (
1271                "no optional parameters",
1272                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF001D01",
1273                "048826005A02380BFE00",
1274                0x00,
1275            ),
1276            (
1277                "two capability parameters",
1278                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF002501",
1279                "045BA0005A66433801080202800002020200",
1280                0x08,
1281            ),
1282            (
1283                "five capability parameters",
1284                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF003901",
1285                "04947100B4CBD0B16E1C02060104000200010202800002020200020246000206410400009471",
1286                0x1C,
1287            ),
1288            (
1289                "one 22-byte capability parameter",
1290                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF003501",
1291                "045BA000F05D9FBB0118021601040001000102004002007841040003215C46004700",
1292                0x18,
1293            ),
1294            (
1295                "one 26-byte capability parameter",
1296                "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF003901",
1297                "045BA0012CB901A6321C021A0104000100010200400600780001010041040003167D46004700",
1298                0x1C,
1299            ),
1300        ];
1301
1302        for (name, header, body, expected_opt_params_len) in fixtures {
1303            let wire = Bytes::from(hex::decode(format!("{header}{body}")).unwrap());
1304            assert_eq!(wire[28], expected_opt_params_len, "{name}");
1305
1306            let mut input = wire.clone();
1307            let parsed =
1308                parse_bgp_message(&mut input, false, &AsnLength::Bits16).unwrap_or_else(|error| {
1309                    panic!("failed to parse {name}: {error}");
1310                });
1311            let encoded = parsed.encode(AsnLength::Bits16).unwrap();
1312
1313            assert_eq!(encoded, wire, "{name}");
1314        }
1315    }
1316
1317    #[test]
1318    fn test_bgp_open_encoding_recomputes_parameter_lengths() {
1319        let msg = BgpOpenMessage {
1320            version: 4,
1321            asn: Asn::new_16bit(64512),
1322            hold_time: 90,
1323            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1324            extended_length: false,
1325            opt_params: vec![OptParam {
1326                param_type: 254,
1327                param_value: ParamValue::Raw(vec![0xAA, 0xBB, 0xCC]),
1328            }],
1329        };
1330
1331        let encoded = msg.encode().unwrap();
1332
1333        assert_eq!(encoded[9], 5);
1334        assert_eq!(&encoded[10..], &[254, 3, 0xAA, 0xBB, 0xCC]);
1335        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1336        assert_eq!(parsed.encode().unwrap(), encoded);
1337    }
1338
1339    #[test]
1340    fn test_bgp_open_encoding_rejects_oversized_add_path_capability() {
1341        use crate::models::capabilities::{AddPathAddressFamily, AddPathSendReceive};
1342
1343        let address_family = AddPathAddressFamily {
1344            afi: Afi::Ipv4,
1345            safi: Safi::Unicast,
1346            send_receive: AddPathSendReceive::SendReceive,
1347        };
1348        let msg = BgpOpenMessage {
1349            version: 4,
1350            asn: Asn::new_16bit(64512),
1351            hold_time: 90,
1352            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1353            extended_length: false,
1354            opt_params: vec![OptParam {
1355                param_type: 2,
1356                param_value: ParamValue::Capacities(vec![Capability {
1357                    ty: BgpCapabilityType::ADD_PATH_CAPABILITY,
1358                    value: CapabilityValue::AddPath(AddPathCapability::new(vec![
1359                        address_family;
1360                        64
1361                    ])),
1362                }]),
1363            }],
1364        };
1365
1366        let err = msg.encode().unwrap_err();
1367        assert_eq!(
1368            err,
1369            EncodingError::ValueTooLarge {
1370                field: "BGP capability value length",
1371                actual: 256,
1372                max: 255
1373            }
1374        );
1375    }
1376
1377    #[test]
1378    fn test_bgp_open_forced_extended_parameter_encoding() {
1379        let msg = BgpOpenMessage {
1380            version: 4,
1381            asn: Asn::new_16bit(64512),
1382            hold_time: 90,
1383            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1384            extended_length: true,
1385            opt_params: vec![OptParam {
1386                param_type: 254,
1387                param_value: ParamValue::Raw(vec![0xAA, 0xBB]),
1388            }],
1389        };
1390
1391        let encoded = msg.encode().unwrap();
1392
1393        assert_eq!(
1394            &encoded[9..],
1395            &[0xFF, 0xFF, 0x00, 0x05, 254, 0x00, 0x02, 0xAA, 0xBB]
1396        );
1397        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1398        assert!(parsed.extended_length);
1399        assert_eq!(parsed.encode().unwrap(), encoded);
1400    }
1401
1402    #[test]
1403    fn test_bgp_open_automatically_uses_extended_parameter_encoding() {
1404        let msg = BgpOpenMessage {
1405            version: 4,
1406            asn: Asn::new_16bit(64512),
1407            hold_time: 90,
1408            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1409            extended_length: false,
1410            opt_params: vec![OptParam {
1411                param_type: 254,
1412                param_value: ParamValue::Raw(vec![0xAA; 256]),
1413            }],
1414        };
1415
1416        let encoded = msg.encode().unwrap();
1417
1418        assert_eq!(encoded.len(), 272);
1419        assert_eq!(&encoded[9..16], &[0xFF, 0xFF, 0x01, 0x03, 254, 0x01, 0x00]);
1420        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1421        assert!(parsed.extended_length);
1422        assert_eq!(parsed.encode().unwrap(), encoded);
1423    }
1424
1425    #[test]
1426    fn test_encode_bgp_notification_message() {
1427        let bgp_message = BgpMessage::Notification(BgpNotificationMessage {
1428            error: BgpError::MessageHeaderError(MessageHeaderError::BAD_MESSAGE_LENGTH),
1429            data: vec![0x00, 0x00],
1430        });
1431        let bytes = bgp_message.encode(AsnLength::Bits16).unwrap();
1432        // RFC 4271: Marker is 16 bytes of 0xFF
1433        assert_eq!(
1434            bytes,
1435            Bytes::from_static(&[
1436                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // marker (8 bytes)
1437                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // marker (8 bytes)
1438                0x00, 0x17, // length = 23 (16 marker + 2 len + 1 type + 4 msg)
1439                0x03, // type = NOTIFICATION
1440                0x01, 0x02, // error code, subcode
1441                0x00, 0x00 // data
1442            ])
1443        );
1444    }
1445
1446    #[test]
1447    fn test_bgp_message_from_bgp_update_message() {
1448        let msg = BgpMessage::from(BgpUpdateMessage::default());
1449        assert!(matches!(msg, BgpMessage::Update(_)));
1450    }
1451
1452    #[test]
1453    fn test_parse_bgp_open_message_with_extended_next_hop_capability() {
1454        use crate::models::{Afi, Safi};
1455
1456        // BGP OPEN message with Extended Next Hop capability - RFC 8950, Section 3
1457        // Version=4, ASN=65001, HoldTime=180, BGP-ID=192.0.2.1
1458        // One capability: Extended Next Hop (type=5) with two entries:
1459        // 1) IPv4 Unicast (AFI=1, SAFI=1) can use IPv6 NextHop (AFI=2)
1460        // 2) IPv4 MPLS VPN (AFI=1, SAFI=128) can use IPv6 NextHop (AFI=2)
1461        let bytes = Bytes::from(vec![
1462            0x04, // version
1463            0xfd, 0xe9, // asn = 65001
1464            0x00, 0xb4, // hold time = 180
1465            0xc0, 0x00, 0x02, 0x01, // sender ip = 192.0.2.1
1466            0x10, // opt params length = 16
1467            0x02, // param type = 2 (capability)
1468            0x0e, // param length = 14
1469            0x05, // capability type = 5 (Extended Next Hop)
1470            0x0c, // capability length = 12 (2 entries * 6 bytes each)
1471            0x00, 0x01, // NLRI AFI = 1 (IPv4)
1472            0x00, 0x01, // NLRI SAFI = 1 (Unicast)
1473            0x00, 0x02, // NextHop AFI = 2 (IPv6)
1474            0x00, 0x01, // NLRI AFI = 1 (IPv4) - second entry
1475            0x00, 0x80, // NLRI SAFI = 128 (MPLS VPN)
1476            0x00, 0x02, // NextHop AFI = 2 (IPv6)
1477        ]);
1478
1479        let msg = parse_bgp_open_message(&mut bytes.clone()).unwrap();
1480        assert_eq!(msg.version, 4);
1481        assert_eq!(msg.asn, Asn::new_16bit(65001));
1482        assert_eq!(msg.hold_time, 180);
1483        assert_eq!(msg.bgp_identifier, Ipv4Addr::new(192, 0, 2, 1));
1484        assert!(!msg.extended_length);
1485        assert_eq!(msg.opt_params.len(), 1);
1486
1487        // Check the capability
1488        if let ParamValue::Capacities(cap) = &msg.opt_params[0].param_value {
1489            assert_eq!(cap[0].ty, BgpCapabilityType::EXTENDED_NEXT_HOP_ENCODING);
1490
1491            if let CapabilityValue::ExtendedNextHop(enh_cap) = &cap[0].value {
1492                assert_eq!(enh_cap.entries.len(), 2);
1493
1494                // Check first entry: IPv4 Unicast can use IPv6 NextHop
1495                let entry1 = &enh_cap.entries[0];
1496                assert_eq!(entry1.nlri_afi, Afi::Ipv4);
1497                assert_eq!(entry1.nlri_safi, Safi::Unicast);
1498                assert_eq!(entry1.nexthop_afi, Afi::Ipv6);
1499
1500                // Check second entry: IPv4 MPLS VPN can use IPv6 NextHop
1501                let entry2 = &enh_cap.entries[1];
1502                assert_eq!(entry2.nlri_afi, Afi::Ipv4);
1503                assert_eq!(entry2.nlri_safi, Safi::MplsVpn);
1504                assert_eq!(entry2.nexthop_afi, Afi::Ipv6);
1505
1506                // Test functionality
1507                assert!(enh_cap.supports(Afi::Ipv4, Safi::Unicast, Afi::Ipv6));
1508                assert!(enh_cap.supports(Afi::Ipv4, Safi::MplsVpn, Afi::Ipv6));
1509                assert!(!enh_cap.supports(Afi::Ipv4, Safi::Multicast, Afi::Ipv6));
1510            } else {
1511                panic!("Expected ExtendedNextHop capability value");
1512            }
1513        } else {
1514            panic!("Expected capability parameter");
1515        }
1516    }
1517
1518    #[test]
1519    fn test_rfc8654_extended_message_length_validation() {
1520        // Test valid extended UPDATE message (within 65535 limit)
1521        let bytes = Bytes::from_static(&[
1522            0x00, 0x00, 0x00, 0x00, // marker
1523            0x00, 0x00, 0x00, 0x00, // marker
1524            0x00, 0x00, 0x00, 0x00, // marker
1525            0x00, 0x00, 0x00, 0x00, // marker
1526            0x13, 0x00, // length = 4864 (0x1300) (extended message)
1527            0x02, // type = UPDATE
1528            0x00, 0x00, // withdrawn length = 0
1529            0x00,
1530            0x00, // path attribute length = 0
1531                  // No NLRI data needed for this test
1532        ]);
1533        let mut data = bytes.clone();
1534        // This should succeed because UPDATE messages can be extended
1535        assert!(parse_bgp_message(&mut data, false, &AsnLength::Bits16).is_ok());
1536
1537        // Test OPEN message exceeding 4096 bytes (should fail)
1538        let bytes = Bytes::from_static(&[
1539            0x00, 0x00, 0x00, 0x00, // marker
1540            0x00, 0x00, 0x00, 0x00, // marker
1541            0x00, 0x00, 0x00, 0x00, // marker
1542            0x00, 0x00, 0x00, 0x00, // marker
1543            0x13, 0x00, // length = 4864 (0x1300) (exceeds 4096 for OPEN)
1544            0x01, // type = OPEN
1545        ]);
1546        let mut data = bytes.clone();
1547        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1548        assert!(result.is_err());
1549        if let Err(ParserError::ParseError(msg)) = result {
1550            assert!(msg.contains("BGP OPEN message length"));
1551            assert!(msg.contains("4096 bytes"));
1552        }
1553
1554        // Test KEEPALIVE message exceeding 4096 bytes (should fail)
1555        let bytes = Bytes::from_static(&[
1556            0x00, 0x00, 0x00, 0x00, // marker
1557            0x00, 0x00, 0x00, 0x00, // marker
1558            0x00, 0x00, 0x00, 0x00, // marker
1559            0x00, 0x00, 0x00, 0x00, // marker
1560            0x13, 0x00, // length = 4864 (0x1300) (exceeds 4096 for KEEPALIVE)
1561            0x04, // type = KEEPALIVE
1562        ]);
1563        let mut data = bytes.clone();
1564        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1565        assert!(result.is_err());
1566        if let Err(ParserError::ParseError(msg)) = result {
1567            assert!(msg.contains("BGP KEEPALIVE message length"));
1568            assert!(msg.contains("4096 bytes"));
1569        }
1570
1571        // Test message exceeding 65535 bytes (maximum allowed)
1572        let bytes = Bytes::from_static(&[
1573            0x00, 0x00, 0x00, 0x00, // marker
1574            0x00, 0x00, 0x00, 0x00, // marker
1575            0x00, 0x00, 0x00, 0x00, // marker
1576            0x00, 0x00, 0x00, 0x00, // marker
1577            0xFF, 0xFF, // length = 65535 (0xFFFF) (maximum allowed)
1578            0x02, // type = UPDATE
1579        ]);
1580        let mut data = bytes.clone();
1581        // This might fail due to insufficient data, but should not fail on length validation
1582        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1583        if let Err(ParserError::ParseError(msg)) = result {
1584            // Should not be a length validation error
1585            assert!(!msg.contains("invalid BGP message length"));
1586        }
1587    }
1588
1589    #[test]
1590    fn test_bgp_extended_message_capability_parsing() {
1591        use crate::models::CapabilityValue;
1592
1593        // Test BGP OPEN message with Extended Message capability (capability code 6)
1594        let bytes = Bytes::from(vec![
1595            0x04, // version
1596            0x00, 0x01, // asn
1597            0x00, 0xb4, // hold time
1598            0xc0, 0x00, 0x02, 0x01, // sender ip
1599            0x04, // opt params length = 4
1600            0x02, // param type = 2 (capability)
1601            0x02, // param length = 2
1602            0x06, // capability type = 6 (Extended Message)
1603            0x00, // capability length = 0 (no parameters)
1604        ]);
1605
1606        let msg = parse_bgp_open_message(&mut bytes.clone()).unwrap();
1607        assert_eq!(msg.version, 4);
1608        assert_eq!(msg.asn, Asn::new_16bit(1));
1609        assert_eq!(msg.opt_params.len(), 1);
1610
1611        // Check that we have the extended message capability
1612        if let ParamValue::Capacities(cap) = &msg.opt_params[0].param_value {
1613            assert_eq!(cap[0].ty, BgpCapabilityType::BGP_EXTENDED_MESSAGE);
1614            if let CapabilityValue::BgpExtendedMessage(_) = &cap[0].value {
1615                // Extended Message capability should have no parameters
1616            } else {
1617                panic!("Expected BgpExtendedMessage capability value");
1618            }
1619        } else {
1620            panic!("Expected capability parameter");
1621        }
1622    }
1623
1624    #[test]
1625    fn test_rfc8654_edge_cases() {
1626        // Test NOTIFICATION message with extended length (should be allowed)
1627        let bytes = Bytes::from_static(&[
1628            0x00, 0x00, 0x00, 0x00, // marker
1629            0x00, 0x00, 0x00, 0x00, // marker
1630            0x00, 0x00, 0x00, 0x00, // marker
1631            0x00, 0x00, 0x00, 0x00, // marker
1632            0x20, 0x00, // length = 8192 (extended NOTIFICATION message)
1633            0x03, // type = NOTIFICATION
1634            0x06, // error code (Cease)
1635            0x00, // error subcode
1636                  // Additional data would go here
1637        ]);
1638        let mut data = bytes.clone();
1639        // This should succeed because NOTIFICATION messages can be extended
1640        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1641        // May fail due to insufficient data, but not due to length validation
1642        if let Err(ParserError::ParseError(msg)) = result {
1643            assert!(!msg.contains("invalid BGP message length"));
1644            assert!(!msg.contains("exceeds maximum allowed 4096 bytes"));
1645        }
1646
1647        // Test message exactly at 4096 bytes for OPEN (should be allowed)
1648        let open_data = vec![
1649            0x00, 0x00, 0x00, 0x00, // marker
1650            0x00, 0x00, 0x00, 0x00, // marker
1651            0x00, 0x00, 0x00, 0x00, // marker
1652            0x00, 0x00, 0x00, 0x00, // marker
1653            0x10, 0x00, // length = 4096 (exactly at limit for OPEN)
1654            0x01, // type = OPEN
1655        ];
1656        let bytes = Bytes::from(open_data);
1657        let mut data = bytes.clone();
1658        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1659        // Should not fail on length validation (may fail on parsing due to insufficient data)
1660        if let Err(ParserError::ParseError(msg)) = result {
1661            assert!(!msg.contains("exceeds maximum allowed 4096 bytes"));
1662        }
1663
1664        // Test message exactly at 65535 bytes for UPDATE (should be allowed)
1665        let bytes = Bytes::from_static(&[
1666            0x00, 0x00, 0x00, 0x00, // marker
1667            0x00, 0x00, 0x00, 0x00, // marker
1668            0x00, 0x00, 0x00, 0x00, // marker
1669            0x00, 0x00, 0x00, 0x00, // marker
1670            0xFF, 0xFF, // length = 65535 (0xFFFF) (maximum allowed)
1671            0x02, // type = UPDATE
1672        ]);
1673        let mut data = bytes.clone();
1674        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1675        // Should not fail on length validation
1676        if let Err(ParserError::ParseError(msg)) = result {
1677            assert!(!msg.contains("invalid BGP message length"));
1678        }
1679    }
1680
1681    #[test]
1682    fn test_rfc8654_capability_encoding_path() {
1683        use crate::models::capabilities::BgpExtendedMessageCapability;
1684
1685        // Test that the encoding path for BgpExtendedMessage capability is covered
1686        // This specifically tests the line: CapabilityValue::BgpExtendedMessage(bem) => bem.encode().unwrap()
1687        let capability_value =
1688            CapabilityValue::BgpExtendedMessage(BgpExtendedMessageCapability::new());
1689        let capability = Capability {
1690            ty: BgpCapabilityType::BGP_EXTENDED_MESSAGE,
1691            value: capability_value,
1692        };
1693
1694        let opt_param = OptParam {
1695            param_type: 2, // capability
1696            param_value: ParamValue::Capacities(vec![capability]),
1697        };
1698
1699        let msg = BgpOpenMessage {
1700            version: 4,
1701            asn: Asn::new_16bit(65001),
1702            hold_time: 180,
1703            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1704            extended_length: false,
1705            opt_params: vec![opt_param],
1706        };
1707
1708        // This will exercise the encoding path we need to test
1709        let encoded = msg.encode().unwrap();
1710        assert!(!encoded.is_empty());
1711
1712        // Verify we can parse it back (exercises the parsing path too)
1713        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1714        assert_eq!(parsed.opt_params.len(), 1);
1715        if let ParamValue::Capacities(cap) = &parsed.opt_params[0].param_value {
1716            assert_eq!(cap[0].ty, BgpCapabilityType::BGP_EXTENDED_MESSAGE);
1717        }
1718    }
1719
1720    #[test]
1721    fn test_rfc8654_error_message_formatting() {
1722        // Test the error message formatting paths that include message type names
1723        // This tests the match arms for OPEN and KEEPALIVE in error messages
1724
1725        // Test OPEN message error path
1726        let bytes = Bytes::from_static(&[
1727            0x00, 0x00, 0x00, 0x00, // marker
1728            0x00, 0x00, 0x00, 0x00, // marker
1729            0x00, 0x00, 0x00, 0x00, // marker
1730            0x00, 0x00, 0x00, 0x00, // marker
1731            0x20, 0x01, // length = 8193 (exceeds 4096 for OPEN)
1732            0x01, // type = OPEN
1733        ]);
1734        let mut data = bytes.clone();
1735        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1736        assert!(result.is_err());
1737        if let Err(ParserError::ParseError(msg)) = result {
1738            assert!(msg.contains("BGP OPEN message length"));
1739            assert!(msg.contains("exceeds maximum allowed 4096 bytes"));
1740        }
1741
1742        // Test KEEPALIVE message error path
1743        let bytes = Bytes::from_static(&[
1744            0x00, 0x00, 0x00, 0x00, // marker
1745            0x00, 0x00, 0x00, 0x00, // marker
1746            0x00, 0x00, 0x00, 0x00, // marker
1747            0x00, 0x00, 0x00, 0x00, // marker
1748            0x20, 0x01, // length = 8193 (exceeds 4096 for KEEPALIVE)
1749            0x04, // type = KEEPALIVE
1750        ]);
1751        let mut data = bytes.clone();
1752        let result = parse_bgp_message(&mut data, false, &AsnLength::Bits16);
1753        assert!(result.is_err());
1754        if let Err(ParserError::ParseError(msg)) = result {
1755            assert!(msg.contains("BGP KEEPALIVE message length"));
1756            assert!(msg.contains("exceeds maximum allowed 4096 bytes"));
1757        }
1758    }
1759
1760    #[test]
1761    fn test_encode_bgp_open_message_with_extended_message_capability() {
1762        use crate::models::capabilities::BgpExtendedMessageCapability;
1763
1764        // Create Extended Message capability
1765        let extended_msg_capability = BgpExtendedMessageCapability::new();
1766
1767        let msg = BgpOpenMessage {
1768            version: 4,
1769            asn: Asn::new_16bit(65001),
1770            hold_time: 180,
1771            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1772            extended_length: false,
1773            opt_params: vec![OptParam {
1774                param_type: 2, // capability
1775                param_value: ParamValue::Capacities(vec![Capability {
1776                    ty: BgpCapabilityType::BGP_EXTENDED_MESSAGE,
1777                    value: CapabilityValue::BgpExtendedMessage(extended_msg_capability),
1778                }]),
1779            }],
1780        };
1781
1782        let encoded = msg.encode().unwrap();
1783
1784        // Parse the encoded message back and verify it matches
1785        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1786        assert_eq!(parsed.version, msg.version);
1787        assert_eq!(parsed.asn, msg.asn);
1788        assert_eq!(parsed.hold_time, msg.hold_time);
1789        assert_eq!(parsed.bgp_identifier, msg.bgp_identifier);
1790        assert_eq!(parsed.opt_params.len(), 1);
1791
1792        // Verify the capability was encoded and parsed correctly
1793        if let ParamValue::Capacities(cap) = &parsed.opt_params[0].param_value {
1794            assert_eq!(cap[0].ty, BgpCapabilityType::BGP_EXTENDED_MESSAGE);
1795            if let CapabilityValue::BgpExtendedMessage(_) = &cap[0].value {
1796                // Extended Message capability should have no parameters
1797            } else {
1798                panic!("Expected BgpExtendedMessage capability value after round trip");
1799            }
1800        } else {
1801            panic!("Expected capability parameter after round trip");
1802        }
1803    }
1804
1805    #[test]
1806    fn test_encode_bgp_open_message_with_extended_next_hop_capability() {
1807        use crate::models::capabilities::{ExtendedNextHopCapability, ExtendedNextHopEntry};
1808        use crate::models::{Afi, Safi};
1809
1810        // Create Extended Next Hop capability
1811        let entries = vec![
1812            ExtendedNextHopEntry {
1813                nlri_afi: Afi::Ipv4,
1814                nlri_safi: Safi::Unicast,
1815                nexthop_afi: Afi::Ipv6,
1816            },
1817            ExtendedNextHopEntry {
1818                nlri_afi: Afi::Ipv4,
1819                nlri_safi: Safi::MplsVpn,
1820                nexthop_afi: Afi::Ipv6,
1821            },
1822        ];
1823        let enh_capability = ExtendedNextHopCapability::new(entries);
1824
1825        let msg = BgpOpenMessage {
1826            version: 4,
1827            asn: Asn::new_16bit(65001),
1828            hold_time: 180,
1829            bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1830            extended_length: false,
1831            opt_params: vec![OptParam {
1832                param_type: 2, // capability
1833                param_value: ParamValue::Capacities(vec![Capability {
1834                    ty: BgpCapabilityType::EXTENDED_NEXT_HOP_ENCODING,
1835                    value: CapabilityValue::ExtendedNextHop(enh_capability),
1836                }]),
1837            }],
1838        };
1839
1840        let encoded = msg.encode().unwrap();
1841
1842        // Parse the encoded message back and verify it matches
1843        let parsed = parse_bgp_open_message(&mut encoded.clone()).unwrap();
1844        assert_eq!(parsed.version, msg.version);
1845        assert_eq!(parsed.asn, msg.asn);
1846        assert_eq!(parsed.hold_time, msg.hold_time);
1847        assert_eq!(parsed.bgp_identifier, msg.bgp_identifier);
1848        assert_eq!(parsed.extended_length, msg.extended_length);
1849        assert_eq!(parsed.opt_params.len(), 1);
1850
1851        // Verify the capability was encoded and parsed correctly
1852        if let ParamValue::Capacities(cap) = &parsed.opt_params[0].param_value {
1853            assert_eq!(cap[0].ty, BgpCapabilityType::EXTENDED_NEXT_HOP_ENCODING);
1854            if let CapabilityValue::ExtendedNextHop(enh_cap) = &cap[0].value {
1855                assert_eq!(enh_cap.entries.len(), 2);
1856                assert!(enh_cap.supports(Afi::Ipv4, Safi::Unicast, Afi::Ipv6));
1857                assert!(enh_cap.supports(Afi::Ipv4, Safi::MplsVpn, Afi::Ipv6));
1858            } else {
1859                panic!("Expected ExtendedNextHop capability value after round trip");
1860            }
1861        } else {
1862            panic!("Expected capability parameter after round trip");
1863        }
1864    }
1865
1866    #[test]
1867    fn test_parse_bgp_open_message_with_multiple_capabilities() {
1868        // Create a BGP OPEN message with multiple capabilities in a single optional parameter
1869        // This tests RFC 5492 support for multiple capabilities per parameter
1870
1871        // Build capabilities: Extended Message, Route Refresh, and 4-octet AS
1872        let extended_msg_cap = Capability {
1873            ty: BgpCapabilityType::BGP_EXTENDED_MESSAGE,
1874            value: CapabilityValue::BgpExtendedMessage(BgpExtendedMessageCapability {}),
1875        };
1876
1877        let route_refresh_cap = Capability {
1878            ty: BgpCapabilityType::ROUTE_REFRESH_CAPABILITY_FOR_BGP_4,
1879            value: CapabilityValue::RouteRefresh(RouteRefreshCapability {}),
1880        };
1881
1882        let four_octet_as_cap = Capability {
1883            ty: BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY,
1884            value: CapabilityValue::FourOctetAs(FourOctetAsCapability { asn: 65536 }),
1885        };
1886
1887        // Create OPEN message with all three capabilities in one parameter
1888        let msg = BgpOpenMessage {
1889            version: 4,
1890            asn: Asn::new_32bit(65000),
1891            hold_time: 180,
1892            bgp_identifier: "10.0.0.1".parse().unwrap(),
1893            extended_length: false,
1894            opt_params: vec![OptParam {
1895                param_type: 2, // capability
1896                param_value: ParamValue::Capacities(vec![
1897                    extended_msg_cap,
1898                    route_refresh_cap,
1899                    four_octet_as_cap,
1900                ]),
1901            }],
1902        };
1903
1904        // Encode the message
1905        let encoded = msg.encode().unwrap();
1906
1907        // Parse it back
1908        let mut encoded_bytes = encoded.clone();
1909        let parsed = parse_bgp_open_message(&mut encoded_bytes).unwrap();
1910
1911        // Verify basic fields
1912        assert_eq!(parsed.version, 4);
1913        assert_eq!(parsed.asn, Asn::new_32bit(65000));
1914        assert_eq!(parsed.hold_time, 180);
1915        assert_eq!(
1916            parsed.bgp_identifier,
1917            "10.0.0.1".parse::<std::net::Ipv4Addr>().unwrap()
1918        );
1919        assert_eq!(parsed.opt_params.len(), 1);
1920
1921        // Verify we have all three capabilities
1922        if let ParamValue::Capacities(caps) = &parsed.opt_params[0].param_value {
1923            assert_eq!(caps.len(), 3, "Should have 3 capabilities");
1924
1925            // Check first capability: Extended Message
1926            assert_eq!(caps[0].ty, BgpCapabilityType::BGP_EXTENDED_MESSAGE);
1927            assert!(matches!(
1928                caps[0].value,
1929                CapabilityValue::BgpExtendedMessage(_)
1930            ));
1931
1932            // Check second capability: Route Refresh
1933            assert_eq!(
1934                caps[1].ty,
1935                BgpCapabilityType::ROUTE_REFRESH_CAPABILITY_FOR_BGP_4
1936            );
1937            assert!(matches!(caps[1].value, CapabilityValue::RouteRefresh(_)));
1938
1939            // Check third capability: 4-octet AS
1940            assert_eq!(
1941                caps[2].ty,
1942                BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY
1943            );
1944            if let CapabilityValue::FourOctetAs(foa) = &caps[2].value {
1945                assert_eq!(foa.asn, 65536);
1946            } else {
1947                panic!("Expected FourOctetAs capability value");
1948            }
1949        } else {
1950            panic!("Expected Capacities parameter");
1951        }
1952    }
1953
1954    #[test]
1955    fn test_parse_bgp_open_message_with_multiple_capability_parameters() {
1956        // Test parsing OPEN message with multiple optional parameters, each containing capabilities
1957        // This is less common but still valid per RFC 5492
1958
1959        let msg = BgpOpenMessage {
1960            version: 4,
1961            asn: Asn::new_32bit(65001),
1962            hold_time: 90,
1963            bgp_identifier: "192.168.1.1".parse().unwrap(),
1964            extended_length: false,
1965            opt_params: vec![
1966                OptParam {
1967                    param_type: 2, // capability
1968                    param_value: ParamValue::Capacities(vec![Capability {
1969                        ty: BgpCapabilityType::BGP_EXTENDED_MESSAGE,
1970                        value: CapabilityValue::BgpExtendedMessage(BgpExtendedMessageCapability {}),
1971                    }]),
1972                },
1973                OptParam {
1974                    param_type: 2, // capability
1975                    param_value: ParamValue::Capacities(vec![Capability {
1976                        ty: BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY,
1977                        value: CapabilityValue::FourOctetAs(FourOctetAsCapability {
1978                            asn: 4200000000,
1979                        }),
1980                    }]),
1981                },
1982            ],
1983        };
1984
1985        // Encode and parse back
1986        let encoded = msg.encode().unwrap();
1987        let mut encoded_bytes = encoded.clone();
1988        let parsed = parse_bgp_open_message(&mut encoded_bytes).unwrap();
1989
1990        // Verify we have 2 optional parameters
1991        assert_eq!(parsed.opt_params.len(), 2);
1992
1993        // Check first parameter
1994        if let ParamValue::Capacities(caps) = &parsed.opt_params[0].param_value {
1995            assert_eq!(caps.len(), 1);
1996            assert_eq!(caps[0].ty, BgpCapabilityType::BGP_EXTENDED_MESSAGE);
1997        } else {
1998            panic!("Expected Capacities in first parameter");
1999        }
2000
2001        // Check second parameter
2002        if let ParamValue::Capacities(caps) = &parsed.opt_params[1].param_value {
2003            assert_eq!(caps.len(), 1);
2004            assert_eq!(
2005                caps[0].ty,
2006                BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY
2007            );
2008            if let CapabilityValue::FourOctetAs(foa) = &caps[0].value {
2009                assert_eq!(foa.asn, 4200000000);
2010            }
2011        } else {
2012            panic!("Expected Capacities in second parameter");
2013        }
2014    }
2015
2016    #[test]
2017    fn test_parse_bgp_update_message_keeps_withdrawals_starting_with_default_route() {
2018        // Withdrawn routes 0.0.0.0/0, 1.0.0.0/24, 1.0.4.0/24, no attributes, no announced NLRI.
2019        // A leading default route must not be read as an ADD-PATH path identifier (#360).
2020        let withdrawn: &[u8] = &[
2021            0x00, // 0.0.0.0/0
2022            0x18, 0x01, 0x00, 0x00, // 1.0.0.0/24
2023            0x18, 0x01, 0x00, 0x04, // 1.0.4.0/24
2024        ];
2025        let mut buf = BytesMut::new();
2026        buf.put_u16(withdrawn.len() as u16);
2027        buf.put_slice(withdrawn);
2028        buf.put_u16(0);
2029
2030        let msg = parse_bgp_update_message(buf.freeze(), false, &AsnLength::Bits32).unwrap();
2031        let got: Vec<String> = msg
2032            .withdrawn_prefixes
2033            .iter()
2034            .map(|p| p.prefix.to_string())
2035            .collect();
2036        assert_eq!(got, vec!["0.0.0.0/0", "1.0.0.0/24", "1.0.4.0/24"]);
2037        assert!(msg.withdrawn_prefixes.iter().all(|p| p.path_id.is_none()));
2038        assert!(msg.attributes.validation_warnings().is_empty());
2039    }
2040}