use std::fs; use std::io::{BufRead, BufReader, Write}; use std::net::TcpListener; use std::ops::ControlFlow; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use arena_tracker_core::{ Error, UpdateChannel, download_update, restart_to_update, update_at_launch, verify_release, }; use base64::prelude::{BASE64_STANDARD, Engine}; use ring::digest; use ring::signature::{Ed25519KeyPair, KeyPair}; use serde_json::{Value, json}; use tempfile::TempDir; const PACKAGE: &str = "ArenaTracker-1.0.0-stable-full.nupkg"; /// A stable 1.0.0 release folder; `signature` None leaves the signature file out. fn release(manifest: &[u8], signature: Option<&[u8]>, package: &[u8]) -> TempDir { let dir = tempfile::tempdir().unwrap(); fs::write(dir.path().join("release-stable.json"), manifest).unwrap(); if let Some(signature) = signature { fs::write(dir.path().join("release-stable.sig"), signature).unwrap(); } fs::write(dir.path().join(PACKAGE), package).unwrap(); dir } /// The files of one Release: (name, bytes). Betas are published as pre-releases. struct Published { prerelease: bool, files: Vec<(String, Vec)>, } /// A release of `version` signed by `key`, following the package contract of #57. fn publish(key: &Ed25519KeyPair, channel: &str, version: &str) -> Published { let package = format!("ArenaTracker-{version}-{channel}-full.nupkg"); let bytes = format!("package {version}").into_bytes(); let manifest = serde_json::to_vec(&json!({ "app": "ArenaTracker", "target": "win-x64", "channel": channel, "version": version, "commit": "c".repeat(40), "package": package, "sha256": BASE64_STANDARD.encode(digest::digest(&digest::SHA256, &bytes)), })) .unwrap(); Published { prerelease: channel == "beta", files: vec![ ( format!("release-{channel}.sig"), key.sign(&manifest).as_ref().to_vec(), ), (format!("release-{channel}.json"), manifest), (package, bytes), ], } } /// Serves `releases` like Gitea's API and returns its releases URL and a count of package /// downloads. With `cut`, a package response stops halfway through its announced length. fn serve(releases: Vec, cut: bool) -> (String, Arc) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", listener.local_addr().unwrap()); let downloads = Arc::new(AtomicUsize::new(0)); let (url, count) = (base.clone(), downloads.clone()); thread::spawn(move || { for stream in listener.incoming() { let mut stream = stream.unwrap(); let mut reader = BufReader::new(&stream); let mut line = String::new(); reader.read_line(&mut line).unwrap(); let path = line.split(' ').nth(1).unwrap().to_string(); // The headers end with an empty line. while !matches!(reader.read_line(&mut String::new()), Ok(0..=2)) {} let (body, cut) = if let Some(query) = path.strip_prefix("/releases?") { let prerelease = query.contains("pre-release=true"); let list: Vec = releases .iter() .enumerate() .filter(|(_, release)| release.prerelease == prerelease) .map(|(i, release)| { let assets: Vec = release .files .iter() .map(|(name, _)| { let link = format!("{url}/files/{i}/{name}"); json!({ "name": name, "browser_download_url": link }) }) .collect(); json!({ "tag_name": format!("t{i}"), "prerelease": prerelease, "assets": assets }) }) .collect(); (serde_json::to_vec(&list).unwrap(), false) } else { let (i, name) = path["/files/".len()..].split_once('/').unwrap(); let files = &releases[i.parse::().unwrap()].files; let (_, bytes) = files.iter().find(|(file, _)| file == name).unwrap(); let package = name.ends_with(".nupkg"); if package { count.fetch_add(1, Ordering::SeqCst); } (bytes.clone(), cut && package) }; let sent = if cut { &body[..body.len() / 2] } else { &body }; let head = format!( "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() ); let _ = stream .write_all(head.as_bytes()) .and_then(|()| stream.write_all(sent)); } }); (format!("{base}/releases"), downloads) } /// A releases URL nothing listens on. fn unreachable() -> String { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); format!("http://{}/releases", listener.local_addr().unwrap()) } fn key() -> Ed25519KeyPair { Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap() } /// The names left in the updates folder. fn kept(dir: &Path) -> Vec { let mut names: Vec = fs::read_dir(dir) .unwrap() .map(|entry| entry.unwrap().file_name().into_string().unwrap()) .collect(); names.sort(); names } /// Keeps `version` of `channel` in `dir` as a finished download would, and returns its package. fn keep(dir: &Path, key: &Ed25519KeyPair, channel: &str, version: &str) -> PathBuf { let folder = dir.join(format!("{channel}-{version}")); fs::create_dir(&folder).unwrap(); for (name, bytes) in publish(key, channel, version).files { fs::write(folder.join(name), bytes).unwrap(); } folder.join(format!("ArenaTracker-{version}-{channel}-full.nupkg")) } type Start<'a> = &'a mut dyn FnMut(&Path) -> std::io::Result; type Outcome<'a> = &'a mut dyn FnMut(u32) -> Option; fn never_started(_: &Path) -> std::io::Result { panic!("the installer must not start") } fn no_installer(_: u32) -> Option { panic!("no installer was started") } /// Records each package handed to the installer, which gets process id `pid`. fn recording(started: &mut Vec, pid: u32) -> impl FnMut(&Path) -> std::io::Result { move |package| { started.push(package.to_owned()); Ok(pid) } } type Launch = ControlFlow<(), Option>; /// The installer replaces this version and opens the app. fn applying(launch: &Launch) -> bool { matches!(launch, ControlFlow::Break(())) } fn loads_quietly(launch: &Launch) -> bool { matches!(launch, ControlFlow::Continue(None)) } fn reports_failed(launch: &Launch, version: &str) -> bool { matches!(launch, ControlFlow::Continue(Some(Error::UpdateFailed(failed))) if failed == version) } #[path = "update_package/downloads.rs"] mod downloads; #[path = "update_package/launch.rs"] mod launch; #[path = "update_package/verification.rs"] mod verification;