1use 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 OversizedRecord {
27 length: u32,
29 },
30 FilterError(String),
31 InvalidLabeledNlriLength,
34 TruncatedLabeledNlri,
36 TruncatedPrefix,
38 MaxLabelStackDepthExceeded,
40 PeerMaxLabelsExceeded,
43 InvalidPrefix,
45}
46
47impl Error for ParserError {}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum EncodingError {
58 ValueTooLarge {
64 field: &'static str,
65 actual: usize,
66 max: usize,
67 },
68 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
88pub(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
134impl 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#[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 AttributeFlagsError {
249 attr_type: AttrType,
250 expected_flags: u8,
251 actual_flags: u8,
252 },
253 AttributeLengthError {
255 attr_type: AttrType,
256 expected_length: Option<usize>,
257 actual_length: usize,
258 },
259 MissingWellKnownAttribute { attr_type: AttrType },
261 UnrecognizedWellKnownAttribute { attr_type_code: u8 },
263 InvalidOriginAttribute { value: u8 },
265 InvalidNextHopAttribute { reason: String },
267 MalformedAsPath { reason: String },
269 OptionalAttributeError { attr_type: AttrType, reason: String },
271 DuplicateAttribute { attr_type: AttrType },
273 InvalidNetworkField { reason: String },
275 MalformedAttributeList { reason: String },
277 PartialAttributeError { attr_type: AttrType, reason: String },
279 MalformedNlri {
289 nlri_type: &'static str,
291 reason: String,
293 raw_bytes: Vec<u8>,
295 },
296 UnknownRouteRefreshSubtype { subtype: u8 },
300 InvalidRouteRefreshLength {
306 subtype: u8,
307 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#[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}