// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Tsiry Sandratraina use anyhow::{Context, Result, bail}; use clap::ValueEnum; use std::{ fs, io, io::{BufRead, Read, Write}, os::unix::net::UnixStream, os::unix::process::CommandExt, path::{Path, PathBuf}, process::{Child, Command, Stdio}, time::{Duration, Instant}, }; #[derive(Clone, Copy, Debug, ValueEnum, PartialEq, Eq)] pub enum Backend { Qemu, Gvproxy, None, } // The supervisor owns the backend and its files. Its stdin is a private // lifetime pipe: the OS closes it even if the runner aborts or gets SIGKILL. pub struct Network(Child); impl Drop for Network { fn drop(&mut self) { drop(self.0.stdin.take()); let _ = self.0.wait(); } } pub async fn connect( backend: Backend, external: Option<&Path>, ) -> Result<(Option, Option)> { if let Some(path) = external { return Ok(( None, Some(UnixStream::connect(path).with_context(|| format!("connect {}", path.display()))?), )); } if backend == Backend::None { return Ok((None, None)); } let child = Command::new(std::env::current_exe()?) .arg("network-helper") .arg(backend.to_possible_value().unwrap().get_name()) .process_group(0) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .context("start network supervisor")?; let mut network = Network(child); let mut line = String::new(); let pipe = network .0 .stdout .take() .context("missing supervisor output")?; let count = io::BufReader::new(pipe).read_line(&mut line)?; anyhow::ensure!(count != 0, "{backend:?} supervisor failed to start"); let path = PathBuf::from(line.trim_end()); let deadline = Instant::now() + Duration::from_secs(10); loop { if let Some(status) = network.0.try_wait()? { bail!("{backend:?} exited during network startup ({status})"); } match UnixStream::connect(&path) { Ok(stream) => return Ok((Some(network), Some(stream))), Err(e) if matches!( e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused ) && Instant::now() < deadline => { tokio::time::sleep(Duration::from_millis(25)).await } Err(e) => return Err(e).context("connect to network helper"), } } } pub fn supervise(backend: Backend) -> Result<()> { anyhow::ensure!(backend != Backend::None, "missing managed backend"); // A short path fits sockaddr_un even on hosts with long TMPDIR names. let dir = tempfile::Builder::new() .prefix("unkernel-net-") .tempdir_in("/tmp")?; let path = dir.path().join("ethernet.sock"); let mut cmd = match backend { Backend::Qemu => { let mut cmd = Command::new("qemu-system-aarch64"); cmd.args([ "-machine", "none", "-nodefaults", "-display", "none", "-monitor", "none", "-serial", "none", "-netdev", "user,id=outside", "-netdev", ]) .arg(format!( "stream,id=inside,server=on,addr.type=unix,addr.path={}", path.display() )) .args([ "-netdev", "hubport,id=wan,hubid=0,netdev=outside", "-netdev", "hubport,id=lan,hubid=0,netdev=inside", ]); cmd } Backend::Gvproxy => { // gvproxy serves DNS on its primary address. Answer ARP for the // project's default route too, so static guest images work as-is. let config = dir.path().join("gvproxy.yaml"); fs::write( &config, "log-level: warn\nstack:\n subnet: 10.0.2.0/24\n gatewayIP: 10.0.2.3\n gatewayVirtualIPs: [10.0.2.2]\n dhcpStaticLeases:\n 10.0.2.15: '5a:94:ef:e4:0c:ee'\n", )?; let mut cmd = Command::new("gvproxy"); cmd.arg("-config") .arg(config) .arg("-listen-qemu") .arg(format!("unix://{}", path.display())); cmd } Backend::None => unreachable!(), }; let mut child = cmd .stdin(Stdio::null()) .stdout(Stdio::null()) .spawn() .with_context(|| { format!( "start {} (required for --net {})", cmd.get_program().to_string_lossy(), backend.to_possible_value().unwrap().get_name() ) })?; // Reading the runner's pipe is independent of the backend's socket. // If the backend exits first, its status reaches the connecting runner. let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = io::stdin().read(&mut [0; 1]); let _ = tx.send(()); }); let result = (|| -> Result<()> { writeln!(io::stdout().lock(), "{}", path.display())?; loop { if let Some(status) = child.try_wait()? { anyhow::ensure!(status.success(), "{backend:?} exited ({status})"); break; } if rx.recv_timeout(Duration::from_millis(100)).is_ok() { break; } } Ok(()) })(); // The Child handle identifies just this session. The child remains // ours to reap, so its PID cannot be recycled before try_wait/wait. if child.try_wait()?.is_none() { use rustix::process::{Pid, Signal, kill_process}; if let Some(pid) = Pid::from_raw(child.id() as i32) { let _ = kill_process(pid, Signal::TERM); } let deadline = Instant::now() + Duration::from_secs(1); while child.try_wait()?.is_none() && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(20)); } if child.try_wait()?.is_none() { let _ = child.kill(); } child.wait()?; } result }