use anyhow::{Context, Result};
use std::path::Path;
pub const VIRTIO_RELEASE_REPO: &str = crate::pins::RELEASE_REPO;
pub const VIRTIO_RELEASE_TAG: &str = crate::pins::DRIVERS_RELEASE_TAG;
pub const VIRTIO_RELEASE_ASSET: &str = crate::paths::VIRTIO_ISO;
pub fn openssh_zip_url(arch: crate::unattend::Architecture) -> String {
format!(
"https://github.com/PowerShell/Win32-OpenSSH/releases/download/{}/{}",
crate::pins::OPENSSH_RELEASE_TAG,
arch.openssh_zip_name()
)
}
const UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
pub async fn download(url: &str, dest: &Path) -> Result<String> {
let client = reqwest::Client::builder()
.user_agent(UA)
.build()
.context("reqwest client")?;
let mut resp = client.get(url).send().await?.error_for_status()?;
let label = dest
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| dest.display().to_string());
let mut progress = Progress::new(&label, resp.content_length());
let mut file = tokio::fs::File::create(dest)
.await
.with_context(|| format!("create {}", dest.display()))?;
use sha2::Digest;
use tokio::io::AsyncWriteExt;
let mut hasher = sha2::Sha256::new();
while let Some(chunk) = resp.chunk().await? {
hasher.update(&chunk);
progress.add(chunk.len());
file.write_all(&chunk).await?;
}
file.flush().await?;
progress.finish();
Ok(hex::encode(hasher.finalize()))
}
pub struct Progress {
label: String,
total: Option<u64>,
downloaded: u64,
start: std::time::Instant,
last_print: std::time::Instant,
}
impl Progress {
pub fn new(label: &str, total: Option<u64>) -> Self {
let now = std::time::Instant::now();
Self {
label: label.to_string(),
total,
downloaded: 0,
start: now,
last_print: now,
}
}
pub fn add(&mut self, n: usize) {
self.downloaded += n as u64;
let now = std::time::Instant::now();
if now.duration_since(self.last_print).as_secs() >= 1 {
self.last_print = now;
eprintln!(
"{}",
format_progress(
&self.label,
self.downloaded,
self.total,
now.duration_since(self.start).as_secs_f64(),
)
);
}
}
pub fn finish(&self) {
eprintln!(
"{}",
format_progress(
&self.label,
self.downloaded,
self.total,
std::time::Instant::now()
.duration_since(self.start)
.as_secs_f64(),
)
);
}
}
fn format_progress(label: &str, downloaded: u64, total: Option<u64>, elapsed_secs: f64) -> String {
let speed = downloaded as f64 / elapsed_secs.max(0.001);
match total {
Some(t) if t > 0 => format!(
"{}: {}/{} ({:.0}%, {}/s)",
label,
fmt_size(downloaded),
fmt_size(t),
downloaded as f64 / t as f64 * 100.0,
fmt_size(speed as u64),
),
_ => format!(
"{}: {} ({}/s)",
label,
fmt_size(downloaded),
fmt_size(speed as u64),
),
}
}
fn fmt_size(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let b = bytes as f64;
if b >= GB {
format!("{:.1} GB", b / GB)
} else if b >= MB {
format!("{:.1} MB", b / MB)
} else if b >= KB {
format!("{:.1} KB", b / KB)
} else {
format!("{bytes} B")
}
}
pub fn iso_cache_dir() -> Result<std::path::PathBuf> {
let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_ISO_DIR")?;
root.ensure_group("iso").context("create ISO cache group")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DownloadStatus {
Cached { path: std::path::PathBuf },
Downloaded {
path: std::path::PathBuf,
sha256: String,
},
}
pub async fn download_if_missing(
url: &str,
dest: &Path,
expected_sha256: Option<&str>,
force: bool,
) -> Result<DownloadStatus> {
if !force
&& let Ok(meta) = std::fs::metadata(dest)
&& meta.len() > 0
{
match expected_sha256 {
Some(expected) => {
let actual = sha256_of(dest).await?;
if actual.eq_ignore_ascii_case(expected) {
tracing::info!("using cached {}", dest.display());
return Ok(DownloadStatus::Cached {
path: dest.to_path_buf(),
});
}
tracing::warn!(
"hash mismatch for {} (expected {expected}, got {actual}); re-downloading",
dest.display()
);
}
None => {
tracing::info!("using cached {}", dest.display());
return Ok(DownloadStatus::Cached {
path: dest.to_path_buf(),
});
}
}
}
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent)
.await
.with_context(|| format!("mkdir {}", parent.display()))?;
}
let tmp = dest.with_extension("part");
let sha256 = match download(url, &tmp).await {
Ok(s) => s,
Err(e) => {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(e);
}
};
if let Some(expected) = expected_sha256
&& !sha256.eq_ignore_ascii_case(expected)
{
let _ = tokio::fs::remove_file(&tmp).await;
anyhow::bail!(
"SHA-256 mismatch for {}: expected {expected}, got {sha256}",
dest.display()
);
}
tokio::fs::rename(&tmp, dest)
.await
.with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
Ok(DownloadStatus::Downloaded {
path: dest.to_path_buf(),
sha256,
})
}
pub async fn sha256_of(path: &Path) -> Result<String> {
use sha2::Digest;
use tokio::io::AsyncReadExt;
let mut file = tokio::fs::File::open(path)
.await
.with_context(|| format!("open {}", path.display()))?;
let mut hasher = sha2::Sha256::new();
let mut buf = vec![0u8; 1024 * 1024];
loop {
let n = file.read(&mut buf).await?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hex::encode(hasher.finalize()))
}
pub async fn fetch_text(url: &str) -> Result<String> {
let client = reqwest::Client::builder()
.user_agent(UA)
.build()
.context("reqwest client")?;
let body = client
.get(url)
.send()
.await?
.error_for_status()
.with_context(|| format!("GET {url}"))?
.text()
.await?;
Ok(body)
}
pub async fn virtio_release_info() -> Result<(String, String)> {
let url = crate::qemu_portable::release_asset_url(
VIRTIO_RELEASE_REPO,
VIRTIO_RELEASE_TAG,
VIRTIO_RELEASE_ASSET,
)
.await?;
let sha_url = crate::qemu_portable::release_asset_url(
VIRTIO_RELEASE_REPO,
VIRTIO_RELEASE_TAG,
crate::paths::VIRTIO_ISO_SHA256,
)
.await?;
let body = fetch_text(&sha_url).await?;
let sha = body
.split_whitespace()
.next()
.with_context(|| format!("empty {}", crate::paths::VIRTIO_ISO_SHA256))?
.to_string();
if !sha.eq_ignore_ascii_case(crate::pins::VIRTIO_WIN_SHA256) {
anyhow::bail!(
"virtio-win.iso sidecar hash {sha} does not match the pinned hash {} \
(tampered drivers release or stale pin after a drivers-tag bump)",
crate::pins::VIRTIO_WIN_SHA256
);
}
Ok((url, sha))
}
pub fn validate_iso_image(path: &Path) -> Result<()> {
use std::io::{Read, Seek, SeekFrom};
fn printable_head(path: &Path, len: usize) -> String {
std::fs::read(path)
.map(|b| {
b.into_iter()
.take(len)
.map(|c| {
if c.is_ascii_graphic() || c == b' ' {
c as char
} else {
'·'
}
})
.collect()
})
.unwrap_or_default()
}
let mut file = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
let len = file.metadata().map(|m| m.len()).unwrap_or(0);
if len < 32774 {
anyhow::bail!(
"{} is too small ({} bytes) to be an ISO image — starts with: {}; \
likely a bot-check/error page saved as .iso — delete it and re-download",
path.display(),
len,
printable_head(path, 120)
);
}
let mut magic = [0u8; 5];
file.seek(SeekFrom::Start(32769))
.context("seek ISO magic")?;
file.read_exact(&mut magic).context("read ISO magic")?;
if &magic != b"CD001" {
anyhow::bail!(
"{} is not an ISO image ({} bytes, starts with: {}); \
likely a bot-check/error page saved as .iso — delete it and re-download",
path.display(),
len,
printable_head(path, 120)
);
}
Ok(())
}
pub fn resolve_win_iso_url(cli_url: Option<String>) -> Result<String> {
if let Some(u) = cli_url {
return Ok(u);
}
std::env::var("WIN11_ISO_URL").map_err(|_| {
anyhow::anyhow!(
"no Windows ISO URL: pass --win-iso-url <url> or set WIN11_ISO_URL.\n\
Get a fresh link in your browser (Microsoft -> Windows 11 -> download; links are time-limited).\n\
See README for Fido/Mido.sh alternatives."
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn skips_existing_file_without_hash() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("virtio-win.iso");
std::fs::write(&dest, b"fake-iso-bytes").unwrap();
let status = download_if_missing("https://example.invalid/x.iso", &dest, None, false)
.await
.unwrap();
assert_eq!(status, DownloadStatus::Cached { path: dest });
}
#[tokio::test]
async fn skips_existing_file_with_matching_hash() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("v.iso");
std::fs::write(&dest, b"abc").unwrap();
let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
let status = download_if_missing(
"https://example.invalid/x.iso",
&dest,
Some(expected),
false,
)
.await
.unwrap();
assert_eq!(status, DownloadStatus::Cached { path: dest.clone() });
assert_eq!(sha256_of(&dest).await.unwrap(), expected);
}
async fn serve_once(body: &'static [u8]) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
if let Ok((mut sock, _)) = listener.accept().await {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = sock.write_all(head.as_bytes()).await;
let _ = sock.write_all(body).await;
}
});
format!("http://{addr}/payload.bin")
}
#[tokio::test]
async fn fresh_download_verifies_hash_and_cleans_tmp_on_mismatch() {
let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("fresh.bin");
let url = serve_once(b"abc").await;
let status = download_if_missing(&url, &dest, Some(expected), false)
.await
.unwrap();
match status {
DownloadStatus::Downloaded { path, sha256 } => {
assert_eq!(path, dest);
assert_eq!(sha256, expected);
}
other => panic!("expected Downloaded, got {other:?}"),
}
assert_eq!(std::fs::read(&dest).unwrap(), b"abc");
let dir2 = tempfile::tempdir().unwrap();
let dest2 = dir2.path().join("bad.bin");
let url2 = serve_once(b"abc").await;
let err = download_if_missing(&url2, &dest2, Some(&"0".repeat(64)), false)
.await
.unwrap_err();
assert!(
format!("{err:#}").contains("SHA-256 mismatch"),
"unexpected error: {err:#}"
);
assert!(!dest2.exists());
assert!(!dest2.with_extension("part").exists());
}
#[tokio::test]
async fn force_bypasses_valid_cache() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("v.iso");
std::fs::write(&dest, b"abc").unwrap();
let err = download_if_missing("https://example.invalid/x.iso", &dest, None, true)
.await
.unwrap_err();
assert!(
format!("{err:#}").contains("example.invalid"),
"unexpected error: {err:#}"
);
assert_eq!(std::fs::read(&dest).unwrap(), b"abc");
}
#[test]
fn cache_dir_override_and_no_eviction() {
let tmp = tempfile::tempdir().unwrap();
let override_root = tmp.path().join("custom-root");
unsafe { std::env::set_var("WINDOWS_HEADLESS_ISO_DIR", &override_root) };
let dir = iso_cache_dir().unwrap();
assert_eq!(dir, override_root.join("iso"));
assert!(dir.is_dir());
std::fs::write(dir.join("virtio-win.iso"), b"fake-iso-bytes").unwrap();
let dir2 = iso_cache_dir().unwrap();
assert_eq!(dir2, dir);
assert_eq!(
std::fs::read(dir2.join("virtio-win.iso")).unwrap(),
b"fake-iso-bytes"
);
unsafe {
std::env::remove_var("WINDOWS_HEADLESS_ISO_DIR");
}
}
#[test]
fn win_iso_url_resolution_prefers_flag_then_env() {
unsafe {
std::env::remove_var("WIN11_ISO_URL");
}
assert!(resolve_win_iso_url(None).is_err());
unsafe {
std::env::set_var("WIN11_ISO_URL", "https://example.invalid/env.iso");
}
assert_eq!(
resolve_win_iso_url(None).unwrap(),
"https://example.invalid/env.iso"
);
assert_eq!(
resolve_win_iso_url(Some("https://example.invalid/flag.iso".into())).unwrap(),
"https://example.invalid/flag.iso"
);
unsafe {
std::env::remove_var("WIN11_ISO_URL");
}
}
#[test]
fn discovery_resolves_project_dot_cache() {
let root = cache_manager::CacheRoot::from_discovery().unwrap();
assert!(
root.path().ends_with(".cache"),
"got {}",
root.path().display()
);
}
#[test]
fn progress_renders_with_and_without_total() {
let line = format_progress("qemu.tar.gz", 13_107_200, Some(36_392_960), 1.5);
assert_eq!(line, "qemu.tar.gz: 12.5 MB/34.7 MB (36%, 8.3 MB/s)");
let line = format_progress("x.iso", 1_048_576, None, 0.0);
assert_eq!(line, "x.iso: 1.0 MB (1000.0 MB/s)");
let line = format_progress("x.iso", 1_048_576, Some(0), 2.0);
assert_eq!(line, "x.iso: 1.0 MB (512.0 KB/s)");
assert_eq!(fmt_size(512), "512 B");
assert_eq!(fmt_size(2048), "2.0 KB");
assert_eq!(fmt_size(8_589_934_592), "8.0 GB");
}
#[test]
fn iso_magic_rejects_html_stubs() {
let dir = tempfile::tempdir().unwrap();
let stub = dir.path().join("bogus.iso");
std::fs::write(&stub, b"<!doctype html>bot check").unwrap();
assert!(validate_iso_image(&stub).is_err());
let mut good = vec![0u8; 32774];
good[32769..32774].copy_from_slice(b"CD001");
let ok = dir.path().join("good.iso");
std::fs::write(&ok, &good).unwrap();
assert!(validate_iso_image(&ok).is_ok());
}
}