Skip to main content

bgpkit_parser/parser/iters/
default.rs

1/*!
2Default iterator implementations that skip errors and return successfully parsed items.
3*/
4use crate::models::*;
5use crate::parser::iters::{handle_record_parse_error, record_matches_filters};
6use crate::parser::mrt::mrt_elem::PendingElems;
7use crate::parser::BgpkitParser;
8use crate::{Elementor, Filterable};
9use std::io::Read;
10
11#[cfg(test)]
12mod tests;
13
14/*********
15MrtRecord Iterator
16**********/
17
18pub struct RecordIterator<R> {
19    pub parser: BgpkitParser<R>,
20    pub count: u64,
21    elementor: Elementor,
22    /// Whether the parser's filters are applied once per record.
23    ///
24    /// Elem iterators test every elem they build, so a record-level pass costs
25    /// a full elem conversion per record (plus a record clone) that is thrown
26    /// away. They construct this iterator with the pass disabled.
27    prefilter: bool,
28}
29
30impl<R> RecordIterator<R> {
31    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
32        RecordIterator {
33            parser,
34            count: 0,
35            elementor: Elementor::new(),
36            prefilter: true,
37        }
38    }
39
40    /// Skip the record-level filter pass for an iterator whose consumer filters
41    /// the elems it builds anyway.
42    pub(crate) fn without_prefilter(mut self) -> Self {
43        self.prefilter = false;
44        self
45    }
46}
47
48impl<R: Read> Iterator for RecordIterator<R> {
49    type Item = MrtRecord;
50
51    fn next(&mut self) -> Option<MrtRecord> {
52        // Text-dump parsers have no MRT-record representation; short-circuit
53        // instead of spinning forever on Unsupported errors from next_record().
54        if self.parser.text_dump_iter.is_some() {
55            return None;
56        }
57        self.count += 1;
58        // A record whose single RIB prefix cannot satisfy a prefix filter yields no matching
59        // elements, so it can be skipped before its body is parsed.
60        // A record skipped here never raises its parse error, and core-dump mode stops at the
61        // first one, so pushdown is off while dumping.
62        let record_pushdown = !self.parser.core_dump
63            && crate::parser::filter::has_record_level_constraint(&self.parser.filters);
64        loop {
65            let next_record = if record_pushdown {
66                self.parser.next_record_prefiltered()
67            } else {
68                self.parser.next_record()
69            };
70            return match next_record {
71                Ok(v) => {
72                    if !self.prefilter
73                        || record_matches_filters(&v, &self.parser.filters, &mut self.elementor)
74                    {
75                        Some(v)
76                    } else {
77                        continue;
78                    }
79                }
80                Err(e) => {
81                    if handle_record_parse_error(&mut self.parser, e.error, e.bytes) {
82                        continue;
83                    }
84                    None
85                }
86            };
87        }
88    }
89}
90
91/*********
92BgpElem Iterator
93**********/
94
95/// What one framed record produced for the element iterator.
96enum Refill {
97    /// `batch` now holds elements to drain.
98    Batch,
99    /// The record went to the owned path, which filled `pending`.
100    Owned,
101    /// End of input, or an error the parser cannot recover from.
102    End,
103}
104
105pub struct ElemIterator<R> {
106    pending: PendingElems,
107    /// Rejects an entry before its element is built, when a predicate can decide it from attributes.
108    screen: Option<std::sync::Arc<crate::parser::attr_scan::EntryScreen>>,
109    /// Elements materialised from one borrowed RIB record, drained before anything else.
110    batch: std::vec::IntoIter<BgpElem>,
111    /// Whether records are dispatched per frame. A core dump needs the owned iterator to read the
112    /// stream itself, because it has to hand back the bytes around a parse error.
113    framed: bool,
114    record_iter: RecordIterator<R>,
115    elementor: Elementor,
116    count: u64,
117}
118
119impl<R> ElemIterator<R> {
120    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
121        // The framed path reads records through the parser's own buffer; the element loop applies
122        // the screen and the filters to what it produces.
123        let framed = !parser.core_dump;
124        let screen =
125            crate::parser::attr_scan::EntryScreen::new(&parser.filters).map(std::sync::Arc::new);
126        ElemIterator {
127            screen,
128            record_iter: RecordIterator::new(parser).without_prefilter(),
129            count: 0,
130            pending: PendingElems::Empty,
131            batch: Vec::new().into_iter(),
132            framed,
133            elementor: Elementor::new(),
134        }
135    }
136}
137
138impl<R: Read> ElemIterator<R> {
139    /// Read one framed record and route it: RIB dump records are materialised from the borrowed
140    /// view, everything else is parsed by the owned path.
141    fn refill(&mut self) -> Refill {
142        use crate::parser::iters::elem_ref::NextBatch;
143
144        match self.record_iter.parser.next_elem_batch() {
145            NextBatch::Rib(record) => {
146                // The declared entry count is attacker-controlled; cap the reservation so a
147                // malformed record cannot ask for a large allocation per record.
148                let mut elems = Vec::with_capacity(record.len().min(1024));
149                let screen = self.screen.clone();
150                for elem in record.iter() {
151                    // An entry the screen can reject from its bytes never becomes an element.
152                    if let Some(screen) = screen.as_deref() {
153                        if !screen.admits_bytes(elem.attrs_bytes()) {
154                            continue;
155                        }
156                    }
157                    elems.push(elem.to_bgp_elem());
158                }
159                // The loop above is the last use of `record`, so its borrow of the parser's
160                // buffers has ended and the filters can be read here.
161                let filters = &self.record_iter.parser.filters;
162                if !filters.is_empty() {
163                    elems.retain(|elem| elem.match_filters(filters));
164                }
165                self.batch = elems.into_iter();
166                Refill::Batch
167            }
168            NextBatch::Other {
169                header,
170                raw_header,
171                body_len,
172            } => {
173                match self.record_iter.parser.parse_framed_record(
174                    header,
175                    raw_header.as_slice(),
176                    body_len,
177                ) {
178                    Ok(record) => {
179                        self.pending = self.elementor.ingest(record);
180                        Refill::Owned
181                    }
182                    Err(failure) => {
183                        if handle_record_parse_error(
184                            &mut self.record_iter.parser,
185                            failure.error,
186                            failure.bytes,
187                        ) {
188                            Refill::Owned
189                        } else {
190                            Refill::End
191                        }
192                    }
193                }
194            }
195            NextBatch::End => Refill::End,
196        }
197    }
198}
199
200impl<R: Read> Iterator for ElemIterator<R> {
201    type Item = BgpElem;
202
203    fn next(&mut self) -> Option<BgpElem> {
204        self.count += 1;
205
206        // Fast path: drain streaming text-dump elems directly, with filter support.
207        if let Some(iter) = &mut self.record_iter.parser.text_dump_iter {
208            for elem in iter.by_ref() {
209                if elem.match_filters(&self.record_iter.parser.filters) {
210                    return Some(elem);
211                }
212            }
213            return None;
214        }
215
216        loop {
217            // Anything already produced comes out first: materialised RIB elements, then the owned
218            // iterator's pending elements.
219            if let Some(elem) = self.batch.next() {
220                return Some(elem);
221            }
222            while let Some(elem) = self.pending.next_elem(self.elementor.peer_table.as_ref()) {
223                if elem.match_filters(&self.record_iter.parser.filters) {
224                    return Some(elem);
225                }
226            }
227
228            if self.framed {
229                match self.refill() {
230                    Refill::Batch | Refill::Owned => continue,
231                    Refill::End => return None,
232                }
233            }
234            let record = self.record_iter.next()?;
235            // This branch is core-dump mode: it builds every element and lets the filter decide.
236            self.pending = self.elementor.ingest(record);
237        }
238    }
239}