Skip to main content

bgpkit_parser/parser/iters/
mod.rs

1/*!
2Iterator implementations for bgpkit-parser.
3
4This module contains different iterator implementations for parsing BGP data:
5- `default`: Standard iterators that skip errors (RecordIterator, ElemIterator)
6- `fallible`: Fallible iterators that return Results (FallibleRecordIterator, FallibleElemIterator)
7- `update`: Iterators for BGP UPDATE messages (UpdateIterator, FallibleUpdateIterator)
8- `route`: Route-level iterators (RouteIterator, FallibleRouteIterator)
9- `recovery`: Iterators that survive damaged MRT framing (RecoveringRecordIterator,
10  RecoveringElemIterator, RecoveryEvent)
11- `diagnostic`: Per-record dissection and validation reporting (DiagnosticIterator,
12  DissectingDiagnosticIterator)
13- `raw`: Raw MRT records with their original bytes (RawRecordIterator,
14  FilteredRawRecordIterator)
15
16It also contains the trait implementations that enable BgpkitParser to be used with
17Rust's iterator syntax.
18*/
19
20pub mod default;
21mod diagnostic;
22pub(crate) mod elem_ref;
23pub mod fallible;
24mod raw;
25mod recovery;
26mod route;
27mod update;
28
29// Re-export all iterator types for convenience
30pub use default::{ElemIterator, RecordIterator};
31pub use diagnostic::{
32    record_validation_warnings, span_record_warnings, DiagnosticEvent, DiagnosticIterator,
33    DissectedDiagnosticEvent, DissectingDiagnosticIterator,
34};
35pub use elem_ref::{
36    AsPathIter, AsPathView, AsnsIter, AsnsView, CommunitiesIter, CommunitiesView, ElemRef,
37    ElemRefIter, RecordElems,
38};
39pub use fallible::{FallibleElemIterator, FallibleRecordIterator};
40pub use raw::{FilteredRawRecordIterator, RawRecordIterator};
41pub use recovery::{
42    RecoveringElemIterator, RecoveringRecordIterator, RecoveryConfig, RecoveryError, RecoveryEvent,
43    RecoveryEvidence, RecoveryGap,
44};
45pub use route::{FallibleRouteIterator, RouteIterator};
46pub use update::{
47    Bgp4MpUpdate, FallibleUpdateIterator, LegacyBgpUpdate, MrtUpdate, TableDumpV2Entry,
48    UpdateIterator,
49};
50
51use crate::error::{ParserError, ParserErrorWithBytes};
52use crate::models::BgpElem;
53use crate::models::{MrtMessage, MrtRecord, TableDumpV2Message};
54use crate::parser::mrt::mrt_record::parse_chunked_record_with_zebra_compat;
55use crate::parser::{chunk_mrt_record, BgpkitParser};
56use crate::RawMrtRecord;
57use crate::{Elementor, Filter, Filterable};
58use log::{debug, error, warn};
59use std::io::Read;
60use std::path::Path;
61
62// Classify stream failures while framing: body parsing can also return
63// skippable IoErrors, but a failed decompressor must not be polled again.
64fn next_fallible_raw_record(
65    reader: &mut impl Read,
66    finished: &mut bool,
67) -> Option<Result<RawMrtRecord, ParserErrorWithBytes>> {
68    if *finished {
69        return None;
70    }
71    match chunk_mrt_record(reader) {
72        Ok(record) => Some(Ok(record)),
73        Err(error) if matches!(error.error, ParserError::EofExpected) => {
74            *finished = true;
75            None
76        }
77        Err(error) => {
78            match &error.error {
79                ParserError::IoError(io_error) | ParserError::EofError(io_error) => {
80                    // A resumed pull starts a fresh header, so retrying is only safe
81                    // when the failed read consumed nothing; otherwise the partial
82                    // framing bytes are gone and the stream stays misaligned.
83                    let nothing_consumed = error.bytes.as_ref().is_none_or(Vec::is_empty);
84                    *finished = !(nothing_consumed
85                        && matches!(
86                            io_error.kind(),
87                            std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
88                        ));
89                }
90                ParserError::OversizedRecord { .. } => {
91                    // no record boundary to resume from
92                    *finished = true;
93                }
94                _ => {}
95            }
96            Some(Err(error))
97        }
98    }
99}
100
101fn next_fallible_record<R: Read>(
102    parser: &mut BgpkitParser<R>,
103    finished: &mut bool,
104) -> Option<Result<MrtRecord, ParserErrorWithBytes>> {
105    let raw_record = match next_fallible_raw_record(&mut parser.reader, finished)? {
106        Ok(record) => record,
107        Err(error) => return Some(Err(error)),
108    };
109    Some(match parse_chunked_record_with_zebra_compat(raw_record) {
110        Ok((record, used_zebra_compat)) => {
111            if used_zebra_compat {
112                parser.warn_zebra_compat_once();
113            }
114            Ok(record)
115        }
116        Err(error) => Err(error),
117    })
118}
119
120#[inline]
121pub(crate) fn record_matches_filters(
122    record: &MrtRecord,
123    filters: &[Filter],
124    elementor: &mut Elementor,
125) -> bool {
126    if filters.is_empty() {
127        return true;
128    }
129    if matches!(
130        &record.message,
131        MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_))
132    ) {
133        let _ = elementor.record_to_elems(record.clone());
134        return true;
135    }
136    // Filters match on the elem projection. Records that produce no elems
137    // (KEEPALIVE, OPEN, NOTIFICATION, state changes) can therefore never
138    // match and are dropped from record iteration while filters are active.
139    let elems = elementor.record_to_elems(record.clone());
140    if elems.is_empty() {
141        debug!(
142            "filters active: record of type {:?} yields no elems and is dropped",
143            record.common_header.entry_type
144        );
145        return false;
146    }
147    elems.iter().any(|element| element.match_filters(filters))
148}
149
150/// Shared body-parse error policy for record-producing iterators.
151///
152/// Mirrors the historical `RecordIterator` behavior: warnings honor
153/// `disable_warnings()`, core dumps are written for recoverable classes,
154/// and a fatal `ParseError` with core dumps enabled stops the iterator so
155/// a later failure cannot overwrite the dump. Returns `true` to continue
156/// iterating, `false` to stop.
157pub(crate) fn handle_record_parse_error<R>(
158    parser: &mut crate::parser::BgpkitParser<R>,
159    error: ParserError,
160    bytes: Option<Vec<u8>>,
161) -> bool {
162    match error {
163        ParserError::TruncatedMsg(err_str) | ParserError::Unsupported(err_str) => {
164            if parser.options.show_warnings {
165                warn!("parser warn: {}", err_str);
166            }
167            write_mrt_core_dump(parser.core_dump, bytes);
168            true
169        }
170        ParserError::ParseError(err_str) => {
171            parser.log_parse_error_once(&err_str);
172            write_mrt_core_dump(parser.core_dump, bytes);
173            // stop after writing the dump so later failures don't overwrite it
174            !parser.core_dump
175        }
176        ParserError::EofExpected => {
177            // normal end of file
178            false
179        }
180        ParserError::OversizedRecord { length } => {
181            // no record boundary to resume from, stop iterating
182            error!(
183                "parser error: MRT message too large: {} bytes; stream position is unreliable, stopping",
184                length
185            );
186            write_mrt_core_dump(parser.core_dump, bytes);
187            false
188        }
189        ParserError::IoError(err) | ParserError::EofError(err) => {
190            // when reaching IO error, stop iterating
191            error!("{:?}", err);
192            write_mrt_core_dump(parser.core_dump, bytes);
193            false
194        }
195        #[cfg(feature = "oneio")]
196        ParserError::OneIoError(_) => false,
197        ParserError::FilterError(_) => {
198            // this should not happen at this stage
199            false
200        }
201        // Labeled NLRI parsing errors - treat as malformed and skip
202        ParserError::InvalidLabeledNlriLength
203        | ParserError::TruncatedLabeledNlri
204        | ParserError::TruncatedPrefix
205        | ParserError::MaxLabelStackDepthExceeded
206        | ParserError::PeerMaxLabelsExceeded
207        | ParserError::InvalidPrefix => {
208            if parser.options.show_warnings {
209                warn!("parser warn: labeled NLRI parsing error: {:?}", error);
210            }
211            true
212        }
213    }
214}
215
216pub(crate) fn write_mrt_core_dump(enabled: bool, bytes: Option<Vec<u8>>) {
217    write_mrt_core_dump_to_path(enabled, bytes, "mrt_core_dump");
218}
219
220pub(crate) fn write_mrt_core_dump_to_path<P: AsRef<Path>>(
221    enabled: bool,
222    bytes: Option<Vec<u8>>,
223    path: P,
224) {
225    if enabled {
226        if let Some(bytes) = bytes {
227            std::fs::write(path, bytes).expect("Unable to write to mrt_core_dump");
228        }
229    }
230}
231
232/// Use [ElemIterator] as the default iterator to return [BgpElem]s instead of [MrtRecord]s.
233impl<R: Read> IntoIterator for BgpkitParser<R> {
234    type Item = BgpElem;
235    type IntoIter = ElemIterator<R>;
236
237    fn into_iter(self) -> Self::IntoIter {
238        ElemIterator::new(self)
239    }
240}
241
242impl<R> BgpkitParser<R> {
243    pub fn into_record_iter(self) -> RecordIterator<R> {
244        RecordIterator::new(self)
245    }
246
247    pub fn into_elem_iter(self) -> ElemIterator<R> {
248        ElemIterator::new(self)
249    }
250
251    pub fn into_raw_record_iter(self) -> RawRecordIterator<R> {
252        RawRecordIterator::new(self)
253    }
254
255    /// Creates an iterator over raw MRT records with record-level filter
256    /// semantics applied.
257    ///
258    /// Like [`into_raw_record_iter`](Self::into_raw_record_iter), but only
259    /// records passing the parser's filters are yielded (same semantics as
260    /// [`into_record_iter`](Self::into_record_iter): filters match on the
261    /// elem projection, so no-elem records such as KEEPALIVEs are dropped
262    /// while filters are active, and the `PeerIndexTable` always passes).
263    /// The yielded records carry their original wire bytes — no
264    /// re-encoding — which is what byte-exact consumers (hex output,
265    /// re-dissection) need. Every record body is parsed once inside the
266    /// iterator and the parsed record is yielded alongside, so consumers
267    /// do not parse the bytes twice; parse failures follow the same
268    /// variant-aware diagnostics as the record iterator.
269    ///
270    /// # Example
271    /// ```no_run
272    /// use bgpkit_parser::BgpkitParser;
273    ///
274    /// let parser = BgpkitParser::new("updates.mrt").unwrap();
275    /// for (raw, _) in parser.into_filtered_raw_record_iter() {
276    ///     println!("{}", raw.raw_bytes().len());
277    /// }
278    /// ```
279    pub fn into_filtered_raw_record_iter(self) -> FilteredRawRecordIterator<R> {
280        FilteredRawRecordIterator::new(self)
281    }
282
283    /// Creates an opt-in iterator that reports skipped byte ranges while recovering MRT framing.
284    ///
285    /// Recovery never reconstructs a damaged record. It scans for a structurally valid boundary,
286    /// confirms a chain of records, emits [`RecoveryEvent::Gap`], and then resumes normal parsing.
287    /// Damage extending to the end of the stream is reported as a terminal gap. Offsets in
288    /// recovery events refer to the decompressed MRT byte stream.
289    pub fn into_recovering_record_iter(
290        self,
291        config: RecoveryConfig,
292    ) -> RecoveringRecordIterator<R> {
293        RecoveringRecordIterator::new(self, config)
294    }
295
296    /// Creates an opt-in iterator over BGP elements that reports skipped byte ranges while
297    /// recovering MRT framing.
298    ///
299    /// Behaves like [`into_recovering_record_iter`](Self::into_recovering_record_iter) but
300    /// converts each recovered record to [`BgpElem`]s, applying the parser's filters per
301    /// element.
302    pub fn into_recovering_elem_iter(self, config: RecoveryConfig) -> RecoveringElemIterator<R> {
303        RecoveringElemIterator::new(self, config)
304    }
305
306    /// Creates an iterator over BGP announcements from MRT data.
307    ///
308    /// This iterator yields `MrtUpdate` items from both UPDATES files (BGP4MP messages)
309    /// and RIB dump files (TableDump/TableDumpV2 messages). It's a middle ground
310    /// between `into_record_iter()` and `into_elem_iter()`:
311    ///
312    /// - More focused than `into_record_iter()` as it only returns BGP announcements
313    /// - More efficient than `into_elem_iter()` as it doesn't duplicate attributes per prefix
314    ///
315    /// The iterator returns an `MrtUpdate` enum with variants:
316    /// - `Bgp4MpUpdate`: BGP UPDATE messages from UPDATES files
317    /// - `LegacyBgpUpdate`: Deprecated MRT Type 5 BGP UPDATE messages
318    /// - `TableDumpV2Entry`: RIB entries from TableDumpV2 RIB dumps
319    /// - `TableDumpMessage`: Legacy TableDump v1 messages
320    ///
321    /// # Example
322    /// ```no_run
323    /// use bgpkit_parser::{BgpkitParser, MrtUpdate};
324    ///
325    /// let parser = BgpkitParser::new("updates.mrt").unwrap();
326    /// for update in parser.into_update_iter() {
327    ///     match update {
328    ///         MrtUpdate::Bgp4MpUpdate(u) => {
329    ///             println!("Peer {} announced {} prefixes",
330    ///                 u.peer_ip,
331    ///                 u.message.announced_prefixes.len()
332    ///             );
333    ///         }
334    ///         MrtUpdate::LegacyBgpUpdate(u) => {
335    ///             println!("Legacy UPDATE from peer {}", u.peer_ip);
336    ///         }
337    ///         MrtUpdate::TableDumpV2Entry(e) => {
338    ///             println!("RIB entry for {} with {} peers",
339    ///                 e.prefix,
340    ///                 e.rib_entries.len()
341    ///             );
342    ///         }
343    ///         MrtUpdate::TableDumpMessage(m) => {
344    ///             println!("Legacy table dump for {}", m.prefix);
345    ///         }
346    ///     }
347    /// }
348    /// ```
349    pub fn into_update_iter(self) -> UpdateIterator<R> {
350        UpdateIterator::new(self)
351    }
352
353    /// Creates an iterator over lightweight route elements from MRT data.
354    ///
355    /// This iterator yields [`BgpRouteElem`](crate::models::BgpRouteElem)
356    /// values and only parses route identity, peer metadata, timestamp, and
357    /// AS path. Use [`into_elem_iter`](Self::into_elem_iter) when you need
358    /// the full [`BgpElem`] attribute set. Filters that only depend on route
359    /// fields are supported; `community` filters do not match route elements.
360    pub fn into_route_iter(self) -> RouteIterator<R> {
361        RouteIterator::new(self)
362    }
363
364    /// Creates a fallible iterator over MRT records that returns parsing errors.
365    ///
366    /// Malformed records can be skipped. A framing I/O or decompression error
367    /// is yielded once and then ends iteration permanently, except for an
368    /// `Interrupted` or `WouldBlock` read that consumed no framing bytes, which
369    /// leaves the stream retryable. Normal EOF also ends iteration permanently.
370    ///
371    /// # Example
372    /// ```no_run
373    /// use bgpkit_parser::BgpkitParser;
374    ///
375    /// let parser = BgpkitParser::new("updates.mrt").unwrap();
376    /// for result in parser.into_fallible_record_iter() {
377    ///     match result {
378    ///         Ok(record) => {
379    ///             // Process the record
380    ///         }
381    ///         Err(e) => {
382    ///             // Handle the error
383    ///             eprintln!("Error parsing record: {}", e);
384    ///         }
385    ///     }
386    /// }
387    /// ```
388    pub fn into_fallible_record_iter(self) -> FallibleRecordIterator<R> {
389        FallibleRecordIterator::new(self)
390    }
391
392    /// Creates a fallible iterator over BGP elements that returns parsing errors.
393    ///
394    /// Uses the same stream-error termination policy as
395    /// [`into_fallible_record_iter`](Self::into_fallible_record_iter).
396    ///
397    /// # Example
398    /// ```no_run
399    /// use bgpkit_parser::BgpkitParser;
400    ///
401    /// let parser = BgpkitParser::new("updates.mrt").unwrap();
402    /// for result in parser.into_fallible_elem_iter() {
403    ///     match result {
404    ///         Ok(elem) => {
405    ///             // Process the element
406    ///         }
407    ///         Err(e) => {
408    ///             // Handle the error
409    ///             eprintln!("Error parsing element: {}", e);
410    ///         }
411    ///     }
412    /// }
413    /// ```
414    pub fn into_fallible_elem_iter(self) -> FallibleElemIterator<R> {
415        FallibleElemIterator::new(self)
416    }
417
418    /// Creates a fallible iterator over BGP announcements that returns parsing errors.
419    ///
420    /// Unlike the default `into_update_iter()`, this iterator returns
421    /// `Result<MrtUpdate, ParserErrorWithBytes>` allowing users to handle parsing
422    /// errors explicitly instead of having them logged and skipped. Uses the same
423    /// stream-error termination policy as
424    /// [`into_fallible_record_iter`](Self::into_fallible_record_iter).
425    ///
426    /// # Example
427    /// ```no_run
428    /// use bgpkit_parser::{BgpkitParser, MrtUpdate};
429    ///
430    /// let parser = BgpkitParser::new("updates.mrt").unwrap();
431    /// for result in parser.into_fallible_update_iter() {
432    ///     match result {
433    ///         Ok(MrtUpdate::Bgp4MpUpdate(update)) => {
434    ///             println!("Peer {} announced {} prefixes",
435    ///                 update.peer_ip,
436    ///                 update.message.announced_prefixes.len()
437    ///             );
438    ///         }
439    ///         Ok(_) => { /* handle other variants */ }
440    ///         Err(e) => {
441    ///             eprintln!("Error parsing: {}", e);
442    ///         }
443    ///     }
444    /// }
445    /// ```
446    pub fn into_fallible_update_iter(self) -> FallibleUpdateIterator<R> {
447        FallibleUpdateIterator::new(self)
448    }
449
450    /// Creates a fallible iterator over lightweight route elements.
451    ///
452    /// Uses the same stream-error termination policy as
453    /// [`into_fallible_record_iter`](Self::into_fallible_record_iter).
454    pub fn into_fallible_route_iter(self) -> FallibleRouteIterator<R> {
455        FallibleRouteIterator::new(self)
456    }
457
458    /// Creates an iterator that classifies each MRT record for malformed-data investigation.
459    ///
460    /// This iterator emits every record with its raw bytes attached: clean
461    /// records have empty warning lists, records with recoverable RFC 7606
462    /// validation findings carry them in `warnings`, and fatal parse errors
463    /// retain the consumed bytes plus a best-effort partial dissection tree
464    /// showing where parsing stopped. It ignores parser filters so that
465    /// malformed records cannot be hidden by element-oriented matching. Text-dump parsers yield
466    /// no diagnostic events because they have no MRT record representation.
467    ///
468    /// # Example
469    /// ```no_run
470    /// use bgpkit_parser::{BgpkitParser, DiagnosticEvent};
471    ///
472    /// for event in BgpkitParser::new("updates.mrt")?.into_diagnostic_iter() {
473    ///     match event {
474    ///         DiagnosticEvent::Record { record, raw, warnings } => {
475    ///             if warnings.is_empty() {
476    ///                 println!("{record}");
477    ///             } else {
478    ///                 eprintln!("validation findings: {warnings:?}");
479    ///                 raw.write_raw_bytes("malformed-record.mrt")?;
480    ///             }
481    ///         }
482    ///         DiagnosticEvent::ParseError { error, raw_bytes, .. } => {
483    ///             eprintln!("parse error: {error}");
484    ///             if let Some(raw_bytes) = raw_bytes {
485    ///                 std::fs::write("malformed-record.mrt", raw_bytes)?;
486    ///             }
487    ///         }
488    ///         _ => {}
489    ///     }
490    /// }
491    /// # Ok::<(), Box<dyn std::error::Error>>(())
492    /// ```
493    pub fn into_diagnostic_iter(self) -> DiagnosticIterator<R> {
494        DiagnosticIterator::new(self)
495    }
496
497    /// Creates an Elementor pre-initialized with PeerIndexTable and an iterator over raw records.
498    ///
499    /// This is useful for parallel processing where the Elementor needs to be shared across threads.
500    /// The Elementor is created with the PeerIndexTable from the first record if present,
501    /// otherwise a new Elementor is created.
502    ///
503    /// # Example
504    /// See the `parallel_records_to_elem` example for full usage.
505    /// ```ignore
506    /// use bgpkit_parser::BgpkitParser;
507    ///
508    /// let parser = BgpkitParser::new_cached(url, "/tmp")?;
509    /// let (elementor, records) = parser.into_elementor_and_raw_record_iter();
510    /// ```
511    ///
512    pub fn into_elementor_and_raw_record_iter(
513        self,
514    ) -> (Elementor, impl Iterator<Item = RawMrtRecord>)
515    where
516        R: Read,
517    {
518        let mut raw_iter = RawRecordIterator::new(self).peekable();
519        let elementor = match raw_iter.peek().cloned().and_then(|r| r.parse().ok()) {
520            Some(MrtRecord {
521                message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(pit)),
522                ..
523            }) => {
524                raw_iter.next();
525                Elementor::with_peer_table(pit)
526            }
527            _ => Elementor::new(),
528        };
529        (elementor, raw_iter)
530    }
531
532    /// Creates an Elementor pre-initialized with PeerIndexTable and an iterator over parsed records.
533    ///
534    /// This is useful for parallel processing where the Elementor needs to be shared across threads.
535    /// The Elementor is created with the PeerIndexTable from the first record if present,
536    /// otherwise a new Elementor is created.
537    ///
538    /// # Example
539    /// See the `parallel_records_to_elem` example for full usage.
540    pub fn into_elementor_and_record_iter(self) -> (Elementor, impl Iterator<Item = MrtRecord>)
541    where
542        R: Read,
543    {
544        let mut record_iter = RecordIterator::new(self).peekable();
545        let elementor = match record_iter.peek().cloned() {
546            Some(MrtRecord {
547                message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(pit)),
548                ..
549            }) => {
550                record_iter.next();
551                Elementor::with_peer_table(pit)
552            }
553            _ => Elementor::new(),
554        };
555        (elementor, record_iter)
556    }
557}