use anyhow::{Context, Result};
use std::time::Duration;
use crate::timeouts;
pub const MON_SOCK_NAME: &str = "qemu-run-mon.sock";
pub const QMP_SOCK_NAME: &str = "qemu-run-qmp.sock";
pub const SERIAL_LOG_NAME: &str = "runserial.log";
pub type Stream = interprocess::local_socket::tokio::Stream;
pub async fn connect(path: &str) -> Result<Stream> {
use interprocess::local_socket::traits::tokio::Stream as _;
#[cfg(unix)]
{
use interprocess::local_socket::{GenericFilePath, ToFsName};
use std::path::Path;
let name = Path::new(path)
.to_fs_name::<GenericFilePath>()
.map_err(|e| anyhow::anyhow!("bad socket path {path:?}: {e}"))?;
Stream::connect(name)
.await
.with_context(|| format!("connect {path}"))
}
#[cfg(windows)]
{
use interprocess::local_socket::{GenericNamespaced, ToNsName};
let name = path
.to_ns_name::<GenericNamespaced>()
.map_err(|e| anyhow::anyhow!("bad pipe name {path:?}: {e}"))?;
Stream::connect(name)
.await
.with_context(|| format!("connect {path}"))
}
}
#[cfg(unix)]
pub fn runtime_dir() -> std::path::PathBuf {
if let Ok(xdg) = std::env::var("XDG_RUNTIME_DIR")
&& !xdg.is_empty()
{
return std::path::PathBuf::from(xdg);
}
if let Ok(tmp) = std::env::var("TMPDIR")
&& !tmp.is_empty()
{
return std::path::PathBuf::from(tmp).join("windows-headless");
}
let user = std::env::var("USER").unwrap_or_else(|_| "shared".into());
std::path::PathBuf::from("/tmp").join(format!("windows-headless-{user}"))
}
pub fn vm_endpoint(vm_dir: &std::path::Path, name: &str) -> String {
#[cfg(unix)]
{
let dir = runtime_dir().join(format!("wh-{}", vm_stem(vm_dir)));
let _ = std::fs::create_dir_all(&dir);
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
}
let full = dir.join(name);
assert!(
full.to_string_lossy().len() < 104,
"socket path too long for sun_path: {}",
full.display()
);
full.to_string_lossy().into_owned()
}
#[cfg(windows)]
{
format!("wh-{}-{}", vm_stem(vm_dir), base_name(name))
}
}
fn vm_stem(vm_dir: &std::path::Path) -> String {
let stem = vm_dir
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "vm".into());
let clean: String = stem
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
clean.chars().take(32).collect()
}
#[cfg(windows)]
fn base_name(name: &str) -> String {
name.trim_end_matches(".sock").replace('.', "-")
}
pub fn qemu_arg(path: &str) -> String {
#[cfg(unix)]
{
format!("unix:{path},server,nowait")
}
#[cfg(windows)]
{
format!(r"pipe:\\.\pipe\{path},server,nowait")
}
}
pub fn stale_remove(path: &str) {
#[cfg(unix)]
{
let _ = std::fs::remove_file(path);
}
#[cfg(windows)]
{
let _ = path;
}
}
pub async fn endpoint_alive(path: &str) -> bool {
connect(path).await.is_ok()
}
pub async fn qmp_alive(socket: &str) -> bool {
endpoint_alive(socket).await
}
pub struct Monitor {
sock: String,
stream: tokio::sync::Mutex<Stream>,
}
impl Monitor {
pub async fn connect(sock: &str) -> Result<Self> {
let mut stream = connect(sock).await?;
consume_greeting(&mut stream).await?;
Ok(Self {
sock: sock.to_string(),
stream: tokio::sync::Mutex::new(stream),
})
}
pub async fn connect_retry(
sock: &str,
timeout_secs: u64,
mut alive: impl FnMut() -> bool,
) -> Result<Self> {
let mut waited = 0u64;
loop {
match connect(sock).await {
Ok(mut stream) => {
if let Err(e) = consume_greeting(&mut stream).await {
if !alive() {
anyhow::bail!("QEMU died during startup: {e:#}");
}
waited += timeouts::MONITOR_RETRY_STEP_SECS;
if waited >= timeout_secs {
anyhow::bail!(
"monitor at {sock} never greeted after {timeout_secs}s on a live QEMU ({e:#})"
);
}
tracing::debug!("monitor not greeted yet ({e:#}); retrying ...");
tokio::time::sleep(Duration::from_secs(timeouts::MONITOR_RETRY_STEP_SECS))
.await;
continue;
}
return Ok(Self {
sock: sock.to_string(),
stream: tokio::sync::Mutex::new(stream),
});
}
Err(e) => {
if !alive() {
anyhow::bail!("QEMU died during startup; monitor never came up: {e:#}");
}
waited += timeouts::MONITOR_RETRY_STEP_SECS;
if waited >= timeout_secs {
anyhow::bail!(
"monitor at {sock} not accepting after {timeout_secs}s on a live QEMU ({e:#})"
);
}
tracing::debug!("monitor not accepting yet ({e:#}); retrying ...");
tokio::time::sleep(Duration::from_secs(timeouts::MONITOR_RETRY_STEP_SECS))
.await;
}
}
}
}
pub fn sock(&self) -> &str {
&self.sock
}
pub async fn command(&self, cmd: &str) -> Result<String> {
use tokio::io::AsyncWriteExt;
let mut stream = self.stream.lock().await;
let mut buf = vec![0u8; 4096];
let mut seen = Vec::new();
stream
.write_all(format!("{cmd}\n").as_bytes())
.await
.context("monitor write")?;
stream.flush().await?;
read_to_prompt(&mut stream, &mut buf, &mut seen).await?;
Ok(String::from_utf8_lossy(&seen).into_owned())
}
}
async fn consume_greeting(stream: &mut Stream) -> Result<()> {
let mut buf = vec![0u8; 4096];
let mut seen = Vec::new();
read_to_prompt(stream, &mut buf, &mut seen).await
}
async fn read_to_prompt(stream: &mut Stream, buf: &mut [u8], seen: &mut Vec<u8>) -> Result<()> {
use tokio::io::AsyncReadExt;
loop {
let n = stream.read(buf).await.context("monitor read")?;
if n == 0 {
anyhow::bail!("monitor closed before prompt");
}
seen.extend_from_slice(&buf[..n]);
if seen.windows(6).any(|w| w == b"(qemu)") {
return Ok(());
}
if seen.len() > 65536 {
anyhow::bail!("monitor greeting too long without prompt");
}
}
}