1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! One borrowed element inside a [`RecordElems`](super::RecordElems) batch.
//!
//! Every accessor reads the record's own bytes; the type itself owns nothing.
use super::*;
/// Borrowed view over a single BGP element inside a [`RecordElems`] batch.
///
/// Attributes are decoded lazily from `attr_bytes` when their accessors are called. The AS path and
/// community accessors do not allocate; `next_hop()` allocates for a dump entry whose next hop comes
/// from `MP_REACH_NLRI`, and materialising an element (`to_bgp_elem`) allocates, since the result
/// owns its AS path and communities.
#[derive(Clone)]
pub struct ElemRef<'a> {
attr_bytes: &'a [u8],
peer_ip: IpAddr,
peer_asn: Asn,
peer_bgp_id: Option<BgpIdentifier>,
as_path_slot: Cell<u64>,
timestamp: f64,
prefix: IpNet,
/// The ADD-PATH identifier the announcement carried, if any. A dump's entry has none.
path_id: Option<u32>,
flags: u8,
elem_type: ElemType,
/// The next hop an update's elements share, decoded once for the record.
update_next_hop: Option<IpAddr>,
/// The attribute the block ended at, when its value ran past the end: reported once, the first
/// time this element needs its attributes.
truncated: Option<(u8, u16, u32)>,
warned_truncation: Cell<bool>,
}
impl std::fmt::Debug for ElemRef<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The derived form printed the raw attribute bytes and the lazily filled cache slot, which
// changed between two calls on the same element.
f.debug_struct("ElemRef")
.field("elem_type", &self.elem_type)
.field("timestamp", &self.timestamp)
.field("peer_ip", &self.peer_ip)
.field("peer_asn", &self.peer_asn)
.field("prefix", &self.prefix())
.finish_non_exhaustive()
}
}
// Structural invariant: none of the borrowed view types own heap allocations or require Drop.
const _: () = assert!(!std::mem::needs_drop::<ElemRef<'static>>());
const _: () = assert!(!std::mem::needs_drop::<AsPathView<'static>>());
const _: () = assert!(!std::mem::needs_drop::<AsnsView<'static>>());
const _: () = assert!(!std::mem::needs_drop::<CommunitiesView<'static>>());
// A borrowed element carries its peer inline so one type serves both dumps and updates.
const _: () = assert!(std::mem::size_of::<ElemRef<'static>>() <= 128);
impl<'a> ElemRef<'a> {
#[inline]
pub(super) fn new(
prefix: IpNet,
peer: &'a Peer,
originated_time: u32,
flags: u8,
attr_bytes: &'a [u8],
truncated: Option<(u8, u16, u32)>,
) -> Self {
Self {
attr_bytes,
peer_ip: peer.peer_ip,
peer_asn: peer.peer_asn,
peer_bgp_id: Some(peer.peer_bgp_id),
as_path_slot: Cell::new(SLOT_UNSCANNED),
timestamp: originated_time as f64,
prefix,
path_id: None,
flags,
elem_type: ElemType::ANNOUNCE,
update_next_hop: None,
truncated,
warned_truncation: Cell::new(false),
}
}
/// An element of a `BGP4MP` update: the peer and the time come from the record header.
#[inline]
pub(super) fn new_update(
entry: &UpdateEntry,
peer_ip: IpAddr,
peer_asn: Asn,
timestamp: f64,
attr_bytes: &'a [u8],
next_hop: Option<IpAddr>,
) -> Self {
Self {
attr_bytes,
peer_ip,
peer_asn,
peer_bgp_id: None,
as_path_slot: Cell::new(SLOT_UNSCANNED),
timestamp,
prefix: entry.prefix.prefix,
path_id: entry.prefix.path_id,
flags: entry.flags | FLAG_UPDATE,
elem_type: entry.elem_type,
update_next_hop: next_hop,
// An update's elements share one attribute block, which the record-level walk reports.
truncated: None,
warned_truncation: Cell::new(false),
}
}
#[inline]
fn afi(&self) -> Afi {
if (self.flags & FLAG_AFI_IPV6) != 0 {
Afi::Ipv6
} else {
Afi::Ipv4
}
}
#[inline]
fn safi(&self) -> Safi {
if (self.flags & FLAG_SAFI_MULTICAST) != 0 {
Safi::Multicast
} else {
Safi::Unicast
}
}
/// The family `NEXT_HOP` is encoded with: the record's for a dump, IPv4 for an update.
#[inline]
fn next_hop_afi(&self) -> Afi {
if (self.flags & FLAG_UPDATE) != 0 {
Afi::Ipv4
} else {
self.afi()
}
}
#[inline]
fn is_add_path(&self) -> bool {
(self.flags & FLAG_ADD_PATH) != 0
}
/// Report the attribute this element's block ended at, once.
#[inline]
fn note_truncation(&self) {
if let Some((code, declared, available)) = self.truncated {
self.warn_truncated_attr_once(code, declared as usize, available as usize);
}
}
#[cold]
#[inline(never)]
fn warn_truncated_attr_once(&self, raw_code: u8, attr_length: usize, bytes_left: usize) {
// An update's elements all share one attribute block, which the record-level walk reports;
// warning per element would repeat the same line for every prefix the record carries.
if (self.flags & FLAG_UPDATE) != 0 {
return;
}
if !self.warned_truncation.replace(true) {
let attr_type = AttrType::from(raw_code);
warn!(
"{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message",
attr_type, attr_length, bytes_left
);
}
}
#[cold]
#[inline(never)]
fn scan_merged_as_paths(&self) -> (&'a [u8], &'a [u8]) {
let bytes = self.attr_bytes;
let mut pos = 0usize;
let mut p2: &'a [u8] = &[];
let mut p4: &'a [u8] = &[];
loop {
match step_attr(bytes, pos) {
AttrStep::End => break,
AttrStep::Truncated {
code,
declared,
available,
} => {
self.warn_truncated_attr_once(code, declared, available);
break;
}
AttrStep::Attr {
code,
value_start: val_start,
value_end: val_end,
} => {
if code == u8::from(AttrType::AS_PATH) {
let slice = &bytes[val_start..val_end];
if validate_as_path_wire(slice) {
p2 = slice;
}
} else if code == u8::from(AttrType::AS4_PATH) {
let slice = &bytes[val_start..val_end];
if validate_as_path_wire(slice) {
p4 = slice;
}
}
pos = val_end;
}
}
}
(p2, p4)
}
#[inline]
fn resolve_as_path_source(&self) -> AsPathSource<'a> {
let cached = self.as_path_slot.get();
if cached != SLOT_UNSCANNED {
return match cached {
SLOT_ABSENT => AsPathSource::Absent,
SLOT_MERGED => {
let (as_path, as4_path) = self.scan_merged_as_paths();
AsPathSource::Merged { as_path, as4_path }
}
packed => {
let start = (packed & 0xFFFF) as usize;
let len = ((packed >> 16) & 0xFFFF) as usize;
AsPathSource::Single(&self.attr_bytes[start..start + len])
}
};
}
let bytes = self.attr_bytes;
let mut pos = 0usize;
let mut as_path_span: Option<(u16, u16)> = None;
let mut as4_path_span: Option<(u16, u16)> = None;
loop {
match step_attr(bytes, pos) {
AttrStep::End => break,
AttrStep::Truncated {
code,
declared,
available,
} => {
self.warn_truncated_attr_once(code, declared, available);
break;
}
AttrStep::Attr {
code,
value_start: val_start,
value_end: val_end,
} => {
if code == u8::from(AttrType::AS_PATH) {
if validate_as_path_wire(&bytes[val_start..val_end]) {
as_path_span = Some((val_start as u16, (val_end - val_start) as u16));
}
} else if code == u8::from(AttrType::AS4_PATH)
&& validate_as_path_wire(&bytes[val_start..val_end])
{
as4_path_span = Some((val_start as u16, (val_end - val_start) as u16));
}
pos = val_end;
}
}
}
match (as_path_span, as4_path_span) {
(None, None) => {
self.as_path_slot.set(SLOT_ABSENT);
AsPathSource::Absent
}
(Some((s, l)), None) | (None, Some((s, l))) => {
let packed = (s as u64) | ((l as u64) << 16);
self.as_path_slot.set(packed);
AsPathSource::Single(&bytes[s as usize..s as usize + l as usize])
}
(Some((s1, l1)), Some((s2, l2))) => {
let p1 = &bytes[s1 as usize..s1 as usize + l1 as usize];
let p2 = &bytes[s2 as usize..s2 as usize + l2 as usize];
// Per RFC 6793 ยง4.2.3, when AS_PATH is shorter than AS4_PATH, AS4_PATH is ignored.
if wire_route_len(p1) < wire_route_len(p2) {
let packed = (s1 as u64) | ((l1 as u64) << 16);
self.as_path_slot.set(packed);
AsPathSource::Single(p1)
} else {
self.as_path_slot.set(SLOT_MERGED);
AsPathSource::Merged {
as_path: p1,
as4_path: p2,
}
}
}
}
}
/// Returns the prefix this element announces, with the ADD-PATH identifier it carried.
#[inline]
pub fn prefix(&self) -> NetworkPrefix {
NetworkPrefix::new(self.prefix, self.path_id)
}
/// Returns the IP address of the peer that exported this RIB entry.
#[inline]
pub fn peer_ip(&self) -> IpAddr {
self.peer_ip
}
/// Returns the AS number of the peer that exported this RIB entry.
#[inline]
pub fn peer_asn(&self) -> Asn {
self.peer_asn
}
/// Returns a zero-allocation borrowed view over the entry's effective `AS_PATH`.
#[inline]
pub fn as_path(&self) -> AsPathView<'a> {
AsPathView {
source: self.resolve_as_path_source(),
}
}
/// Returns a zero-allocation view over the originating ASNs of the effective `AS_PATH`.
#[inline]
pub fn origin_asns(&self) -> AsnsView<'a> {
match self.resolve_as_path_source() {
AsPathSource::Absent => AsnsView {
repr: OriginsRepr::Absent,
},
AsPathSource::Single(wire) => single_wire_origins(wire),
AsPathSource::Merged { as_path, as4_path } => merged_wire_origins(as_path, as4_path),
}
}
/// Returns a zero-allocation view over the entry's standard, extended, and large communities.
#[inline]
pub fn communities(&self) -> CommunitiesView<'a> {
self.note_truncation();
CommunitiesView {
attr_bytes: self.attr_bytes,
}
}
/// Returns the effective next-hop address (`NEXT_HOP`, or `MP_REACH_NLRI`'s global next hop).
///
/// An update's elements read the address their record decoded once. A dump entry decodes
/// `MP_REACH_NLRI` here, through the owned NLRI parser, which allocates for the copied body and
/// the prefix list it validates.
pub fn next_hop(&self) -> Option<IpAddr> {
// A withdrawal carries no attributes, so it has no next hop on the owned path either.
if self.elem_type == ElemType::WITHDRAW {
return None;
}
if (self.flags & FLAG_UPDATE) != 0 {
return self.update_next_hop;
}
let bytes = self.attr_bytes;
let afi = self.afi();
let safi = self.safi();
let is_add_path = self.is_add_path();
let mut pos = 0usize;
let mut next_hop: Option<IpAddr> = None;
let mut mp_next_hop: Option<IpAddr> = None;
loop {
match step_attr(bytes, pos) {
AttrStep::End => break,
AttrStep::Truncated {
code,
declared,
available,
} => {
self.warn_truncated_attr_once(code, declared, available);
break;
}
AttrStep::Attr {
code,
value_start: val_start,
value_end: val_end,
} => {
if code == u8::from(AttrType::NEXT_HOP) {
let mut val = &bytes[val_start..val_end];
if let Ok(addr) = val.read_address(&self.next_hop_afi()) {
next_hop = Some(addr);
}
} else if code == u8::from(AttrType::MP_REACHABLE_NLRI) {
// A body the owned parser rejects becomes raw bytes there and leaves the earlier
// value in place, so the earlier next hop stands here too.
if let Ok(address) = mp_reach_next_hop(
&bytes[val_start..val_end],
self.prefix(),
afi,
safi,
is_add_path,
(self.flags & FLAG_UPDATE) != 0,
) {
mp_next_hop = address;
}
}
pos = val_end;
}
}
}
next_hop.or(mp_next_hop)
}
/// Returns the Multi-Exit Discriminator (`MULTI_EXIT_DISCRIMINATOR`), matching
/// [`BgpElem::med`](crate::BgpElem::med) (`Some(0)` on RIB announcements without MED).
pub fn med(&self) -> Option<u32> {
if self.elem_type == ElemType::WITHDRAW {
return None;
}
Some(
self.scan_u32_attr(u8::from(AttrType::MULTI_EXIT_DISCRIMINATOR))
.unwrap_or(0),
)
}
/// Returns the Local Preference (`LOCAL_PREFERENCE`), matching
/// [`BgpElem::local_pref`](crate::BgpElem::local_pref) (`Some(0)` on RIB announcements without
/// `LOCAL_PREFERENCE`).
pub fn local_pref(&self) -> Option<u32> {
if self.elem_type == ElemType::WITHDRAW {
return None;
}
Some(
self.scan_u32_attr(u8::from(AttrType::LOCAL_PREFERENCE))
.unwrap_or(0),
)
}
/// This entry's attribute block, for the predicates that can decide an entry from bytes.
pub(crate) fn attrs_bytes(&self) -> &'a [u8] {
self.attr_bytes
}
/// Materialise this entry as an owned [`BgpElem`], for the fields the borrowed accessors do
/// not expose.
pub fn to_bgp_elem(&self) -> BgpElem {
self.note_truncation();
let bytes = self.attr_bytes;
let afi = self.afi();
let safi = self.safi();
let is_add_path = self.is_add_path();
let mut origin: Option<Origin> = None;
let mut atomic = false;
let mut aggregator: Option<(Asn, BgpIdentifier)> = None;
let mut only_to_customer: Option<Asn> = None;
let mut med: Option<u32> = None;
let mut local_pref: Option<u32> = None;
// An update's next hop was decoded once for the whole record.
let from_update = (self.flags & FLAG_UPDATE) != 0;
let mut next_hop: Option<IpAddr> = self.update_next_hop;
let mut mp_next_hop: Option<IpAddr> = None;
let mut as_path_wire: Option<&[u8]> = None;
let mut as4_path_wire: Option<&[u8]> = None;
let mut communities: Vec<MetaCommunity> = Vec::new();
let mut unknown: Vec<AttrRaw> = Vec::new();
let mut deprecated: Vec<AttrRaw> = Vec::new();
let mut pos = 0usize;
loop {
match step_attr(bytes, pos) {
AttrStep::End => break,
AttrStep::Truncated {
code,
declared,
available,
} => {
self.warn_truncated_attr_once(code, declared, available);
break;
}
AttrStep::Attr {
code,
value_start: val_start,
value_end: val_end,
} => {
let val = &bytes[val_start..val_end];
let tlv_start = pos;
pos = val_end;
if get_deprecated_attr_type(code).is_some() {
deprecated.push(AttrRaw {
code,
bytes: Bytes::copy_from_slice(val),
});
continue;
}
if crate::parser::bgp::attributes::is_raw_retained_attr(AttrType::from(code)) {
unknown.push(AttrRaw {
code,
bytes: Bytes::copy_from_slice(val),
});
continue;
}
// A known attribute this cannot decode keeps its bytes in `unknown`, which is what the
// owned path does with an attribute it falls back to `AttributeValue::Raw`.
let mut undecoded = false;
match AttrType::from(code) {
// A value the owned path cannot parse becomes raw bytes and leaves the earlier
// attribute of the same type in place, so keep what is already known here too.
AttrType::ORIGIN => {
match val.first().and_then(|value| Origin::try_from(*value).ok()) {
Some(decoded) => origin = Some(decoded),
None => undecoded = true,
}
}
AttrType::AS_PATH => {
if validate_as_path_wire(val) {
as_path_wire = Some(val);
} else {
undecoded = true;
}
}
AttrType::AS4_PATH => {
if validate_as_path_wire(val) {
as4_path_wire = Some(val);
} else {
undecoded = true;
}
}
AttrType::NEXT_HOP if from_update => {
// Decoded once per record above; whether the value is usable is the owned
// parser's decision, not a length test here.
if crate::parser::bgp::attributes::attr_03_next_hop::parse_next_hop(
val, &None,
)
.is_err()
{
undecoded = true;
}
}
AttrType::NEXT_HOP => {
let mut value = val;
match value.read_address(&self.next_hop_afi()) {
Ok(address) => next_hop = Some(address),
Err(_) => undecoded = true,
}
}
AttrType::MULTI_EXIT_DISCRIMINATOR => {
let mut value = val;
match value.read_u32() {
Ok(number) => med = Some(number),
Err(_) => undecoded = true,
}
}
AttrType::LOCAL_PREFERENCE => {
let mut value = val;
match value.read_u32() {
Ok(number) => local_pref = Some(number),
Err(_) => undecoded = true,
}
}
AttrType::ATOMIC_AGGREGATE => atomic = true,
// ORIGINATOR_ID is exactly one identifier; CLUSTER_LIST is any number of them,
// including none, which is what the owned parsers accept.
AttrType::ORIGINATOR_ID => {
if val.len() != 4 {
undecoded = true;
}
}
AttrType::CLUSTER_LIST => {
if !val.len().is_multiple_of(4) {
undecoded = true;
}
}
AttrType::AGGREGATOR | AttrType::AS4_AGGREGATOR => {
match crate::parser::bgp::attributes::parse_aggregator_slice(
bytes::Bytes::copy_from_slice(val),
&AsnLength::Bits32,
)
.ok()
{
Some(decoded) => aggregator = Some(decoded),
None => undecoded = true,
}
}
// Each community attribute is decoded by the owned parser for that attribute, at the
// position it appears, so an unsupported sub-type, a length that is not a whole
// element, and the special values all follow the owned rules and the raw bytes of a
// malformed one land in `unknown` where the owned path puts them.
AttrType::COMMUNITIES
| AttrType::EXTENDED_COMMUNITIES
| AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
| AttrType::LARGE_COMMUNITIES => {
let input = bytes::Bytes::copy_from_slice(val);
let decoded = match AttrType::from(code) {
AttrType::COMMUNITIES => {
crate::parser::bgp::attributes::parse_communities_attribute(input).map(
|value| match value {
crate::models::AttributeValue::Communities(v) => {
communities.extend(v.into_iter().map(MetaCommunity::Plain));
true
}
_ => false,
},
)
}
AttrType::EXTENDED_COMMUNITIES => {
crate::parser::bgp::attributes::parse_extended_communities_attribute(
input,
)
.map(|value| match value {
crate::models::AttributeValue::ExtendedCommunities(v) => {
communities
.extend(v.into_iter().map(MetaCommunity::Extended));
true
}
_ => false,
})
}
AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES => crate::parser::bgp::attributes::parse_ipv6_extended_communities_attribute(input)
.map(|value| match value {
crate::models::AttributeValue::Ipv6AddressSpecificExtendedCommunities(v) => {
communities
.extend(v.into_iter().map(MetaCommunity::Ipv6Extended));
true
}
_ => false,
}),
_ => crate::parser::bgp::attributes::parse_large_communities_attribute(input)
.map(|value| match value {
crate::models::AttributeValue::LargeCommunities(v) => {
communities.extend(v.into_iter().map(MetaCommunity::Large));
true
}
_ => false,
}),
};
if !decoded.unwrap_or(false) {
undecoded = true;
}
}
AttrType::ONLY_TO_CUSTOMER => {
if val.len() >= 4 {
only_to_customer = Some(Asn::new_32bit(u32::from_be_bytes([
val[0], val[1], val[2], val[3],
])));
} else {
undecoded = true;
}
}
AttrType::MP_REACHABLE_NLRI if from_update => {
if mp_reach_next_hop(val, self.prefix(), afi, safi, is_add_path, true)
.is_err()
{
undecoded = true;
}
}
AttrType::MP_REACHABLE_NLRI => {
match mp_reach_next_hop(
val,
self.prefix(),
afi,
safi,
is_add_path,
false,
) {
Ok(address) => mp_next_hop = address,
Err(()) => undecoded = true,
}
}
// Types the element path keeps as raw bytes, mirroring `get_relevant_attributes`.
// A valid traffic-engineering attribute is parsed by the owned path and then
// discarded from the element, so only a malformed one is kept raw.
AttrType::TRAFFIC_ENGINEERING => {
if crate::parser::bgp::attributes::parse_traffic_engineering(
bytes::Bytes::copy_from_slice(val),
)
.is_err()
{
undecoded = true;
}
}
AttrType::Unknown(_) => unknown.push(AttrRaw {
code,
bytes: Bytes::copy_from_slice(val),
}),
// Every remaining typed attribute is decoded by the owned dispatcher: if it comes
// back raw there, its bytes belong in `unknown` here too.
_ => {
// The owned parser is asked about this one attribute with the same context the
// record kind gives it: an update carries its own family, a dump entry hands in
// the record's prefix.
let tlv = &bytes[tlv_start..val_end];
let own_prefix = [self.prefix()];
let (afi, safi, prefixes) = if from_update {
(None, None, None)
} else {
(Some(afi), Some(safi), Some(&own_prefix[..]))
};
let parsed = crate::parser::bgp::attributes::parse_attributes(
bytes::Bytes::copy_from_slice(tlv),
&AsnLength::Bits32,
is_add_path,
afi,
safi,
prefixes,
);
let raw = match parsed {
Ok(attributes) => attributes.inner.iter().any(|attribute| {
matches!(
attribute.value,
crate::models::AttributeValue::Raw(_)
| crate::models::AttributeValue::Unknown(_)
)
}),
Err(_) => true,
};
if raw {
undecoded = true;
}
}
}
if undecoded {
unknown.push(AttrRaw {
code,
bytes: Bytes::copy_from_slice(val),
});
}
}
}
}
// RFC 6793 ยง4.2.3: when AS_PATH is shorter than AS4_PATH, AS4_PATH is ignored.
let source = match (as_path_wire, as4_path_wire) {
(None, None) => AsPathSource::Absent,
(Some(path), None) => AsPathSource::Single(path),
(None, Some(path)) => AsPathSource::Single(path),
(Some(path), Some(as4_path)) => {
if wire_route_len(path) < wire_route_len(as4_path) {
AsPathSource::Single(path)
} else {
AsPathSource::Merged {
as_path: path,
as4_path,
}
}
}
};
let as_path = AsPathView { source }.to_as_path();
let origin_asns = match source {
AsPathSource::Absent => None,
AsPathSource::Single(wire) => Some(single_wire_origins(wire).to_vec()),
AsPathSource::Merged { as_path, as4_path } => {
Some(merged_wire_origins(as_path, as4_path).to_vec())
}
};
let is_withdrawal = self.elem_type() == ElemType::WITHDRAW;
BgpElem {
timestamp: self.timestamp(),
elem_type: self.elem_type(),
peer_ip: self.peer_ip,
peer_asn: self.peer_asn,
peer_bgp_id: self.peer_bgp_id,
prefix: NetworkPrefix {
prefix: self.prefix,
path_id: self.path_id,
},
// A withdrawal carries no attributes, so it has no next hop on either path.
next_hop: if is_withdrawal {
None
} else {
next_hop.or(mp_next_hop)
},
as_path,
origin,
origin_asns,
// A withdrawal carries no attributes, so the owned path leaves these unset; every other
// case keeps the `Some(0)` default the owned path applies too.
local_pref: (!is_withdrawal).then(|| local_pref.unwrap_or(0)),
med: (!is_withdrawal).then(|| med.unwrap_or(0)),
communities: (!communities.is_empty()).then_some(communities),
atomic,
aggr_asn: aggregator.map(|value| value.0),
aggr_ip: aggregator.map(|value| value.1),
only_to_customer,
unknown: (!unknown.is_empty()).then_some(unknown),
deprecated: (!deprecated.is_empty()).then_some(deprecated),
}
}
/// Returns this element's Unix timestamp as seconds (`f64`): the entry's originated time for
/// a dump, the record's time for an update.
#[inline]
pub fn timestamp(&self) -> f64 {
self.timestamp
}
/// Returns whether this element is an announcement or a withdrawal.
#[inline]
pub fn elem_type(&self) -> ElemType {
self.elem_type
}
fn scan_u32_attr(&self, target_code: u8) -> Option<u32> {
let bytes = self.attr_bytes;
let mut pos = 0usize;
let mut found = None;
loop {
match step_attr(bytes, pos) {
AttrStep::End => break,
AttrStep::Truncated {
code,
declared,
available,
} => {
self.warn_truncated_attr_once(code, declared, available);
break;
}
AttrStep::Attr {
code,
value_start: val_start,
value_end: val_end,
} => {
if code == target_code && val_end - val_start >= 4 {
found = Some(u32::from_be_bytes([
bytes[val_start],
bytes[val_start + 1],
bytes[val_start + 2],
bytes[val_start + 3],
]));
}
pos = val_end;
}
}
}
found
}
}