Skip to main content

bgpkit_parser/
error.rs

1/*!
2error module defines the error types used in bgpkit-parser.
3*/
4use crate::models::{Afi, AttrType, Bgp4MpType, BgpState, EntryType, Safi, TableDumpV2Type};
5use num_enum::TryFromPrimitiveError;
6#[cfg(feature = "oneio")]
7use oneio::OneIoError;
8use std::fmt::{Display, Formatter};
9use std::io::ErrorKind;
10use std::{error::Error, fmt, io};
11
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum ParserError {
15    IoError(io::Error),
16    EofError(io::Error),
17    #[cfg(feature = "oneio")]
18    OneIoError(OneIoError),
19    EofExpected,
20    ParseError(String),
21    TruncatedMsg(String),
22    Unsupported(String),
23    /// An MRT common header declared a body over the 16 MiB limit. The length is
24    /// untrusted, so the reader is left past the header with no record boundary to
25    /// resume from, and the iterators stop instead of reading the body as headers.
26    OversizedRecord {
27        /// The declared body length that exceeded the limit.
28        length: u32,
29    },
30    FilterError(String),
31    /// NLRI length field is inconsistent with content
32    /// (total_bits < minimum required, or underflow in prefix calculation)
33    InvalidLabeledNlriLength,
34    /// Input ended before completing NLRI structure
35    TruncatedLabeledNlri,
36    /// Input ended in the middle of prefix data
37    TruncatedPrefix,
38    /// Exceeded configured max_labels without finding Bottom-of-Stack bit
39    MaxLabelStackDepthExceeded,
40    /// Exceeded peer-advertised max labels (Multiple Labels Capability)
41    /// Per RFC 8277 §2.1, this should be treated as a withdrawal
42    PeerMaxLabelsExceeded,
43    /// Invalid prefix in NLRI
44    InvalidPrefix,
45}
46
47impl Error for ParserError {}
48
49/// Errors that can occur when encoding BGP/MRT messages to wire format.
50///
51/// These arise when in-memory data structures contain values that cannot be
52/// represented in their wire-format fields (e.g. an AS_PATH segment with more
53/// than 255 ASes, or an attribute value exceeding 65535 bytes). All such
54/// conditions were previously handled by silently truncating — see issue #313.
55#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum EncodingError {
58    /// A value exceeded the maximum size that fits in its wire-format field.
59    ///
60    /// `field` names the wire field (e.g. `"AS_PATH segment count"`,
61    /// `"BGP attribute value length"`). `actual` is the byte/element count
62    /// that overflowed; `max` is the field's capacity.
63    ValueTooLarge {
64        field: &'static str,
65        actual: usize,
66        max: usize,
67    },
68    /// The value cannot be represented in wire format at all (e.g. ATTR_SET
69    /// encoding is not implemented, a labeled NLRI has an empty label stack,
70    /// or a BGP OPEN optional parameter uses the reserved type 255).
71    Unencodable { field: &'static str, reason: String },
72}
73
74impl EncodingError {
75    pub(crate) fn too_large(field: &'static str, actual: usize, max: usize) -> Self {
76        EncodingError::ValueTooLarge { field, actual, max }
77    }
78
79    #[cfg(feature = "parser")]
80    pub(crate) fn unencodable(field: &'static str, reason: impl Into<String>) -> Self {
81        EncodingError::Unencodable {
82            field,
83            reason: reason.into(),
84        }
85    }
86}
87
88/// Check that `actual` fits within `max`, returning `actual` unchanged.
89///
90/// This is the single place where wire-format capacity checks happen, so
91/// non-power-of-two bounds (e.g. the 12-bit FlowSpec NLRI length) are an
92/// explicit, greppable decision at the call site.
93pub(crate) fn check_max(
94    field: &'static str,
95    actual: usize,
96    max: usize,
97) -> Result<usize, EncodingError> {
98    if actual > max {
99        return Err(EncodingError::too_large(field, actual, max));
100    }
101    Ok(actual)
102}
103
104impl Display for EncodingError {
105    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
106        match self {
107            EncodingError::ValueTooLarge { field, actual, max } => write!(
108                f,
109                "encoding error: {field} ({actual}) exceeds maximum ({max})"
110            ),
111            EncodingError::Unencodable { field, reason } => {
112                write!(f, "encoding error: {field} cannot be encoded: {reason}")
113            }
114        }
115    }
116}
117
118impl Error for EncodingError {}
119
120#[derive(Debug)]
121pub struct ParserErrorWithBytes {
122    pub error: ParserError,
123    pub bytes: Option<Vec<u8>>,
124}
125
126impl Display for ParserErrorWithBytes {
127    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
128        write!(f, "{}", self.error)
129    }
130}
131
132impl Error for ParserErrorWithBytes {}
133
134/// implement Display trait for Error which satistifies the std::error::Error
135/// trait's requirement (must implement Display and Debug traits, Debug already derived)
136impl Display for ParserError {
137    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
138        match self {
139            ParserError::IoError(e) => write!(f, "Error: {e}"),
140            ParserError::EofError(e) => write!(f, "Error: {e}"),
141            ParserError::ParseError(s) => write!(f, "Error: {s}"),
142            ParserError::TruncatedMsg(s) => write!(f, "Error: {s}"),
143            ParserError::Unsupported(s) => write!(f, "Error: {s}"),
144            ParserError::OversizedRecord { length } => {
145                write!(f, "Error: MRT message too large: {length} bytes")
146            }
147            ParserError::EofExpected => write!(f, "Error: reach end of file"),
148            #[cfg(feature = "oneio")]
149            ParserError::OneIoError(e) => write!(f, "Error: {e}"),
150            ParserError::FilterError(e) => write!(f, "Error: {e}"),
151            ParserError::InvalidLabeledNlriLength => {
152                write!(f, "Error: invalid labeled NLRI length field")
153            }
154            ParserError::TruncatedLabeledNlri => write!(f, "Error: truncated labeled NLRI"),
155            ParserError::TruncatedPrefix => write!(f, "Error: truncated prefix in NLRI"),
156            ParserError::MaxLabelStackDepthExceeded => write!(
157                f,
158                "Error: max label stack depth exceeded without finding BoS bit"
159            ),
160            ParserError::PeerMaxLabelsExceeded => write!(
161                f,
162                "Error: received more labels than peer advertised maximum"
163            ),
164            ParserError::InvalidPrefix => write!(f, "Error: invalid prefix in NLRI"),
165        }
166    }
167}
168
169#[cfg(feature = "oneio")]
170impl From<OneIoError> for ParserErrorWithBytes {
171    fn from(error: OneIoError) -> Self {
172        ParserErrorWithBytes {
173            error: ParserError::OneIoError(error),
174            bytes: None,
175        }
176    }
177}
178
179#[cfg(feature = "oneio")]
180impl From<OneIoError> for ParserError {
181    fn from(error: OneIoError) -> Self {
182        ParserError::OneIoError(error)
183    }
184}
185
186impl From<ParserError> for ParserErrorWithBytes {
187    fn from(error: ParserError) -> Self {
188        ParserErrorWithBytes { error, bytes: None }
189    }
190}
191
192impl From<io::Error> for ParserError {
193    fn from(io_error: io::Error) -> Self {
194        match io_error.kind() {
195            ErrorKind::UnexpectedEof => ParserError::EofError(io_error),
196            _ => ParserError::IoError(io_error),
197        }
198    }
199}
200
201impl From<TryFromPrimitiveError<Bgp4MpType>> for ParserError {
202    fn from(value: TryFromPrimitiveError<Bgp4MpType>) -> Self {
203        ParserError::ParseError(format!("cannot parse bgp4mp subtype: {}", value.number))
204    }
205}
206
207impl From<TryFromPrimitiveError<BgpState>> for ParserError {
208    fn from(value: TryFromPrimitiveError<BgpState>) -> Self {
209        ParserError::ParseError(format!("cannot parse bgp4mp state: {}", value.number))
210    }
211}
212
213impl From<TryFromPrimitiveError<TableDumpV2Type>> for ParserError {
214    fn from(value: TryFromPrimitiveError<TableDumpV2Type>) -> Self {
215        ParserError::ParseError(format!("cannot parse table dump v2 type: {}", value.number))
216    }
217}
218
219impl From<TryFromPrimitiveError<EntryType>> for ParserError {
220    fn from(value: TryFromPrimitiveError<EntryType>) -> Self {
221        ParserError::ParseError(format!("cannot parse entry type: {}", value.number))
222    }
223}
224
225impl From<TryFromPrimitiveError<Afi>> for ParserError {
226    fn from(value: TryFromPrimitiveError<Afi>) -> Self {
227        ParserError::ParseError(format!("Unknown AFI type: {}", value.number))
228    }
229}
230
231impl From<TryFromPrimitiveError<Safi>> for ParserError {
232    fn from(value: TryFromPrimitiveError<Safi>) -> Self {
233        ParserError::ParseError(format!("Unknown SAFI type: {}", value.number))
234    }
235}
236
237/// BGP validation warnings for RFC 7606 compliant error handling.
238/// These represent non-fatal validation issues that don't prevent parsing.
239///
240/// This enum is `#[non_exhaustive]` so that new warning variants can be added
241/// in minor releases without breaking exhaustive matches.
242#[derive(Debug, Clone, PartialEq, Eq)]
243#[cfg_attr(feature = "serde", derive(serde::Serialize))]
244#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))]
245#[non_exhaustive]
246pub enum BgpValidationWarning {
247    /// Attribute flags conflict with attribute type code (RFC 4271 Section 6.3)
248    AttributeFlagsError {
249        attr_type: AttrType,
250        expected_flags: u8,
251        actual_flags: u8,
252    },
253    /// Attribute length conflicts with expected length (RFC 4271 Section 6.3)
254    AttributeLengthError {
255        attr_type: AttrType,
256        expected_length: Option<usize>,
257        actual_length: usize,
258    },
259    /// Missing well-known mandatory attribute (RFC 4271 Section 6.3)
260    MissingWellKnownAttribute { attr_type: AttrType },
261    /// Unrecognized well-known attribute (RFC 4271 Section 6.3)
262    UnrecognizedWellKnownAttribute { attr_type_code: u8 },
263    /// Invalid origin attribute value (RFC 4271 Section 6.3)
264    InvalidOriginAttribute { value: u8 },
265    /// Invalid next hop attribute (RFC 4271 Section 6.3)
266    InvalidNextHopAttribute { reason: String },
267    /// Malformed AS_PATH attribute (RFC 4271 Section 6.3)
268    MalformedAsPath { reason: String },
269    /// Optional attribute error (RFC 4271 Section 6.3)
270    OptionalAttributeError { attr_type: AttrType, reason: String },
271    /// Attribute appears more than once (RFC 4271 Section 6.3)
272    DuplicateAttribute { attr_type: AttrType },
273    /// Invalid network field in NLRI (RFC 4271 Section 6.3)
274    InvalidNetworkField { reason: String },
275    /// Malformed attribute list (RFC 4271 Section 6.3)
276    MalformedAttributeList { reason: String },
277    /// Partial attribute with errors (RFC 7606)
278    PartialAttributeError { attr_type: AttrType, reason: String },
279    /// Malformed NLRI field (RFC 7606 §5.3). The UPDATE message was parseable
280    /// up to the NLRI section, but the NLRI itself contained syntactic errors.
281    /// Per RFC 7606, the recommended action is "treat-as-withdrawal": all
282    /// routes carried in the NLRI section should be withdrawn.
283    ///
284    /// `nlri_type` distinguishes between the standard (IPv4 unicast) NLRI
285    /// field and the multiprotocol NLRI carried inside MP_REACH/MP_UNREACH
286    /// path attributes. `raw_bytes` preserves the offending NLRI bytes so
287    /// callers can inspect or export them without re-encoding.
288    MalformedNlri {
289        /// "withdrawn", "announced", "mp_reach", or "mp_unreach"
290        nlri_type: &'static str,
291        /// Human-readable description of the parse error
292        reason: String,
293        /// Raw NLRI bytes as they appeared in the UPDATE message
294        raw_bytes: Vec<u8>,
295    },
296    /// ROUTE-REFRESH message subtype other than 0, 1, or 2 (RFC 7313
297    /// Section 5). A live speaker MUST ignore such a message and SHOULD log
298    /// an error; the parser retains it raw and reports this warning.
299    UnknownRouteRefreshSubtype { subtype: u8 },
300    /// BoRR/EoRR ROUTE-REFRESH message (RFC 7313 subtype 1 or 2) whose body
301    /// is not exactly 4 bytes. On the wire this is a fatal "Invalid Message
302    /// Length" NOTIFICATION when the Enhanced Route Refresh capability was
303    /// negotiated; MRT data carries no session context, so the parser
304    /// retains the message and reports this warning instead.
305    InvalidRouteRefreshLength {
306        subtype: u8,
307        /// Message body length excluding the 19-byte BGP header
308        length: usize,
309    },
310}
311
312impl Display for BgpValidationWarning {
313    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
314        match self {
315            BgpValidationWarning::AttributeFlagsError { attr_type, expected_flags, actual_flags } => {
316                write!(f, "Attribute flags error for {attr_type:?}: expected 0x{expected_flags:02x}, got 0x{actual_flags:02x}")
317            }
318            BgpValidationWarning::AttributeLengthError { attr_type, expected_length, actual_length } => {
319                match expected_length {
320                    Some(expected) => write!(f, "Attribute length error for {attr_type:?}: expected {expected}, got {actual_length}"),
321                    None => write!(f, "Attribute length error for {attr_type:?}: invalid length {actual_length}"),
322                }
323            }
324            BgpValidationWarning::MissingWellKnownAttribute { attr_type } => {
325                write!(f, "Missing well-known mandatory attribute: {attr_type:?}")
326            }
327            BgpValidationWarning::UnrecognizedWellKnownAttribute { attr_type_code } => {
328                write!(f, "Unrecognized well-known attribute: type code {attr_type_code}")
329            }
330            BgpValidationWarning::InvalidOriginAttribute { value } => {
331                write!(f, "Invalid origin attribute value: {value}")
332            }
333            BgpValidationWarning::InvalidNextHopAttribute { reason } => {
334                write!(f, "Invalid next hop attribute: {reason}")
335            }
336            BgpValidationWarning::MalformedAsPath { reason } => {
337                write!(f, "Malformed AS_PATH: {reason}")
338            }
339            BgpValidationWarning::OptionalAttributeError { attr_type, reason } => {
340                write!(f, "Optional attribute error for {attr_type:?}: {reason}")
341            }
342            BgpValidationWarning::DuplicateAttribute { attr_type } => {
343                write!(f, "Duplicate attribute: {attr_type:?}")
344            }
345            BgpValidationWarning::InvalidNetworkField { reason } => {
346                write!(f, "Invalid network field: {reason}")
347            }
348            BgpValidationWarning::MalformedAttributeList { reason } => {
349                write!(f, "Malformed attribute list: {reason}")
350            }
351            BgpValidationWarning::PartialAttributeError { attr_type, reason } => {
352                write!(f, "Partial attribute error for {attr_type:?}: {reason}")
353            }
354            BgpValidationWarning::MalformedNlri { nlri_type, reason, .. } => {
355                write!(f, "Malformed NLRI ({nlri_type}): {reason}")
356            }
357            BgpValidationWarning::UnknownRouteRefreshSubtype { subtype } => {
358                write!(f, "Unknown ROUTE-REFRESH message subtype: {subtype}")
359            }
360            BgpValidationWarning::InvalidRouteRefreshLength { subtype, length } => {
361                write!(f, "Invalid ROUTE-REFRESH message length for subtype {subtype}: body is {length} bytes, expected 4")
362            }
363        }
364    }
365}
366
367/// Result type for BGP attribute parsing that includes validation warnings
368#[derive(Debug, Clone)]
369pub struct BgpValidationResult<T> {
370    pub value: T,
371    pub warnings: Vec<BgpValidationWarning>,
372}
373
374impl<T> BgpValidationResult<T> {
375    pub fn new(value: T) -> Self {
376        Self {
377            value,
378            warnings: Vec::new(),
379        }
380    }
381
382    pub fn with_warnings(value: T, warnings: Vec<BgpValidationWarning>) -> Self {
383        Self { value, warnings }
384    }
385
386    pub fn add_warning(&mut self, warning: BgpValidationWarning) {
387        self.warnings.push(warning);
388    }
389
390    pub fn has_warnings(&self) -> bool {
391        !self.warnings.is_empty()
392    }
393}