Skip to main content

bgpkit_parser/parser/mrt/messages/table_dump_v2/
rib_afi_entries.rs

1use crate::bgp::attributes::parse_attributes;
2use crate::encoder::sink::with_u16_len;
3use crate::error::{check_max, EncodingError};
4use crate::models::{
5    Afi, AsnLength, NetworkPrefix, RibAfiEntries, RibEntry, Safi, TableDumpV2Type,
6};
7use crate::parser::ReadUtils;
8use crate::ParserError;
9use bytes::{Buf, BufMut, Bytes, BytesMut};
10use log::warn;
11
12fn extract_afi_safi_from_rib_type(rib_type: &TableDumpV2Type) -> Result<(Afi, Safi), ParserError> {
13    let afi: Afi;
14    let safi: Safi;
15    match rib_type {
16        TableDumpV2Type::RibIpv4Unicast | TableDumpV2Type::RibIpv4UnicastAddPath => {
17            afi = Afi::Ipv4;
18            safi = Safi::Unicast
19        }
20        TableDumpV2Type::RibIpv4Multicast | TableDumpV2Type::RibIpv4MulticastAddPath => {
21            afi = Afi::Ipv4;
22            safi = Safi::Multicast
23        }
24        TableDumpV2Type::RibIpv6Unicast | TableDumpV2Type::RibIpv6UnicastAddPath => {
25            afi = Afi::Ipv6;
26            safi = Safi::Unicast
27        }
28        TableDumpV2Type::RibIpv6Multicast | TableDumpV2Type::RibIpv6MulticastAddPath => {
29            afi = Afi::Ipv6;
30            safi = Safi::Multicast
31        }
32        _ => {
33            return Err(ParserError::ParseError(format!(
34                "wrong RIB type for parsing: {rib_type:?}"
35            )))
36        }
37    };
38
39    Ok((afi, safi))
40}
41
42fn is_add_path_rib_type(rib_type: TableDumpV2Type) -> bool {
43    matches!(
44        rib_type,
45        TableDumpV2Type::RibIpv4UnicastAddPath
46            | TableDumpV2Type::RibIpv4MulticastAddPath
47            | TableDumpV2Type::RibIpv6UnicastAddPath
48            | TableDumpV2Type::RibIpv6MulticastAddPath
49    )
50}
51
52pub(crate) const fn rib_entry_min_len(is_add_path: bool) -> usize {
53    2 /*peer_index*/ + 4 /*time*/ + 2 /*attr_len*/ + if is_add_path { 4 } else { 0 }
54}
55
56/// RIB AFI-specific entries
57///
58/// https://tools.ietf.org/html/rfc6396#section-4.3
59pub fn parse_rib_afi_entries(
60    data: &mut Bytes,
61    rib_type: TableDumpV2Type,
62) -> Result<RibAfiEntries, ParserError> {
63    let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type)?;
64    let is_add_path = is_add_path_rib_type(rib_type);
65
66    let sequence_number = data.read_u32()?;
67
68    // NOTE: here we parse the prefix as only length and prefix, the path identifier for add_path
69    //       entry is not handled here. We follow RFC6396 here https://www.rfc-editor.org/rfc/rfc6396.html#section-4.3.2
70    let prefix = data.read_nlri_prefix(&afi, false)?;
71
72    let entry_count = data.read_u16()?;
73    // Pre-allocate cautiously to avoid overflow/OOM with malformed inputs. One slot per entry:
74    // the RIB wire format never carries more entries than the remaining bytes can express.
75    let min_entry_size = rib_entry_min_len(is_add_path);
76    let max_possible = data.remaining() / min_entry_size;
77    let reserve = (entry_count as usize).min(max_possible);
78    let mut rib_entries = Vec::with_capacity(reserve);
79
80    // get the u8 slice of the rest of the data
81    // let attr_data_slice = &input.into_inner()[(input.position() as usize)..];
82
83    for _i in 0..entry_count {
84        let entry = match parse_rib_entry(data, is_add_path, &afi, &safi, prefix) {
85            Ok(entry) => entry,
86            Err(e) => {
87                warn!(
88                    "early break due to error {} while parsing RIB AFI entries",
89                    e
90                );
91                break;
92            }
93        };
94        rib_entries.push(entry);
95    }
96
97    Ok(RibAfiEntries {
98        rib_type,
99        sequence_number,
100        prefix,
101        rib_entries,
102    })
103}
104
105/// RIB entry: one prefix per entry
106///
107///
108/// https://datatracker.ietf.org/doc/html/rfc6396#section-4.3.4
109/// ```text
110///         0                   1                   2                   3
111///         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
112///        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113///        |         Peer Index            |
114///        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115///        |                         Originated Time                       |
116///        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117///        |      Attribute Length         |
118///        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
119///        |                    BGP Attributes... (variable)
120///        +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121///
122///                           Figure 10: RIB Entries
123/// ```
124pub fn parse_rib_entry(
125    input: &mut Bytes,
126    is_add_path: bool,
127    afi: &Afi,
128    safi: &Safi,
129    prefix: NetworkPrefix,
130) -> Result<RibEntry, ParserError> {
131    if input.remaining() < 8 {
132        // total length - current position less than 16 --
133        // meaning less than 16 bytes available to read
134        return Err(ParserError::TruncatedMsg("truncated msg".to_string()));
135    }
136
137    let peer_index = input.read_u16()?;
138    let originated_time = input.read_u32()?;
139
140    let path_id = match is_add_path {
141        true => Some(input.read_u32()?),
142        false => None,
143    };
144
145    let attribute_length = input.read_u16()? as usize;
146
147    input.has_n_remaining(attribute_length)?;
148    let attr_data_slice = input.split_to(attribute_length);
149    let mut attributes = parse_attributes(
150        attr_data_slice,
151        &AsnLength::Bits32,
152        is_add_path,
153        Some(*afi),
154        Some(*safi),
155        Some(&[prefix]),
156    )?;
157
158    // validate mandatory attributes (RIB entry is always an announcement)
159    attributes.check_mandatory_attributes(true, *afi == Afi::Ipv4);
160
161    Ok(RibEntry {
162        peer_index,
163        originated_time,
164        path_id,
165        attributes,
166    })
167}
168
169impl RibAfiEntries {
170    pub fn encode(&self) -> Result<Bytes, EncodingError> {
171        let mut bytes = BytesMut::new();
172        let is_add_path = is_add_path_rib_type(self.rib_type);
173
174        bytes.put_u32(self.sequence_number);
175        bytes.extend(self.prefix.encode());
176
177        let entry_count = self.rib_entries.len();
178        check_max("RIB entry count", entry_count, u16::MAX as usize)?;
179        bytes.put_u16(entry_count as u16);
180
181        for entry in &self.rib_entries {
182            entry.encode_for_rib_type(is_add_path, &mut bytes)?;
183        }
184
185        Ok(bytes.freeze())
186    }
187}
188
189impl RibEntry {
190    pub fn encode(&self) -> Result<Bytes, EncodingError> {
191        let mut bytes = BytesMut::new();
192        self.encode_for_rib_type(self.path_id.is_some(), &mut bytes)?;
193        Ok(bytes.freeze())
194    }
195
196    fn encode_for_rib_type(
197        &self,
198        include_path_id: bool,
199        bytes: &mut BytesMut,
200    ) -> Result<(), EncodingError> {
201        bytes.put_u16(self.peer_index);
202        bytes.put_u32(self.originated_time);
203        if include_path_id {
204            if let Some(path_id) = self.path_id {
205                bytes.put_u32(path_id);
206            }
207        }
208        with_u16_len(bytes, "RIB entry attribute length", |b| {
209            self.attributes.encode_to(AsnLength::Bits32, b)
210        })
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use bytes::Buf;
218    use std::str::FromStr;
219
220    #[test]
221    fn test_extract_afi_safi_from_rib_type() {
222        let rib_type = TableDumpV2Type::RibIpv4Unicast;
223        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
224        assert_eq!(afi, Afi::Ipv4);
225        assert_eq!(safi, Safi::Unicast);
226
227        let rib_type = TableDumpV2Type::RibIpv4Multicast;
228        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
229        assert_eq!(afi, Afi::Ipv4);
230        assert_eq!(safi, Safi::Multicast);
231
232        let rib_type = TableDumpV2Type::RibIpv6Unicast;
233        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
234        assert_eq!(afi, Afi::Ipv6);
235        assert_eq!(safi, Safi::Unicast);
236
237        let rib_type = TableDumpV2Type::RibIpv6Multicast;
238        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
239        assert_eq!(afi, Afi::Ipv6);
240        assert_eq!(safi, Safi::Multicast);
241
242        let rib_type = TableDumpV2Type::RibIpv4UnicastAddPath;
243        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
244        assert_eq!(afi, Afi::Ipv4);
245        assert_eq!(safi, Safi::Unicast);
246
247        let rib_type = TableDumpV2Type::RibIpv4MulticastAddPath;
248        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
249        assert_eq!(afi, Afi::Ipv4);
250        assert_eq!(safi, Safi::Multicast);
251
252        let rib_type = TableDumpV2Type::RibIpv6UnicastAddPath;
253        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
254        assert_eq!(afi, Afi::Ipv6);
255        assert_eq!(safi, Safi::Unicast);
256
257        let rib_type = TableDumpV2Type::RibIpv6MulticastAddPath;
258        let (afi, safi) = extract_afi_safi_from_rib_type(&rib_type).unwrap();
259        assert_eq!(afi, Afi::Ipv6);
260        assert_eq!(safi, Safi::Multicast);
261
262        let rib_type = TableDumpV2Type::RibGeneric;
263        let res = extract_afi_safi_from_rib_type(&rib_type);
264        assert!(res.is_err());
265    }
266
267    #[test]
268    fn test_rib_entry_encode() {
269        use crate::models::{AttributeValue, Attributes, Origin};
270
271        let mut attributes = Attributes::default();
272        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
273
274        let rib_entry = RibEntry {
275            peer_index: 1,
276            originated_time: 12345,
277            path_id: Some(42),
278            attributes,
279        };
280
281        let mut encoded = rib_entry.encode().unwrap();
282        assert_eq!(encoded.read_u16().unwrap(), 1);
283        assert_eq!(encoded.read_u32().unwrap(), 12345);
284        assert_eq!(encoded.read_u32().unwrap(), 42);
285        let attr_len = encoded.read_u16().unwrap() as usize;
286        assert_eq!(encoded.remaining(), attr_len);
287    }
288
289    #[test]
290    fn test_rib_afi_entries_encode_roundtrip_add_path() {
291        use crate::models::{AttributeValue, Attributes, Origin};
292
293        let mut attributes = Attributes::default();
294        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
295
296        let rib = RibAfiEntries {
297            rib_type: TableDumpV2Type::RibIpv4UnicastAddPath,
298            sequence_number: 7,
299            prefix: NetworkPrefix::from_str("10.0.0.0/24").unwrap(),
300            rib_entries: vec![RibEntry {
301                peer_index: 3,
302                originated_time: 12345,
303                path_id: Some(42),
304                attributes,
305            }],
306        };
307
308        let encoded = rib.encode().unwrap();
309        let parsed = parse_rib_afi_entries(&mut encoded.clone(), rib.rib_type).unwrap();
310        assert_eq!(parsed.rib_type, rib.rib_type);
311        assert_eq!(parsed.sequence_number, rib.sequence_number);
312        assert_eq!(parsed.prefix, rib.prefix);
313        assert_eq!(parsed.rib_entries.len(), 1);
314        assert_eq!(parsed.rib_entries[0].peer_index, 3);
315        assert_eq!(parsed.rib_entries[0].originated_time, 12345);
316        assert_eq!(parsed.rib_entries[0].path_id, Some(42));
317        assert_eq!(
318            parsed.rib_entries[0].attributes.inner,
319            rib.rib_entries[0].attributes.inner
320        );
321    }
322}