Skip to main content

bgpkit_parser/parser/
utils.rs

1/*!
2Provides IO utility functions for read bytes of different length and converting to corresponding structs.
3*/
4use ipnet::{IpNet, Ipv4Net, Ipv6Net};
5use std::convert::TryFrom;
6use std::{
7    io,
8    net::{Ipv4Addr, Ipv6Addr},
9};
10
11use crate::error::ParserError;
12use crate::models::*;
13use crate::ParserError::TruncatedMsg;
14use bytes::{Buf, BufMut, Bytes, BytesMut};
15use log::debug;
16use regex::Regex;
17use std::net::IpAddr;
18
19impl ReadUtils for Bytes {}
20
21// Attribute values that decode straight from a borrowed record body.
22impl ReadUtils for &[u8] {}
23
24// Allow reading IPs from Reads
25pub trait ReadUtils: Buf {
26    #[inline]
27    fn has_n_remaining(&self, n: usize) -> Result<(), ParserError> {
28        let remaining = self.remaining();
29        if remaining < n {
30            Err(TruncatedMsg(format!(
31                "not enough bytes to read. remaining: {remaining}, required: {n}"
32            )))
33        } else {
34            Ok(())
35        }
36    }
37
38    #[inline]
39    fn read_u8(&mut self) -> Result<u8, ParserError> {
40        self.has_n_remaining(1)?;
41        Ok(self.get_u8())
42    }
43
44    #[inline]
45    fn read_u16(&mut self) -> Result<u16, ParserError> {
46        self.has_n_remaining(2)?;
47        Ok(self.get_u16())
48    }
49
50    #[inline]
51    fn read_u32(&mut self) -> Result<u32, ParserError> {
52        self.has_n_remaining(4)?;
53        Ok(self.get_u32())
54    }
55
56    #[inline]
57    fn read_u64(&mut self) -> Result<u64, ParserError> {
58        self.has_n_remaining(8)?;
59        Ok(self.get_u64())
60    }
61
62    fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ParserError> {
63        self.has_n_remaining(buf.len())?;
64        self.copy_to_slice(buf);
65        Ok(())
66    }
67
68    fn read_address(&mut self, afi: &Afi) -> io::Result<IpAddr> {
69        match afi {
70            Afi::Ipv4 => match self.read_ipv4_address() {
71                Ok(ip) => Ok(IpAddr::V4(ip)),
72                _ => Err(io::Error::other("Cannot parse IPv4 address")),
73            },
74            Afi::Ipv6 => match self.read_ipv6_address() {
75                Ok(ip) => Ok(IpAddr::V6(ip)),
76                _ => Err(io::Error::other("Cannot parse IPv6 address")),
77            },
78            Afi::LinkState | Afi::L2vpn => {
79                // Neither Link-State nor EVPN uses a traditional IP next hop in
80                // this path; use the IPv4 zero address as a placeholder.
81                Ok(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)))
82            }
83        }
84    }
85
86    fn read_ipv4_address(&mut self) -> Result<Ipv4Addr, ParserError> {
87        let addr = self.read_u32()?;
88        Ok(Ipv4Addr::from(addr))
89    }
90
91    fn read_ipv6_address(&mut self) -> Result<Ipv6Addr, ParserError> {
92        self.has_n_remaining(16)?;
93        let buf = self.get_u128();
94        Ok(Ipv6Addr::from(buf))
95    }
96
97    fn read_ipv4_prefix(&mut self) -> Result<Ipv4Net, ParserError> {
98        let addr = self.read_ipv4_address()?;
99        let mask = self.read_u8()?;
100        match Ipv4Net::new(addr, mask) {
101            Ok(n) => Ok(n),
102            Err(_) => Err(io::Error::other("Invalid prefix mask").into()),
103        }
104    }
105
106    fn read_ipv6_prefix(&mut self) -> Result<Ipv6Net, ParserError> {
107        let addr = self.read_ipv6_address()?;
108        let mask = self.read_u8()?;
109        match Ipv6Net::new(addr, mask) {
110            Ok(n) => Ok(n),
111            Err(_) => Err(io::Error::other("Invalid prefix mask").into()),
112        }
113    }
114
115    #[inline]
116    fn read_asn(&mut self, as_length: AsnLength) -> Result<Asn, ParserError> {
117        match as_length {
118            AsnLength::Bits16 => self.read_u16().map(Asn::new_16bit),
119            AsnLength::Bits32 => self.read_u32().map(Asn::new_32bit),
120        }
121    }
122
123    fn read_asns(&mut self, as_length: &AsnLength, count: usize) -> Result<Vec<Asn>, ParserError> {
124        // Verify the bytes are actually present before allocating, so a large
125        // `count` cannot pre-allocate memory the buffer could never fill.
126        // `checked_mul` guards against overflow of `count * width` on 32-bit
127        // targets.
128        let width = match as_length {
129            AsnLength::Bits16 => 2,
130            AsnLength::Bits32 => 4,
131        };
132        let needed = count
133            .checked_mul(width)
134            .ok_or_else(|| TruncatedMsg("ASN count overflows buffer length".to_string()))?;
135        self.has_n_remaining(needed)?;
136
137        let mut path = Vec::with_capacity(count);
138        match as_length {
139            AsnLength::Bits16 => {
140                for _ in 0..count {
141                    path.push(Asn::new_16bit(self.read_u16()?));
142                }
143            }
144            AsnLength::Bits32 => {
145                for _ in 0..count {
146                    path.push(Asn::new_32bit(self.read_u32()?));
147                }
148            }
149        }
150
151        Ok(path)
152    }
153
154    fn read_afi(&mut self) -> Result<Afi, ParserError> {
155        Afi::try_from(self.read_u16()?).map_err(ParserError::from)
156    }
157
158    fn read_safi(&mut self) -> Result<Safi, ParserError> {
159        Safi::try_from(self.read_u8()?).map_err(ParserError::from)
160    }
161
162    /// Read announced/withdrawn prefix.
163    ///
164    /// The length in bits is 1 byte, and then based on the IP version it reads different number of bytes.
165    /// If the `add_path` is true, it will also first read a 4-byte path id first; otherwise, a path-id of 0
166    /// is automatically set.
167    fn read_nlri_prefix(
168        &mut self,
169        afi: &Afi,
170        add_path: bool,
171    ) -> Result<NetworkPrefix, ParserError> {
172        // Use try_parse_prefix on remaining bytes, then advance
173        let data = self.chunk();
174        let (prefix, consumed) = try_parse_prefix(data, afi, add_path)?;
175        self.advance(consumed);
176        Ok(prefix)
177    }
178
179    fn read_n_bytes(&mut self, n_bytes: usize) -> Result<Vec<u8>, ParserError> {
180        self.has_n_remaining(n_bytes)?;
181        Ok(self.copy_to_bytes(n_bytes).into())
182    }
183
184    fn read_n_bytes_to_string(&mut self, n_bytes: usize) -> Result<String, ParserError> {
185        let buffer = self.read_n_bytes(n_bytes)?;
186        Ok(buffer
187            .into_iter()
188            .map(|x: u8| x as char)
189            .collect::<String>())
190    }
191}
192
193/// Parse NLRI prefix from byte slice without consuming bytes.
194/// Returns (prefix, bytes_consumed) on success.
195pub(crate) fn try_parse_prefix(
196    data: &[u8],
197    afi: &Afi,
198    add_path: bool,
199) -> Result<(NetworkPrefix, usize), ParserError> {
200    let mut pos = 0;
201
202    // Read path_id if add_path
203    let path_id = if add_path {
204        if data.len() < pos + 4 {
205            return Err(ParserError::TruncatedMsg("truncated path_id".to_string()));
206        }
207        let id = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
208        pos += 4;
209        Some(id)
210    } else {
211        None
212    };
213
214    // Read prefix length
215    if data.len() < pos + 1 {
216        return Err(ParserError::TruncatedMsg(
217            "truncated prefix length".to_string(),
218        ));
219    }
220    let bit_len = data[pos];
221    pos += 1;
222
223    // Validate prefix length
224    let max_bit_len: u8 = match afi {
225        Afi::Ipv4 => 32,
226        Afi::Ipv6 => 128,
227        // EVPN NLRI are decoded by their own parser; a bit-length prefix does
228        // not apply to either family here.
229        Afi::LinkState | Afi::L2vpn => 0,
230    };
231
232    if bit_len > max_bit_len {
233        return Err(ParserError::ParseError(format!(
234            "Invalid prefix length: {bit_len} (max {max_bit_len} for {afi:?})"
235        )));
236    }
237
238    // Calculate bytes needed
239    let byte_len = (bit_len as usize).div_ceil(8);
240
241    // Parse address
242    let addr: IpAddr = match afi {
243        Afi::Ipv4 => {
244            if byte_len > 4 {
245                return Err(ParserError::ParseError(
246                    "Invalid byte length for IPv4".to_string(),
247                ));
248            }
249            if data.len() < pos + byte_len {
250                return Err(ParserError::TruncatedMsg(
251                    "truncated IPv4 prefix".to_string(),
252                ));
253            }
254            let mut buff = [0u8; 4];
255            buff[..byte_len].copy_from_slice(&data[pos..pos + byte_len]);
256            pos += byte_len;
257            IpAddr::V4(Ipv4Addr::from(buff))
258        }
259        Afi::Ipv6 => {
260            if byte_len > 16 {
261                return Err(ParserError::ParseError(
262                    "Invalid byte length for IPv6".to_string(),
263                ));
264            }
265            if data.len() < pos + byte_len {
266                return Err(ParserError::TruncatedMsg(
267                    "truncated IPv6 prefix".to_string(),
268                ));
269            }
270            let mut buff = [0u8; 16];
271            buff[..byte_len].copy_from_slice(&data[pos..pos + byte_len]);
272            pos += byte_len;
273            IpAddr::V6(Ipv6Addr::from(buff))
274        }
275        // Neither Link-State nor EVPN carries a traditional prefix here.
276        Afi::LinkState | Afi::L2vpn => {
277            pos += byte_len;
278            IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))
279        }
280    };
281
282    let prefix = IpNet::new(addr, bit_len).map_err(|_| {
283        ParserError::ParseError(format!("Invalid network prefix length: {bit_len}"))
284    })?;
285
286    Ok((NetworkPrefix::new(prefix, path_id), pos))
287}
288
289/// Decode an NLRI block with a known ADD-PATH setting.
290///
291/// Every entry is decoded the same way, and an error discards the whole block: partially decoded
292/// prefixes must not escape to the caller.
293fn parse_nlri_list_exact(
294    mut input: Bytes,
295    add_path: bool,
296    afi: &Afi,
297) -> Result<Vec<NetworkPrefix>, ParserError> {
298    let mut prefixes = Vec::new();
299    while input.remaining() > 0 {
300        let (prefix, consumed) = try_parse_prefix(input.as_ref(), afi, add_path)?;
301        input.advance(consumed);
302        prefixes.push(prefix);
303    }
304    Ok(prefixes)
305}
306
307/// Parse an NLRI block, resolving a leading `0x00` byte that the ADD-PATH flag cannot explain.
308///
309/// A block starting with `0x00` is ambiguous. RFC 4271 ยง4.3 reads it as a prefix length of 0, the
310/// default route. Some producers instead wrap an ADD-PATH message in a non-ADD-PATH record, where
311/// the same byte is the first octet of a path identifier (issue #31), and guessing matters there:
312/// without it almost three quarters of the elements of such a file disappear.
313///
314/// The guess is made over the whole block, and a block the ADD-PATH reading cannot consume falls
315/// back to the flag. Retrying at the failure position, the previous behaviour, kept the prefixes
316/// already decoded out of path-id bytes and dropped the real ones, which emptied or corrupted
317/// withdrawal lists that begin with the default route (#360).
318///
319/// A plain block whose bytes also happen to frame exactly as ADD-PATH is still read as ADD-PATH:
320/// the bytes carry nothing that decides between them, and on the data that motivated the guess the
321/// ADD-PATH reading is the correct one (see `test_parse_nlri_list_ambiguous_block_prefers_add_path`).
322/// A short block of that shape, `0.0.0.0/0` followed by one prefix, is still misread.
323pub fn parse_nlri_list(
324    input: Bytes,
325    add_path: bool,
326    afi: &Afi,
327) -> Result<Vec<NetworkPrefix>, ParserError> {
328    if add_path {
329        return parse_nlri_list_exact(input, true, afi);
330    }
331    if input.first() == Some(&0) {
332        debug!("NLRI: block starts with 0x00, trying the ADD-PATH framing");
333        if let Ok(prefixes) = parse_nlri_list_exact(input.clone(), true, afi) {
334            return Ok(prefixes);
335        }
336        debug!("NLRI: the ADD-PATH framing does not consume the block, decoding with the flag");
337    }
338    parse_nlri_list_exact(input, false, afi)
339}
340
341pub fn encode_asn(asn: &Asn, asn_len: &AsnLength) -> Bytes {
342    let mut bytes = BytesMut::new();
343    match asn_len {
344        AsnLength::Bits16 => bytes.put_u16(asn.into()),
345        AsnLength::Bits32 => {
346            bytes.put_u32(asn.into());
347        }
348    }
349    bytes.freeze()
350}
351
352pub fn encode_ipaddr(addr: &IpAddr) -> Vec<u8> {
353    match addr {
354        IpAddr::V4(addr) => addr.octets().to_vec(),
355        IpAddr::V6(addr) => addr.octets().to_vec(),
356    }
357}
358
359pub fn encode_nlri_prefixes(prefixes: &[NetworkPrefix]) -> Bytes {
360    let mut bytes = BytesMut::new();
361    for prefix in prefixes {
362        bytes.extend(prefix.encode());
363    }
364    bytes.freeze()
365}
366
367/// A CRC32 implementation that converts a string to a hex string.
368///
369/// CRC32 is a checksum algorithm that is used to verify the integrity of data. It is short in
370/// length and sufficient for generating unique file names based on remote URLs.
371pub fn crc32(input: &str) -> String {
372    let input_bytes = input.as_bytes();
373    let mut table = [0u32; 256];
374    let polynomial = 0xedb88320u32;
375
376    for i in 0..256 {
377        let mut crc = i as u32;
378        for _ in 0..8 {
379            if crc & 1 == 1 {
380                crc = (crc >> 1) ^ polynomial;
381            } else {
382                crc >>= 1;
383            }
384        }
385        table[i as usize] = crc;
386    }
387
388    let mut crc = !0u32;
389    for byte in input_bytes.iter() {
390        let index = ((crc ^ (*byte as u32)) & 0xff) as usize;
391        crc = (crc >> 8) ^ table[index];
392    }
393
394    format!("{:08x}", !crc)
395}
396
397/// Convert a f64 timestamp into u32 seconds and u32 microseconds.
398///
399/// # Arguments
400///
401/// * `timestamp` - The timestamp to convert.
402///
403/// # Returns
404///
405/// A tuple containing the converted seconds and microseconds.
406///
407/// # Example
408///
409/// ```rust
410/// use bgpkit_parser::utils::convert_timestamp;
411///
412/// let timestamp = 1609459200.123456;
413/// let (seconds, microseconds) = convert_timestamp(timestamp);
414/// assert_eq!(seconds, 1609459200);
415/// assert_eq!(microseconds, 123456);
416/// ```
417// convert f64 timestamp into u32 seconds and u32 microseconds
418pub fn convert_timestamp(timestamp: f64) -> (u32, u32) {
419    let seconds = timestamp as u32;
420    let microseconds = ((timestamp - seconds as f64) * 1_000_000.0) as u32;
421    (seconds, microseconds)
422}
423
424#[derive(Debug, Clone)]
425pub struct ComparableRegex {
426    pattern: String,
427    regex: Regex,
428}
429
430impl PartialEq for ComparableRegex {
431    fn eq(&self, other: &Self) -> bool {
432        self.pattern == other.pattern
433    }
434}
435
436impl ComparableRegex {
437    pub fn new(pattern: &str) -> Result<Self, ParserError> {
438        let regex = match Regex::new(pattern) {
439            Ok(r) => r,
440            Err(_) => {
441                return Err(ParserError::FilterError(format!(
442                    "Invalid regex pattern: {pattern}"
443                )))
444            }
445        };
446        Ok(ComparableRegex {
447            pattern: pattern.to_string(),
448            regex,
449        })
450    }
451
452    pub fn is_match<S: AsRef<str>>(&self, text: S) -> bool {
453        self.regex.is_match(text.as_ref())
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460    use bytes::Bytes;
461
462    #[test]
463    fn test_read_u8() {
464        let mut buf = Bytes::from_static(&[0x12]);
465        assert_eq!(buf.read_u8().unwrap(), 0x12);
466    }
467
468    #[test]
469    fn test_read_u16() {
470        let mut buf = Bytes::from_static(&[0x12, 0x34]);
471        assert_eq!(buf.read_u16().unwrap(), 0x1234);
472    }
473
474    #[test]
475    fn test_read_u32() {
476        let mut buf = Bytes::from_static(&[0x12, 0x34, 0x56, 0x78]);
477        assert_eq!(buf.read_u32().unwrap(), 0x12345678);
478    }
479
480    #[test]
481    fn test_read_u64() {
482        let mut buf = Bytes::from_static(&[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]);
483        assert_eq!(buf.read_u64().unwrap(), 0x123456789ABCDEF0);
484    }
485
486    #[test]
487    fn test_read_ipv4_address() {
488        let mut buf = Bytes::from_static(&[0xC0, 0xA8, 0x01, 0x01]);
489        assert_eq!(
490            buf.read_ipv4_address().unwrap(),
491            Ipv4Addr::new(192, 168, 1, 1)
492        );
493    }
494
495    #[test]
496    fn test_read_ipv6_address() {
497        let mut buf = Bytes::from_static(&[
498            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
499            0x73, 0x34,
500        ]);
501        assert_eq!(
502            buf.read_ipv6_address().unwrap(),
503            Ipv6Addr::new(0x2001, 0x0DB8, 0x85A3, 0x0000, 0x0000, 0x8A2E, 0x0370, 0x7334)
504        );
505    }
506
507    #[test]
508    fn test_read_address() {
509        let mut buf = Bytes::from_static(&[0xC0, 0xA8, 0x01, 0x01]);
510        assert_eq!(
511            buf.read_address(&Afi::Ipv4).unwrap(),
512            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))
513        );
514
515        let mut buf = Bytes::from_static(&[
516            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
517            0x73, 0x34,
518        ]);
519        assert_eq!(
520            buf.read_address(&Afi::Ipv6).unwrap(),
521            IpAddr::V6(Ipv6Addr::new(
522                0x2001, 0x0DB8, 0x85A3, 0x0000, 0x0000, 0x8A2E, 0x0370, 0x7334
523            ))
524        );
525
526        let mut buf = Bytes::from_static(&[0xC0, 0xA8, 0x01]);
527        assert!(buf.read_address(&Afi::Ipv4).is_err());
528
529        let mut buf = Bytes::from_static(&[
530            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
531            0x73,
532        ]);
533        assert!(buf.read_address(&Afi::Ipv6).is_err());
534    }
535
536    #[test]
537    fn test_read_asn() {
538        let mut buf = Bytes::from_static(&[0x00, 0x01]);
539        assert_eq!(buf.read_asn(AsnLength::Bits16).unwrap(), Asn::new_16bit(1));
540
541        let mut buf = Bytes::from_static(&[0x00, 0x00, 0x01, 0x00]);
542        assert_eq!(
543            buf.read_asn(AsnLength::Bits32).unwrap(),
544            Asn::new_32bit(256)
545        );
546    }
547
548    #[test]
549    fn read_asns() {
550        let mut buf = Bytes::from_static(&[0x00, 0x01, 0x00, 0x00]);
551        assert_eq!(
552            buf.read_asns(&AsnLength::Bits16, 2).unwrap(),
553            vec![Asn::new_16bit(1), Asn::new_16bit(0)]
554        );
555    }
556
557    #[test]
558    fn test_read_afi() {
559        let mut buf = Bytes::from_static(&[0x00, 0x01]);
560        assert_eq!(buf.read_afi().unwrap(), Afi::Ipv4);
561
562        let mut buf = Bytes::from_static(&[0x00, 0x02]);
563        assert_eq!(buf.read_afi().unwrap(), Afi::Ipv6);
564    }
565
566    #[test]
567    fn test_read_safi() {
568        let mut buf = Bytes::from_static(&[0x01]);
569        assert_eq!(buf.read_safi().unwrap(), Safi::Unicast);
570
571        let mut buf = Bytes::from_static(&[0x02]);
572        assert_eq!(buf.read_safi().unwrap(), Safi::Multicast);
573
574        // RFC 8950 VPN SAFI values
575        let mut buf = Bytes::from_static(&[0x80]); // 128 in hex
576        assert_eq!(buf.read_safi().unwrap(), Safi::MplsVpn);
577
578        let mut buf = Bytes::from_static(&[0x81]); // 129 in hex
579        assert_eq!(buf.read_safi().unwrap(), Safi::MulticastVpn);
580    }
581
582    #[test]
583    fn test_has_n_remaining() {
584        let mut buf = Bytes::from_static(&[0x12, 0x34, 0x56, 0x78]);
585        assert!(buf.has_n_remaining(4).is_ok());
586        assert!(buf.has_n_remaining(5).is_err());
587
588        let _ = buf.read_u8().unwrap();
589        assert!(buf.has_n_remaining(3).is_ok());
590        assert!(buf.has_n_remaining(4).is_err());
591    }
592
593    #[test]
594    fn test_read_ipv4_prefix() {
595        let mut buf = Bytes::from_static(&[0xC0, 0xA8, 0x01, 0x01, 0x18]);
596        assert_eq!(
597            buf.read_ipv4_prefix().unwrap(),
598            Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 1), 24).unwrap()
599        );
600
601        // Test with invalid IPv4 prefix mask, /33
602        let mut buf = Bytes::from_static(&[0xC0, 0xA8, 0x01, 0x01, 0x21]);
603        assert!(buf.read_ipv4_prefix().is_err());
604    }
605
606    #[test]
607    fn test_read_ipv6_prefix() {
608        let mut buf = Bytes::from_static(&[
609            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
610            0x73, 0x34, 0x40,
611        ]);
612        assert_eq!(
613            buf.read_ipv6_prefix().unwrap(),
614            Ipv6Net::new(
615                Ipv6Addr::new(0x2001, 0x0DB8, 0x85A3, 0x0000, 0x0000, 0x8A2E, 0x0370, 0x7334),
616                64
617            )
618            .unwrap()
619        );
620
621        // Test with invalid IPv6 prefix mask, /129
622        let mut buf = Bytes::from_static(&[
623            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
624            0x73, 0x34, 0x81,
625        ]);
626        assert!(buf.read_ipv6_prefix().is_err());
627    }
628
629    #[test]
630    fn test_read_n_bytes() {
631        let mut buf = Bytes::from_static(&[0x12, 0x34, 0x56, 0x78]);
632        assert_eq!(buf.read_n_bytes(4).unwrap(), vec![0x12, 0x34, 0x56, 0x78]);
633    }
634
635    #[test]
636    fn test_read_n_bytes_to_string() {
637        let mut buf = Bytes::from_static(&[0x48, 0x65, 0x6C, 0x6C, 0x6F]); // "Hello" in ASCII
638        assert_eq!(buf.read_n_bytes_to_string(5).unwrap(), "Hello");
639    }
640
641    #[test]
642    fn test_crc32() {
643        assert_eq!(crc32("Hello, World!"), "ec4ac3d0");
644    }
645
646    #[test]
647    fn test_read_nlri_prefix() {
648        let mut buf = Bytes::from_static(&[0x18, 0xC0, 0xA8, 0x01]);
649        let expected = NetworkPrefix::new(
650            IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
651            None,
652        );
653        assert_eq!(buf.read_nlri_prefix(&Afi::Ipv4, false).unwrap(), expected);
654
655        let mut buf = Bytes::from_static(&[0x00, 0x00, 0x00, 0x01, 0x18, 0xC0, 0xA8, 0x01]);
656        let expected = NetworkPrefix::new(
657            IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
658            Some(1),
659        );
660        assert_eq!(buf.read_nlri_prefix(&Afi::Ipv4, true).unwrap(), expected);
661    }
662
663    #[test]
664    fn test_read_nlri_prefix_length_validation() {
665        // Test IPv4 prefix length > 32 (e.g., 33, 255) is rejected
666        for invalid_len in [33u8, 255] {
667            let mut buf = Bytes::from(vec![invalid_len, 0xC0, 0xA8, 0x01]);
668            let result = buf.read_nlri_prefix(&Afi::Ipv4, false);
669            assert!(
670                result.is_err(),
671                "IPv4 prefix length {} should be rejected",
672                invalid_len
673            );
674            if let Err(ParserError::ParseError(msg)) = result {
675                assert!(msg.contains("Invalid prefix length"));
676            }
677        }
678
679        // Test IPv6 prefix length > 128 (e.g., 129, 255) is rejected
680        for invalid_len in [129u8, 255] {
681            let mut buf = Bytes::from(vec![invalid_len, 0x20, 0x01, 0x0D, 0xB8]);
682            let result = buf.read_nlri_prefix(&Afi::Ipv6, false);
683            assert!(
684                result.is_err(),
685                "IPv6 prefix length {} should be rejected",
686                invalid_len
687            );
688            if let Err(ParserError::ParseError(msg)) = result {
689                assert!(msg.contains("Invalid prefix length"));
690            }
691        }
692
693        // Test valid IPv4 prefix lengths pass (0-32)
694        for valid_len in [0u8, 1, 32] {
695            // Provide enough bytes for any byte_len calculation
696            let mut buf = Bytes::from(vec![valid_len, 0x00, 0x00, 0x00, 0x00]);
697            let result = buf.read_nlri_prefix(&Afi::Ipv4, false);
698            assert!(
699                result.is_ok(),
700                "IPv4 prefix length {} should be valid",
701                valid_len
702            );
703        }
704
705        // Test valid IPv6 prefix lengths pass (0-128)
706        for valid_len in [0u8, 1, 64, 128] {
707            // Provide enough bytes for any byte_len calculation (max 16 bytes)
708            let buf_data: Vec<u8> = std::iter::once(valid_len)
709                .chain(std::iter::repeat_n(0x00, 16))
710                .collect();
711            let mut buf = Bytes::from(buf_data);
712            let result = buf.read_nlri_prefix(&Afi::Ipv6, false);
713            assert!(
714                result.is_ok(),
715                "IPv6 prefix length {} should be valid",
716                valid_len
717            );
718        }
719    }
720
721    #[test]
722    fn test_encode_asn() {
723        let asn = Asn::new_32bit(1);
724        let asn_len = AsnLength::Bits32;
725        let expected = Bytes::from_static(&[0x00, 0x00, 0x00, 0x01]);
726        assert_eq!(encode_asn(&asn, &asn_len), expected);
727
728        let asn = Asn::new_16bit(1);
729        let asn_len = AsnLength::Bits16;
730        let expected = Bytes::from_static(&[0x00, 0x01]);
731        assert_eq!(encode_asn(&asn, &asn_len), expected);
732    }
733
734    #[test]
735    fn test_encode_ipaddr() {
736        let addr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
737        let expected = vec![192, 168, 1, 1];
738        assert_eq!(encode_ipaddr(&addr), expected);
739
740        let addr = IpAddr::V6(Ipv6Addr::new(
741            0x2001, 0x0DB8, 0x85A3, 0x0000, 0x0000, 0x8A2E, 0x0370, 0x7334,
742        ));
743        let expected = vec![
744            0x20, 0x01, 0x0D, 0xB8, 0x85, 0xA3, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x2E, 0x03, 0x70,
745            0x73, 0x34,
746        ];
747        assert_eq!(encode_ipaddr(&addr), expected);
748    }
749
750    #[test]
751    fn test_encode_nlri_prefixes() {
752        let prefixes = vec![
753            NetworkPrefix::new(
754                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
755                None,
756            ),
757            NetworkPrefix::new(
758                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 2, 0), 24).unwrap()),
759                None,
760            ),
761        ];
762        let expected = Bytes::from_static(&[0x18, 0xC0, 0xA8, 0x01, 0x18, 0xC0, 0xA8, 0x02]);
763        assert_eq!(encode_nlri_prefixes(&prefixes), expected);
764
765        let prefixes = vec![
766            NetworkPrefix::new(
767                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
768                Some(1),
769            ),
770            NetworkPrefix::new(
771                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 2, 0), 24).unwrap()),
772                Some(1),
773            ),
774        ];
775        let expected = Bytes::from_static(&[
776            0x00, 0x00, 0x00, 0x01, 0x18, 0xC0, 0xA8, 0x01, 0x00, 0x00, 0x00, 0x01, 0x18, 0xC0,
777            0xA8, 0x02,
778        ]);
779        assert_eq!(encode_nlri_prefixes(&prefixes), expected);
780    }
781
782    #[test]
783    fn test_comparable_regex_functionality() {
784        // Test valid pattern creation
785        let regex1 = ComparableRegex::new(r"\d+").unwrap();
786        let regex2 = ComparableRegex::new(r"\d+").unwrap();
787        let regex3 = ComparableRegex::new(r"\w+").unwrap();
788
789        // Verify pattern storage
790        assert_eq!(regex1.pattern, r"\d+");
791        assert_eq!(regex3.pattern, r"\w+");
792
793        // Verify equality with same pattern
794        assert_eq!(regex1, regex2);
795
796        // Verify inequality with different patterns
797        assert_ne!(regex1, regex3);
798
799        // Verify regex matching functionality
800        assert!(regex1.regex.is_match("123"));
801        assert!(!regex1.regex.is_match("abc"));
802    }
803
804    #[test]
805    #[should_panic(expected = "Invalid regex pattern")]
806    fn test_comparable_regex_invalid_pattern_panic() {
807        // Test invalid pattern creation
808        ComparableRegex::new(r"(\d+").unwrap(); // Unclosed parenthesis should panic
809    }
810
811    #[test]
812    fn test_parse_nlri_list() {
813        // Test normal case with add_path=false
814        let input = Bytes::from_static(&[0x18, 0xC0, 0xA8, 0x01, 0x18, 0xC0, 0xA8, 0x02]);
815        let expected = vec![
816            NetworkPrefix::new(
817                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
818                None,
819            ),
820            NetworkPrefix::new(
821                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 2, 0), 24).unwrap()),
822                None,
823            ),
824        ];
825        assert_eq!(parse_nlri_list(input, false, &Afi::Ipv4).unwrap(), expected);
826
827        // Test normal case with add_path=true
828        let input = Bytes::from_static(&[
829            0x00, 0x00, 0x00, 0x01, 0x18, 0xC0, 0xA8, 0x01, 0x00, 0x00, 0x00, 0x02, 0x18, 0xC0,
830            0xA8, 0x02,
831        ]);
832        let expected = vec![
833            NetworkPrefix::new(
834                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
835                Some(1),
836            ),
837            NetworkPrefix::new(
838                IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 2, 0), 24).unwrap()),
839                Some(2),
840            ),
841        ];
842        assert_eq!(parse_nlri_list(input, true, &Afi::Ipv4).unwrap(), expected);
843
844        // Test the auto-detection of add_path when first byte is 0
845        let input = Bytes::from_static(&[0x00, 0x00, 0x00, 0x01, 0x18, 0xC0, 0xA8, 0x01]);
846        let expected = vec![NetworkPrefix::new(
847            IpNet::V4(Ipv4Net::new(Ipv4Addr::new(192, 168, 1, 0), 24).unwrap()),
848            Some(1),
849        )];
850        assert_eq!(parse_nlri_list(input, false, &Afi::Ipv4).unwrap(), expected);
851    }
852
853    #[test]
854    fn test_convert_timestamp() {
855        // Test integer timestamp
856        let (seconds, microseconds) = convert_timestamp(1609459200.0);
857        assert_eq!(seconds, 1609459200);
858        assert_eq!(microseconds, 0);
859
860        // Test fractional timestamp
861        let (seconds, microseconds) = convert_timestamp(1609459200.123456);
862        assert_eq!(seconds, 1609459200);
863        assert_eq!(microseconds, 123456);
864
865        // Test rounding
866        let (seconds, microseconds) = convert_timestamp(1609459200.1234567);
867        assert_eq!(seconds, 1609459200);
868        assert_eq!(microseconds, 123456); // Should round to microseconds
869    }
870
871    #[test]
872    fn test_parse_nlri_list_add_path_heuristic() {
873        // Test the Add-Path heuristic: first byte is 0 suggests path_id = 0
874        // This tests the memory-optimized lazy clone behavior
875
876        // Valid Add-Path NLRI with path_id = 0: [0x00, 0x00, 0x00, 0x00, prefix_len, prefix_bytes...]
877        let input = Bytes::from(vec![
878            0x00, 0x00, 0x00, 0x00, // path_id = 0
879            0x18, // prefix_len = 24 bits
880            0xC0, 0xA8, 0x01, // 192.168.1 prefix
881        ]);
882
883        // With add_path=false, the heuristic should trigger (first byte is 0)
884        // and parse successfully with Add-Path format
885        let result = parse_nlri_list(input, false, &Afi::Ipv4);
886        assert!(
887            result.is_ok(),
888            "Add-Path heuristic should parse successfully"
889        );
890
891        let prefixes = result.unwrap();
892        assert_eq!(prefixes.len(), 1);
893        assert_eq!(
894            prefixes[0].prefix.addr(),
895            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 0))
896        );
897        assert_eq!(prefixes[0].prefix.prefix_len(), 24);
898        assert_eq!(prefixes[0].path_id, Some(0));
899    }
900
901    #[test]
902    fn test_parse_nlri_list_non_addpath_with_zero_prefix() {
903        // Edge case: Non-Add-Path NLRI where the first prefix byte happens to be 0
904        // This could trigger a false positive in the heuristic
905        // Example: /0 default route would start with byte 0
906
907        // Non-Add-Path NLRI for 0.0.0.0/0 (default route)
908        // Format: [prefix_len, prefix_bytes...]
909        let input = Bytes::from(vec![
910            0x00, // prefix_len = 0 (default route)
911                 // No prefix bytes needed for /0
912        ]);
913
914        // This might trigger the heuristic (first byte is 0)
915        // The optimized code should handle the retry correctly
916        let result = parse_nlri_list(input, false, &Afi::Ipv4);
917
918        // Should either parse successfully or return an error
919        // The key point is it shouldn't panic
920        match result {
921            Ok(prefixes) => {
922                // If parsed, should be the default route
923                if !prefixes.is_empty() {
924                    assert_eq!(prefixes[0].prefix.prefix_len(), 0);
925                }
926            }
927            Err(_) => {
928                // Error is acceptable - the heuristic might fail on this edge case
929                // The important thing is we don't panic
930            }
931        }
932    }
933
934    #[test]
935    fn test_parse_nlri_list_multiple_prefixes_with_addpath() {
936        // Test multiple prefixes with Add-Path enabled
937        // This would have caught the bug where we dropped the clone after first prefix
938
939        // Two prefixes with path_id = 0:
940        // [path_id=0, len=24, 192.168.1] [path_id=0, len=24, 192.168.2]
941        let input = Bytes::from(vec![
942            // First prefix
943            0x00, 0x00, 0x00, 0x00, // path_id = 0
944            0x18, // prefix_len = 24 bits
945            0xC0, 0xA8, 0x01, // 192.168.1
946            // Second prefix
947            0x00, 0x00, 0x00, 0x00, // path_id = 0
948            0x18, // prefix_len = 24 bits
949            0xC0, 0xA8, 0x02, // 192.168.2
950        ]);
951
952        // With add_path=false, heuristic should trigger and parse both
953        let result = parse_nlri_list(input, false, &Afi::Ipv4);
954        assert!(result.is_ok(), "Should parse multiple Add-Path prefixes");
955
956        let prefixes = result.unwrap();
957        assert_eq!(prefixes.len(), 2, "Should have 2 prefixes");
958
959        // First prefix
960        assert_eq!(
961            prefixes[0].prefix.addr(),
962            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 0))
963        );
964        assert_eq!(prefixes[0].prefix.prefix_len(), 24);
965        assert_eq!(prefixes[0].path_id, Some(0));
966
967        // Second prefix
968        assert_eq!(
969            prefixes[1].prefix.addr(),
970            IpAddr::V4(Ipv4Addr::new(192, 168, 2, 0))
971        );
972        assert_eq!(prefixes[1].prefix.prefix_len(), 24);
973        assert_eq!(prefixes[1].path_id, Some(0));
974    }
975
976    #[test]
977    fn test_parse_nlri_list_ipv6_addpath() {
978        // Test IPv6 NLRI with Add-Path
979        let input = Bytes::from(vec![
980            // path_id = 1
981            0x00, 0x00, 0x00, 0x01, // prefix_len = 64 bits
982            0x40, // 2001:db8::/64 (first 8 bytes)
983            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
984        ]);
985
986        let result = parse_nlri_list(input, true, &Afi::Ipv6);
987        assert!(result.is_ok(), "Should parse IPv6 Add-Path prefix");
988
989        let prefixes = result.unwrap();
990        assert_eq!(prefixes.len(), 1);
991        assert_eq!(prefixes[0].prefix.prefix_len(), 64);
992        assert_eq!(prefixes[0].path_id, Some(1));
993    }
994
995    #[test]
996    fn test_parse_nlri_list_explicit_addpath_nonzero_path_id() {
997        // Test with explicit add_path=true and non-zero path_id
998        let input = Bytes::from(vec![
999            0x00, 0x00, 0x00, 0xFF, // path_id = 255
1000            0x18, // prefix_len = 24 bits
1001            0xC0, 0xA8, 0x01, // 192.168.1
1002        ]);
1003
1004        let result = parse_nlri_list(input, true, &Afi::Ipv4);
1005        assert!(result.is_ok());
1006
1007        let prefixes = result.unwrap();
1008        assert_eq!(prefixes.len(), 1);
1009        assert_eq!(prefixes[0].path_id, Some(255));
1010    }
1011
1012    #[test]
1013    fn test_parse_nlri_list_empty() {
1014        // Empty input should return empty vec
1015        let input = Bytes::from(vec![]);
1016        let result = parse_nlri_list(input, false, &Afi::Ipv4);
1017        assert!(result.is_ok());
1018        assert!(result.unwrap().is_empty());
1019    }
1020
1021    #[test]
1022    fn test_parse_nlri_list_truncated_data() {
1023        // Truncated data should return error, not panic
1024        let input = Bytes::from(vec![
1025            0x18, // prefix_len = 24 bits (claims 3 bytes)
1026            0xC0, // but only 1 byte provided
1027        ]);
1028
1029        let result = parse_nlri_list(input, false, &Afi::Ipv4);
1030        assert!(result.is_err(), "Should error on truncated data");
1031    }
1032
1033    #[test]
1034    fn test_parse_nlri_list_single_default_route() {
1035        // A lone 0x00 is a prefix length of 0 with no address octets: the default route.
1036        let prefixes = parse_nlri_list(Bytes::from_static(&[0x00]), false, &Afi::Ipv4).unwrap();
1037        assert_eq!(prefixes.len(), 1);
1038        assert_eq!(prefixes[0].prefix.to_string(), "0.0.0.0/0");
1039        assert_eq!(prefixes[0].path_id, None);
1040    }
1041
1042    // A block whose first prefix is the default route is not an ADD-PATH block. Reading the 0x00 as
1043    // a path identifier shifted the decode and dropped or invented withdrawals (#360).
1044    fn assert_ipv4_block(block: &'static [u8], expected: &[&str]) {
1045        let prefixes = parse_nlri_list(Bytes::from_static(block), false, &Afi::Ipv4).unwrap();
1046        let got: Vec<String> = prefixes.iter().map(|p| p.prefix.to_string()).collect();
1047        assert_eq!(got, expected);
1048        assert!(
1049            prefixes.iter().all(|p| p.path_id.is_none()),
1050            "non-ADD-PATH block must not produce path ids"
1051        );
1052    }
1053
1054    #[test]
1055    fn test_parse_nlri_list_non_addpath_default_route_at_head() {
1056        assert_ipv4_block(
1057            &[
1058                0x00, // 0.0.0.0/0
1059                0x18, 0x01, 0x00, 0x00, // 1.0.0.0/24
1060                0x18, 0x01, 0x00, 0x04, // 1.0.4.0/24
1061                0x18, 0x01, 0x00, 0x05, // 1.0.5.0/24
1062                0x18, 0x01, 0x00, 0x06, // 1.0.6.0/24
1063            ],
1064            &[
1065                "0.0.0.0/0",
1066                "1.0.0.0/24",
1067                "1.0.4.0/24",
1068                "1.0.5.0/24",
1069                "1.0.6.0/24",
1070            ],
1071        );
1072    }
1073
1074    #[test]
1075    fn test_parse_nlri_list_non_addpath_default_route_in_middle() {
1076        assert_ipv4_block(
1077            &[
1078                0x18, 0x01, 0x00, 0x00, // 1.0.0.0/24
1079                0x00, // 0.0.0.0/0
1080                0x18, 0x01, 0x00, 0x04, // 1.0.4.0/24
1081            ],
1082            &["1.0.0.0/24", "0.0.0.0/0", "1.0.4.0/24"],
1083        );
1084    }
1085
1086    #[test]
1087    fn test_parse_nlri_list_non_addpath_default_route_at_tail() {
1088        assert_ipv4_block(
1089            &[
1090                0x18, 0x01, 0x00, 0x00, // 1.0.0.0/24
1091                0x18, 0x01, 0x00, 0x04, // 1.0.4.0/24
1092                0x00, // 0.0.0.0/0
1093            ],
1094            &["1.0.0.0/24", "1.0.4.0/24", "0.0.0.0/0"],
1095        );
1096    }
1097
1098    #[test]
1099    fn test_parse_nlri_list_non_addpath_ipv6_default_route_at_head() {
1100        let block = &[
1101            0x00, // ::/0
1102            0x30, 0x2a, 0x0a, 0x02, 0xc0, 0x00, 0x1a, // 2a0a:2c0:1a::/48
1103            0x2a, 0x26, 0x20, 0x01, 0x29, 0x20, 0x00, // 2620:129:2000::/42
1104            0x20, 0x28, 0x04, 0x50, 0x5c, // 2804:505c::/32
1105        ];
1106        let prefixes = parse_nlri_list(Bytes::from_static(block), false, &Afi::Ipv6).unwrap();
1107        let got: Vec<String> = prefixes.iter().map(|p| p.prefix.to_string()).collect();
1108        assert_eq!(
1109            got,
1110            vec![
1111                "::/0",
1112                "2a0a:2c0:1a::/48",
1113                "2620:129:2000::/42",
1114                "2804:505c::/32"
1115            ]
1116        );
1117        assert!(prefixes.iter().all(|p| p.path_id.is_none()));
1118    }
1119
1120    #[test]
1121    fn test_parse_nlri_list_ambiguous_block_prefers_add_path() {
1122        // Bytes from route-views.amsix 2020-06-17 18:30 UTC: ADD-PATH data under a non-ADD-PATH
1123        // subtype, one entry. Framing it without path ids yields a run of /0 prefixes, framing it
1124        // with them yields the real route. Both readings consume the block, and this is the reading
1125        // the data requires, so the guess stays on ties.
1126        let block = &[0x00, 0x00, 0x01, 0xe2, 0x18, 0x8a, 0x61, 0x16];
1127        // Both readings have to consume the block for this to be the tie the wrapper resolves.
1128        let framed = parse_nlri_list_exact(Bytes::from_static(block), false, &Afi::Ipv4).unwrap();
1129        assert_eq!(framed.len(), 4);
1130        assert!(framed.iter().all(|p| p.path_id.is_none()));
1131        let plain = parse_nlri_list(Bytes::from_static(block), false, &Afi::Ipv4).unwrap();
1132        assert_eq!(plain.len(), 1);
1133        assert_eq!(plain[0].prefix.to_string(), "138.97.22.0/24");
1134        assert_eq!(plain[0].path_id, Some(482));
1135    }
1136
1137    #[test]
1138    fn test_parse_nlri_list_short_ambiguous_block_is_read_as_add_path() {
1139        // 0.0.0.0/0 followed by one /24 also frames exactly as a single ADD-PATH entry, so the
1140        // guess stays on and the /24 is lost. The bytes decide nothing here; the limitation is
1141        // deliberate and recorded in the CHANGELOG.
1142        let block = &[0x00, 0x18, 0x01, 0x00, 0x00];
1143        let prefixes = parse_nlri_list(Bytes::from_static(block), false, &Afi::Ipv4).unwrap();
1144        assert_eq!(prefixes.len(), 1);
1145        assert_eq!(prefixes[0].prefix.to_string(), "0.0.0.0/0");
1146        assert!(prefixes[0].path_id.is_some());
1147    }
1148
1149    #[test]
1150    fn test_parse_nlri_list_wrapped_addpath_block_keeps_path_ids() {
1151        // ADD-PATH data under a non-ADD-PATH flag still has to decode with its path ids (#31).
1152        let block = &[
1153            0x00, 0x00, 0x00, 0x01, 0x18, 0xc0, 0xa8, 0x01, // path_id 1, 192.168.1.0/24
1154            0x00, 0x00, 0x00, 0x02, 0x18, 0xc0, 0xa8, 0x02, // path_id 2, 192.168.2.0/24
1155        ];
1156        let prefixes = parse_nlri_list(Bytes::from_static(block), false, &Afi::Ipv4).unwrap();
1157        assert_eq!(prefixes.len(), 2);
1158        assert_eq!(prefixes[0].prefix.to_string(), "192.168.1.0/24");
1159        assert_eq!(prefixes[1].prefix.to_string(), "192.168.2.0/24");
1160        assert_eq!(prefixes[0].path_id, Some(1));
1161        assert_eq!(prefixes[1].path_id, Some(2));
1162    }
1163}