Skip to main content

bgpkit_parser/parser/
mod.rs

1/*!
2parser module maintains the main logic for processing BGP and MRT messages.
3*/
4use crate::models::{BgpElem, MrtRecord};
5use log::{debug, error, warn};
6use std::io::{BufReader, Cursor, Read};
7pub use text_dump::{detect_text_dump, infer_timestamp_from_path, TextDumpElemIterator};
8
9#[macro_use]
10pub mod utils;
11pub(crate) mod attr_scan;
12pub mod bgp;
13pub mod bmp;
14pub mod filter;
15pub mod iters;
16pub mod mrt;
17pub mod rpki;
18pub mod text_dump;
19
20#[cfg(feature = "rislive")]
21pub mod rislive;
22
23pub(crate) use self::utils::*;
24
25pub use mrt::mrt_elem::{BgpUpdateElemIter, ElemError, Elementor, RecordElemIter};
26#[cfg(feature = "oneio")]
27use oneio::{get_cache_reader, get_reader, get_resumable_http_reader};
28
29pub use crate::error::{ParserError, ParserErrorWithBytes};
30pub use bmp::{parse_bmp_msg, parse_openbmp_header, parse_openbmp_msg};
31pub use filter::*;
32pub use iters::*;
33pub use mrt::*;
34
35#[cfg(feature = "rislive")]
36pub use rislive::messages::{
37    RisLiveClientMessage, RisLiveMeta, RisLiveRawFull, RisSubscribe, RisSubscribeSocketOptions,
38    RisSubscribeType,
39};
40#[cfg(feature = "rislive")]
41pub use rislive::{
42    parse_ris_live_message, parse_ris_live_message_iter, parse_ris_live_message_json,
43    parse_ris_live_message_raw, parse_ris_live_message_raw_full, RisLiveElemIter,
44};
45
46pub struct BgpkitParser<R> {
47    reader: R,
48    core_dump: bool,
49    filters: Vec<Filter>,
50    options: ParserOptions,
51    /// Streaming element iterator for text dumps. `None` for MRT input,
52    /// which is parsed lazily through [`Self::next_record`].
53    text_dump_iter: Option<Box<dyn Iterator<Item = BgpElem> + Send>>,
54    /// Reusable buffer/table state for [`Self::next_record_elems`].
55    elem_view_state: iters::elem_ref::ElemViewState,
56}
57
58pub(crate) struct ParserOptions {
59    show_warnings: bool,
60    warned_zebra_compat: bool,
61    logged_parse_error: bool,
62    warned_view_scope: bool,
63    warned_view_filters: bool,
64}
65impl Default for ParserOptions {
66    fn default() -> Self {
67        ParserOptions {
68            show_warnings: true,
69            warned_zebra_compat: false,
70            logged_parse_error: false,
71            warned_view_scope: false,
72            warned_view_filters: false,
73        }
74    }
75}
76
77impl ParserOptions {
78    /// Say once, per parser, that the borrowed element view met a record kind it does not serve.
79    pub(crate) fn warn_view_scope_once(&mut self, kind: &str) {
80        if self.show_warnings && !self.warned_view_scope {
81            warn!(
82                "next_record_elems cannot serve {kind}; skipping them (further occurrences for this parser will not be logged). Use into_elem_iter for every record kind."
83            );
84            self.warned_view_scope = true;
85        }
86    }
87
88    /// Say once, per parser, that the borrowed view refuses a parser that carries filters.
89    pub(crate) fn warn_view_filters_once(&mut self) {
90        if self.show_warnings && !self.warned_view_filters {
91            warn!(
92                "next_record_elems does not apply filters, so it returns no records for this parser; use into_elem_iter when filters are set (further calls will not be logged)."
93            );
94            self.warned_view_filters = true;
95        }
96    }
97
98    pub(crate) fn warn_zebra_compat_once(&mut self) {
99        if self.show_warnings && !self.warned_zebra_compat {
100            warn!(
101                "recovered shortened Zebra BGP4MP records with missing envelope fields; substituting IPv4 zero addresses and interface index 0 (further occurrences for this parser will not be logged)"
102            );
103            self.warned_zebra_compat = true;
104        }
105    }
106
107    /// Log a record-level parse error at `error` level the first time it happens for this
108    /// parser, and at `debug` level afterwards. A corrupted stream re-synchronises header by
109    /// header, which can otherwise produce one `error` line per 12 bytes of damaged input.
110    ///
111    /// `stops_iteration` is set when the iterator ends at this error (core dumps enabled), so
112    /// there are no further errors to announce.
113    fn log_parse_error_once(&mut self, error: &dyn std::fmt::Display, stops_iteration: bool) {
114        if self.logged_parse_error {
115            debug!("parser error: {}", error);
116        } else if stops_iteration {
117            error!("parser error: {}", error);
118            self.logged_parse_error = true;
119        } else {
120            error!(
121                "parser error: {} (further parse errors for this parser will be logged at debug level)",
122                error
123            );
124            self.logged_parse_error = true;
125        }
126    }
127}
128
129#[cfg(feature = "oneio")]
130impl BgpkitParser<Box<dyn Read + Send>> {
131    /// Creating a new parser from a object that implements [Read] trait.
132    pub fn new(path: &str) -> Result<Self, ParserErrorWithBytes> {
133        let reader = get_reader(path)?;
134        Ok(BgpkitParser {
135            reader,
136            core_dump: false,
137            filters: vec![],
138            options: ParserOptions::default(),
139            text_dump_iter: None,
140            elem_view_state: Default::default(),
141        })
142    }
143
144    /// Creates a parser backed by an experimental resumable HTTP(S) reader.
145    ///
146    /// If a remote server drops a connection while the parser is reading, the
147    /// reader reconnects with an HTTP Range request and continues at the last
148    /// byte read. Resumed responses are validated by `oneio`; servers that do
149    /// not support Range requests, or resources that change while being read,
150    /// return an error instead of combining inconsistent bytes.
151    ///
152    /// This constructor is opt-in. [`BgpkitParser::new`] retains its existing
153    /// reader behavior. Use a fallible iterator when the caller needs to
154    /// handle an unrecoverable read failure explicitly.
155    ///
156    /// # Example
157    ///
158    /// ```no_run
159    /// use bgpkit_parser::BgpkitParser;
160    ///
161    /// let url = "https://data.ris.ripe.net/rrc00/latest-update.gz";
162    /// let parser = BgpkitParser::new_resumable_http(url)?;
163    /// # Ok::<(), bgpkit_parser::ParserErrorWithBytes>(())
164    /// ```
165    pub fn new_resumable_http(path: &str) -> Result<Self, ParserErrorWithBytes> {
166        let reader = get_resumable_http_reader(path)?;
167        Ok(BgpkitParser {
168            reader,
169            core_dump: false,
170            filters: vec![],
171            options: ParserOptions::default(),
172            text_dump_iter: None,
173            elem_view_state: Default::default(),
174        })
175    }
176
177    /// Creating a new parser that also caches the remote content to a local cache directory.
178    ///
179    /// The cache file name is generated by the following format: `cache-<crc32 of file name>-<file name>`.
180    /// For example, the remote file `http://archive.routeviews.org/route-views.chile/bgpdata/2023.03/RIBS/rib.20230326.0600.bz2`
181    /// will be cached as `cache-682cb1eb-rib.20230326.0600.bz2` in the cache directory.
182    pub fn new_cached(path: &str, cache_dir: &str) -> Result<Self, ParserErrorWithBytes> {
183        let file_name = path.rsplit('/').next().unwrap().to_string();
184        let new_file_name = format!(
185            "cache-{}",
186            add_suffix_to_filename(file_name.as_str(), crc32(path).as_str())
187        );
188        let reader = get_cache_reader(path, cache_dir, Some(new_file_name), false)?;
189        Ok(BgpkitParser {
190            reader,
191            core_dump: false,
192            filters: vec![],
193            options: ParserOptions::default(),
194            text_dump_iter: None,
195            elem_view_state: Default::default(),
196        })
197    }
198
199    /// Create a parser for a Cisco `sh ip bgp` text dump (PCH daily snapshots
200    /// or route-views `oix-full-snapshot-*` files).
201    ///
202    /// The file is auto-decompressed by oneio. The timestamp for all elements
203    /// is inferred from the file name when possible. To override the timestamp,
204    /// use [`from_text_reader_with_timestamp`](Self::from_text_reader_with_timestamp)
205    /// directly. The resulting parser streams [`BgpElem`]s lazily — one route
206    /// line at a time, constant memory. Calling [`into_record_iter`](Self::into_record_iter)
207    /// or [`next_record`](Self::next_record) on a text-dump parser returns no
208    /// records (text dumps have no MRT-record representation); use
209    /// [`into_elem_iter`](Self::into_elem_iter) or the `for elem in parser` loop instead.
210    ///
211    /// # Example
212    ///
213    /// ```no_run
214    /// use bgpkit_parser::BgpkitParser;
215    ///
216    /// let url = "https://downloads.pch.net/files/Routing_Data/IPv4_daily_snapshots/2026/07/route-collector.bom2.pch.net/route-collector.bom2.pch.net-ipv4_bgp_routes.2026.07.01.gz";
217    /// for elem in BgpkitParser::new_text(url).unwrap() {
218    ///     println!("{elem}");
219    /// }
220    /// ```
221    pub fn new_text(path: &str) -> Result<Self, ParserErrorWithBytes> {
222        let timestamp = infer_timestamp_from_path(path).unwrap_or(0.0);
223        let reader = get_reader(path)?;
224        Self::from_text_reader_with_timestamp(reader, timestamp)
225    }
226
227    /// Create a parser that auto-detects whether the input is an MRT file or a
228    /// Cisco `sh ip bgp` text dump, parsing accordingly.
229    ///
230    /// Peeks the first 256 bytes: if they look like a Cisco text dump the file
231    /// is parsed as one (timestamp inferred from the path); otherwise it is
232    /// treated as MRT and parsed lazily as usual. This is the most convenient
233    /// constructor when the input type is unknown.
234    ///
235    /// # Example
236    ///
237    /// ```no_run
238    /// use bgpkit_parser::BgpkitParser;
239    ///
240    /// // works for either MRT or text dumps
241    /// for elem in BgpkitParser::new_auto("https://downloads.pch.net/files/Routing_Data/IPv4_daily_snapshots/2026/07/route-collector.bom2.pch.net/route-collector.bom2.pch.net-ipv4_bgp_routes.2026.07.01.gz").unwrap() {
242    ///     println!("{elem}");
243    /// }
244    /// ```
245    pub fn new_auto(path: &str) -> Result<Self, ParserErrorWithBytes> {
246        let reader = get_reader(path)?;
247        Self::from_auto_reader_with_timestamp(reader, infer_timestamp_from_path(path))
248    }
249}
250
251#[cfg(feature = "oneio")]
252fn add_suffix_to_filename(filename: &str, suffix: &str) -> String {
253    let mut parts: Vec<&str> = filename.split('.').collect(); // Split filename by dots
254    if parts.len() > 1 {
255        let last_part = parts.pop().unwrap(); // Remove the last part (suffix) from the parts vector
256        let new_last_part = format!("{suffix}.{last_part}"); // Add the suffix to the last part
257        parts.push(&new_last_part); // Add the updated last part back to the parts vector
258        parts.join(".") // Join the parts back into a filename string with dots
259    } else {
260        // If the filename does not have any dots, simply append the suffix to the end
261        format!("{filename}.{suffix}")
262    }
263}
264
265impl<R: Read> BgpkitParser<R> {
266    /// Creating a new parser from an object that implements [Read] trait.
267    pub fn from_reader(reader: R) -> Self {
268        BgpkitParser {
269            reader,
270            core_dump: false,
271            filters: vec![],
272            options: ParserOptions::default(),
273            text_dump_iter: None,
274            elem_view_state: Default::default(),
275        }
276    }
277
278    /// This is used in for loop `for item in parser{}`
279    pub fn next_record(&mut self) -> Result<MrtRecord, ParserErrorWithBytes> {
280        if self.text_dump_iter.is_some() {
281            return Err(ParserError::Unsupported(
282                "text-dump parsers have no MRT record representation; iterate elements instead"
283                    .to_string(),
284            )
285            .into());
286        }
287        let (record, used_zebra_compat) =
288            mrt::mrt_record::parse_mrt_record_with_zebra_compat(&mut self.reader)?;
289        if used_zebra_compat {
290            self.warn_zebra_compat_once();
291        }
292        Ok(record)
293    }
294
295    /// Advance to the next record, skipping records that provably yield no element `filters` keeps.
296    ///
297    /// A record is skipped when the filter is decidable from bytes already read: the prefix and
298    /// address family of a `TABLE_DUMP_V2` RIB record, the peer, timestamp and address family of a
299    /// `BGP4MP` record, and the attribute block of either. Skipping such a record returns the same
300    /// elements as parsing it and then filtering.
301    ///
302    /// A record whose match cannot be decided this way is parsed normally, including a malformed
303    /// one: a framing or parse error is reported exactly as [`Self::next_record`] reports it.
304    fn next_record_prefiltered(&mut self) -> Result<MrtRecord, ParserErrorWithBytes> {
305        loop {
306            let (header, raw_header, body_len) = match iters::elem_ref::frame_next(self) {
307                Ok(framed) => framed,
308                Err(failure) => {
309                    return Err(ParserErrorWithBytes {
310                        error: failure.error,
311                        bytes: failure.bytes,
312                    })
313                }
314            };
315            // Record-level predicates: a dump record covers one prefix; an update names one peer
316            // and one time in its header. A record whose predicate is not decidable here falls
317            // through to the general parser unchanged.
318            if iters::elem_ref::record_excluded_by_filters(self, &header, body_len) {
319                continue;
320            }
321            return self.parse_framed_record(header, raw_header.as_slice(), body_len);
322        }
323    }
324
325    /// Advance to the next record, serving RIB records from the borrowed element engine.
326    ///
327    /// `Other` means the record is not a RIB dump record; its bytes are still in the record buffer,
328    /// and [`Self::parse_framed_record`] turns them into an owned record.
329    pub(crate) fn next_elem_batch(&mut self) -> iters::elem_ref::NextBatch<'_>
330    where
331        R: std::io::Read,
332    {
333        iters::elem_ref::next_batch(self)
334    }
335
336    /// Parse the record the last [`Self::next_elem_batch`] call left in the record buffer.
337    pub(crate) fn parse_framed_record(
338        &mut self,
339        header: crate::models::CommonHeader,
340        raw_header: &[u8],
341        body_len: usize,
342    ) -> Result<MrtRecord, ParserErrorWithBytes> {
343        let body = bytes::Bytes::copy_from_slice(&self.elem_view_state.body_buf[..body_len]);
344        let used_zebra_compat =
345            matches!(
346                header.entry_type,
347                crate::models::EntryType::BGP4MP | crate::models::EntryType::BGP4MP_ET
348            ) && mrt::messages::bgp4mp::uses_zebra_compat(header.entry_subtype, &body);
349        match mrt::mrt_record::parse_mrt_body(header.entry_type as u16, header.entry_subtype, body)
350        {
351            Ok(message) => {
352                // A record that parses is the only one worth warning about: a malformed one is
353                // reported as a parse error, and a warning about how it was written would be noise.
354                if used_zebra_compat {
355                    self.warn_zebra_compat_once();
356                }
357                Ok(MrtRecord {
358                    common_header: header,
359                    message,
360                })
361            }
362            // A core dump must replay as MRT, so the header travels with the body.
363            Err(error) => Err(ParserErrorWithBytes {
364                error,
365                bytes: Some(mrt::frame::assemble_error_bytes(
366                    raw_header,
367                    &self.elem_view_state.body_buf[..body_len],
368                )),
369            }),
370        }
371    }
372
373    /// Advance to the next record this path serves and return a borrowed view over its elements.
374    ///
375    /// A dump's `RIB_AFI` entry is read straight from the record body. An update's element shares
376    /// its record's attribute block, and the next hop is decoded once for the whole record.
377    ///
378    /// The returned [`RecordElems`] borrows this parser (its reusable record buffer and active
379    /// `PeerIndexTable`); drop `RecordElems` before calling `next_record_elems` again.
380    ///
381    /// # Scope
382    ///
383    /// Serves `TABLE_DUMP_V2` `RIB_AFI` records (`PeerIndexTable` records update the active peer
384    /// table internally) and `BGP4MP_AS4` message records, for both dumps and updates. A record this
385    /// path does not serve at all is skipped silently. An update that yields no element — an
386    /// end-of-RIB marker, or a message whose only content is another address family — is returned as
387    /// an empty [`RecordElems`] rather than skipped, so a caller can tell "this record carries
388    /// nothing" from "the file ended"; [`RecordElems::is_empty`] is the test, and `continue` is the
389    /// usual response. A record that would produce elements but is not served here, today a `BGP4MP`
390    /// record with 2-byte AS numbers, is skipped and logs one warning naming that reason, so a
391    /// caller cannot mistake "this path does not cover this file" for "this file has no
392    /// elements"; use [`into_elem_iter`](Self::into_elem_iter) for every record kind. Text-dump
393    /// parsers return `None` immediately.
394    ///
395    /// A parser with filters returns `None` on the first call, reads nothing, and logs one warning:
396    /// this path does not apply them, and silently returning unfiltered elements to a caller that
397    /// asked for a filter is worse than refusing. Use [`into_elem_iter`](Self::into_elem_iter) when
398    /// the parser carries filters.
399    pub fn next_record_elems(&mut self) -> Option<RecordElems<'_>> {
400        iters::elem_ref::next_record_elems_impl(self)
401    }
402
403    /// Count this parser's elements without materialising them.
404    ///
405    /// The same elements `into_elem_iter().count()` yields, produced by walking the borrowed batches
406    /// entry by entry and, for a record the borrowed view does not serve, by counting the elements
407    /// the owned path builds for it. No attribute is decoded for a record the view serves, so this
408    /// costs a fraction of a full iteration.
409    ///
410    /// `None` when this path cannot answer: a text-dump parser, or one carrying filters, which the
411    /// borrowed view refuses rather than return unfiltered elements. Use [`Self::into_elem_iter`]
412    /// for those.
413    pub fn count_elems(&mut self) -> Option<usize> {
414        if !self.filters.is_empty() {
415            return None;
416        }
417        iters::elem_ref::count_elems(self)
418    }
419}
420
421impl BgpkitParser<Box<dyn Read + Send>> {
422    /// Create a text-dump parser from any reader, with timestamp `0.0`.
423    /// Prefer [`BgpkitParser::new_text`] when you have a file path or URL,
424    /// as it will infer the timestamp automatically.
425    pub fn from_text_reader(
426        reader: impl Read + Send + 'static,
427    ) -> Result<Self, ParserErrorWithBytes> {
428        Self::from_text_reader_with_timestamp(reader, 0.0)
429    }
430
431    /// Create a text-dump parser from a reader with an explicit element
432    /// timestamp. The parser streams elements lazily — one route line at a
433    /// time, constant memory. It has no MRT-record representation.
434    pub fn from_text_reader_with_timestamp(
435        reader: impl Read + Send + 'static,
436        timestamp: f64,
437    ) -> Result<Self, ParserErrorWithBytes> {
438        let buf_reader = BufReader::new(reader);
439        let iter = TextDumpElemIterator::new(buf_reader, timestamp).map_err(ParserError::from)?;
440        Ok(BgpkitParser {
441            reader: Box::new(std::io::empty()),
442            core_dump: false,
443            filters: vec![],
444            options: ParserOptions::default(),
445            text_dump_iter: Some(Box::new(iter)),
446            elem_view_state: Default::default(),
447        })
448    }
449
450    /// Create a parser from any reader, auto-detecting MRT vs text dump by
451    /// sniffing the first bytes. Timestamp defaults to `0.0` for text dumps.
452    pub fn from_auto_reader(
453        reader: impl Read + Send + 'static,
454    ) -> Result<Self, ParserErrorWithBytes> {
455        Self::from_auto_reader_with_timestamp(reader, None)
456    }
457
458    /// Create a parser from any reader, auto-detecting MRT vs text dump.
459    /// `timestamp` sets the element timestamp for text dumps (`None` → `0.0`);
460    /// for filename-based inference, use [`new_auto`](Self::new_auto) instead.
461    pub fn from_auto_reader_with_timestamp(
462        reader: impl Read + Send + 'static,
463        timestamp: Option<f64>,
464    ) -> Result<Self, ParserErrorWithBytes> {
465        let mut buf_reader = BufReader::new(reader);
466        let (is_text, head) = detect_text_dump(&mut buf_reader).map_err(ParserError::from)?;
467        if is_text {
468            let chained = BufReader::new(Cursor::new(head).chain(buf_reader));
469            let ts = timestamp.unwrap_or(0.0);
470            let iter = TextDumpElemIterator::new(chained, ts).map_err(ParserError::from)?;
471            Ok(BgpkitParser {
472                reader: Box::new(std::io::empty()),
473                core_dump: false,
474                filters: vec![],
475                options: ParserOptions::default(),
476                text_dump_iter: Some(Box::new(iter)),
477                elem_view_state: Default::default(),
478            })
479        } else {
480            Ok(BgpkitParser {
481                reader: Box::new(Cursor::new(head).chain(buf_reader)),
482                core_dump: false,
483                filters: vec![],
484                options: ParserOptions::default(),
485                text_dump_iter: None,
486                elem_view_state: Default::default(),
487            })
488        }
489    }
490}
491
492impl<R> BgpkitParser<R> {
493    pub(crate) fn warn_zebra_compat_once(&mut self) {
494        self.options.warn_zebra_compat_once();
495    }
496
497    /// See [`ParserOptions::log_parse_error_once`]; iterators stop at the first parse error
498    /// when core dumps are enabled.
499    pub(crate) fn log_parse_error_once(&mut self, error: &dyn std::fmt::Display) {
500        self.options.log_parse_error_once(error, self.core_dump);
501    }
502
503    pub fn enable_core_dump(self) -> Self {
504        BgpkitParser {
505            reader: self.reader,
506            core_dump: true,
507            filters: self.filters,
508            options: self.options,
509            text_dump_iter: self.text_dump_iter,
510            elem_view_state: self.elem_view_state,
511        }
512    }
513
514    pub fn disable_warnings(self) -> Self {
515        let mut options = self.options;
516        options.show_warnings = false;
517        BgpkitParser {
518            reader: self.reader,
519            core_dump: self.core_dump,
520            filters: self.filters,
521            options,
522            text_dump_iter: self.text_dump_iter,
523            elem_view_state: self.elem_view_state,
524        }
525    }
526
527    /// Add a filter to the parser by specifying filter type and value as strings.
528    ///
529    /// This method parses the filter type and value strings to create a [`Filter`] and adds it
530    /// to the parser's filter list. For the full list of available filter types and their
531    /// formats, see the [`Filter`] struct documentation.
532    ///
533    /// # Available Filter Types
534    ///
535    /// - `origin_asn` - Origin AS number (e.g., "12345")
536    /// - `origin_asns` - Multiple origin AS numbers, comma-separated (e.g., "12345,67890")
537    /// - `prefix` - Exact prefix match (e.g., "192.168.1.0/24")
538    /// - `prefix_super` - Match prefix and super-prefixes
539    /// - `prefix_sub` - Match prefix and sub-prefixes
540    /// - `prefix_super_sub` - Match prefix, super-prefixes, and sub-prefixes
541    /// - `prefixes` - Multiple prefixes (e.g., "1.1.1.0/24,8.8.8.0/24")
542    /// - `peer_ip` - Peer IP address (e.g., "192.168.1.1")
543    /// - `peer_ips` - Multiple peer IPs (e.g., "192.168.1.1,192.168.1.2")
544    /// - `peer_asn` - Peer AS number (e.g., "12345")
545    /// - `peer_asns` - Multiple peer AS numbers (e.g., "12345,67890")
546    /// - `type` - Message type: "a"/"announce" or "w"/"withdraw"
547    /// - `ts_start` - Start timestamp (unix timestamp or RFC3339)
548    /// - `ts_end` - End timestamp (unix timestamp or RFC3339)
549    /// - `as_path` - AS path regex pattern
550    /// - `community` - Community regex pattern
551    /// - `ip_version` - IP version: "4"/"ipv4" or "6"/"ipv6"
552    /// - `otc` - Only-to-customer ASN (RFC 9234); `*` for present, `!*` for absent
553    /// - `next_hop` - Next hop IP address; `*`/`!*` for presence
554    /// - `origin` - Origin attribute: "igp", "egp", or "incomplete"; `*`/`!*` for presence
555    /// - `local_pref` - Local preference value; `*`/`!*` for presence
556    /// - `med` - Multi-exit discriminator value; `*`/`!*` for presence
557    /// - `atomic` - Atomic aggregate flag: "true"/"false"
558    /// - `aggr_asn` - Aggregator ASN; `*`/`!*` for presence
559    /// - `aggr_ip` - Aggregator IP address; `*`/`!*` for presence
560    /// - `peer_bgp_id` - Peer BGP identifier (router ID); `*`/`!*` for presence
561    ///
562    /// # Negative Filters
563    ///
564    /// Most filters support negation by prefixing the value with `!`. For example:
565    /// - `origin_asn=!13335` matches elements where origin AS is NOT 13335
566    /// - `prefix=!10.0.0.0/8` matches elements where prefix is NOT 10.0.0.0/8
567    ///
568    /// # Presence Filters
569    ///
570    /// Optional fields (`Option<T>`) support `*` as a wildcard to check whether a field
571    /// is present or absent: `otc=*` matches elements with an OTC value, `otc=!*` matches
572    /// elements without one.
573    ///
574    /// # Example
575    ///
576    /// ```no_run
577    /// use bgpkit_parser::BgpkitParser;
578    ///
579    /// let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
580    ///     .unwrap()
581    ///     .add_filter("peer_ip", "185.1.8.65")
582    ///     .unwrap()
583    ///     .add_filter("type", "w")
584    ///     .unwrap();
585    ///
586    /// for elem in parser {
587    ///     println!("{}", elem);
588    /// }
589    /// ```
590    pub fn add_filter(
591        self,
592        filter_type: &str,
593        filter_value: &str,
594    ) -> Result<Self, ParserErrorWithBytes> {
595        let mut filters = self.filters;
596        filters.push(Filter::new(filter_type, filter_value)?);
597        Ok(BgpkitParser {
598            reader: self.reader,
599            core_dump: self.core_dump,
600            filters,
601            options: self.options,
602            text_dump_iter: self.text_dump_iter,
603            elem_view_state: self.elem_view_state,
604        })
605    }
606
607    /// Add multiple filters to the parser.
608    ///
609    /// This method extends the existing filters with the provided slice of filters.
610    ///
611    /// # Example
612    ///
613    /// ```no_run
614    /// use bgpkit_parser::BgpkitParser;
615    /// use bgpkit_parser::parser::Filter;
616    ///
617    /// let filters = vec![
618    ///     Filter::new("peer_ip", "185.1.8.65").unwrap(),
619    ///     Filter::new("type", "w").unwrap(),
620    /// ];
621    ///
622    /// let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
623    ///     .unwrap()
624    ///     .add_filters(&filters);
625    /// ```
626    pub fn add_filters(mut self, filters: &[Filter]) -> Self {
627        self.filters.extend(filters.iter().cloned());
628        self
629    }
630
631    /// Set filters directly, replacing any existing filters.
632    ///
633    /// This method allows passing a pre-built `Vec<Filter>` directly to the parser,
634    /// bypassing the need to parse filter strings. This is useful when you want to
635    /// build filter specifications independently and reuse them across multiple parsers.
636    ///
637    /// # Example
638    ///
639    /// ```no_run
640    /// use bgpkit_parser::BgpkitParser;
641    /// use bgpkit_parser::parser::Filter;
642    ///
643    /// // Build filters independently
644    /// let filters = vec![
645    ///     Filter::new("peer_ip", "185.1.8.65").unwrap(),
646    ///     Filter::new("type", "w").unwrap(),
647    /// ];
648    ///
649    /// // Apply to multiple parsers (no manual clone needed)
650    /// let parser1 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
651    ///     .unwrap()
652    ///     .with_filters(&filters);
653    ///
654    /// let parser2 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
655    ///     .unwrap()
656    ///     .with_filters(&filters);
657    /// ```
658    pub fn with_filters(mut self, filters: &[Filter]) -> Self {
659        self.filters = filters.to_vec();
660        self
661    }
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use crate::models::Asn;
668
669    // Downloads a file from archive.routeviews.org, so it fails wherever that host is unreachable or
670    // slow, which has nothing to do with this crate. Run it deliberately with `--ignored`.
671    #[test]
672    #[ignore = "downloads from archive.routeviews.org"]
673    fn test_new_with_reader() {
674        // bzip2 reader for a compressed file
675        let reader = oneio::get_reader("http://archive.routeviews.org/route-views.ny/bgpdata/2023.02/UPDATES/updates.20230215.0630.bz2").unwrap();
676        assert_eq!(
677            12683,
678            BgpkitParser::from_reader(reader).into_elem_iter().count()
679        );
680
681        // remote reader for an uncompressed updates file
682        let reader = oneio::get_reader("https://spaces.bgpkit.org/parser/update-example").unwrap();
683        assert_eq!(
684            8160,
685            BgpkitParser::from_reader(reader).into_elem_iter().count()
686        );
687    }
688
689    #[test]
690    fn test_new_resumable_http() {
691        let parser =
692            BgpkitParser::new_resumable_http("https://spaces.bgpkit.org/parser/update-example.gz")
693                .unwrap();
694        assert_eq!(8160, parser.into_elem_iter().count());
695    }
696
697    #[test]
698    fn test_new_cached_with_reader() {
699        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
700        let parser = BgpkitParser::new_cached(url, "/tmp/bgpkit-parser-tests")
701            .unwrap()
702            .enable_core_dump()
703            .disable_warnings();
704        let count = parser.into_elem_iter().count();
705        assert_eq!(8160, count);
706        let parser = BgpkitParser::new_cached(url, "/tmp/bgpkit-parser-tests").unwrap();
707        let count = parser.into_elem_iter().count();
708        assert_eq!(8160, count);
709    }
710
711    #[test]
712    fn test_add_suffix_to_filename() {
713        // Test with a filename that has dots
714        let filename = "example.txt";
715        let suffix = "suffix";
716        let result = add_suffix_to_filename(filename, suffix);
717        assert_eq!(result, "example.suffix.txt");
718
719        // Test with a filename that has multiple dots
720        let filename = "example.tar.gz";
721        let suffix = "suffix";
722        let result = add_suffix_to_filename(filename, suffix);
723        assert_eq!(result, "example.tar.suffix.gz");
724
725        // Test with a filename that has no dots
726        let filename = "example";
727        let suffix = "suffix";
728        let result = add_suffix_to_filename(filename, suffix);
729        assert_eq!(result, "example.suffix");
730
731        // Test with an empty filename
732        let filename = "";
733        let suffix = "suffix";
734        let result = add_suffix_to_filename(filename, suffix);
735        assert_eq!(result, ".suffix");
736
737        // Test with an empty suffix
738        let filename = "example.txt";
739        let suffix = "";
740        let result = add_suffix_to_filename(filename, suffix);
741        assert_eq!(result, "example..txt");
742    }
743
744    #[test]
745    fn test_with_filters() {
746        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
747
748        // Build filters independently
749        let filters = vec![
750            Filter::new("peer_ip", "185.1.8.65").unwrap(),
751            Filter::new("type", "w").unwrap(),
752        ];
753
754        // Test with_filters - sets filters directly
755        let parser = BgpkitParser::new(url).unwrap().with_filters(&filters);
756        let count = parser.into_elem_iter().count();
757
758        // peer 185.1.8.65 has 3393 total, 132 withdrawals
759        assert_eq!(count, 132);
760
761        // Test that with_filters replaces existing filters
762        let filters1 = vec![Filter::new("peer_ip", "185.1.8.65").unwrap()];
763        let filters2 = vec![Filter::new("peer_ip", "185.1.8.50").unwrap()];
764
765        let parser = BgpkitParser::new(url)
766            .unwrap()
767            .with_filters(&filters1)
768            .with_filters(&filters2); // Should replace filters1
769        let count = parser.into_elem_iter().count();
770
771        // peer 185.1.8.50 has 1563 elements
772        assert_eq!(count, 1563);
773    }
774
775    #[test]
776    fn test_add_filters() {
777        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
778
779        // Build filters independently
780        let filters = vec![
781            Filter::new("peer_ip", "185.1.8.65").unwrap(),
782            Filter::new("type", "w").unwrap(),
783        ];
784
785        // Test add_filters - extends existing filters
786        let parser = BgpkitParser::new(url).unwrap().add_filters(&filters);
787        let count = parser.into_elem_iter().count();
788
789        // peer 185.1.8.65 has 3393 total, 132 withdrawals
790        assert_eq!(count, 132);
791
792        // Test combining add_filter and add_filters
793        let parser = BgpkitParser::new(url)
794            .unwrap()
795            .add_filter("peer_ip", "185.1.8.65")
796            .unwrap()
797            .add_filters(&[Filter::new("type", "w").unwrap()]);
798        let count = parser.into_elem_iter().count();
799        assert_eq!(count, 132);
800    }
801
802    #[test]
803    fn test_with_filters_empty() {
804        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
805
806        // Test with empty filters - should return all elements
807        let parser = BgpkitParser::new(url).unwrap().with_filters(&[]);
808        let count = parser.into_elem_iter().count();
809
810        // Total elements in the file
811        assert_eq!(count, 8160);
812    }
813
814    #[test]
815    fn test_add_filters_empty() {
816        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
817
818        // Test adding empty filters - should not change behavior
819        let parser = BgpkitParser::new(url)
820            .unwrap()
821            .add_filter("peer_ip", "185.1.8.65")
822            .unwrap()
823            .add_filters(&[]);
824        let count = parser.into_elem_iter().count();
825
826        // peer 185.1.8.65 has 3393 elements
827        assert_eq!(count, 3393);
828    }
829
830    #[test]
831    fn test_with_filters_reuse() {
832        let url = "https://spaces.bgpkit.org/parser/update-example.gz";
833
834        // Build filters once
835        let filters = vec![
836            Filter::new("peer_ip", "185.1.8.65").unwrap(),
837            Filter::new("type", "w").unwrap(),
838        ];
839
840        // Apply to multiple parsers (simulating reuse pattern - no clone needed)
841        let parser1 = BgpkitParser::new(url).unwrap().with_filters(&filters);
842        let count1 = parser1.into_elem_iter().count();
843
844        let parser2 = BgpkitParser::new(url).unwrap().with_filters(&filters);
845        let count2 = parser2.into_elem_iter().count();
846
847        // Both should have same count: 132 withdrawals from peer 185.1.8.65
848        assert_eq!(count1, 132);
849        assert_eq!(count2, 132);
850    }
851
852    #[test]
853    fn test_from_text_reader_inline() {
854        let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
855Default local pref 100, local AS 65001\n\n\
856    Network          Next Hop            Metric LocPrf Weight Path\n\
857 *> 1.0.0.0/24       10.0.0.1                 0             0 13335 i\n";
858        let parser =
859            BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
860        let elems: Vec<_> = parser.into_elem_iter().collect();
861        assert_eq!(elems.len(), 1);
862        assert_eq!(elems[0].prefix.prefix.to_string(), "1.0.0.0/24");
863        assert_eq!(elems[0].peer_ip.to_string(), "1.2.3.4");
864        assert_eq!(u32::from(elems[0].peer_asn), 65001);
865        assert_eq!(elems[0].origin_asns, Some(vec![Asn::from(13335u32)]));
866    }
867
868    #[test]
869    fn test_from_auto_reader_detects_text() {
870        let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
871Default local pref 100, local AS 65001\n\n\
872    Network          Next Hop            Metric LocPrf Weight Path\n\
873 *> 1.0.0.0/24       10.0.0.1                 0             0 13335 i\n";
874        let parser = BgpkitParser::from_auto_reader(dump.as_bytes()).expect("auto-detect parse");
875        let elems: Vec<_> = parser.into_elem_iter().collect();
876        assert_eq!(elems.len(), 1);
877        assert_eq!(elems[0].origin_asns, Some(vec![Asn::from(13335u32)]));
878    }
879
880    #[test]
881    fn test_from_auto_reader_detects_mrt() {
882        // A few zero bytes — not a text dump, so auto-detect should fall
883        // through to the MRT path (which will then hit EOF cleanly).
884        let data: Vec<u8> = vec![0x00u8; 16];
885        let parser =
886            BgpkitParser::from_auto_reader(std::io::Cursor::new(data)).expect("auto-detect parse");
887        let count = parser.into_elem_iter().count();
888        assert_eq!(count, 0);
889    }
890
891    #[test]
892    fn test_text_dump_parser_with_filter() {
893        let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
894Default local pref 100, local AS 65001\n\n\
895    Network          Next Hop            Metric LocPrf Weight Path\n\
896 *> 1.0.0.0/24       10.0.0.1                 0             0 13335 i\n\
897 *> 8.8.8.0/24       10.0.0.2                 0             0 15169 i\n";
898        let parser = BgpkitParser::from_text_reader(dump.as_bytes())
899            .unwrap()
900            .add_filter("origin_asn", "13335")
901            .unwrap();
902        let elems: Vec<_> = parser.into_elem_iter().collect();
903        assert_eq!(elems.len(), 1);
904        assert_eq!(elems[0].prefix.prefix.to_string(), "1.0.0.0/24");
905    }
906
907    #[test]
908    fn test_text_dump_next_record_errors() {
909        let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
910Default local pref 100, local AS 65001\n\n\
911    Network          Next Hop            Metric LocPrf Weight Path\n\
912 *> 1.0.0.0/24       10.0.0.1                 0             0 13335 i\n";
913        let mut parser =
914            BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
915        assert!(parser.next_record().is_err());
916    }
917
918    #[test]
919    fn test_text_dump_record_iter_terminates() {
920        // Calling into_record_iter on a text-dump parser should yield 0
921        // records immediately, not spin forever on Unsupported errors.
922        let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
923Default local pref 100, local AS 65001\n\n\
924    Network          Next Hop            Metric LocPrf Weight Path\n\
925 *> 1.0.0.0/24       10.0.0.1                 0             0 13335 i\n";
926        let parser =
927            BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
928        assert_eq!(parser.into_record_iter().count(), 0);
929    }
930}