windows: the component manager, verified programs, a Wine test

components.json pins sing-box, XRay, Flowseal's zapret, bol-van's
winws2 bundle with nfqws2-keenetic's strategies, and tg-ws-proxy (built
with the release): release assets by archive hash, commit snapshots by
the hash of every file taken. The service installs them (admin only),
staged and swapped in, refusing archive paths that leave the directory,
and checks each program against the hashes recorded at install before
running it. stage-components does the same for building a release.

The state root is created with its protected descriptor in one call,
or, existing, checked through a handle that does not follow links.

tools/wine-e2e.sh runs the Windows build under Wine: the service, the
named pipe, impersonation, the component check, rendering and the
supervisor all work; Wine lacks an iphlpapi call sing-box needs, so
proxying itself needs real Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 23:33:55 +03:00
1 parent b878dd93db
commit 68b496cafa
10 files changed
+709 -81

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
//! 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<Vec<u8>> {
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) {
if 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<usize> {
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::<Vec<_>>().join(", "));
}
}
Ok(n)
}
/// The version of `name` installed under `bin`.
pub fn installed_version(bin: &Path, name: &str) -> Option<String> {
std::fs::read_to_string(bin.join(name).join(".version")).ok().map(|s| s.trim().to_owned())
}
/// Puts `comp` into `bin\<name>\`: 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<String, String>) -> 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\<component>\`) still has the hash it was installed with.
pub fn verify(component_dir: &Path, program: &Path) -> Result<()> {
let files: std::collections::BTreeMap<String, String> = 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\<name>\`, 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 comp.bundled || (!only.is_empty() && !only.contains(name)) {
continue;
}
println!("{name} {}", comp.version);
install(to, name, comp, &[fetch::Route::Direct], cache).await.with_context(|| format!("staging {name}"))?;
}
Ok(())
}