arcbox-net 0.1.4

High-performance network stack for ArcBox
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
//! smoltcp `Device` adapter for the guest VM socketpair FD.
//!
//! Bridges L2 Ethernet frames between the guest VM's VirtIO network device
//! (exposed via a `socketpair(2)` FD) and the smoltcp TCP/IP stack.
//!
//! # Frame classification
//!
//! Frames read from the guest FD are classified and routed:
//!
//! - **ARP** and **TCP** → passed to smoltcp via `receive()`
//! - **DHCP** (UDP:67), **DNS** (UDP:53 to gateway), **UDP**, **ICMP** →
//!   intercepted and stored in the `intercepted` queue for the datapath loop
//!
//! This keeps the existing DHCP/DNS/UDP/ICMP handlers unchanged while smoltcp
//! handles ARP automatically and TCP via its socket pool.

use std::collections::VecDeque;
use std::io;
use std::net::Ipv4Addr;
use std::os::fd::RawFd;

use smoltcp::phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken};
use smoltcp::time::Instant;

use crate::ethernet::ETH_HEADER_LEN;

/// MTU for the Ethernet medium (excludes Ethernet header).
const ETHERNET_MTU: usize = 1500;

/// Maximum Ethernet frame size we handle.
const MAX_FRAME_SIZE: usize = 65535;

/// Protocol numbers.
const PROTO_ICMP: u8 = 1;
const PROTO_TCP: u8 = 6;
const PROTO_UDP: u8 = 17;

/// TCP SYN connection info extracted during frame classification.
///
/// SYN frames are held back from smoltcp (`gated_syns`) until the host
/// connect completes. The full frame is stored so it can be injected
/// into the rx_queue later.
#[derive(Debug, Clone)]
pub struct TcpSynInfo {
    pub dst_port: u16,
    pub src_ip: Ipv4Addr,
    pub src_port: u16,
    pub dst_ip: Ipv4Addr,
    pub syn_seq: u32,
    pub frame: Vec<u8>,
}

/// An intercepted frame from the guest that should not go through smoltcp.
#[derive(Debug)]
pub struct InterceptedFrame {
    pub frame: Vec<u8>,
    pub kind: InterceptedKind,
}

/// Classification of intercepted frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterceptedKind {
    /// DHCP packet (UDP dst port 67).
    Dhcp,
    /// DNS query (UDP dst port 53 to gateway IP).
    Dns,
    /// Other UDP traffic.
    Udp,
    /// ICMP traffic.
    Icmp,
}

/// smoltcp `Device` implementation wrapping the guest VM's socketpair FD.
///
/// Performs frame classification to separate traffic that smoltcp should
/// handle (ARP, TCP) from traffic handled by existing proxy modules.
pub struct SmoltcpDevice {
    /// Raw FD of the host end of the socketpair.
    fd: RawFd,
    /// Gateway IP for DNS interception.
    gateway_ip: Ipv4Addr,
    /// Frames queued for smoltcp ingress (ARP, TCP).
    rx_queue: VecDeque<Vec<u8>>,
    /// Frames generated by smoltcp to be written to the guest FD.
    tx_pending: Vec<Vec<u8>>,
    /// Frames intercepted from the guest (DHCP, DNS, UDP, ICMP).
    intercepted: Vec<InterceptedFrame>,
    /// TCP SYN frames held back from smoltcp until host connect completes.
    gated_syns: Vec<TcpSynInfo>,
    /// Reusable read buffer to avoid per-call allocation in `drain_guest_fd`.
    read_buf: Vec<u8>,
}

impl SmoltcpDevice {
    /// Creates a new device for the given socketpair FD.
    pub fn new(fd: RawFd, gateway_ip: Ipv4Addr) -> Self {
        Self {
            fd,
            gateway_ip,
            rx_queue: VecDeque::new(),
            tx_pending: Vec::new(),
            intercepted: Vec::new(),
            gated_syns: Vec::new(),
            read_buf: vec![0u8; MAX_FRAME_SIZE],
        }
    }

    /// Drains all available frames from the guest FD, classifying each as
    /// either a smoltcp frame (ARP/TCP) or an intercepted frame.
    ///
    /// Must be called before `iface.poll()` to feed smoltcp with new data.
    /// Also learns the guest MAC address from frame source addresses.
    pub fn drain_guest_fd(&mut self, guest_mac: &mut Option<[u8; 6]>) {
        loop {
            match fd_read(self.fd, &mut self.read_buf) {
                Ok(n) if n > 0 => {
                    tracing::debug!("drain_guest_fd: read {n} bytes");
                    let frame = self.read_buf[..n].to_vec();
                    self.classify_frame(frame, guest_mac);
                }
                Ok(_) => break,
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => {
                    tracing::warn!("Guest FD read error: {}", e);
                    break;
                }
            }
        }
    }

    /// Injects a raw frame directly into the rx_queue for smoltcp processing.
    ///
    /// Used by TcpBridge to inject gated SYN frames when host connect succeeds,
    /// and in tests for frames that need to bypass the FD read path.
    pub fn inject_rx(&mut self, frame: Vec<u8>) {
        self.rx_queue.push_back(frame);
    }

    /// Takes all intercepted frames, leaving the internal buffer empty.
    pub fn take_intercepted(&mut self) -> Vec<InterceptedFrame> {
        std::mem::take(&mut self.intercepted)
    }

    /// Takes all pending TX frames generated by smoltcp, leaving the buffer empty.
    pub fn take_tx_pending(&mut self) -> Vec<Vec<u8>> {
        std::mem::take(&mut self.tx_pending)
    }

    /// Takes all gated TCP SYN frames, leaving the buffer empty.
    pub fn take_gated_syns(&mut self) -> Vec<TcpSynInfo> {
        std::mem::take(&mut self.gated_syns)
    }

    /// Classifies a frame and routes it to the appropriate queue.
    fn classify_frame(&mut self, frame: Vec<u8>, guest_mac: &mut Option<[u8; 6]>) {
        if frame.len() < ETH_HEADER_LEN {
            return;
        }

        // Learn guest MAC from source address.
        let src_mac = [frame[6], frame[7], frame[8], frame[9], frame[10], frame[11]];
        learn_guest_mac(src_mac, guest_mac);

        let ethertype = u16::from_be_bytes([frame[12], frame[13]]);

        match ethertype {
            // ARP → smoltcp
            0x0806 => {
                self.rx_queue.push_back(frame);
            }
            // IPv4 → classify by protocol
            0x0800 => {
                self.classify_ipv4(frame);
            }
            // Everything else → drop
            _ => {
                tracing::debug!(
                    "Dropping frame with EtherType {:#06x}, len={}",
                    ethertype,
                    frame.len()
                );
            }
        }
    }

    /// Classifies an IPv4 frame by L4 protocol.
    fn classify_ipv4(&mut self, frame: Vec<u8>) {
        let ip_start = ETH_HEADER_LEN;
        if frame.len() < ip_start + 20 {
            return;
        }

        let protocol = frame[ip_start + 9];
        let ihl = ((frame[ip_start] & 0x0F) as usize) * 4;
        let l4_start = ip_start + ihl;

        match protocol {
            PROTO_TCP => {
                if l4_start + 14 <= frame.len() {
                    let dst_port = u16::from_be_bytes([frame[l4_start + 2], frame[l4_start + 3]]);
                    let src_port = u16::from_be_bytes([frame[l4_start], frame[l4_start + 1]]);
                    let flags = frame[l4_start + 13];
                    let dst_ip = Ipv4Addr::new(
                        frame[ip_start + 16],
                        frame[ip_start + 17],
                        frame[ip_start + 18],
                        frame[ip_start + 19],
                    );
                    let src_ip = Ipv4Addr::new(
                        frame[ip_start + 12],
                        frame[ip_start + 13],
                        frame[ip_start + 14],
                        frame[ip_start + 15],
                    );
                    tracing::debug!(
                        "TCP frame: {src_ip}:{src_port} → {dst_ip}:{dst_port} flags={flags:#04x} len={}",
                        frame.len()
                    );
                    // SYN without ACK = new outbound connection attempt — gate it.
                    if flags & 0x02 != 0 && flags & 0x10 == 0 {
                        let syn_seq = u32::from_be_bytes([
                            frame[l4_start + 4],
                            frame[l4_start + 5],
                            frame[l4_start + 6],
                            frame[l4_start + 7],
                        ]);
                        tracing::debug!("TCP SYN gated: {src_ip}:{src_port} → {dst_ip}:{dst_port}");
                        self.gated_syns.push(TcpSynInfo {
                            dst_port,
                            src_ip,
                            src_port,
                            dst_ip,
                            syn_seq,
                            frame,
                        });
                        return;
                    }
                }
                self.rx_queue.push_back(frame);
            }
            // UDP → check for DHCP/DNS interception
            PROTO_UDP => {
                if l4_start + 8 <= frame.len() {
                    let dst_port = u16::from_be_bytes([frame[l4_start + 2], frame[l4_start + 3]]);
                    let dst_ip = Ipv4Addr::new(
                        frame[ip_start + 16],
                        frame[ip_start + 17],
                        frame[ip_start + 18],
                        frame[ip_start + 19],
                    );

                    let kind = if dst_port == 67 {
                        InterceptedKind::Dhcp
                    } else if dst_port == 53 && dst_ip == self.gateway_ip {
                        InterceptedKind::Dns
                    } else {
                        InterceptedKind::Udp
                    };

                    self.intercepted.push(InterceptedFrame { frame, kind });
                }
            }
            // ICMP → intercept
            PROTO_ICMP => {
                self.intercepted.push(InterceptedFrame {
                    frame,
                    kind: InterceptedKind::Icmp,
                });
            }
            _ => {
                tracing::debug!("Dropping IPv4 protocol {}", protocol);
            }
        }
    }
}

impl Device for SmoltcpDevice {
    type RxToken<'a> = SmoltcpRxToken;
    type TxToken<'a> = SmoltcpTxToken<'a>;

    fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
        let frame = self.rx_queue.pop_front()?;
        Some((
            SmoltcpRxToken { frame },
            SmoltcpTxToken {
                tx_pending: &mut self.tx_pending,
            },
        ))
    }

    fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
        Some(SmoltcpTxToken {
            tx_pending: &mut self.tx_pending,
        })
    }

    fn capabilities(&self) -> DeviceCapabilities {
        let mut caps = DeviceCapabilities::default();
        caps.medium = Medium::Ethernet;
        caps.max_transmission_unit = ETHERNET_MTU;
        caps.max_burst_size = Some(32);
        caps
    }
}

/// RX token: delivers a received frame to smoltcp.
pub struct SmoltcpRxToken {
    frame: Vec<u8>,
}

impl RxToken for SmoltcpRxToken {
    fn consume<R, F>(self, f: F) -> R
    where
        F: FnOnce(&[u8]) -> R,
    {
        f(&self.frame)
    }
}

/// TX token: collects a frame from smoltcp for later writing to the guest FD.
pub struct SmoltcpTxToken<'a> {
    tx_pending: &'a mut Vec<Vec<u8>>,
}

impl TxToken for SmoltcpTxToken<'_> {
    fn consume<R, F>(self, len: usize, f: F) -> R
    where
        F: FnOnce(&mut [u8]) -> R,
    {
        let mut buf = vec![0u8; len];
        let result = f(&mut buf);
        self.tx_pending.push(buf);
        result
    }
}

/// Reads from a file descriptor into `buf`, returning number of bytes read.
fn fd_read(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
    // SAFETY: reading into our buffer from a valid fd.
    let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
    if n < 0 {
        Err(io::Error::last_os_error())
    } else {
        #[allow(clippy::cast_sign_loss)]
        Ok(n as usize)
    }
}

/// Learns the guest MAC from a frame's source address.
fn learn_guest_mac(mac: [u8; 6], guest_mac: &mut Option<[u8; 6]>) {
    // Skip broadcast/multicast
    if mac[0] & 0x01 != 0 || mac == [0; 6] {
        return;
    }
    if guest_mac.is_none() {
        tracing::info!(
            "Learned guest MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
            mac[0],
            mac[1],
            mac[2],
            mac[3],
            mac[4],
            mac[5]
        );
    }
    *guest_mac = Some(mac);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::fd::FromRawFd;

    fn socketpair() -> (std::os::fd::OwnedFd, std::os::fd::OwnedFd) {
        use std::os::fd::OwnedFd;
        let mut fds: [i32; 2] = [0; 2];
        // SAFETY: valid pointer to 2-element array.
        let ret = unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, fds.as_mut_ptr()) };
        assert_eq!(ret, 0, "socketpair() failed");
        // SAFETY: fds are valid file descriptors from socketpair.
        unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }
    }

    fn set_nonblocking(fd: RawFd) {
        // SAFETY: fcntl on a valid fd.
        unsafe {
            let flags = libc::fcntl(fd, libc::F_GETFL);
            libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
        }
    }

    /// Writes raw bytes to an FD.
    fn fd_write_raw(fd: RawFd, data: &[u8]) {
        // SAFETY: writing from valid buffer to valid fd.
        unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
    }

    /// Builds a minimal ARP frame for testing.
    fn make_arp_frame() -> Vec<u8> {
        let mut frame = vec![0u8; 42];
        let guest_mac = [0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE];
        // Ethernet: dst=broadcast, src=guest, type=ARP
        frame[0..6].copy_from_slice(&[0xFF; 6]);
        frame[6..12].copy_from_slice(&guest_mac);
        frame[12..14].copy_from_slice(&[0x08, 0x06]);
        frame
    }

    /// Builds a minimal TCP SYN frame for testing.
    fn make_tcp_frame() -> Vec<u8> {
        let mut frame = vec![0u8; ETH_HEADER_LEN + 40];
        let guest_mac = [0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE];
        // Ethernet
        frame[0..6].copy_from_slice(&[0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
        frame[6..12].copy_from_slice(&guest_mac);
        frame[12..14].copy_from_slice(&[0x08, 0x00]); // IPv4
        // IPv4 header
        let ip = ETH_HEADER_LEN;
        frame[ip] = 0x45;
        frame[ip + 2..ip + 4].copy_from_slice(&40u16.to_be_bytes());
        frame[ip + 9] = PROTO_TCP;
        frame[ip + 12..ip + 16].copy_from_slice(&[192, 168, 64, 2]);
        frame[ip + 16..ip + 20].copy_from_slice(&[1, 1, 1, 1]);
        frame
    }

    /// Builds a minimal UDP frame for testing.
    fn make_udp_frame(dst_ip: [u8; 4], dst_port: u16) -> Vec<u8> {
        let mut frame = vec![0u8; ETH_HEADER_LEN + 28];
        let guest_mac = [0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE];
        frame[0..6].copy_from_slice(&[0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
        frame[6..12].copy_from_slice(&guest_mac);
        frame[12..14].copy_from_slice(&[0x08, 0x00]);
        let ip = ETH_HEADER_LEN;
        frame[ip] = 0x45;
        frame[ip + 2..ip + 4].copy_from_slice(&28u16.to_be_bytes());
        frame[ip + 9] = PROTO_UDP;
        frame[ip + 12..ip + 16].copy_from_slice(&[192, 168, 64, 2]);
        frame[ip + 16..ip + 20].copy_from_slice(&dst_ip);
        // UDP header
        let l4 = ip + 20;
        frame[l4..l4 + 2].copy_from_slice(&1234u16.to_be_bytes());
        frame[l4 + 2..l4 + 4].copy_from_slice(&dst_port.to_be_bytes());
        frame[l4 + 4..l4 + 6].copy_from_slice(&8u16.to_be_bytes());
        frame
    }

    /// Builds a minimal ICMP frame for testing.
    fn make_icmp_frame() -> Vec<u8> {
        let mut frame = vec![0u8; ETH_HEADER_LEN + 28];
        let guest_mac = [0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE];
        frame[0..6].copy_from_slice(&[0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
        frame[6..12].copy_from_slice(&guest_mac);
        frame[12..14].copy_from_slice(&[0x08, 0x00]);
        let ip = ETH_HEADER_LEN;
        frame[ip] = 0x45;
        frame[ip + 2..ip + 4].copy_from_slice(&28u16.to_be_bytes());
        frame[ip + 9] = PROTO_ICMP;
        frame[ip + 12..ip + 16].copy_from_slice(&[192, 168, 64, 2]);
        frame[ip + 16..ip + 20].copy_from_slice(&[8, 8, 8, 8]);
        frame
    }

    #[test]
    fn classify_arp_goes_to_rx_queue() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_arp_frame(), &mut guest_mac);

        assert_eq!(device.rx_queue.len(), 1);
        assert!(device.intercepted.is_empty());
    }

    #[test]
    fn classify_tcp_goes_to_rx_queue() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_tcp_frame(), &mut guest_mac);

        assert_eq!(device.rx_queue.len(), 1);
        assert!(device.intercepted.is_empty());
    }

    #[test]
    fn classify_dhcp_intercepted() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_udp_frame([255, 255, 255, 255], 67), &mut guest_mac);

        assert!(device.rx_queue.is_empty());
        assert_eq!(device.intercepted.len(), 1);
        assert_eq!(device.intercepted[0].kind, InterceptedKind::Dhcp);
    }

    #[test]
    fn classify_dns_to_gateway_intercepted() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_udp_frame([192, 168, 64, 1], 53), &mut guest_mac);

        assert!(device.rx_queue.is_empty());
        assert_eq!(device.intercepted.len(), 1);
        assert_eq!(device.intercepted[0].kind, InterceptedKind::Dns);
    }

    #[test]
    fn classify_dns_to_external_is_udp() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        // DNS to 8.8.8.8 is regular UDP, not intercepted as DNS.
        device.classify_frame(make_udp_frame([8, 8, 8, 8], 53), &mut guest_mac);

        assert!(device.rx_queue.is_empty());
        assert_eq!(device.intercepted.len(), 1);
        assert_eq!(device.intercepted[0].kind, InterceptedKind::Udp);
    }

    #[test]
    fn classify_icmp_intercepted() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_icmp_frame(), &mut guest_mac);

        assert!(device.rx_queue.is_empty());
        assert_eq!(device.intercepted.len(), 1);
        assert_eq!(device.intercepted[0].kind, InterceptedKind::Icmp);
    }

    #[test]
    fn classify_regular_udp_intercepted() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        device.classify_frame(make_udp_frame([1, 1, 1, 1], 443), &mut guest_mac);

        assert!(device.rx_queue.is_empty());
        assert_eq!(device.intercepted.len(), 1);
        assert_eq!(device.intercepted[0].kind, InterceptedKind::Udp);
    }

    #[test]
    fn drain_guest_fd_reads_and_classifies() {
        use std::os::fd::AsRawFd;
        let (host_fd, guest_fd) = socketpair();
        set_nonblocking(host_fd.as_raw_fd());

        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(host_fd.as_raw_fd(), gateway_ip);
        let mut guest_mac = None;

        // Write an ARP frame and a UDP frame via the guest side.
        fd_write_raw(guest_fd.as_raw_fd(), &make_arp_frame());
        fd_write_raw(guest_fd.as_raw_fd(), &make_icmp_frame());

        device.drain_guest_fd(&mut guest_mac);

        assert_eq!(device.rx_queue.len(), 1, "ARP should go to rx_queue");
        assert_eq!(device.intercepted.len(), 1, "ICMP should be intercepted");
        assert!(guest_mac.is_some(), "Guest MAC should be learned");
    }

    #[test]
    fn tx_token_collects_frames() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);

        let token = device.transmit(Instant::from_millis(0)).unwrap();
        token.consume(42, |buf| {
            buf[0..6].copy_from_slice(&[0xFF; 6]);
        });

        let pending = device.take_tx_pending();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].len(), 42);
        assert_eq!(&pending[0][0..6], &[0xFF; 6]);
    }

    #[test]
    fn learn_guest_mac_ignores_broadcast() {
        let mut mac = None;
        learn_guest_mac([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], &mut mac);
        assert!(mac.is_none());
    }

    #[test]
    fn learn_guest_mac_records_unicast() {
        let mut mac = None;
        learn_guest_mac([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE], &mut mac);
        assert_eq!(mac, Some([0x02, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE]));
    }

    #[test]
    fn classify_tcp_syn_is_gated() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        // Build a TCP SYN frame (flags = 0x02).
        let mut frame = make_tcp_frame();
        let ip = ETH_HEADER_LEN;
        let l4 = ip + 20;
        frame[l4 + 13] = 0x02; // SYN flag
        // Set src port = 12345, dst port = 443
        frame[l4..l4 + 2].copy_from_slice(&12345u16.to_be_bytes());
        frame[l4 + 2..l4 + 4].copy_from_slice(&443u16.to_be_bytes());
        // Set seq = 1000
        frame[l4 + 4..l4 + 8].copy_from_slice(&1000u32.to_be_bytes());

        device.classify_frame(frame.clone(), &mut guest_mac);

        assert!(device.rx_queue.is_empty(), "SYN should NOT go to rx_queue");
        assert_eq!(device.gated_syns.len(), 1);
        assert_eq!(device.gated_syns[0].dst_port, 443);
        assert_eq!(device.gated_syns[0].src_port, 12345);
        assert_eq!(device.gated_syns[0].syn_seq, 1000);
        assert_eq!(device.gated_syns[0].dst_ip, Ipv4Addr::new(1, 1, 1, 1));
        assert_eq!(device.gated_syns[0].src_ip, Ipv4Addr::new(192, 168, 64, 2));
    }

    #[test]
    fn classify_tcp_non_syn_goes_to_rx_queue() {
        let gateway_ip = Ipv4Addr::new(192, 168, 64, 1);
        let mut device = SmoltcpDevice::new(0, gateway_ip);
        let mut guest_mac = None;

        // Build a TCP ACK frame (flags = 0x10).
        let mut frame = make_tcp_frame();
        let ip = ETH_HEADER_LEN;
        let l4 = ip + 20;
        frame[l4 + 13] = 0x10; // ACK flag

        device.classify_frame(frame, &mut guest_mac);

        assert_eq!(
            device.rx_queue.len(),
            1,
            "Non-SYN TCP should go to rx_queue"
        );
        assert!(device.gated_syns.is_empty());
    }
}