Skip to main content

smolvm_network/
lib.rs

1//! Host-side virtio-net runtime.
2//!
3//! Context
4//! =======
5//!
6//! This module is the host-side half of the new networking path:
7//!
8//! ```text
9//! guest app
10//!   -> guest kernel TCP/IP stack
11//!   -> virtio-net device
12//!   -> libkrun unix-stream bridge
13//!   -> smolvm FrameStreamBridge
14//!   -> shared frame queues
15//!   -> smoltcp gateway/runtime
16//!   -> host sockets / DNS forwarding / TCP relay
17//!   -> external network
18//! ```
19//!
20//! Main runtime components:
21//!
22//! ```text
23//! VirtioNetworkRuntime
24//! ├─ FrameStreamBridge
25//! │  ├─ reader thread
26//! │  └─ writer thread
27//! ├─ TcpPortListeners
28//! │  └─ one non-blocking accept loop per `-p HOST:GUEST`
29//! ├─ Arc<NetworkFrameQueues>
30//! │  ├─ guest_to_host
31//! │  ├─ host_to_guest
32//! │  ├─ guest_wake
33//! │  ├─ host_wake
34//! │  └─ relay_wake
35//! └─ smolvm-net-poll thread
36//!    ├─ VirtioNetworkDevice
37//!    ├─ smoltcp Interface
38//!    ├─ SocketSet
39//!    └─ TcpRelayTable
40//! ```
41//!
42//! Component roles:
43//! - `FrameStreamBridge`: translates libkrun's Unix-stream frame protocol into
44//!   queue operations
45//! - `TcpPortListeners`: accepts host TCP connections for published ports
46//!   and hands them to the poll loop
47//! - `NetworkFrameQueues`: handoff boundary between threads
48//! - `VirtioNetworkDevice`: adapts those queues to smoltcp's `phy::Device`
49//! - poll thread: acts as the guest-visible gateway and protocol dispatcher
50//! - `TcpRelayTable`: maps guest TCP flows onto host-side relay threads
51//!
52//! This runtime is responsible for:
53//! - exchanging raw Ethernet frames with libkrun
54//! - presenting a gateway endpoint to the guest
55//! - handling DNS through a gateway UDP socket and host UDP forwarding
56//! - relaying guest TCP connections to host `TcpStream`s
57//! - accepting published host TCP ports and forwarding them into guest TCP
58//!   connections
59
60pub mod device;
61pub mod dns;
62pub mod egress;
63// The libkrun frame bridge speaks over an AF_UNIX stream socket, available on
64// both Unix and Windows (10 1809+), so the whole stack is cross-platform.
65pub mod frame_stream;
66pub mod icmp_relay;
67pub mod queues;
68pub mod stack;
69pub mod tcp_listeners;
70pub mod tcp_relay;
71pub mod udp_relay;
72
73pub use egress::EgressPolicy;
74
75use socket2::Socket;
76use std::fmt;
77use std::io;
78use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
79use std::thread::JoinHandle;
80use std::time::SystemTime;
81
82use frame_stream::{start_frame_stream_bridge, FrameStreamBridge};
83use queues::NetworkFrameQueues;
84use queues::DEFAULT_FRAME_QUEUE_CAPACITY;
85use stack::{start_network_stack, VirtioPollConfig};
86use tcp_listeners::create_tcp_channel;
87use tcp_listeners::TcpPortListeners;
88
89/// Default upstream DNS resolver used by the gateway runtime.
90pub const DEFAULT_DNS_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1));
91
92/// Host->guest published TCP port mapping serviced by the virtio gateway.
93///
94/// This stays crate-local so the launchers can translate CLI/data-layer port
95/// mappings into the gateway runtime without pulling the gateway logic back
96/// into the main `smolvm` crate.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct PortMapping {
99    /// Port bound on the host loopback interface.
100    pub host: u16,
101    /// Port exposed inside the guest.
102    pub guest: u16,
103}
104
105impl PortMapping {
106    /// Create a new published port mapping.
107    pub const fn new(host: u16, guest: u16) -> Self {
108        Self { host, guest }
109    }
110}
111
112/// Static guest network configuration for the virtio-net MVP.
113///
114/// This struct describes the two endpoints of the single virtual Ethernet link:
115/// - the guest NIC (`guest_*`)
116/// - the host-side gateway implemented by smolvm (`gateway_*`)
117///
118/// The link is dual-stack: a /30 IPv4 point-to-point pair and a /64 ULA IPv6
119/// pair (`fd53:4d00::/64` — `53:4d` = "SM", matching the MAC OUI scheme).
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct GuestNetworkConfig {
122    /// Guest IPv4 address.
123    pub guest_ip: Ipv4Addr,
124    /// Gateway IPv4 address.
125    pub gateway_ip: Ipv4Addr,
126    /// Prefix length.
127    pub prefix_len: u8,
128    /// Guest IPv6 (ULA) address.
129    pub guest_ip6: Ipv6Addr,
130    /// Gateway IPv6 (ULA) address.
131    pub gateway_ip6: Ipv6Addr,
132    /// IPv6 prefix length.
133    pub prefix_len6: u8,
134    /// Guest MAC address.
135    pub guest_mac: [u8; 6],
136    /// Gateway MAC address.
137    pub gateway_mac: [u8; 6],
138    /// DNS server address presented to the guest.
139    ///
140    /// For virtio-net this is the gateway's own address (`gateway_ip`): the
141    /// guest sends DNS to the gateway, which forwards upstream to
142    /// [`Self::upstream_dns`].
143    pub dns_server: Ipv4Addr,
144    /// Upstream resolver the gateway forwards guest DNS queries to.
145    ///
146    /// Defaults to [`DEFAULT_DNS_ADDR`]; the launcher overrides it when the
147    /// caller passes `--dns <ip>` so a VM on a network that blocks the default
148    /// resolver can still resolve names.
149    pub upstream_dns: Ipv4Addr,
150}
151
152impl GuestNetworkConfig {
153    /// Default Phase 1 guest network configuration.
154    pub const fn default() -> Self {
155        Self {
156            guest_ip: Ipv4Addr::new(100, 96, 0, 2),
157            gateway_ip: Ipv4Addr::new(100, 96, 0, 1),
158            prefix_len: 30,
159            guest_ip6: Ipv6Addr::new(0xfd53, 0x4d00, 0, 0, 0, 0, 0, 2),
160            gateway_ip6: Ipv6Addr::new(0xfd53, 0x4d00, 0, 0, 0, 0, 0, 1),
161            prefix_len6: 64,
162            guest_mac: [0x02, 0x53, 0x4d, 0x00, 0x00, 0x02],
163            gateway_mac: [0x02, 0x53, 0x4d, 0x00, 0x00, 0x01],
164            dns_server: Ipv4Addr::new(100, 96, 0, 1),
165            upstream_dns: match DEFAULT_DNS_ADDR {
166                IpAddr::V4(ip) => ip,
167                IpAddr::V6(_) => Ipv4Addr::new(1, 1, 1, 1),
168            },
169        }
170    }
171}
172
173fn format_network_log_line(timestamp: SystemTime, message: &str) -> String {
174    format!(
175        "[{}]: {}",
176        humantime::format_rfc3339_seconds(timestamp),
177        message
178    )
179}
180
181pub(crate) fn emit_network_log_line(message: fmt::Arguments<'_>) {
182    eprintln!(
183        "{}",
184        format_network_log_line(SystemTime::now(), &message.to_string())
185    );
186}
187
188macro_rules! virtio_net_log {
189    ($($arg:tt)*) => {
190        $crate::emit_network_log_line(format_args!($($arg)*))
191    };
192}
193
194pub(crate) use virtio_net_log;
195
196/// Running host-side virtio-net runtime for one guest NIC.
197///
198/// Ownership model:
199/// - one runtime instance corresponds to one guest virtio NIC
200/// - it owns the queue set shared by the worker threads
201/// - it owns the libkrun Unix-stream bridge threads
202/// - it owns the published-port listener threads
203/// - it owns the smoltcp poll thread
204///
205/// Dropping the runtime is the shutdown signal. `Drop` marks the shared queues
206/// as shutting down, wakes blocked workers, and joins the poll thread.
207pub struct VirtioNetworkRuntime {
208    queues: std::sync::Arc<NetworkFrameQueues>,
209    _frame_bridge: FrameStreamBridge,
210    published_ports: Option<TcpPortListeners>,
211    poll_handle: Option<JoinHandle<()>>,
212}
213
214/// Start the host-side virtio-net runtime for one guest NIC.
215///
216/// Inputs:
217/// - `host_fd`: the host-side Unix stream fd that libkrun will use for this
218///   guest NIC. The launcher eventually gets this from the libkrun
219///   `krun_add_net_unixstream()` setup path.
220/// - `guest_network`: the static guest/gateway addressing and MAC plan for this
221///   NIC.
222/// - `published_ports`: host->guest TCP port mappings that should be serviced
223///   directly by the virtio runtime instead of TSI.
224///
225/// High-level flow:
226///
227/// ```text
228/// start_virtio_network()
229///   -> create shared frame queues + wake pipes
230///   -> start frame reader/writer threads on the Unix stream
231///   -> start host TcpListeners for published ports
232///   -> start the smoltcp poll thread
233///   -> return a handle that owns the whole runtime
234/// ```
235///
236/// Expanded startup picture:
237///
238/// ```text
239/// host_fd from libkrun
240///   -> FrameStreamBridge(host_fd)
241///      -> reader thread
242///      -> writer thread
243///   -> TcpPortListeners
244///      -> accept host TcpStreams
245///      -> send them to the poll loop over a bounded channel
246///   -> NetworkFrameQueues
247///   -> start_network_stack(...)
248///      -> poll thread owns smoltcp Interface + sockets
249///   -> VirtioNetworkRuntime returned to launcher
250/// ```
251///
252/// Outcome:
253/// - guest->host Ethernet frames start flowing into the queues
254/// - host->guest Ethernet frames emitted by smoltcp are written back to libkrun
255/// - published host TCP connections can be forwarded toward guest listeners
256/// - the poll loop starts acting as the guest-visible gateway
257///
258/// Cross-platform: the libkrun frame bridge speaks over an AF_UNIX stream
259/// socket, available on Unix and Windows (10 1809+). The caller supplies the
260/// already-connected host-side socket (Unix: one end of a `socketpair`;
261/// Windows: the socket `accept`ed from libkrun on the per-VM path).
262pub fn start_virtio_network(
263    host_stream: Socket,
264    guest_network: GuestNetworkConfig,
265    published_ports: &[PortMapping],
266    egress: EgressPolicy,
267) -> io::Result<VirtioNetworkRuntime> {
268    virtio_net_log!(
269        "virtio-net: starting runtime guest_ip={} gateway_ip={} dns_server={}",
270        guest_network.guest_ip,
271        guest_network.gateway_ip,
272        guest_network.dns_server
273    );
274    let queues = NetworkFrameQueues::shared(DEFAULT_FRAME_QUEUE_CAPACITY);
275    let frame_bridge = start_frame_stream_bridge(host_stream, queues.clone())?;
276    // tcp_sender sends the accepted TCP connections to the channel
277    // tcp_receiver receives the accepted TCP connections via the channel, and let it be consumed in poll thread.
278    let (tcp_sender, tcp_receiver) = create_tcp_channel();
279    let tcp_listeners = if published_ports.is_empty() {
280        None
281    } else {
282        Some(TcpPortListeners::start(
283            published_ports,
284            tcp_sender,
285            queues.relay_wake.clone(),
286        )?)
287    };
288    let poll_handle = start_network_stack(
289        queues.clone(),
290        VirtioPollConfig {
291            gateway_mac: guest_network.gateway_mac,
292            guest_mac: guest_network.guest_mac,
293            gateway_ipv4: guest_network.gateway_ip,
294            guest_ipv4: guest_network.guest_ip,
295            gateway_ipv6: guest_network.gateway_ip6,
296            guest_ipv6: guest_network.guest_ip6,
297            prefix_len6: guest_network.prefix_len6,
298            upstream_dns: guest_network.upstream_dns,
299            mtu: 1500,
300        },
301        tcp_listeners.as_ref().map(|_| tcp_receiver),
302        egress,
303    )?;
304
305    Ok(VirtioNetworkRuntime {
306        queues,
307        _frame_bridge: frame_bridge,
308        published_ports: tcp_listeners,
309        poll_handle: Some(poll_handle),
310    })
311}
312
313impl VirtioNetworkRuntime {
314    /// Cumulative guest-outbound (egress) bytes on this NIC since boot, at the
315    /// ethernet-frame level. The launcher polls this to surface per-machine
316    /// egress to the node API for billing. TSI VMs have no virtio runtime, so
317    /// egress is unavailable for them (a documented metering gap).
318    pub fn egress_bytes(&self) -> u64 {
319        self.queues.egress_bytes()
320    }
321
322    /// A cheap, cloneable read handle to this NIC's egress counter, so the
323    /// launcher can spawn a thread that periodically flushes the value to the
324    /// VM's runtime dir for the node API to read (the runtime is not `Clone`).
325    pub fn egress_counter(&self) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
326        self.queues.egress_counter()
327    }
328
329    /// Take ownership of the runtime and block until the libkrun stream closes
330    /// (the frame reader marks the queues shutting down on EOF), then drop it for
331    /// a graceful shutdown. Used on Windows, where the runtime is built on the
332    /// `accept` thread: that thread parks here so the runtime — and its worker
333    /// threads — live for the whole VM lifetime instead of being dropped at the
334    /// end of the `accept` callback.
335    pub fn block_until_shutdown(self) {
336        while !self.queues.is_shutting_down() {
337            std::thread::sleep(std::time::Duration::from_millis(200));
338        }
339        // `self` drops here, joining the worker threads.
340    }
341}
342
343impl Drop for VirtioNetworkRuntime {
344    /// Shut down the worker threads in a bounded, cooperative way.
345    ///
346    /// The queue shutdown flag wakes the frame bridge and smoltcp poll loop so
347    /// they can exit on their own. We only explicitly join the poll thread
348    /// here because the frame bridge joins its own threads in its own `Drop`.
349    fn drop(&mut self) {
350        self.queues.begin_shutdown();
351        self.published_ports = None;
352        if let Some(handle) = self.poll_handle.take() {
353            let _ = handle.join();
354        }
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::format_network_log_line;
361    use std::time::UNIX_EPOCH;
362
363    #[test]
364    fn formats_timestamped_network_log_prefix() {
365        let line = format_network_log_line(UNIX_EPOCH, "virtio-net: smoke test");
366        assert_eq!(line, "[1970-01-01T00:00:00Z]: virtio-net: smoke test");
367    }
368}