diff --git a/CHANGELOG.md b/CHANGELOG.md index b687782b..ca67edc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` 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 @@ -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 diff --git a/src/error.rs b/src/error.rs index dde1b25a..76953b9e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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) @@ -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}"), diff --git a/src/parser/iters/default.rs b/src/parser/iters/default.rs index 5159976e..e66f9301 100644 --- a/src/parser/iters/default.rs +++ b/src/parser/iters/default.rs @@ -8,6 +8,9 @@ use crate::parser::BgpkitParser; use crate::{Elementor, Filterable}; use std::io::Read; +#[cfg(test)] +mod tests; + /********* MrtRecord Iterator **********/ diff --git a/src/parser/iters/default/tests.rs b/src/parser/iters/default/tests.rs new file mode 100644 index 00000000..6c7b80a6 --- /dev/null +++ b/src/parser/iters/default/tests.rs @@ -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 { + 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 { + 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 { + 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 = BgpkitParser::from_reader(Cursor::new(wire)) + .into_record_iter() + .collect(); + + let timestamps: Vec = 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 = 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 = BgpkitParser::from_reader(Cursor::new(wire)) + .into_record_iter() + .collect(); + + let timestamps: Vec = 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()); +} diff --git a/src/parser/iters/diagnostic.rs b/src/parser/iters/diagnostic.rs index 981f594a..5bb8e8c0 100644 --- a/src/parser/iters/diagnostic.rs +++ b/src/parser/iters/diagnostic.rs @@ -93,8 +93,9 @@ impl Iterator for DiagnosticIterator { } 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, @@ -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![ diff --git a/src/parser/iters/mod.rs b/src/parser/iters/mod.rs index 61f5ffcf..a13f1606 100644 --- a/src/parser/iters/mod.rs +++ b/src/parser/iters/mod.rs @@ -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)) } @@ -165,6 +172,15 @@ pub(crate) fn handle_record_parse_error( // 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); diff --git a/src/parser/iters/route.rs b/src/parser/iters/route.rs index 2c58265d..418c3291 100644 --- a/src/parser/iters/route.rs +++ b/src/parser/iters/route.rs @@ -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()); } } diff --git a/src/parser/mrt/mrt_header.rs b/src/parser/mrt/mrt_header.rs index 70bbf898..2522e3da 100644 --- a/src/parser/mrt/mrt_header.rs +++ b/src/parser/mrt/mrt_header.rs @@ -118,6 +118,27 @@ pub fn parse_common_header(input: &mut T) -> Result(input: &mut T) -> Result { + let framed = frame_common_header(input)?; + Ok(ParsedHeader { + header: framed.header?, + raw_bytes: framed.raw_bytes, + }) +} + +/// A common header as read from the wire, with its contents validated separately +/// from its framing. +pub(crate) struct FramedHeader { + /// The parsed header, or why its contents were rejected. + pub(crate) header: Result, + /// The header bytes as read from the wire. + pub(crate) raw_bytes: Bytes, + /// Length of the record body following `raw_bytes`. + pub(crate) body_length: u32, +} + +/// Read a common header, keeping its body length even when the contents are +/// rejected. Only I/O failures are returned as `Err`. +pub(crate) fn frame_common_header(input: &mut T) -> std::io::Result { let mut base_bytes = [0u8; 12]; input.read_exact(&mut base_bytes)?; @@ -126,40 +147,56 @@ pub fn parse_common_header_with_bytes(input: &mut T) -> Result entry_type, + Err(error) => return Ok(rejected(error.into())), + }; + + let (microsecond_timestamp, raw_bytes, body_length) = match &entry_type { EntryType::BGP4MP_ET => { // For ET records, the on-wire length includes the extra 4-byte microsecond timestamp // that lives in the header. Internally we store `length` as the message length only, // so subtract 4 after validating to avoid underflow. if length < 4 { - return Err(ParserError::ParseError( + return Ok(rejected(ParserError::ParseError( "invalid MRT header length for ET record: length < 4".into(), - )); + ))); } - length -= 4; let mut combined = [0u8; 16]; combined[..12].copy_from_slice(&base_bytes); input.read_exact(&mut combined[12..])?; let microseconds = u32::from_be_bytes(combined[12..16].try_into().unwrap()); - (Some(microseconds), Bytes::copy_from_slice(&combined)) + ( + Some(microseconds), + Bytes::copy_from_slice(&combined), + length - 4, + ) } - _ => (None, Bytes::copy_from_slice(&base_bytes)), + _ => (None, Bytes::copy_from_slice(&base_bytes), length), }; - Ok(ParsedHeader { - header: CommonHeader { + Ok(FramedHeader { + header: Ok(CommonHeader { timestamp, microsecond_timestamp, entry_type, entry_subtype, - length, - }, + length: body_length, + }), raw_bytes, + body_length, }) } diff --git a/src/parser/mrt/mrt_record.rs b/src/parser/mrt/mrt_record.rs index 2b264138..c5834e57 100644 --- a/src/parser/mrt/mrt_record.rs +++ b/src/parser/mrt/mrt_record.rs @@ -1,4 +1,4 @@ -use super::mrt_header::parse_common_header_with_bytes; +use super::mrt_header::frame_common_header; use crate::bmp::messages::{BmpMessage, BmpMessageBody}; use crate::error::{check_max, EncodingError, ParserError}; use crate::models::*; @@ -16,6 +16,9 @@ use std::net::IpAddr; use std::path::Path; use std::str::FromStr; +/// Upper bound on the MRT body length the parser will read into memory. +const MAX_MRT_MESSAGE_LEN: u32 = 16 * 1024 * 1024; // 16 MiB + /// Raw MRT record containing the common header and unparsed message bytes. /// This allows for lazy parsing of the MRT message body, and provides /// utilities for debugging and exporting problematic records. @@ -33,6 +36,9 @@ pub(crate) struct RawMrtRecordError { pub(crate) error: ParserError, pub(crate) common_header: Option, pub(crate) bytes: Option>, + /// A rejected header's declared body was read in full, so the next read starts + /// after this record, though not necessarily on a true boundary. + pub(crate) record_consumed: bool, } impl RawMrtRecord { @@ -132,76 +138,88 @@ pub fn chunk_mrt_record(input: &mut impl Read) -> Result Result { - // parse common header and capture raw bytes + // read the common header and capture raw bytes let mut consumed_header = Vec::with_capacity(16); - let parsed_header = match parse_common_header_with_bytes(&mut CapturingReader { + let framed = match frame_common_header(&mut CapturingReader { inner: input, captured: &mut consumed_header, }) { - Ok(v) => v, - Err(e) => { - if let ParserError::EofError(e) = &e { - if e.kind() == std::io::ErrorKind::UnexpectedEof && consumed_header.is_empty() { - return Err(RawMrtRecordError { - error: ParserError::EofExpected, - common_header: None, - bytes: None, - }); - } + Ok(framed) => framed, + Err(error) => { + if error.kind() == std::io::ErrorKind::UnexpectedEof && consumed_header.is_empty() { + return Err(RawMrtRecordError { + error: ParserError::EofExpected, + common_header: None, + bytes: None, + record_consumed: false, + }); } return Err(RawMrtRecordError { - error: e, + error: error.into(), common_header: None, bytes: Some(consumed_header), + record_consumed: false, }); } }; - let common_header = parsed_header.header; - let header_bytes = parsed_header.raw_bytes; + let header_bytes = framed.raw_bytes; + let parsed_header = framed.header.as_ref().ok().copied(); // Protect against unreasonable allocations from corrupt headers - const MAX_MRT_MESSAGE_LEN: u32 = 16 * 1024 * 1024; // 16 MiB upper bound - if common_header.length > MAX_MRT_MESSAGE_LEN { + if framed.body_length > MAX_MRT_MESSAGE_LEN { return Err(RawMrtRecordError { - error: ParserError::Unsupported(format!( - "MRT message too large: {} bytes", - common_header.length - )), - common_header: Some(common_header), + error: ParserError::OversizedRecord { + length: framed.body_length, + }, + common_header: parsed_header, bytes: Some(header_bytes.to_vec()), + record_consumed: false, }); } // Read the declared body while retaining partial bytes on failure. - let mut buffer = Vec::with_capacity(common_header.length as usize + 4); + let mut buffer = Vec::with_capacity(framed.body_length as usize + 4); if let Err(error) = input - .take(common_header.length as u64) + .take(framed.body_length as u64) .read_to_end(&mut buffer) { return Err(record_io_error( error, - common_header, + parsed_header, &header_bytes, &buffer, )); } - if buffer.len() != common_header.length as usize { + if buffer.len() != framed.body_length as usize { return Err(record_io_error( std::io::Error::new( std::io::ErrorKind::UnexpectedEof, format!( "truncated MRT body: expected {} bytes, read {}", - common_header.length, + framed.body_length, buffer.len() ), ), - common_header, + parsed_header, &header_bytes, &buffer, )); } + // A rejected header is reported only now, so its body is not left in the stream. + let common_header = match framed.header { + Ok(common_header) => common_header, + Err(error) => { + return Err(RawMrtRecordError { + error, + common_header: None, + bytes: Some([&header_bytes[..], &buffer].concat()), + record_consumed: true, + }) + } + }; + if common_header.entry_type == EntryType::TABLE_DUMP && super::messages::table_dump::needs_legacy_length_correction( common_header.entry_subtype, @@ -213,7 +231,7 @@ pub(crate) fn chunk_mrt_record_with_context( buffer.extend_from_slice(&correction); return Err(record_io_error( error, - common_header, + Some(common_header), &header_bytes, &buffer, )); @@ -225,7 +243,7 @@ pub(crate) fn chunk_mrt_record_with_context( std::io::ErrorKind::UnexpectedEof, "truncated historical TABLE_DUMP length correction", ), - common_header, + Some(common_header), &header_bytes, &buffer, )); @@ -260,7 +278,7 @@ impl Read for CapturingReader<'_, R> { fn record_io_error( error: std::io::Error, - common_header: CommonHeader, + common_header: Option, header: &[u8], body: &[u8], ) -> RawMrtRecordError { @@ -269,8 +287,9 @@ fn record_io_error( bytes.extend_from_slice(body); RawMrtRecordError { error: ParserError::IoError(error), - common_header: Some(common_header), + common_header, bytes: Some(bytes), + record_consumed: false, } } @@ -766,4 +785,145 @@ mod tests { let error = chunk_mrt_record(&mut Cursor::new(wire.clone().freeze())).unwrap_err(); assert_eq!(error.bytes.as_deref(), Some(wire.as_ref())); } + + /// A record of type 0x7777 whose 20-byte body reads as a plausible common + /// header (timestamp 1, type BGP, subtype 7, length 32), so a reader that + /// skips only the 12 header bytes would treat the body as the next record. + fn unknown_type_record() -> Vec { + 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() + } + + fn keepalive_record() -> (CommonHeader, Vec) { + let body = vec![0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2]; + let header = CommonHeader { + timestamp: 946_684_801, + 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); + (header, wire) + } + + #[test] + fn chunk_skips_body_of_unknown_entry_type() { + let unknown = unknown_type_record(); + let (next_header, next_wire) = keepalive_record(); + let mut wire = unknown.clone(); + wire.extend_from_slice(&next_wire); + let mut cursor = Cursor::new(wire); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!( + matches!(&error.error, ParserError::ParseError(msg) if msg.contains("entry type")), + "unexpected error: {}", + error.error + ); + assert_eq!(error.bytes.as_deref(), Some(unknown.as_slice())); + assert_eq!(cursor.position(), unknown.len() as u64); + + let next = chunk_mrt_record(&mut cursor).unwrap(); + assert_eq!(next.common_header, next_header); + assert!(matches!( + next.parse().unwrap().message, + MrtMessage::LegacyBgp(LegacyBgp::Message(LegacyBgpMessage { + bgp_message: BgpMessage::KeepAlive, + .. + })) + )); + assert!(matches!( + chunk_mrt_record(&mut cursor).unwrap_err().error, + ParserError::EofExpected + )); + } + + #[test] + fn chunk_skips_body_of_et_header_with_short_length() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(EntryType::BGP4MP_ET as u16); + wire.put_u16(4); + wire.put_u32(2); + wire.put_slice(&[0xaa; 2]); + let rejected = wire.to_vec(); + let (next_header, next_wire) = keepalive_record(); + wire.put_slice(&next_wire); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err(); + assert!(matches!(error.error, ParserError::ParseError(_))); + assert!(error.record_consumed); + assert_eq!(error.bytes.as_deref(), Some(rejected.as_slice())); + assert_eq!( + chunk_mrt_record(&mut cursor).unwrap().common_header, + next_header + ); + } + + #[test] + fn chunk_reports_truncated_body_of_unknown_entry_type() { + let unknown = unknown_type_record(); + let truncated = &unknown[..unknown.len() - 5]; + let mut cursor = Cursor::new(truncated.to_vec()); + + let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err(); + assert!(matches!( + &error.error, + ParserError::IoError(io_error) if io_error.kind() == std::io::ErrorKind::UnexpectedEof + )); + assert!(error.common_header.is_none()); + assert!(!error.record_consumed); + assert_eq!(error.bytes.as_deref(), Some(truncated)); + assert!(matches!( + chunk_mrt_record(&mut cursor).unwrap_err().error, + ParserError::EofExpected + )); + } + + #[test] + fn chunk_reports_oversized_length_without_reading_body() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(EntryType::BGP as u16); + wire.put_u16(7); + wire.put_u32(MAX_MRT_MESSAGE_LEN + 1); + wire.put_slice(&[0xaa; 32]); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!(matches!( + error.error, + ParserError::OversizedRecord { length } if length == MAX_MRT_MESSAGE_LEN + 1 + )); + assert_eq!(error.bytes.as_deref(), Some(&wire[..12])); + assert_eq!(cursor.position(), 12); + } + + #[test] + fn chunk_reports_oversized_length_for_unknown_entry_type() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(0x7777); + wire.put_u16(0); + wire.put_u32(u32::MAX); + wire.put_slice(&[0xaa; 32]); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!(matches!( + error.error, + ParserError::OversizedRecord { length: u32::MAX } + )); + assert_eq!(error.bytes.as_deref(), Some(&wire[..12])); + assert_eq!(cursor.position(), 12); + } } diff --git a/tests/torn_mrt_records.rs b/tests/torn_mrt_records.rs index 29d0c0c9..e49fb600 100644 --- a/tests/torn_mrt_records.rs +++ b/tests/torn_mrt_records.rs @@ -35,8 +35,17 @@ //! UPDATE, 307 STATE_CHANGE, 34 KEEPALIVE), 5,378 elements, zero errors — so there //! is no body-level parsing defect here. What is missing is stream //! resynchronization: on a framing error the reader has no pushback and cannot scan -//! forward for the next plausible common header, so every iterator either retries -//! at the same wrong offset or stops. +//! forward for the next plausible common header. From offset 14,756 the parser +//! frames two more "headers" out of mid-record bytes before giving up: +//! +//! ```text +//! 00 cb 25 ff 7e 31 6e c1 00 00 01 00 unknown entry type 32305, 256-byte body +//! de 57 0c 14 c8 bc 80 38 dc 36 b9 00 length 3,694,573,824 exceeds the 16 MiB limit +//! ``` +//! +//! Skipping the unknown-type "record" by its declared length does not restore +//! alignment here: it moves 256 bytes further into the damage. Only the oversized +//! length stops iteration. //! //! The assertions below therefore pin **current, lossy** behaviour rather than //! desired behaviour. Every count is a deterministic function of the fixture bytes. @@ -57,10 +66,13 @@ const FIXTURE: &str = "tests/fixtures/ripe/rrc00/2000.03/updates.20000325.0345.g /// holds 2,580 recoverable records and 5,378 recoverable elements, so all but these /// four are lost. const RECORDS_BEFORE_FIRST_TORN_WRITE: usize = 4; -/// Errors produced while the parser hunts forward 12 bytes at a time after -/// desynchronizing. It never re-aligns, because the true record boundary is not a -/// multiple of 12 from where the oversized read left it. -const DESYNCHRONIZED_ERRORS: usize = 128; +/// Errors produced from the torn write onwards: the truncated 14,556-byte body, +/// the unknown-type "record" skipped whole, and the oversized length that ends +/// iteration. +const DESYNCHRONIZED_ERRORS: usize = 3; +/// Body length the unknown-type "header" at offset 14,756 declares; its 12 header +/// bytes plus this body are consumed and attached to the error. +const UNKNOWN_TYPE_BODY_LENGTH: usize = 256; /// Header the parser manufactures from the 10-byte torn write at offset 188. const TORN_HEADER_TIMESTAMP: u32 = 953_955_944; @@ -87,16 +99,13 @@ fn torn_writes_desynchronize_raw_record_framing() { } // Only 5 of the fixture's 2,580 records reach framing — 4 genuine ones plus the - // 14,556-byte torn "record" — after which the parser frames 3 more headers out of - // misaligned bytes. - assert_eq!(raw_records, 8); + // 14,556-byte torn "record". The misaligned bytes after it frame no further + // records: one header has an unknown type and is skipped, the next declares an + // oversized body and stops the iterator. + assert_eq!(raw_records, 5); assert_eq!( headers, BTreeMap::from([ - ( - (EntryType::NULL as u16, 256), - 3 // pure garbage, framed mid-record after desynchronizing - ), ( (EntryType::BGP as u16, 1), 4 // 3 genuine UPDATEs plus the torn 14,556-byte "record" @@ -110,8 +119,8 @@ fn torn_writes_desynchronize_raw_record_framing() { fn torn_writes_lose_all_but_four_records() { let source = repo_fixture(FIXTURE); - // Skipping iterators: the error arms can only retry at the same wrong offset or - // stop, so 2,576 of 2,580 records and 5,374 of 5,378 elements are lost. + // Skipping iterators: the error arms can only skip a framed record or stop, so + // 2,576 of 2,580 records and 5,374 of 5,378 elements are lost. assert_eq!( BgpkitParser::new(&source) .unwrap() @@ -207,9 +216,10 @@ fn diagnostic_iterator_reports_both_torn_writes() { .into_diagnostic_iter() .collect(); - // Four clean records, then one body error, then one framing error which - // terminates the iterator by design. - assert_eq!(events.len(), RECORDS_BEFORE_FIRST_TORN_WRITE + 2); + // Four clean records, then one body error, then the unknown-type record that + // is skipped whole, then the oversized length which terminates the iterator + // by design. + assert_eq!(events.len(), RECORDS_BEFORE_FIRST_TORN_WRITE + 3); for event in &events[..RECORDS_BEFORE_FIRST_TORN_WRITE] { let DiagnosticEvent::Record { record, .. } = event else { panic!("expected a clean record, got {event:?}"); @@ -248,9 +258,10 @@ fn diagnostic_iterator_reports_both_torn_writes() { Some(12 + TORN_HEADER_LENGTH as usize) ); - // The oversized read left the stream mid-record, so the next 12 bytes are not a - // header. There is no header to report, and the framing error terminates - // iteration rather than reinterpreting the remaining bytes. + // The 14,556-byte read left the stream mid-record, so the next 12 bytes are not a + // real header. Their entry type is unknown, so no header is reported; the + // declared 256-byte body is consumed and attached, and the iterator carries on + // from the byte after it, still misaligned. let DiagnosticEvent::ParseError { error, common_header, @@ -268,5 +279,34 @@ fn diagnostic_iterator_reports_both_torn_writes() { }; assert_eq!(message, "cannot parse entry type: 32305"); assert!(common_header.is_none()); + assert_eq!( + raw_bytes.as_deref().map(<[u8]>::len), + Some(12 + UNKNOWN_TYPE_BODY_LENGTH) + ); + + // The next 12 bytes have another unknown entry type (51388) and a length over + // the 16 MiB limit, which ends iteration. + let DiagnosticEvent::ParseError { + error, + common_header, + raw_bytes, + .. + } = &events[RECORDS_BEFORE_FIRST_TORN_WRITE + 2] + else { + panic!( + "expected an oversized-length error, got {:?}", + events[RECORDS_BEFORE_FIRST_TORN_WRITE + 2] + ); + }; + assert!( + matches!( + error, + ParserError::OversizedRecord { + length: 3_694_573_824 + } + ), + "expected OversizedRecord, got {error:?}" + ); + assert!(common_header.is_none()); assert_eq!(raw_bytes.as_deref().map(<[u8]>::len), Some(12)); }