Merge pull request #440 from ludovic111/feat/launcher-owner-download

Launcher: download Minecraft from Mojang for a signed-in owner
This commit is contained in:
Ludovic Marie
2026-10-16 00:53:49 +02:00
committed by GitHub
8 changed files with 591 additions and 45 deletions
+6
View File
@@ -422,6 +422,12 @@ fn profile(ep: &Endpoints, token: &str) -> Result<Account, String> {
})
}
/// Whether the signed-in account still owns Minecraft: Java Edition, asked again now: the
/// launcher downloads the game's files only for an owner (sources.rs).
pub fn owns_minecraft(ep: &Endpoints, secrets: &Secrets) -> Result<bool, String> {
owns_game(ep, &secrets.minecraft_token)
}
/// What the keychain keeps for one account.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Secrets {
+15
View File
@@ -275,6 +275,21 @@ fn refresh_only_when_the_token_runs_out() {
);
}
#[test]
fn ownership_is_asked_again_with_the_saved_token() {
let secrets = |token: &str| Secrets {
refresh_token: "ms-refresh-1".into(),
minecraft_token: token.into(),
minecraft_expires_at: now() + 7200,
xuid: None,
};
let (m, ep) = mock(|_| {});
assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(true));
assert_eq!(m.lock().unwrap().log.len(), 1);
let (_, ep) = mock(|m| m.owns_game = false);
assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(false));
}
#[test]
fn refusals_have_messages() {
let tokens = || MsTokens {
+64 -5
View File
@@ -1,7 +1,7 @@
//! Everything that is not UI: GitHub, installs, resource preparation, the game's processes and
//! updates. The GUI, the CLI and the MCP server all go through this module. Functions here
//! block; the GUI runs them on threads and reads their messages.
use crate::sources;
use crate::{account, mojang, sources};
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
@@ -642,6 +642,54 @@ fn preparer_binary(dir: &Path) -> Option<PathBuf> {
binary.is_file().then_some(binary)
}
/// Downloads the pinned version from Mojang into `dir` when the signed-in account owns
/// Minecraft (asked again now), else says what signing in would do, as the last line of the
/// not-found error.
fn download_for_owner(
pins: &sources::Pins,
dir: &Path,
fetch: sources::Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let owner = (|| -> Result<Option<(String, bool)>, String> {
let ep = account::Endpoints::live();
let mut accounts = account::Accounts::load();
let Some((a, secrets)) = account::session_for_launch(&ep, account::store(), &mut accounts)?
else {
return Ok(None);
};
Ok(Some((a.name, account::owns_minecraft(&ep, &secrets)?)))
})();
match owner {
Ok(Some((name, true))) => {
log(format!(
"{name} owns Minecraft: downloading {v} from Mojang"
));
let os = match sources::Os::current() {
sources::Os::Linux => "linux",
sources::Os::MacOs => "osx",
sources::Os::Windows => "windows",
};
mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| {
format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}")
})
}
Ok(Some((name, false))) => Err(format!(
"\n • {name}, the signed-in account, doesn't own Minecraft: Java Edition, so Horizon \
can't download it."
)),
Ok(None) => Err(format!(
"\n • Or sign in with the Microsoft account that owns Minecraft: Horizon then \
downloads {v} from Mojang itself."
)),
Err(e) => Err(format!(
"\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \
checked: {e}"
)),
}
}
/// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same
/// steps: the player's own launcher install, the server jar from that version's own json, and
/// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder
@@ -661,9 +709,13 @@ pub fn preparer(
let pins = read_json(&dir.join("research-lock.json"))
.and_then(|lock| sources::Pins::read(&lock))
.ok_or("The version's research-lock.json doesn't pin the Minecraft files")?;
let known = sources::Folders::current()
.map(|f| sources::known_folders(sources::Os::current(), &f))
.unwrap_or_default();
let own = data_dir().join("minecraft");
let mut known = vec![("Horizon's own download", own.clone())];
known.extend(
sources::Folders::current()
.map(|f| sources::known_folders(sources::Os::current(), &f))
.unwrap_or_default(),
);
let fetch = |url: &str| -> Result<Vec<u8>, String> {
let mut body = Vec::new();
get(url)?
@@ -673,7 +725,14 @@ pub fn preparer(
Ok(body)
};
let linked = data_dir().join("linked-minecraft");
sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)?
match sources::resolve(minecraft, &pins, &known, &linked, &fetch, log)? {
sources::Resolved::Folder(dir) => dir,
sources::Resolved::NotFound(checked) => {
let not_found = sources::not_found(&version, &checked);
download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?;
own
}
}
};
let manifest = minecraft
.join("versions")
+1
View File
@@ -2,5 +2,6 @@
pub mod account;
pub mod backend;
pub mod desktop;
pub mod mojang;
pub mod sources;
pub mod telemetry;
+194
View File
@@ -0,0 +1,194 @@
//! The player's own download of the pinned version from Mojang, for a signed-in account that
//! owns Minecraft: Java Edition (#434), as other launchers get it: the version JSON, the client
//! jar, this system's libraries and the assets (the sounds), each checked against its sha1,
//! in the official launcher's layout in the launcher's data folder. sources.rs then finds them
//! there like any launcher's. Nothing of Mojang's is part of Horizon.
use crate::sources::{fetch_checked, fetch_manifest, sha1_file, write_file, Fetch, Pins};
use serde_json::Value;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::sync::Mutex;
use std::time::Duration;
const OBJECTS: &str = "https://resources.download.minecraft.net";
/// One file to download.
struct File {
url: String,
sha1: String,
path: PathBuf,
}
/// Downloads the pinned version into `dir`, `jobs` files at a time; files already there and
/// whole are kept. An asset that fails is a line in the log (the game is then partly silent),
/// anything else an error.
pub fn download(
pins: &Pins,
dir: &Path,
os: &str,
jobs: usize,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let v = &pins.version;
let versions = dir.join("versions").join(v);
let manifest = versions.join(format!("{v}.json"));
fetch_manifest(pins, &manifest, fetch, log)?;
let manifest = read_json(&manifest)?;
let client = &manifest["downloads"]["client"];
let mut game = vec![File {
url: text(client, "url")?,
sha1: pins.client_sha1.clone(),
path: versions.join(format!("{v}.jar")),
}];
let libraries = manifest["libraries"]
.as_array()
.ok_or("The version file has no libraries")?;
for library in libraries.iter().filter(|l| allowed(l, os)) {
let artifact = &library["downloads"]["artifact"];
if artifact.is_null() {
continue;
}
game.push(File {
url: text(artifact, "url")?,
sha1: text(artifact, "sha1")?,
path: dir
.join("libraries")
.join(relative(&text(artifact, "path")?)?),
});
}
log(format!(
"Downloading Minecraft {v} from Mojang: the game and {} libraries",
game.len() - 1
));
fetch_all(&game, jobs, fetch, log)?;
let index = &manifest["assetIndex"];
let index = File {
url: text(index, "url")?,
sha1: text(index, "sha1")?,
path: dir
.join("assets/indexes")
.join(relative(&format!("{}.json", text(index, "id")?))?),
};
let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, log)
.and_then(|_| objects(&read_json(&index.path)?, dir))
.and_then(|objects| {
log(format!("Downloading the sounds ({} files)", objects.len()));
fetch_all(&objects, jobs, fetch, log)
});
if let Err(e) = assets {
log(format!("The sounds could not all be downloaded: {e}"));
}
Ok(())
}
fn read_json(path: &Path) -> Result<Value, String> {
let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
}
fn text(v: &Value, key: &str) -> Result<String, String> {
v[key]
.as_str()
.map(String::from)
.ok_or_else(|| format!("The version file has no {key} in {v}"))
}
/// A path from the version file, refused if it could leave the folder.
fn relative(path: &str) -> Result<PathBuf, String> {
let safe = !path.contains('\\')
&& Path::new(path)
.components()
.all(|c| matches!(c, Component::Normal(_)));
safe.then(|| PathBuf::from(path))
.ok_or_else(|| format!("Unsafe path {path:?} in the version file"))
}
/// Whether a library's rules let this system (`osx`, `windows`, `linux`) use it: the last
/// rule that matches decides.
fn allowed(library: &Value, os: &str) -> bool {
let Some(rules) = library["rules"].as_array() else {
return true;
};
rules
.iter()
.rfind(|rule| rule["os"]["name"].as_str().is_none_or(|name| name == os))
.is_some_and(|rule| rule["action"] == "allow")
}
/// The asset index's objects, once each.
fn objects(index: &Value, dir: &Path) -> Result<Vec<File>, String> {
let objects = index["objects"]
.as_object()
.ok_or("The asset index has no objects")?;
let mut hashes: Vec<&str> = objects
.values()
.filter_map(|o| o["hash"].as_str())
.collect();
hashes.sort_unstable();
hashes.dedup();
hashes
.into_iter()
.map(|hash| {
if hash.len() != 40 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(format!("Bad asset hash {hash:?} in the asset index"));
}
let path = format!("{}/{hash}", &hash[..2]);
Ok(File {
url: format!("{OBJECTS}/{path}"),
sha1: hash.to_string(),
path: dir.join("assets/objects").join(path),
})
})
.collect()
}
/// Downloads the files not already there, `jobs` at a time, with a line every few seconds;
/// stops at the first error.
fn fetch_all(
files: &[File],
jobs: usize,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
let next = AtomicUsize::new(0);
let done = AtomicUsize::new(0);
let failed = Mutex::new(None);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..jobs.clamp(1, files.len().max(1)))
.map(|_| {
scope.spawn(|| {
while let Some(file) = files.get(next.fetch_add(1, Relaxed)) {
if failed.lock().unwrap().is_some() {
break;
}
if sha1_file(&file.path).as_ref() != Some(&file.sha1) {
let got = fetch_checked(fetch, &file.url, &file.sha1)
.map_err(|e| format!("{} {e}", file.url))
.and_then(|body| write_file(&file.path, &body));
if let Err(e) = got {
failed.lock().unwrap().get_or_insert(e);
}
}
done.fetch_add(1, Relaxed);
}
})
})
.collect();
let mut waited = 0;
while !workers.iter().all(|w| w.is_finished()) {
std::thread::sleep(Duration::from_millis(100));
waited += 1;
if waited % 50 == 0 {
log(format!("{} of {} files", done.load(Relaxed), files.len()));
}
}
});
failed.into_inner().unwrap().map_or(Ok(()), Err)
}
#[cfg(test)]
#[path = "mojang_tests.rs"]
mod tests;
+232
View File
@@ -0,0 +1,232 @@
//! A download from a mock of Mojang's servers serving small fake files (never Mojang's).
use super::*;
use crate::sources::{resolve, sha1_hex, Resolved};
use std::collections::HashMap;
const CLIENT: &[u8] = b"fake client jar";
const COMMON: &[u8] = b"a library every system uses";
const LINUX: &[u8] = b"a linux native";
const SOUND: &[u8] = b"a fake ogg";
const LANG: &[u8] = b"{}";
/// The fake version file, asset index and files, by URL.
fn mojang() -> (Pins, HashMap<String, Vec<u8>>) {
let artifact = |name: &str, data: &[u8]| {
serde_json::json!({
"path": format!("org/fake/{name}/1/{name}-1.jar"),
"sha1": sha1_hex(data),
"url": format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar"),
})
};
let index = serde_json::json!({"objects": {
"minecraft/sounds/a.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
"minecraft/sounds/same.ogg": {"hash": sha1_hex(SOUND), "size": SOUND.len()},
"minecraft/lang/fr_fr.json": {"hash": sha1_hex(LANG), "size": LANG.len()},
}})
.to_string();
let manifest = serde_json::json!({
"id": "26.3",
"assetIndex": {"id": "34", "sha1": sha1_hex(index.as_bytes()),
"url": "https://piston-meta.mojang.com/v1/packages/i/34.json"},
"downloads": {"client": {"sha1": sha1_hex(CLIENT), "url": "https://piston-data.mojang.com/client.jar"}},
"libraries": [
{"name": "org.fake:common:1", "downloads": {"artifact": artifact("common", COMMON)}},
{"name": "org.fake:linux:1", "downloads": {"artifact": artifact("linux", LINUX)},
"rules": [{"action": "allow", "os": {"name": "linux"}}]},
{"name": "org.fake:not-osx:1", "downloads": {"artifact": artifact("not-osx", COMMON)},
"rules": [{"action": "allow"}, {"action": "disallow", "os": {"name": "osx"}}]},
{"name": "org.fake:windows:1", "downloads": {"artifact": artifact("windows", b"w")},
"rules": [{"action": "allow", "os": {"name": "windows"}}]},
],
})
.to_string();
let pins = Pins::read(&serde_json::json!({"minecraft": {
"version": "26.3",
"client_sha1": sha1_hex(CLIENT),
"manifest_sha1": sha1_hex(manifest.as_bytes()),
}}))
.unwrap();
let object = |data: &[u8]| {
let hash = sha1_hex(data);
format!("{OBJECTS}/{}/{hash}", &hash[..2])
};
let lib =
|name: &str| format!("https://libraries.minecraft.net/org/fake/{name}/1/{name}-1.jar");
let files = HashMap::from([
(
format!(
"https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
sha1_hex(manifest.as_bytes())
),
manifest.into_bytes(),
),
(
"https://piston-data.mojang.com/client.jar".into(),
CLIENT.to_vec(),
),
(lib("common"), COMMON.to_vec()),
(lib("linux"), LINUX.to_vec()),
(lib("not-osx"), COMMON.to_vec()),
(lib("windows"), b"w".to_vec()),
(
"https://piston-meta.mojang.com/v1/packages/i/34.json".into(),
index.into_bytes(),
),
(object(SOUND), SOUND.to_vec()),
(object(LANG), LANG.to_vec()),
]);
(pins, files)
}
struct Server {
files: HashMap<String, Vec<u8>>,
asked: Mutex<Vec<String>>,
}
impl Server {
fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
self.asked.lock().unwrap().push(url.to_string());
self.files
.get(url)
.cloned()
.ok_or_else(|| format!("{url} answered 404"))
}
fn asked(&self) -> Vec<String> {
std::mem::take(&mut *self.asked.lock().unwrap())
}
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("horizon-mojang-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
dir
}
#[test]
fn an_owner_gets_the_official_layout_with_this_systems_libraries() {
let (pins, files) = mojang();
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("layout");
let logged = Mutex::new(Vec::new());
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|line| {
logged.lock().unwrap().push(line)
})
.unwrap();
assert_eq!(
fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(),
CLIENT
);
let libraries = dir.join("libraries/org/fake");
assert_eq!(
fs::read(libraries.join("common/1/common-1.jar")).unwrap(),
COMMON
);
assert_eq!(
fs::read(libraries.join("linux/1/linux-1.jar")).unwrap(),
LINUX
);
assert!(libraries.join("not-osx/1/not-osx-1.jar").is_file());
assert!(!libraries.join("windows").exists());
let hash = sha1_hex(SOUND);
assert_eq!(
fs::read(dir.join("assets/objects").join(&hash[..2]).join(&hash)).unwrap(),
SOUND
);
assert!(dir.join("assets/indexes/34.json").is_file());
let asked = server.asked();
// The sound two names share is fetched once; nothing is fetched twice.
assert_eq!(asked.len(), 8, "{asked:#?}");
assert!(!asked.iter().any(|u| u.contains("windows")));
assert_eq!(
logged.lock().unwrap()[1],
"Downloading Minecraft 26.3 from Mojang: the game and 3 libraries"
);
// Found like any launcher's folder, as it is; a second download fetches nothing.
let found = resolve(
&dir,
&pins,
&[],
&scratch("unused"),
&|url| server.fetch(url),
&|_| {},
);
assert_eq!(found, Ok(Resolved::Folder(dir.clone())));
download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|_| {}).unwrap();
assert_eq!(server.asked(), Vec::<String>::new());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn macos_skips_what_its_rules_disallow() {
let (pins, files) = mojang();
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("osx");
download(&pins, &dir, "osx", 2, &|url| server.fetch(url), &|_| {}).unwrap();
let libraries = dir.join("libraries/org/fake");
assert!(libraries.join("common/1/common-1.jar").is_file());
assert!(!libraries.join("linux").exists());
assert!(!libraries.join("not-osx").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_file_that_is_not_the_pinned_one_stops_the_download() {
let (pins, mut files) = mojang();
files.insert(
"https://piston-data.mojang.com/client.jar".into(),
b"something else".to_vec(),
);
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("bad-jar");
let error = download(&pins, &dir, "linux", 2, &|url| server.fetch(url), &|_| {}).unwrap_err();
assert!(
error.starts_with("https://piston-data.mojang.com/client.jar is not the one Horizon pins"),
"{error}"
);
assert!(!dir.join("versions/26.3/26.3.jar").exists());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn missing_sounds_are_a_line_in_the_log_not_an_error() {
let (pins, mut files) = mojang();
let hash = sha1_hex(SOUND);
files.remove(&format!("{OBJECTS}/{}/{hash}", &hash[..2]));
let server = Server {
files,
asked: Mutex::new(Vec::new()),
};
let dir = scratch("no-sound");
let logged = Mutex::new(Vec::new());
download(&pins, &dir, "linux", 1, &|url| server.fetch(url), &|line| {
logged.lock().unwrap().push(line)
})
.unwrap();
assert!(dir.join("versions/26.3/26.3.jar").is_file());
let last = logged.lock().unwrap().last().cloned().unwrap();
assert!(
last.starts_with("The sounds could not all be downloaded:")
&& last.ends_with("answered 404"),
"{last}"
);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn version_file_paths_stay_in_the_folder() {
assert!(relative("org/fake/a.jar").is_ok());
for bad in ["../a.jar", "/etc/a", "a/../../b", "a\\b"] {
assert!(relative(bad).is_err(), "{bad}");
}
}
+65 -23
View File
@@ -194,7 +194,7 @@ fn client_jars(base: &Path, version: &str) -> Vec<String> {
jars
}
fn sha1_file(path: &Path) -> Option<String> {
pub(crate) fn sha1_file(path: &Path) -> Option<String> {
let mut file = fs::File::open(path).ok()?;
let mut hash = Sha1::new();
let mut buffer = vec![0; 1 << 20];
@@ -264,8 +264,17 @@ pub fn not_found(version: &str, checked: &[(PathBuf, String)]) -> String {
text
}
/// Fetches a URL's body.
pub type Fetch<'a> = &'a dyn Fn(&str) -> Result<Vec<u8>, String>;
/// Fetches a URL's body (from several threads for a download).
pub type Fetch<'a> = &'a (dyn Fn(&str) -> Result<Vec<u8>, String> + Sync);
/// Where the pinned version is.
#[derive(Debug, PartialEq)]
pub enum Resolved {
/// A folder in the official launcher's layout.
Folder(PathBuf),
/// In none of these folders; each with what it lacks.
NotFound(Vec<(PathBuf, String)>),
}
/// A Minecraft folder in the official launcher's layout holding the pinned version: the
/// chosen folder when it is one, else the files found in the chosen folder (or a folder above
@@ -278,7 +287,7 @@ pub fn resolve(
linked: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<PathBuf, String> {
) -> Result<Resolved, String> {
let mut checked = Vec::new();
let mut found = None;
for dir in chosen.ancestors().take(4) {
@@ -302,7 +311,7 @@ pub fn resolve(
}
}
let Some((name, found)) = found else {
return Err(not_found(&pins.version, &checked));
return Ok(Resolved::NotFound(checked));
};
log(format!(
"Using Minecraft {} from {name} ({})",
@@ -310,10 +319,57 @@ pub fn resolve(
found.base.display()
));
if found.official_layout(&pins.version) {
return Ok(found.base);
return Ok(Resolved::Folder(found.base));
}
link_official_layout(&found, pins, linked, fetch, log)?;
Ok(linked.to_path_buf())
Ok(Resolved::Folder(linked.to_path_buf()))
}
/// The pinned version JSON at `path`, from piston-meta (by its sha1) unless it is there.
pub(crate) fn fetch_manifest(
pins: &Pins,
path: &Path,
fetch: Fetch,
log: &dyn Fn(String),
) -> Result<(), String> {
if pins.manifest_accepted(path) {
return Ok(());
}
let (v, sha1) = (&pins.version, &pins.manifests[0]);
log(format!("Downloading the {v} version file from Mojang"));
let url = format!("https://piston-meta.mojang.com/v1/packages/{sha1}/{v}.json");
let body =
fetch_checked(fetch, &url, sha1).map_err(|e| format!("Mojang's {v} version file {e}"))?;
write_file(path, &body)
}
pub(crate) fn sha1_hex(data: &[u8]) -> String {
Sha1::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
/// A download checked against its sha1; the error says how it differs.
pub(crate) fn fetch_checked(fetch: Fetch, url: &str, sha1: &str) -> Result<Vec<u8>, String> {
let body = fetch(url)?;
match sha1_hex(&body) {
actual if actual == sha1 => Ok(body),
actual => Err(format!("is not the one Horizon pins (sha1 {actual})")),
}
}
/// Writes a file whole: a partial one never takes its place.
pub(crate) fn write_file(path: &Path, data: &[u8]) -> Result<(), String> {
let error = |e: std::io::Error| format!("{}: {e}", path.display());
fs::create_dir_all(path.parent().unwrap()).map_err(error)?;
let partial = path.with_file_name(format!(
"{}.partial",
path.file_name().unwrap().to_string_lossy()
));
fs::write(&partial, data)
.and_then(|_| fs::rename(&partial, path))
.map_err(error)
}
/// Links a launcher's files into the official layout in `linked`: the client jar as
@@ -332,22 +388,8 @@ fn link_official_layout(
let manifest = versions.join(format!("{v}.json"));
if let Some(source) = &found.manifest {
fs::copy(source, &manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
} else if !pins.manifest_accepted(&manifest) {
let sha1 = &pins.manifests[0];
log(format!("Downloading the {v} version file from Mojang"));
let body = fetch(&format!(
"https://piston-meta.mojang.com/v1/packages/{sha1}/{v}.json"
))?;
let actual: String = Sha1::digest(&body)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
if &actual != sha1 {
return Err(format!(
"Mojang's {v} version file is not the one Horizon pins (sha1 {actual})"
));
}
fs::write(&manifest, body).map_err(|e| format!("{}: {e}", manifest.display()))?;
} else {
fetch_manifest(pins, &manifest, fetch, log)?;
}
link(&found.client, &versions.join(format!("{v}.jar")))?;
for dir in ["libraries", "assets"] {
+14 -17
View File
@@ -1,17 +1,11 @@
//! Each launcher's layout, rebuilt with small fake files (never Mojang's).
use super::*;
use std::cell::RefCell;
use std::sync::Mutex;
const CLIENT: &[u8] = b"fake 26.3 client jar";
const MANIFEST: &[u8] = br#"{"id": "26.3", "fake": true}"#;
fn sha1_hex(data: &[u8]) -> String {
Sha1::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn pins() -> Pins {
Pins::read(&serde_json::json!({ "minecraft": {
"version": "26.3",
@@ -64,19 +58,19 @@ impl Drop for Scratch {
/// Mojang's piston-meta, serving `body` and counting the requests.
struct Mojang {
body: Vec<u8>,
urls: RefCell<Vec<String>>,
urls: Mutex<Vec<String>>,
}
impl Mojang {
fn new(body: &[u8]) -> Mojang {
Mojang {
body: body.to_vec(),
urls: RefCell::new(Vec::new()),
urls: Mutex::new(Vec::new()),
}
}
fn fetch(&self, url: &str) -> Result<Vec<u8>, String> {
self.urls.borrow_mut().push(url.to_string());
self.urls.lock().unwrap().push(url.to_string());
Ok(self.body.clone())
}
}
@@ -87,14 +81,17 @@ fn resolve_with(
linked: &Path,
mojang: &Mojang,
) -> Result<PathBuf, String> {
resolve(
match resolve(
chosen,
&pins(),
known,
linked,
&|url| mojang.fetch(url),
&|_| {},
)
)? {
Resolved::Folder(dir) => Ok(dir),
Resolved::NotFound(checked) => Err(not_found("26.3", &checked)),
}
}
/// The linked folder is the official layout, pointing at the launcher's files.
@@ -140,7 +137,7 @@ fn the_official_layout_is_used_as_it_is() {
let mojang = Mojang::new(b"");
let got = resolve_with(&dir, &[], &s.0.join("linked"), &mojang).unwrap();
assert_eq!(got, dir);
assert!(mojang.urls.borrow().is_empty());
assert!(mojang.urls.lock().unwrap().is_empty());
assert!(!s.0.join("linked").exists());
}
@@ -172,7 +169,7 @@ fn prism_launcher_and_multimc_are_read_through_their_metadata() {
assert_eq!(resolve_with(&dir, &[], &linked, &mojang).unwrap(), linked);
assert_linked(&linked, &dir, jar);
assert_eq!(
*mojang.urls.borrow(),
*mojang.urls.lock().unwrap(),
[format!(
"https://piston-meta.mojang.com/v1/packages/{}/26.3.json",
sha1_hex(MANIFEST)
@@ -180,7 +177,7 @@ fn prism_launcher_and_multimc_are_read_through_their_metadata() {
);
// A second preparation keeps the version file it has.
resolve_with(&dir, &[], &linked, &mojang).unwrap();
assert_eq!(mojang.urls.borrow().len(), 1);
assert_eq!(mojang.urls.lock().unwrap().len(), 1);
}
#[test]
@@ -276,7 +273,7 @@ fn the_known_folders_are_searched_after_the_chosen_one() {
&|url| mojang.fetch(url),
&|line| logged.borrow_mut().push(line),
);
assert_eq!(got.unwrap(), linked);
assert_eq!(got.unwrap(), Resolved::Folder(linked.clone()));
assert_linked(&linked, &prism, jar);
assert_eq!(
logged.borrow()[0],
@@ -340,7 +337,7 @@ fn nothing_found_lists_every_folder_and_what_it_lacks() {
assert!(error.contains("Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher"));
// A launcher that isn't installed isn't listed.
assert!(!error.contains("atlauncher"));
assert!(mojang.urls.borrow().is_empty());
assert!(mojang.urls.lock().unwrap().is_empty());
}
#[test]