netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! `pnet` raw socket backend  -  portable, ~1M pps.
//!
//! Uses `pnet::transport` for Layer 4 raw TCP packet TX/RX.
//! This is the fallback backend that works on any Linux with CAP_NET_RAW.
//! Performance is limited by per-packet `sendto()` syscall overhead.

use std::io;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Mutex;
use std::time::Duration;

use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::tcp::TcpPacket;
use pnet::packet::Packet;
use pnet::transport::{
    tcp_packet_iter, transport_channel, TransportChannelType::Layer4,
    TransportProtocol::Ipv4, TransportReceiver, TransportSender,
};

use crate::engine::{rate_limiter_from_pps, EngineConfig, EngineError, EngineStats, PacketEngine, RxPacket};
use crate::packet::{RawPacket, MAX_PACKET_SIZE, offsets};
use crate::stats_window::PpsTracker;
use crate::checksum::ip_checksum;

/// Abstraction over pnet's `TransportSender` so the engine can be unit-tested
/// without opening raw sockets.
pub trait PnetSender: Send + Sync {
    /// Send a raw TCP segment to `dst`.
    fn send_segment(&mut self, segment: &[u8], dst: Ipv4Addr) -> io::Result<usize>;
}

/// Abstraction over pnet's `TransportReceiver` so the engine can be unit-tested
/// without opening raw sockets.
pub trait PnetReceiver: Send + Sync {
    /// Non-blocking receive of one raw TCP segment.
    fn next_segment(&mut self, timeout: Duration) -> io::Result<Option<(Vec<u8>, Ipv4Addr)>>;
}

impl PnetSender for TransportSender {
    fn send_segment(&mut self, segment: &[u8], dst: Ipv4Addr) -> io::Result<usize> {
        let tcp = TcpPacket::new(segment).ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidData, "invalid TCP segment")
        })?;
        self.send_to(tcp, IpAddr::V4(dst))
    }
}

impl PnetReceiver for TransportReceiver {
    fn next_segment(&mut self, timeout: Duration) -> io::Result<Option<(Vec<u8>, Ipv4Addr)>> {
        let mut iter = tcp_packet_iter(self);
        match iter.next_with_timeout(timeout)? {
            None => Ok(None),
            Some((tcp, addr)) => {
                let bytes = tcp.packet().to_vec();
                let IpAddr::V4(src_ip) = addr else {
                    return Ok(None);
                };
                Ok(Some((bytes, src_ip)))
            }
        }
    }
}

/// `pnet`-based raw socket packet engine.
///
/// Sends TCP packets via Layer 4 raw sockets (kernel handles IP header).
/// Note: `pnet` Layer4 only sends the TCP portion; the kernel adds the IP
/// header. For full control, we'd need Layer3, but Layer4 is sufficient
/// for SYN scanning.
pub struct PnetEngine<S = TransportSender, R = TransportReceiver> {
    tx: Mutex<S>,
    rx: Mutex<R>,
    #[allow(dead_code)]
    config: EngineConfig,
    tx_stats: PpsTracker,
    rx_stats: PpsTracker,
    rate_limiter: Option<ratelimit::TokenBucket>,
}

impl PnetEngine<TransportSender, TransportReceiver> {
    /// Create a new `pnet` engine.
    ///
    /// Requires `CAP_NET_RAW` or root privileges.
    pub fn new(config: EngineConfig) -> Result<Self, EngineError> {
        let protocol = Layer4(Ipv4(IpNextHeaderProtocols::Tcp));
        let (tx, rx) = transport_channel(65536, protocol).map_err(|e| {
            EngineError::PermissionDenied(format!(
                "failed to open raw socket: {e}. Run with CAP_NET_RAW or as root."
            ))
        })?;

        Ok(Self::with_senders(config, tx, rx))
    }
}

impl<S, R> PnetEngine<S, R> {
    /// Build an engine from pre-constructed sender/receiver. Used by tests.
    pub fn with_senders(config: EngineConfig, tx: S, rx: R) -> Self {
        let rate_limiter = rate_limiter_from_pps(config.rate_pps);
        Self {
            tx: Mutex::new(tx),
            rx: Mutex::new(rx),
            config,
            tx_stats: PpsTracker::new(),
            rx_stats: PpsTracker::new(),
            rate_limiter,
        }
    }
}

impl<S: PnetSender, R: PnetReceiver> PacketEngine for PnetEngine<S, R> {
    fn tx_batch(&self, packets: &[RawPacket]) -> Result<usize, EngineError> {
        let mut tx = self.tx.lock().map_err(|_| {
            EngineError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                "TX lock poisoned",
            ))
        })?;

        let mut sent = 0usize;
        for (i, pkt) in packets.iter().enumerate() {
            if pkt.len < 40 {
                self.tx_stats.record_drop(1);
                continue;
            }

            if let Some(ref bucket) = self.rate_limiter {
                if !bucket.try_acquire() {
                    // No token available: rate-limit this packet and all remaining.
                    self.tx_stats.record_drop((packets.len() - i) as u64);
                    break;
                }
            }

            // Extract destination IP from the packet's IP header
            let dst_ip = Ipv4Addr::new(
                pkt.buf[offsets::IP_DST],
                pkt.buf[offsets::IP_DST + 1],
                pkt.buf[offsets::IP_DST + 2],
                pkt.buf[offsets::IP_DST + 3],
            );

            // pnet Layer4 expects just the TCP portion. `pkt.len` is clamped
            // to the backing buffer: it is a public field, so an oversized
            // value would otherwise panic here.
            let tcp_data = &pkt.buf[offsets::TCP_START..pkt.clamped_len()];

            match tx.send_segment(tcp_data, dst_ip) {
                Ok(_) => {
                    sent += 1;
                    self.tx_stats.record(1);
                }
                Err(_) => {
                    self.tx_stats.record_drop(1);
                }
            }
        }

        Ok(sent)
    }

    fn rx_batch(&self, buf: &mut [RxPacket]) -> Result<usize, EngineError> {
        let mut rx = self.rx.lock().map_err(|_| {
            EngineError::Io(std::io::Error::new(
                std::io::ErrorKind::Other,
                "RX lock poisoned",
            ))
        })?;

        let mut received = 0usize;

        // Non-blocking drain: try to fill the buffer
        while received < buf.len() {
            match rx.next_segment(Duration::from_millis(0)) {
                Ok(Some((raw_bytes, src_ip))) => {
                    if raw_bytes.len() < 20 {
                        self.rx_stats.record_drop(1);
                        continue;
                    }
                    let tcp_data_offset = {
                        // Data offset is the high nibble of byte 12, in 32-bit words.
                        let data_offset_words = (raw_bytes.get(12).copied().unwrap_or(0) >> 4) as usize;
                        data_offset_words * 4
                    };
                    if tcp_data_offset < 20 || tcp_data_offset > raw_bytes.len() {
                        self.rx_stats.record_drop(1);
                        continue;
                    }
                    let payload = raw_bytes[tcp_data_offset..].to_vec();

                    // pnet Layer4 only gives the TCP segment; reconstruct the
                    // IPv4 header so RxPacket.packet has the same L3 layout as
                    // the sendmmsg/xdp backends (IP + TCP). IP fields not
                    // exposed by pnet use sane defaults: TTL 64, identification 0,
                    // no flags/fragmentation, and the destination is the engine's
                    // configured source IP (the IP the scanner binds traffic to).
                    let total_len = (20 + raw_bytes.len()) as u16;
                    let mut ip_header = [0u8; 20];
                    ip_header[0] = 0x45; // version 4, IHL 5
                    ip_header[2..4].copy_from_slice(&total_len.to_be_bytes());
                    ip_header[8] = 64; // TTL (not accessible via pnet Layer4)
                    ip_header[9] = 6; // TCP protocol number
                    ip_header[12..16].copy_from_slice(&src_ip.octets());
                    ip_header[16..20].copy_from_slice(&self.config.source_ip.octets());
                    let checksum = ip_checksum(&ip_header);
                    ip_header[10..12].copy_from_slice(&checksum.to_be_bytes());

                    // Build the IP+TCP L3 packet directly into the RawPacket's
                    // fixed inline buffer. The old `Vec::with_capacity(..)`
                    // heap-allocated a staging buffer on EVERY received packet in
                    // the hot RX path, only for `from_bytes` to copy it again into
                    // `RawPacket.buf` (Law 7). `reconstruct_l3_packet` writes the
                    // two segments straight into the inline buffer: zero heap,
                    // single copy.
                    let Some(packet) = reconstruct_l3_packet(&ip_header, &raw_bytes) else {
                        self.rx_stats.record_drop(1);
                        continue;
                    };

                    // Parse the fixed TCP fields directly from the segment.
                    let src_port = u16::from_be_bytes([raw_bytes[0], raw_bytes[1]]);
                    let dst_port = u16::from_be_bytes([raw_bytes[2], raw_bytes[3]]);
                    let seq_num = u32::from_be_bytes([raw_bytes[4], raw_bytes[5], raw_bytes[6], raw_bytes[7]]);
                    let ack_num = u32::from_be_bytes([raw_bytes[8], raw_bytes[9], raw_bytes[10], raw_bytes[11]]);
                    let tcp_flags = raw_bytes[13];
                    let window = u16::from_be_bytes([raw_bytes[14], raw_bytes[15]]);

                    buf[received] = RxPacket {
                        packet,
                        src_ip,
                        src_port,
                        dst_port,
                        tcp_flags,
                        ack_num,
                        seq_num,
                        ttl: 64, // Not accessible via pnet Layer4
                        window,
                        payload,
                    };

                    received += 1;
                    self.rx_stats.record(1);
                }
                Ok(None) => break, // Timeout, no more packets
                Err(e) => {
                    // A socket read error is NOT "no more packets". The old
                    // `Err(_) => break` returned Ok(received), silently reporting
                    // a short successful batch and hiding EBADF/EINTR/closed-socket
                    // failures from the caller (Law 10). Surface it: the caller
                    // must see the read failed, not a truncated count.
                    return Err(EngineError::Io(e));
                }
            }
        }

        Ok(received)
    }

    fn stats(&self) -> EngineStats {
        EngineStats {
            tx_packets: self.tx_stats.total(),
            rx_packets: self.rx_stats.total(),
            tx_drops: self.tx_stats.drops(),
            rx_drops: self.rx_stats.drops(),
            tx_pps: self.tx_stats.snapshot_pps(),
            rx_pps: self.rx_stats.snapshot_pps(),
        }
    }

    fn name(&self) -> &'static str {
        "pnet"
    }
}

/// Reconstruct an IP + TCP L3 packet directly into a [`RawPacket`]'s fixed inline
/// buffer, with no intermediate heap allocation.
///
/// `RawPacket` stores its bytes in a `[u8; MAX_PACKET_SIZE]` array, so staging the
/// packet in a `Vec` first (as the RX loop used to) both heap-allocates per packet
/// AND copies twice (into the Vec, then from_bytes into the array). Writing the
/// two segments straight into an empty `RawPacket` is zero-heap and single-copy.
///
/// Returns `None` if the combined header + segment exceeds [`MAX_PACKET_SIZE`],
/// matching [`RawPacket::from_bytes`]'s size contract.
fn reconstruct_l3_packet(ip_header: &[u8; 20], tcp_segment: &[u8]) -> Option<RawPacket> {
    let l3_len = ip_header.len() + tcp_segment.len();
    if l3_len > MAX_PACKET_SIZE {
        return None;
    }
    let mut packet = RawPacket::empty();
    packet.buf[..ip_header.len()].copy_from_slice(ip_header);
    packet.buf[ip_header.len()..l3_len].copy_from_slice(tcp_segment);
    packet.len = l3_len as u16;
    Some(packet)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::packet::{build_syn_template, stamp_syn};
    use std::alloc::{GlobalAlloc, Layout, System};

    // Test-only counting allocator so we can prove the hot-path L3 reconstruction
    // performs zero heap allocations. It counts allocations PER THREAD (a
    // thread-local counter, not a process-global one) so a measurement on the
    // test's own thread is not perturbed by other tests allocating in parallel.
    // `#[global_allocator]` here is scoped to netforge's unit-test binary
    // (cfg(test)); it does not affect the shipped library or integration tests.
    thread_local! {
        static THREAD_ALLOCS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    }

    struct CountingAlloc;
    unsafe impl GlobalAlloc for CountingAlloc {
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            // Best-effort: `try_with` avoids touching the TLS during its own
            // initialization or teardown (when it may be unavailable).
            let _ = THREAD_ALLOCS.try_with(|c| c.set(c.get().wrapping_add(1)));
            System.alloc(layout)
        }
        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            System.dealloc(ptr, layout);
        }
    }

    #[global_allocator]
    static COUNTING_ALLOCATOR: CountingAlloc = CountingAlloc;

    fn thread_alloc_count() -> usize {
        THREAD_ALLOCS.with(|c| c.get())
    }

    #[test]
    fn reconstruct_l3_packet_writes_ip_header_then_tcp_segment() {
        let mut ip_header = [0u8; 20];
        ip_header[0] = 0x45; // version 4, IHL 5
        ip_header[9] = 6; // TCP
        let tcp_segment = [0x11u8, 0x22, 0x33, 0x44, 0x55];

        let packet = reconstruct_l3_packet(&ip_header, &tcp_segment).expect("fits");
        assert_eq!(packet.len as usize, 25);
        assert_eq!(&packet.as_bytes()[..20], &ip_header);
        assert_eq!(&packet.as_bytes()[20..], &tcp_segment);
    }

    #[test]
    fn reconstruct_l3_packet_does_not_heap_allocate() {
        let ip_header = [0u8; 20];
        let tcp_segment = [0xABu8; 40];

        // Force the counter's TLS to initialize before the measured region, then
        // measure this thread's allocations in isolation: the reconstruction
        // writes into a stack-returned RawPacket's inline buffer, so the count
        // must not move (the old Vec::with_capacity staging allocated per packet).
        let before = thread_alloc_count();
        let packet = reconstruct_l3_packet(&ip_header, &tcp_segment).expect("fits");
        let after = thread_alloc_count();

        assert_eq!(
            after - before,
            0,
            "L3 reconstruction must not heap-allocate in the hot RX path"
        );
        assert_eq!(packet.len as usize, 60);
    }

    #[test]
    fn reconstruct_l3_packet_rejects_oversized_segment_at_the_boundary() {
        let ip_header = [0u8; 20];
        // 20-byte header + this segment is exactly one over MAX_PACKET_SIZE.
        let too_big = vec![0u8; MAX_PACKET_SIZE - 20 + 1];
        assert!(
            reconstruct_l3_packet(&ip_header, &too_big).is_none(),
            "a packet exceeding MAX_PACKET_SIZE must be rejected, not truncated"
        );
        // Exactly at the limit fits.
        let exact = vec![0u8; MAX_PACKET_SIZE - 20];
        let packet = reconstruct_l3_packet(&ip_header, &exact).expect("boundary fits");
        assert_eq!(packet.len as usize, MAX_PACKET_SIZE);
    }

    /// A fake sender that records every segment it is asked to send.
    struct MockSender {
        sent: Vec<(Vec<u8>, Ipv4Addr)>,
        fail_next: bool,
    }

    impl MockSender {
        fn new() -> Self {
            Self {
                sent: Vec::new(),
                fail_next: false,
            }
        }
    }

    impl PnetSender for MockSender {
        fn send_segment(&mut self, segment: &[u8], dst: Ipv4Addr) -> io::Result<usize> {
            if self.fail_next {
                return Err(io::Error::new(io::ErrorKind::Other, "injected send failure"));
            }
            self.sent.push((segment.to_vec(), dst));
            Ok(segment.len())
        }
    }

    /// A fake receiver with a queue of segments to return.
    struct MockReceiver {
        segments: Vec<(Vec<u8>, Ipv4Addr)>,
    }

    impl MockReceiver {
        fn new(segments: Vec<(Vec<u8>, Ipv4Addr)>) -> Self {
            Self { segments }
        }
    }

    impl PnetReceiver for MockReceiver {
        fn next_segment(&mut self, _timeout: Duration) -> io::Result<Option<(Vec<u8>, Ipv4Addr)>> {
            if self.segments.is_empty() {
                return Ok(None);
            }
            Ok(Some(self.segments.remove(0)))
        }
    }

    fn make_syn_packet(dst_ip: Ipv4Addr, dst_port: u16) -> RawPacket {
        let src_ip = Ipv4Addr::new(10, 0, 0, 1);
        let mut pkt = build_syn_template(src_ip, 49152);
        stamp_syn(&mut pkt, dst_ip, dst_port, 0x12345678);
        pkt
    }

    /// Build a minimal TCP segment with the given ports/flags/offset.
    fn build_tcp_segment(
        src_port: u16,
        dst_port: u16,
        seq: u32,
        ack: u32,
        data_offset_words: u8,
        flags: u8,
        window: u16,
        payload: &[u8],
    ) -> Vec<u8> {
        let header_len = (data_offset_words as usize) * 4;
        let mut seg = Vec::with_capacity(header_len + payload.len());
        seg.extend_from_slice(&src_port.to_be_bytes());
        seg.extend_from_slice(&dst_port.to_be_bytes());
        seg.extend_from_slice(&seq.to_be_bytes());
        seg.extend_from_slice(&ack.to_be_bytes());
        seg.push(data_offset_words << 4);
        seg.push(flags);
        seg.extend_from_slice(&window.to_be_bytes());
        seg.extend_from_slice(&[0u8, 0u8]); // checksum
        seg.extend_from_slice(&[0u8, 0u8]); // urgent pointer
        // Zero out any options bytes.
        seg.resize(header_len, 0);
        seg.extend_from_slice(payload);
        seg
    }

    fn empty_rx_slot() -> RxPacket {
        RxPacket {
            packet: RawPacket::empty(),
            src_ip: Ipv4Addr::UNSPECIFIED,
            src_port: 0,
            dst_port: 0,
            tcp_flags: 0,
            ack_num: 0,
            seq_num: 0,
            ttl: 0,
            window: 0,
            payload: Vec::new(),
        }
    }

    #[test]
    fn tx_batch_sends_valid_syn_and_counts_it() {
        let dst = Ipv4Addr::new(1, 2, 3, 4);
        let pkt = make_syn_packet(dst, 443);
        let sender = MockSender::new();
        let receiver = MockReceiver::new(vec![]);
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let sent = engine.tx_batch(std::slice::from_ref(&pkt)).unwrap();

        assert_eq!(sent, 1);
        let stats = engine.stats();
        assert_eq!(stats.tx_packets, 1);
        assert_eq!(stats.tx_drops, 0);
        let guard = engine.tx.lock().unwrap();
        assert_eq!(guard.sent.len(), 1);
        assert_eq!(guard.sent[0].1, dst);
        // The segment must be the TCP portion of the L3 packet.
        assert_eq!(guard.sent[0].0, &pkt.buf[offsets::TCP_START..pkt.len as usize]);
    }

    #[test]
    fn tx_batch_drops_short_packets() {
        let mut pkt = RawPacket::empty();
        pkt.len = 30; // below the 40-byte minimum
        pkt.buf[offsets::TCP_START..offsets::TCP_START + 10].copy_from_slice(&[0u8; 10]);
        let sender = MockSender::new();
        let receiver = MockReceiver::new(vec![]);
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let sent = engine.tx_batch(&[pkt]).unwrap();

        assert_eq!(sent, 0);
        let guard = engine.tx.lock().unwrap();
        assert!(guard.sent.is_empty());
        assert_eq!(engine.stats().tx_drops, 1);
    }

    #[test]
    fn tx_batch_records_drop_on_send_error() {
        let dst = Ipv4Addr::new(1, 2, 3, 4);
        let pkt = make_syn_packet(dst, 443);
        let mut sender = MockSender::new();
        sender.fail_next = true;
        let receiver = MockReceiver::new(vec![]);
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let sent = engine.tx_batch(&[pkt]).unwrap();

        assert_eq!(sent, 0);
        assert_eq!(engine.stats().tx_drops, 1);
    }

    #[test]
    fn rx_batch_reconstructs_l3_packet_and_populates_rx_packet() {
        let src_ip = Ipv4Addr::new(192, 0, 2, 1);
        let segment = build_tcp_segment(443, 12345, 0xdeadbeef, 0xcafebabe, 5, 0x12, 64240, b"payload");
        let receiver = MockReceiver::new(vec![(segment, src_ip)]);
        let sender = MockSender::new();
        let mut config = EngineConfig::default();
        config.source_ip = Ipv4Addr::new(10, 0, 0, 1);
        let engine = PnetEngine::with_senders(config, sender, receiver);

        let mut buf = vec![RxPacket {
            packet: RawPacket::empty(),
            src_ip: Ipv4Addr::UNSPECIFIED,
            src_port: 0,
            dst_port: 0,
            tcp_flags: 0,
            ack_num: 0,
            seq_num: 0,
            ttl: 0,
            window: 0,
            payload: Vec::new(),
        }; 4];
        let received = engine.rx_batch(&mut buf).unwrap();

        assert_eq!(received, 1);
        let rx = &buf[0];
        assert_eq!(rx.src_ip, src_ip);
        assert_eq!(rx.src_port, 443);
        assert_eq!(rx.dst_port, 12345);
        assert_eq!(rx.seq_num, 0xdeadbeef);
        assert_eq!(rx.ack_num, 0xcafebabe);
        assert_eq!(rx.tcp_flags, 0x12);
        assert_eq!(rx.window, 64240);
        assert_eq!(rx.payload, b"payload");
        assert_eq!(rx.packet.len, 20 + 20 + 7);
        // Reconstructed IP header should start with version 4, IHL 5.
        assert_eq!(rx.packet.buf[0], 0x45);
        // Protocol = TCP.
        assert_eq!(rx.packet.buf[9], 6);
        let stats = engine.stats();
        assert_eq!(stats.rx_packets, 1);
        assert_eq!(stats.rx_drops, 0);
    }

    #[test]
    fn rx_batch_skips_malformed_tcp_data_offset() {
        // data offset = 4 words (16 bytes) is below the 20-byte minimum.
        let segment = build_tcp_segment(443, 12345, 0, 0, 4, 0x10, 0, &[]);
        let receiver = MockReceiver::new(vec![(segment, Ipv4Addr::new(192, 0, 2, 1))]);
        let sender = MockSender::new();
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let mut buf = vec![empty_rx_slot()];
        let received = engine.rx_batch(&mut buf).unwrap();

        assert_eq!(received, 0);
        assert_eq!(engine.stats().rx_drops, 1);
    }

    #[test]
    fn rx_batch_skips_segment_with_data_offset_past_end() {
        // data offset = 15 words (60 bytes) but segment is only 20 bytes.
        let mut segment = build_tcp_segment(443, 12345, 0, 0, 5, 0x10, 0, &[]);
        // Truncate so the claimed header runs past the segment end.
        segment.truncate(20);
        segment[12] = 0xF0; // set data offset to 15
        let receiver = MockReceiver::new(vec![(segment, Ipv4Addr::new(192, 0, 2, 1))]);
        let sender = MockSender::new();
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let mut buf = vec![empty_rx_slot()];
        let received = engine.rx_batch(&mut buf).unwrap();

        assert_eq!(received, 0);
        assert_eq!(engine.stats().rx_drops, 1);
    }

    #[test]
    fn rx_batch_stops_when_buffer_is_full() {
        let src_ip = Ipv4Addr::new(192, 0, 2, 1);
        let segments = vec![
            (build_tcp_segment(443, 1, 1, 0, 5, 0x10, 0, &[]), src_ip),
            (build_tcp_segment(443, 2, 2, 0, 5, 0x10, 0, &[]), src_ip),
        ];
        let receiver = MockReceiver::new(segments);
        let sender = MockSender::new();
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let mut buf = vec![RxPacket {
            packet: RawPacket::empty(),
            src_ip: Ipv4Addr::UNSPECIFIED,
            src_port: 0,
            dst_port: 0,
            tcp_flags: 0,
            ack_num: 0,
            seq_num: 0,
            ttl: 0,
            window: 0,
            payload: Vec::new(),
        }; 1];
        let received = engine.rx_batch(&mut buf).unwrap();

        assert_eq!(received, 1);
        assert_eq!(buf[0].src_port, 443);
        assert_eq!(buf[0].dst_port, 1);
    }

    #[test]
    fn rx_batch_stops_on_empty_receiver() {
        let receiver = MockReceiver::new(vec![]);
        let sender = MockSender::new();
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let mut buf: Vec<RxPacket> = Vec::new();
        let received = engine.rx_batch(&mut buf).unwrap();

        assert_eq!(received, 0);
    }

    /// A receiver that yields one good segment, then reports a socket read error
    /// on the next poll. Models a raw-socket recv failing partway through a batch.
    struct FailAfterOneReceiver {
        first: Option<(Vec<u8>, Ipv4Addr)>,
    }

    impl PnetReceiver for FailAfterOneReceiver {
        fn next_segment(&mut self, _timeout: Duration) -> io::Result<Option<(Vec<u8>, Ipv4Addr)>> {
            match self.first.take() {
                Some(segment) => Ok(Some(segment)),
                None => Err(io::Error::new(io::ErrorKind::Other, "injected recv failure")),
            }
        }
    }

    #[test]
    fn rx_batch_propagates_socket_read_error_instead_of_reporting_short_batch() {
        // The old `Err(_) => break` returned Ok(received), telling the caller the
        // batch ended normally when the socket read actually FAILED (Law 10). The
        // read error must surface as EngineError, even after a packet was received.
        let src_ip = Ipv4Addr::new(192, 0, 2, 1);
        let segment = build_tcp_segment(443, 12345, 1, 0, 5, 0x12, 0, &[]);
        let receiver = FailAfterOneReceiver {
            first: Some((segment, src_ip)),
        };
        let sender = MockSender::new();
        let engine = PnetEngine::with_senders(EngineConfig::default(), sender, receiver);

        let mut buf = vec![empty_rx_slot(); 4];
        let result = engine.rx_batch(&mut buf);

        let err = result.expect_err("a socket read error must surface, not a short Ok batch");
        assert!(
            matches!(err, EngineError::Io(_)),
            "expected EngineError::Io from the propagated recv failure, got {err:?}"
        );
        assert!(
            err.to_string().contains("injected recv failure"),
            "the underlying io error must be preserved: {err}"
        );
    }

    #[test]
    fn tx_batch_rate_limits_to_rate_pps() {
        let dst = Ipv4Addr::new(1, 2, 3, 4);
        let pkts = vec![
            make_syn_packet(dst, 443),
            make_syn_packet(dst, 444),
            make_syn_packet(dst, 445),
        ];
        let mut config = EngineConfig::default();
        config.rate_pps = 2; // bucket has burst=2 tokens
        let sender = MockSender::new();
        let receiver = MockReceiver::new(vec![]);
        let engine = PnetEngine::with_senders(config, sender, receiver);

        let sent = engine.tx_batch(&pkts).unwrap();

        assert_eq!(sent, 2);
        let guard = engine.tx.lock().unwrap();
        assert_eq!(guard.sent.len(), 2);
        drop(guard);
        let stats = engine.stats();
        assert_eq!(stats.tx_packets, 2);
        assert_eq!(stats.tx_drops, 1);
    }

    #[test]
    fn tx_batch_rate_pps_zero_is_unlimited() {
        let dst = Ipv4Addr::new(1, 2, 3, 4);
        let pkts = vec![
            make_syn_packet(dst, 443),
            make_syn_packet(dst, 444),
            make_syn_packet(dst, 445),
        ];
        let mut config = EngineConfig::default();
        config.rate_pps = 0;
        let sender = MockSender::new();
        let receiver = MockReceiver::new(vec![]);
        let engine = PnetEngine::with_senders(config, sender, receiver);

        let sent = engine.tx_batch(&pkts).unwrap();

        assert_eq!(sent, 3);
        let guard = engine.tx.lock().unwrap();
        assert_eq!(guard.sent.len(), 3);
        drop(guard);
        let stats = engine.stats();
        assert_eq!(stats.tx_packets, 3);
        assert_eq!(stats.tx_drops, 0);
    }
}