unkernel-rs 0.6.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Pure-Rust virtual Layer-2 Ethernet switch (`switch0`) for multi-VM `unkernel-rs` labs.
//!
//! Connects 2+ Wasmtime Linux VMs over an in-process learning L2 Ethernet switch with:
//! - Automatic MAC address learning, unicast forwarding, and broadcast/unknown-unicast flooding.
//! - Real-time chaos/fault injection per port: `cut_link`, `reconnect_link`, `set_drop_rate`,
//!   and `set_delay_ms`.
//! - Optional zero-dependency **PCAPng** packet capture (Wireshark-compatible) recording every
//!   Ethernet frame traversing the switch with microsecond timestamps and source-port annotations.
//! - Optional per-port NAT uplink ([`NetStack`]) so nodes can talk to each other over L2/L3
//!   **and** optionally reach the internet with full VMI / TLS inspection.

use crate::net::{
    ETH_ARP, ETH_IP, GW_IP, GW_MAC, MASK_IP, NET_IP, NetDevice, NetStack, build_switch_dhcp_reply,
};
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::Write;
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

type RaiseIrqFn = Arc<dyn Fn() + Send + Sync>;

/// Attachment parameters passed via [`crate::VmConfig::switch`] to wire a VM onto a [`VirtualSwitch`].
#[derive(Clone)]
pub struct SwitchAttachment {
    pub switch: Arc<VirtualSwitch>,
    pub node_name: String,
    pub mac: [u8; 6],
    pub ip: [u8; 4],
}

impl std::fmt::Debug for SwitchAttachment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SwitchAttachment")
            .field("switch", &self.switch.name())
            .field("node_name", &self.node_name)
            .field("mac", &format_mac(self.mac))
            .field("ip", &Ipv4Addr::from(self.ip))
            .finish()
    }
}

/// Live statistics for a single switch port.
#[derive(Debug, Clone, Serialize)]
pub struct SwitchPortStats {
    pub port_id: usize,
    pub node: String,
    pub mac: String,
    pub ip: String,
    pub link_up: bool,
    pub drop_pct: u8,
    pub delay_ms: u64,
    pub tx_frames: u64,
    pub rx_frames: u64,
    pub dropped_frames: u64,
    pub has_uplink: bool,
}

/// One learned entry in the switch's L2 MAC forwarding table.
#[derive(Debug, Clone, Serialize)]
pub struct MacTableEntry {
    pub mac: String,
    pub port_id: usize,
    pub node: String,
}

struct PortInner {
    port_id: usize,
    node: String,
    mac: [u8; 6],
    ip: [u8; 4],
    rx_queue: VecDeque<Vec<u8>>,
    raise_irq: RaiseIrqFn,
    uplink: Option<Arc<NetStack>>,
    link_up: bool,
    drop_pct: u8,
    delay_ms: u64,
    tx_frames: u64,
    rx_frames: u64,
    dropped_frames: u64,
    closed: bool,
}

struct SwitchInner {
    ports: Vec<PortInner>,
    mac_table: HashMap<[u8; 6], usize>,
    pcap: Option<PcapNgWriter>,
}

/// In-process learning Layer-2 Ethernet switch linking multiple `unkernel-rs` VMs.
pub struct VirtualSwitch {
    name: String,
    inner: Mutex<SwitchInner>,
    total_frames: AtomicU64,
    prng_state: AtomicU64,
}

impl VirtualSwitch {
    /// Create a new virtual L2 Ethernet switch (e.g. `"switch0"`).
    pub fn new(name: impl Into<String>) -> Arc<Self> {
        Arc::new(Self {
            name: name.into(),
            inner: Mutex::new(SwitchInner {
                ports: Vec::new(),
                mac_table: HashMap::new(),
                pcap: None,
            }),
            total_frames: AtomicU64::new(0),
            prng_state: AtomicU64::new(0x9e37_79b9_7f4a_7c15),
        })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    /// Attach a pre-opened host file for Wireshark-compatible PCAPng capture of all L2 frames.
    pub fn attach_pcap(&self, file: File) -> std::io::Result<()> {
        let writer = PcapNgWriter::new(file, &self.name)?;
        self.inner.lock().unwrap().pcap = Some(writer);
        Ok(())
    }

    /// Register a VM port on this switch and return a [`NetDevice`] handle for the guest NIC.
    pub fn add_port(
        self: &Arc<Self>,
        node_name: impl Into<String>,
        mac: [u8; 6],
        ip: [u8; 4],
        raise_irq: RaiseIrqFn,
        uplink: Option<Arc<NetStack>>,
    ) -> Arc<SwitchPort> {
        let mut inner = self.inner.lock().unwrap();
        let port_id = inner.ports.len();
        inner.ports.push(PortInner {
            port_id,
            node: node_name.into(),
            mac,
            ip,
            rx_queue: VecDeque::new(),
            raise_irq,
            uplink,
            link_up: true,
            drop_pct: 0,
            delay_ms: 0,
            tx_frames: 0,
            rx_frames: 0,
            dropped_frames: 0,
            closed: false,
        });
        Arc::new(SwitchPort {
            switch: Arc::clone(self),
            port_id,
            mac,
        })
    }

    /// Deterministically assign a unique guest MAC (`52:54:00:00:00:XX`) and IPv4 (`10.0.2.10+idx`).
    pub fn allocate_identity(index: usize) -> ([u8; 6], [u8; 4]) {
        let octet = (10u8).saturating_add(index as u8).min(250);
        ([0x52, 0x54, 0x00, 0x00, 0x00, octet], [10, 0, 2, octet])
    }

    /// Simulate unplugging a node's Ethernet cable (drops all TX/RX frames on that port).
    pub fn cut_link(&self, node: &str) -> bool {
        let mut inner = self.inner.lock().unwrap();
        if let Some(p) = inner.ports.iter_mut().find(|p| p.node == node) {
            p.link_up = false;
            true
        } else {
            false
        }
    }

    /// Reconnect a previously cut port cable.
    pub fn reconnect_link(&self, node: &str) -> bool {
        let mut inner = self.inner.lock().unwrap();
        if let Some(p) = inner.ports.iter_mut().find(|p| p.node == node) {
            p.link_up = true;
            true
        } else {
            false
        }
    }

    /// Configure simulated packet loss (`0..=100` percent) on a node's switch port.
    pub fn set_drop_rate(&self, node: &str, pct: u8) -> bool {
        let mut inner = self.inner.lock().unwrap();
        if let Some(p) = inner.ports.iter_mut().find(|p| p.node == node) {
            p.drop_pct = pct.min(100);
            true
        } else {
            false
        }
    }

    /// Configure simulated one-way delivery latency in milliseconds on a node's switch port.
    pub fn set_delay_ms(&self, node: &str, ms: u64) -> bool {
        let mut inner = self.inner.lock().unwrap();
        if let Some(p) = inner.ports.iter_mut().find(|p| p.node == node) {
            p.delay_ms = ms.min(10_000);
            true
        } else {
            false
        }
    }

    /// Snapshot live per-port statistics and chaos settings.
    pub fn port_stats(&self) -> Vec<SwitchPortStats> {
        let inner = self.inner.lock().unwrap();
        inner
            .ports
            .iter()
            .map(|p| SwitchPortStats {
                port_id: p.port_id,
                node: p.node.clone(),
                mac: format_mac(p.mac),
                ip: Ipv4Addr::from(p.ip).to_string(),
                link_up: p.link_up,
                drop_pct: p.drop_pct,
                delay_ms: p.delay_ms,
                tx_frames: p.tx_frames,
                rx_frames: p.rx_frames,
                dropped_frames: p.dropped_frames,
                has_uplink: p.uplink.is_some(),
            })
            .collect()
    }

    /// Snapshot the switch's learned L2 MAC forwarding table.
    pub fn mac_table(&self) -> Vec<MacTableEntry> {
        let inner = self.inner.lock().unwrap();
        let mut out: Vec<MacTableEntry> = inner
            .mac_table
            .iter()
            .filter_map(|(&mac, &pid)| {
                inner.ports.get(pid).map(|p| MacTableEntry {
                    mac: format_mac(mac),
                    port_id: pid,
                    node: p.node.clone(),
                })
            })
            .collect();
        out.sort_by(|a, b| a.port_id.cmp(&b.port_id).then_with(|| a.mac.cmp(&b.mac)));
        out
    }

    /// Total Ethernet frames switched across all ports.
    pub fn total_frames(&self) -> u64 {
        self.total_frames.load(Ordering::Relaxed)
    }

    /// Flush the PCAPng capture file (if attached).
    pub fn flush_pcap(&self) {
        let mut inner = self.inner.lock().unwrap();
        if let Some(pcap) = inner.pcap.as_mut() {
            pcap.flush();
        }
    }

    fn should_drop(&self, pct: u8) -> bool {
        if pct == 0 {
            return false;
        }
        if pct >= 100 {
            return true;
        }
        // Simple xorshift64* PRNG for deterministic-overhead chaos simulation
        let prev = self
            .prng_state
            .fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed);
        let mut x = prev ^ (prev >> 12);
        x ^= x << 25;
        x ^= x >> 27;
        let sample = (x.wrapping_mul(0x2545_f491_4f6c_dd1d) % 100) as u8;
        sample < pct
    }

    /// Deliver an uplink NAT reply frame back into a port (recording it in PCAPng and honoring
    /// link-cut / drop / delay state).
    pub fn inject_uplink_reply(self: &Arc<Self>, port_id: usize, frame: Vec<u8>) {
        let delivery = {
            let mut inner = self.inner.lock().unwrap();
            let SwitchInner { ports, pcap, .. } = &mut *inner;
            let Some(port) = ports.get_mut(port_id) else {
                return;
            };
            if port.closed || !port.link_up {
                port.dropped_frames += 1;
                return;
            }
            if self.should_drop(port.drop_pct) {
                port.dropped_frames += 1;
                return;
            }
            let comment = format!("uplink->{}", port.node);
            let delay_ms = port.delay_ms;
            if let Some(w) = pcap.as_mut() {
                w.write_packet(&frame, &comment);
            }
            self.total_frames.fetch_add(1, Ordering::Relaxed);
            if delay_ms == 0 {
                port.rx_frames += 1;
                port.rx_queue.push_back(frame);
                Some((port.raise_irq.clone(), None))
            } else {
                Some((port.raise_irq.clone(), Some((delay_ms, frame))))
            }
        };

        if let Some((irq, delayed)) = delivery {
            if let Some((delay_ms, frame)) = delayed {
                self.schedule_delayed_delivery(port_id, delay_ms, frame);
            } else {
                (irq)();
            }
        }
    }

    fn schedule_delayed_delivery(self: &Arc<Self>, port_id: usize, delay_ms: u64, frame: Vec<u8>) {
        let sw = Arc::clone(self);
        std::thread::Builder::new()
            .name("unkernel-switch-delay".into())
            .spawn(move || {
                std::thread::sleep(Duration::from_millis(delay_ms));
                let irq = {
                    let mut inner = sw.inner.lock().unwrap();
                    let Some(port) = inner.ports.get_mut(port_id) else {
                        return;
                    };
                    if port.closed || !port.link_up {
                        port.dropped_frames += 1;
                        return;
                    }
                    port.rx_frames += 1;
                    port.rx_queue.push_back(frame);
                    port.raise_irq.clone()
                };
                (irq)();
            })
            .ok();
    }

    fn forward_from_port(self: &Arc<Self>, src_port_id: usize, frame: &[u8]) {
        if frame.len() < 14 {
            return;
        }
        let mut dst_mac = [0u8; 6];
        let mut src_mac = [0u8; 6];
        dst_mac.copy_from_slice(&frame[0..6]);
        src_mac.copy_from_slice(&frame[6..12]);
        let ethertype = u16::from_be_bytes([frame[12], frame[13]]);

        let mut immediate_irqs: Vec<RaiseIrqFn> = Vec::new();
        let mut delayed_deliveries: Vec<(usize, u64, Vec<u8>)> = Vec::new();
        let mut uplink_target: Option<Arc<NetStack>> = None;
        let mut local_dhcp_reply: Option<Vec<u8>> = None;

        {
            let mut inner = self.inner.lock().unwrap();
            let (src_node, src_ip, src_up, src_drop, src_uplink) =
                match inner.ports.get_mut(src_port_id) {
                    Some(p) => {
                        if p.closed {
                            return;
                        }
                        if !p.link_up || self.should_drop(p.drop_pct) {
                            p.dropped_frames += 1;
                            return;
                        }
                        p.tx_frames += 1;
                        (
                            p.node.clone(),
                            u32::from_be_bytes(p.ip),
                            p.link_up,
                            p.drop_pct,
                            p.uplink.clone(),
                        )
                    }
                    None => return,
                };
            let _ = (src_up, src_drop);

            // Learn source MAC (ignore multicast/broadcast source MACs)
            if (src_mac[0] & 1) == 0 {
                inner.mac_table.insert(src_mac, src_port_id);
            }

            // Record every L2 frame in PCAPng
            if let Some(pcap) = inner.pcap.as_mut() {
                pcap.write_packet(frame, &format!("tx:{src_node}"));
            }
            self.total_frames.fetch_add(1, Ordering::Relaxed);

            // Check whether this frame is addressed to the gateway/uplink or is DHCP
            let to_gateway = dst_mac == GW_MAC || is_uplink_candidate(ethertype, frame);
            if to_gateway {
                if let Some(up) = src_uplink {
                    uplink_target = Some(up);
                    if dst_mac == GW_MAC {
                        // Unicast to gateway MAC -> send directly to uplink without flooding peers
                        drop(inner);
                        if let Some(up) = uplink_target {
                            up.send_frame(frame);
                        }
                        return;
                    }
                } else if let Some(reply) = build_switch_dhcp_reply(frame, src_ip) {
                    local_dhcp_reply = Some(reply);
                }
            }

            let is_broadcast_or_mcast = (dst_mac[0] & 1) == 1;
            let known_dst = if is_broadcast_or_mcast {
                None
            } else {
                inner.mac_table.get(&dst_mac).copied()
            };

            match known_dst {
                Some(dst_id) if dst_id != src_port_id => {
                    if let Some(dst) = inner.ports.get_mut(dst_id) {
                        if dst.closed || !dst.link_up || self.should_drop(dst.drop_pct) {
                            dst.dropped_frames += 1;
                        } else if dst.delay_ms > 0 {
                            delayed_deliveries.push((dst_id, dst.delay_ms, frame.to_vec()));
                        } else {
                            dst.rx_frames += 1;
                            dst.rx_queue.push_back(frame.to_vec());
                            immediate_irqs.push(dst.raise_irq.clone());
                        }
                    }
                }
                Some(_) => {
                    // Destined to sender's own MAC — drop (standard L2 switch behavior)
                }
                None => {
                    // Flood to all other active ports
                    for idx in 0..inner.ports.len() {
                        if idx == src_port_id {
                            continue;
                        }
                        let dst = &mut inner.ports[idx];
                        if dst.closed || !dst.link_up {
                            continue;
                        }
                        if self.should_drop(dst.drop_pct) {
                            dst.dropped_frames += 1;
                            continue;
                        }
                        if dst.delay_ms > 0 {
                            delayed_deliveries.push((idx, dst.delay_ms, frame.to_vec()));
                        } else {
                            dst.rx_frames += 1;
                            dst.rx_queue.push_back(frame.to_vec());
                            immediate_irqs.push(dst.raise_irq.clone());
                        }
                    }
                }
            }
        }

        for irq in immediate_irqs {
            (irq)();
        }
        for (dst_id, delay_ms, f) in delayed_deliveries {
            self.schedule_delayed_delivery(dst_id, delay_ms, f);
        }
        if let Some(up) = uplink_target {
            up.send_frame(frame);
        }
        if let Some(reply) = local_dhcp_reply {
            self.inject_uplink_reply(src_port_id, reply);
        }
    }
}

fn is_uplink_candidate(ethertype: u16, frame: &[u8]) -> bool {
    match ethertype {
        ETH_ARP if frame.len() >= 42 => {
            let tip = u32::from_be_bytes([frame[38], frame[39], frame[40], frame[41]]);
            tip == GW_IP || tip == crate::net::DNS_IP
        }
        ETH_IP if frame.len() >= 34 => {
            let dst = u32::from_be_bytes([frame[30], frame[31], frame[32], frame[33]]);
            // Gateway/DNS, external non-subnet IP, or broadcast (DHCP)
            dst == GW_IP
                || dst == crate::net::DNS_IP
                || dst == u32::MAX
                || (dst & MASK_IP) != NET_IP
        }
        _ => false,
    }
}

/// Guest-side handle representing one port on a [`VirtualSwitch`].
pub struct SwitchPort {
    switch: Arc<VirtualSwitch>,
    port_id: usize,
    mac: [u8; 6],
}

impl SwitchPort {
    pub fn port_id(&self) -> usize {
        self.port_id
    }

    pub fn attach_uplink(&self, uplink: Arc<NetStack>) {
        let mut inner = self.switch.inner.lock().unwrap();
        if let Some(p) = inner.ports.get_mut(self.port_id) {
            p.uplink = Some(uplink);
        }
    }
}

impl NetDevice for SwitchPort {
    fn mac(&self) -> [u8; 6] {
        self.mac
    }

    fn rx_len(&self) -> usize {
        let inner = self.switch.inner.lock().unwrap();
        inner
            .ports
            .get(self.port_id)
            .and_then(|p| p.rx_queue.front().map(|f| f.len()))
            .unwrap_or(0)
    }

    fn recv_frame(&self) -> Option<Vec<u8>> {
        let mut inner = self.switch.inner.lock().unwrap();
        inner
            .ports
            .get_mut(self.port_id)
            .and_then(|p| p.rx_queue.pop_front())
    }

    fn send_frame(&self, frame: &[u8]) {
        self.switch.forward_from_port(self.port_id, frame);
    }

    fn shutdown(&self) {
        let uplink = {
            let mut inner = self.switch.inner.lock().unwrap();
            if let Some(p) = inner.ports.get_mut(self.port_id) {
                p.closed = true;
                p.link_up = false;
                p.rx_queue.clear();
                p.uplink.take()
            } else {
                None
            }
        };
        if let Some(up) = uplink {
            up.shutdown();
        }
        self.switch.flush_pcap();
    }
}

pub fn format_mac(mac: [u8; 6]) -> String {
    format!(
        "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
        mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
    )
}

/// Zero-dependency Wireshark-compatible PCAPng writer (SHB + Ethernet IDB + EPB).
struct PcapNgWriter {
    file: File,
}

impl PcapNgWriter {
    fn new(mut file: File, iface_name: &str) -> std::io::Result<Self> {
        // 1. Section Header Block (SHB)
        let mut shb = Vec::with_capacity(28);
        shb.extend_from_slice(&0x0a0d_0d0au32.to_le_bytes()); // Block Type
        shb.extend_from_slice(&28u32.to_le_bytes()); // Block Total Length
        shb.extend_from_slice(&0x1a2b_3c4du32.to_le_bytes()); // Byte-Order Magic
        shb.extend_from_slice(&1u16.to_le_bytes()); // Major Version
        shb.extend_from_slice(&0u16.to_le_bytes()); // Minor Version
        shb.extend_from_slice(&(-1i64).to_le_bytes()); // Unspecified Section Length
        shb.extend_from_slice(&28u32.to_le_bytes()); // Trailing Block Total Length
        file.write_all(&shb)?;

        // 2. Interface Description Block (IDB, LINKTYPE_ETHERNET = 1)
        let name_bytes = iface_name.as_bytes();
        let name_pad = (4 - (name_bytes.len() % 4)) % 4;
        let opts_len = 4 + name_bytes.len() + name_pad + 4; // opt_if_name + opt_endofopt
        let idb_len = (20 + opts_len) as u32;
        let mut idb = Vec::with_capacity(idb_len as usize);
        idb.extend_from_slice(&0x0000_0001u32.to_le_bytes()); // IDB
        idb.extend_from_slice(&idb_len.to_le_bytes());
        idb.extend_from_slice(&1u16.to_le_bytes()); // LINKTYPE_ETHERNET
        idb.extend_from_slice(&0u16.to_le_bytes()); // Reserved
        idb.extend_from_slice(&65535u32.to_le_bytes()); // SnapLen
        // Option 2: if_name
        idb.extend_from_slice(&2u16.to_le_bytes());
        idb.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
        idb.extend_from_slice(name_bytes);
        idb.resize(idb.len() + name_pad, 0);
        // Option 0: endofopt
        idb.extend_from_slice(&0u32.to_le_bytes());
        idb.extend_from_slice(&idb_len.to_le_bytes());
        file.write_all(&idb)?;
        file.flush()?;

        Ok(Self { file })
    }

    fn write_packet(&mut self, frame: &[u8], comment: &str) {
        let now_us = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_micros() as u64)
            .unwrap_or(0);
        let ts_high = (now_us >> 32) as u32;
        let ts_low = (now_us & 0xffff_ffff) as u32;

        let cap_len = frame.len().min(65535);
        let frame_pad = (4 - (cap_len % 4)) % 4;

        let comment_bytes = comment.as_bytes();
        let comment_pad = (4 - (comment_bytes.len() % 4)) % 4;
        let opts_len = if !comment_bytes.is_empty() {
            4 + comment_bytes.len() + comment_pad + 4
        } else {
            0
        };

        let epb_len = (32 + cap_len + frame_pad + opts_len) as u32;
        let mut epb = Vec::with_capacity(epb_len as usize);
        epb.extend_from_slice(&0x0000_0006u32.to_le_bytes()); // EPB
        epb.extend_from_slice(&epb_len.to_le_bytes());
        epb.extend_from_slice(&0u32.to_le_bytes()); // Interface ID 0
        epb.extend_from_slice(&ts_high.to_le_bytes());
        epb.extend_from_slice(&ts_low.to_le_bytes());
        epb.extend_from_slice(&(cap_len as u32).to_le_bytes());
        epb.extend_from_slice(&(frame.len() as u32).to_le_bytes());
        epb.extend_from_slice(&frame[..cap_len]);
        epb.resize(epb.len() + frame_pad, 0);

        if !comment_bytes.is_empty() {
            epb.extend_from_slice(&1u16.to_le_bytes()); // opt_comment
            epb.extend_from_slice(&(comment_bytes.len() as u16).to_le_bytes());
            epb.extend_from_slice(comment_bytes);
            epb.resize(epb.len() + comment_pad, 0);
            epb.extend_from_slice(&0u32.to_le_bytes()); // opt_endofopt
        }

        epb.extend_from_slice(&epb_len.to_le_bytes());
        let _ = self.file.write_all(&epb);
    }

    fn flush(&mut self) {
        let _ = self.file.flush();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicUsize;

    fn eth_frame(dst: [u8; 6], src: [u8; 6], payload: &[u8]) -> Vec<u8> {
        let mut f = Vec::with_capacity(14 + payload.len());
        f.extend_from_slice(&dst);
        f.extend_from_slice(&src);
        f.extend_from_slice(&ETH_IP.to_be_bytes());
        f.extend_from_slice(payload);
        f
    }

    #[test]
    fn switch_learns_macs_forwards_unicast_and_honors_cut_reconnect() {
        let sw = VirtualSwitch::new("switch0");
        let irq1 = Arc::new(AtomicUsize::new(0));
        let irq2 = Arc::new(AtomicUsize::new(0));
        let irq3 = Arc::new(AtomicUsize::new(0));

        let (m1, ip1) = VirtualSwitch::allocate_identity(0);
        let (m2, ip2) = VirtualSwitch::allocate_identity(1);
        let (m3, ip3) = VirtualSwitch::allocate_identity(2);

        let i1 = irq1.clone();
        let p1 = sw.add_port(
            "node1",
            m1,
            ip1,
            Arc::new(move || {
                i1.fetch_add(1, Ordering::SeqCst);
            }),
            None,
        );
        let i2 = irq2.clone();
        let p2 = sw.add_port(
            "node2",
            m2,
            ip2,
            Arc::new(move || {
                i2.fetch_add(1, Ordering::SeqCst);
            }),
            None,
        );
        let i3 = irq3.clone();
        let p3 = sw.add_port(
            "node3",
            m3,
            ip3,
            Arc::new(move || {
                i3.fetch_add(1, Ordering::SeqCst);
            }),
            None,
        );

        // 1. Broadcast from node1 floods to node2 & node3 (not back to node1)
        p1.send_frame(&eth_frame([0xff; 6], m1, b"hello-all"));
        assert_eq!(p1.rx_len(), 0);
        assert!(p2.recv_frame().is_some());
        assert!(p3.recv_frame().is_some());
        assert_eq!(irq2.load(Ordering::SeqCst), 1);
        assert_eq!(irq3.load(Ordering::SeqCst), 1);

        // 2. Node2 replies unicast to learned m1 -> delivered ONLY to node1, NOT node3
        p2.send_frame(&eth_frame(m1, m2, b"reply-to-1"));
        assert!(p1.recv_frame().is_some());
        assert_eq!(p3.rx_len(), 0);
        assert_eq!(sw.mac_table().len(), 2);

        // 3. Cut node2's link -> unicast to node2 is dropped
        assert!(sw.cut_link("node2"));
        p1.send_frame(&eth_frame(m2, m1, b"dropped"));
        assert_eq!(p2.rx_len(), 0);

        // 4. Reconnect node2 -> unicast delivered again
        assert!(sw.reconnect_link("node2"));
        p1.send_frame(&eth_frame(m2, m1, b"back-online"));
        assert!(p2.recv_frame().is_some());
    }

    #[test]
    fn switch_writes_valid_pcapng_header_and_epb() {
        let dir = std::env::temp_dir().join(format!("unkernel-pcap-test-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("test.pcapng");
        let file = File::create(&path).unwrap();

        let sw = VirtualSwitch::new("switch0");
        sw.attach_pcap(file).unwrap();
        let (m1, ip1) = VirtualSwitch::allocate_identity(0);
        let (m2, ip2) = VirtualSwitch::allocate_identity(1);
        let p1 = sw.add_port("node1", m1, ip1, Arc::new(|| {}), None);
        let _p2 = sw.add_port("node2", m2, ip2, Arc::new(|| {}), None);

        p1.send_frame(&eth_frame([0xff; 6], m1, b"pcap-test-payload"));
        sw.flush_pcap();

        let raw = std::fs::read(&path).unwrap();
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir(&dir);

        // Verify SHB magic (0x0a0d0d0a), Byte-Order Magic (0x1a2b3c4d), and EPB type (0x00000006)
        assert!(raw.len() > 80);
        assert_eq!(&raw[0..4], &0x0a0d_0d0au32.to_le_bytes());
        assert_eq!(&raw[8..12], &0x1a2b_3c4du32.to_le_bytes());
        assert!(raw.windows(17).any(|w| w == b"pcap-test-payload"));
    }
}