windows_headless/ipc.rs
1//! Cross-platform IPC to QEMU's monitor (HMP) and QMP endpoints.
2//!
3//! Unix: unix-domain sockets. Windows: named pipes (QEMU's `pipe:` chardev
4//! on the QEMU side, `interprocess` client on ours). One `Stream` type, one
5//! `connect`, per-platform QEMU argv — all protocol code above this is
6//! transport-agnostic.
7//!
8//! Single-client transports (Windows named pipes, and QEMU's single-slot
9//! unix listen backlog while its main loop is busy in hvf init) mean two
10//! rules, learned live: never probe-connect (a connect-and-drop occupies
11//! the only slot and refuses the real handshake with ECONNREFUSED), and
12//! never overlap sessions. [`Monitor`] enforces the second: one handle per
13//! VM run, shared by reference with every task of that run.
14//!
15//! NOTE (Windows): compiled, never run here — no Windows host in this lab.
16//! Pipe names and the `pipe:` argv form follow QEMU docs; expect iteration.
17
18use anyhow::{Context, Result};
19use std::time::Duration;
20
21use crate::timeouts;
22
23pub const MON_SOCK_NAME: &str = "qemu-run-mon.sock";
24pub const QMP_SOCK_NAME: &str = "qemu-run-qmp.sock";
25pub const SERIAL_LOG_NAME: &str = "runserial.log";
26
27/// Byte stream to a QEMU endpoint: Unix-domain socket on Unix, named
28/// pipe on Windows. One enum from `interprocess` — no platform branches
29/// at use sites.
30pub type Stream = interprocess::local_socket::tokio::Stream;
31
32/// Connect to the endpoint at `path`: socket path in the VM dir on Unix
33/// (filesystem-path name, used verbatim), pipe base name from
34/// [`vm_endpoint`] on Windows (namespaced name).
35pub async fn connect(path: &str) -> Result<Stream> {
36 use interprocess::local_socket::traits::tokio::Stream as _;
37 #[cfg(unix)]
38 {
39 use interprocess::local_socket::{GenericFilePath, ToFsName};
40 use std::path::Path;
41 let name = Path::new(path)
42 .to_fs_name::<GenericFilePath>()
43 .map_err(|e| anyhow::anyhow!("bad socket path {path:?}: {e}"))?;
44 Stream::connect(name)
45 .await
46 .with_context(|| format!("connect {path}"))
47 }
48 #[cfg(windows)]
49 {
50 use interprocess::local_socket::{GenericNamespaced, ToNsName};
51 let name = path
52 .to_ns_name::<GenericNamespaced>()
53 .map_err(|e| anyhow::anyhow!("bad pipe name {path:?}: {e}"))?;
54 Stream::connect(name)
55 .await
56 .with_context(|| format!("connect {path}"))
57 }
58}
59
60/// Runtime dir for sockets: `$XDG_RUNTIME_DIR` on Linux (RAM, 0700,
61/// cleared on reboot), `$TMPDIR` on macOS (per-user, private). Never the
62/// VM dir itself: `~/.cache` lives on persistent (sometimes network)
63/// storage, and `sun_path` caps socket paths at 104 bytes on macOS —
64/// deep checkouts breach it. Per-VM subdirs preserve isolation.
65#[cfg(unix)]
66pub fn runtime_dir() -> std::path::PathBuf {
67 if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR")
68 && !xdg.is_empty()
69 {
70 return std::path::PathBuf::from(xdg);
71 }
72 if let Ok(tmp) = std::env::var("TMPDIR")
73 && !tmp.is_empty()
74 {
75 return std::path::PathBuf::from(tmp).join("windows-headless");
76 }
77 // Last resort: per-user subdir of /tmp (0700 at creation, below).
78 // `$USER` spoofing buys an attacker nothing they don't already have.
79 let user = std::env::var("USER").unwrap_or_else(|_| "shared".into());
80 std::path::PathBuf::from("/tmp").join(format!("windows-headless-{user}"))
81}
82
83/// Transport address for `name` scoped to `vm_dir`. Unix: socket file in
84/// a per-VM subdir of [`runtime_dir`] (private, short, never NFS home —
85/// only the dir *stem* travels, so deep checkouts can't breach
86/// `sun_path`). Windows: bare pipe base name (flat `\\.\pipe\`
87/// namespace; [`qemu_arg`] adds the prefix for QEMU's `pipe:` chardev).
88pub fn vm_endpoint(vm_dir: &std::path::Path, name: &str) -> String {
89 #[cfg(unix)]
90 {
91 let dir = runtime_dir().join(format!("wh-{}", vm_stem(vm_dir)));
92 let _ = std::fs::create_dir_all(&dir);
93 // 0700 the fallback so a shared /tmp can't be squatted.
94 {
95 use std::os::unix::fs::PermissionsExt;
96 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
97 }
98 let full = dir.join(name);
99 // Fail loudly, not at bind(2): macOS caps sun_path at 104 bytes.
100 assert!(
101 full.to_string_lossy().len() < 104,
102 "socket path too long for sun_path: {}",
103 full.display()
104 );
105 full.to_string_lossy().into_owned()
106 }
107 #[cfg(windows)]
108 {
109 format!("wh-{}-{}", vm_stem(vm_dir), base_name(name))
110 }
111}
112
113/// Sanitized VM dir stem: alphanumeric + `-`, truncated so full socket
114/// paths stay far under `sun_path` limits.
115fn vm_stem(vm_dir: &std::path::Path) -> String {
116 let stem = vm_dir
117 .file_name()
118 .map(|s| s.to_string_lossy().into_owned())
119 .unwrap_or_else(|| "vm".into());
120 let clean: String = stem
121 .chars()
122 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
123 .collect();
124 clean.chars().take(32).collect()
125}
126
127/// `qemu-run-mon.sock` → `qemu-run-mon` (pipe names have no extensions).
128#[cfg(windows)]
129fn base_name(name: &str) -> String {
130 name.trim_end_matches(".sock").replace('.', "-")
131}
132
133/// QEMU `-monitor`/`-qmp` arg for `path`: `unix:` vs `pipe:`.
134pub fn qemu_arg(path: &str) -> String {
135 #[cfg(unix)]
136 {
137 format!("unix:{path},server,nowait")
138 }
139 #[cfg(windows)]
140 {
141 format!(r"pipe:\\.\pipe\{path},server,nowait")
142 }
143}
144
145/// Remove a stale endpoint. Named pipes aren't fs entries: no-op there.
146pub fn stale_remove(path: &str) {
147 #[cfg(unix)]
148 {
149 let _ = std::fs::remove_file(path);
150 }
151 #[cfg(windows)]
152 {
153 let _ = path;
154 }
155}
156
157/// True when something accepts on the endpoint (i.e. our QEMU is alive).
158/// Advisory only: connect-and-drop, so never call it while a [`Monitor`]
159/// or QMP session to the same endpoint is open on single-client transports
160/// (it would steal the slot / report down). All our flows drop sessions
161/// before probing — see `cmd_stop`.
162pub async fn endpoint_alive(path: &str) -> bool {
163 connect(path).await.is_ok()
164}
165
166/// Backwards-compatible name used across the codebase.
167pub async fn qmp_alive(socket: &str) -> bool {
168 endpoint_alive(socket).await
169}
170
171/// One HMP session per VM run. Holds the single connection behind a mutex
172/// so the VNC handshake, screenshot task, and idle poll of the same run
173/// serialize instead of overlapping (fatal on single-client transports).
174/// Create after spawn, share by reference (`&Monitor`) with every task.
175pub struct Monitor {
176 sock: String,
177 stream: tokio::sync::Mutex<Stream>,
178}
179
180impl Monitor {
181 /// Connect once. Consumes the initial `(qemu)` greeting so [`Monitor::command`]
182 /// can write-then-read on every call. For spawn races (slow hvf init)
183 /// use [`Monitor::connect_retry`] instead.
184 pub async fn connect(sock: &str) -> Result<Self> {
185 let mut stream = connect(sock).await?;
186 consume_greeting(&mut stream).await?;
187 Ok(Self {
188 sock: sock.to_string(),
189 stream: tokio::sync::Mutex::new(stream),
190 })
191 }
192
193 /// Keep connecting while `alive()` says the child lives, up to
194 /// `timeout_secs`. Never fails fast on a live-but-slow QEMU — the old
195 /// fixed-sleep spawn check murdered slow starters via `kill_on_drop`.
196 pub async fn connect_retry(
197 sock: &str,
198 timeout_secs: u64,
199 mut alive: impl FnMut() -> bool,
200 ) -> Result<Self> {
201 let mut waited = 0u64;
202 loop {
203 match connect(sock).await {
204 Ok(mut stream) => {
205 // Greeting consumed here, once: every later command()
206 // is write-then-read on the same connection. (The first
207 // version re-read a greeting per command and hung
208 // forever waiting for bytes QEMU only sends after input.)
209 if let Err(e) = consume_greeting(&mut stream).await {
210 if !alive() {
211 anyhow::bail!("QEMU died during startup: {e:#}");
212 }
213 waited += timeouts::MONITOR_RETRY_STEP_SECS;
214 if waited >= timeout_secs {
215 anyhow::bail!(
216 "monitor at {sock} never greeted after {timeout_secs}s on a live QEMU ({e:#})"
217 );
218 }
219 // Retries are routine on slow starters (hvf/TCG):
220 // debug-only so the normal log shows one wait line.
221 tracing::debug!("monitor not greeted yet ({e:#}); retrying ...");
222 tokio::time::sleep(Duration::from_secs(timeouts::MONITOR_RETRY_STEP_SECS))
223 .await;
224 continue;
225 }
226 return Ok(Self {
227 sock: sock.to_string(),
228 stream: tokio::sync::Mutex::new(stream),
229 });
230 }
231 Err(e) => {
232 if !alive() {
233 anyhow::bail!("QEMU died during startup; monitor never came up: {e:#}");
234 }
235 waited += timeouts::MONITOR_RETRY_STEP_SECS;
236 if waited >= timeout_secs {
237 anyhow::bail!(
238 "monitor at {sock} not accepting after {timeout_secs}s on a live QEMU ({e:#})"
239 );
240 }
241 // Same as above: routine while QEMU starts, debug-only.
242 tracing::debug!("monitor not accepting yet ({e:#}); retrying ...");
243 tokio::time::sleep(Duration::from_secs(timeouts::MONITOR_RETRY_STEP_SECS))
244 .await;
245 }
246 }
247 }
248 }
249
250 /// Endpoint path (for messages).
251 pub fn sock(&self) -> &str {
252 &self.sock
253 }
254
255 /// Run one HMP command; returns everything printed after it. The
256 /// connection persists across commands, so this is write-then-read:
257 /// the greeting was consumed at connect time. Reads raw bytes until
258 /// the `(qemu)` marker: the prompt has no trailing newline, so
259 /// line-based reads deadlock here (observed live).
260 pub async fn command(&self, cmd: &str) -> Result<String> {
261 use tokio::io::AsyncWriteExt;
262 let mut stream = self.stream.lock().await;
263 let mut buf = vec![0u8; 4096];
264 let mut seen = Vec::new();
265 stream
266 .write_all(format!("{cmd}\n").as_bytes())
267 .await
268 .context("monitor write")?;
269 stream.flush().await?;
270 read_to_prompt(&mut stream, &mut buf, &mut seen).await?;
271 Ok(String::from_utf8_lossy(&seen).into_owned())
272 }
273}
274
275/// Read and discard bytes until the first `(qemu)` marker: the server
276/// greeting, consumed once per connection.
277async fn consume_greeting(stream: &mut Stream) -> Result<()> {
278 let mut buf = vec![0u8; 4096];
279 let mut seen = Vec::new();
280 read_to_prompt(stream, &mut buf, &mut seen).await
281}
282
283async fn read_to_prompt(stream: &mut Stream, buf: &mut [u8], seen: &mut Vec<u8>) -> Result<()> {
284 use tokio::io::AsyncReadExt;
285 loop {
286 let n = stream.read(buf).await.context("monitor read")?;
287 if n == 0 {
288 anyhow::bail!("monitor closed before prompt");
289 }
290 seen.extend_from_slice(&buf[..n]);
291 if seen.windows(6).any(|w| w == b"(qemu)") {
292 return Ok(());
293 }
294 if seen.len() > 65536 {
295 anyhow::bail!("monitor greeting too long without prompt");
296 }
297 }
298}