//! Installing components: download, verify, extract, swap in. use std::io::Read; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; use ps_core::components::{Component, Source}; use sha2::{Digest, Sha256}; use crate::fetch; fn hex(data: &[u8]) -> String { let mut h = Sha256::new(); h.update(data); h.finalize().iter().map(|b| format!("{b:02x}")).collect() } /// The archive of `src`, from `cache` if it holds a verified copy, else downloaded there. pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Result> { std::fs::create_dir_all(cache)?; let key = hex(src.url.as_bytes()); let cached = cache.join(&key[..32]); if let Ok(data) = std::fs::read(&cached) && src.sha256.as_ref().is_none_or(|want| hex(&data) == *want) { return Ok(data); } let mut last = None; for route in routes { match fetch::get(&src.url, route, 512 * 1024 * 1024).await { Ok(data) => { if let Some(want) = &src.sha256 { let got = hex(&data); if got != *want { bail!("{} has SHA-256 {got}, not the pinned {want}", src.url); } } crate::paths::write_atomic(&cached, &data)?; return Ok(data); } Err(e) => last = Some(e), } } Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")).context(format!("fetching {}", src.url))) } /// Extracts what `src` takes from `data` into `dest`, verifying each file it pins. pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result { let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?; let mut seen = std::collections::BTreeSet::new(); let mut n = 0; for i in 0..zip.len() { let mut entry = zip.by_index(i)?; let name = entry.name().to_owned(); let Some(rel) = src.place(&name) else { continue }; let mut body = Vec::with_capacity(entry.size() as usize); entry.read_to_end(&mut body)?; if let Some(files) = &src.files { let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(&name); let want = &files[in_archive]; let got = hex(&body); if got != *want { bail!("{in_archive} has SHA-256 {got}, not the pinned {want}"); } seen.insert(in_archive.to_owned()); } let out = dest.join(&rel); if let Some(parent) = out.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(&out, &body).with_context(|| format!("writing {}", out.display()))?; n += 1; } if let Some(files) = &src.files { let missing: Vec<&String> = files.keys().filter(|f| !seen.contains(*f)).collect(); if !missing.is_empty() { bail!("the archive lacks {}", missing.iter().map(|s| s.as_str()).collect::>().join(", ")); } } Ok(n) } /// The version of `name` installed under `bin`. pub fn installed_version(bin: &Path, name: &str) -> Option { std::fs::read_to_string(bin.join(name).join(".version")).ok().map(|s| s.trim().to_owned()) } /// Puts `comp` into `bin\\`: staged next to it, then swapped in whole, so a failure /// leaves what was there. pub async fn install(bin: &Path, name: &str, comp: &Component, routes: &[fetch::Route], cache: &Path) -> Result<()> { if comp.bundled { bail!("{name} comes with the release and is not fetched on its own"); } let staging = bin.join(format!("{name}.staging")); let _ = std::fs::remove_dir_all(&staging); std::fs::create_dir_all(&staging)?; for src in &comp.sources { let data = archive(src, routes, cache).await?; let n = extract(src, &data, &staging).with_context(|| format!("unpacking {}", src.url))?; if n == 0 { bail!("nothing in {} matched", src.url); } } std::fs::write(staging.join(".version"), &comp.version)?; // What was installed, by hash: checked again before anything from it runs. let mut files = std::collections::BTreeMap::new(); record(&staging, &staging, &mut files)?; std::fs::write(staging.join(".files.json"), serde_json::to_vec_pretty(&files)?)?; swap(bin, name, &staging) } fn record(root: &Path, dir: &Path, out: &mut std::collections::BTreeMap) -> Result<()> { for entry in std::fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); let ty = entry.file_type()?; if ty.is_dir() { record(root, &path, out)?; } else if ty.is_file() { let rel = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/"); if !rel.starts_with('.') { out.insert(rel, hex(&std::fs::read(&path)?)); } } } Ok(()) } /// Whether `program` (below `bin\\`) still has the hash it was installed with. pub fn verify(component_dir: &Path, program: &Path) -> Result<()> { let files: std::collections::BTreeMap = serde_json::from_slice( &std::fs::read(component_dir.join(".files.json")).context("no record of what was installed (reinstall it)")?, )?; let rel = program.strip_prefix(component_dir)?.to_string_lossy().replace('\\', "/"); let want = files.get(&rel).with_context(|| format!("{rel} was not installed with the component"))?; let got = hex(&std::fs::read(program)?); if got != *want { bail!("{} has changed since it was installed (SHA-256 {got}); reinstall the component", program.display()); } Ok(()) } fn swap(bin: &Path, name: &str, staging: &Path) -> Result<()> { let target = bin.join(name); let old: PathBuf = bin.join(format!("{name}.old")); let _ = std::fs::remove_dir_all(&old); if target.exists() { std::fs::rename(&target, &old).with_context(|| format!("moving the old {name} aside (is it running?)"))?; } if let Err(e) = std::fs::rename(staging, &target) { let _ = std::fs::rename(&old, &target); return Err(e).context(format!("putting {name} in place")); } let _ = std::fs::remove_dir_all(&old); Ok(()) } /// For the release: every component that has sources, into `to\\`, with a cache. pub async fn stage(to: &Path, cache: &Path, only: &[String]) -> Result<()> { let manifest = ps_core::components::manifest(); std::fs::create_dir_all(to)?; for (name, comp) in &manifest.components { if !only.is_empty() && !only.contains(name) { continue; } if comp.bundled { // Built beside this (tools/build-*.sh): recorded as an install records. let dir = to.join(name); match installed_version(to, name) { Some(v) if v == comp.version => { let mut files = std::collections::BTreeMap::new(); record(&dir, &dir, &mut files)?; std::fs::write(dir.join(".files.json"), serde_json::to_vec_pretty(&files)?)?; println!("{name} {} (built)", comp.version); } Some(v) => bail!("{name} in {} is {v}, the manifest wants {}", to.display(), comp.version), None => println!("{name}: not built (tools/build-{name}.sh); left out"), } continue; } println!("{name} {}", comp.version); install(to, name, comp, &[fetch::Route::Direct], cache).await.with_context(|| format!("staging {name}"))?; } Ok(()) } /// Where the release's components are, next to the running program, if it runs from a /// place only administrators can change (on Windows: Program Files, where `install` puts it). pub fn bundled_components_dir() -> Option { let exe = std::env::current_exe().ok()?; let dir = exe.parent()?.join("components"); if !dir.is_dir() { return None; } #[cfg(windows)] { let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from)?; if !exe.starts_with(&program_files) { tracing::warn!("not taking components from {}: the service runs outside Program Files", dir.display()); return None; } } Some(dir) } fn copy_tree(from: &Path, to: &Path) -> Result<()> { std::fs::create_dir_all(to)?; for entry in std::fs::read_dir(from)? { let entry = entry?; let ty = entry.file_type()?; let dest = to.join(entry.file_name()); if ty.is_dir() { copy_tree(&entry.path(), &dest)?; } else if ty.is_file() { std::fs::copy(entry.path(), &dest)?; } } Ok(()) } /// Every file `.files.json` names, with its hash. fn verify_all(dir: &Path) -> Result<()> { let files: std::collections::BTreeMap = serde_json::from_slice(&std::fs::read(dir.join(".files.json")).context("no .files.json")?)?; for (rel, want) in files { if !ps_core::components::safe_relative(&rel) { bail!("{rel} is not a plain path"); } let got = hex(&std::fs::read(dir.join(&rel)).with_context(|| format!("{rel} is missing"))?); if got != want { bail!("{rel} does not match its recorded hash"); } } Ok(()) } /// Copies each component of `from` (the release's) into `bin` when `bin` lacks it or holds /// another version: staged, verified file by file, swapped in. What it did, as lines. pub fn seed(from: &Path, bin: &Path) -> Vec { let manifest = ps_core::components::manifest(); let mut notes = Vec::new(); for (name, comp) in &manifest.components { let src = from.join(name); if installed_version(from, name).as_deref() != Some(comp.version.as_str()) { continue; } if installed_version(bin, name).as_deref() == Some(comp.version.as_str()) { continue; } let staging = bin.join(format!("{name}.staging")); let _ = std::fs::remove_dir_all(&staging); let result = copy_tree(&src, &staging).and_then(|()| verify_all(&staging)).and_then(|()| swap(bin, name, &staging)); match result { Ok(()) => notes.push(format!("installed {name} {} from the release", comp.version)), Err(e) => { let _ = std::fs::remove_dir_all(&staging); notes.push(format!("could not install {name} from the release: {e:#}")); } } } notes }