netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
//! Raw packet representation for zero-allocation packet construction.
//!
//! [`RawPacket`] is a fixed-size buffer that holds a complete Ethernet + IP +
//! TCP frame. Templates are pre-built once, then stamped with per-target
//! fields (dst IP, dst port, checksums) via direct byte writes.

use std::net::Ipv4Addr;

/// Maximum raw packet size. Covers Ethernet (14) + IP (20) + TCP (20) + payload.
/// 1514 bytes = standard Ethernet MTU frame.
pub const MAX_PACKET_SIZE: usize = 1514;

/// Minimum TCP SYN packet: IP header (20) + TCP header (20) = 40 bytes.
pub const MIN_SYN_SIZE: usize = 40;

/// A raw network packet stored in a fixed-size stack buffer.
///
/// No heap allocation. Packets are constructed by stamping pre-built templates.
#[derive(Clone)]
pub struct RawPacket {
    /// Raw bytes. Only `buf[..len]` is valid.
    pub buf: [u8; MAX_PACKET_SIZE],
    /// Valid length of the packet.
    pub len: u16,
}

impl RawPacket {
    /// Create an empty packet.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            buf: [0u8; MAX_PACKET_SIZE],
            len: 0,
        }
    }

    /// Create a packet from a byte slice.
    ///
    /// Returns `None` if `data` exceeds [`MAX_PACKET_SIZE`].
    #[must_use]
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() > MAX_PACKET_SIZE {
            return None;
        }
        let mut pkt = Self::empty();
        pkt.buf[..data.len()].copy_from_slice(data);
        pkt.len = data.len() as u16;
        Some(pkt)
    }

    /// Valid packet bytes.
    ///
    /// The slice is clamped to the backing buffer: `len` is a public field, so
    /// a caller can set it beyond [`MAX_PACKET_SIZE`]; slicing through this
    /// clamp degrades such misuse to truncation instead of a panic.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        &self.buf[..self.clamped_len()]
    }

    /// Mutable access to valid packet bytes.
    ///
    /// Clamped like [`RawPacket::as_bytes`].
    #[inline]
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        let end = self.clamped_len();
        &mut self.buf[..end]
    }

    /// `len` clamped to the backing buffer. Every slice derived from the
    /// packet goes through this clamp (see [`RawPacket::as_bytes`]).
    #[inline]
    pub(crate) fn clamped_len(&self) -> usize {
        (self.len as usize).min(MAX_PACKET_SIZE)
    }
}

impl Default for RawPacket {
    fn default() -> Self {
        Self::empty()
    }
}

impl std::fmt::Debug for RawPacket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RawPacket")
            .field("len", &self.len)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// SYN packet template builder
// ---------------------------------------------------------------------------

/// Offsets within an IP + TCP packet (no Ethernet header).
/// These are Layer 3 offsets for use with raw sockets.
pub mod offsets {
    /// IP header: destination address (bytes 16..20).
    pub const IP_DST: usize = 16;
    /// IP header: source address (bytes 12..16).
    pub const IP_SRC: usize = 12;
    /// IP header: total length (bytes 2..4).
    pub const IP_TOTAL_LEN: usize = 2;
    /// IP header: checksum (bytes 10..12).
    pub const IP_CHECKSUM: usize = 10;
    /// TCP header start (byte 20 for standard IP header).
    pub const TCP_START: usize = 20;
    /// TCP: source port (TCP_START + 0..2).
    pub const TCP_SRC_PORT: usize = 20;
    /// TCP: destination port (TCP_START + 2..4).
    pub const TCP_DST_PORT: usize = 22;
    /// TCP: sequence number (TCP_START + 4..8).
    pub const TCP_SEQ: usize = 24;
    /// TCP: acknowledgement number (TCP_START + 8..12).
    pub const TCP_ACK: usize = 28;
    /// TCP: data offset + flags (TCP_START + 12..14).
    pub const TCP_FLAGS: usize = 32;
    /// TCP: window size (TCP_START + 14..16).
    pub const TCP_WINDOW: usize = 34;
    /// TCP: checksum (TCP_START + 16..18).
    pub const TCP_CHECKSUM: usize = 36;
}

/// Build a SYN packet template. Only `dst_ip`, `dst_port`, `seq`, and checksums
/// need to be stamped per-target.
pub fn build_syn_template(src_ip: Ipv4Addr, src_port: u16) -> RawPacket {
    let mut pkt = RawPacket::empty();
    pkt.len = MIN_SYN_SIZE as u16;

    let buf = &mut pkt.buf;

    // --- IP Header (20 bytes) ---
    buf[0] = 0x45; // Version 4, IHL 5 (20 bytes)
    buf[1] = 0x00; // DSCP/ECN
    let total_len = MIN_SYN_SIZE as u16;
    buf[offsets::IP_TOTAL_LEN..offsets::IP_TOTAL_LEN + 2]
        .copy_from_slice(&total_len.to_be_bytes());
    buf[4..6].copy_from_slice(&[0x00, 0x00]); // Identification
    buf[6..8].copy_from_slice(&[0x40, 0x00]); // Don't Fragment
    buf[8] = 64; // TTL
    buf[9] = 6; // Protocol: TCP
    // IP checksum at [10..12]  -  computed per-target
    let src_octets = src_ip.octets();
    buf[offsets::IP_SRC..offsets::IP_SRC + 4].copy_from_slice(&src_octets);
    // dst IP at [16..20]  -  stamped per-target

    // --- TCP Header (20 bytes) ---
    buf[offsets::TCP_SRC_PORT..offsets::TCP_SRC_PORT + 2]
        .copy_from_slice(&src_port.to_be_bytes());
    // dst port at [22..24]  -  stamped per-target
    // seq at [24..28]  -  stamped per-target
    buf[offsets::TCP_ACK..offsets::TCP_ACK + 4].copy_from_slice(&0u32.to_be_bytes());
    // Data offset (5 = 20 bytes) + SYN flag
    buf[offsets::TCP_FLAGS] = 0x50; // Data offset = 5 (20 bytes)
    buf[offsets::TCP_FLAGS + 1] = 0x02; // SYN flag
    buf[offsets::TCP_WINDOW..offsets::TCP_WINDOW + 2]
        .copy_from_slice(&64240u16.to_be_bytes()); // Window size
    // TCP checksum at [36..38]  -  computed per-target
    buf[38..40].copy_from_slice(&[0x00, 0x00]); // Urgent pointer

    pkt
}

/// Stamp a SYN template with target-specific fields and compute checksums.
///
/// This is the hot path  -  called once per target per port. Must be as fast
/// as possible: 4 writes + 2 checksum computations.
pub fn stamp_syn(
    template: &mut RawPacket,
    dst_ip: Ipv4Addr,
    dst_port: u16,
    seq: u32,
) {
    if template.len < MIN_SYN_SIZE as u16 {
        template.len = MIN_SYN_SIZE as u16;
    }
    let tcp_end = template.clamped_len();
    let buf = &mut template.buf;
    let dst_octets = dst_ip.octets();

    // Stamp target fields
    buf[offsets::IP_DST..offsets::IP_DST + 4].copy_from_slice(&dst_octets);
    buf[offsets::TCP_DST_PORT..offsets::TCP_DST_PORT + 2]
        .copy_from_slice(&dst_port.to_be_bytes());
    buf[offsets::TCP_SEQ..offsets::TCP_SEQ + 4]
        .copy_from_slice(&seq.to_be_bytes());

    // Compute IP checksum
    buf[offsets::IP_CHECKSUM..offsets::IP_CHECKSUM + 2].copy_from_slice(&[0, 0]);
    let ip_cksum = crate::checksum::ip_checksum(&buf[..20]);
    buf[offsets::IP_CHECKSUM..offsets::IP_CHECKSUM + 2]
        .copy_from_slice(&ip_cksum.to_be_bytes());

    // Compute TCP checksum (requires pseudo-header)
    buf[offsets::TCP_CHECKSUM..offsets::TCP_CHECKSUM + 2].copy_from_slice(&[0, 0]);
    let src_ip: [u8; 4] = buf[offsets::IP_SRC..offsets::IP_SRC + 4]
        .try_into()
        .expect("IP_SRC..+4 is exactly 4 bytes");
    let dst_ip: [u8; 4] = buf[offsets::IP_DST..offsets::IP_DST + 4]
        .try_into()
        .expect("IP_DST..+4 is exactly 4 bytes");
    let tcp_cksum = crate::checksum::tcp_checksum(
        src_ip,
        dst_ip,
        &buf[offsets::TCP_START..tcp_end],
    );
    buf[offsets::TCP_CHECKSUM..offsets::TCP_CHECKSUM + 2]
        .copy_from_slice(&tcp_cksum.to_be_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn syn_template_has_correct_length() {
        let pkt = build_syn_template(Ipv4Addr::new(10, 0, 0, 1), 49152);
        assert_eq!(pkt.len, 40);
    }

    #[test]
    fn stamp_syn_produces_valid_checksums() {
        let mut pkt = build_syn_template(Ipv4Addr::new(10, 0, 0, 1), 49152);
        stamp_syn(&mut pkt, Ipv4Addr::new(1, 1, 1, 1), 80, 0x12345678);

        // Re-running the one's-complement checksum over a header that already
        // carries its embedded checksum must verify to 0 (ip_checksum returns
        // the inverted folded sum, so a self-consistent header yields 0x0000).
        let ip_sum = crate::checksum::ip_checksum(&pkt.buf[..20]);
        assert_eq!(
            ip_sum, 0,
            "IP header did not verify against its own embedded checksum"
        );
    }

    #[test]
    fn empty_packet_is_zeroed() {
        let pkt = RawPacket::empty();
        assert_eq!(pkt.len, 0);
        assert!(pkt.buf.iter().all(|&b| b == 0));
    }

    #[test]
    fn from_bytes_respects_max_size() {
        let data = vec![0xABu8; MAX_PACKET_SIZE];
        assert!(RawPacket::from_bytes(&data).is_some());

        let too_big = vec![0xABu8; MAX_PACKET_SIZE + 1];
        assert!(RawPacket::from_bytes(&too_big).is_none());
    }

    /// Regression: an oversized public `len` must not panic or leak memory.
    ///
    /// `len` is a public `u16` field, so a caller can set it beyond
    /// `MAX_PACKET_SIZE`. Before the clamp, `as_bytes` panicked on the
    /// out-of-range slice and the sendmmsg backend passed the raw value to the
    /// kernel as `iov_len`, transmitting memory past the buffer on the wire.
    /// Slices derived from the packet are now clamped to the buffer.
    #[test]
    fn oversized_public_len_is_clamped_not_panicking() {
        let mut pkt = build_syn_template(Ipv4Addr::new(10, 0, 0, 1), 49152);
        pkt.len = u16::MAX; // hostile value, far past the 1514-byte buffer

        assert_eq!(pkt.as_bytes().len(), MAX_PACKET_SIZE);
        assert_eq!(pkt.as_bytes_mut().len(), MAX_PACKET_SIZE);

        // The hot path must tolerate the same hostile value without panicking.
        stamp_syn(&mut pkt, Ipv4Addr::new(1, 1, 1, 1), 80, 0x1234_5678);
    }
    /// Regression: an undersized template (e.g. `RawPacket::empty()`) must be
    /// expanded to minimum SYN size rather than panicking on a slice index out of range.
    #[test]
    fn undersized_template_is_expanded_without_panicking() {
        let mut pkt = RawPacket::empty();
        assert_eq!(pkt.len, 0);
        stamp_syn(&mut pkt, Ipv4Addr::new(1, 1, 1, 1), 80, 0x1234_5678);
        assert_eq!(pkt.len, MIN_SYN_SIZE as u16);
    }
}