use crate::models::{Asn, Origin};
use crate::parser::mrt::frame::FLAG_ADD_PATH;
use crate::Filter;
use smallvec::SmallVec;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AttrPredicate {
Asn(u32),
Asns(Vec<u32>),
Value(Origin),
}
#[derive(Debug, Default)]
struct EntryFacts<'a> {
origin_at: Option<u8>,
path: Option<&'a [u8]>,
has_as4_path: bool,
truncated: bool,
}
fn read_u16(bytes: &[u8]) -> u16 {
u16::from_be_bytes([bytes[0], bytes[1]])
}
fn read_entry(attrs: &[u8]) -> EntryFacts<'_> {
let mut facts = EntryFacts::default();
let mut rest = attrs;
while !rest.is_empty() {
if rest.len() < 3 {
facts.truncated = true;
return facts;
}
let extended = rest[0] & 0x10 != 0;
let attr_type = rest[1];
let (header_len, body_len) = if extended {
if rest.len() < 4 {
facts.truncated = true;
return facts;
}
(4, read_u16(&rest[2..]) as usize)
} else {
(3, rest[2] as usize)
};
if rest.len() < header_len + body_len {
facts.truncated = true;
return facts;
}
let body = &rest[header_len..header_len + body_len];
match attr_type {
1 => {
if let Some(at) = body.first().filter(|at| **at <= 2) {
facts.origin_at = Some(*at);
}
}
2 => {
if path_validates(body) {
facts.path = Some(body);
}
}
17 => facts.has_as4_path = true,
_ => {}
}
rest = &rest[header_len + body_len..];
}
facts
}
fn path_validates(body: &[u8]) -> bool {
crate::parser::bgp::attributes::validate_as_path_slice(body, &crate::models::AsnLength::Bits32)
}
fn path_origin(mut body: &[u8]) -> Result<Option<Asn>, ()> {
let mut last: Option<(u8, &[u8])> = None;
while !body.is_empty() {
if body.len() < 2 {
return Err(());
}
let segment_type = body[0];
let count = body[1] as usize;
let len = count * 4;
if !(1..=4).contains(&segment_type) || body.len() < 2 + len {
return Err(());
}
last = Some((segment_type, &body[2..2 + len]));
body = &body[2 + len..];
}
let Some((segment_type, members)) = last else {
return Ok(None);
};
match segment_type {
2 => Ok(members
.as_chunks::<4>()
.0
.last()
.map(|chunk| u32::from_be_bytes(*chunk).into())),
1 => {
if members.len() == 4 {
Ok(Some(
u32::from_be_bytes([members[0], members[1], members[2], members[3]]).into(),
))
} else {
Err(())
}
}
3 | 4 => Ok(None),
_ => Err(()),
}
}
pub(crate) struct EntryScreen {
predicates: SmallVec<[AttrPredicate; 4]>,
}
impl EntryScreen {
pub(crate) fn new(filters: &[Filter]) -> Option<Self> {
let predicates: SmallVec<[AttrPredicate; 4]> =
filters.iter().filter_map(predicate_for).collect();
(!predicates.is_empty()).then_some(EntryScreen { predicates })
}
pub(crate) fn admits_bytes(&self, attrs: &[u8]) -> bool {
let facts = read_entry(attrs);
if facts.truncated {
return true;
}
self.predicates
.iter()
.all(|predicate| entry_satisfies(&facts, predicate) != Some(false))
}
}
pub(crate) fn predicate_for(filter: &Filter) -> Option<AttrPredicate> {
match filter {
Filter::OriginAsn(asn) => Some(AttrPredicate::Asn(*asn)),
Filter::OriginAsns(asns) => Some(AttrPredicate::Asns(asns.clone())),
Filter::Origin(origin) => Some(AttrPredicate::Value(*origin)),
_ => None,
}
}
fn entry_satisfies(facts: &EntryFacts<'_>, predicate: &AttrPredicate) -> Option<bool> {
if facts.truncated {
return None;
}
match predicate {
AttrPredicate::Asn(asn) => {
if facts.has_as4_path {
return None;
}
Some(path_origin(facts.path?).ok()? == Some((*asn).into()))
}
AttrPredicate::Asns(asns) => {
if facts.has_as4_path {
return None;
}
let origin = path_origin(facts.path?).ok()?;
Some(origin.is_some_and(|origin| asns.iter().any(|asn| Asn::from(*asn) == origin)))
}
AttrPredicate::Value(origin) => Some(facts.origin_at == Some(*origin as u8)),
}
}
fn bgp4mp_attributes(body: &[u8], subtype: u16) -> Option<&[u8]> {
match crate::parser::mrt::frame::bgp4mp_asn_len(subtype)? {
crate::models::AsnLength::Bits32 => {}
crate::models::AsnLength::Bits16 => return None,
}
let asn_len = 4;
let mut rest = body.get(asn_len * 2..)?;
if rest.len() < 4 {
return None;
}
let ip_len = match u16::from_be_bytes([rest[2], rest[3]]) {
1 => 4,
2 => 16,
_ => return None,
};
rest = rest.get(4 + ip_len * 2..)?;
if rest.len() < 19 || rest[18] != 2 {
return None;
}
rest = &rest[19..];
if rest.len() < 2 {
return None;
}
let withdrawn_len = read_u16(rest) as usize;
rest = rest.get(2 + withdrawn_len..)?;
if rest.len() < 2 {
return None;
}
let attr_len = read_u16(rest) as usize;
rest.get(2..2 + attr_len)
}
pub(crate) fn bgp4mp_record_excluded(filters: &[Filter], body: &[u8], subtype: u16) -> bool {
let predicates: SmallVec<[AttrPredicate; 4]> =
filters.iter().filter_map(predicate_for).collect();
if predicates.is_empty() {
return false;
}
if !matches!(
crate::parser::mrt::frame::bgp4mp_asn_len(subtype),
Some(crate::models::AsnLength::Bits32)
) {
return false;
}
let Some(attrs) = bgp4mp_attributes(body, subtype) else {
return false;
};
let facts = read_entry(attrs);
if facts.truncated {
return false;
}
predicates
.iter()
.any(|predicate| entry_satisfies(&facts, predicate) == Some(false))
}
pub(crate) fn rib_record_excluded(
filters: &[Filter],
body: &[u8],
entries_offset: usize,
flags: u8,
) -> bool {
let predicates: SmallVec<[AttrPredicate; 4]> =
filters.iter().filter_map(predicate_for).collect();
if predicates.is_empty() {
return false;
}
let mut state: SmallVec<[u8; 4]> = SmallVec::from_elem(0, predicates.len());
let head = if flags & FLAG_ADD_PATH != 0 { 12 } else { 8 };
let mut rest = body.get(entries_offset..).unwrap_or(&[]);
while !rest.is_empty() {
if rest.len() < head {
return false;
}
let attr_len = read_u16(&rest[head - 2..]) as usize;
if rest.len() < head + attr_len {
return false;
}
let facts = read_entry(&rest[head..head + attr_len]);
if facts.truncated {
return false;
}
for (index, predicate) in predicates.iter().enumerate() {
match entry_satisfies(&facts, predicate) {
Some(true) => state[index] = 1,
Some(false) => {}
None if state[index] != 1 => state[index] = 2,
None => {}
}
}
rest = &rest[head + attr_len..];
}
state.contains(&0)
}
#[cfg(test)]
mod tests {
use super::*;
fn attrs(items: &[(u8, &[u8])]) -> Vec<u8> {
let mut out = Vec::new();
for (attr_type, body) in items {
out.push(0x40);
out.push(*attr_type);
out.push(body.len() as u8);
out.extend_from_slice(body);
}
out
}
fn as_path(segments: &[(u8, &[u32])]) -> Vec<u8> {
let mut out = Vec::new();
for (segment_type, asns) in segments {
out.push(*segment_type);
out.push(asns.len() as u8);
for asn in *asns {
out.extend_from_slice(&asn.to_be_bytes());
}
}
out
}
#[test]
fn sequence_origin_is_the_last_asn() {
let path = as_path(&[(2, &[64512, 174, 15169])]);
let block = attrs(&[(1, &[0]), (2, &path)]);
let facts = read_entry(&block);
assert_eq!(path_origin(facts.path.unwrap()), Ok(Some(15169u32.into())));
assert_eq!(facts.origin_at, Some(0));
}
#[test]
fn several_sequences_use_the_last_segment() {
let path = as_path(&[(2, &[64512, 174]), (2, &[3356, 15169])]);
assert_eq!(path_origin(&path), Ok(Some(15169u32.into())));
}
#[test]
fn a_single_member_set_is_decided_and_a_multi_member_set_is_not() {
let single = as_path(&[(2, &[64512]), (1, &[15169])]);
assert_eq!(path_origin(&single), Ok(Some(15169u32.into())));
let multi = as_path(&[(2, &[64512]), (1, &[15169, 13335])]);
assert_eq!(path_origin(&multi), Err(()));
}
#[test]
fn confederation_segments_contribute_no_origin() {
let path = as_path(&[(2, &[64512]), (3, &[65001])]);
assert_eq!(path_origin(&path), Ok(None));
}
#[test]
fn empty_and_missing_paths_have_no_origin() {
assert_eq!(path_origin(&[]), Ok(None));
let block = attrs(&[(1, &[0])]);
let facts = read_entry(&block);
assert_eq!(entry_satisfies(&facts, &AttrPredicate::Asn(15169)), None);
}
#[test]
fn two_byte_bgp4mp_records_are_undecidable_for_origin_predicates() {
use crate::models::Bgp4MpType;
let mut body = Vec::new();
body.extend_from_slice(&64512u16.to_be_bytes());
body.extend_from_slice(&64513u16.to_be_bytes());
body.extend_from_slice(&0u16.to_be_bytes());
body.extend_from_slice(&1u16.to_be_bytes());
body.extend_from_slice(&[192, 0, 2, 1]);
body.extend_from_slice(&[192, 0, 2, 2]);
body.extend_from_slice(&[0xFF; 16]);
body.extend_from_slice(&40u16.to_be_bytes());
body.push(2);
body.extend_from_slice(&0u16.to_be_bytes());
body.extend_from_slice(&13u16.to_be_bytes());
body.extend_from_slice(&[0x40, 1, 1, 0]);
body.extend_from_slice(&[0x40, 2, 6, 2, 2]);
body.extend_from_slice(&3356u16.to_be_bytes());
body.extend_from_slice(&13335u16.to_be_bytes());
body.extend_from_slice(&[24, 203, 0, 113]);
assert!(
!bgp4mp_record_excluded(
&[Filter::OriginAsn(3356)],
&body,
Bgp4MpType::Message as u16
),
"a two-byte record must not be excluded on an origin predicate"
);
}
fn bgp4mp_update(attributes: &[u8]) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(&65001u32.to_be_bytes());
body.extend_from_slice(&65002u32.to_be_bytes());
body.extend_from_slice(&0u16.to_be_bytes());
body.extend_from_slice(&1u16.to_be_bytes());
body.extend_from_slice(&[10, 0, 0, 1]);
body.extend_from_slice(&[10, 0, 0, 2]);
body.extend_from_slice(&[0xff; 16]);
body.extend_from_slice(&(19u16 + 2 + 2 + attributes.len() as u16 + 4).to_be_bytes());
body.push(2);
body.extend_from_slice(&0u16.to_be_bytes());
body.extend_from_slice(&(attributes.len() as u16).to_be_bytes());
body.extend_from_slice(attributes);
body.extend_from_slice(&[24, 8, 8, 8]);
body
}
#[test]
fn a_bgp4mp_update_locates_its_attributes() {
let block = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[174, 15169])]))]);
let body = bgp4mp_update(&block);
let located = bgp4mp_attributes(&body, 4).expect("attributes located");
assert_eq!(located, block.as_slice());
assert!(!bgp4mp_record_excluded(
&[Filter::OriginAsn(15169)],
&body,
4
));
assert!(bgp4mp_record_excluded(&[Filter::OriginAsn(3356)], &body, 4));
assert!(!bgp4mp_record_excluded(
&[Filter::Origin(Origin::IGP)],
&body,
4
));
assert!(bgp4mp_record_excluded(
&[Filter::Origin(Origin::INCOMPLETE)],
&body,
4
));
assert!(bgp4mp_attributes(&body, 99).is_none());
assert!(!bgp4mp_record_excluded(
&[Filter::OriginAsn(3356)],
&body,
99
));
assert!(
bgp4mp_attributes(&body, 6).is_none(),
"2-byte header against a 4-byte body"
);
}
#[test]
fn a_malformed_duplicate_does_not_overwrite_a_valid_origin() {
let block = attrs(&[(1, &[0]), (1, &[99])]);
let facts = read_entry(&block);
assert_eq!(
entry_satisfies(&facts, &AttrPredicate::Value(Origin::IGP)),
Some(true)
);
}
#[test]
fn a_malformed_duplicate_does_not_overwrite_a_valid_as_path() {
let valid = as_path(&[(2, &[13335])]);
let mut malformed = vec![9u8, 0];
malformed.extend_from_slice(&[2u8, 1]);
malformed.extend_from_slice(&64512u32.to_be_bytes());
let block = attrs(&[(2, &valid), (2, &malformed), (1, &[0])]);
let facts = read_entry(&block);
assert_eq!(
entry_satisfies(&facts, &AttrPredicate::Asn(13335)),
Some(true)
);
assert_eq!(
entry_satisfies(&facts, &AttrPredicate::Value(Origin::IGP)),
Some(true)
);
}
#[test]
fn as4_path_and_truncation_are_undecidable() {
let path = as_path(&[(2, &[64512, 13335])]);
let mut block = attrs(&[(1, &[0]), (2, &path), (17, &[0, 0, 0, 0])]);
block.extend_from_slice(&[0x40, 8, 4, 0, 0, 0, 0]);
assert_eq!(
entry_satisfies(&read_entry(&block), &AttrPredicate::Asn(13335)),
None
);
let mut short = attrs(&[(1, &[0])]);
short.extend_from_slice(&[0x40, 2, 30]);
assert!(read_entry(&short).truncated);
}
#[test]
fn filters_this_module_does_not_decide_never_exclude() {
use crate::ComparableRegex;
let path = as_path(&[(2, &[64512, 3356])]);
let block = attrs(&[(1, &[0]), (2, &path)]);
for filter in [
Filter::Community(ComparableRegex::new("^3356:").unwrap()),
Filter::AsPath(ComparableRegex::new("^64512 ").unwrap()),
] {
assert_eq!(predicate_for(&filter), None);
let body = rib_body(&[203, 0, 113], std::slice::from_ref(&block));
assert!(!rib_record_excluded(
std::slice::from_ref(&filter),
&body,
4,
0
));
}
}
fn rib_body(prefix: &[u8], entries: &[Vec<u8>]) -> Vec<u8> {
let mut body = vec![(prefix.len() * 8) as u8];
body.extend_from_slice(prefix);
for (index, entry) in entries.iter().enumerate() {
body.extend_from_slice(&(index as u16).to_be_bytes());
body.extend_from_slice(&0u32.to_be_bytes());
body.extend_from_slice(&(entry.len() as u16).to_be_bytes());
body.extend_from_slice(entry);
}
body
}
#[test]
fn a_record_is_excluded_only_when_no_entry_matches() {
let matching = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 15169])]))]);
let other = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 3356])]))]);
let filters = [Filter::OriginAsn(15169)];
let both = rib_body(&[203, 0, 113], &[other.clone(), matching]);
assert!(!rib_record_excluded(&filters, &both, 4, 0));
let only_other = rib_body(&[203, 0, 113], &[other]);
assert!(rib_record_excluded(&filters, &only_other, 4, 0));
}
#[test]
fn an_add_path_record_is_read_with_the_longer_entry_head() {
use crate::parser::mrt::frame::FLAG_ADD_PATH;
let other = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 3356])]))]);
let mut body = vec![(3u8) * 8];
body.extend_from_slice(&[203, 0, 113]);
for (index, entry) in [&other, &other].iter().enumerate() {
body.extend_from_slice(&(index as u16).to_be_bytes()); body.extend_from_slice(&0u32.to_be_bytes()); body.extend_from_slice(&0u32.to_be_bytes()); body.extend_from_slice(&(entry.len() as u16).to_be_bytes());
body.extend_from_slice(entry);
}
let filters = [Filter::OriginAsn(15169)];
assert!(
rib_record_excluded(&filters, &body, 4, FLAG_ADD_PATH),
"neither entry reaches 15169, so the record is skipped"
);
assert!(!rib_record_excluded(&filters, &body, 4, 0));
}
#[test]
fn an_undecidable_entry_prevents_exclusion() {
let undecided = attrs(&[
(1, &[0]),
(2, &as_path(&[(2, &[64512]), (1, &[15169, 13335])])),
]);
let other = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 3356])]))]);
let body = rib_body(&[203, 0, 113], &[other, undecided]);
assert!(!rib_record_excluded(
&[Filter::OriginAsn(15169)],
&body,
4,
0
));
}
#[test]
fn origin_prefilter_matches_the_element_level_semantics() {
use crate::parser::BgpkitParser;
let igp_15169 = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 174, 15169])]))]);
let egp_3356 = attrs(&[(1, &[1]), (2, &as_path(&[(2, &[64512, 3356])]))]);
let single_member_set = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512]), (1, &[15169])]))]);
let confederation = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512]), (3, &[65001])]))]);
assert_eq!(
entry_satisfies(&read_entry(&igp_15169), &AttrPredicate::Asn(15169)),
Some(true)
);
assert_eq!(
entry_satisfies(&read_entry(&egp_3356), &AttrPredicate::Asn(3356)),
Some(true)
);
assert_eq!(
entry_satisfies(&read_entry(&egp_3356), &AttrPredicate::Value(Origin::EGP)),
Some(true)
);
assert_eq!(
entry_satisfies(
&read_entry(&single_member_set),
&AttrPredicate::Asns(vec![15169, 13335])
),
Some(true)
);
assert_eq!(
entry_satisfies(&read_entry(&confederation), &AttrPredicate::Asn(65001)),
Some(false)
);
assert_eq!(
entry_satisfies(
&read_entry(&igp_15169),
&AttrPredicate::Value(Origin::INCOMPLETE)
),
Some(false)
);
let fixture = "tests/fixtures/routeviews/bview.slice.gz";
let all: Vec<crate::models::BgpElem> = BgpkitParser::new(fixture)
.expect("open fixture")
.into_elem_iter()
.collect();
assert!(all.len() > 10_000, "fixture should hold a real slice");
let expected_for = |predicate: &dyn Fn(&crate::models::BgpElem) -> bool| -> Vec<_> {
all.iter().filter(|elem| predicate(elem)).cloned().collect()
};
for asn in [15169u32, 13335, 3356, 174, 64073, 9999] {
let expected = expected_for(&|elem| {
elem.origin_asns
.as_ref()
.is_some_and(|origins| origins.contains(&asn.into()))
});
let actual: Vec<_> = BgpkitParser::new(fixture)
.expect("open fixture")
.add_filters(&[Filter::OriginAsn(asn)])
.into_elem_iter()
.collect();
assert_eq!(expected, actual, "origin_asn {asn} diverged");
}
for origin in [Origin::IGP, Origin::INCOMPLETE] {
let expected = expected_for(&|elem| elem.origin == Some(origin));
let actual: Vec<_> = BgpkitParser::new(fixture)
.expect("open fixture")
.add_filters(&[Filter::Origin(origin)])
.into_elem_iter()
.collect();
assert_eq!(expected, actual, "origin {origin} diverged");
}
}
#[test]
fn conjuncts_are_decided_independently() {
let only_asn = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 15169])]))]);
let only_origin = attrs(&[(1, &[1]), (2, &as_path(&[(2, &[64512, 3356])]))]);
let both = attrs(&[(1, &[1]), (2, &as_path(&[(2, &[3356, 15169])]))]);
let filters = [Filter::OriginAsn(15169), Filter::Origin(Origin::EGP)];
assert!(!rib_record_excluded(
&filters,
&rib_body(&[203, 0, 113], &[only_asn.clone(), only_origin.clone()]),
4,
0
));
assert!(rib_record_excluded(
&filters,
&rib_body(&[203, 0, 113], std::slice::from_ref(&only_asn)),
4,
0
));
assert!(rib_record_excluded(
&filters,
&rib_body(&[203, 0, 113], std::slice::from_ref(&only_origin)),
4,
0
));
assert!(!rib_record_excluded(
&filters,
&rib_body(&[203, 0, 113], std::slice::from_ref(&both)),
4,
0
));
let neither = attrs(&[(1, &[0]), (2, &as_path(&[(2, &[64512, 3356])]))]);
assert!(rib_record_excluded(
&filters,
&rib_body(&[203, 0, 113], std::slice::from_ref(&neither)),
4,
0
));
}
}