netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
//! TCP/IP checksum computation.
//!
//! Internet checksums are ones-complement sums of 16-bit words. The current
//! implementation is a portable scalar loop; future work may add an AVX2
//! SIMD path, but that acceleration is not present today and the docs
//! previously falsely claimed it was.

/// Compute the Internet checksum (RFC 1071) over a byte slice.
///
/// Used for both IP and TCP header checksums. The input should have the
/// checksum field zeroed before calling.
#[inline]
pub fn ones_complement_sum(data: &[u8]) -> u16 {
    let mut sum: u32 = 0;
    let mut chunks = data.chunks_exact(2);

    for chunk in &mut chunks {
        sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
    }

    // Handle odd byte
    if let Some(&last) = chunks.remainder().first() {
        sum += (last as u32) << 8;
    }

    // Fold 32-bit sum into 16-bit
    while sum >> 16 != 0 {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }

    !(sum as u16)
}

/// Compute IP header checksum.
///
/// The checksum field in the header (bytes 10-11) must be zeroed before calling.
#[inline]
pub fn ip_checksum(ip_header: &[u8]) -> u16 {
    ones_complement_sum(ip_header)
}

/// Compute TCP checksum including the pseudo-header.
///
/// # Arguments
/// - `src_ip`: source IPv4 address octets
/// - `dst_ip`: destination IPv4 address octets
/// - `tcp_segment`: TCP header + payload (checksum field must be zeroed)
///
/// The IP addresses are taken as fixed `[u8; 4]` arrays so an out-of-bounds
/// index is impossible by construction (was previously `&[u8]`, which panicked
/// on a slice shorter than 4 bytes).
///
/// # Panics
///
/// Debug-asserts that `tcp_segment` is at most `u16::MAX` bytes. The pseudo-header
/// TCP length field is 16-bit, so a longer segment cannot exist on the wire; a
/// caller passing one would otherwise silently fold a truncated length into the
/// sum and produce a wrong checksum. In release builds the length is saturated to
/// `u16::MAX` (a segment that large is already a malformed input).
pub fn tcp_checksum(src_ip: [u8; 4], dst_ip: [u8; 4], tcp_segment: &[u8]) -> u16 {
    debug_assert!(
        tcp_segment.len() <= u16::MAX as usize,
        "tcp_segment length {} exceeds the 16-bit TCP length field; checksum would be wrong",
        tcp_segment.len()
    );
    let tcp_len = u16::try_from(tcp_segment.len()).unwrap_or(u16::MAX);

    // Build pseudo-header sum
    let mut sum: u32 = 0;

    // Source IP (2 × 16-bit words)
    sum += u16::from_be_bytes([src_ip[0], src_ip[1]]) as u32;
    sum += u16::from_be_bytes([src_ip[2], src_ip[3]]) as u32;

    // Destination IP
    sum += u16::from_be_bytes([dst_ip[0], dst_ip[1]]) as u32;
    sum += u16::from_be_bytes([dst_ip[2], dst_ip[3]]) as u32;

    // Protocol (TCP = 6) + TCP length
    sum += 6u32; // TCP protocol number
    sum += tcp_len as u32;

    // Add TCP segment words
    let mut chunks = tcp_segment.chunks_exact(2);
    for chunk in &mut chunks {
        sum += u16::from_be_bytes([chunk[0], chunk[1]]) as u32;
    }
    if let Some(&last) = chunks.remainder().first() {
        sum += (last as u32) << 8;
    }

    // Fold
    while sum >> 16 != 0 {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }

    !(sum as u16)
}

/// Batch-compute IP checksums for the given packets, in place.
///
/// The header length is read from the IHL field (low nibble of byte 0) rather
/// than assumed to be 20 bytes, so packets carrying IP options are checksummed
/// over their full header. The checksum field (bytes 10-11) is zeroed and
/// recomputed. Packets whose IHL is invalid (< 5 words) or whose header would
/// run past the captured length are skipped, matching the existing undersized
/// skip.
pub fn batch_ip_checksum(packets: &mut [crate::RawPacket]) {
    for pkt in packets.iter_mut() {
        let len = pkt.clamped_len();
        if len < 20 {
            continue;
        }
        // IPv4 version must be 4. IHL is the number of 32-bit words in the
        // header (minimum 5 = 20 bytes, maximum 15 = 60 bytes). Compute
        // over exactly that many bytes.
        let version = pkt.buf[0] >> 4;
        let ihl = (pkt.buf[0] & 0x0F) as usize;
        let header_len = ihl * 4;
        if version != 4 || ihl < 5 || header_len > len {
            continue;
        }
        pkt.buf[10] = 0;
        pkt.buf[11] = 0;
        let cksum = ip_checksum(&pkt.buf[..header_len]);
        pkt.buf[10..12].copy_from_slice(&cksum.to_be_bytes());
    }
}

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

    #[test]
    fn ip_checksum_known_value() {
        // Example from RFC 1071
        // IP header: version=4, ihl=5, tos=0, total_len=20
        // id=0, flags=DF, ttl=64, proto=6(TCP)
        // src=10.0.0.1, dst=1.1.1.1
        let mut header = [0u8; 20];
        header[0] = 0x45;
        header[2..4].copy_from_slice(&20u16.to_be_bytes());
        header[6] = 0x40; // DF
        header[8] = 64; // TTL
        header[9] = 6; // TCP
        header[12..16].copy_from_slice(&[10, 0, 0, 1]); // src
        header[16..20].copy_from_slice(&[1, 1, 1, 1]); // dst

        let cksum = ip_checksum(&header);

        // Verify: embed checksum, recompute should give 0xFFFF
        header[10..12].copy_from_slice(&cksum.to_be_bytes());
        let verify: u32 = (0..20)
            .step_by(2)
            .map(|i| u16::from_be_bytes([header[i], header[i + 1]]) as u32)
            .sum();
        let folded = {
            let mut s = verify;
            while s >> 16 != 0 {
                s = (s & 0xFFFF) + (s >> 16);
            }
            s as u16
        };
        assert_eq!(folded, 0xFFFF);
    }

    #[test]
    fn tcp_checksum_roundtrip() {
        let src_ip = [10, 0, 0, 1];
        let dst_ip = [1, 1, 1, 1];

        // Minimal TCP SYN: 20 bytes
        let mut tcp = [0u8; 20];
        tcp[0..2].copy_from_slice(&49152u16.to_be_bytes()); // src port
        tcp[2..4].copy_from_slice(&80u16.to_be_bytes()); // dst port
        tcp[4..8].copy_from_slice(&0x12345678u32.to_be_bytes()); // seq
        tcp[12] = 0x50; // data offset = 5
        tcp[13] = 0x02; // SYN
        tcp[14..16].copy_from_slice(&64240u16.to_be_bytes()); // window

        let cksum = tcp_checksum(src_ip, dst_ip, &tcp);
        assert_ne!(cksum, 0, "TCP checksum should not be zero for valid packet");
    }

    #[test]
    fn empty_checksum_is_ffff() {
        // Checksum of nothing should be 0xFFFF (all ones complement of zero)
        assert_eq!(ones_complement_sum(&[]), 0xFFFF);
    }

    #[test]
    fn tcp_checksum_verifies_to_ffff_when_embedded() {
        // Embedding the computed checksum and recomputing over the pseudo-header
        // + segment must fold to 0xFFFF (the ones-complement self-check).
        let src_ip = [10, 0, 0, 1];
        let dst_ip = [1, 1, 1, 1];
        let mut tcp = [0u8; 20];
        tcp[0..2].copy_from_slice(&49152u16.to_be_bytes());
        tcp[2..4].copy_from_slice(&80u16.to_be_bytes());
        tcp[12] = 0x50;
        tcp[13] = 0x02;

        let cksum = tcp_checksum(src_ip, dst_ip, &tcp);
        tcp[16..18].copy_from_slice(&cksum.to_be_bytes());
        // Recompute: with the checksum embedded, the result must be 0.
        let verify = tcp_checksum(src_ip, dst_ip, &tcp);
        assert_eq!(verify, 0, "embedded TCP checksum must self-verify to 0");
    }

    #[test]
    fn batch_ip_checksum_covers_ihl_options_header() {
        // A packet with IP options (IHL=6, 24-byte header) must be checksummed
        // over all 24 bytes, not a fixed 20. Build such a packet, stamp it, and
        // verify the header (with the embedded checksum) folds to 0xFFFF.
        let mut pkt = crate::RawPacket::empty();
        pkt.len = 24;
        pkt.buf[0] = 0x46; // version 4, IHL 6 (24 bytes)
        pkt.buf[2..4].copy_from_slice(&24u16.to_be_bytes()); // total length
        pkt.buf[8] = 64; // TTL
        pkt.buf[9] = 6; // TCP
        pkt.buf[12..16].copy_from_slice(&[10, 0, 0, 1]); // src
        pkt.buf[16..20].copy_from_slice(&[1, 1, 1, 1]); // dst
        pkt.buf[20..24].copy_from_slice(&[0x01, 0x01, 0x01, 0x00]); // NOP,NOP,NOP,EOL options

        batch_ip_checksum(std::slice::from_mut(&mut pkt));

        // The checksum field (bytes 10-11) is now populated; verify over 24 bytes.
        let verify: u32 = (0..24)
            .step_by(2)
            .map(|i| u16::from_be_bytes([pkt.buf[i], pkt.buf[i + 1]]) as u32)
            .sum();
        let mut folded = verify;
        while folded >> 16 != 0 {
            folded = (folded & 0xFFFF) + (folded >> 16);
        }
        assert_eq!(
            folded as u16, 0xFFFF,
            "24-byte IHL=6 header checksum must self-verify"
        );

        // A fixed 20-byte checksum would NOT cover the options words, so it must
        // differ from the full-header checksum (proving IHL is honored).
        let full = u16::from_be_bytes([pkt.buf[10], pkt.buf[11]]);
        pkt.buf[10] = 0;
        pkt.buf[11] = 0;
        let only_20 = ip_checksum(&pkt.buf[..20]);
        assert_ne!(
            full, only_20,
            "checksum over 24-byte header must differ from a 20-byte-only checksum"
        );
    }

    #[test]
    fn batch_ip_checksum_skips_invalid_ihl() {
        // IHL < 5 is malformed; the packet must be skipped (checksum left zero),
        // never checksummed over a bogus sub-20-byte header.
        let mut pkt = crate::RawPacket::empty();
        pkt.len = 20;
        pkt.buf[0] = 0x44; // version 4, IHL 4 (16 bytes) - invalid
        pkt.buf[10] = 0xAB; // sentinel: must remain untouched
        pkt.buf[11] = 0xCD;
        batch_ip_checksum(std::slice::from_mut(&mut pkt));
        assert_eq!(
            [pkt.buf[10], pkt.buf[11]],
            [0xAB, 0xCD],
            "invalid IHL packet must be skipped, not rewritten"
        );
    }
    #[test]
    fn batch_ip_checksum_skips_non_ipv4_version() {
        let mut pkt = crate::RawPacket::empty();
        pkt.len = 20;
        pkt.buf[0] = 0x65; // version 6, IHL 5
        pkt.buf[10] = 0xAB; // sentinel: must remain untouched
        pkt.buf[11] = 0xCD;
        batch_ip_checksum(std::slice::from_mut(&mut pkt));
        assert_eq!(
            [pkt.buf[10], pkt.buf[11]],
            [0xAB, 0xCD],
            "non-IPv4 version packet must be skipped, not rewritten"
        );
    }
}