1use super::*;
8
9pub(super) fn wire_route_len(mut wire: &[u8]) -> usize {
10 let mut total = 0usize;
11 while wire.len() >= 2 {
12 let seg_type = wire[0];
13 let count = wire[1] as usize;
14 match seg_type {
15 AS_PATH_AS_SEQUENCE => total += count,
16 AS_PATH_AS_SET => total += 1,
17 _ => {}
18 }
19 wire = &wire[2 + count * 4..];
20 }
21 total
22}
23
24pub(super) fn mp_reach_next_hop(
31 value: &[u8],
32 prefix: NetworkPrefix,
33 afi: Afi,
34 safi: Safi,
35 add_path: bool,
36 from_update: bool,
37) -> Result<Option<IpAddr>, ()> {
38 let prefix_list = [prefix];
39 let (afi, safi, prefixes) = if from_update {
40 (None, None, None)
41 } else {
42 (Some(afi), Some(safi), Some(&prefix_list[..]))
43 };
44 let decoded = crate::parser::bgp::attributes::parse_nlri(
45 bytes::Bytes::copy_from_slice(value),
46 &afi,
47 &safi,
48 &prefixes,
49 true,
50 add_path,
51 )
52 .map_err(|_| ())?;
53 match decoded {
54 crate::models::AttributeValue::MpReachNlri(nlri) => {
55 Ok(nlri.next_hop.map(|next_hop| next_hop.global_addr()))
56 }
57 _ => Err(()),
58 }
59}
60
61#[derive(Clone, Copy, Debug)]
66pub(super) enum AsPathSource<'a> {
67 Absent,
68 Single(&'a [u8]),
69 Merged {
70 as_path: &'a [u8],
71 as4_path: &'a [u8],
72 },
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77pub(super) enum AsPathSegmentType {
78 AsSet,
79 AsSequence,
80 ConfedSequence,
81 ConfedSet,
82}
83
84impl AsPathSegmentType {
85 #[inline]
86 fn from_wire(code: u8) -> Self {
87 match code {
88 AS_PATH_AS_SET => Self::AsSet,
89 AS_PATH_AS_SEQUENCE => Self::AsSequence,
90 AS_PATH_CONFED_SEQUENCE => Self::ConfedSequence,
91 AS_PATH_CONFED_SET => Self::ConfedSet,
92 _ => Self::AsSequence,
95 }
96 }
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub(super) struct AsPathSegmentRef<'a> {
102 seg_type: AsPathSegmentType,
103 asn_bytes: &'a [u8],
104}
105
106#[derive(Clone, Copy, Debug)]
113pub struct AsPathView<'a> {
114 pub(super) source: AsPathSource<'a>,
115}
116
117impl<'a> AsPathView<'a> {
118 #[inline]
121 pub fn is_present(&self) -> bool {
122 !matches!(self.source, AsPathSource::Absent)
123 }
124
125 #[inline]
130 pub fn has_no_asns(&self) -> bool {
131 self.iter().next().is_none()
132 }
133
134 #[inline]
140 pub fn segments(&self) -> crate::models::SegmentIntoIter {
141 match self.to_as_path() {
142 Some(path) => path.into_segments_iter(),
143 None => AsPath::default().into_segments_iter(),
144 }
145 }
146
147 #[inline]
149 fn wire_segments(&self) -> AsPathSegments<'a> {
150 match self.source {
151 AsPathSource::Absent => AsPathSegments {
152 lead: &[],
153 lead_remaining: 0,
154 tail: &[],
155 },
156 AsPathSource::Single(wire) => AsPathSegments {
157 lead: &[],
158 lead_remaining: 0,
159 tail: wire,
160 },
161 AsPathSource::Merged { as_path, as4_path } => {
162 let lead_remaining = wire_route_len(as_path) - wire_route_len(as4_path);
163 AsPathSegments {
164 lead: if lead_remaining > 0 { as_path } else { &[] },
165 lead_remaining,
166 tail: as4_path,
167 }
168 }
169 }
170 }
171
172 #[inline]
175 pub fn iter(&self) -> AsPathIter<'a> {
176 match self.source {
177 AsPathSource::Absent => AsPathIter {
178 cur_words: &[],
179 segs: AsPathSegments {
180 lead: &[],
181 lead_remaining: 0,
182 tail: &[],
183 },
184 },
185 AsPathSource::Single(wire) => {
186 if wire.len() >= 2 {
187 let count = wire[1] as usize;
188 let end = 2 + count * 4;
189 AsPathIter {
190 cur_words: bytes_as_be_u32_words(&wire[2..end]),
191 segs: AsPathSegments {
192 lead: &[],
193 lead_remaining: 0,
194 tail: &wire[end..],
195 },
196 }
197 } else {
198 AsPathIter {
199 cur_words: &[],
200 segs: AsPathSegments {
201 lead: &[],
202 lead_remaining: 0,
203 tail: &[],
204 },
205 }
206 }
207 }
208 AsPathSource::Merged { .. } => AsPathIter {
209 cur_words: &[],
210 segs: self.wire_segments(),
211 },
212 }
213 }
214
215 pub fn to_vec(&self) -> Vec<Asn> {
217 self.iter().collect()
218 }
219
220 pub fn to_as_path(&self) -> Option<AsPath> {
222 match self.source {
223 AsPathSource::Absent => None,
224 AsPathSource::Single(wire) => Some(wire_to_owned_as_path(wire)),
225 AsPathSource::Merged { as_path, as4_path } => {
226 let p1 = wire_to_owned_as_path(as_path);
227 let p2 = wire_to_owned_as_path(as4_path);
228 Some(AsPath::merge_aspath_as4path(&p1, &p2))
229 }
230 }
231 }
232}
233
234fn wire_to_owned_as_path(wire: &[u8]) -> AsPath {
235 let mut out = AsPath::new();
236 let mut rest = wire;
237 while rest.len() >= 2 {
238 let code = rest[0];
239 let count = rest[1] as usize;
240 let end = 2 + count * 4;
241 let asns = bytes_as_be_u32_words(&rest[2..end])
242 .iter()
243 .map(|w| Asn::new_32bit(w.get()))
244 .collect();
245 let seg = match code {
246 AS_PATH_AS_SET => Some(AsPathSegment::AsSet(asns)),
247 AS_PATH_AS_SEQUENCE => Some(AsPathSegment::AsSequence(asns)),
248 AS_PATH_CONFED_SEQUENCE => Some(AsPathSegment::ConfedSequence(asns)),
249 AS_PATH_CONFED_SET => Some(AsPathSegment::ConfedSet(asns)),
250 _ => None,
253 };
254 if let Some(seg) = seg {
255 out.append_segment(seg);
256 }
257 rest = &rest[end..];
258 }
259 out
260}
261
262impl<'a> IntoIterator for AsPathView<'a> {
263 type Item = Asn;
264 type IntoIter = AsPathIter<'a>;
265
266 #[inline]
267 fn into_iter(self) -> Self::IntoIter {
268 self.iter()
269 }
270}
271
272impl<'a> IntoIterator for &AsPathView<'a> {
273 type Item = Asn;
274 type IntoIter = AsPathIter<'a>;
275
276 #[inline]
277 fn into_iter(self) -> Self::IntoIter {
278 self.iter()
279 }
280}
281
282#[derive(Clone, Debug)]
284pub(super) struct AsPathSegments<'a> {
285 lead: &'a [u8],
286 lead_remaining: usize,
287 tail: &'a [u8],
288}
289
290impl<'a> Iterator for AsPathSegments<'a> {
291 type Item = AsPathSegmentRef<'a>;
292
293 #[inline]
294 fn next(&mut self) -> Option<Self::Item> {
295 if self.lead_remaining > 0 && self.lead.len() >= 2 {
296 let code = self.lead[0];
297 let count = self.lead[1] as usize;
298 let end = 2 + count * 4;
299 let full_asn_bytes = &self.lead[2..end];
300 self.lead = &self.lead[end..];
301
302 let seg_type = AsPathSegmentType::from_wire(code);
303 let route_asns = match seg_type {
304 AsPathSegmentType::AsSequence => count,
305 AsPathSegmentType::AsSet => 1,
306 AsPathSegmentType::ConfedSequence | AsPathSegmentType::ConfedSet => 0,
307 };
308
309 if route_asns <= self.lead_remaining {
310 self.lead_remaining -= route_asns;
311 if self.lead_remaining == 0 {
312 self.lead = &[];
313 }
314 return Some(AsPathSegmentRef {
315 seg_type,
316 asn_bytes: full_asn_bytes,
317 });
318 } else {
319 let take_bytes = self.lead_remaining * 4;
321 self.lead_remaining = 0;
322 self.lead = &[];
323 return Some(AsPathSegmentRef {
324 seg_type,
325 asn_bytes: &full_asn_bytes[..take_bytes],
326 });
327 }
328 }
329
330 if self.tail.len() >= 2 {
331 let code = self.tail[0];
332 let count = self.tail[1] as usize;
333 let end = 2 + count * 4;
334 let asn_bytes = &self.tail[2..end];
335 self.tail = &self.tail[end..];
336 return Some(AsPathSegmentRef {
337 seg_type: AsPathSegmentType::from_wire(code),
338 asn_bytes,
339 });
340 }
341
342 None
343 }
344}
345
346#[derive(Clone, Debug)]
348pub struct AsPathIter<'a> {
349 cur_words: &'a [BeU32],
350 segs: AsPathSegments<'a>,
351}
352
353impl<'a> Iterator for AsPathIter<'a> {
354 type Item = Asn;
355
356 #[inline]
357 fn next(&mut self) -> Option<Self::Item> {
358 loop {
359 if let Some((first, rest)) = self.cur_words.split_first() {
360 self.cur_words = rest;
361 return Some(Asn::new_32bit(first.get()));
362 }
363 let seg = self.segs.next()?;
364 self.cur_words = bytes_as_be_u32_words(seg.asn_bytes);
365 }
366 }
367}
368
369#[derive(Clone, Copy, Debug)]
370pub(super) enum OriginsRepr<'a> {
371 Absent,
372 Empty,
373 One(Asn),
374 Set(&'a [BeU32]),
375}
376
377#[inline]
378pub(super) fn single_wire_origins(wire: &[u8]) -> AsnsView<'_> {
379 if wire.len() >= 6 && wire[0] == AS_PATH_AS_SEQUENCE && 2 + (wire[1] as usize) * 4 == wire.len()
381 {
382 let last = wire.len() - 4;
383 let asn = Asn::new_32bit(u32::from_be_bytes([
384 wire[last],
385 wire[last + 1],
386 wire[last + 2],
387 wire[last + 3],
388 ]));
389 return AsnsView {
390 repr: OriginsRepr::One(asn),
391 };
392 }
393
394 let mut rest = wire;
395 let mut last_seg: Option<(u8, &[u8])> = None;
396 while rest.len() >= 2 {
397 let code = rest[0];
398 let count = rest[1] as usize;
399 let end = 2 + count * 4;
400 last_seg = Some((code, &rest[2..end]));
401 rest = &rest[end..];
402 }
403
404 let repr = match last_seg {
405 Some((AS_PATH_AS_SEQUENCE, bytes)) if bytes.len() >= 4 => {
406 let i = bytes.len() - 4;
407 OriginsRepr::One(Asn::new_32bit(u32::from_be_bytes([
408 bytes[i],
409 bytes[i + 1],
410 bytes[i + 2],
411 bytes[i + 3],
412 ])))
413 }
414 Some((AS_PATH_AS_SET, bytes)) if !bytes.is_empty() => {
415 OriginsRepr::Set(bytes_as_be_u32_words(bytes))
416 }
417 _ => OriginsRepr::Empty,
418 };
419 AsnsView { repr }
420}
421
422#[cold]
425pub(super) fn merged_wire_origins<'a>(as_path: &'a [u8], as4_path: &'a [u8]) -> AsnsView<'a> {
426 #[derive(Clone, Copy)]
427 enum LastCoalesced<'b> {
428 None,
429 EmptySeq,
430 NonEmptyAsSeq(Asn),
431 NonEmptyConfedSeq,
432 AsSet(&'b [BeU32]),
433 ConfedSet,
434 }
435
436 let segs = AsPathSegments {
437 lead: if wire_route_len(as_path) > wire_route_len(as4_path) {
438 as_path
439 } else {
440 &[]
441 },
442 lead_remaining: wire_route_len(as_path) - wire_route_len(as4_path),
443 tail: as4_path,
444 };
445
446 let mut state = LastCoalesced::None;
447 for seg in segs {
448 let next_state = match seg.seg_type {
449 AsPathSegmentType::AsSequence => {
450 if seg.asn_bytes.len() >= 4 {
451 let i = seg.asn_bytes.len() - 4;
452 LastCoalesced::NonEmptyAsSeq(Asn::new_32bit(u32::from_be_bytes([
453 seg.asn_bytes[i],
454 seg.asn_bytes[i + 1],
455 seg.asn_bytes[i + 2],
456 seg.asn_bytes[i + 3],
457 ])))
458 } else {
459 LastCoalesced::EmptySeq
460 }
461 }
462 AsPathSegmentType::ConfedSequence => {
463 if seg.asn_bytes.is_empty() {
464 LastCoalesced::EmptySeq
465 } else {
466 LastCoalesced::NonEmptyConfedSeq
467 }
468 }
469 AsPathSegmentType::AsSet => LastCoalesced::AsSet(bytes_as_be_u32_words(seg.asn_bytes)),
470 AsPathSegmentType::ConfedSet => LastCoalesced::ConfedSet,
471 };
472
473 state = match (state, next_state) {
475 (LastCoalesced::None, y) | (LastCoalesced::EmptySeq, y) => y,
476 (x, LastCoalesced::EmptySeq) => x,
477 (_, y) => y,
478 };
479 }
480
481 let repr = match state {
482 LastCoalesced::NonEmptyAsSeq(asn) => OriginsRepr::One(asn),
483 LastCoalesced::AsSet(words) if !words.is_empty() => OriginsRepr::Set(words),
484 _ => OriginsRepr::Empty,
485 };
486 AsnsView { repr }
487}
488
489#[derive(Clone, Copy, Debug)]
491pub struct AsnsView<'a> {
492 pub(super) repr: OriginsRepr<'a>,
493}
494
495impl<'a> AsnsView<'a> {
496 #[inline]
499 pub fn is_present(&self) -> bool {
500 !matches!(self.repr, OriginsRepr::Absent)
501 }
502
503 #[inline]
506 pub fn len(&self) -> usize {
507 match self.repr {
508 OriginsRepr::Absent | OriginsRepr::Empty => 0,
509 OriginsRepr::One(_) => 1,
510 OriginsRepr::Set(words) => words.len(),
511 }
512 }
513
514 #[inline]
516 pub fn is_empty(&self) -> bool {
517 self.len() == 0
518 }
519
520 #[inline]
522 pub fn iter(&self) -> AsnsIter<'a> {
523 AsnsIter { repr: self.repr }
524 }
525
526 pub fn to_vec(&self) -> Vec<Asn> {
528 self.iter().collect()
529 }
530}
531
532impl<'a> IntoIterator for AsnsView<'a> {
533 type Item = Asn;
534 type IntoIter = AsnsIter<'a>;
535
536 #[inline]
537 fn into_iter(self) -> Self::IntoIter {
538 self.iter()
539 }
540}
541
542impl<'a> IntoIterator for &AsnsView<'a> {
543 type Item = Asn;
544 type IntoIter = AsnsIter<'a>;
545
546 #[inline]
547 fn into_iter(self) -> Self::IntoIter {
548 self.iter()
549 }
550}
551
552#[derive(Clone, Debug)]
554pub struct AsnsIter<'a> {
555 repr: OriginsRepr<'a>,
556}
557
558impl<'a> Iterator for AsnsIter<'a> {
559 type Item = Asn;
560
561 #[inline]
562 fn next(&mut self) -> Option<Self::Item> {
563 match &mut self.repr {
564 OriginsRepr::Absent | OriginsRepr::Empty => None,
565 OriginsRepr::One(asn) => {
566 let out = *asn;
567 self.repr = OriginsRepr::Empty;
568 Some(out)
569 }
570 OriginsRepr::Set(words) => {
571 let (first, rest) = words.split_first()?;
572 *words = rest;
573 Some(Asn::new_32bit(first.get()))
574 }
575 }
576 }
577
578 #[inline]
579 fn size_hint(&self) -> (usize, Option<usize>) {
580 let len = match self.repr {
581 OriginsRepr::Absent | OriginsRepr::Empty => 0,
582 OriginsRepr::One(_) => 1,
583 OriginsRepr::Set(words) => words.len(),
584 };
585 (len, Some(len))
586 }
587}
588
589impl ExactSizeIterator for AsnsIter<'_> {}
590
591#[inline]
600pub(super) fn bytes_as_be_u32_words(bytes: &[u8]) -> &[BeU32] {
601 if !bytes.len().is_multiple_of(4) {
602 return &[];
603 }
604 <[BeU32]>::ref_from_bytes(bytes).unwrap_or(&[])
605}
606
607#[derive(Clone, Copy, Debug)]
618pub struct CommunitiesView<'a> {
619 pub(super) attr_bytes: &'a [u8],
620}
621
622impl<'a> CommunitiesView<'a> {
623 #[inline]
625 pub fn is_empty(&self) -> bool {
626 self.iter().next().is_none()
627 }
628
629 #[inline]
632 pub fn iter(&self) -> CommunitiesIter<'a> {
633 CommunitiesIter {
634 rest_attrs: self.attr_bytes,
635 cur_kind: ActiveCommunityAttr::None,
636 }
637 }
638}
639
640impl<'a> IntoIterator for CommunitiesView<'a> {
641 type Item = MetaCommunity;
642 type IntoIter = CommunitiesIter<'a>;
643
644 #[inline]
645 fn into_iter(self) -> Self::IntoIter {
646 self.iter()
647 }
648}
649
650impl<'a> IntoIterator for &CommunitiesView<'a> {
651 type Item = MetaCommunity;
652 type IntoIter = CommunitiesIter<'a>;
653
654 #[inline]
655 fn into_iter(self) -> Self::IntoIter {
656 self.iter()
657 }
658}
659
660pub(super) enum AttrStep {
662 End,
664 Truncated {
667 code: u8,
668 declared: usize,
669 available: usize,
670 },
671 Attr {
673 code: u8,
674 value_start: usize,
675 value_end: usize,
676 },
677}
678
679pub(super) enum AttrBlockScan {
681 Usable {
684 usable_len: usize,
685 truncated: Option<(u8, usize, usize)>,
686 },
687 Unreadable,
690}
691
692pub(super) fn scan_attr_block(bytes: &[u8]) -> AttrBlockScan {
698 let mut pos = 0usize;
699 loop {
700 if pos + 3 > bytes.len() {
702 return AttrBlockScan::Usable {
703 usable_len: pos,
704 truncated: None,
705 };
706 }
707 if bytes[pos] & AttrFlags::EXTENDED.bits() != 0 && pos + 4 > bytes.len() {
709 return AttrBlockScan::Unreadable;
710 }
711 match step_attr(bytes, pos) {
712 AttrStep::End => {
713 return AttrBlockScan::Usable {
714 usable_len: pos,
715 truncated: None,
716 }
717 }
718 AttrStep::Truncated {
719 code,
720 declared,
721 available,
722 } => {
723 return AttrBlockScan::Usable {
724 usable_len: pos,
725 truncated: Some((code, declared, available)),
726 }
727 }
728 AttrStep::Attr { value_end, .. } => pos = value_end,
729 }
730 }
731}
732
733pub(super) fn next_attr_bounds(bytes: &[u8], pos: usize) -> Option<(u8, usize, usize)> {
736 match step_attr(bytes, pos) {
737 AttrStep::Attr {
738 code,
739 value_start,
740 value_end,
741 } => Some((code, value_start, value_end)),
742 AttrStep::Truncated { .. } | AttrStep::End => None,
743 }
744}
745
746pub(super) fn step_attr(bytes: &[u8], pos: usize) -> AttrStep {
751 if pos + 3 > bytes.len() {
752 return AttrStep::End;
753 }
754 let flags = bytes[pos];
755 let code = bytes[pos + 1];
756 let (header_len, declared) = if (flags & AttrFlags::EXTENDED.bits()) == 0 {
757 (3usize, bytes[pos + 2] as usize)
758 } else {
759 if pos + 4 > bytes.len() {
760 return AttrStep::End;
761 }
762 (
763 4usize,
764 u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]) as usize,
765 )
766 };
767 let value_start = pos + header_len;
768 let value_end = value_start + declared;
769 if value_end > bytes.len() {
770 return AttrStep::Truncated {
771 code,
772 declared,
773 available: bytes.len() - value_start,
774 };
775 }
776 AttrStep::Attr {
777 code,
778 value_start,
779 value_end,
780 }
781}
782
783#[inline]
784pub(super) fn next_attr_tlv(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> {
785 let (code, header_len, value_end) = next_attr_bounds(bytes, 0)?;
786 Some((code, &bytes[header_len..value_end], &bytes[value_end..]))
787}
788
789#[derive(Clone, Debug)]
790enum ActiveCommunityAttr<'a> {
791 None,
792 Plain(&'a [BeU32]),
793 Extended(&'a [u8]),
794 Ipv6Extended(&'a [u8]),
795 Large(&'a [BeU32]),
796}
797
798#[derive(Clone, Debug)]
800pub struct CommunitiesIter<'a> {
801 rest_attrs: &'a [u8],
802 cur_kind: ActiveCommunityAttr<'a>,
803}
804
805impl Iterator for CommunitiesIter<'_> {
806 type Item = MetaCommunity;
807
808 #[inline]
809 fn next(&mut self) -> Option<MetaCommunity> {
810 loop {
811 match &mut self.cur_kind {
812 ActiveCommunityAttr::Plain(words) => {
813 if let Some((first, rest)) = words.split_first() {
814 *words = rest;
815 return Some(MetaCommunity::Plain(
816 crate::parser::bgp::attributes::decode_regular_community(first.get()),
817 ));
818 }
819 }
820 ActiveCommunityAttr::Extended(bytes) => {
821 if bytes.len() >= 8 {
822 let mut chunk = &bytes[..8];
823 *bytes = &bytes[8..];
824 return Some(MetaCommunity::Extended(
825 crate::parser::bgp::attributes::parse_extended_community_one(
826 &mut chunk,
827 )
828 .unwrap_or(ExtendedCommunity::Raw([0u8; 8])),
829 ));
830 }
831 }
832 ActiveCommunityAttr::Ipv6Extended(bytes) => {
833 if bytes.len() >= 20 {
834 let mut chunk = &bytes[..20];
835 *bytes = &bytes[20..];
836 if let Ok(item) =
837 crate::parser::bgp::attributes::parse_ipv6_extended_community_one(
838 &mut chunk,
839 )
840 {
841 return Some(MetaCommunity::Ipv6Extended(item));
842 }
843 }
844 }
845 ActiveCommunityAttr::Large(words) => {
846 if words.len() >= 3 {
847 let ga = words[0].get();
848 let d0 = words[1].get();
849 let d1 = words[2].get();
850 *words = &words[3..];
851 return Some(MetaCommunity::Large(LargeCommunity::new(ga, [d0, d1])));
852 }
853 }
854 ActiveCommunityAttr::None => {}
855 }
856
857 self.cur_kind = ActiveCommunityAttr::None;
858 let (code, val, next_rest) = next_attr_tlv(self.rest_attrs)?;
859 self.rest_attrs = next_rest;
860 match AttrType::from(code) {
861 AttrType::COMMUNITIES if val.len().is_multiple_of(4) => {
862 self.cur_kind = ActiveCommunityAttr::Plain(bytes_as_be_u32_words(val));
863 }
864 AttrType::EXTENDED_COMMUNITIES if val.len().is_multiple_of(8) => {
865 self.cur_kind = ActiveCommunityAttr::Extended(val);
866 }
867 AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
868 if val.len().is_multiple_of(20) =>
869 {
870 self.cur_kind = ActiveCommunityAttr::Ipv6Extended(val);
871 }
872 AttrType::LARGE_COMMUNITIES if val.len().is_multiple_of(12) => {
873 self.cur_kind = ActiveCommunityAttr::Large(bytes_as_be_u32_words(val));
874 }
875 _ => {}
876 }
877 }
878 }
879}