1use crate::kwpatch::unpack_smp_bundle;
5use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7use std::fs::{self, File};
8use std::io::{Read, Write};
9use std::path::{Path, PathBuf};
10use std::time::Instant;
11use wasmtime::error::Context;
12use wasmtime::{Engine, Module, Result, bail, format_err};
13
14pub const DEFAULT_UNKERNEL_VERSION: &str = "0.3.0-261130-3ef745b";
16
17pub const DEFAULT_BUNDLE_SHA256: &str =
19 "a0a4efd7c0d321fab7fb1d287659550586fc7aad0cd41c645fe0e3f090ba12ab";
20
21pub const DEFAULT_SMP_SHA256: &str =
23 "c161c121f1fad75a4323f94025ef86c2d343e3248d4a9b0ee198150b3e55ceec";
24
25pub const DEFAULT_ALPINE_SHA256: &str =
27 "b7f5c84d35dbcb999a8b59e57928fc3411e5f153d7cbf8422dd8efee60da15af";
28
29const RELEASE_REPO: &str = "pithings/unkernel";
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32struct BundleMeta {
33 bundle_sha256: String,
34 smp_sha256: String,
35 cmdline: String,
36}
37
38#[derive(Debug, Clone, Deserialize)]
39struct DistroIndex {
40 distros: Vec<DistroEntry>,
41}
42
43#[derive(Debug, Clone, Deserialize)]
44struct DistroEntry {
45 name: String,
46 file: String,
47 size: u64,
48 sha256: String,
49}
50
51pub struct ResolvedArtifacts {
53 pub module: Module,
54 pub from_cwasm_cache: bool,
55 pub load_ms: u64,
56 pub initrd: Vec<u8>,
57 pub datadisk_template: Vec<u8>,
58 pub cmdline: String,
59 pub distro_path: Option<PathBuf>,
60 pub cache_dir: PathBuf,
61 pub cwasm_path: PathBuf,
62}
63
64pub fn default_cache_dir() -> PathBuf {
66 if let Ok(dir) = std::env::var("UNKERNEL_RS_CACHE_DIR")
67 && !dir.is_empty()
68 {
69 return PathBuf::from(dir);
70 }
71 if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
72 && Path::new(&xdg).is_absolute()
73 {
74 return PathBuf::from(xdg).join("unkernel-rs");
75 }
76 if let Ok(home) = std::env::var("HOME")
77 && !home.is_empty()
78 {
79 return PathBuf::from(home).join(".cache").join("unkernel-rs");
80 }
81 if let Ok(local_app_data) = std::env::var("LOCALAPPDATA")
82 && !local_app_data.is_empty()
83 {
84 return PathBuf::from(local_app_data)
85 .join("unkernel-rs")
86 .join("cache");
87 }
88 if let Ok(profile) = std::env::var("USERPROFILE")
89 && !profile.is_empty()
90 {
91 return PathBuf::from(profile).join(".cache").join("unkernel-rs");
92 }
93 std::env::temp_dir().join("unkernel-rs-cache")
94}
95
96fn replace_file(src: &Path, dest: &Path) -> std::io::Result<()> {
97 #[cfg(windows)]
98 {
99 if dest.exists() {
100 let _ = fs::remove_file(dest);
101 }
102 }
103 fs::rename(src, dest)
104}
105
106fn upstream_unkernel_cache_dir(version: &str) -> Option<PathBuf> {
107 if let Ok(dir) = std::env::var("UNKERNEL_CACHE_DIR")
108 && !dir.is_empty()
109 {
110 return Some(PathBuf::from(dir).join(format!("v{version}")));
111 }
112 if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
113 && Path::new(&xdg).is_absolute()
114 {
115 return Some(
116 PathBuf::from(xdg)
117 .join("unkernel")
118 .join(format!("v{version}")),
119 );
120 }
121 std::env::var("HOME")
122 .ok()
123 .filter(|h| !h.is_empty())
124 .map(|h| {
125 PathBuf::from(h)
126 .join(".cache")
127 .join("unkernel")
128 .join(format!("v{version}"))
129 })
130}
131
132pub fn sha256_hex(bytes: &[u8]) -> String {
133 Sha256::digest(bytes)
134 .iter()
135 .map(|b| format!("{b:02x}"))
136 .collect()
137}
138
139pub fn sha256_file(path: &Path) -> Result<String> {
140 let mut f = File::open(path).with_context(|| format!("open {}", path.display()))?;
141 let mut hasher = Sha256::new();
142 let mut buf = [0u8; 64 * 1024];
143 loop {
144 let n = f.read(&mut buf)?;
145 if n == 0 {
146 break;
147 }
148 hasher.update(&buf[..n]);
149 }
150 Ok(hasher
151 .finalize()
152 .iter()
153 .map(|b| format!("{b:02x}"))
154 .collect())
155}
156
157fn download_to_file(urls: &[String], dest: &Path, expected_sha256: Option<&str>) -> Result<()> {
158 if let Some(parent) = dest.parent() {
159 fs::create_dir_all(parent).with_context(|| format!("mkdir {}", parent.display()))?;
160 }
161 let tmp = dest.with_extension("tmp");
162 let mut last_err = None;
163
164 for url in urls {
165 match ureq::get(url).set("User-Agent", "unkernel-rs/0.1").call() {
166 Ok(resp) => {
167 let mut reader = resp.into_reader();
168 let mut out =
169 File::create(&tmp).with_context(|| format!("create {}", tmp.display()))?;
170 let mut hasher = Sha256::new();
171 let mut buf = [0u8; 64 * 1024];
172 loop {
173 let n = reader.read(&mut buf)?;
174 if n == 0 {
175 break;
176 }
177 out.write_all(&buf[..n])?;
178 hasher.update(&buf[..n]);
179 }
180 out.flush()?;
181 drop(out);
182
183 let got: String = hasher
184 .finalize()
185 .iter()
186 .map(|b| format!("{b:02x}"))
187 .collect();
188 if let Some(expected) = expected_sha256
189 && got != expected
190 {
191 let _ = fs::remove_file(&tmp);
192 last_err = Some(format!(
193 "{url}: SHA-256 mismatch (got {got}, expected {expected})"
194 ));
195 continue;
196 }
197 replace_file(&tmp, dest)
198 .with_context(|| format!("rename {} -> {}", tmp.display(), dest.display()))?;
199 return Ok(());
200 }
201 Err(e) => {
202 let _ = fs::remove_file(&tmp);
203 last_err = Some(format!("{url}: {e}"));
204 }
205 }
206 }
207
208 bail!(
209 "failed to download {}: {}",
210 dest.display(),
211 last_err.unwrap_or_else(|| "no URLs".into())
212 )
213}
214
215pub fn resolve_bundle_path(
218 explicit: Option<&Path>,
219 cache_root: &Path,
220 version: &str,
221 offline: bool,
222) -> Result<PathBuf> {
223 if let Some(p) = explicit {
224 if !p.exists() {
225 bail!("bundle file not found: {}", p.display());
226 }
227 return Ok(p.to_path_buf());
228 }
229 if let Ok(env_path) = std::env::var("UNKERNEL_BUNDLE_PATH")
230 && !env_path.is_empty()
231 {
232 let p = PathBuf::from(env_path);
233 if p.exists() {
234 return Ok(p);
235 }
236 }
237
238 let ver_dir = cache_root.join(format!("v{version}"));
239 let cached = ver_dir.join("unkernel.wasm");
240 let expected_sha = if version == DEFAULT_UNKERNEL_VERSION {
241 Some(DEFAULT_BUNDLE_SHA256)
242 } else {
243 None
244 };
245
246 if cached.exists() {
247 if let Some(exp) = expected_sha {
248 if sha256_file(&cached).ok().as_deref() == Some(exp) {
249 return Ok(cached);
250 }
251 } else {
252 return Ok(cached);
253 }
254 }
255
256 if offline {
257 bail!(
258 "unkernel.wasm not cached at {} and --offline is set (pass --bundle PATH or run `unkernel-rs fetch`)",
259 cached.display()
260 );
261 }
262
263 let urls = vec![
264 format!("https://cdn.jsdelivr.net/npm/unkernel@{version}/dist/unkernel.wasm"),
265 format!("https://unpkg.com/unkernel@{version}/dist/unkernel.wasm"),
266 ];
267 download_to_file(&urls, &cached, expected_sha)?;
268 Ok(cached)
269}
270
271pub fn resolve_distro_path(
273 distro_name: Option<&str>,
274 explicit_file: Option<&Path>,
275 cache_root: &Path,
276 version: &str,
277 offline: bool,
278) -> Result<Option<PathBuf>> {
279 if let Some(p) = explicit_file {
280 if !p.exists() {
281 bail!("distro image not found: {}", p.display());
282 }
283 return Ok(Some(p.to_path_buf()));
284 }
285 let Some(name) = distro_name else {
286 return Ok(None);
287 };
288 if name.is_empty() || name == "none" {
289 return Ok(None);
290 }
291 if !name
292 .bytes()
293 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
294 {
295 bail!("invalid distro name {name:?} (expected [a-z0-9]+)");
296 }
297
298 let ver_dir = cache_root.join(format!("v{version}"));
299 let candidate_names = [format!("{name}.erofs"), format!("{name}.ext4")];
300
301 let mut search_dirs = vec![ver_dir.clone()];
303 if let Some(up) = upstream_unkernel_cache_dir(version) {
304 search_dirs.push(up);
305 }
306
307 let pinned_alpine = name == "alpine" && version == DEFAULT_UNKERNEL_VERSION;
308 for dir in &search_dirs {
309 for fname in &candidate_names {
310 let p = dir.join(fname);
311 if p.exists() {
312 if pinned_alpine && fname == "alpine.erofs" {
313 if sha256_file(&p).ok().as_deref() == Some(DEFAULT_ALPINE_SHA256) {
314 return Ok(Some(p));
315 }
316 } else {
317 return Ok(Some(p));
318 }
319 }
320 }
321 }
322
323 if offline {
324 bail!(
325 "distro {name:?} not cached in {} and --offline is set (pass --distro-file PATH or run `unkernel-rs fetch`)",
326 ver_dir.display()
327 );
328 }
329
330 let base = format!("https://github.com/{RELEASE_REPO}/releases/download/v{version}/");
331 let index_url = format!("{base}distros.json");
332 let index_text = ureq::get(&index_url)
333 .set("User-Agent", "unkernel-rs/0.1")
334 .call()
335 .with_context(|| format!("GET {index_url}"))?
336 .into_string()
337 .with_context(|| format!("read {index_url}"))?;
338 let index: DistroIndex =
339 serde_json::from_str(&index_text).with_context(|| format!("parse {index_url}"))?;
340
341 let entry = index
342 .distros
343 .into_iter()
344 .find(|d| d.name == name)
345 .ok_or_else(|| format_err!("distro {name:?} not found in {index_url}"))?;
346
347 if entry.file.contains('/') || entry.file.contains('\\') || entry.file.contains("..") {
348 bail!("unsafe distro filename in index: {:?}", entry.file);
349 }
350
351 let dest = ver_dir.join(&entry.file);
352 let img_url = format!("{base}{}", entry.file);
353 download_to_file(&[img_url], &dest, Some(&entry.sha256))?;
354 let meta = fs::metadata(&dest)?;
355 if meta.len() != entry.size {
356 let _ = fs::remove_file(&dest);
357 bail!(
358 "downloaded {} size {} != expected {}",
359 dest.display(),
360 meta.len(),
361 entry.size
362 );
363 }
364 Ok(Some(dest))
365}
366
367#[allow(clippy::too_many_arguments)]
369pub fn prepare_artifacts(
370 engine: &Engine,
371 bundle_override: Option<&Path>,
372 distro_name: Option<&str>,
373 distro_file_override: Option<&Path>,
374 cache_root: &Path,
375 version: &str,
376 offline: bool,
377 epoch_enabled: bool,
378 rebuild_cache: bool,
379) -> Result<ResolvedArtifacts> {
380 let ver_dir = cache_root.join(format!("v{version}"));
381 fs::create_dir_all(&ver_dir).with_context(|| format!("mkdir {}", ver_dir.display()))?;
382
383 let bundle_path = resolve_bundle_path(bundle_override, cache_root, version, offline)?;
384 let distro_path = resolve_distro_path(
385 distro_name,
386 distro_file_override,
387 cache_root,
388 version,
389 offline,
390 )?;
391
392 let t0 = Instant::now();
393 let meta_path = ver_dir.join("bundle-meta.json");
394 let initrd_path = ver_dir.join("initrd.bin");
395 let datadisk_path = ver_dir.join("datadisk.kwsparse.gz");
396
397 let cached_meta: Option<BundleMeta> = fs::read_to_string(&meta_path)
399 .ok()
400 .and_then(|s| serde_json::from_str(&s).ok());
401
402 let bundle_sha = if bundle_override.is_none()
403 && version == DEFAULT_UNKERNEL_VERSION
404 && cached_meta
405 .as_ref()
406 .is_some_and(|m| m.bundle_sha256 == DEFAULT_BUNDLE_SHA256)
407 {
408 DEFAULT_BUNDLE_SHA256.to_string()
409 } else {
410 sha256_file(&bundle_path)?
411 };
412
413 let (smp_sha, initrd, datadisk_template, cmdline, unpacked_smp) = match cached_meta {
414 Some(m)
415 if !rebuild_cache
416 && m.bundle_sha256 == bundle_sha
417 && initrd_path.exists()
418 && datadisk_path.exists() =>
419 {
420 let initrd = fs::read(&initrd_path)?;
421 let datadisk_template = fs::read(&datadisk_path)?;
422 (m.smp_sha256, initrd, datadisk_template, m.cmdline, None)
423 }
424 _ => {
425 let bundle_bytes = fs::read(&bundle_path)
426 .with_context(|| format!("read {}", bundle_path.display()))?;
427 let unpacked = unpack_smp_bundle(&bundle_bytes)?;
428 let smp_sha = sha256_hex(&unpacked.smp_wasm);
429 fs::write(&initrd_path, &unpacked.initrd)?;
430 fs::write(&datadisk_path, &unpacked.datadisk)?;
431 let meta = BundleMeta {
432 bundle_sha256: bundle_sha.clone(),
433 smp_sha256: smp_sha.clone(),
434 cmdline: unpacked.cmdline.clone(),
435 };
436 fs::write(&meta_path, serde_json::to_vec_pretty(&meta)?)?;
437 (
438 smp_sha,
439 unpacked.initrd,
440 unpacked.datadisk,
441 unpacked.cmdline,
442 Some(unpacked.smp_wasm),
443 )
444 }
445 };
446
447 let cwasm_name = format!(
448 "unkernel-smp-{}-wt48-mg1-{}-ep{}.cwasm",
449 &smp_sha[..12],
450 std::env::consts::ARCH,
451 if epoch_enabled { 1 } else { 0 }
452 );
453 let cwasm_path = ver_dir.join(cwasm_name);
454
455 let (module, from_cwasm_cache) = if !rebuild_cache && cwasm_path.exists() {
456 match unsafe { Module::deserialize_file(engine, &cwasm_path) } {
458 Ok(m) => (m, true),
459 Err(_) => {
460 let smp_bytes = match unpacked_smp {
462 Some(b) => b,
463 None => {
464 let bundle_bytes = fs::read(&bundle_path)?;
465 unpack_smp_bundle(&bundle_bytes)?.smp_wasm
466 }
467 };
468 let smp_bytes = crate::kwpatch::ensure_mutable_globals_exported(&smp_bytes)?;
469 let m = Module::new(engine, &smp_bytes)?;
470 if let Ok(serialized) = m.serialize() {
471 let tmp = cwasm_path.with_extension("tmp");
472 if fs::write(&tmp, serialized).is_ok() {
473 let _ = replace_file(&tmp, &cwasm_path);
474 }
475 }
476 (m, false)
477 }
478 }
479 } else {
480 let smp_bytes = match unpacked_smp {
481 Some(b) => b,
482 None => {
483 let bundle_bytes = fs::read(&bundle_path)?;
484 unpack_smp_bundle(&bundle_bytes)?.smp_wasm
485 }
486 };
487 let smp_bytes = crate::kwpatch::ensure_mutable_globals_exported(&smp_bytes)?;
488 let m = Module::new(engine, &smp_bytes)?;
489 if let Ok(serialized) = m.serialize() {
490 let tmp = cwasm_path.with_extension("tmp");
491 if fs::write(&tmp, serialized).is_ok() {
492 let _ = replace_file(&tmp, &cwasm_path);
493 }
494 }
495 (m, false)
496 };
497
498 let load_ms = t0.elapsed().as_millis() as u64;
499 Ok(ResolvedArtifacts {
500 module,
501 from_cwasm_cache,
502 load_ms,
503 initrd,
504 datadisk_template,
505 cmdline,
506 distro_path,
507 cache_dir: ver_dir,
508 cwasm_path,
509 })
510}