use std::fmt;
use std::net::SocketAddrV4;
use std::time::Duration;
#[derive(Clone, PartialEq, Eq)]
pub struct Packet {
pub index: u64,
pub timestamp: Duration,
pub interface: u32,
pub source: SocketAddrV4,
pub destination: SocketAddrV4,
pub transport: Transport,
pub payload: Vec<u8>,
}
impl Packet {
pub fn udp_payload_to(&self, port: u16) -> Option<&[u8]> {
(self.transport == Transport::Udp && self.destination.port() == port)
.then_some(self.payload.as_slice())
}
}
impl fmt::Debug for Packet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let protocol = match self.transport {
Transport::Udp => "udp",
Transport::Tcp { .. } => "tcp",
};
write!(
f,
"#{} {:.6}s {protocol} {} -> {} {}B",
self.index,
self.timestamp.as_secs_f64(),
self.source,
self.destination,
self.payload.len()
)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Transport {
Udp,
Tcp {
sequence: u32,
syn: bool,
fin: bool,
reset: bool,
},
}
impl Transport {
pub fn is_udp(self) -> bool {
matches!(self, Self::Udp)
}
pub fn is_tcp(self) -> bool {
matches!(self, Self::Tcp { .. })
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Flow {
pub source: SocketAddrV4,
pub destination: SocketAddrV4,
}
impl Flow {
pub fn of(packet: &Packet) -> Self {
Self {
source: packet.source,
destination: packet.destination,
}
}
#[must_use]
pub fn reversed(self) -> Self {
Self {
source: self.destination,
destination: self.source,
}
}
pub fn involves(self, port: u16) -> bool {
self.source.port() == port || self.destination.port() == port
}
}
impl fmt::Debug for Flow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} -> {}", self.source, self.destination)
}
}