1use anyhow::{Context, Result};
3use std::path::Path;
4
5pub const VIRTIO_RELEASE_REPO: &str = crate::pins::RELEASE_REPO;
9pub const VIRTIO_RELEASE_TAG: &str = crate::pins::DRIVERS_RELEASE_TAG;
10pub const VIRTIO_RELEASE_ASSET: &str = crate::paths::VIRTIO_ISO;
11pub fn openssh_zip_url(arch: crate::unattend::Architecture) -> String {
14 format!(
15 "https://github.com/PowerShell/Win32-OpenSSH/releases/download/{}/{}",
16 crate::pins::OPENSSH_RELEASE_TAG,
17 arch.openssh_zip_name()
18 )
19}
20const UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
21
22pub async fn download(url: &str, dest: &Path) -> Result<String> {
25 let client = reqwest::Client::builder()
26 .user_agent(UA)
27 .build()
28 .context("reqwest client")?;
29 let mut resp = client.get(url).send().await?.error_for_status()?;
30 let label = dest
31 .file_name()
32 .map(|n| n.to_string_lossy().into_owned())
33 .unwrap_or_else(|| dest.display().to_string());
34 let mut progress = Progress::new(&label, resp.content_length());
35 let mut file = tokio::fs::File::create(dest)
36 .await
37 .with_context(|| format!("create {}", dest.display()))?;
38 use sha2::Digest;
39 use tokio::io::AsyncWriteExt;
40 let mut hasher = sha2::Sha256::new();
41 while let Some(chunk) = resp.chunk().await? {
42 hasher.update(&chunk);
43 progress.add(chunk.len());
44 file.write_all(&chunk).await?;
45 }
46 file.flush().await?;
47 progress.finish();
48 Ok(hex::encode(hasher.finalize()))
49}
50
51pub struct Progress {
56 label: String,
57 total: Option<u64>,
58 downloaded: u64,
59 start: std::time::Instant,
60 last_print: std::time::Instant,
61}
62
63impl Progress {
64 pub fn new(label: &str, total: Option<u64>) -> Self {
65 let now = std::time::Instant::now();
66 Self {
67 label: label.to_string(),
68 total,
69 downloaded: 0,
70 start: now,
71 last_print: now,
72 }
73 }
74
75 pub fn add(&mut self, n: usize) {
77 self.downloaded += n as u64;
78 let now = std::time::Instant::now();
79 if now.duration_since(self.last_print).as_secs() >= 1 {
80 self.last_print = now;
81 eprintln!(
82 "{}",
83 format_progress(
84 &self.label,
85 self.downloaded,
86 self.total,
87 now.duration_since(self.start).as_secs_f64(),
88 )
89 );
90 }
91 }
92
93 pub fn finish(&self) {
95 eprintln!(
96 "{}",
97 format_progress(
98 &self.label,
99 self.downloaded,
100 self.total,
101 std::time::Instant::now()
102 .duration_since(self.start)
103 .as_secs_f64(),
104 )
105 );
106 }
107}
108
109fn format_progress(label: &str, downloaded: u64, total: Option<u64>, elapsed_secs: f64) -> String {
112 let speed = downloaded as f64 / elapsed_secs.max(0.001);
113 match total {
114 Some(t) if t > 0 => format!(
115 "{}: {}/{} ({:.0}%, {}/s)",
116 label,
117 fmt_size(downloaded),
118 fmt_size(t),
119 downloaded as f64 / t as f64 * 100.0,
120 fmt_size(speed as u64),
121 ),
122 _ => format!(
123 "{}: {} ({}/s)",
124 label,
125 fmt_size(downloaded),
126 fmt_size(speed as u64),
127 ),
128 }
129}
130
131fn fmt_size(bytes: u64) -> String {
133 const KB: f64 = 1024.0;
134 const MB: f64 = 1024.0 * 1024.0;
135 const GB: f64 = 1024.0 * 1024.0 * 1024.0;
136 let b = bytes as f64;
137 if b >= GB {
138 format!("{:.1} GB", b / GB)
139 } else if b >= MB {
140 format!("{:.1} MB", b / MB)
141 } else if b >= KB {
142 format!("{:.1} KB", b / KB)
143 } else {
144 format!("{bytes} B")
145 }
146}
147
148pub fn iso_cache_dir() -> Result<std::path::PathBuf> {
157 let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_ISO_DIR")?;
158 root.ensure_group("iso").context("create ISO cache group")
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum DownloadStatus {
164 Cached { path: std::path::PathBuf },
166 Downloaded {
168 path: std::path::PathBuf,
169 sha256: String,
170 },
171}
172
173pub async fn download_if_missing(
185 url: &str,
186 dest: &Path,
187 expected_sha256: Option<&str>,
188 force: bool,
189) -> Result<DownloadStatus> {
190 if !force
191 && let Ok(meta) = std::fs::metadata(dest)
192 && meta.len() > 0
193 {
194 match expected_sha256 {
195 Some(expected) => {
196 let actual = sha256_of(dest).await?;
197 if actual.eq_ignore_ascii_case(expected) {
198 tracing::info!("using cached {}", dest.display());
199 return Ok(DownloadStatus::Cached {
200 path: dest.to_path_buf(),
201 });
202 }
203 tracing::warn!(
204 "hash mismatch for {} (expected {expected}, got {actual}); re-downloading",
205 dest.display()
206 );
207 }
208 None => {
209 tracing::info!("using cached {}", dest.display());
210 return Ok(DownloadStatus::Cached {
211 path: dest.to_path_buf(),
212 });
213 }
214 }
215 }
216 if let Some(parent) = dest.parent()
217 && !parent.as_os_str().is_empty()
218 {
219 tokio::fs::create_dir_all(parent)
220 .await
221 .with_context(|| format!("mkdir {}", parent.display()))?;
222 }
223 let tmp = dest.with_extension("part");
226 let sha256 = match download(url, &tmp).await {
227 Ok(s) => s,
228 Err(e) => {
229 let _ = tokio::fs::remove_file(&tmp).await;
230 return Err(e);
231 }
232 };
233 if let Some(expected) = expected_sha256
234 && !sha256.eq_ignore_ascii_case(expected)
235 {
236 let _ = tokio::fs::remove_file(&tmp).await;
238 anyhow::bail!(
239 "SHA-256 mismatch for {}: expected {expected}, got {sha256}",
240 dest.display()
241 );
242 }
243 tokio::fs::rename(&tmp, dest)
244 .await
245 .with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
246 Ok(DownloadStatus::Downloaded {
247 path: dest.to_path_buf(),
248 sha256,
249 })
250}
251
252pub async fn sha256_of(path: &Path) -> Result<String> {
254 use sha2::Digest;
255 use tokio::io::AsyncReadExt;
256 let mut file = tokio::fs::File::open(path)
257 .await
258 .with_context(|| format!("open {}", path.display()))?;
259 let mut hasher = sha2::Sha256::new();
260 let mut buf = vec![0u8; 1024 * 1024];
261 loop {
262 let n = file.read(&mut buf).await?;
263 if n == 0 {
264 break;
265 }
266 hasher.update(&buf[..n]);
267 }
268 Ok(hex::encode(hasher.finalize()))
269}
270pub async fn fetch_text(url: &str) -> Result<String> {
272 let client = reqwest::Client::builder()
273 .user_agent(UA)
274 .build()
275 .context("reqwest client")?;
276 let body = client
277 .get(url)
278 .send()
279 .await?
280 .error_for_status()
281 .with_context(|| format!("GET {url}"))?
282 .text()
283 .await?;
284 Ok(body)
285}
286
287pub async fn virtio_release_info() -> Result<(String, String)> {
303 let url = crate::qemu_portable::release_asset_url(
304 VIRTIO_RELEASE_REPO,
305 VIRTIO_RELEASE_TAG,
306 VIRTIO_RELEASE_ASSET,
307 )
308 .await?;
309 let sha_url = crate::qemu_portable::release_asset_url(
310 VIRTIO_RELEASE_REPO,
311 VIRTIO_RELEASE_TAG,
312 crate::paths::VIRTIO_ISO_SHA256,
313 )
314 .await?;
315 let body = fetch_text(&sha_url).await?;
316 let sha = body
317 .split_whitespace()
318 .next()
319 .with_context(|| format!("empty {}", crate::paths::VIRTIO_ISO_SHA256))?
320 .to_string();
321 if !sha.eq_ignore_ascii_case(crate::pins::VIRTIO_WIN_SHA256) {
322 anyhow::bail!(
323 "virtio-win.iso sidecar hash {sha} does not match the pinned hash {} \
324 (tampered drivers release or stale pin after a drivers-tag bump)",
325 crate::pins::VIRTIO_WIN_SHA256
326 );
327 }
328 Ok((url, sha))
329}
330
331pub fn validate_iso_image(path: &Path) -> Result<()> {
336 use std::io::{Read, Seek, SeekFrom};
337 fn printable_head(path: &Path, len: usize) -> String {
338 std::fs::read(path)
339 .map(|b| {
340 b.into_iter()
341 .take(len)
342 .map(|c| {
343 if c.is_ascii_graphic() || c == b' ' {
344 c as char
345 } else {
346 '·'
347 }
348 })
349 .collect()
350 })
351 .unwrap_or_default()
352 }
353 let mut file = std::fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
354 let len = file.metadata().map(|m| m.len()).unwrap_or(0);
355 if len < 32774 {
356 anyhow::bail!(
357 "{} is too small ({} bytes) to be an ISO image — starts with: {}; \
358 likely a bot-check/error page saved as .iso — delete it and re-download",
359 path.display(),
360 len,
361 printable_head(path, 120)
362 );
363 }
364 let mut magic = [0u8; 5];
365 file.seek(SeekFrom::Start(32769))
366 .context("seek ISO magic")?;
367 file.read_exact(&mut magic).context("read ISO magic")?;
368 if &magic != b"CD001" {
369 anyhow::bail!(
370 "{} is not an ISO image ({} bytes, starts with: {}); \
371 likely a bot-check/error page saved as .iso — delete it and re-download",
372 path.display(),
373 len,
374 printable_head(path, 120)
375 );
376 }
377 Ok(())
378}
379pub fn resolve_win_iso_url(cli_url: Option<String>) -> Result<String> {
387 if let Some(u) = cli_url {
388 return Ok(u);
389 }
390 std::env::var("WIN11_ISO_URL").map_err(|_| {
391 anyhow::anyhow!(
392 "no Windows ISO URL: pass --win-iso-url <url> or set WIN11_ISO_URL.\n\
393 Get a fresh link in your browser (Microsoft -> Windows 11 -> download; links are time-limited).\n\
394 See README for Fido/Mido.sh alternatives."
395 )
396 })
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[tokio::test]
404 async fn skips_existing_file_without_hash() {
405 let dir = tempfile::tempdir().unwrap();
406 let dest = dir.path().join("virtio-win.iso");
407 std::fs::write(&dest, b"fake-iso-bytes").unwrap();
408 let status = download_if_missing("https://example.invalid/x.iso", &dest, None, false)
409 .await
410 .unwrap();
411 assert_eq!(status, DownloadStatus::Cached { path: dest });
412 }
413
414 #[tokio::test]
415 async fn skips_existing_file_with_matching_hash() {
416 let dir = tempfile::tempdir().unwrap();
417 let dest = dir.path().join("v.iso");
418 std::fs::write(&dest, b"abc").unwrap();
419 let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
421 let status = download_if_missing(
422 "https://example.invalid/x.iso",
423 &dest,
424 Some(expected),
425 false,
426 )
427 .await
428 .unwrap();
429 assert_eq!(status, DownloadStatus::Cached { path: dest.clone() });
430 assert_eq!(sha256_of(&dest).await.unwrap(), expected);
431 }
432
433 async fn serve_once(body: &'static [u8]) -> String {
435 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
436 let addr = listener.local_addr().unwrap();
437 tokio::spawn(async move {
438 if let Ok((mut sock, _)) = listener.accept().await {
439 use tokio::io::{AsyncReadExt, AsyncWriteExt};
440 let mut buf = vec![0u8; 8192];
441 let _ = sock.read(&mut buf).await;
443 let head = format!(
444 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
445 body.len()
446 );
447 let _ = sock.write_all(head.as_bytes()).await;
448 let _ = sock.write_all(body).await;
449 }
450 });
451 format!("http://{addr}/payload.bin")
452 }
453
454 #[tokio::test]
455 async fn fresh_download_verifies_hash_and_cleans_tmp_on_mismatch() {
456 let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
458 let dir = tempfile::tempdir().unwrap();
460 let dest = dir.path().join("fresh.bin");
461 let url = serve_once(b"abc").await;
462 let status = download_if_missing(&url, &dest, Some(expected), false)
463 .await
464 .unwrap();
465 match status {
466 DownloadStatus::Downloaded { path, sha256 } => {
467 assert_eq!(path, dest);
468 assert_eq!(sha256, expected);
469 }
470 other => panic!("expected Downloaded, got {other:?}"),
471 }
472 assert_eq!(std::fs::read(&dest).unwrap(), b"abc");
473
474 let dir2 = tempfile::tempdir().unwrap();
477 let dest2 = dir2.path().join("bad.bin");
478 let url2 = serve_once(b"abc").await;
479 let err = download_if_missing(&url2, &dest2, Some(&"0".repeat(64)), false)
480 .await
481 .unwrap_err();
482 assert!(
483 format!("{err:#}").contains("SHA-256 mismatch"),
484 "unexpected error: {err:#}"
485 );
486 assert!(!dest2.exists());
487 assert!(!dest2.with_extension("part").exists());
488 }
489
490 #[tokio::test]
491 async fn force_bypasses_valid_cache() {
492 let dir = tempfile::tempdir().unwrap();
493 let dest = dir.path().join("v.iso");
494 std::fs::write(&dest, b"abc").unwrap();
495 let err = download_if_missing("https://example.invalid/x.iso", &dest, None, true)
498 .await
499 .unwrap_err();
500 assert!(
501 format!("{err:#}").contains("example.invalid"),
502 "unexpected error: {err:#}"
503 );
504 assert_eq!(std::fs::read(&dest).unwrap(), b"abc");
507 }
508
509 #[test]
510 fn cache_dir_override_and_no_eviction() {
511 let tmp = tempfile::tempdir().unwrap();
515 let override_root = tmp.path().join("custom-root");
516 unsafe { std::env::set_var("WINDOWS_HEADLESS_ISO_DIR", &override_root) };
517
518 let dir = iso_cache_dir().unwrap();
519 assert_eq!(dir, override_root.join("iso"));
520 assert!(dir.is_dir());
521
522 std::fs::write(dir.join("virtio-win.iso"), b"fake-iso-bytes").unwrap();
525 let dir2 = iso_cache_dir().unwrap();
526 assert_eq!(dir2, dir);
527 assert_eq!(
528 std::fs::read(dir2.join("virtio-win.iso")).unwrap(),
529 b"fake-iso-bytes"
530 );
531
532 unsafe {
533 std::env::remove_var("WINDOWS_HEADLESS_ISO_DIR");
534 }
535 }
536
537 #[test]
538 fn win_iso_url_resolution_prefers_flag_then_env() {
539 unsafe {
540 std::env::remove_var("WIN11_ISO_URL");
541 }
542 assert!(resolve_win_iso_url(None).is_err());
543 unsafe {
544 std::env::set_var("WIN11_ISO_URL", "https://example.invalid/env.iso");
545 }
546 assert_eq!(
547 resolve_win_iso_url(None).unwrap(),
548 "https://example.invalid/env.iso"
549 );
550 assert_eq!(
551 resolve_win_iso_url(Some("https://example.invalid/flag.iso".into())).unwrap(),
552 "https://example.invalid/flag.iso"
553 );
554 unsafe {
555 std::env::remove_var("WIN11_ISO_URL");
556 }
557 }
558
559 #[test]
560 fn discovery_resolves_project_dot_cache() {
561 let root = cache_manager::CacheRoot::from_discovery().unwrap();
565 assert!(
566 root.path().ends_with(".cache"),
567 "got {}",
568 root.path().display()
569 );
570 }
571
572 #[test]
573 fn progress_renders_with_and_without_total() {
574 let line = format_progress("qemu.tar.gz", 13_107_200, Some(36_392_960), 1.5);
576 assert_eq!(line, "qemu.tar.gz: 12.5 MB/34.7 MB (36%, 8.3 MB/s)");
577 let line = format_progress("x.iso", 1_048_576, None, 0.0);
580 assert_eq!(line, "x.iso: 1.0 MB (1000.0 MB/s)");
581 let line = format_progress("x.iso", 1_048_576, Some(0), 2.0);
582 assert_eq!(line, "x.iso: 1.0 MB (512.0 KB/s)");
583 assert_eq!(fmt_size(512), "512 B");
585 assert_eq!(fmt_size(2048), "2.0 KB");
586 assert_eq!(fmt_size(8_589_934_592), "8.0 GB");
587 }
588
589 #[test]
590 fn iso_magic_rejects_html_stubs() {
591 let dir = tempfile::tempdir().unwrap();
592 let stub = dir.path().join("bogus.iso");
593 std::fs::write(&stub, b"<!doctype html>bot check").unwrap();
594 assert!(validate_iso_image(&stub).is_err());
595 let mut good = vec![0u8; 32774];
597 good[32769..32774].copy_from_slice(b"CD001");
598 let ok = dir.path().join("good.iso");
599 std::fs::write(&ok, &good).unwrap();
600 assert!(validate_iso_image(&ok).is_ok());
601 }
602}