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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,27 @@ All notable changes to this project will be documented in this file.

### Breaking changes

* **`ElemType` gains `RESET` and is `#[non_exhaustive]`**: RFC 7606 error handling (see Added) marks announcements of an UPDATE whose errors call for a session reset or AFI/SAFI disable with the new variant, rendered `R` in text and PSV output. Matches on `ElemType` now need a wildcard arm. Without RFC 7606 error handling enabled, no `RESET` elems are produced.
* **`BgpElem` gains an `error_handling` field**: the RFC 7606 approach applied to the elem's UPDATE, `None` unless RFC 7606 error handling is enabled and the UPDATE had findings. Struct literals need `error_handling: None` (or `..Default::default()`); JSON output omits the field when it is `None`, and PSV output is unchanged. `Elementor` also gains a private field, so build it with `Elementor::new()` or `Elementor::with_peer_table` instead of a struct literal.
* **More specific RFC 7606 findings**: a malformed ORIGIN, AS_PATH or NEXT_HOP is reported as `InvalidOriginAttribute`, `MalformedAsPath` or `InvalidNextHopAttribute` instead of `MalformedAttributeList`, and a malformed LOCAL_PREF as `OptionalAttributeError`. A malformed MP_REACH_NLRI or MP_UNREACH_NLRI is reported as `MalformedNlri { nlri_type: "mp_reach" | "mp_unreach", .. }` with the attribute bytes, instead of `OptionalAttributeError`. `MalformedAttributeList` now means an attribute-list framing error.
* **`ParserBmpError` carries the failing value and is `#[non_exhaustive]`**: `From<io::Error>` and the unknown-message-type conversion collapsed every failure into `InvalidOpenBmpHeader` and dropped the cause; they now return the new `IoError { kind, message }` and `UnknownMessageType(u8)` variants. Downstream matches on the enum now need a wildcard arm: `#[non_exhaustive]` means the two new variants cannot be covered by adding arms alone.

### Added

* **RFC 7606 error handling (treat-as-withdraw)** ([RFC 7606](https://datatracker.ietf.org/doc/html/rfc7606)): the parser now says what a router does with each malformed UPDATE, not just that it is malformed.
* `models::malformed_attribute_approach` maps every path attribute to the approach its RFC prescribes when it is malformed — attribute discard, treat-as-withdraw, AFI/SAFI disable, or session reset — covering RFC 7606 §7 and the later attribute RFCs (AS4_PATH, PMSI_TUNNEL, Tunnel Encapsulation, AIGP, BGP-LS, Large Communities, BGPsec_PATH, OTC, D-PATH, SFP, BFD Discriminator, Prefix-SID, BIER). The table is also documented in `src/parser/bgp/attributes/README.md`.
* `BgpValidationWarning::error_handling_approach` classifies one finding; `Attributes::error_handling_approach`, `BgpUpdateMessage::error_handling_approach` and `BgpUpdateMessage::is_treat_as_withdraw` combine an UPDATE's findings with the "strongest action wins" rule (§3(h)) and the missing-NLRI escalation (§5.2).
* MRT data does not record the session type and route collectors peer over eBGP, so the classification assumes eBGP: a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST is attribute discard rather than treat-as-withdraw.
* Opt-in elem conversion: `BgpkitParser::enable_rfc7606_error_handling()` / `with_error_handling(ErrorHandlingMode)`, `Elementor::with_error_handling`, and the CLI flag `--rfc7606`. Announcements of a treat-as-withdraw UPDATE become `WITHDRAW` elems, those of a session-reset or AFI/SAFI-disable UPDATE become `RESET` elems, and attributes subject to attribute discard (plus repeats of an attribute after its first occurrence) are left out. Elem and filtered record iteration apply it; RIB entries are unchanged. The route iterator stays a selective parser: it checks every attribute header like the elem iterator, but parses only the values of ORIGIN, AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI, so it may keep routes the elem iterator withdraws, never the reverse.
* **New RFC 7606 findings**: an attribute running past the attribute list, or trailing bytes too short for an attribute header (§4), previously skipped silently, now record `MalformedAttributeList`. Length checks now cover the "non-zero multiple of N" rules (COMMUNITIES, CLUSTER_LIST, extended, IPv6-specific and large communities), AGGREGATOR (6 or 8), AS4_AGGREGATOR (8), and the MP_REACH_NLRI/MP_UNREACH_NLRI minimums. An unrecognized attribute without the optional bit records `UnrecognizedWellKnownAttribute`, AS path segments without ASNs record `MalformedAsPath`, and AS 0 in AS_PATH, AS4_PATH, AGGREGATOR or AS4_AGGREGATOR is reported per [RFC 7607](https://datatracker.ietf.org/doc/html/rfc7607). The typed values are kept, so default elem output does not change.
* **BGP Domain Path (D-PATH) attribute support** ([RFC 10039](https://datatracker.ietf.org/doc/html/rfc10039)): path attribute type 36 now parses into `AttributeValue::DomainPath(DomainPathAttribute)` — segments of `DomainPathDomain { global_admin, local_admin, isf_safi_type }` — and re-encodes byte-identically instead of falling into the `Unknown` raw catch-all. Malformed values, and a D-PATH on a family other than IPVPN or EVPN, become RFC 7606 validation findings with the bytes retained raw, and the encoder refuses values it cannot represent. Text rendering and byte-level dissection label the attribute `BGP_DOMAIN_PATH`.
* **`--color auto|always|never` for `--format text`**: colors session keys, section headers, prefixes, and next-hop values with ANSI accents that follow the terminal theme. `auto` (the default) colors only when stdout is a terminal; `NO_COLOR` disables coloring and `CLICOLOR_FORCE` forces it. Library callers opt in with `render::text::Style::ansi()` plus the new `format_record_with_style` / `format_record_with_hex_and_style`; `format_record` and the unstyled output are unchanged, since styling is a post-pass over the rendered block.
* **`parse_ris_live_message_iter`**: parses one RIS Live JSON message into an iterator over its elems instead of a `Vec`. Every elem carries its own copy of the message's AS path and communities, so collecting a message that announces many prefixes needs memory proportional to prefixes × path length; the iterator makes those copies one elem at a time. `parse_ris_live_message` is unchanged and now builds on it.

### Changed

* **Repeated attributes report only `DuplicateAttribute`**: RFC 7606 §3(g) discards every repeat of an attribute, so flag, length and value errors in a repeat are no longer reported, and no longer withdraw the routes or discard the valid first copy.
* **`examples/treat_as_withdrawal.rs` uses the library classification**: the example's own Junos-style classifier is replaced by `error_handling_approach()` and `enable_rfc7606_error_handling()`.
* **Internal cleanups, no behavior change**: the MP next-hop encoder (`encode_mp_next_hop`) is shared by the `NEXT_HOP` and MP_REACH encoders instead of being duplicated, `AsPathSegment` hashing skips the sort when a set is already ordered, `Elementor::record_to_elems` logs peer-table conversion errors as its documentation promises, the invariant `unreachable!()` arms state their invariant, and both the crate-wide `uninlined_format_args` allow and a module-wide `#![allow(unused)]` are removed.
* **`--format text` session labels are now `PEER`/`LOCAL`**: the endpoint lines read `PEER: <peer_ip> AS<peer_asn>` and `LOCAL: <local_ip> AS<local_asn>`, matching the peer/local names MRT ([RFC 6396](https://www.rfc-editor.org/rfc/rfc6396.html)) uses for the same fields instead of the ambiguous `FROM`/`TO`. The rendered values are unchanged.
* **Record parse errors are logged once per parser**: the default, raw, update and route iterators log the first `ParseError` of a parser at `error` level and later ones at `debug` level. A corrupted stream re-synchronises header by header, which previously emitted one `error` line per 12 bytes of damaged input. Other error classes are logged as before.
Expand Down
48 changes: 47 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,51 @@ match process_mrt_file("http://example.com/updates.bz2") {
}
```

**RFC 7606 Error Handling (Treat-as-Withdraw)**

Malformed path attributes never stop parsing: each finding is recorded as a
`BgpValidationWarning` on the UPDATE, and the attribute bytes are kept. RFC 7606 and the RFCs
defining later attributes say what a router does with each finding: discard the attribute, treat
the UPDATE's routes as withdrawn, disable the AFI/SAFI, or reset the session.
`BgpUpdateMessage::error_handling_approach` returns that approach for an UPDATE, combining its
findings with the "strongest action wins" rule. The attribute-to-approach table is
`models::malformed_attribute_approach`.

MRT data does not say whether a session was iBGP or eBGP. Route collectors peer over eBGP, so the
classification assumes eBGP: a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST is attribute
discard, not treat-as-withdraw.

Element output is unchanged unless you opt in with `enable_rfc7606_error_handling()`. Then:

- announcements of an UPDATE that RFC 7606 treats as withdrawn become `ElemType::WITHDRAW`;
- announcements of an UPDATE whose errors call for a session reset or AFI/SAFI disable become
`ElemType::RESET`;
- attributes subject to attribute discard, and repeats of an attribute after its first
occurrence, are left out of the announcement;
- every element of such an UPDATE carries the approach in `BgpElem::error_handling`.

RIB dump entries are converted as before. The CLI flag is `--rfc7606`.

The route iterator (`into_route_iter`) stays a cheap, selective parser under this mode: it checks
every attribute header like the element iterators do, but parses only the values of ORIGIN,
AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI. It can miss a value error in another
attribute, so it may keep routes the element iterators withdraw, never the reverse.

```rust
use bgpkit_parser::BgpkitParser;
use bgpkit_parser::models::{ElemType, ErrorHandlingApproach};

let parser = BgpkitParser::new("https://data.ris.ripe.net/rrc00/latest-update.gz")
.unwrap()
.enable_rfc7606_error_handling();
for elem in parser {
if elem.error_handling == Some(ErrorHandlingApproach::TreatAsWithdraw) {
assert_eq!(elem.elem_type, ElemType::WITHDRAW);
println!("treated as withdrawn: {}", elem.prefix);
}
}
```

**Recovering After Damaged MRT Framing**

Recovery is opt-in and never reconstructs a damaged record. It reports the skipped decompressed
Expand Down Expand Up @@ -758,7 +803,7 @@ See the [BgpElem] documentation for the complete structure definition.

**Key fields**:
- `timestamp`: Unix timestamp of the BGP message
- `elem_type`: Announcement or withdrawal
- `elem_type`: Announcement, withdrawal, or (with RFC 7606 error handling) reset
- `peer_ip` / `peer_asn`: The BGP peer information
- `prefix`: The IP prefix being announced or withdrawn
- `as_path`: The AS path attribute (if present)
Expand Down Expand Up @@ -795,6 +840,7 @@ BGPKIT Parser implements comprehensive BGP, MRT, BMP, and related protocol stand
- [RFC 4271](https://datatracker.ietf.org/doc/html/rfc4271): A Border Gateway Protocol 4 (BGP-4) - Core protocol
- [RFC 2858](https://datatracker.ietf.org/doc/html/rfc2858): Multiprotocol Extensions for BGP-4 (IPv6 support)
- [RFC 6793](https://datatracker.ietf.org/doc/html/rfc6793): Four-Octet AS Number Space
- [RFC 7607](https://datatracker.ietf.org/doc/html/rfc7607): Codification of AS 0 Processing
- [RFC 7911](https://datatracker.ietf.org/doc/html/rfc7911): Advertisement of Multiple Paths (ADD-PATH)

**Additional BGP RFCs**:
Expand Down
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Construct and serialize BGP/MRT data, including the fallible encoders and the RF

- [dissect_mrt.rs](dissect_mrt.rs) — Wireshark-style byte-level dissection: render the `DissectionNode` field tree with byte-offset gutters for MRT/BGP records, including a truncated-input demo showing dissectors never fail.
- [diagnostic_iterator.rs](diagnostic_iterator.rs) — Classify clean records, RFC 7606 validation findings, and fatal parse failures while exporting each finding's raw MRT bytes.
- [treat_as_withdrawal.rs](treat_as_withdrawal.rs) — Scan MRT files for RFC 7606 validation issues (malformed NLRI, bad attributes) and classify them by error-handling category: attribute discard vs. treat-as-withdrawal.
- [treat_as_withdrawal.rs](treat_as_withdrawal.rs) — Report the RFC 7606 approach (attribute discard, treat-as-withdraw, AFI/SAFI disable, session reset) of each malformed UPDATE in an MRT file, then count the announcements `enable_rfc7606_error_handling()` withdraws.
- [fallible_parsing.rs](fallible_parsing.rs) — Demonstrate fallible record/element iterators that let you handle parse errors explicitly while continuing to process.
- [mrt_debug.rs](mrt_debug.rs) — Print parsed and raw MRT records for debugging, including raw-byte export and re-parsing.
- [extract_problematic_records.rs](extract_problematic_records.rs) — Find and export MRT records that fail to parse for further analysis with other tools.
Expand Down
Loading
Loading