use byteorder::{BigEndian, ReadBytesExt};
use std::fs::File;
use std::io::{BufReader, Error, ErrorKind, Read};
use std::path::Path;
pub mod records;
pub mod readahead;
pub fn open<P: AsRef<Path>>(path: P) -> std::io::Result<Box<dyn Read>> {
let mut file = File::open(path.as_ref())?;
let mut magic = [0u8; 2];
let read = read_full_or_partial(&mut file, &mut magic)?;
let prefix = std::io::Cursor::new(magic[..read].to_vec());
let chained: Box<dyn Read> = Box::new(prefix.chain(file));
if read == 2 && magic == [0x1F, 0x8B] {
Ok(Box::new(BufReader::with_capacity(
1 << 20,
flate2::read::MultiGzDecoder::new(chained),
)))
} else {
Ok(Box::new(BufReader::with_capacity(1 << 20, chained)))
}
}
fn read_full_or_partial(mut r: impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
let mut filled = 0;
while filled < buf.len() {
match r.read(&mut buf[filled..])? {
0 => break,
n => filled += n,
}
}
Ok(filled)
}
pub use records::bgp;
pub use records::bgp4mp;
pub use records::bgp4plus;
pub use records::isis;
pub use records::ospf;
pub use records::rip;
pub use records::tabledump;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum AFI {
IPV4 = 1,
IPV6 = 2,
}
impl AFI {
#[inline]
pub fn size(&self) -> u32 {
match self {
AFI::IPV4 => 4,
AFI::IPV6 => 16,
}
}
#[inline]
pub(crate) fn from_u16(value: u16) -> std::io::Result<Self> {
match value {
1 => Ok(AFI::IPV4),
2 => Ok(AFI::IPV6),
_ => Err(Error::new(ErrorKind::InvalidData, "invalid AFI value")),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
pub timestamp: u32,
pub extended: u32,
pub record_type: u16,
pub sub_type: u16,
pub length: u32,
}
#[derive(Debug)]
#[allow(missing_docs)]
#[allow(non_camel_case_types)]
pub enum Record {
NULL,
START,
DIE,
I_AM_DEAD,
PEER_DOWN,
BGP(records::bgp::BGP),
RIP(records::rip::RIP),
IDRP,
RIPNG(records::rip::RIPNG),
BGP4PLUS(records::bgp4plus::BGP4PLUS),
BGP4PLUS_01(records::bgp4plus::BGP4PLUS),
OSPFv2(records::ospf::OSPFv2),
TABLE_DUMP(records::tabledump::TABLE_DUMP),
TABLE_DUMP_V2(records::tabledump::TABLE_DUMP_V2),
BGP4MP(records::bgp4mp::BGP4MP),
BGP4MP_ET(records::bgp4mp::BGP4MP),
ISIS(Vec<u8>),
ISIS_ET(Vec<u8>),
OSPFv3(records::ospf::OSPFv3),
OSPFv3_ET(records::ospf::OSPFv3),
}
mod record_types {
pub const NULL: u16 = 0;
pub const START: u16 = 1;
pub const DIE: u16 = 2;
pub const I_AM_DEAD: u16 = 3;
pub const PEER_DOWN: u16 = 4;
pub const BGP: u16 = 5;
pub const RIP: u16 = 6;
pub const IDRP: u16 = 7;
pub const RIPNG: u16 = 8;
pub const BGP4PLUS: u16 = 9;
pub const BGP4PLUS_01: u16 = 10;
pub const OSPFV2: u16 = 11;
pub const TABLE_DUMP: u16 = 12;
pub const TABLE_DUMP_V2: u16 = 13;
pub const BGP4MP: u16 = 16;
pub const BGP4MP_ET: u16 = 17;
pub const ISIS: u16 = 32;
pub const ISIS_ET: u16 = 33;
pub const OSPFV3: u16 = 48;
pub const OSPFV3_ET: u16 = 49;
}
#[inline]
fn is_extended_type(record_type: u16) -> bool {
matches!(
record_type,
record_types::BGP4MP_ET | record_types::ISIS_ET | record_types::OSPFV3_ET
)
}
#[inline]
pub fn read(stream: &mut impl Read) -> Result<Option<(Header, Record)>, Error> {
let mut header_buf = [0u8; 12];
match stream.read_exact(&mut header_buf) {
Ok(()) => {}
Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let timestamp = u32::from_be_bytes([header_buf[0], header_buf[1], header_buf[2], header_buf[3]]);
let record_type = u16::from_be_bytes([header_buf[4], header_buf[5]]);
let sub_type = u16::from_be_bytes([header_buf[6], header_buf[7]]);
let length = u32::from_be_bytes([header_buf[8], header_buf[9], header_buf[10], header_buf[11]]);
let (extended, body_length) = if is_extended_type(record_type) {
let microseconds = stream.read_u32::<BigEndian>()?;
(microseconds, length.saturating_sub(4))
} else {
(0, length)
};
let header = Header {
timestamp,
extended,
record_type,
sub_type,
length,
};
let body_len = body_length as usize;
let mut body_buf = Vec::with_capacity(body_len);
unsafe {
body_buf.set_len(body_len);
}
stream.read_exact(&mut body_buf)?;
let record = parse_record(&header, &body_buf)?;
Ok(Some((header, record)))
}
#[inline]
pub fn read_with_buffer(
stream: &mut impl Read,
body_buf: &mut Vec<u8>,
) -> Result<Option<(Header, Record)>, Error> {
let mut header_buf = [0u8; 12];
match stream.read_exact(&mut header_buf) {
Ok(()) => {}
Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let timestamp = u32::from_be_bytes([header_buf[0], header_buf[1], header_buf[2], header_buf[3]]);
let record_type = u16::from_be_bytes([header_buf[4], header_buf[5]]);
let sub_type = u16::from_be_bytes([header_buf[6], header_buf[7]]);
let length = u32::from_be_bytes([header_buf[8], header_buf[9], header_buf[10], header_buf[11]]);
let (extended, body_length) = if is_extended_type(record_type) {
let microseconds = stream.read_u32::<BigEndian>()?;
(microseconds, length.saturating_sub(4))
} else {
(0, length)
};
let header = Header {
timestamp,
extended,
record_type,
sub_type,
length,
};
let body_len = body_length as usize;
if body_buf.capacity() >= body_len {
unsafe {
body_buf.set_len(body_len);
}
} else {
body_buf.clear();
body_buf.reserve(body_len);
unsafe {
body_buf.set_len(body_len);
}
}
stream.read_exact(body_buf)?;
let record = parse_record(&header, body_buf)?;
Ok(Some((header, record)))
}
#[inline]
pub fn read_header_only(stream: &mut (impl Read + std::io::Seek)) -> Result<Option<Header>, Error> {
use std::io::SeekFrom;
let timestamp = match stream.read_u32::<BigEndian>() {
Ok(ts) => ts,
Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
};
let record_type = stream.read_u16::<BigEndian>()?;
let sub_type = stream.read_u16::<BigEndian>()?;
let length = stream.read_u32::<BigEndian>()?;
let extended = if is_extended_type(record_type) {
stream.read_u32::<BigEndian>()?
} else {
0
};
let skip_len = if is_extended_type(record_type) {
length.saturating_sub(4)
} else {
length
};
stream.seek(SeekFrom::Current(skip_len as i64))?;
Ok(Some(Header {
timestamp,
extended,
record_type,
sub_type,
length,
}))
}
#[inline]
fn parse_record(header: &Header, body: &[u8]) -> Result<Record, Error> {
use record_types::*;
let mut cursor = std::io::Cursor::new(body);
match header.record_type {
NULL => Ok(Record::NULL),
START => Ok(Record::START),
DIE => Ok(Record::DIE),
I_AM_DEAD => Ok(Record::I_AM_DEAD),
PEER_DOWN => Ok(Record::PEER_DOWN),
BGP => Ok(Record::BGP(records::bgp::BGP::parse(header, &mut cursor)?)),
RIP => Ok(Record::RIP(records::rip::RIP::parse(header, &mut cursor)?)),
IDRP => Ok(Record::IDRP),
RIPNG => Ok(Record::RIPNG(records::rip::RIPNG::parse(
header,
&mut cursor,
)?)),
BGP4PLUS => Ok(Record::BGP4PLUS(records::bgp4plus::BGP4PLUS::parse(
header,
&mut cursor,
)?)),
BGP4PLUS_01 => Ok(Record::BGP4PLUS_01(records::bgp4plus::BGP4PLUS::parse(
header,
&mut cursor,
)?)),
OSPFV2 => Ok(Record::OSPFv2(records::ospf::OSPFv2::parse(
header,
&mut cursor,
)?)),
TABLE_DUMP => Ok(Record::TABLE_DUMP(records::tabledump::TABLE_DUMP::parse(
header,
&mut cursor,
)?)),
TABLE_DUMP_V2 => Ok(Record::TABLE_DUMP_V2(
records::tabledump::TABLE_DUMP_V2::parse(header, &mut cursor)?,
)),
BGP4MP => Ok(Record::BGP4MP(records::bgp4mp::BGP4MP::parse(
header,
&mut cursor,
)?)),
BGP4MP_ET => Ok(Record::BGP4MP_ET(records::bgp4mp::BGP4MP::parse(
header,
&mut cursor,
)?)),
ISIS => Ok(Record::ISIS(records::isis::parse(header, &mut cursor)?)),
ISIS_ET => Ok(Record::ISIS_ET(records::isis::parse(header, &mut cursor)?)),
OSPFV3 => Ok(Record::OSPFv3(records::ospf::OSPFv3::parse(
header,
&mut cursor,
)?)),
OSPFV3_ET => Ok(Record::OSPFv3_ET(records::ospf::OSPFv3::parse(
header,
&mut cursor,
)?)),
_ => Err(Error::new(ErrorKind::InvalidData, "unknown record type")),
}
}
pub(crate) mod address {
use byteorder::{BigEndian, ReadBytesExt};
use std::io::Read;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use crate::AFI;
#[inline]
pub fn read_ipv4(stream: &mut impl Read) -> std::io::Result<Ipv4Addr> {
Ok(Ipv4Addr::from(stream.read_u32::<BigEndian>()?))
}
#[inline]
pub fn read_ipv6(stream: &mut impl Read) -> std::io::Result<Ipv6Addr> {
Ok(Ipv6Addr::from(stream.read_u128::<BigEndian>()?))
}
#[inline]
pub fn read_ip_by_afi(stream: &mut impl Read, afi: &AFI) -> std::io::Result<IpAddr> {
match afi {
AFI::IPV4 => Ok(IpAddr::V4(read_ipv4(stream)?)),
AFI::IPV6 => Ok(IpAddr::V6(read_ipv6(stream)?)),
}
}
#[inline]
pub fn read_afi(stream: &mut impl Read) -> std::io::Result<AFI> {
let afi_raw = stream.read_u16::<BigEndian>()?;
AFI::from_u16(afi_raw)
}
#[inline]
pub fn prefix_bytes_needed(prefix_length: u8) -> usize {
((prefix_length as usize) + 7) / 8
}
#[inline]
pub fn read_prefix(stream: &mut impl Read, prefix_length: u8) -> std::io::Result<Vec<u8>> {
let bytes_needed = prefix_bytes_needed(prefix_length);
let mut prefix = vec![0u8; bytes_needed];
stream.read_exact(&mut prefix)?;
Ok(prefix)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_afi_size() {
assert_eq!(AFI::IPV4.size(), 4);
assert_eq!(AFI::IPV6.size(), 16);
}
#[test]
fn test_afi_repr() {
assert_eq!(std::mem::size_of::<AFI>(), 2);
assert_eq!(AFI::IPV4 as u16, 1);
assert_eq!(AFI::IPV6 as u16, 2);
}
#[test]
fn test_read_eof_at_start() {
let data: &[u8] = &[];
let result = read(&mut data.as_ref());
assert!(result.unwrap().is_none());
}
#[test]
fn test_read_null_record() {
let data: &[u8] = &[
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
let result = read(&mut data.as_ref()).unwrap().unwrap();
assert_eq!(result.0.timestamp, 1);
assert!(matches!(result.1, Record::NULL));
}
#[test]
fn test_read_start_record() {
let data: &[u8] = &[
0x5F, 0x5E, 0x10, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
let result = read(&mut data.as_ref()).unwrap().unwrap();
assert!(matches!(result.1, Record::START));
}
#[test]
fn test_read_unknown_type_error() {
let data: &[u8] = &[
0x00, 0x00, 0x00, 0x01, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
let result = read(&mut data.as_ref());
assert!(result.is_err());
assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidData);
}
#[test]
fn test_is_extended_type() {
assert!(!is_extended_type(16)); assert!(is_extended_type(17)); assert!(!is_extended_type(32)); assert!(is_extended_type(33)); assert!(!is_extended_type(48)); assert!(is_extended_type(49)); }
}