use super::*;
pub(super) fn wire_route_len(mut wire: &[u8]) -> usize {
let mut total = 0usize;
while wire.len() >= 2 {
let seg_type = wire[0];
let count = wire[1] as usize;
match seg_type {
AS_PATH_AS_SEQUENCE => total += count,
AS_PATH_AS_SET => total += 1,
_ => {}
}
wire = &wire[2 + count * 4..];
}
total
}
pub(super) fn mp_reach_next_hop(
value: &[u8],
prefix: NetworkPrefix,
afi: Afi,
safi: Safi,
add_path: bool,
from_update: bool,
) -> Result<Option<IpAddr>, ()> {
let prefix_list = [prefix];
let (afi, safi, prefixes) = if from_update {
(None, None, None)
} else {
(Some(afi), Some(safi), Some(&prefix_list[..]))
};
let decoded = crate::parser::bgp::attributes::parse_nlri(
bytes::Bytes::copy_from_slice(value),
&afi,
&safi,
&prefixes,
true,
add_path,
)
.map_err(|_| ())?;
match decoded {
crate::models::AttributeValue::MpReachNlri(nlri) => {
Ok(nlri.next_hop.map(|next_hop| next_hop.global_addr()))
}
_ => Err(()),
}
}
#[derive(Clone, Copy, Debug)]
pub(super) enum AsPathSource<'a> {
Absent,
Single(&'a [u8]),
Merged {
as_path: &'a [u8],
as4_path: &'a [u8],
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum AsPathSegmentType {
AsSet,
AsSequence,
ConfedSequence,
ConfedSet,
}
impl AsPathSegmentType {
#[inline]
fn from_wire(code: u8) -> Self {
match code {
AS_PATH_AS_SET => Self::AsSet,
AS_PATH_AS_SEQUENCE => Self::AsSequence,
AS_PATH_CONFED_SEQUENCE => Self::ConfedSequence,
AS_PATH_CONFED_SET => Self::ConfedSet,
_ => Self::AsSequence,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct AsPathSegmentRef<'a> {
seg_type: AsPathSegmentType,
asn_bytes: &'a [u8],
}
#[derive(Clone, Copy, Debug)]
pub struct AsPathView<'a> {
pub(super) source: AsPathSource<'a>,
}
impl<'a> AsPathView<'a> {
#[inline]
pub fn is_present(&self) -> bool {
!matches!(self.source, AsPathSource::Absent)
}
#[inline]
pub fn has_no_asns(&self) -> bool {
self.iter().next().is_none()
}
#[inline]
pub fn segments(&self) -> crate::models::SegmentIntoIter {
match self.to_as_path() {
Some(path) => path.into_segments_iter(),
None => AsPath::default().into_segments_iter(),
}
}
#[inline]
fn wire_segments(&self) -> AsPathSegments<'a> {
match self.source {
AsPathSource::Absent => AsPathSegments {
lead: &[],
lead_remaining: 0,
tail: &[],
},
AsPathSource::Single(wire) => AsPathSegments {
lead: &[],
lead_remaining: 0,
tail: wire,
},
AsPathSource::Merged { as_path, as4_path } => {
let lead_remaining = wire_route_len(as_path) - wire_route_len(as4_path);
AsPathSegments {
lead: if lead_remaining > 0 { as_path } else { &[] },
lead_remaining,
tail: as4_path,
}
}
}
}
#[inline]
pub fn iter(&self) -> AsPathIter<'a> {
match self.source {
AsPathSource::Absent => AsPathIter {
cur_words: &[],
segs: AsPathSegments {
lead: &[],
lead_remaining: 0,
tail: &[],
},
},
AsPathSource::Single(wire) => {
if wire.len() >= 2 {
let count = wire[1] as usize;
let end = 2 + count * 4;
AsPathIter {
cur_words: bytes_as_be_u32_words(&wire[2..end]),
segs: AsPathSegments {
lead: &[],
lead_remaining: 0,
tail: &wire[end..],
},
}
} else {
AsPathIter {
cur_words: &[],
segs: AsPathSegments {
lead: &[],
lead_remaining: 0,
tail: &[],
},
}
}
}
AsPathSource::Merged { .. } => AsPathIter {
cur_words: &[],
segs: self.wire_segments(),
},
}
}
pub fn to_vec(&self) -> Vec<Asn> {
self.iter().collect()
}
pub fn to_as_path(&self) -> Option<AsPath> {
match self.source {
AsPathSource::Absent => None,
AsPathSource::Single(wire) => Some(wire_to_owned_as_path(wire)),
AsPathSource::Merged { as_path, as4_path } => {
let p1 = wire_to_owned_as_path(as_path);
let p2 = wire_to_owned_as_path(as4_path);
Some(AsPath::merge_aspath_as4path(&p1, &p2))
}
}
}
}
fn wire_to_owned_as_path(wire: &[u8]) -> AsPath {
let mut out = AsPath::new();
let mut rest = wire;
while rest.len() >= 2 {
let code = rest[0];
let count = rest[1] as usize;
let end = 2 + count * 4;
let asns = bytes_as_be_u32_words(&rest[2..end])
.iter()
.map(|w| Asn::new_32bit(w.get()))
.collect();
let seg = match code {
AS_PATH_AS_SET => Some(AsPathSegment::AsSet(asns)),
AS_PATH_AS_SEQUENCE => Some(AsPathSegment::AsSequence(asns)),
AS_PATH_CONFED_SEQUENCE => Some(AsPathSegment::ConfedSequence(asns)),
AS_PATH_CONFED_SET => Some(AsPathSegment::ConfedSet(asns)),
_ => None,
};
if let Some(seg) = seg {
out.append_segment(seg);
}
rest = &rest[end..];
}
out
}
impl<'a> IntoIterator for AsPathView<'a> {
type Item = Asn;
type IntoIter = AsPathIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &AsPathView<'a> {
type Item = Asn;
type IntoIter = AsPathIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug)]
pub(super) struct AsPathSegments<'a> {
lead: &'a [u8],
lead_remaining: usize,
tail: &'a [u8],
}
impl<'a> Iterator for AsPathSegments<'a> {
type Item = AsPathSegmentRef<'a>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.lead_remaining > 0 && self.lead.len() >= 2 {
let code = self.lead[0];
let count = self.lead[1] as usize;
let end = 2 + count * 4;
let full_asn_bytes = &self.lead[2..end];
self.lead = &self.lead[end..];
let seg_type = AsPathSegmentType::from_wire(code);
let route_asns = match seg_type {
AsPathSegmentType::AsSequence => count,
AsPathSegmentType::AsSet => 1,
AsPathSegmentType::ConfedSequence | AsPathSegmentType::ConfedSet => 0,
};
if route_asns <= self.lead_remaining {
self.lead_remaining -= route_asns;
if self.lead_remaining == 0 {
self.lead = &[];
}
return Some(AsPathSegmentRef {
seg_type,
asn_bytes: full_asn_bytes,
});
} else {
let take_bytes = self.lead_remaining * 4;
self.lead_remaining = 0;
self.lead = &[];
return Some(AsPathSegmentRef {
seg_type,
asn_bytes: &full_asn_bytes[..take_bytes],
});
}
}
if self.tail.len() >= 2 {
let code = self.tail[0];
let count = self.tail[1] as usize;
let end = 2 + count * 4;
let asn_bytes = &self.tail[2..end];
self.tail = &self.tail[end..];
return Some(AsPathSegmentRef {
seg_type: AsPathSegmentType::from_wire(code),
asn_bytes,
});
}
None
}
}
#[derive(Clone, Debug)]
pub struct AsPathIter<'a> {
cur_words: &'a [BeU32],
segs: AsPathSegments<'a>,
}
impl<'a> Iterator for AsPathIter<'a> {
type Item = Asn;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some((first, rest)) = self.cur_words.split_first() {
self.cur_words = rest;
return Some(Asn::new_32bit(first.get()));
}
let seg = self.segs.next()?;
self.cur_words = bytes_as_be_u32_words(seg.asn_bytes);
}
}
}
#[derive(Clone, Copy, Debug)]
pub(super) enum OriginsRepr<'a> {
Absent,
Empty,
One(Asn),
Set(&'a [BeU32]),
}
#[inline]
pub(super) fn single_wire_origins(wire: &[u8]) -> AsnsView<'_> {
if wire.len() >= 6 && wire[0] == AS_PATH_AS_SEQUENCE && 2 + (wire[1] as usize) * 4 == wire.len()
{
let last = wire.len() - 4;
let asn = Asn::new_32bit(u32::from_be_bytes([
wire[last],
wire[last + 1],
wire[last + 2],
wire[last + 3],
]));
return AsnsView {
repr: OriginsRepr::One(asn),
};
}
let mut rest = wire;
let mut last_seg: Option<(u8, &[u8])> = None;
while rest.len() >= 2 {
let code = rest[0];
let count = rest[1] as usize;
let end = 2 + count * 4;
last_seg = Some((code, &rest[2..end]));
rest = &rest[end..];
}
let repr = match last_seg {
Some((AS_PATH_AS_SEQUENCE, bytes)) if bytes.len() >= 4 => {
let i = bytes.len() - 4;
OriginsRepr::One(Asn::new_32bit(u32::from_be_bytes([
bytes[i],
bytes[i + 1],
bytes[i + 2],
bytes[i + 3],
])))
}
Some((AS_PATH_AS_SET, bytes)) if !bytes.is_empty() => {
OriginsRepr::Set(bytes_as_be_u32_words(bytes))
}
_ => OriginsRepr::Empty,
};
AsnsView { repr }
}
#[cold]
pub(super) fn merged_wire_origins<'a>(as_path: &'a [u8], as4_path: &'a [u8]) -> AsnsView<'a> {
#[derive(Clone, Copy)]
enum LastCoalesced<'b> {
None,
EmptySeq,
NonEmptyAsSeq(Asn),
NonEmptyConfedSeq,
AsSet(&'b [BeU32]),
ConfedSet,
}
let segs = AsPathSegments {
lead: if wire_route_len(as_path) > wire_route_len(as4_path) {
as_path
} else {
&[]
},
lead_remaining: wire_route_len(as_path) - wire_route_len(as4_path),
tail: as4_path,
};
let mut state = LastCoalesced::None;
for seg in segs {
let next_state = match seg.seg_type {
AsPathSegmentType::AsSequence => {
if seg.asn_bytes.len() >= 4 {
let i = seg.asn_bytes.len() - 4;
LastCoalesced::NonEmptyAsSeq(Asn::new_32bit(u32::from_be_bytes([
seg.asn_bytes[i],
seg.asn_bytes[i + 1],
seg.asn_bytes[i + 2],
seg.asn_bytes[i + 3],
])))
} else {
LastCoalesced::EmptySeq
}
}
AsPathSegmentType::ConfedSequence => {
if seg.asn_bytes.is_empty() {
LastCoalesced::EmptySeq
} else {
LastCoalesced::NonEmptyConfedSeq
}
}
AsPathSegmentType::AsSet => LastCoalesced::AsSet(bytes_as_be_u32_words(seg.asn_bytes)),
AsPathSegmentType::ConfedSet => LastCoalesced::ConfedSet,
};
state = match (state, next_state) {
(LastCoalesced::None, y) | (LastCoalesced::EmptySeq, y) => y,
(x, LastCoalesced::EmptySeq) => x,
(_, y) => y,
};
}
let repr = match state {
LastCoalesced::NonEmptyAsSeq(asn) => OriginsRepr::One(asn),
LastCoalesced::AsSet(words) if !words.is_empty() => OriginsRepr::Set(words),
_ => OriginsRepr::Empty,
};
AsnsView { repr }
}
#[derive(Clone, Copy, Debug)]
pub struct AsnsView<'a> {
pub(super) repr: OriginsRepr<'a>,
}
impl<'a> AsnsView<'a> {
#[inline]
pub fn is_present(&self) -> bool {
!matches!(self.repr, OriginsRepr::Absent)
}
#[inline]
pub fn len(&self) -> usize {
match self.repr {
OriginsRepr::Absent | OriginsRepr::Empty => 0,
OriginsRepr::One(_) => 1,
OriginsRepr::Set(words) => words.len(),
}
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn iter(&self) -> AsnsIter<'a> {
AsnsIter { repr: self.repr }
}
pub fn to_vec(&self) -> Vec<Asn> {
self.iter().collect()
}
}
impl<'a> IntoIterator for AsnsView<'a> {
type Item = Asn;
type IntoIter = AsnsIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &AsnsView<'a> {
type Item = Asn;
type IntoIter = AsnsIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug)]
pub struct AsnsIter<'a> {
repr: OriginsRepr<'a>,
}
impl<'a> Iterator for AsnsIter<'a> {
type Item = Asn;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
match &mut self.repr {
OriginsRepr::Absent | OriginsRepr::Empty => None,
OriginsRepr::One(asn) => {
let out = *asn;
self.repr = OriginsRepr::Empty;
Some(out)
}
OriginsRepr::Set(words) => {
let (first, rest) = words.split_first()?;
*words = rest;
Some(Asn::new_32bit(first.get()))
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let len = match self.repr {
OriginsRepr::Absent | OriginsRepr::Empty => 0,
OriginsRepr::One(_) => 1,
OriginsRepr::Set(words) => words.len(),
};
(len, Some(len))
}
}
impl ExactSizeIterator for AsnsIter<'_> {}
#[inline]
pub(super) fn bytes_as_be_u32_words(bytes: &[u8]) -> &[BeU32] {
if !bytes.len().is_multiple_of(4) {
return &[];
}
<[BeU32]>::ref_from_bytes(bytes).unwrap_or(&[])
}
#[derive(Clone, Copy, Debug)]
pub struct CommunitiesView<'a> {
pub(super) attr_bytes: &'a [u8],
}
impl<'a> CommunitiesView<'a> {
#[inline]
pub fn is_empty(&self) -> bool {
self.iter().next().is_none()
}
#[inline]
pub fn iter(&self) -> CommunitiesIter<'a> {
CommunitiesIter {
rest_attrs: self.attr_bytes,
cur_kind: ActiveCommunityAttr::None,
}
}
}
impl<'a> IntoIterator for CommunitiesView<'a> {
type Item = MetaCommunity;
type IntoIter = CommunitiesIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a> IntoIterator for &CommunitiesView<'a> {
type Item = MetaCommunity;
type IntoIter = CommunitiesIter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
pub(super) enum AttrStep {
End,
Truncated {
code: u8,
declared: usize,
available: usize,
},
Attr {
code: u8,
value_start: usize,
value_end: usize,
},
}
pub(super) enum AttrBlockScan {
Usable {
usable_len: usize,
truncated: Option<(u8, usize, usize)>,
},
Unreadable,
}
pub(super) fn scan_attr_block(bytes: &[u8]) -> AttrBlockScan {
let mut pos = 0usize;
loop {
if pos + 3 > bytes.len() {
return AttrBlockScan::Usable {
usable_len: pos,
truncated: None,
};
}
if bytes[pos] & AttrFlags::EXTENDED.bits() != 0 && pos + 4 > bytes.len() {
return AttrBlockScan::Unreadable;
}
match step_attr(bytes, pos) {
AttrStep::End => {
return AttrBlockScan::Usable {
usable_len: pos,
truncated: None,
}
}
AttrStep::Truncated {
code,
declared,
available,
} => {
return AttrBlockScan::Usable {
usable_len: pos,
truncated: Some((code, declared, available)),
}
}
AttrStep::Attr { value_end, .. } => pos = value_end,
}
}
}
pub(super) fn next_attr_bounds(bytes: &[u8], pos: usize) -> Option<(u8, usize, usize)> {
match step_attr(bytes, pos) {
AttrStep::Attr {
code,
value_start,
value_end,
} => Some((code, value_start, value_end)),
AttrStep::Truncated { .. } | AttrStep::End => None,
}
}
pub(super) fn step_attr(bytes: &[u8], pos: usize) -> AttrStep {
if pos + 3 > bytes.len() {
return AttrStep::End;
}
let flags = bytes[pos];
let code = bytes[pos + 1];
let (header_len, declared) = if (flags & AttrFlags::EXTENDED.bits()) == 0 {
(3usize, bytes[pos + 2] as usize)
} else {
if pos + 4 > bytes.len() {
return AttrStep::End;
}
(
4usize,
u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]) as usize,
)
};
let value_start = pos + header_len;
let value_end = value_start + declared;
if value_end > bytes.len() {
return AttrStep::Truncated {
code,
declared,
available: bytes.len() - value_start,
};
}
AttrStep::Attr {
code,
value_start,
value_end,
}
}
#[inline]
pub(super) fn next_attr_tlv(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> {
let (code, header_len, value_end) = next_attr_bounds(bytes, 0)?;
Some((code, &bytes[header_len..value_end], &bytes[value_end..]))
}
#[derive(Clone, Debug)]
enum ActiveCommunityAttr<'a> {
None,
Plain(&'a [BeU32]),
Extended(&'a [u8]),
Ipv6Extended(&'a [u8]),
Large(&'a [BeU32]),
}
#[derive(Clone, Debug)]
pub struct CommunitiesIter<'a> {
rest_attrs: &'a [u8],
cur_kind: ActiveCommunityAttr<'a>,
}
impl Iterator for CommunitiesIter<'_> {
type Item = MetaCommunity;
#[inline]
fn next(&mut self) -> Option<MetaCommunity> {
loop {
match &mut self.cur_kind {
ActiveCommunityAttr::Plain(words) => {
if let Some((first, rest)) = words.split_first() {
*words = rest;
return Some(MetaCommunity::Plain(
crate::parser::bgp::attributes::decode_regular_community(first.get()),
));
}
}
ActiveCommunityAttr::Extended(bytes) => {
if bytes.len() >= 8 {
let mut chunk = &bytes[..8];
*bytes = &bytes[8..];
return Some(MetaCommunity::Extended(
crate::parser::bgp::attributes::parse_extended_community_one(
&mut chunk,
)
.unwrap_or(ExtendedCommunity::Raw([0u8; 8])),
));
}
}
ActiveCommunityAttr::Ipv6Extended(bytes) => {
if bytes.len() >= 20 {
let mut chunk = &bytes[..20];
*bytes = &bytes[20..];
if let Ok(item) =
crate::parser::bgp::attributes::parse_ipv6_extended_community_one(
&mut chunk,
)
{
return Some(MetaCommunity::Ipv6Extended(item));
}
}
}
ActiveCommunityAttr::Large(words) => {
if words.len() >= 3 {
let ga = words[0].get();
let d0 = words[1].get();
let d1 = words[2].get();
*words = &words[3..];
return Some(MetaCommunity::Large(LargeCommunity::new(ga, [d0, d1])));
}
}
ActiveCommunityAttr::None => {}
}
self.cur_kind = ActiveCommunityAttr::None;
let (code, val, next_rest) = next_attr_tlv(self.rest_attrs)?;
self.rest_attrs = next_rest;
match AttrType::from(code) {
AttrType::COMMUNITIES if val.len().is_multiple_of(4) => {
self.cur_kind = ActiveCommunityAttr::Plain(bytes_as_be_u32_words(val));
}
AttrType::EXTENDED_COMMUNITIES if val.len().is_multiple_of(8) => {
self.cur_kind = ActiveCommunityAttr::Extended(val);
}
AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
if val.len().is_multiple_of(20) =>
{
self.cur_kind = ActiveCommunityAttr::Ipv6Extended(val);
}
AttrType::LARGE_COMMUNITIES if val.len().is_multiple_of(12) => {
self.cur_kind = ActiveCommunityAttr::Large(bytes_as_be_u32_words(val));
}
_ => {}
}
}
}
}