1use super::*;
6
7#[derive(Clone)]
14pub struct ElemRef<'a> {
15 attr_bytes: &'a [u8],
16 peer_ip: IpAddr,
17 peer_asn: Asn,
18 peer_bgp_id: Option<BgpIdentifier>,
19 as_path_slot: Cell<u64>,
20 timestamp: f64,
21 prefix: IpNet,
22 path_id: Option<u32>,
24 flags: u8,
25 elem_type: ElemType,
26 update_next_hop: Option<IpAddr>,
28 truncated: Option<(u8, u16, u32)>,
31 warned_truncation: Cell<bool>,
32}
33
34impl std::fmt::Debug for ElemRef<'_> {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 f.debug_struct("ElemRef")
39 .field("elem_type", &self.elem_type)
40 .field("timestamp", &self.timestamp)
41 .field("peer_ip", &self.peer_ip)
42 .field("peer_asn", &self.peer_asn)
43 .field("prefix", &self.prefix())
44 .finish_non_exhaustive()
45 }
46}
47
48const _: () = assert!(!std::mem::needs_drop::<ElemRef<'static>>());
50const _: () = assert!(!std::mem::needs_drop::<AsPathView<'static>>());
51const _: () = assert!(!std::mem::needs_drop::<AsnsView<'static>>());
52const _: () = assert!(!std::mem::needs_drop::<CommunitiesView<'static>>());
53const _: () = assert!(std::mem::size_of::<ElemRef<'static>>() <= 128);
55
56impl<'a> ElemRef<'a> {
57 #[inline]
58 pub(super) fn new(
59 prefix: IpNet,
60 peer: &'a Peer,
61 originated_time: u32,
62 flags: u8,
63 attr_bytes: &'a [u8],
64 truncated: Option<(u8, u16, u32)>,
65 ) -> Self {
66 Self {
67 attr_bytes,
68 peer_ip: peer.peer_ip,
69 peer_asn: peer.peer_asn,
70 peer_bgp_id: Some(peer.peer_bgp_id),
71 as_path_slot: Cell::new(SLOT_UNSCANNED),
72 timestamp: originated_time as f64,
73 prefix,
74 path_id: None,
75 flags,
76 elem_type: ElemType::ANNOUNCE,
77 update_next_hop: None,
78 truncated,
79 warned_truncation: Cell::new(false),
80 }
81 }
82
83 #[inline]
85 pub(super) fn new_update(
86 entry: &UpdateEntry,
87 peer_ip: IpAddr,
88 peer_asn: Asn,
89 timestamp: f64,
90 attr_bytes: &'a [u8],
91 next_hop: Option<IpAddr>,
92 ) -> Self {
93 Self {
94 attr_bytes,
95 peer_ip,
96 peer_asn,
97 peer_bgp_id: None,
98 as_path_slot: Cell::new(SLOT_UNSCANNED),
99 timestamp,
100 prefix: entry.prefix.prefix,
101 path_id: entry.prefix.path_id,
102 flags: entry.flags | FLAG_UPDATE,
103 elem_type: entry.elem_type,
104 update_next_hop: next_hop,
105 truncated: None,
107 warned_truncation: Cell::new(false),
108 }
109 }
110
111 #[inline]
112 fn afi(&self) -> Afi {
113 if (self.flags & FLAG_AFI_IPV6) != 0 {
114 Afi::Ipv6
115 } else {
116 Afi::Ipv4
117 }
118 }
119
120 #[inline]
121 fn safi(&self) -> Safi {
122 if (self.flags & FLAG_SAFI_MULTICAST) != 0 {
123 Safi::Multicast
124 } else {
125 Safi::Unicast
126 }
127 }
128
129 #[inline]
131 fn next_hop_afi(&self) -> Afi {
132 if (self.flags & FLAG_UPDATE) != 0 {
133 Afi::Ipv4
134 } else {
135 self.afi()
136 }
137 }
138
139 #[inline]
140 fn is_add_path(&self) -> bool {
141 (self.flags & FLAG_ADD_PATH) != 0
142 }
143
144 #[inline]
146 fn note_truncation(&self) {
147 if let Some((code, declared, available)) = self.truncated {
148 self.warn_truncated_attr_once(code, declared as usize, available as usize);
149 }
150 }
151
152 #[cold]
153 #[inline(never)]
154 fn warn_truncated_attr_once(&self, raw_code: u8, attr_length: usize, bytes_left: usize) {
155 if (self.flags & FLAG_UPDATE) != 0 {
158 return;
159 }
160 if !self.warned_truncation.replace(true) {
161 let attr_type = AttrType::from(raw_code);
162 warn!(
163 "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message",
164 attr_type, attr_length, bytes_left
165 );
166 }
167 }
168
169 #[cold]
170 #[inline(never)]
171 fn scan_merged_as_paths(&self) -> (&'a [u8], &'a [u8]) {
172 let bytes = self.attr_bytes;
173 let mut pos = 0usize;
174 let mut p2: &'a [u8] = &[];
175 let mut p4: &'a [u8] = &[];
176
177 loop {
178 match step_attr(bytes, pos) {
179 AttrStep::End => break,
180 AttrStep::Truncated {
181 code,
182 declared,
183 available,
184 } => {
185 self.warn_truncated_attr_once(code, declared, available);
186 break;
187 }
188 AttrStep::Attr {
189 code,
190 value_start: val_start,
191 value_end: val_end,
192 } => {
193 if code == u8::from(AttrType::AS_PATH) {
194 let slice = &bytes[val_start..val_end];
195 if validate_as_path_wire(slice) {
196 p2 = slice;
197 }
198 } else if code == u8::from(AttrType::AS4_PATH) {
199 let slice = &bytes[val_start..val_end];
200 if validate_as_path_wire(slice) {
201 p4 = slice;
202 }
203 }
204 pos = val_end;
205 }
206 }
207 }
208 (p2, p4)
209 }
210
211 #[inline]
212 fn resolve_as_path_source(&self) -> AsPathSource<'a> {
213 let cached = self.as_path_slot.get();
214 if cached != SLOT_UNSCANNED {
215 return match cached {
216 SLOT_ABSENT => AsPathSource::Absent,
217 SLOT_MERGED => {
218 let (as_path, as4_path) = self.scan_merged_as_paths();
219 AsPathSource::Merged { as_path, as4_path }
220 }
221 packed => {
222 let start = (packed & 0xFFFF) as usize;
223 let len = ((packed >> 16) & 0xFFFF) as usize;
224 AsPathSource::Single(&self.attr_bytes[start..start + len])
225 }
226 };
227 }
228
229 let bytes = self.attr_bytes;
230 let mut pos = 0usize;
231 let mut as_path_span: Option<(u16, u16)> = None;
232 let mut as4_path_span: Option<(u16, u16)> = None;
233
234 loop {
235 match step_attr(bytes, pos) {
236 AttrStep::End => break,
237 AttrStep::Truncated {
238 code,
239 declared,
240 available,
241 } => {
242 self.warn_truncated_attr_once(code, declared, available);
243 break;
244 }
245 AttrStep::Attr {
246 code,
247 value_start: val_start,
248 value_end: val_end,
249 } => {
250 if code == u8::from(AttrType::AS_PATH) {
251 if validate_as_path_wire(&bytes[val_start..val_end]) {
252 as_path_span = Some((val_start as u16, (val_end - val_start) as u16));
253 }
254 } else if code == u8::from(AttrType::AS4_PATH)
255 && validate_as_path_wire(&bytes[val_start..val_end])
256 {
257 as4_path_span = Some((val_start as u16, (val_end - val_start) as u16));
258 }
259 pos = val_end;
260 }
261 }
262 }
263
264 match (as_path_span, as4_path_span) {
265 (None, None) => {
266 self.as_path_slot.set(SLOT_ABSENT);
267 AsPathSource::Absent
268 }
269 (Some((s, l)), None) | (None, Some((s, l))) => {
270 let packed = (s as u64) | ((l as u64) << 16);
271 self.as_path_slot.set(packed);
272 AsPathSource::Single(&bytes[s as usize..s as usize + l as usize])
273 }
274 (Some((s1, l1)), Some((s2, l2))) => {
275 let p1 = &bytes[s1 as usize..s1 as usize + l1 as usize];
276 let p2 = &bytes[s2 as usize..s2 as usize + l2 as usize];
277 if wire_route_len(p1) < wire_route_len(p2) {
279 let packed = (s1 as u64) | ((l1 as u64) << 16);
280 self.as_path_slot.set(packed);
281 AsPathSource::Single(p1)
282 } else {
283 self.as_path_slot.set(SLOT_MERGED);
284 AsPathSource::Merged {
285 as_path: p1,
286 as4_path: p2,
287 }
288 }
289 }
290 }
291 }
292
293 #[inline]
295 pub fn prefix(&self) -> NetworkPrefix {
296 NetworkPrefix::new(self.prefix, self.path_id)
297 }
298
299 #[inline]
301 pub fn peer_ip(&self) -> IpAddr {
302 self.peer_ip
303 }
304
305 #[inline]
307 pub fn peer_asn(&self) -> Asn {
308 self.peer_asn
309 }
310
311 #[inline]
313 pub fn as_path(&self) -> AsPathView<'a> {
314 AsPathView {
315 source: self.resolve_as_path_source(),
316 }
317 }
318
319 #[inline]
321 pub fn origin_asns(&self) -> AsnsView<'a> {
322 match self.resolve_as_path_source() {
323 AsPathSource::Absent => AsnsView {
324 repr: OriginsRepr::Absent,
325 },
326 AsPathSource::Single(wire) => single_wire_origins(wire),
327 AsPathSource::Merged { as_path, as4_path } => merged_wire_origins(as_path, as4_path),
328 }
329 }
330
331 #[inline]
333 pub fn communities(&self) -> CommunitiesView<'a> {
334 self.note_truncation();
335 CommunitiesView {
336 attr_bytes: self.attr_bytes,
337 }
338 }
339
340 pub fn next_hop(&self) -> Option<IpAddr> {
346 if self.elem_type == ElemType::WITHDRAW {
348 return None;
349 }
350 if (self.flags & FLAG_UPDATE) != 0 {
351 return self.update_next_hop;
352 }
353 let bytes = self.attr_bytes;
354 let afi = self.afi();
355 let safi = self.safi();
356 let is_add_path = self.is_add_path();
357 let mut pos = 0usize;
358 let mut next_hop: Option<IpAddr> = None;
359 let mut mp_next_hop: Option<IpAddr> = None;
360
361 loop {
362 match step_attr(bytes, pos) {
363 AttrStep::End => break,
364 AttrStep::Truncated {
365 code,
366 declared,
367 available,
368 } => {
369 self.warn_truncated_attr_once(code, declared, available);
370 break;
371 }
372 AttrStep::Attr {
373 code,
374 value_start: val_start,
375 value_end: val_end,
376 } => {
377 if code == u8::from(AttrType::NEXT_HOP) {
378 let mut val = &bytes[val_start..val_end];
379 if let Ok(addr) = val.read_address(&self.next_hop_afi()) {
380 next_hop = Some(addr);
381 }
382 } else if code == u8::from(AttrType::MP_REACHABLE_NLRI) {
383 if let Ok(address) = mp_reach_next_hop(
386 &bytes[val_start..val_end],
387 self.prefix(),
388 afi,
389 safi,
390 is_add_path,
391 (self.flags & FLAG_UPDATE) != 0,
392 ) {
393 mp_next_hop = address;
394 }
395 }
396 pos = val_end;
397 }
398 }
399 }
400
401 next_hop.or(mp_next_hop)
402 }
403
404 pub fn med(&self) -> Option<u32> {
407 if self.elem_type == ElemType::WITHDRAW {
408 return None;
409 }
410 Some(
411 self.scan_u32_attr(u8::from(AttrType::MULTI_EXIT_DISCRIMINATOR))
412 .unwrap_or(0),
413 )
414 }
415
416 pub fn local_pref(&self) -> Option<u32> {
420 if self.elem_type == ElemType::WITHDRAW {
421 return None;
422 }
423 Some(
424 self.scan_u32_attr(u8::from(AttrType::LOCAL_PREFERENCE))
425 .unwrap_or(0),
426 )
427 }
428
429 pub(crate) fn attrs_bytes(&self) -> &'a [u8] {
431 self.attr_bytes
432 }
433
434 pub fn to_bgp_elem(&self) -> BgpElem {
437 self.note_truncation();
438 let bytes = self.attr_bytes;
439 let afi = self.afi();
440 let safi = self.safi();
441 let is_add_path = self.is_add_path();
442
443 let mut origin: Option<Origin> = None;
444 let mut atomic = false;
445 let mut aggregator: Option<(Asn, BgpIdentifier)> = None;
446 let mut only_to_customer: Option<Asn> = None;
447 let mut med: Option<u32> = None;
448 let mut local_pref: Option<u32> = None;
449 let from_update = (self.flags & FLAG_UPDATE) != 0;
451 let mut next_hop: Option<IpAddr> = self.update_next_hop;
452 let mut mp_next_hop: Option<IpAddr> = None;
453 let mut as_path_wire: Option<&[u8]> = None;
454 let mut as4_path_wire: Option<&[u8]> = None;
455 let mut communities: Vec<MetaCommunity> = Vec::new();
456 let mut unknown: Vec<AttrRaw> = Vec::new();
457 let mut deprecated: Vec<AttrRaw> = Vec::new();
458
459 let mut pos = 0usize;
460 loop {
461 match step_attr(bytes, pos) {
462 AttrStep::End => break,
463 AttrStep::Truncated {
464 code,
465 declared,
466 available,
467 } => {
468 self.warn_truncated_attr_once(code, declared, available);
469 break;
470 }
471 AttrStep::Attr {
472 code,
473 value_start: val_start,
474 value_end: val_end,
475 } => {
476 let val = &bytes[val_start..val_end];
477 let tlv_start = pos;
478 pos = val_end;
479
480 if get_deprecated_attr_type(code).is_some() {
481 deprecated.push(AttrRaw {
482 code,
483 bytes: Bytes::copy_from_slice(val),
484 });
485 continue;
486 }
487
488 if crate::parser::bgp::attributes::is_raw_retained_attr(AttrType::from(code)) {
489 unknown.push(AttrRaw {
490 code,
491 bytes: Bytes::copy_from_slice(val),
492 });
493 continue;
494 }
495 let mut undecoded = false;
498 match AttrType::from(code) {
499 AttrType::ORIGIN => {
502 match val.first().and_then(|value| Origin::try_from(*value).ok()) {
503 Some(decoded) => origin = Some(decoded),
504 None => undecoded = true,
505 }
506 }
507 AttrType::AS_PATH => {
508 if validate_as_path_wire(val) {
509 as_path_wire = Some(val);
510 } else {
511 undecoded = true;
512 }
513 }
514 AttrType::AS4_PATH => {
515 if validate_as_path_wire(val) {
516 as4_path_wire = Some(val);
517 } else {
518 undecoded = true;
519 }
520 }
521 AttrType::NEXT_HOP if from_update => {
522 if crate::parser::bgp::attributes::attr_03_next_hop::parse_next_hop(
525 val, &None,
526 )
527 .is_err()
528 {
529 undecoded = true;
530 }
531 }
532 AttrType::NEXT_HOP => {
533 let mut value = val;
534 match value.read_address(&self.next_hop_afi()) {
535 Ok(address) => next_hop = Some(address),
536 Err(_) => undecoded = true,
537 }
538 }
539 AttrType::MULTI_EXIT_DISCRIMINATOR => {
540 let mut value = val;
541 match value.read_u32() {
542 Ok(number) => med = Some(number),
543 Err(_) => undecoded = true,
544 }
545 }
546 AttrType::LOCAL_PREFERENCE => {
547 let mut value = val;
548 match value.read_u32() {
549 Ok(number) => local_pref = Some(number),
550 Err(_) => undecoded = true,
551 }
552 }
553 AttrType::ATOMIC_AGGREGATE => atomic = true,
554 AttrType::ORIGINATOR_ID => {
557 if val.len() != 4 {
558 undecoded = true;
559 }
560 }
561 AttrType::CLUSTER_LIST => {
562 if !val.len().is_multiple_of(4) {
563 undecoded = true;
564 }
565 }
566 AttrType::AGGREGATOR | AttrType::AS4_AGGREGATOR => {
567 match crate::parser::bgp::attributes::parse_aggregator_slice(
568 bytes::Bytes::copy_from_slice(val),
569 &AsnLength::Bits32,
570 )
571 .ok()
572 {
573 Some(decoded) => aggregator = Some(decoded),
574 None => undecoded = true,
575 }
576 }
577 AttrType::COMMUNITIES
582 | AttrType::EXTENDED_COMMUNITIES
583 | AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
584 | AttrType::LARGE_COMMUNITIES => {
585 let input = bytes::Bytes::copy_from_slice(val);
586 let decoded = match AttrType::from(code) {
587 AttrType::COMMUNITIES => {
588 crate::parser::bgp::attributes::parse_communities_attribute(input).map(
589 |value| match value {
590 crate::models::AttributeValue::Communities(v) => {
591 communities.extend(v.into_iter().map(MetaCommunity::Plain));
592 true
593 }
594 _ => false,
595 },
596 )
597 }
598 AttrType::EXTENDED_COMMUNITIES => {
599 crate::parser::bgp::attributes::parse_extended_communities_attribute(
600 input,
601 )
602 .map(|value| match value {
603 crate::models::AttributeValue::ExtendedCommunities(v) => {
604 communities
605 .extend(v.into_iter().map(MetaCommunity::Extended));
606 true
607 }
608 _ => false,
609 })
610 }
611 AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES => crate::parser::bgp::attributes::parse_ipv6_extended_communities_attribute(input)
612 .map(|value| match value {
613 crate::models::AttributeValue::Ipv6AddressSpecificExtendedCommunities(v) => {
614 communities
615 .extend(v.into_iter().map(MetaCommunity::Ipv6Extended));
616 true
617 }
618 _ => false,
619 }),
620 _ => crate::parser::bgp::attributes::parse_large_communities_attribute(input)
621 .map(|value| match value {
622 crate::models::AttributeValue::LargeCommunities(v) => {
623 communities.extend(v.into_iter().map(MetaCommunity::Large));
624 true
625 }
626 _ => false,
627 }),
628 };
629 if !decoded.unwrap_or(false) {
630 undecoded = true;
631 }
632 }
633 AttrType::ONLY_TO_CUSTOMER => {
634 if val.len() >= 4 {
635 only_to_customer = Some(Asn::new_32bit(u32::from_be_bytes([
636 val[0], val[1], val[2], val[3],
637 ])));
638 } else {
639 undecoded = true;
640 }
641 }
642 AttrType::MP_REACHABLE_NLRI if from_update => {
643 if mp_reach_next_hop(val, self.prefix(), afi, safi, is_add_path, true)
644 .is_err()
645 {
646 undecoded = true;
647 }
648 }
649 AttrType::MP_REACHABLE_NLRI => {
650 match mp_reach_next_hop(
651 val,
652 self.prefix(),
653 afi,
654 safi,
655 is_add_path,
656 false,
657 ) {
658 Ok(address) => mp_next_hop = address,
659 Err(()) => undecoded = true,
660 }
661 }
662 AttrType::TRAFFIC_ENGINEERING => {
666 if crate::parser::bgp::attributes::parse_traffic_engineering(
667 bytes::Bytes::copy_from_slice(val),
668 )
669 .is_err()
670 {
671 undecoded = true;
672 }
673 }
674 AttrType::Unknown(_) => unknown.push(AttrRaw {
675 code,
676 bytes: Bytes::copy_from_slice(val),
677 }),
678 _ => {
681 let tlv = &bytes[tlv_start..val_end];
685 let own_prefix = [self.prefix()];
686 let (afi, safi, prefixes) = if from_update {
687 (None, None, None)
688 } else {
689 (Some(afi), Some(safi), Some(&own_prefix[..]))
690 };
691 let parsed = crate::parser::bgp::attributes::parse_attributes(
692 bytes::Bytes::copy_from_slice(tlv),
693 &AsnLength::Bits32,
694 is_add_path,
695 afi,
696 safi,
697 prefixes,
698 );
699 let raw = match parsed {
700 Ok(attributes) => attributes.inner.iter().any(|attribute| {
701 matches!(
702 attribute.value,
703 crate::models::AttributeValue::Raw(_)
704 | crate::models::AttributeValue::Unknown(_)
705 )
706 }),
707 Err(_) => true,
708 };
709 if raw {
710 undecoded = true;
711 }
712 }
713 }
714 if undecoded {
715 unknown.push(AttrRaw {
716 code,
717 bytes: Bytes::copy_from_slice(val),
718 });
719 }
720 }
721 }
722 }
723
724 let source = match (as_path_wire, as4_path_wire) {
726 (None, None) => AsPathSource::Absent,
727 (Some(path), None) => AsPathSource::Single(path),
728 (None, Some(path)) => AsPathSource::Single(path),
729 (Some(path), Some(as4_path)) => {
730 if wire_route_len(path) < wire_route_len(as4_path) {
731 AsPathSource::Single(path)
732 } else {
733 AsPathSource::Merged {
734 as_path: path,
735 as4_path,
736 }
737 }
738 }
739 };
740 let as_path = AsPathView { source }.to_as_path();
741 let origin_asns = match source {
742 AsPathSource::Absent => None,
743 AsPathSource::Single(wire) => Some(single_wire_origins(wire).to_vec()),
744 AsPathSource::Merged { as_path, as4_path } => {
745 Some(merged_wire_origins(as_path, as4_path).to_vec())
746 }
747 };
748
749 let is_withdrawal = self.elem_type() == ElemType::WITHDRAW;
750 BgpElem {
751 timestamp: self.timestamp(),
752 elem_type: self.elem_type(),
753 peer_ip: self.peer_ip,
754 peer_asn: self.peer_asn,
755 peer_bgp_id: self.peer_bgp_id,
756 prefix: NetworkPrefix {
757 prefix: self.prefix,
758 path_id: self.path_id,
759 },
760 next_hop: if is_withdrawal {
762 None
763 } else {
764 next_hop.or(mp_next_hop)
765 },
766 as_path,
767 origin,
768 origin_asns,
769 local_pref: (!is_withdrawal).then(|| local_pref.unwrap_or(0)),
772 med: (!is_withdrawal).then(|| med.unwrap_or(0)),
773 communities: (!communities.is_empty()).then_some(communities),
774 atomic,
775 aggr_asn: aggregator.map(|value| value.0),
776 aggr_ip: aggregator.map(|value| value.1),
777 only_to_customer,
778 unknown: (!unknown.is_empty()).then_some(unknown),
779 deprecated: (!deprecated.is_empty()).then_some(deprecated),
780 }
781 }
782
783 #[inline]
786 pub fn timestamp(&self) -> f64 {
787 self.timestamp
788 }
789
790 #[inline]
792 pub fn elem_type(&self) -> ElemType {
793 self.elem_type
794 }
795
796 fn scan_u32_attr(&self, target_code: u8) -> Option<u32> {
797 let bytes = self.attr_bytes;
798 let mut pos = 0usize;
799 let mut found = None;
800
801 loop {
802 match step_attr(bytes, pos) {
803 AttrStep::End => break,
804 AttrStep::Truncated {
805 code,
806 declared,
807 available,
808 } => {
809 self.warn_truncated_attr_once(code, declared, available);
810 break;
811 }
812 AttrStep::Attr {
813 code,
814 value_start: val_start,
815 value_end: val_end,
816 } => {
817 if code == target_code && val_end - val_start >= 4 {
818 found = Some(u32::from_be_bytes([
819 bytes[val_start],
820 bytes[val_start + 1],
821 bytes[val_start + 2],
822 bytes[val_start + 3],
823 ]));
824 }
825 pos = val_end;
826 }
827 }
828 }
829 found
830 }
831}