use crate::kwpatch::unpack_smp_bundle;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use wasmtime::error::Context;
use wasmtime::{Engine, Module, Result, bail, format_err};
pub const DEFAULT_UNKERNEL_VERSION: &str = "0.3.0-261130-3ef745b";
pub const DEFAULT_BUNDLE_SHA256: &str =
"a0a4efd7c0d321fab7fb1d287659550586fc7aad0cd41c645fe0e3f090ba12ab";
pub const DEFAULT_SMP_SHA256: &str =
"c161c121f1fad75a4323f94025ef86c2d343e3248d4a9b0ee198150b3e55ceec";
pub const DEFAULT_ALPINE_SHA256: &str =
"b7f5c84d35dbcb999a8b59e57928fc3411e5f153d7cbf8422dd8efee60da15af";
const RELEASE_REPO: &str = "pithings/unkernel";
#[derive(Debug, Clone, Serialize, Deserialize)]
struct BundleMeta {
bundle_sha256: String,
smp_sha256: String,
cmdline: String,
}
#[derive(Debug, Clone, Deserialize)]
struct DistroIndex {
distros: Vec<DistroEntry>,
}
#[derive(Debug, Clone, Deserialize)]
struct DistroEntry {
name: String,
file: String,
size: u64,
sha256: String,
}
pub struct ResolvedArtifacts {
pub module: Module,
pub from_cwasm_cache: bool,
pub load_ms: u64,
pub initrd: Vec<u8>,
pub datadisk_template: Vec<u8>,
pub cmdline: String,
pub distro_path: Option<PathBuf>,
pub cache_dir: PathBuf,
pub cwasm_path: PathBuf,
}
pub fn default_cache_dir() -> PathBuf {
if let Ok(dir) = std::env::var("UNKERNEL_RS_CACHE_DIR")
&& !dir.is_empty()
{
return PathBuf::from(dir);
}
if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
&& Path::new(&xdg).is_absolute()
{
return PathBuf::from(xdg).join("unkernel-rs");
}
if let Ok(home) = std::env::var("HOME")
&& !home.is_empty()
{
return PathBuf::from(home).join(".cache").join("unkernel-rs");
}
if let Ok(local_app_data) = std::env::var("LOCALAPPDATA")
&& !local_app_data.is_empty()
{
return PathBuf::from(local_app_data)
.join("unkernel-rs")
.join("cache");
}
if let Ok(profile) = std::env::var("USERPROFILE")
&& !profile.is_empty()
{
return PathBuf::from(profile).join(".cache").join("unkernel-rs");
}
std::env::temp_dir().join("unkernel-rs-cache")
}
fn replace_file(src: &Path, dest: &Path) -> std::io::Result<()> {
#[cfg(windows)]
{
if dest.exists() {
let _ = fs::remove_file(dest);
}
}
fs::rename(src, dest)
}
fn upstream_unkernel_cache_dir(version: &str) -> Option<PathBuf> {
if let Ok(dir) = std::env::var("UNKERNEL_CACHE_DIR")
&& !dir.is_empty()
{
return Some(PathBuf::from(dir).join(format!("v{version}")));
}
if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
&& Path::new(&xdg).is_absolute()
{
return Some(
PathBuf::from(xdg)
.join("unkernel")
.join(format!("v{version}")),
);
}
std::env::var("HOME")
.ok()
.filter(|h| !h.is_empty())
.map(|h| {
PathBuf::from(h)
.join(".cache")
.join("unkernel")
.join(format!("v{version}"))
})
}
pub fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
pub fn sha256_file(path: &Path) -> Result<String> {
let mut f = File::open(path).with_context(|| format!("open {}", path.display()))?;
let mut hasher = Sha256::new();
let mut buf = [0u8; 64 * 1024];
loop {
let n = f.read(&mut buf)?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect())
}
fn download_to_file(urls: &[String], dest: &Path, expected_sha256: Option<&str>) -> Result<()> {
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent).with_context(|| format!("mkdir {}", parent.display()))?;
}
let tmp = dest.with_extension("tmp");
let mut last_err = None;
for url in urls {
match ureq::get(url).set("User-Agent", "unkernel-rs/0.1").call() {
Ok(resp) => {
let mut reader = resp.into_reader();
let mut out =
File::create(&tmp).with_context(|| format!("create {}", tmp.display()))?;
let mut hasher = Sha256::new();
let mut buf = [0u8; 64 * 1024];
loop {
let n = reader.read(&mut buf)?;
if n == 0 {
break;
}
out.write_all(&buf[..n])?;
hasher.update(&buf[..n]);
}
out.flush()?;
drop(out);
let got: String = hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
if let Some(expected) = expected_sha256
&& got != expected
{
let _ = fs::remove_file(&tmp);
last_err = Some(format!(
"{url}: SHA-256 mismatch (got {got}, expected {expected})"
));
continue;
}
replace_file(&tmp, dest)
.with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
return Ok(());
}
Err(e) => {
let _ = fs::remove_file(&tmp);
last_err = Some(format!("{url}: {e}"));
}
}
}
bail!(
"failed to download {}: {}",
dest.display(),
last_err.unwrap_or_else(|| "no URLs".into())
)
}
pub fn resolve_bundle_path(
explicit: Option<&Path>,
cache_root: &Path,
version: &str,
offline: bool,
) -> Result<PathBuf> {
if let Some(p) = explicit {
if !p.exists() {
bail!("bundle file not found: {}", p.display());
}
return Ok(p.to_path_buf());
}
if let Ok(env_path) = std::env::var("UNKERNEL_BUNDLE_PATH")
&& !env_path.is_empty()
{
let p = PathBuf::from(env_path);
if p.exists() {
return Ok(p);
}
}
let ver_dir = cache_root.join(format!("v{version}"));
let cached = ver_dir.join("unkernel.wasm");
let expected_sha = if version == DEFAULT_UNKERNEL_VERSION {
Some(DEFAULT_BUNDLE_SHA256)
} else {
None
};
if cached.exists() {
if let Some(exp) = expected_sha {
if sha256_file(&cached).ok().as_deref() == Some(exp) {
return Ok(cached);
}
} else {
return Ok(cached);
}
}
if offline {
bail!(
"unkernel.wasm not cached at {} and --offline is set (pass --bundle PATH or run `unkernel-rs fetch`)",
cached.display()
);
}
let urls = vec![
format!("https://cdn.jsdelivr.net/npm/unkernel@{version}/dist/unkernel.wasm"),
format!("https://unpkg.com/unkernel@{version}/dist/unkernel.wasm"),
];
download_to_file(&urls, &cached, expected_sha)?;
Ok(cached)
}
pub fn resolve_distro_path(
distro_name: Option<&str>,
explicit_file: Option<&Path>,
cache_root: &Path,
version: &str,
offline: bool,
) -> Result<Option<PathBuf>> {
if let Some(p) = explicit_file {
if !p.exists() {
bail!("distro image not found: {}", p.display());
}
return Ok(Some(p.to_path_buf()));
}
let Some(name) = distro_name else {
return Ok(None);
};
if name.is_empty() || name == "none" {
return Ok(None);
}
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
{
bail!("invalid distro name {name:?} (expected [a-z0-9]+)");
}
let ver_dir = cache_root.join(format!("v{version}"));
let candidate_names = [format!("{name}.erofs"), format!("{name}.ext4")];
let mut search_dirs = vec![ver_dir.clone()];
if let Some(up) = upstream_unkernel_cache_dir(version) {
search_dirs.push(up);
}
let pinned_alpine = name == "alpine" && version == DEFAULT_UNKERNEL_VERSION;
for dir in &search_dirs {
for fname in &candidate_names {
let p = dir.join(fname);
if p.exists() {
if pinned_alpine && fname == "alpine.erofs" {
if sha256_file(&p).ok().as_deref() == Some(DEFAULT_ALPINE_SHA256) {
return Ok(Some(p));
}
} else {
return Ok(Some(p));
}
}
}
}
if offline {
bail!(
"distro {name:?} not cached in {} and --offline is set (pass --distro-file PATH or run `unkernel-rs fetch`)",
ver_dir.display()
);
}
let base = format!("https://github.com/{RELEASE_REPO}/releases/download/v{version}/");
let index_url = format!("{base}distros.json");
let index_text = ureq::get(&index_url)
.set("User-Agent", "unkernel-rs/0.1")
.call()
.with_context(|| format!("GET {index_url}"))?
.into_string()
.with_context(|| format!("read {index_url}"))?;
let index: DistroIndex =
serde_json::from_str(&index_text).with_context(|| format!("parse {index_url}"))?;
let entry = index
.distros
.into_iter()
.find(|d| d.name == name)
.ok_or_else(|| format_err!("distro {name:?} not found in {index_url}"))?;
if entry.file.contains('/') || entry.file.contains('\\') || entry.file.contains("..") {
bail!("unsafe distro filename in index: {:?}", entry.file);
}
let dest = ver_dir.join(&entry.file);
let img_url = format!("{base}{}", entry.file);
download_to_file(&[img_url], &dest, Some(&entry.sha256))?;
let meta = fs::metadata(&dest)?;
if meta.len() != entry.size {
let _ = fs::remove_file(&dest);
bail!(
"downloaded {} size {} != expected {}",
dest.display(),
meta.len(),
entry.size
);
}
Ok(Some(dest))
}
#[allow(clippy::too_many_arguments)]
pub fn prepare_artifacts(
engine: &Engine,
bundle_override: Option<&Path>,
distro_name: Option<&str>,
distro_file_override: Option<&Path>,
cache_root: &Path,
version: &str,
offline: bool,
epoch_enabled: bool,
rebuild_cache: bool,
) -> Result<ResolvedArtifacts> {
let ver_dir = cache_root.join(format!("v{version}"));
fs::create_dir_all(&ver_dir).with_context(|| format!("mkdir {}", ver_dir.display()))?;
let bundle_path = resolve_bundle_path(bundle_override, cache_root, version, offline)?;
let distro_path = resolve_distro_path(
distro_name,
distro_file_override,
cache_root,
version,
offline,
)?;
let t0 = Instant::now();
let meta_path = ver_dir.join("bundle-meta.json");
let initrd_path = ver_dir.join("initrd.bin");
let datadisk_path = ver_dir.join("datadisk.kwsparse.gz");
let cached_meta: Option<BundleMeta> = fs::read_to_string(&meta_path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok());
let bundle_sha = if bundle_override.is_none()
&& version == DEFAULT_UNKERNEL_VERSION
&& cached_meta
.as_ref()
.is_some_and(|m| m.bundle_sha256 == DEFAULT_BUNDLE_SHA256)
{
DEFAULT_BUNDLE_SHA256.to_string()
} else {
sha256_file(&bundle_path)?
};
let (smp_sha, initrd, datadisk_template, cmdline, unpacked_smp) = match cached_meta {
Some(m)
if !rebuild_cache
&& m.bundle_sha256 == bundle_sha
&& initrd_path.exists()
&& datadisk_path.exists() =>
{
let initrd = fs::read(&initrd_path)?;
let datadisk_template = fs::read(&datadisk_path)?;
(m.smp_sha256, initrd, datadisk_template, m.cmdline, None)
}
_ => {
let bundle_bytes = fs::read(&bundle_path)
.with_context(|| format!("read {}", bundle_path.display()))?;
let unpacked = unpack_smp_bundle(&bundle_bytes)?;
let smp_sha = sha256_hex(&unpacked.smp_wasm);
fs::write(&initrd_path, &unpacked.initrd)?;
fs::write(&datadisk_path, &unpacked.datadisk)?;
let meta = BundleMeta {
bundle_sha256: bundle_sha.clone(),
smp_sha256: smp_sha.clone(),
cmdline: unpacked.cmdline.clone(),
};
fs::write(&meta_path, serde_json::to_vec_pretty(&meta)?)?;
(
smp_sha,
unpacked.initrd,
unpacked.datadisk,
unpacked.cmdline,
Some(unpacked.smp_wasm),
)
}
};
let cwasm_name = format!(
"unkernel-smp-{}-wt48-mg1-{}-ep{}.cwasm",
&smp_sha[..12],
std::env::consts::ARCH,
if epoch_enabled { 1 } else { 0 }
);
let cwasm_path = ver_dir.join(cwasm_name);
let (module, from_cwasm_cache) = if !rebuild_cache && cwasm_path.exists() {
match unsafe { Module::deserialize_file(engine, &cwasm_path) } {
Ok(m) => (m, true),
Err(_) => {
let smp_bytes = match unpacked_smp {
Some(b) => b,
None => {
let bundle_bytes = fs::read(&bundle_path)?;
unpack_smp_bundle(&bundle_bytes)?.smp_wasm
}
};
let smp_bytes = crate::kwpatch::ensure_mutable_globals_exported(&smp_bytes)?;
let m = Module::new(engine, &smp_bytes)?;
if let Ok(serialized) = m.serialize() {
let tmp = cwasm_path.with_extension("tmp");
if fs::write(&tmp, serialized).is_ok() {
let _ = replace_file(&tmp, &cwasm_path);
}
}
(m, false)
}
}
} else {
let smp_bytes = match unpacked_smp {
Some(b) => b,
None => {
let bundle_bytes = fs::read(&bundle_path)?;
unpack_smp_bundle(&bundle_bytes)?.smp_wasm
}
};
let smp_bytes = crate::kwpatch::ensure_mutable_globals_exported(&smp_bytes)?;
let m = Module::new(engine, &smp_bytes)?;
if let Ok(serialized) = m.serialize() {
let tmp = cwasm_path.with_extension("tmp");
if fs::write(&tmp, serialized).is_ok() {
let _ = replace_file(&tmp, &cwasm_path);
}
}
(m, false)
};
let load_ms = t0.elapsed().as_millis() as u64;
Ok(ResolvedArtifacts {
module,
from_cwasm_cache,
load_ms,
initrd,
datadisk_template,
cmdline,
distro_path,
cache_dir: ver_dir,
cwasm_path,
})
}