Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file.

### Breaking changes

* **`ParserError::OversizedRecord { length }`**: an MRT header declaring a body over the 16 MiB limit now returns this variant instead of `Unsupported("MRT message too large: …")`. The `Display` text is unchanged. Downstream exhaustive matches on `ParserError` need a new arm.
* **`ParserBmpError` carries the failing value and is `#[non_exhaustive]`**: `From<io::Error>` and the unknown-message-type conversion collapsed every failure into `InvalidOpenBmpHeader` and dropped the cause; they now return the new `IoError { kind, message }` and `UnknownMessageType(u8)` variants. Downstream matches on the enum now need a wildcard arm: `#[non_exhaustive]` means the two new variants cannot be covered by adding arms alone.

### Added
Expand All @@ -23,13 +24,15 @@ All notable changes to this project will be documented in this file.

### Fixed

* **Iterators stay aligned after an unknown MRT entry type**: `chunk_mrt_record` rejected an unknown entry type after reading only the 12-byte header, so `into_record_iter`, `into_elem_iter`, `into_raw_record_iter` and the fallible iterators read the record body as the next header and misparsed or dropped every record after it. The body is now consumed first, and the error's `bytes` hold the whole record. `into_diagnostic_iter` reports the record as a `ParseError` event and continues, where it previously stopped at any framing error.
* **Iterators stop at an oversized MRT length**: after a header declaring a body over 16 MiB, the default and fallible iterators read that body as headers. The default iterators now log the new `OversizedRecord` error and end, and the fallible iterators yield it once and end. `into_recovering_record_iter` still scans forward.
* **RIS Live JSON elems carry `origin_asns`**: `parse_ris_live_message` left `origin_asns` empty, so an `origin_asn` filter never matched an elem parsed from RIS Live's JSON fields. It is now derived from the AS path, as `parse_ris_live_message_raw` and the MRT iterators already did.
* **Dissection span correlation is linear in the number of warnings**: `span_record_warnings` (used by `DiagnosticIterator::with_dissection`) walked the whole dissection tree once per warning, so a BGP UPDATE carrying thousands of duplicate attributes took tens of seconds to diagnose. The tree is now indexed by field name once per record. Spans are unchanged.
* **Fallible iterators stop after a fatal stream read error**: `into_fallible_record_iter`, `into_fallible_elem_iter`, `into_fallible_update_iter` and `into_fallible_route_iter` now yield a framing I/O or decompression error once and then end, instead of polling a spent decoder indefinitely. An `Interrupted`/`WouldBlock` read stays retryable only when it consumed no framing bytes, and skippable malformed records are unchanged ([#350](https://github.com/bgpkit/bgpkit-parser/pull/350)).

### Contributors

* @ties — faster elem conversion ([#348](https://github.com/bgpkit/bgpkit-parser/pull/348)), `parse_ris_live_message_iter` and RIS Live origin ASNs, once-per-parser parse error logging, linear-time dissection span correlation
* @ties — faster elem conversion ([#348](https://github.com/bgpkit/bgpkit-parser/pull/348)), `parse_ris_live_message_iter` and RIS Live origin ASNs, once-per-parser parse error logging, linear-time dissection span correlation, MRT framing after unknown entry types and oversized lengths

## v0.22.0 - 2026-09-10

Expand Down
10 changes: 10 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ pub enum ParserError {
ParseError(String),
TruncatedMsg(String),
Unsupported(String),
/// An MRT common header declared a body over the 16 MiB limit. The length is
/// untrusted, so the reader is left past the header with no record boundary to
/// resume from, and the iterators stop instead of reading the body as headers.
OversizedRecord {
/// The declared body length that exceeded the limit.
length: u32,
},
FilterError(String),
/// NLRI length field is inconsistent with content
/// (total_bits < minimum required, or underflow in prefix calculation)
Expand Down Expand Up @@ -133,6 +140,9 @@ impl Display for ParserError {
ParserError::ParseError(s) => write!(f, "Error: {s}"),
ParserError::TruncatedMsg(s) => write!(f, "Error: {s}"),
ParserError::Unsupported(s) => write!(f, "Error: {s}"),
ParserError::OversizedRecord { length } => {
write!(f, "Error: MRT message too large: {length} bytes")
}
ParserError::EofExpected => write!(f, "Error: reach end of file"),
#[cfg(feature = "oneio")]
ParserError::OneIoError(e) => write!(f, "Error: {e}"),
Expand Down
3 changes: 3 additions & 0 deletions src/parser/iters/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use crate::parser::BgpkitParser;
use crate::{Elementor, Filterable};
use std::io::Read;

#[cfg(test)]
mod tests;

/*********
MrtRecord Iterator
**********/
Expand Down
127 changes: 127 additions & 0 deletions src/parser/iters/default/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//! Alignment tests for the skip-and-continue iterators: a rejected header must
//! leave the reader at a record boundary, or stop iteration when it cannot.

use crate::models::*;
use crate::parser::BgpkitParser;
use crate::{ParserError, RawMrtRecord};
use bytes::{BufMut, BytesMut};
use std::io::Cursor;

/// A record of type 0x7777 whose 20-byte body reads as a plausible common
/// header, so reading only the 12 header bytes would desynchronise the stream.
fn unknown_type_record() -> Vec<u8> {
let mut wire = BytesMut::new();
wire.put_u32(946_684_800);
wire.put_u16(0x7777);
wire.put_u16(0);
wire.put_u32(20);
wire.put_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]);
wire.put_slice(&[0xaa; 8]);
wire.to_vec()
}

/// A legacy BGP KEEPALIVE record (type BGP, subtype 7).
fn keepalive_record(timestamp: u32) -> Vec<u8> {
let body = [0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2];
let header = CommonHeader {
timestamp,
microsecond_timestamp: None,
entry_type: EntryType::BGP,
entry_subtype: 7,
length: body.len() as u32,
};
let mut wire = header.encode().to_vec();
wire.extend_from_slice(&body);
wire
}

/// A bare header declaring a body over the 16 MiB limit. Tests append a valid
/// record after it to check that iteration does not resume there.
fn oversized_record() -> Vec<u8> {
let mut wire = BytesMut::new();
wire.put_u32(1);
wire.put_u16(EntryType::BGP as u16);
wire.put_u16(7);
wire.put_u32(17 * 1024 * 1024);
wire.to_vec()
}

#[test]
fn record_iter_skips_unknown_entry_type_whole() {
let mut wire = unknown_type_record();
wire.extend_from_slice(&keepalive_record(946_684_801));
wire.extend_from_slice(&keepalive_record(946_684_802));

let records: Vec<MrtRecord> = BgpkitParser::from_reader(Cursor::new(wire))
.into_record_iter()
.collect();

let timestamps: Vec<u32> = records
.iter()
.map(|record| record.common_header.timestamp)
.collect();
assert_eq!(timestamps, vec![946_684_801, 946_684_802]);
}

#[test]
fn raw_record_iter_skips_unknown_entry_type_whole() {
let mut wire = unknown_type_record();
wire.extend_from_slice(&keepalive_record(946_684_801));

let records: Vec<RawMrtRecord> = BgpkitParser::from_reader(Cursor::new(wire))
.into_raw_record_iter()
.collect();

assert_eq!(records.len(), 1);
assert_eq!(records[0].common_header.timestamp, 946_684_801);
}

#[test]
fn record_iter_stops_at_oversized_length() {
let mut wire = keepalive_record(946_684_801);
wire.extend_from_slice(&oversized_record());
wire.extend_from_slice(&keepalive_record(946_684_802));

let records: Vec<MrtRecord> = BgpkitParser::from_reader(Cursor::new(wire))
.into_record_iter()
.collect();

let timestamps: Vec<u32> = records
.iter()
.map(|record| record.common_header.timestamp)
.collect();
assert_eq!(timestamps, vec![946_684_801]);
}

#[test]
fn fallible_record_iter_yields_unknown_type_error_then_next_record() {
let mut wire = unknown_type_record();
wire.extend_from_slice(&keepalive_record(946_684_801));

let mut iter = BgpkitParser::from_reader(Cursor::new(wire)).into_fallible_record_iter();

let error = iter.next().expect("unknown-type error").unwrap_err();
assert!(matches!(error.error, ParserError::ParseError(_)));
assert_eq!(
error.bytes.as_deref(),
Some(unknown_type_record().as_slice())
);
let record = iter.next().expect("following record").unwrap();
assert_eq!(record.common_header.timestamp, 946_684_801);
assert!(iter.next().is_none());
}

#[test]
fn fallible_record_iter_ends_after_oversized_length() {
let mut wire = oversized_record();
wire.extend_from_slice(&keepalive_record(946_684_801));

let mut iter = BgpkitParser::from_reader(Cursor::new(wire)).into_fallible_record_iter();

let error = iter.next().expect("oversized error").unwrap_err();
assert!(matches!(
error.error,
ParserError::OversizedRecord { length } if length == 17 * 1024 * 1024
));
assert!(iter.next().is_none());
}
60 changes: 58 additions & 2 deletions src/parser/iters/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,9 @@ impl<R: Read> Iterator for DiagnosticIterator<R> {
}
Err(error) => {
// A framing error may leave the reader between record boundaries. Do not
// attempt to reinterpret the remaining bytes as another MRT header.
self.terminated = true;
// attempt to reinterpret the remaining bytes as another MRT header unless
// a rejected header's record was consumed whole.
self.terminated = !error.record_consumed;
return Some(DiagnosticEvent::ParseError {
error: error.error,
common_header: error.common_header,
Expand Down Expand Up @@ -687,6 +688,61 @@ mod tests {
assert!(iter.next().is_none());
}

#[test]
fn diagnostic_iterator_continues_after_unknown_entry_type() {
// An unknown entry type is skipped whole, so the reader is still on a
// record boundary and the following record must be reported.
let mut unknown = vec![
0, 0, 0, 1, // timestamp
0x77, 0x77, // unknown entry type
0, 0, // subtype
0, 0, 0, 20, // length
];
unknown.extend_from_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]);
unknown.extend_from_slice(&[0xaa; 8]);
let mut input = unknown.clone();
input.extend_from_slice(&update_record(valid_attributes()).encode().unwrap());

let mut iter = BgpkitParser::from_reader(Cursor::new(input)).into_diagnostic_iter();
match iter.next().unwrap() {
DiagnosticEvent::ParseError {
error,
common_header,
raw_bytes,
..
} => {
assert!(matches!(error, ParserError::ParseError(_)));
assert_eq!(common_header, None);
assert_eq!(raw_bytes.as_deref(), Some(unknown.as_slice()));
}
event => panic!("expected parse error event, got {event:?}"),
}
assert!(matches!(iter.next(), Some(DiagnosticEvent::Record { .. })));
assert!(iter.next().is_none());
}

#[test]
fn diagnostic_iterator_terminates_after_truncated_unknown_entry_type() {
// The declared body outruns the stream, so no boundary is known and the
// iterator must not poll again.
let input = vec![
0, 0, 0, 1, // timestamp
0x77, 0x77, // unknown entry type
0, 0, // subtype
0, 0, 0, 8, // length, but only 4 body bytes follow
1, 2, 3, 4,
];

let mut iter = BgpkitParser::from_reader(Cursor::new(input.clone())).into_diagnostic_iter();
match iter.next().unwrap() {
DiagnosticEvent::ParseError { raw_bytes, .. } => {
assert_eq!(raw_bytes.as_deref(), Some(input.as_slice()));
}
event => panic!("expected parse error event, got {event:?}"),
}
assert!(iter.next().is_none());
}

#[test]
fn diagnostic_iterator_preserves_invalid_header_bytes() {
let invalid_header = vec![
Expand Down
36 changes: 26 additions & 10 deletions src/parser/iters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,23 @@ fn next_fallible_raw_record(
None
}
Err(error) => {
if let ParserError::IoError(io_error) | ParserError::EofError(io_error) = &error.error {
// A resumed pull starts a fresh header, so retrying is only safe
// when the failed read consumed nothing; otherwise the partial
// framing bytes are gone and the stream stays misaligned.
let nothing_consumed = error.bytes.as_ref().is_none_or(Vec::is_empty);
*finished = !(nothing_consumed
&& matches!(
io_error.kind(),
std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
));
match &error.error {
ParserError::IoError(io_error) | ParserError::EofError(io_error) => {
// A resumed pull starts a fresh header, so retrying is only safe
// when the failed read consumed nothing; otherwise the partial
// framing bytes are gone and the stream stays misaligned.
let nothing_consumed = error.bytes.as_ref().is_none_or(Vec::is_empty);
*finished = !(nothing_consumed
&& matches!(
io_error.kind(),
std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
));
}
ParserError::OversizedRecord { .. } => {
// no record boundary to resume from
*finished = true;
}
_ => {}
}
Some(Err(error))
}
Expand Down Expand Up @@ -165,6 +172,15 @@ pub(crate) fn handle_record_parse_error<R>(
// normal end of file
false
}
ParserError::OversizedRecord { length } => {
// no record boundary to resume from, stop iterating
error!(
"parser error: MRT message too large: {} bytes; stream position is unreliable, stopping",
length
);
write_mrt_core_dump(parser.core_dump, bytes);
false
}
ParserError::IoError(err) | ParserError::EofError(err) => {
// when reaching IO error, stop iterating
error!("{:?}", err);
Expand Down
5 changes: 4 additions & 1 deletion src/parser/iters/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1950,7 +1950,10 @@ mod tests {
let mut iter =
BgpkitParser::from_reader(Cursor::new(invalid_data.clone())).into_fallible_route_iter();

// The unknown-type record is skipped whole, so the error carries the
// header and the declared body, and the stream ends cleanly after it.
let error = iter.next().unwrap().unwrap_err();
assert_eq!(error.bytes.as_deref(), Some(&invalid_data[..12]));
assert_eq!(error.bytes.as_deref(), Some(invalid_data.as_slice()));
assert!(iter.next().is_none());
}
}
Loading
Loading