netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
//! Packet engine trait and configuration.
//!
//! [`PacketEngine`] is the abstraction over raw packet I/O backends.
//! Implementations live in `backend_pnet`, `backend_sendmmsg`, and
//! `backend_xdp` modules.

use std::net::Ipv4Addr;
use crate::RawPacket;

/// Build a token-bucket rate limiter from `EngineConfig::rate_pps`.
///
/// `rate_pps == 0` means unlimited and returns `None`.  Rates are clamped to
/// `u32::MAX` (the largest burst / rate the in-tree bucket accepts) and the
/// burst size is set equal to the configured rate.
pub(crate) fn rate_limiter_from_pps(rate_pps: u64) -> Option<ratelimit::TokenBucket> {
    if rate_pps == 0 {
        return None;
    }
    let clamped = rate_pps.min(u32::MAX as u64);
    let rate = clamped as f64;
    let burst = clamped as u32;
    // A clamped, positive u64 always converts to a normal f64.
    ratelimit::TokenBucket::new(rate, burst)
        .inspect_err(|e| tracing::warn!("invalid rate_pps {rate_pps}, disabling rate limit: {e}"))
        .ok()
}

/// Packet engine configuration.
#[derive(Debug, Clone)]
pub struct EngineConfig {
    /// Source IPv4 address for outgoing packets.
    pub source_ip: Ipv4Addr,
    /// Source port range start for ephemeral ports.
    pub source_port_start: u16,
    /// Source port range end (exclusive).
    pub source_port_end: u16,
    /// Target packets per second (0 = unlimited).
    pub rate_pps: u64,
    /// Network interface name (e.g., "eth0") for AF_XDP/sendmmsg.
    pub interface: Option<String>,
    /// TX ring buffer size (number of slots).
    pub tx_ring_size: u32,
    /// RX ring buffer size (number of slots).
    pub rx_ring_size: u32,
}

impl Default for EngineConfig {
    fn default() -> Self {
        Self {
            source_ip: Ipv4Addr::UNSPECIFIED,
            source_port_start: 49152,
            source_port_end: 65535,
            rate_pps: 1_000_000, // 1M pps default
            interface: None,
            tx_ring_size: 4096,
            rx_ring_size: 4096,
        }
    }
}

/// Runtime statistics from a packet engine.
#[derive(Debug, Clone, Default)]
pub struct EngineStats {
    /// Total packets transmitted.
    pub tx_packets: u64,
    /// Total packets received (after filter).
    pub rx_packets: u64,
    /// TX packets dropped (ring full, rate limit, etc.).
    pub tx_drops: u64,
    /// RX packets dropped (buffer full, invalid checksum, etc.).
    pub rx_drops: u64,
    /// Current TX rate in packets per second.
    pub tx_pps: u64,
    /// Current RX rate in packets per second.
    pub rx_pps: u64,
}

/// A received packet with metadata.
#[derive(Debug, Clone)]
pub struct RxPacket {
    /// Raw packet data.
    pub packet: RawPacket,
    /// Source IP address (parsed from IP header).
    pub src_ip: Ipv4Addr,
    /// Source port (parsed from TCP header).
    pub src_port: u16,
    /// Destination port (our port).
    pub dst_port: u16,
    /// TCP flags.
    pub tcp_flags: u8,
    /// TCP acknowledgement number.
    pub ack_num: u32,
    /// TCP sequence number.
    pub seq_num: u32,
    /// IP TTL (for OS fingerprinting).
    pub ttl: u8,
    /// TCP window size (for OS fingerprinting).
    pub window: u16,
    /// Payload bytes (TCP data after header, if any).
    pub payload: Vec<u8>,
}

/// Common TCP flag constants.
pub mod tcp_flags {
    /// FIN flag.
    pub const FIN: u8 = 0x01;
    /// SYN flag.
    pub const SYN: u8 = 0x02;
    /// RST flag.
    pub const RST: u8 = 0x04;
    /// PSH flag.
    pub const PSH: u8 = 0x08;
    /// ACK flag.
    pub const ACK: u8 = 0x10;
    /// SYN+ACK combination.
    pub const SYN_ACK: u8 = SYN | ACK;
}

/// Error type for packet engine operations.
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
    /// Insufficient privileges to open raw sockets.
    #[error("insufficient privileges: {0} (need CAP_NET_RAW or root)")]
    PermissionDenied(String),
    /// Network interface not found or not suitable.
    #[error("interface error: {0}")]
    InterfaceError(String),
    /// Backend-specific I/O error.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// Configuration value is invalid or unsupported.
    #[error("invalid configuration: {0}")]
    InvalidConfig(String),
    /// Packet too large for the engine's MTU.
    #[error("packet exceeds MTU: {size} > {mtu}")]
    PacketTooLarge {
        /// Actual packet size.
        size: usize,
        /// Engine's MTU limit.
        mtu: usize,
    },
}

/// Trait for raw packet I/O backends.
///
/// Implementations must be `Send + Sync` for use across async tasks.
/// All methods are synchronous  -  the caller is responsible for running them
/// on blocking threads or io_uring.
pub trait PacketEngine: Send + Sync {
    /// Send a batch of raw packets.
    ///
    /// Returns the number of packets successfully enqueued for transmission.
    /// Packets that cannot be sent (ring full, rate limited) are silently dropped
    /// and counted in [`EngineStats::tx_drops`].
    fn tx_batch(&self, packets: &[RawPacket]) -> Result<usize, EngineError>;

    /// Receive a batch of packets.
    ///
    /// Fills `buf` with received packets and returns the count.
    /// Non-blocking: returns 0 if no packets are available.
    fn rx_batch(&self, buf: &mut [RxPacket]) -> Result<usize, EngineError>;

    /// Get current engine statistics.
    fn stats(&self) -> EngineStats;

    /// Backend name for logging.
    fn name(&self) -> &'static str;
}

/// Auto-select the best available backend based on system capabilities.
///
/// Priority: AF_XDP > sendmmsg > pnet. We try the fastest backend first,
/// falling back if the binary lacks the feature OR if construction fails
/// (e.g. sendmmsg requires CAP_NET_RAW; if the process can't open a raw
/// socket, fall through to pnet which uses libpnet's privileged datalink).
pub fn auto_select(config: EngineConfig) -> Result<Box<dyn PacketEngine>, EngineError> {
    // Try AF_XDP first when compiled in (Linux 5.10+, requires CAP_BPF
    // and an explicit interface). Currently a scaffold that always
    // returns PermissionDenied  -  falls through to sendmmsg until the
    // full XSK implementation lands.
    #[cfg(all(target_os = "linux", feature = "xdp-backend"))]
    {
        match crate::backend_xdp::XdpEngine::new(config.clone()) {
            Ok(eng) => {
                tracing::info!(backend = "xdp", "netforge selected AF_XDP backend");
                return Ok(Box::new(eng) as Box<dyn PacketEngine>);
            }
            Err(EngineError::PermissionDenied(e)) => {
                tracing::debug!(error = %e, "xdp backend unavailable; trying sendmmsg");
            }
            Err(e) => return Err(e),
        }
    }

    // Try sendmmsg next when compiled in (Linux, ~10M pps via batched
    // raw sockets). Honour any explicit success  -  only fall through on
    // construction failure due to missing permissions/capabilities.
    #[cfg(all(target_os = "linux", feature = "sendmmsg-backend"))]
    {
        match crate::backend_sendmmsg::SendmmsgEngine::new(config.clone()) {
            Ok(eng) => {
                tracing::info!(backend = "sendmmsg", "netforge selected sendmmsg backend");
                return Ok(Box::new(eng) as Box<dyn PacketEngine>);
            }
            Err(EngineError::PermissionDenied(e)) => {
                tracing::warn!(error = %e, "sendmmsg backend unavailable; falling back");
            }
            Err(e) => return Err(e),
        }
    }

    #[cfg(feature = "pnet-backend")]
    {
        let eng = crate::backend_pnet::PnetEngine::new(config)?;
        tracing::info!(backend = "pnet", "netforge selected pnet backend");
        return Ok(Box::new(eng) as Box<dyn PacketEngine>);
    }

    #[cfg(not(feature = "pnet-backend"))]
    {
        Err(EngineError::PermissionDenied(
            "no packet backend compiled in (need sendmmsg-backend or pnet-backend)".into(),
        ))
    }
}