use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Chain, Cursor, Read};
use std::net::{Ipv4Addr, SocketAddrV4};
use std::path::Path;
use std::time::Duration;
use etherparse::{IpNumber, LaxNetSlice, LaxSlicedPacket, TcpSlice, UdpSlice};
use pcap_file::PcapError;
use pcap_file::pcap::PcapReader;
use pcap_file::pcapng::blocks::interface_description::{
InterfaceDescriptionBlock, InterfaceDescriptionOption,
};
use pcap_file::pcapng::{Block, PcapNgReader};
use crate::sparse::Sparse;
use crate::{Error, Packet, Result, Transport};
const PCAPNG_SECTION_HEADER: [u8; 4] = [0x0a, 0x0d, 0x0d, 0x0a];
const PCAP_MAGICS: [[u8; 4]; 4] = [
[0xa1, 0xb2, 0xc3, 0xd4],
[0xd4, 0xc3, 0xb2, 0xa1],
[0xa1, 0xb2, 0x3c, 0x4d],
[0x4d, 0x3c, 0xb2, 0xa1],
];
const LINKTYPE_ETHERNET: u32 = 1;
const DEFAULT_TS_DIVISOR: u64 = 1_000_000;
const MAX_PENDING_DATAGRAMS: usize = 1024;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Format {
Pcap,
PcapNg,
}
type Rewound<R> = BufReader<Chain<Cursor<[u8; 4]>, R>>;
enum Source<R: Read> {
Pcap(Box<PcapReader<Rewound<R>>>),
PcapNg(Box<PcapNgReader<Rewound<R>>>),
}
#[derive(Clone, Copy, Debug)]
struct Interface {
link_type: u32,
ts_divisor: u64,
reported: bool,
}
pub struct Capture<R: Read> {
source: Source<R>,
interfaces: Vec<Interface>,
defragmenter: Defragmenter,
index: u64,
finished: bool,
}
impl Capture<File> {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::new(File::open(path)?)
}
}
impl<R: Read> Capture<R> {
pub fn new(mut reader: R) -> Result<Self> {
let mut magic = [0u8; 4];
let mut filled = 0usize;
while filled < magic.len() {
let Some(rest) = magic.get_mut(filled..) else {
break;
};
match reader.read(rest) {
Ok(0) => return Err(Error::NotACapture { magic }),
Ok(read) => filled = filled.saturating_add(read),
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
Err(error) => return Err(error.into()),
}
}
let rewound = BufReader::new(Cursor::new(magic).chain(reader));
if magic == PCAPNG_SECTION_HEADER {
let reader = PcapNgReader::new(rewound).map_err(convert)?;
return Ok(Self::from_source(
Source::PcapNg(Box::new(reader)),
Vec::new(),
));
}
if PCAP_MAGICS.contains(&magic) {
let reader = PcapReader::new(rewound).map_err(convert)?;
let link_type = u32::from(reader.header().datalink);
if link_type != LINKTYPE_ETHERNET {
return Err(Error::UnsupportedLinkType { link_type });
}
let interface = Interface {
link_type,
ts_divisor: DEFAULT_TS_DIVISOR,
reported: false,
};
return Ok(Self::from_source(
Source::Pcap(Box::new(reader)),
vec![interface],
));
}
Err(Error::NotACapture { magic })
}
fn from_source(source: Source<R>, interfaces: Vec<Interface>) -> Self {
Self {
source,
interfaces,
defragmenter: Defragmenter::new(),
index: 0,
finished: false,
}
}
pub fn format(&self) -> Format {
match self.source {
Source::Pcap(_) => Format::Pcap,
Source::PcapNg(_) => Format::PcapNg,
}
}
pub fn udp_to(self, port: u16) -> UdpTo<R> {
UdpTo {
capture: self,
port,
}
}
}
impl<R: Read> std::fmt::Debug for Capture<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Capture")
.field("format", &self.format())
.field("interfaces", &self.interfaces.len())
.field("frames_read", &self.index)
.finish_non_exhaustive()
}
}
impl<R: Read> Iterator for Capture<R> {
type Item = Result<Packet>;
fn next(&mut self) -> Option<Self::Item> {
while !self.finished {
let outcome = match &mut self.source {
Source::Pcap(reader) => {
let Some(frame) = reader.next_packet() else {
self.finished = true;
return None;
};
match frame {
Ok(frame) => {
self.index = self.index.saturating_add(1);
dissect(
&mut self.defragmenter,
&frame.data,
0,
self.index,
frame.timestamp,
)
.map(Ok)
}
Err(error) => Some(Err(convert(error))),
}
}
Source::PcapNg(reader) => {
let Some(block) = reader.next_block() else {
self.finished = true;
return None;
};
match block {
Ok(block) => step_pcapng(
block,
&mut self.interfaces,
&mut self.defragmenter,
&mut self.index,
),
Err(error) => Some(Err(convert(error))),
}
}
};
match outcome {
Some(Ok(packet)) => return Some(Ok(packet)),
Some(Err(error)) => {
if !matches!(error, Error::UnsupportedLinkType { .. }) {
self.finished = true;
}
return Some(Err(error));
}
None => {}
}
}
None
}
}
fn step_pcapng(
block: Block<'_>,
interfaces: &mut Vec<Interface>,
defragmenter: &mut Defragmenter,
index: &mut u64,
) -> Option<Result<Packet>> {
match block {
Block::SectionHeader(_) => {
interfaces.clear();
None
}
Block::InterfaceDescription(idb) => {
interfaces.push(Interface {
link_type: u32::from(idb.linktype),
ts_divisor: timestamp_divisor(&idb),
reported: false,
});
None
}
Block::EnhancedPacket(epb) => {
*index = index.saturating_add(1);
let interface_id = epb.interface_id;
let Some(interface) = usize::try_from(interface_id)
.ok()
.and_then(|id| interfaces.get_mut(id))
else {
return Some(Err(Error::Malformed {
reason: format!("packet block names interface {interface_id}, undeclared"),
}));
};
if interface.link_type != LINKTYPE_ETHERNET {
if interface.reported {
return None;
}
interface.reported = true;
return Some(Err(Error::UnsupportedLinkType {
link_type: interface.link_type,
}));
}
let timestamp = rescale(epb.timestamp, interface.ts_divisor);
dissect(defragmenter, &epb.data, interface_id, *index, timestamp).map(Ok)
}
Block::SimplePacket(spb) => {
*index = index.saturating_add(1);
let link_type = interfaces
.first()
.map_or(LINKTYPE_ETHERNET, |i| i.link_type);
if link_type != LINKTYPE_ETHERNET {
return None;
}
dissect(defragmenter, &spb.data, 0, *index, Duration::ZERO).map(Ok)
}
_ => None,
}
}
fn timestamp_divisor(idb: &InterfaceDescriptionBlock<'_>) -> u64 {
for option in &idb.options {
if let InterfaceDescriptionOption::IfTsResol(resolution) = *option {
return if resolution & 0x80 == 0 {
10u64
.checked_pow(u32::from(resolution))
.unwrap_or(DEFAULT_TS_DIVISOR)
} else {
1u64.checked_shl(u32::from(resolution & 0x7f))
.unwrap_or(DEFAULT_TS_DIVISOR)
};
}
}
DEFAULT_TS_DIVISOR
}
fn rescale(raw: Duration, divisor: u64) -> Duration {
let ticks = raw.as_nanos();
let divisor = u128::from(divisor);
let Some(seconds) = ticks.checked_div(divisor) else {
return Duration::ZERO;
};
let nanos = ticks
.checked_rem(divisor)
.and_then(|fraction| fraction.checked_mul(1_000_000_000))
.and_then(|scaled| scaled.checked_div(divisor))
.unwrap_or(0);
Duration::new(
u64::try_from(seconds).unwrap_or(u64::MAX),
u32::try_from(nanos).unwrap_or(0),
)
}
fn dissect(
defragmenter: &mut Defragmenter,
frame: &[u8],
interface: u32,
index: u64,
timestamp: Duration,
) -> Option<Packet> {
let sliced = LaxSlicedPacket::from_ethernet(frame).ok()?;
let Some(LaxNetSlice::Ipv4(ipv4)) = sliced.net else {
return None;
};
let header = ipv4.header();
let source_ip = header.source_addr();
let destination_ip = header.destination_addr();
let ip_payload = ipv4.payload();
let assembled;
let (protocol, payload) = if ip_payload.fragmented {
let key = FragmentKey {
interface,
source: source_ip,
destination: destination_ip,
identification: header.identification(),
protocol: ip_payload.ip_number,
};
assembled = defragmenter.add(
key,
index,
u64::from(header.fragments_offset().byte_offset()),
ip_payload.payload,
header.more_fragments(),
)?;
(ip_payload.ip_number, assembled.as_slice())
} else {
(ip_payload.ip_number, ip_payload.payload)
};
let segment = parse_transport(protocol, payload)?;
Some(Packet {
index,
timestamp,
interface,
source: SocketAddrV4::new(source_ip, segment.source_port),
destination: SocketAddrV4::new(destination_ip, segment.destination_port),
transport: segment.transport,
payload: segment.payload.to_vec(),
})
}
struct Segment<'a> {
source_port: u16,
destination_port: u16,
transport: Transport,
payload: &'a [u8],
}
fn parse_transport(protocol: IpNumber, payload: &[u8]) -> Option<Segment<'_>> {
if protocol == IpNumber::UDP {
let udp = UdpSlice::from_slice_lax(payload).ok()?;
return Some(Segment {
source_port: udp.source_port(),
destination_port: udp.destination_port(),
transport: Transport::Udp,
payload: udp.payload(),
});
}
if protocol == IpNumber::TCP {
let tcp = TcpSlice::from_slice(payload).ok()?;
return Some(Segment {
source_port: tcp.source_port(),
destination_port: tcp.destination_port(),
transport: Transport::Tcp {
sequence: tcp.sequence_number(),
syn: tcp.syn(),
fin: tcp.fin(),
reset: tcp.rst(),
},
payload: tcp.payload(),
});
}
None
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct FragmentKey {
interface: u32,
source: Ipv4Addr,
destination: Ipv4Addr,
identification: u16,
protocol: IpNumber,
}
struct Pending {
bytes: Sparse,
total: Option<u64>,
last_seen: u64,
}
struct Defragmenter {
pending: HashMap<FragmentKey, Pending>,
}
impl Defragmenter {
fn new() -> Self {
Self {
pending: HashMap::new(),
}
}
fn add(
&mut self,
key: FragmentKey,
index: u64,
offset: u64,
payload: &[u8],
more_fragments: bool,
) -> Option<Vec<u8>> {
if self.pending.len() > MAX_PENDING_DATAGRAMS {
let horizon = index.saturating_sub(
u64::try_from(MAX_PENDING_DATAGRAMS).unwrap_or(u64::from(u32::MAX)),
);
self.pending
.retain(|_, pending| pending.last_seen >= horizon);
}
let entry = self.pending.entry(key).or_insert_with(|| Pending {
bytes: Sparse::new(),
total: None,
last_seen: index,
});
entry.last_seen = index;
entry.bytes.insert(offset, payload);
if !more_fragments {
entry.total = Some(offset.saturating_add(payload.len().try_into().unwrap_or(u64::MAX)));
}
let total = entry.total?;
let complete = entry
.bytes
.contiguous()
.is_some_and(|bytes| u64::try_from(bytes.len()).unwrap_or(u64::MAX) >= total);
if !complete {
return None;
}
let mut assembled = self.pending.remove(&key)?.bytes.contiguous()?.to_vec();
assembled.truncate(usize::try_from(total).unwrap_or(usize::MAX));
Some(assembled)
}
}
#[derive(Debug)]
pub struct UdpTo<R: Read> {
capture: Capture<R>,
port: u16,
}
impl<R: Read> Iterator for UdpTo<R> {
type Item = Result<Packet>;
fn next(&mut self) -> Option<Self::Item> {
loop {
match self.capture.next()? {
Ok(packet) => {
if packet.transport.is_udp() && packet.destination.port() == self.port {
return Some(Ok(packet));
}
}
Err(error) => return Some(Err(error)),
}
}
}
}
fn convert(error: PcapError) -> Error {
match error {
PcapError::IncompleteBuffer => Error::Truncated,
PcapError::IoError(inner) if inner.kind() == std::io::ErrorKind::UnexpectedEof => {
Error::Truncated
}
PcapError::IoError(inner) => Error::Io(inner),
other => Error::Malformed {
reason: other.to_string(),
},
}
}