feat(net): fetch native libraries and verify mojang downloads
Model natives/classifiers/extract on Library, download the matching native classifier jar and unpack it into versions/<id>/natives so pre-1.13 versions can launch. Cached client jar, libraries and assets are now checked against their recorded size and sha1 instead of a bare exists(), and fresh client jar downloads are verified before use.
This commit is contained in:
1 parent
edd8a34b14
commit
4803fe9e3f
2 files changed
+357
-35
No files matched your search
+212
-28
@@ -1,3 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// handles all downloads from mojang's servers: version manifests,
|
||||
// client jars, libraries, and asset objects. this is the core of
|
||||
// getting vanilla minecraft onto disk.
|
||||
@@ -77,16 +80,36 @@ pub struct Library {
|
||||
pub name: String,
|
||||
pub downloads: LibraryDownloads,
|
||||
pub rules: Option<Vec<crate::launch_profile::rules::Rule>>,
|
||||
// os name -> natives classifier (e.g. "linux" -> "natives-linux").
|
||||
// present on pre-1.13-era libraries whose native code ships in
|
||||
// separate per-platform jars.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub natives: Option<HashMap<String, String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub extract: Option<LibraryExtract>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct LibraryExtract {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exclude: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct LibraryDownloads {
|
||||
pub artifact: Option<Artifact>,
|
||||
// classifier -> download info (same shape as artifact). populated on
|
||||
// libraries that declare `natives`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub classifiers: Option<HashMap<String, Artifact>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Artifact {
|
||||
pub url: String,
|
||||
// empty when upstream omits it; callers fall back to deriving the
|
||||
// relative path from the library's maven coordinate.
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
pub sha1: String,
|
||||
pub size: u64,
|
||||
@@ -147,6 +170,40 @@ pub async fn fetch_version_meta_with_raw(
|
||||
client.get_json_with_raw(&entry.url, "version meta").await
|
||||
}
|
||||
|
||||
// sha1 of a file as lowercase hex, or None if unreadable.
|
||||
fn sha1_hex(path: &Path) -> Option<String> {
|
||||
use sha1::Digest;
|
||||
use std::io::Read;
|
||||
let mut file = std::fs::File::open(path).ok()?;
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
match file.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(read) => hasher.update(&buffer[..read]),
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
Some(format!("{:x}", hasher.finalize()))
|
||||
}
|
||||
|
||||
// true when the cached file matches mojang's recorded size + sha1.
|
||||
// guards against partial files left by killed downloads: those used to be
|
||||
// trusted forever on the strength of an exists() check alone. size is
|
||||
// checked first so truncated files skip the hashing cost.
|
||||
fn verify_cached(path: &Path, expected_sha1: &str, expected_size: u64) -> bool {
|
||||
if !path.exists() {
|
||||
return false;
|
||||
}
|
||||
if expected_size > 0 {
|
||||
let actual = std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0);
|
||||
if actual != expected_size {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
sha1_hex(path).is_some_and(|hash| hash == expected_sha1)
|
||||
}
|
||||
|
||||
pub async fn download_client_jar(
|
||||
client: &HttpClient,
|
||||
meta: &VersionMeta,
|
||||
@@ -157,7 +214,11 @@ pub async fn download_client_jar(
|
||||
.join(&meta.id)
|
||||
.join(format!("{}.jar", meta.id));
|
||||
|
||||
if jar_path.exists() {
|
||||
if verify_cached(
|
||||
&jar_path,
|
||||
&meta.downloads.client.sha1,
|
||||
meta.downloads.client.size,
|
||||
) {
|
||||
tracing::info!("Client JAR already cached: {}", meta.id);
|
||||
tracing::trace!("Cached client JAR path: {}", jar_path.display());
|
||||
return Ok(());
|
||||
@@ -181,6 +242,22 @@ pub async fn download_client_jar(
|
||||
.await;
|
||||
|
||||
clear();
|
||||
|
||||
// a fresh download that doesn't match the manifest is worse than no
|
||||
// download: delete it so the next attempt doesn't trust it.
|
||||
if result.is_ok()
|
||||
&& !verify_cached(
|
||||
&jar_path,
|
||||
&meta.downloads.client.sha1,
|
||||
meta.downloads.client.size,
|
||||
)
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&jar_path).await;
|
||||
return Err(NetError::Parse(format!(
|
||||
"Downloaded client JAR {} failed its sha1 verification",
|
||||
meta.id
|
||||
)));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -205,7 +282,17 @@ pub async fn download_libraries(
|
||||
features: &features,
|
||||
};
|
||||
|
||||
let mut downloads = Vec::new();
|
||||
// matches the directory launch passes as java.library.path
|
||||
// (instance/launch/mod.rs).
|
||||
let natives_dir = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.versions()
|
||||
.join(&meta.id)
|
||||
.join("natives");
|
||||
|
||||
let mut downloads: Vec<(String, PathBuf, String)> = Vec::new();
|
||||
// natives jars to unpack once every download has landed:
|
||||
// (jar path inside the library cache, extract.exclude prefixes)
|
||||
let mut natives_jars: Vec<(PathBuf, Vec<String>)> = Vec::new();
|
||||
for library in &meta.libraries {
|
||||
if let Some(rules) = &library.rules
|
||||
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
|
||||
@@ -214,39 +301,136 @@ pub async fn download_libraries(
|
||||
continue;
|
||||
}
|
||||
|
||||
let artifact = match &library.downloads.artifact {
|
||||
Some(artifact) => artifact,
|
||||
None => {
|
||||
tracing::trace!(
|
||||
"Skipping library {} without artifact download",
|
||||
library.name
|
||||
);
|
||||
continue;
|
||||
if let Some(artifact) = &library.downloads.artifact {
|
||||
let rel = match library_relative_path(library, artifact.path.as_str()) {
|
||||
Some(rel) => rel,
|
||||
None => {
|
||||
tracing::warn!("Skipping unresolvable library {}", library.name);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
if verify_cached(&destination, &artifact.sha1, artifact.size) {
|
||||
tracing::trace!("Library already cached: {}", rel);
|
||||
} else {
|
||||
downloads.push((artifact.url.clone(), destination, rel));
|
||||
}
|
||||
};
|
||||
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&artifact.path);
|
||||
|
||||
if destination.exists() {
|
||||
tracing::trace!("Library already cached: {}", artifact.path);
|
||||
continue;
|
||||
}
|
||||
|
||||
downloads.push((artifact.url.clone(), destination, artifact.path.clone()));
|
||||
// native classifier jar (pre-1.13 era libraries). the jar itself is
|
||||
// cached alongside the other libraries; its contents get unpacked
|
||||
// into versions/<id>/natives where java.library.path points.
|
||||
if let Some(classifier) = library
|
||||
.natives
|
||||
.as_ref()
|
||||
.and_then(|n| n.get(crate::launch_profile::system::mojang_os_name()))
|
||||
&& let Some(info) = library
|
||||
.downloads
|
||||
.classifiers
|
||||
.as_ref()
|
||||
.and_then(|classifiers| classifiers.get(classifier))
|
||||
{
|
||||
// the maven fallback must carry the classifier: it selects
|
||||
// <artifact>-<version>-<classifier>.jar, not the base jar.
|
||||
let rel = if !info.path.is_empty() {
|
||||
info.path.clone()
|
||||
} else {
|
||||
match crate::instance::loader::maven::maven_coord_to_path(&format!(
|
||||
"{}:{}",
|
||||
library.name, classifier
|
||||
)) {
|
||||
Some(rel) => rel,
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"Skipping natives of library {}: no usable path",
|
||||
library.name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
if !verify_cached(&destination, &info.sha1, info.size) {
|
||||
downloads.push((info.url.clone(), destination.clone(), rel));
|
||||
}
|
||||
let exclude = library
|
||||
.extract
|
||||
.as_ref()
|
||||
.and_then(|extract| extract.exclude.clone())
|
||||
.unwrap_or_default();
|
||||
natives_jars.push((destination, exclude));
|
||||
}
|
||||
}
|
||||
|
||||
if downloads.is_empty() {
|
||||
let result = if downloads.is_empty() {
|
||||
tracing::info!("All libraries already cached");
|
||||
clear();
|
||||
return Ok(());
|
||||
Ok(())
|
||||
} else {
|
||||
tracing::debug!("Downloading {} missing libraries", downloads.len());
|
||||
run_parallel_downloads(client, downloads, false).await
|
||||
};
|
||||
clear();
|
||||
result?;
|
||||
|
||||
for (jar, exclude) in &natives_jars {
|
||||
extract_natives(jar, &natives_dir, exclude)?;
|
||||
}
|
||||
|
||||
tracing::debug!("Downloading {} missing libraries", downloads.len());
|
||||
let result = run_parallel_downloads(client, downloads, false).await;
|
||||
clear();
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// relative path of a library artifact inside the shared library cache.
|
||||
// upstream usually records it; fall back to deriving it from the maven
|
||||
// coordinate when the field is missing/empty.
|
||||
fn library_relative_path(library: &Library, recorded_path: &str) -> Option<String> {
|
||||
if !recorded_path.is_empty() {
|
||||
return Some(recorded_path.to_owned());
|
||||
}
|
||||
crate::instance::loader::maven::maven_coord_to_path(&library.name)
|
||||
}
|
||||
|
||||
// unpacks a natives jar into dest. skips directories, archive entries with
|
||||
// traversal paths, and anything matching an `extract.exclude` prefix.
|
||||
fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), NetError> {
|
||||
let file = std::fs::File::open(jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| NetError::Parse(format!("Invalid natives jar {}: {e}", jar.display())))?;
|
||||
std::fs::create_dir_all(dest)?;
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index).map_err(|e| {
|
||||
NetError::Parse(format!(
|
||||
"Corrupt entry in natives jar {}: {e}",
|
||||
jar.display()
|
||||
))
|
||||
})?;
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
// enclosed_name is None for absolute paths / .. traversal
|
||||
let Some(rel) = entry.enclosed_name() else {
|
||||
tracing::warn!(
|
||||
"Skipping unsafe path in natives jar {}: {}",
|
||||
jar.display(),
|
||||
entry.name()
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let name = rel.to_string_lossy();
|
||||
if exclude.iter().any(|prefix| name.starts_with(prefix)) {
|
||||
continue;
|
||||
}
|
||||
let out_path = dest.join(&rel);
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut out = std::fs::File::create(&out_path)?;
|
||||
std::io::copy(&mut entry, &mut out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn download_assets(
|
||||
@@ -337,7 +521,7 @@ pub async fn download_assets_from(
|
||||
.join(prefix)
|
||||
.join(&object.hash);
|
||||
|
||||
if destination.exists() {
|
||||
if verify_cached(&destination, &object.hash, object.size) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
+145
-7
@@ -1,3 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// integration tests for the public mojang fetchers. wiremock stands in for
|
||||
// Mojang so tests are fast, deterministic, and don't depend on the live
|
||||
// endpoint. these are different from the #[ignore = "hits live Mojang API"]
|
||||
@@ -144,8 +147,11 @@ fn meta_with_one_library(server_uri: &str) -> VersionMeta {
|
||||
sha1: "0".repeat(40),
|
||||
size: 11,
|
||||
}),
|
||||
classifiers: None,
|
||||
},
|
||||
rules: None,
|
||||
natives: None,
|
||||
extract: None,
|
||||
}],
|
||||
java_version: Some(JavaVersion { major_version: 17 }),
|
||||
}
|
||||
@@ -178,9 +184,9 @@ async fn download_libraries_writes_artifact_to_meta_dir() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_libraries_skips_when_destination_exists() {
|
||||
// pre-create the destination file. download_libraries should detect it
|
||||
// and skip the network entirely; wiremock's expect(0) would panic on any
|
||||
// request hitting the mock.
|
||||
// pre-create the destination file with content matching the recorded
|
||||
// size + sha1. download_libraries should verify and skip the network
|
||||
// entirely; wiremock's expect(0) would panic on any request.
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/slf4j.jar"))
|
||||
@@ -189,20 +195,54 @@ async fn download_libraries_skips_when_destination_exists() {
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let mut meta = meta_with_one_library(&server.uri());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let existing = tmp
|
||||
.path()
|
||||
.join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
|
||||
std::fs::create_dir_all(existing.parent().unwrap()).unwrap();
|
||||
std::fs::write(&existing, b"already there").unwrap();
|
||||
|
||||
use sha1::Digest;
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
hasher.update(b"already there");
|
||||
let artifact = meta.libraries[0].downloads.artifact.as_mut().unwrap();
|
||||
artifact.sha1 = format!("{:x}", hasher.finalize());
|
||||
artifact.size = b"already there".len() as u64;
|
||||
|
||||
download_libraries(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.expect("noop succeeds");
|
||||
|
||||
// file untouched, mock untouched (server drop will panic if it isn't)
|
||||
assert_eq!(std::fs::read(&existing).unwrap(), b"already there");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_libraries_redownloads_corrupted_cache() {
|
||||
// a cached file whose content doesn't match the recorded sha1/size
|
||||
// (e.g. a previously killed download) must be replaced, not trusted.
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/slf4j.jar"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(b"fresh-bytes".to_vec()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let meta = meta_with_one_library(&server.uri());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let existing = tmp
|
||||
.path()
|
||||
.join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar");
|
||||
std::fs::create_dir_all(existing.parent().unwrap()).unwrap();
|
||||
std::fs::write(&existing, b"already there").unwrap();
|
||||
std::fs::write(&existing, b"truncated").unwrap();
|
||||
|
||||
download_libraries(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.expect("noop succeeds");
|
||||
.expect("re-download succeeds");
|
||||
|
||||
// file untouched, mock untouched (server drop will panic if it isn't)
|
||||
assert_eq!(std::fs::read(&existing).unwrap(), b"already there");
|
||||
assert_eq!(std::fs::read(&existing).unwrap(), b"fresh-bytes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -278,3 +318,101 @@ async fn download_assets_writes_index_when_objects_is_empty() {
|
||||
serde_json::from_slice(&std::fs::read(&index_path).unwrap()).unwrap();
|
||||
assert!(body.get("objects").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_libraries_downloads_and_extracts_natives() {
|
||||
// pre-1.13-era library: no artifact, only a natives classifier for the
|
||||
// running OS. the jar must be cached in libraries/ and unpacked into
|
||||
// versions/<id>/natives, honouring extract.exclude.
|
||||
let server = MockServer::start().await;
|
||||
|
||||
use std::io::Write as _;
|
||||
let mut jar = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
jar.start_file("META-INF/MANIFEST.MF", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
jar.write_all(b"manifest").unwrap();
|
||||
jar.start_file("lib/native.so", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
jar.write_all(b"native-bits").unwrap();
|
||||
let jar_bytes = jar.finish().unwrap().into_inner();
|
||||
|
||||
use sha1::Digest;
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
hasher.update(&jar_bytes);
|
||||
let jar_sha1 = format!("{:x}", hasher.finalize());
|
||||
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/lwjgl-natives.jar"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(jar_bytes.clone()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let server_uri = server.uri();
|
||||
let meta = VersionMeta {
|
||||
id: "test".to_string(),
|
||||
main_class: "net.test.Main".to_string(),
|
||||
asset_index: AssetIndex {
|
||||
id: "5".to_string(),
|
||||
url: format!("{server_uri}/assets/index.json"),
|
||||
sha1: "0".repeat(40),
|
||||
},
|
||||
downloads: VersionDownloads {
|
||||
client: Download {
|
||||
url: format!("{server_uri}/client.jar"),
|
||||
sha1: "0".repeat(40),
|
||||
size: 0,
|
||||
},
|
||||
},
|
||||
libraries: vec![Library {
|
||||
name: "org.lwjgl.lwjgl:lwjgl:2.9.4".to_string(),
|
||||
downloads: LibraryDownloads {
|
||||
artifact: None,
|
||||
classifiers: Some(std::collections::HashMap::from([(
|
||||
"natives-linux".to_string(),
|
||||
Artifact {
|
||||
url: format!("{server_uri}/lwjgl-natives.jar"),
|
||||
path: "org/lwjgl/lwjgl/lwjgl/2.9.4/lwjgl-2.9.4-natives-linux.jar"
|
||||
.to_string(),
|
||||
sha1: jar_sha1,
|
||||
size: jar_bytes.len() as u64,
|
||||
},
|
||||
)])),
|
||||
},
|
||||
rules: None,
|
||||
natives: Some(std::collections::HashMap::from([(
|
||||
rmcl::launch_profile::system::mojang_os_name().to_string(),
|
||||
"natives-linux".to_string(),
|
||||
)])),
|
||||
extract: Some(rmcl::net::mojang::LibraryExtract {
|
||||
exclude: Some(vec!["META-INF/".to_string()]),
|
||||
}),
|
||||
}],
|
||||
java_version: Some(JavaVersion { major_version: 8 }),
|
||||
};
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
download_libraries(&HttpClient::new(), &meta, tmp.path())
|
||||
.await
|
||||
.expect("download_libraries with natives");
|
||||
|
||||
let cached_jar = tmp.path().join(
|
||||
"cache/minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4/lwjgl-2.9.4-natives-linux.jar",
|
||||
);
|
||||
assert_eq!(std::fs::read(&cached_jar).unwrap(), jar_bytes);
|
||||
|
||||
let extracted = tmp
|
||||
.path()
|
||||
.join("cache/minecraft/versions/test/natives/lib/native.so");
|
||||
assert_eq!(
|
||||
std::fs::read(&extracted).unwrap(),
|
||||
b"native-bits",
|
||||
"natives payload must be unpacked next to java.library.path"
|
||||
);
|
||||
assert!(
|
||||
!tmp.path()
|
||||
.join("cache/minecraft/versions/test/natives/META-INF")
|
||||
.exists(),
|
||||
"extract.exclude prefixes must be skipped"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user