use anyhow::{Context, Result};
use std::env::consts;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
const UA: &str = "windows-headless/0.1";
pub const ALLOW_UNVERIFIED_ENV: &str = "WINDOWS_HEADLESS_ALLOW_UNVERIFIED";
fn unverified_allowed(explicit: bool) -> bool {
if explicit {
return true;
}
let v = std::env::var(ALLOW_UNVERIFIED_ENV)
.unwrap_or_default()
.to_ascii_lowercase();
matches!(v.as_str(), "1" | "true" | "yes" | "on")
}
async fn verify_archive_against_sums(
assets: &[(String, String)],
asset_name: &str,
archive_path: &Path,
base: &Path,
allow_unverified: bool,
expected_pin: Option<&str>,
) -> Result<()> {
let sums_url = assets
.iter()
.find(|(n, _)| n == crate::paths::SHA256SUMS_FILE)
.map(|(_, u)| u.clone());
let Some(sums_url) = sums_url else {
if unverified_allowed(allow_unverified) {
tracing::warn!(
"{asset_name}: no {} in release; proceeding unverified (explicitly allowed via {ALLOW_UNVERIFIED_ENV} or --allow-unverified)",
crate::paths::SHA256SUMS_FILE
);
return Ok(());
}
let _ = std::fs::remove_file(archive_path);
anyhow::bail!(
"{asset_name}: release ships no {sums} — refusing unverified download. \
Set {ALLOW_UNVERIFIED_ENV}=1 or pass --allow-unverified to proceed anyway (not recommended)",
sums = crate::paths::SHA256SUMS_FILE
);
};
let sums_path = base.join(format!("{}.download", crate::paths::SHA256SUMS_FILE));
fetch_to(&sums_url, &sums_path).await?;
let body = std::fs::read_to_string(&sums_path)?;
let _ = std::fs::remove_file(&sums_path);
match parse_sums(&body, asset_name) {
Some(expected) => {
let actual = crate::downloader::sha256_of(archive_path).await?;
if !actual.eq_ignore_ascii_case(&expected) {
let _ = std::fs::remove_file(archive_path);
anyhow::bail!(
"SHA-256 mismatch for {asset_name}: expected {expected}, got {actual}"
);
}
if let Some(pin) = expected_pin
&& !expected.eq_ignore_ascii_case(pin)
{
let _ = std::fs::remove_file(archive_path);
anyhow::bail!(
"SHA-256 sums entry for {asset_name} does not match the pinned hash \
(expected pin {pin}, release sums say {expected}): refusing possibly \
compromised release asset"
);
}
Ok(())
}
None => {
if unverified_allowed(allow_unverified) {
tracing::warn!(
"{asset_name} not listed in {}; proceeding unverified (explicitly allowed)",
crate::paths::SHA256SUMS_FILE
);
return Ok(());
}
let _ = std::fs::remove_file(archive_path);
anyhow::bail!(
"{asset_name} not listed in {} — refusing unverified download. \
Set {ALLOW_UNVERIFIED_ENV}=1 or pass --allow-unverified to proceed anyway (not recommended)",
crate::paths::SHA256SUMS_FILE
);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AssetKind {
TarGz,
TarXz,
}
#[derive(Debug, Clone)]
pub struct PortableQemu {
pub root: PathBuf,
pub version: String,
}
impl PortableQemu {
pub fn qemu_img(&self) -> PathBuf {
self.root
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::QEMU_IMG_NAME)
}
pub fn qemu_system(&self, binary: &str) -> PathBuf {
self.root.join("bin").join(binary)
}
pub fn system_binaries(&self) -> Vec<PathBuf> {
let mut out = Vec::new();
if let Ok(rd) = std::fs::read_dir(self.root.join("bin")) {
for entry in rd.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with("qemu-system-") {
out.push(entry.path());
}
}
}
out.sort();
out
}
}
fn asset_for_host() -> Result<(&'static str, AssetKind)> {
match (consts::OS, consts::ARCH) {
("macos", "aarch64") => Ok((crate::paths::MARKER_MACOS_ARM64, AssetKind::TarGz)),
("linux", "x86_64") => Ok((crate::paths::MARKER_LINUX_X86_64, AssetKind::TarXz)),
("linux", "aarch64") => Ok((crate::paths::MARKER_LINUX_AARCH64, AssetKind::TarXz)),
(os, arch) => anyhow::bail!(
"no portable QEMU build for {os}/{arch} (only macos-arm64 and linux x86_64/aarch64 are published); install system QEMU instead"
),
}
}
pub(crate) fn pinned_qemu_sha256(marker: &str) -> Option<&'static str> {
match marker {
crate::paths::MARKER_MACOS_ARM64 => Some(crate::pins::QEMU_PORTABLE_SHA256_MACOS_ARM64),
crate::paths::MARKER_LINUX_X86_64 => Some(crate::pins::QEMU_PORTABLE_SHA256_LINUX_X86_64),
crate::paths::MARKER_LINUX_AARCH64 => Some(crate::pins::QEMU_PORTABLE_SHA256_LINUX_AARCH64),
_ => None,
}
}
pub(crate) fn pinned_wimlib_sha256(marker: &str) -> Option<&'static str> {
match marker {
crate::paths::MARKER_MACOS_ARM64 => Some(crate::pins::WIMLIB_PORTABLE_SHA256_MACOS_ARM64),
crate::paths::MARKER_LINUX_X86_64 => Some(crate::pins::WIMLIB_PORTABLE_SHA256_LINUX_X86_64),
crate::paths::MARKER_LINUX_AARCH64 => {
Some(crate::pins::WIMLIB_PORTABLE_SHA256_LINUX_AARCH64)
}
_ => None,
}
}
pub const DEFAULT_QEMU_PORTABLE_TAG: &str = crate::pins::QEMU_PORTABLE_TAG;
pub(crate) fn parse_sums(body: &str, asset: &str) -> Option<String> {
body.lines().find_map(|line| {
let mut parts = line.split_whitespace();
match (parts.next(), parts.next()) {
(Some(hash), Some(name)) if name.trim_start_matches('*') == asset => {
Some(hash.to_string())
}
_ => None,
}
})
}
async fn fetch_to(url: &str, dest: &Path) -> Result<()> {
let client = reqwest::Client::builder()
.user_agent(UA)
.build()
.context("reqwest client")?;
let mut resp = client
.get(url)
.header("Accept", "application/vnd.github+json")
.send()
.await?
.error_for_status()
.with_context(|| format!("GET {url}"))?;
if let Some(parent) = dest.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent).await?;
}
let name = dest
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| dest.display().to_string());
let label = name.strip_suffix(".download").unwrap_or(&name).to_string();
let mut progress = crate::downloader::Progress::new(&label, resp.content_length());
let tmp = dest.with_extension("part");
let mut file = tokio::fs::File::create(&tmp).await?;
use tokio::io::AsyncWriteExt;
while let Some(chunk) = resp.chunk().await? {
progress.add(chunk.len());
file.write_all(&chunk).await?;
}
file.flush().await?;
progress.finish();
drop(file);
tokio::fs::rename(&tmp, dest).await?;
Ok(())
}
fn github_client() -> Result<reqwest::Client> {
let mut headers = reqwest::header::HeaderMap::new();
if let Some(token) = std::env::var("GITHUB_TOKEN")
.or_else(|_| std::env::var("GH_TOKEN"))
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
{
headers.insert(
reqwest::header::AUTHORIZATION,
format!("Bearer {token}").parse().context("token header")?,
);
}
reqwest::Client::builder()
.user_agent(UA)
.default_headers(headers)
.build()
.context("reqwest client")
}
#[cfg_attr(windows, allow(unused_variables))]
fn extract(kind: AssetKind, archive: &Path, dest: &Path, inner_bin_dir: &str) -> Result<()> {
let file =
std::fs::File::open(archive).with_context(|| format!("open {}", archive.display()))?;
match kind {
AssetKind::TarGz => {
extract_tar(flate2::read::GzDecoder::new(file), dest)?;
}
AssetKind::TarXz => {
extract_tar(liblzma::read::XzDecoder::new(file), dest)?;
}
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(rd) = std::fs::read_dir(dest.join(inner_bin_dir)) {
for entry in rd.flatten() {
let p = entry.path();
if p.is_file() {
let mut perm = std::fs::metadata(&p)?.permissions();
perm.set_mode(perm.mode() | 0o111);
std::fs::set_permissions(&p, perm)?;
}
}
}
}
Ok(())
}
fn extract_tar<R: Read>(reader: R, dest: &Path) -> Result<()> {
let mut archive = tar::Archive::new(reader);
for entry in archive.entries().context("read tar entries")? {
let mut entry = entry.context("read tar entry")?;
let path = entry.path().context("tar entry path")?.into_owned();
if path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
anyhow::bail!("refusing unsafe tar entry: {}", path.display());
}
entry
.unpack_in(dest)
.with_context(|| format!("unpack {}", path.display()))?;
}
Ok(())
}
pub async fn ensure(
dir: Option<PathBuf>,
version: Option<String>,
allow_unverified: bool,
) -> Result<PortableQemu> {
let root = crate::cache::resolve_cache_root(dir, "WINDOWS_HEADLESS_QEMU_DIR")?;
root.ensure_group(crate::paths::QEMU_GROUP)
.context("create qemu-portable cache group")?;
let (marker, kind) = asset_for_host()?;
let tag: String = match version {
Some(v) => v,
None => DEFAULT_QEMU_PORTABLE_TAG.to_string(),
};
let group = root.group(format!("{}/{tag}", crate::paths::QEMU_GROUP));
group.ensure_dir().context("create version cache group")?;
let tree = group.path().join(crate::paths::QEMU_INNER);
if tree
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::QEMU_IMG_NAME)
.is_file()
{
return Ok(PortableQemu {
root: tree,
version: tag,
});
}
let assets = release_by_tag(&tag).await?;
let asset_name = assets
.iter()
.map(|(n, _)| n.as_str())
.find(|n| n.contains(marker) && n.starts_with(crate::paths::QEMU_ASSET_PREFIX))
.context(format!(
"release has no portable asset for this host ({marker})"
))?
.to_string();
let url = assets
.iter()
.find(|(n, _)| n == &asset_name)
.map(|(_, u)| u.clone())
.unwrap();
let base = root.group_path(crate::paths::QEMU_GROUP);
let archive_path = base.join(format!("{asset_name}.download"));
fetch_to(&url, &archive_path).await?;
let expected_pin = (tag == DEFAULT_QEMU_PORTABLE_TAG).then(|| pinned_qemu_sha256(marker));
let expected_pin = expected_pin.flatten();
verify_archive_against_sums(
&assets,
&asset_name,
&archive_path,
&base,
allow_unverified,
expected_pin,
)
.await?;
let dest = group.path().to_path_buf();
if dest.exists() {
std::fs::remove_dir_all(&dest)
.with_context(|| format!("clear stale {}", dest.display()))?;
}
group.ensure_dir()?;
extract(
kind,
&archive_path,
&dest,
&format!(
"{}/{}",
crate::paths::QEMU_INNER,
crate::paths::PORTABLE_BIN_DIR
),
)?;
group.ensure_dir()?;
let _ = std::fs::remove_file(&archive_path);
let root = dest.join(crate::paths::QEMU_INNER);
Ok(PortableQemu { root, version: tag })
}
pub fn pinned_cached() -> Result<PortableQemu> {
let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_QEMU_DIR")?;
let base = root.group_path(crate::paths::QEMU_GROUP);
let tag = DEFAULT_QEMU_PORTABLE_TAG.to_string();
let tree = base.join(&tag).join(crate::paths::QEMU_INNER);
if tree
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::QEMU_IMG_NAME)
.is_file()
{
return Ok(PortableQemu {
root: tree,
version: tag,
});
}
let found = cached_versions(&base);
anyhow::bail!(
"pinned portable QEMU {tag} not cached (found: {found}); run `fetch-qemu` (fetches the pin) or pass `--qemu-dir` to use another tree explicitly",
)
}
fn cached_versions(base: &Path) -> String {
let mut found: Vec<String> = std::fs::read_dir(base)
.map(|rd| {
rd.flatten()
.filter(|e| {
e.path()
.join(crate::paths::QEMU_INNER)
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::QEMU_IMG_NAME)
.is_file()
})
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
found.sort();
if found.is_empty() {
"none".to_string()
} else {
found.join(", ")
}
}
pub(crate) async fn release_by_tag(tag: &str) -> Result<Vec<(String, String)>> {
let url = format!(
"https://api.github.com/repos/{}/releases/tags/{tag}",
crate::pins::RELEASE_REPO,
);
let body = github_get_json(&url, &format!("portable QEMU release {tag}")).await?;
let (_, assets) = parse_release_body(&body)?;
Ok(assets)
}
async fn github_get_json(url: &str, what: &str) -> Result<serde_json::Value> {
let resp = github_client()?
.get(url)
.header("Accept", "application/vnd.github+json")
.send()
.await?;
let status = resp.status();
resp.error_for_status()
.with_context(|| {
format!("{what} lookup failed (HTTP {status}; 403 usually means GitHub API rate limit — retry with GITHUB_TOKEN set)")
})?
.json()
.await
.context("decode GitHub release JSON")
}
fn parse_release_body(body: &serde_json::Value) -> Result<(String, Vec<(String, String)>)> {
let tag = body
.get("tag_name")
.and_then(|t| t.as_str())
.context("release has no tag_name")?
.to_string();
let assets = body
.get("assets")
.and_then(|a| a.as_array())
.context("release has no assets array")?
.iter()
.filter_map(|a| {
Some((
a.get("name")?.as_str()?.to_string(),
a.get("browser_download_url")?.as_str()?.to_string(),
))
})
.collect();
Ok((tag, assets))
}
#[derive(Debug, Clone)]
pub struct PortableWimlib {
pub root: PathBuf,
pub version: String,
}
impl PortableWimlib {
pub fn wimlib_bin(&self) -> PathBuf {
self.root
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::WIMLIB_IMGX_NAME)
}
}
pub const DEFAULT_WIMLIB_PORTABLE_TAG: &str = crate::pins::WIMLIB_PORTABLE_TAG;
async fn release_for_tag(repo: &str, tag: &str) -> Result<(String, Vec<(String, String)>)> {
let url = format!("https://api.github.com/repos/{repo}/releases/tags/{tag}");
let body = github_get_json(&url, &format!("release {tag} in {repo}")).await?;
parse_release_body(&body)
}
pub async fn release_asset_url(repo: &str, tag: &str, asset: &str) -> Result<String> {
let (_, assets) = release_for_tag(repo, tag).await?;
assets
.iter()
.find(|(n, _)| n == asset)
.map(|(_, u)| u.clone())
.with_context(|| format!("release {tag} has no asset {asset}"))
}
pub async fn ensure_wimlib(
dir: Option<PathBuf>,
version: Option<String>,
allow_unverified: bool,
) -> Result<PortableWimlib> {
let root = crate::cache::resolve_cache_root(dir, "WINDOWS_HEADLESS_WIMLIB_DIR")?;
root.ensure_group(crate::paths::WIMLIB_GROUP)
.context("create wimlib-portable cache group")?;
let (marker, kind) = asset_for_host()?;
let tag: String = match version {
Some(v) => v,
None => DEFAULT_WIMLIB_PORTABLE_TAG.to_string(),
};
let group = root.group(format!("{}/{tag}", crate::paths::WIMLIB_GROUP));
group.ensure_dir().context("create version cache group")?;
let tree = group.path().join(crate::paths::WIMLIB_INNER);
if tree
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::WIMLIB_IMGX_NAME)
.is_file()
{
return Ok(PortableWimlib {
root: tree,
version: tag,
});
}
let (_, assets) = release_for_tag(crate::pins::RELEASE_REPO, &tag).await?;
let asset_name = assets
.iter()
.map(|(n, _)| n.as_str())
.find(|n| n.contains(marker) && n.starts_with(crate::paths::WIMLIB_ASSET_PREFIX))
.with_context(|| format!("release {tag} has no portable asset for this host ({marker})"))?
.to_string();
let url = assets
.iter()
.find(|(n, _)| n == &asset_name)
.map(|(_, u)| u.clone())
.unwrap();
let base = root.group_path(crate::paths::WIMLIB_GROUP);
let archive_path = base.join(format!("{asset_name}.download"));
fetch_to(&url, &archive_path).await?;
let expected_pin = (tag == DEFAULT_WIMLIB_PORTABLE_TAG).then(|| pinned_wimlib_sha256(marker));
let expected_pin = expected_pin.flatten();
verify_archive_against_sums(
&assets,
&asset_name,
&archive_path,
&base,
allow_unverified,
expected_pin,
)
.await?;
let dest = group.path().to_path_buf();
if dest.exists() {
std::fs::remove_dir_all(&dest)
.with_context(|| format!("clear stale {}", dest.display()))?;
}
group.ensure_dir()?;
extract(
kind,
&archive_path,
&dest,
&format!(
"{}/{}",
crate::paths::WIMLIB_INNER,
crate::paths::PORTABLE_BIN_DIR
),
)?;
group.ensure_dir()?;
let _ = std::fs::remove_file(&archive_path);
let root = dest.join(crate::paths::WIMLIB_INNER);
Ok(PortableWimlib { root, version: tag })
}
pub fn pinned_cached_wimlib() -> Result<PortableWimlib> {
let root = crate::cache::resolve_cache_root(None, "WINDOWS_HEADLESS_WIMLIB_DIR")?;
let base = root.group_path(crate::paths::WIMLIB_GROUP);
let tag = DEFAULT_WIMLIB_PORTABLE_TAG.to_string();
let tree = base.join(&tag).join(crate::paths::WIMLIB_INNER);
if tree
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::WIMLIB_IMGX_NAME)
.is_file()
{
return Ok(PortableWimlib {
root: tree,
version: tag,
});
}
let found = cached_wimlib_versions(&base);
anyhow::bail!(
"pinned portable wimlib {tag} not cached (found: {found}); run `fetch-wimlib` (fetches the pin)"
)
}
fn cached_wimlib_versions(base: &Path) -> String {
let mut found: Vec<String> = std::fs::read_dir(base)
.map(|rd| {
rd.flatten()
.filter(|e| {
e.path()
.join(crate::paths::WIMLIB_INNER)
.join(crate::paths::PORTABLE_BIN_DIR)
.join(crate::paths::WIMLIB_IMGX_NAME)
.is_file()
})
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
found.sort();
if found.is_empty() {
"none".to_string()
} else {
found.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sums_parsing() {
let body = "abc123 qemu-portable-linux-x86_64-11.1.1.tar.xz\ndef456 *other.zip\n";
assert_eq!(
parse_sums(body, "qemu-portable-linux-x86_64-11.1.1.tar.xz"),
Some("abc123".to_string())
);
assert_eq!(parse_sums(body, "missing"), None);
}
#[test]
fn default_qemu_tag_is_the_pin() {
assert_eq!(DEFAULT_QEMU_PORTABLE_TAG, crate::pins::QEMU_PORTABLE_TAG);
}
#[test]
fn pinned_cached_finds_pin_and_rejects_others() {
let tmp = tempfile::tempdir().unwrap();
let pin_bin = tmp
.path()
.join("qemu-portable")
.join(DEFAULT_QEMU_PORTABLE_TAG)
.join("qemu-portable/bin");
std::fs::create_dir_all(&pin_bin).unwrap();
std::fs::write(pin_bin.join("qemu-img"), b"x").unwrap();
let other_bin = tmp
.path()
.join("qemu-portable/qemu-v99.99.99/qemu-portable/bin");
std::fs::create_dir_all(&other_bin).unwrap();
std::fs::write(other_bin.join("qemu-img"), b"x").unwrap();
unsafe { std::env::set_var("WINDOWS_HEADLESS_QEMU_DIR", tmp.path()) };
let got = pinned_cached().unwrap();
assert_eq!(got.version, DEFAULT_QEMU_PORTABLE_TAG);
assert!(
got.root
.ends_with(format!("{}/qemu-portable", DEFAULT_QEMU_PORTABLE_TAG))
);
std::fs::remove_dir_all(
tmp.path()
.join("qemu-portable")
.join(DEFAULT_QEMU_PORTABLE_TAG),
)
.unwrap();
assert!(pinned_cached().is_err());
unsafe { std::env::remove_var("WINDOWS_HEADLESS_QEMU_DIR") };
}
#[test]
fn default_wimlib_tag_is_the_pin() {
assert_eq!(
DEFAULT_WIMLIB_PORTABLE_TAG,
crate::pins::WIMLIB_PORTABLE_TAG
);
}
#[test]
fn pinned_cached_wimlib_finds_pin_and_rejects_others() {
let tmp = tempfile::tempdir().unwrap();
let pin_bin = tmp
.path()
.join("wimlib-portable")
.join(DEFAULT_WIMLIB_PORTABLE_TAG)
.join("wimlib-portable/bin");
std::fs::create_dir_all(&pin_bin).unwrap();
std::fs::write(pin_bin.join("wimlib-imagex"), b"x").unwrap();
let other_bin = tmp
.path()
.join("wimlib-portable/wimlib-v9.9.9/wimlib-portable/bin");
std::fs::create_dir_all(&other_bin).unwrap();
std::fs::write(other_bin.join("wimlib-imagex"), b"x").unwrap();
unsafe { std::env::set_var("WINDOWS_HEADLESS_WIMLIB_DIR", tmp.path()) };
let got = pinned_cached_wimlib().unwrap();
assert_eq!(got.version, DEFAULT_WIMLIB_PORTABLE_TAG);
assert!(
got.root
.ends_with(format!("{}/wimlib-portable", DEFAULT_WIMLIB_PORTABLE_TAG))
);
std::fs::remove_dir_all(
tmp.path()
.join("wimlib-portable")
.join(DEFAULT_WIMLIB_PORTABLE_TAG),
)
.unwrap();
assert!(pinned_cached_wimlib().is_err());
unsafe { std::env::remove_var("WINDOWS_HEADLESS_WIMLIB_DIR") };
}
#[test]
fn host_asset_selection_matches_this_machine() {
let _ = asset_for_host();
}
#[test]
fn unverified_gate_truth_table() {
let prior = std::env::var(ALLOW_UNVERIFIED_ENV).ok();
unsafe { std::env::remove_var(ALLOW_UNVERIFIED_ENV) };
assert!(!unverified_allowed(false));
assert!(unverified_allowed(true));
unsafe { std::env::set_var(ALLOW_UNVERIFIED_ENV, "1") };
assert!(unverified_allowed(false));
unsafe { std::env::set_var(ALLOW_UNVERIFIED_ENV, "0") };
assert!(!unverified_allowed(false));
assert!(unverified_allowed(true));
match prior {
Some(v) => unsafe { std::env::set_var(ALLOW_UNVERIFIED_ENV, v) },
None => unsafe { std::env::remove_var(ALLOW_UNVERIFIED_ENV) },
}
}
}