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