use std::net::IpAddr;
use crate::builder::BuildError;
use crate::packet::Packet;
use crate::udp::{UDP_HEADER_LEN, UdpHeader, UdpPacket};
use bytes::Bytes;
#[derive(Debug, Clone)]
pub struct UdpPacketBuilder {
src_ip: IpAddr,
dst_ip: IpAddr,
packet: UdpPacket,
}
impl UdpPacketBuilder {
pub fn new(src_ip: IpAddr, dst_ip: IpAddr) -> Self {
Self {
src_ip,
dst_ip,
packet: UdpPacket {
header: UdpHeader {
source: 0,
destination: 0,
length: 0, checksum: 0,
},
payload: Bytes::new(),
},
}
}
pub fn source(mut self, port: u16) -> Self {
self.packet.header.source = port;
self
}
pub fn destination(mut self, port: u16) -> Self {
self.packet.header.destination = port;
self
}
pub fn checksum(mut self, checksum: u16) -> Self {
self.packet.header.checksum = checksum;
self
}
pub fn payload(mut self, data: Bytes) -> Self {
self.packet.payload = data;
self
}
pub fn calculate_checksum(mut self) -> Self {
self.packet.header.checksum =
crate::udp::checksum(&self.packet, &self.src_ip, &self.dst_ip);
self
}
pub fn build(mut self) -> Result<UdpPacket, BuildError> {
if !matches!(
(self.src_ip, self.dst_ip),
(IpAddr::V4(_), IpAddr::V4(_)) | (IpAddr::V6(_), IpAddr::V6(_))
) {
return Err(BuildError::AddressFamilyMismatch { context: "UDP" });
}
let total_len = UDP_HEADER_LEN
.checked_add(self.packet.payload.len())
.ok_or(BuildError::LengthOverflow {
context: "UDP length",
maximum: u16::MAX as usize,
actual: usize::MAX,
})?;
if total_len > u16::MAX as usize {
return Err(BuildError::LengthOverflow {
context: "UDP length",
maximum: u16::MAX as usize,
actual: total_len,
});
}
self.packet.header.length = total_len as u16;
self.packet.header.checksum =
crate::udp::checksum(&self.packet, &self.src_ip, &self.dst_ip);
Ok(self.packet)
}
pub fn to_bytes(self) -> Result<Bytes, BuildError> {
self.build().map(|packet| packet.to_bytes())
}
pub fn header_bytes(&self) -> Result<Bytes, BuildError> {
self.clone().build().map(|packet| packet.header())
}
}
#[cfg(test)]
mod tests {
use std::net::Ipv4Addr;
use super::*;
use bytes::Bytes;
#[test]
fn udp_builder_sets_length() {
let pkt = UdpPacketBuilder::new(
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100)),
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
)
.source(1)
.destination(2)
.payload(Bytes::from_static(&[1, 2, 3]))
.build()
.expect("valid UDP packet");
assert_eq!(pkt.header.length, (UDP_HEADER_LEN + 3) as u16);
assert_eq!(pkt.payload, Bytes::from_static(&[1, 2, 3]));
}
#[test]
fn udp_builder_rejects_oversized_payload() {
let error = UdpPacketBuilder::new(
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V4(Ipv4Addr::LOCALHOST),
)
.payload(Bytes::from(vec![0; u16::MAX as usize]))
.build()
.expect_err("UDP length overflow");
assert!(matches!(
error,
BuildError::LengthOverflow {
context: "UDP length",
..
}
));
}
}