Skip to main content

windows_headless/
downloader.rs

1//! ISO download helpers (feature `downloader`).
2use anyhow::{Context, Result};
3use std::path::Path;
4
5/// virtio-win ISO vendored on our own releases (no Fedora bot-wall, no
6/// rsync): `drivers-<date>` tag, `virtio-win.iso` + `virtio-win.iso.sha256`.
7/// Values live in [`crate::pins`]; these aliases keep existing call sites.
8pub 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;
11/// Offline SSH installer, Microsoft release asset (documented source;
12/// candidate for our own releases later). Per guest arch: Win64 vs ARM64.
13pub 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
22/// Stream `url` to `dest`, computing SHA-256 on the fly. Returns hex digest.
23/// Always (re)downloads; see [`download_if_missing`] for the caching variant.
24pub 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
51/// Throttled stderr progress for multi-MB downloads (Windows ISOs are GBs;
52/// without this the CLI sits silent for minutes). Dependency-free: byte
53/// counting + one line at most per second, plus a final line. Status goes
54/// to stderr per the crate stream rule — never stdout.
55pub 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    /// Record `n` more bytes; prints at most once per second.
76    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    /// Final line (always printed, even for tiny files).
94    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
109/// Pure rendering (unit-tested): `label: 12.5/34.7 MB (36%, 8.3 MB/s)`;
110/// without a known total the fraction is omitted.
111fn 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
131/// Human size: `512 B`, `3.2 KB`, `12.5 MB`, `1.2 GB`.
132fn 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
148/// Resolve (and create) the ISO cache dir via the shared [`crate::cache`]
149/// helper: `$WINDOWS_HEADLESS_ISO_DIR` wins, then workspace discovery, then
150/// the OS user cache — never a silent `<cwd>/.cache`.
151///
152/// Eviction is intentionally **disabled**: the group is ensured with no
153/// `EvictPolicy` (no `max_bytes`, no `max_files`, no `max_age`). ISOs are
154/// multi-GB and the Windows ISO URLs are time-limited, so size-capped eviction
155/// would force surprise re-downloads.
156pub 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/// Outcome of [`download_if_missing`].
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum DownloadStatus {
164    /// File already present (and hash-verified when `expected_sha256` given).
165    Cached { path: std::path::PathBuf },
166    /// Freshly downloaded; includes the computed SHA-256 hex digest.
167    Downloaded {
168        path: std::path::PathBuf,
169        sha256: String,
170    },
171}
172
173/// Download `url` to `dest` unless it is already there.
174///
175/// - File exists and non-empty with no `expected_sha256`: skipped.
176/// - File exists with `expected_sha256`: re-downloaded only on hash mismatch.
177/// - Missing or empty: downloaded (parent dirs created).
178/// - `force`: skip all of the above and re-download unconditionally (for
179///   URL-rotated artifacts like the Windows ISO, where the cache slot name
180///   can't see that the upstream bytes changed).
181///
182/// Note: Windows ISO URLs are time-limited, so callers should only pass
183/// `expected_sha256` for stable artifacts like `virtio-win.iso`.
184pub 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    // Download to a temp sibling first so a failed run never leaves a
224    // truncated file that a later call would mistake for a valid cache entry.
225    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        // Ordering is load-bearing: remove the poisoned tmp BEFORE bailing.
237        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
252/// SHA-256 hex digest of an existing file.
253pub 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}
270/// Fetch a small text URL (SHA256SUMS sidecars, version pins).
271pub 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
287/// `(download URL, SHA-256)` for the vendored virtio-win ISO: asset URL
288/// from release metadata (rename-proof) + hash from the `.sha256` sidecar.
289///
290/// The sidecar hash must additionally match the code pin
291/// ([`crate::pins::VIRTIO_WIN_SHA256`]): a forged sidecar+ISO pair fails the
292/// pin check, closing the TOFU gap. Mismatch here means the drivers release
293/// was tampered with or the pin is stale after a drivers-tag bump.
294///
295/// Always resolve, even when the file is already cached — do NOT
296/// short-circuit on existence. The sidecar hash is the update channel:
297/// bumping the drivers pin changes the expected hash, which is what makes
298/// `download_if_missing` re-download the stale file; it is also the only
299/// check that sees corruption beyond the ISO magic bytes (a truncated
300/// multi-hundred-MB download still has valid magic). A cheaper
301/// exists-or-magic check would cement stale files silently.
302pub 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
331/// Verify `path` is a real ISO image (ISO9660 `CD001` magic at sector 16).
332/// Catches the classic failure where a bot-wall or error page (HTTP 200
333/// HTML) gets saved as `.iso` — which later hangs EDK2 at boot with zero
334/// block I/O and a black screen, far from the actual cause.
335pub 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}
379/// Resolve the concrete Windows 11 retail ISO URL: explicit `--win-iso-url`
380/// wins, else `$WIN11_ISO_URL`.
381/// There is intentionally no page scraper — Microsoft issues links behind an
382/// interactive, bot-guarded form, so the only reliable source is a fresh,
383/// time-limited link copied from a browser (or a community fetcher like
384/// Fido/Mido.sh — see README). Proven media is retail; non-retail
385/// (Enterprise/OEM) media is untested.
386pub 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        // SHA-256 of "abc".
420        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    /// Serve `body` once over loopback HTTP; returns the URL to fetch.
434    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                // Read the request (ignore content); then serve the body.
442                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        // SHA-256 of "abc".
457        let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
458        // Matching hash: downloads, verifies, renames into place.
459        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        // Mismatching hash: bails BEFORE rename, removes the `.part` tmp,
475        // and never creates `dest`.
476        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        // example.invalid never resolves: success would mean the cache
496        // short-circuit fired, failure means force attempted the download.
497        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        // Untouched: the failed forced download leaves no .part behind
505        // masquerading as cache (download() targets the tmp sibling).
506        assert_eq!(std::fs::read(&dest).unwrap(), b"abc");
507    }
508
509    #[test]
510    fn cache_dir_override_and_no_eviction() {
511        // Single test owns the env var to avoid racing parallel tests.
512        // (unsafe blocks: std::env mutation is process-global; tests are
513        // the documented single-threaded-owner case here.)
514        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        // Previously cached entries survive re-resolution: no eviction policy
523        // (no max_bytes / max_files / max_age) is ever applied.
524        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        // Read-only w.r.t. process globals: from_discovery only reads CWD.
562        // `cargo test` runs with CWD at the package root, which contains
563        // [workspace], so this must resolve to <repo>/.cache without I/O.
564        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        // 12.5 MiB of 34.7 MiB at ~8.3 MB/s.
575        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        // Unknown total: fraction omitted, never divides by zero
578        // (elapsed clamps to 1 ms).
579        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        // Small files render in KB/B, large ones in GB.
584        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        // Minimal valid ISO9660: CD001 at offset 32769.
596        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}