From dc351df54602ee010c856e9f44825ef2b10f2e7c Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 23:22:53 +0200 Subject: [PATCH] fix: launch with the selected JVM and own subprocess lifetimes --- src/instance/java.rs | 507 +++++++++++++++-- src/instance/launch/mod.rs | 527 ++++++++++-------- src/instance/launch/output.rs | 72 +++ src/instance/launch/parser.rs | 5 +- src/instance/launch/patches.rs | 370 +++++++------ src/instance/loader/forge.rs | 55 +- src/instance/loader/mod.rs | 7 +- src/instance/loader/neoforge.rs | 50 +- src/instance/loader/vanilla.rs | 4 +- src/instance/manager.rs | 69 ++- src/instance/mod.rs | 1 + src/instance/process.rs | 175 ++++++ src/instance/runtime.rs | 27 +- src/instance/tests/launch/parser.rs | 16 + src/instance/tests/launch/patches.rs | 301 ++++++---- src/instance/tests/launch/pipeline.rs | 140 ++++- src/instance/tests/loader/forge.rs | 3 - src/instance/tests/loader/installers.rs | 190 ++++++- src/instance/tests/manager.rs | 144 +++++ src/launch_profile/model.rs | 16 +- src/launch_profile/resolve.rs | 17 +- src/launch_profile/rules.rs | 2 +- src/launch_profile/system.rs | 96 +++- src/launch_profile/templates.rs | 12 +- src/launch_profile/tests/render.rs | 8 - src/launch_profile/tests/resolve.rs | 23 + src/launch_profile/tests/templates.rs | 18 +- src/net/mojang.rs | 248 ++++++--- tests/fixtures/InstallerLifetimeFixture.java | 21 + tests/launch_pipeline.rs | 553 ++++++++++++++++++- tests/net_mojang.rs | 204 ++++++- 31 files changed, 3061 insertions(+), 820 deletions(-) create mode 100644 src/instance/launch/output.rs create mode 100644 src/instance/process.rs create mode 100644 tests/fixtures/InstallerLifetimeFixture.java diff --git a/src/instance/java.rs b/src/instance/java.rs index f67dde9..e1b0fd1 100644 --- a/src/instance/java.rs +++ b/src/instance/java.rs @@ -2,9 +2,8 @@ // SPDX-License-Identifier: GPL-3.0-only use std::{ - collections::HashSet, + collections::{BTreeMap, HashSet}, path::{Path, PathBuf}, - process::Command, }; use serde::{Deserialize, Serialize}; @@ -15,34 +14,177 @@ pub struct JavaInstallation { pub version: Option, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JavaRuntime { + pub major_version: u32, + pub platform: crate::launch_profile::system::JavaPlatform, +} + +#[must_use] +pub fn resolve_java_path(instance_java: Option<&str>) -> String { + let settings = crate::config::SETTINGS.read().clone(); + let environment = merge_environment(&settings.defaults.environment, &BTreeMap::new()); + resolve_java_path_in( + instance_java.or(settings.paths.effective_java_path()), + &std::env::current_dir().unwrap_or_default(), + &environment, + ) +} + +/// Command uses the platform's environment-key comparison, including Windows Unicode casing. +pub fn merge_environment( + global: &BTreeMap, + instance: &BTreeMap, +) -> BTreeMap { + let mut command = std::process::Command::new("java"); + command.envs(global).envs(instance); + command + .get_envs() + .map(|(name, value)| { + ( + name.to_str() + .expect("environment names originate from strings") + .to_owned(), + value + .expect("only environment additions were configured") + .to_str() + .expect("environment values originate from strings") + .to_owned(), + ) + }) + .collect() +} + +// These lookups are for the ASCII variable names PATH, JAVA_HOME and JDK_HOME. +fn environment_value( + environment: &BTreeMap, + name: &str, +) -> Option { + environment + .iter() + .rev() + .find(|(key, _)| { + if cfg!(windows) { + key.eq_ignore_ascii_case(name) + } else { + key.as_str() == name + } + }) + .map(|(_, value)| std::ffi::OsString::from(value)) + .or_else(|| std::env::var_os(name)) +} + +pub fn resolve_java_path_in( + configured: Option<&str>, + cwd: &Path, + environment: &BTreeMap, +) -> String { + let search_path = environment_value(environment, "PATH"); + let find = |name: &str| { + if Path::new(name).components().count() > 1 { + return which::which_in(name, None::<&std::ffi::OsStr>, cwd).ok(); + } + search_path.as_deref().and_then(|path| { + std::env::split_paths(path) + .filter(|directory| !cfg!(windows) || !directory.as_os_str().is_empty()) + .find_map(|directory| { + which::which_in( + cwd.join(directory).join(name), + None::<&std::ffi::OsStr>, + cwd, + ) + .ok() + }) + }) + }; + if let Some(configured) = configured.filter(|path| !path.is_empty()) { + return find(configured) + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_else(|| configured.to_owned()); + } + if let Some(home) = environment_value(environment, "JAVA_HOME") { + let bin = cwd + .join(home) + .join("bin") + .join(if cfg!(windows) { "java.exe" } else { "java" }); + if bin.is_file() { + return bin.to_string_lossy().into_owned(); + } + } + find("java") + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_else(|| "java".to_owned()) +} + +/// Probe the selected executable, rather than inferring its architecture from rmcl. +pub async fn probe_java(path: &Path) -> std::io::Result { + let (cwd, environment) = default_probe_context()?; + probe_java_in(path, &cwd, &environment).await +} + +pub async fn probe_java_in( + path: &Path, + cwd: &Path, + environment: &BTreeMap, +) -> std::io::Result { + let output = java_version_output_in(path, cwd, environment).await?; + if !output.status.success() { + return Err(std::io::Error::other(format!( + "Java settings probe exited with {}", + output.status + ))); + } + parse_runtime_properties(&format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + )) +} + +fn default_probe_context() -> std::io::Result<(PathBuf, BTreeMap)> { + Ok(( + std::env::current_dir()?, + merge_environment( + &crate::config::SETTINGS.read().defaults.environment, + &BTreeMap::new(), + ), + )) +} + +fn parse_runtime_properties(output: &str) -> std::io::Result { + let property = |name: &str| -> std::io::Result<&str> { + output + .lines() + .filter_map(|line| line.trim().split_once(" = ")) + .find_map(|(key, value)| (key == name).then_some(value.trim())) + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Java probe did not report {name}"), + ) + }) + }; + let major_version = parse_java_major_version(property("java.version")?).ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid Java java.version") + })?; + Ok(JavaRuntime { + major_version, + platform: crate::launch_profile::system::JavaPlatform::from_java_properties( + property("os.name")?, + property("os.arch")?, + property("sun.arch.data.model")?, + property("os.version")?, + )?, + }) +} + #[must_use] pub fn detect_java_path() -> String { - if let Ok(java_home) = std::env::var("JAVA_HOME") { - let java_name = if cfg!(windows) { "java.exe" } else { "java" }; - let bin = std::path::Path::new(&java_home).join("bin").join(java_name); - if bin.exists() { - tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display()); - return bin.to_string_lossy().to_string(); - } - tracing::warn!( - "JAVA_HOME is set to {}, but {} does not exist", - java_home, - bin.display() - ); - } - match which::which("java") { - Ok(path) => { - tracing::trace!("Detected Java from PATH: {}", path.display()); - path.to_string_lossy().to_string() - } - Err(e) => { - tracing::warn!( - "Could not find java on PATH, falling back to literal 'java': {}", - e - ); - "java".to_string() - } - } + let Ok((cwd, environment)) = default_probe_context() else { + return "java".to_owned(); + }; + resolve_java_path_in(None, &cwd, &environment) } /// Finds Java executables in the environment and the conventional installation @@ -50,23 +192,39 @@ pub fn detect_java_path() -> String { /// opening the selector never walks an entire drive. #[must_use] pub fn discover_installations() -> Vec { + let Ok((cwd, environment)) = default_probe_context() else { + return Vec::new(); + }; + discover_installations_in(&cwd, &environment) +} + +#[must_use] +pub fn discover_installations_in( + cwd: &Path, + environment: &BTreeMap, +) -> Vec { let mut candidates = Vec::new(); for variable in ["JAVA_HOME", "JDK_HOME"] { - if let Ok(java_home) = std::env::var(variable) { - add_java_home(Path::new(&java_home), &mut candidates); + if let Some(java_home) = environment_value(environment, variable) { + add_java_home(&cwd.join(java_home), &mut candidates); } } - if let Ok(path) = which::which("java") { + let search_path = environment_value(environment, "PATH"); + if let Ok(path) = which::which_in( + resolve_java_path_in(None, cwd, environment), + None::<&std::ffi::OsStr>, + cwd, + ) { candidates.push(path); } - if let Some(path) = std::env::var_os("PATH") { + if let Some(path) = search_path { for directory in std::env::split_paths(&path) { let executable = if cfg!(target_os = "windows") { "java.exe" } else { "java" }; - candidates.push(directory.join(executable)); + candidates.push(cwd.join(directory).join(executable)); } } @@ -81,7 +239,7 @@ pub fn discover_installations() -> Vec { .filter_map(|path| { let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone()); seen.insert(identity) - .then(|| inspect_installation(&path)) + .then(|| inspect_installation_in(&path, cwd, environment)) .flatten() }) .collect::>(); @@ -96,25 +254,96 @@ pub fn discover_installations() -> Vec { /// Reads the version reported by one Java executable. #[must_use] pub fn inspect_installation(path: &Path) -> Option { + let (cwd, environment) = default_probe_context().ok()?; + inspect_installation_in(path, &cwd, &environment) +} + +#[must_use] +pub fn inspect_installation_in( + path: &Path, + cwd: &Path, + environment: &BTreeMap, +) -> Option { + let resolved = path + .to_str() + .map(|path| resolve_java_path_in(Some(path), cwd, environment)); + let path = resolved.as_deref().map_or(path, Path::new); path.is_file().then(|| JavaInstallation { - version: java_version(path), + version: java_version_in(path, cwd, environment), path: path.to_path_buf(), }) } #[must_use] pub fn load_installation_cache(path: &Path) -> Option> { - let mut installations = - serde_json::from_slice::>(&std::fs::read(path).ok()?).ok()?; - installations.retain(|installation| installation.path.is_file()); - (!installations.is_empty()).then_some(installations) + let (cwd, environment) = default_probe_context().ok()?; + load_installation_cache_in(path, &cwd, &environment) +} + +#[derive(Serialize, Deserialize)] +struct InstallationCache { + context: String, + installations: Vec, +} + +#[must_use] +pub fn probe_context_key(cwd: &Path, environment: &BTreeMap) -> String { + use sha2::Digest; + let mut hash = sha2::Sha256::new(); + let mut add = |bytes: &[u8]| { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + }; + add(cwd.as_os_str().as_encoded_bytes()); + let mut ambient: Vec<_> = std::env::vars_os().collect(); + ambient.sort(); + for (key, value) in &ambient { + add(key.as_encoded_bytes()); + add(value.as_encoded_bytes()); + } + // Store a digest only; configured environment values may contain credentials. + for (key, value) in merge_environment(environment, &BTreeMap::new()) { + add(key.as_bytes()); + add(value.as_bytes()); + } + format!("{:x}", hash.finalize()) +} + +#[must_use] +pub fn load_installation_cache_in( + path: &Path, + cwd: &Path, + environment: &BTreeMap, +) -> Option> { + let mut cache: InstallationCache = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; + if cache.context != probe_context_key(cwd, environment) { + return None; + } + cache + .installations + .retain(|installation| installation.path.is_file()); + (!cache.installations.is_empty()).then_some(cache.installations) } pub fn save_installation_cache( path: &Path, installations: &[JavaInstallation], ) -> std::io::Result<()> { - let bytes = serde_json::to_vec_pretty(installations).map_err(std::io::Error::other)?; + let (cwd, environment) = default_probe_context()?; + save_installation_cache_in(path, installations, &cwd, &environment) +} + +pub fn save_installation_cache_in( + path: &Path, + installations: &[JavaInstallation], + cwd: &Path, + environment: &BTreeMap, +) -> std::io::Result<()> { + let cache = InstallationCache { + context: probe_context_key(cwd, environment), + installations: installations.to_vec(), + }; + let bytes = serde_json::to_vec_pretty(&cache).map_err(std::io::Error::other)?; crate::storage::write_atomic(path, &bytes) } @@ -203,8 +432,18 @@ fn add_java_home(home: &Path, candidates: &mut Vec) { } } -pub(crate) fn java_version(path: &Path) -> Option { - let output = Command::new(path).arg("-version").output().ok()?; +pub fn java_version_in( + path: &Path, + cwd: &Path, + environment: &BTreeMap, +) -> Option { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .ok()?; + let output = runtime + .block_on(java_version_output_in(path, cwd, environment)) + .ok()?; if !output.status.success() { return None; } @@ -216,8 +455,36 @@ pub(crate) fn java_version(path: &Path) -> Option { parse_java_version(&text) } +async fn java_version_output_in( + path: &Path, + cwd: &Path, + environment: &BTreeMap, +) -> std::io::Result { + let java = path + .to_str() + .map(|path| resolve_java_path_in(Some(path), cwd, environment)); + let mut command = tokio::process::Command::new(java.as_deref().map_or(path, Path::new)); + command + .args(["-XshowSettings:properties", "-version"]) + .current_dir(cwd) + .envs(environment) + .kill_on_drop(true); + tokio::time::timeout(std::time::Duration::from_secs(10), command.output()) + .await + .map_err(|_| { + std::io::Error::new(std::io::ErrorKind::TimedOut, "Java version check timed out") + })? +} + fn parse_java_version(output: &str) -> Option { output.lines().find_map(|line| { + let line = line.trim(); + if let Some(version) = line.strip_prefix("java.version = ") { + return Some(version.trim().to_owned()); + } + if !line.starts_with("java version ") && !line.starts_with("openjdk version ") { + return None; + } line.split_once('"') .and_then(|(_, rest)| rest.split_once('"')) .map(|(version, _)| version.to_owned()) @@ -246,16 +513,7 @@ pub(crate) fn parse_java_major_version(output: &str) -> Option { } let start = output.find(|character: char| character.is_ascii_digit())?; - let parts = output[start..] - .split(|character: char| !character.is_ascii_digit()) - .filter(|part| !part.is_empty()) - .filter_map(|part| part.parse::().ok()) - .collect::>(); - match parts.as_slice() { - [1, legacy_major, ..] => Some(*legacy_major), - [major, ..] => Some(*major), - [] => None, - } + Some(java_major(Some(&output[start..]))).filter(|major| *major > 0) } #[cfg(test)] @@ -299,4 +557,149 @@ mod tests { std::fs::remove_file(executable).unwrap(); assert_eq!(load_installation_cache(&cache), None); } + + #[test] + fn runtime_properties_report_selected_java_architecture_and_os_version() { + for (os, arch, bits, name, normalized) in [ + ("Windows 10", "x86", "32", "windows", "x86"), + ("Windows 11", "amd64", "64", "windows", "x86_64"), + ("Mac OS X", "x86_64", "64", "osx", "x86_64"), + ("Mac OS X", "aarch64", "64", "osx", "arm64"), + ("Linux", "amd64", "64", "linux", "x86_64"), + ] { + let properties = format!( + "Property settings:\r\n java.version = 1.8.0_412\r\n os.name = {os}\r\n os.arch = {arch}\r\n sun.arch.data.model = {bits}\r\n os.version = 10.0\r\n" + ); + let runtime = parse_runtime_properties(&properties).unwrap(); + assert_eq!(runtime.major_version, 8); + assert_eq!(runtime.platform.os_name, name); + assert_eq!(runtime.platform.arch, normalized); + assert_eq!(runtime.platform.bitness.to_string(), bits); + assert_eq!(runtime.platform.os_version, "10.0"); + assert!( + parse_runtime_properties(&properties.replace("sun.arch.data.model =", "unknown =")) + .unwrap_err() + .to_string() + .contains("sun.arch.data.model") + ); + } + } + + #[test] + fn incomplete_runtime_properties_do_not_fall_back_to_the_launcher_architecture() { + assert!(parse_runtime_properties("openjdk version \"25.0.1\"").is_err()); + assert!( + crate::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + "../x86", + "32", + "10.0" + ) + .is_err() + ); + assert!( + crate::launch_profile::system::JavaPlatform::from_java_properties( + "Mac OS X", "aarch64", "unknown", "15.0" + ) + .is_err() + ); + } + + #[cfg(unix)] + #[test] + fn relative_java_search_paths_are_bound_to_the_execution_directory() { + use std::os::unix::fs::PermissionsExt; + let temp = + tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap(); + let cwd = temp.path().join("minecraft"); + let java = cwd.join("bin/java"); + std::fs::create_dir_all(java.parent().unwrap()).unwrap(); + std::fs::write(&java, "#!/bin/sh\nexit 0\n").unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + let environment = BTreeMap::from([ + ("PATH".to_owned(), "bin".to_owned()), + ("JAVA_HOME".to_owned(), "missing-home".to_owned()), + ]); + for configured in [None, Some("java"), Some("bin/java")] { + assert_eq!( + Path::new(&resolve_java_path_in(configured, &cwd, &environment)), + java + ); + } + } + + #[tokio::test] + async fn installed_jdk_reports_runtime_properties_on_the_native_platform() { + let cwd = std::env::current_dir().unwrap(); + let environment = BTreeMap::new(); + let java = resolve_java_path_in(None, &cwd, &environment); + let runtime = probe_java_in(Path::new(&java), &cwd, &environment) + .await + .unwrap(); + assert!(runtime.major_version >= 8); + assert_eq!( + runtime.platform.os_name, + crate::launch_profile::system::mojang_os_name() + ); + assert!(matches!(runtime.platform.bitness, 32 | 64)); + assert!(!runtime.platform.os_version.is_empty()); + } + + #[test] + fn environment_overrides_follow_native_case_rules_and_are_deterministic() { + let global = BTreeMap::from([ + ("PATH".into(), "global".into()), + ("TÊST".into(), "global".into()), + ]); + let instance = BTreeMap::from([ + ("PATH".into(), "first".into()), + ("path".into(), "last".into()), + ("têst".into(), "instance".into()), + ]); + let merged = merge_environment(&global, &instance); + assert_eq!( + environment_value(&instance, "PATH").unwrap(), + std::ffi::OsString::from(if cfg!(windows) { "last" } else { "first" }) + ); + if cfg!(windows) { + assert_eq!(merged.len(), 2); + assert_eq!(merged["PATH"], "last"); + assert_eq!(merged["TÊST"], "instance"); + } else { + assert_eq!(merged.len(), 4); + assert_eq!(merged["PATH"], "first"); + assert_eq!(merged["path"], "last"); + assert_eq!(merged["TÊST"], "global"); + } + } + + #[test] + fn installation_cache_is_bound_to_the_probe_context_without_storing_environment_values() { + let temp = tempfile::tempdir().unwrap(); + let executable = temp.path().join("java"); + std::fs::write(&executable, b"java").unwrap(); + let cache = temp.path().join("installations.json"); + let installations = vec![JavaInstallation { + path: executable, + version: Some("25.0.1".into()), + }]; + let environment = + BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "sensitive-cache-value".into())]); + save_installation_cache_in(&cache, &installations, temp.path(), &environment).unwrap(); + assert_eq!( + load_installation_cache_in(&cache, temp.path(), &environment), + Some(installations) + ); + assert!( + !std::fs::read_to_string(&cache) + .unwrap() + .contains("sensitive-cache-value") + ); + let changed = BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "another-value".into())]); + assert!(load_installation_cache_in(&cache, temp.path(), &changed).is_none()); + assert!( + load_installation_cache_in(&cache, &temp.path().join("other-cwd"), &environment) + .is_none() + ); + } } diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index d39c010..342ca68 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +mod output; pub(crate) mod parser; mod patches; @@ -8,12 +9,14 @@ use std::path::{Path, PathBuf}; use thiserror::Error; +use super::process; use crate::auth::AccountType; +use crate::instance::java::JavaRuntime; use crate::instance::models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode}; use crate::launch_profile::model::{Argument, LaunchProfile}; use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext}; use crate::launch_profile::templates::TemplateContext; -use crate::launch_profile::{render, resolve, system}; +use crate::launch_profile::{render, resolve}; #[derive(Debug, Error)] pub enum LaunchError { @@ -33,18 +36,44 @@ pub enum LaunchError { required: u32, detected: u32, }, - #[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")] + #[error("Could not inspect Java runtime {java}: {reason}")] JavaCheckFailed { java: String, required: u32, reason: String, }, + #[error("Download error: {0}")] + Download(#[from] crate::net::NetError), #[error("{0}")] Auth(String), #[error("{phase} command failed: {reason}")] Command { phase: &'static str, reason: String }, #[error("Config sync error: {0}")] ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError), + #[error("Launch cancelled")] + Cancelled, +} + +struct LaunchCleanup(String); + +impl Drop for LaunchCleanup { + fn drop(&mut self) { + crate::instance::runtime::cleanup_kill_sender(&self.0); + if crate::instance::runtime::is_active(&self.0) { + crate::instance::runtime::remove(&self.0); + } + } +} + +async fn wait_for_kill(receiver: &mut Option>) { + if let Some(pending) = receiver { + let result = pending.await; + *receiver = None; + if result.is_ok() { + return; + } + } + std::future::pending::<()>().await; } fn build_game_args( @@ -77,49 +106,16 @@ fn apply_window_mode(game_args: &mut Vec, window_mode: WindowMode) { } } -async fn check_java_version(java: &str, required: Option) -> Result<(), LaunchError> { +fn check_java_version( + java: &str, + runtime: &JavaRuntime, + required: Option, +) -> Result<(), LaunchError> { let Some(required) = required.filter(|major| *major > 0) else { return Ok(()); }; - let mut command = tokio::process::Command::new(java); - command.arg("-version").kill_on_drop(true); - let output = tokio::time::timeout(std::time::Duration::from_secs(10), command.output()) - .await - .map_err(|_| LaunchError::JavaCheckFailed { - java: java.to_owned(), - required, - reason: "version check timed out".to_owned(), - })? - .map_err(|e| LaunchError::JavaCheckFailed { - java: java.to_owned(), - required, - reason: e.to_string(), - })?; - - if !output.status.success() { - return Err(LaunchError::JavaCheckFailed { - java: java.to_owned(), - required, - reason: format!("`java -version` exited with {}", output.status), - }); - } - - let version_text = format!( - "{}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - - let detected = - crate::instance::java::parse_java_major_version(&version_text).ok_or_else(|| { - LaunchError::JavaCheckFailed { - java: java.to_owned(), - required, - reason: format!("could not parse `java -version` output: {version_text:?}"), - } - })?; - + let detected = runtime.major_version; if detected < required { return Err(LaunchError::JavaTooOld { java: java.to_owned(), @@ -131,11 +127,7 @@ async fn check_java_version(java: &str, required: Option) -> Result<(), Lau Ok(()) } -// existing installs from rmcl <= 0.3.0 have meta.json files in the -// stripped legacy format (no `arguments`, no `minecraftArguments`). every -// real upstream profile has at least one of those fields. on detecting the -// stripped format, re-fetch the version metadata from mojang's manifest -// and overwrite the file with the raw upstream bytes. +// rmcl <= 0.3.0 stripped upstream arguments from cached metadata. async fn migrate_legacy_meta_if_needed( meta_path: &Path, profile: &LaunchProfile, @@ -193,9 +185,6 @@ async fn migrate_legacy_meta_if_needed( Ok(Some(refreshed)) } -// the forge/neoforge installer writes its version JSON to a path that's -// loader-specific. encode the naming convention here so migration code -// can find the original file when it needs to rebuild our cache. fn installer_version_dir_name( loader: ModLoader, game_version: &str, @@ -208,35 +197,19 @@ fn installer_version_dir_name( } } -// loader profiles installed by rmcl <= 0.3.0 are in our stripped -// `{mainClass, libraries[, gameArguments]}` format, which silently drops -// `inheritsFrom`, `arguments.jvm`, and conditional rules from upstream. -// detect that shape (no inheritsFrom AND no arguments AND no -// minecraftArguments - every real upstream profile has at least one) and -// rebuild from the installer's original JSON if it's still on disk. +// Recover JVM arguments and rules stripped by rmcl <= 0.3.0 from the installer original. async fn migrate_legacy_loader_profile_if_needed( profile_path: &Path, profile: &LaunchProfile, config: &InstanceConfig, instance_dir: &Path, ) -> Result, LaunchError> { - // Fabric and Quilt fetch their profiles from a network endpoint at - // install time; there's no installer-written JSON on disk to recover - // from. their upstream profiles also happen to match the "legacy - // stripped" predicate (no inheritsFrom, no arguments), so without this - // early return every Fabric/Quilt launch would incorrectly fail - // migration. resolve() handles their lack of inheritsFrom via the - // implicit fallback in the launch flow. + // Fabric/Quilt profiles can omit these fields and have no installer original. if matches!(config.loader, ModLoader::Fabric | ModLoader::Quilt) { return Ok(None); } - // tightened predicate per the spec: only treat a profile as "legacy - // stripped" when our old `gameArguments` field is present. that field - // is unique to rmcl <= 0.3.0's custom shape; no upstream profile - // emits it. without this gate, an upstream profile that happens to - // omit inheritsFrom/arguments/minecraftArguments would be mistakenly - // re-extracted from the installer JSON. + // gameArguments identifies rmcl's old shape, avoiding false positives on upstream profiles. let is_legacy = profile.inherits_from.is_none() && profile.arguments.is_none() && profile.minecraft_arguments.is_none() @@ -256,9 +229,6 @@ async fn migrate_legacy_loader_profile_if_needed( let Some(version_dir) = installer_version_dir_name(config.loader, &config.game_version, loader_version) else { - // unreachable today: only Vanilla/Fabric/Quilt return None, and - // Vanilla doesn't pass this code path (no loader profile to - // migrate) while Fabric/Quilt are filtered above. return Err(LaunchError::Parse(format!( "Loader profile at {} is in an outdated format. Reinstall {} for this instance.", profile_path.display(), @@ -366,10 +336,32 @@ pub async fn build_launch_invocation( auth: &LaunchAuth<'_>, quick_play_world: Option<&str>, ) -> Result { - let instance_dir = instances_dir.join(&config.name); + let settings = crate::config::SETTINGS.read().clone(); + build_launch_invocation_with_settings( + config, + instances_dir, + meta_dir, + auth, + quick_play_world, + &settings, + ) + .await +} + +pub async fn build_launch_invocation_with_settings( + config: &InstanceConfig, + instances_dir: &Path, + meta_dir: &Path, + auth: &LaunchAuth<'_>, + quick_play_world: Option<&str>, + settings: &crate::config::Config, +) -> Result { + let meta_dir = std::path::absolute(meta_dir)?; + let meta_dir = meta_dir.as_path(); + let instance_dir = std::path::absolute(instances_dir.join(&config.name))?; let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME); let (window_mode, resolution) = { - let defaults = &crate::config::SETTINGS.read().defaults; + let defaults = &settings.defaults; ( config.effective_window_mode(defaults.window_mode), config.effective_resolution(defaults.resolution), @@ -399,20 +391,6 @@ pub async fn build_launch_invocation( has_custom_resolution: resolution.map(|_| true), ..Default::default() }; - let host_os_version = system::mojang_os_version(); - let rule_ctx = RuleContext { - os_name: system::mojang_os_name(), - os_version: &host_os_version, - arch: system::mojang_arch_name(), - features: ¤t_features, - }; - - let asset_index_id = meta - .asset_index - .as_ref() - .map(|ai| ai.id.clone()) - .unwrap_or_default(); - let lib_dir = metadata_paths.libraries(); let lv = config.loader_version.as_deref().unwrap_or("unknown"); @@ -423,7 +401,7 @@ pub async fn build_launch_invocation( // if needed, and resolve `inheritsFrom` against the vanilla parent (which // the vanilla meta migration above ensured is fresh on disk). when no // loader is configured we use the already-loaded vanilla meta directly. - let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename { + let mut merged_profile: LaunchProfile = if let Some(filename) = &profile_filename { let profile_path = metadata_paths.loader_profiles().join(filename); if !profile_path.exists() { return Err(LaunchError::MetaNotFound( @@ -458,7 +436,7 @@ pub async fn build_launch_invocation( meta.clone() }; - let main_class = merged_profile + let mut main_class = merged_profile .main_class .clone() .ok_or_else(|| LaunchError::Parse("merged profile missing mainClass".into()))?; @@ -467,12 +445,71 @@ pub async fn build_launch_invocation( return Err(LaunchError::NotSupported("Quick Play".to_owned())); } - // rebuild the classpath from the merged profile. vanilla-style libraries - // have `downloads.artifact.path` set and live in meta_dir/libraries/. - // loader-style libraries only have a maven coordinate; for forge/neoforge, - // the installer drops some of them into /.minecraft/libraries/ - // so we check there first. - let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &config.environment, + ); + let java = crate::instance::java::resolve_java_path_in( + config + .java_path + .as_deref() + .or(settings.paths.effective_java_path()), + &minecraft_dir, + &environment, + ); + let runtime = + crate::instance::java::probe_java_in(Path::new(&java), &minecraft_dir, &environment) + .await + .map_err(|error| LaunchError::JavaCheckFailed { + java: java.clone(), + required: merged_profile + .java_version + .as_ref() + .map_or(0, |version| version.major_version), + reason: error.to_string(), + })?; + let platform = &runtime.platform; + let patches = if config.loader == ModLoader::Forge { + patches::load(&minecraft_dir, platform)? + } else { + None + }; + if let Some(patches) = &patches { + merged_profile = resolve::merge_into(patches.profile.clone(), merged_profile); + // The embedded version.json is a complete client profile. Appending + // the old Forge arguments would run its tweakers a second time. + merged_profile.arguments = patches.profile.arguments.clone(); + merged_profile.inherits_from = None; + patches::strip_replaced_libs(&mut merged_profile); + main_class = merged_profile + .main_class + .clone() + .expect("validated patch main class"); + } + check_java_version( + &java, + &runtime, + merged_profile + .java_version + .as_ref() + .map(|version| version.major_version), + )?; + let rule_ctx = RuleContext { + os_name: platform.os_name, + os_version: &platform.os_version, + arch: &platform.arch, + features: ¤t_features, + }; + let asset_index_id = merged_profile + .asset_index + .as_ref() + .map(|index| index.id.clone()) + .unwrap_or_default(); + let natives_dir = platform.natives_directory(meta_dir, &config.game_version); + + // Forge installers can place libraries in the instance instead of the shared cache. + let has_local_libs = + matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge) && patches.is_none(); let local_lib_dir = minecraft_dir.join("libraries"); let library_directory = if has_local_libs { &local_lib_dir @@ -480,6 +517,35 @@ pub async fn build_launch_invocation( &lib_dir }; + let mut to_download = Vec::new(); + for library in &merged_profile.libraries { + if library + .rules + .as_ref() + .is_some_and(|conditions| !rules::evaluate(conditions, &rule_ctx)) + { + continue; + } + // Installer-owned artifacts are already in the instance's library directory. + let local = has_local_libs + && crate::net::mojang::library_artifact_path(library)? + .is_some_and(|path| local_lib_dir.join(path).is_file()); + let mut library = library.clone(); + if local && let Some(downloads) = &mut library.downloads { + downloads.artifact = None; + } + to_download.push(library); + } + crate::net::mojang::download_profile_libraries( + &crate::net::HttpClient::new(), + &to_download, + &lib_dir, + &natives_dir, + platform, + ¤t_features, + ) + .await?; + let mut classpath: Vec = Vec::new(); for lib in &merged_profile.libraries { if let Some(rules) = &lib.rules @@ -488,25 +554,10 @@ pub async fn build_launch_invocation( continue; } - // resolve a relative path for this library. prefer downloads.artifact.path - // when present (vanilla-style), fall back to maven_coord_to_path(name) - // for loader-style entries that only have a coord. - let rel: PathBuf = match lib - .downloads - .as_ref() - .and_then(|d| d.artifact.as_ref()) - .map(|a| PathBuf::from(&a.path)) - .or_else(|| { - crate::instance::loader::maven::maven_coord_to_path(&lib.name).map(PathBuf::from) - }) { - Some(p) => p, - None => continue, + let Some(rel) = crate::net::mojang::library_artifact_path(lib)? else { + continue; }; - // for forge/neoforge, the installer drops some libs (notably the - // bootstrap library) into /.minecraft/libraries/ rather - // than the shared meta cache. check there first regardless of - // whether the lib has a downloads.artifact entry. if has_local_libs { let in_local = local_lib_dir.join(&rel); if in_local.exists() { @@ -524,14 +575,10 @@ pub async fn build_launch_invocation( .join(format!("{}.jar", config.game_version)), ); - // apply loader-specific patches (lwjgl3ify for old forge on java 9+) - let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) { - match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await { - Some(p) => (p.jvm_args, p.main_class, p.extra_args), - None => (Vec::new(), main_class, Vec::new()), - } + let (main_class, extra_args, patch_jvm_args) = if let Some(patches) = patches { + patches::apply(patches, &minecraft_dir, &lib_dir, &mut classpath).await? } else { - (Vec::new(), main_class, Vec::new()) + (main_class, Vec::new(), Vec::new()) }; let sep = if cfg!(windows) { ";" } else { ":" }; @@ -541,32 +588,7 @@ pub async fn build_launch_invocation( .collect::>() .join(sep); - let java = config - .java_path - .clone() - .or_else(|| { - crate::config::SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - }) - .unwrap_or_else(crate::instance::java::detect_java_path); - - check_java_version( - &java, - merged_profile - .java_version - .as_ref() - .map(|version| version.major_version), - ) - .await?; - let assets_root = metadata_paths.assets(); - let natives_dir = metadata_paths - .versions() - .join(&config.game_version) - .join("natives"); let version_type = merged_profile.type_.as_deref().unwrap_or("release"); let resolution_width = resolution.map(|(width, _)| width.to_string()); let resolution_height = resolution.map(|(_, height)| height.to_string()); @@ -601,8 +623,7 @@ pub async fn build_launch_invocation( apply_custom_resolution(&mut game_args, resolution); apply_window_mode(&mut game_args, window_mode); - let (memory_min, memory_max, global_jvm_args, global_environment) = { - let settings = crate::config::SETTINGS.read(); + let (memory_min, memory_max, global_jvm_args) = { ( config .memory_min @@ -613,10 +634,12 @@ pub async fn build_launch_invocation( .clone() .unwrap_or_else(|| settings.defaults.memory_max.clone()), settings.defaults.jvm_args.clone(), - settings.defaults.environment.clone(), ) }; let mut jvm_args: Vec = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")]; + if merged_profile.arguments.is_none() { + jvm_args.push(format!("-Djava.library.path={}", natives_dir.display())); + } jvm_args.extend(patch_jvm_args); jvm_args.extend(upstream_jvm_args); jvm_args.extend(global_jvm_args); @@ -625,9 +648,6 @@ pub async fn build_launch_invocation( jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}")); } - let mut environment = global_environment; - environment.extend(config.environment.clone()); - Ok(LaunchInvocation { java, jvm_args, @@ -644,8 +664,12 @@ pub async fn build_launch_invocation( fn command_process(command: &str) -> tokio::process::Command { #[cfg(windows)] { - let mut process = tokio::process::Command::new("cmd"); - process.args(["/C", command]); + let mut process = tokio::process::Command::new("cmd.exe"); + // cmd parses shell text rather than CRT argv. /S removes this outer pair + // of quotes; raw_arg preserves all quotes and metacharacters inside it. + process + .args(["/D", "/S", "/C"]) + .raw_arg(format!("\"{command}\"")); process } #[cfg(not(windows))] @@ -683,29 +707,66 @@ async fn run_launch_command( .envs(&invocation.environment) .env("INST_NAME", &config.name) .env("INST_ID", &config.name) - .env("INST_DIR", instance_dir) + .env("INST_DIR", std::path::absolute(instance_dir)?) .env("INST_MC_DIR", &invocation.working_dir) .env("INST_JAVA", &invocation.java) - .env("INST_JAVA_ARGS", invocation.jvm_args.join(" ")); - let output = process - .output() - .await - .map_err(|error| LaunchError::Command { + .env("INST_JAVA_ARGS", invocation.jvm_args.join(" ")) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + let (mut child, tree) = + process::spawn_owned(&mut process).map_err(|error| LaunchError::Command { phase, reason: error.to_string(), })?; - for line in String::from_utf8_lossy(&output.stdout).lines() { - tracing::info!("[{}] [{}] {}", config.name, phase, line); + let (sender, mut receiver) = tokio::sync::mpsc::channel(64); + let mut readers = tokio::task::JoinSet::new(); + if let Some(stdout) = child.stdout.take() { + readers.spawn(output::capture( + stdout, + parser::LogStream::Stdout, + sender.clone(), + Default::default(), + )); } - for line in String::from_utf8_lossy(&output.stderr).lines() { - tracing::warn!("[{}] [{}] {}", config.name, phase, line); + if let Some(stderr) = child.stderr.take() { + readers.spawn(output::capture( + stderr, + parser::LogStream::Stderr, + sender.clone(), + Default::default(), + )); } - if output.status.success() { + drop(sender); + let log = |stream, line| match stream { + parser::LogStream::Stdout => tracing::info!("[{}] [{}] {}", config.name, phase, line), + parser::LogStream::Stderr => tracing::warn!("[{}] [{}] {}", config.name, phase, line), + }; + let status = loop { + tokio::select! { + status = child.wait() => break status?, + Some((stream, line)) = receiver.recv() => log(stream, line), + } + }; + let drain_deadline = tokio::time::sleep(std::time::Duration::from_secs(1)); + tokio::pin!(drain_deadline); + loop { + tokio::select! { + line = receiver.recv() => match line { Some((stream, line)) => log(stream, line), None => break }, + _ = &mut drain_deadline => { tracing::warn!("[{phase}] Output pipes remained open after command exit"); break; }, + } + } + // Normal completion can intentionally leave a background command running. + // Cancellation before this point still drops the armed process-tree guard. + tree.detach().map_err(|error| LaunchError::Command { + phase, + reason: error.to_string(), + })?; + if status.success() { Ok(()) } else { Err(LaunchError::Command { phase, - reason: output.status.to_string(), + reason: status.to_string(), }) } } @@ -729,6 +790,13 @@ pub async fn launch( quick_play_world: Option<&str>, ) -> Result<(), LaunchError> { let name = config.name.clone(); + let instance_lock = crate::instance::runtime::lock_instance(instances_dir, &name) + .map_err(|error| LaunchError::Parse(error.to_string()))?; + let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); + let mut kill_rx = Some(kill_rx); + crate::instance::runtime::register_kill(&name, kill_tx); + let launch_cleanup = LaunchCleanup(name.clone()); + crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Authenticating); let mut account_store = crate::auth::AccountStore::load(); account_store @@ -749,7 +817,10 @@ pub async fn launch( } let (token, new_refresh, new_expires) = match acc.account_type { - AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await { + AccountType::Microsoft => match tokio::select! { + result = crate::auth::refresh_and_get_token(&acc) => result, + _ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled), + } { Ok(triple) => triple, Err(e) => return Err(LaunchError::Auth(format!("Authentication failed: {e}"))), }, @@ -770,8 +841,10 @@ pub async fn launch( user_type, }; - let invocation = - build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?; + let invocation = tokio::select! { + result = build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world) => result?, + _ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled), + }; let instance_dir = instances_dir.join(&config.name); tracing::debug!( "[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}", @@ -788,21 +861,20 @@ pub async fn launch( meta_dir, &invocation.working_dir, )?; - if let Err(error) = run_launch_command( + if let Err(error) = tokio::select! { + result = run_launch_command( "Pre-launch", &config.pre_launch_command, config, &invocation, &instance_dir, - ) - .await - { + ) => result, + _ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled), + } { finish_config_sync(config_sync_lock, &invocation.working_dir, &name); return Err(error); } - let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>(); - crate::instance::runtime::register_kill(&name, kill_tx); crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Starting); tracing::info!( "[{}] Starting Minecraft ({} {})", @@ -835,6 +907,7 @@ pub async fn launch( cmd.envs(&invocation.environment); cmd.stdout(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped()); + cmd.kill_on_drop(true); let mut child = match cmd.spawn() { Ok(c) => c, @@ -870,11 +943,11 @@ pub async fn launch( let invocation_for_post_exit = invocation.clone(); tokio::spawn(async move { - use std::io::Write; + let _instance_lock = instance_lock; + let _launch_cleanup = launch_cleanup; use std::sync::{Arc, Mutex}; - use tokio::io::AsyncBufReadExt; use tokio::sync::mpsc; - use tokio::time::{Duration, sleep}; + use tokio::time::Duration; use crate::instance::launch::parser::{LogStream, MinecraftLogParser}; @@ -887,6 +960,9 @@ pub async fn launch( let parser_task = tokio::spawn(async move { let mut parser = MinecraftLogParser::new(); let idle_flush = Duration::from_millis(150); + let mut flush_interval = tokio::time::interval(idle_flush); + flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + flush_interval.tick().await; loop { tokio::select! { @@ -900,7 +976,7 @@ pub async fn launch( None => break, } } - _ = sleep(idle_flush), if parser.has_pending() => { + _ = flush_interval.tick(), if parser.has_pending() => { if let Some(event) = parser.flush() { emit_parsed_instance_log(&parser_name, event); } @@ -913,47 +989,28 @@ pub async fn launch( } }); + let mut readers = tokio::task::JoinSet::new(); if let Some(stdout) = child.stdout.take() { - let w = log_writer.clone(); - let tx = log_tx.clone(); - let mut lines = tokio::io::BufReader::new(stdout).lines(); - tokio::spawn(async move { - while let Ok(Some(line)) = lines.next_line().await { - if let Ok(mut f) = w.lock() - && let Some(f) = f.as_mut() - { - let _ = writeln!(f, "{}", line); - } - if tx.send((LogStream::Stdout, line)).await.is_err() { - break; - } - } - tracing::trace!("Minecraft stdout capture task ended"); - }); + readers.spawn(output::capture( + stdout, + LogStream::Stdout, + log_tx.clone(), + log_writer.clone(), + )); } if let Some(stderr) = child.stderr.take() { - let w = log_writer.clone(); - let tx = log_tx.clone(); - let mut lines = tokio::io::BufReader::new(stderr).lines(); - tokio::spawn(async move { - while let Ok(Some(line)) = lines.next_line().await { - if let Ok(mut f) = w.lock() - && let Some(f) = f.as_mut() - { - let _ = writeln!(f, "{}", line); - } - if tx.send((LogStream::Stderr, line)).await.is_err() { - break; - } - } - tracing::trace!("Minecraft stderr capture task ended"); - }); + readers.spawn(output::capture( + stderr, + LogStream::Stderr, + log_tx.clone(), + log_writer.clone(), + )); } drop(log_tx); let (code, killed_by_user) = tokio::select! { - _ = kill_rx => { + _ = wait_for_kill(&mut kill_rx) => { tracing::info!("[{}] Kill requested, terminating process", name_for_task); let _ = child.kill().await; let _ = child.wait().await; @@ -963,23 +1020,46 @@ pub async fn launch( (result.ok().and_then(|s| s.code()), false) } }; + if tokio::time::timeout(Duration::from_secs(1), async { + while readers.join_next().await.is_some() {} + }) + .await + .is_err() + { + tracing::warn!("Minecraft output pipes remained open after process exit"); + readers.abort_all(); + while readers.join_next().await.is_some() {} + } let _ = parser_task.await; tracing::info!("[{}] Exited with code {:?}", name_for_task, code); - if let Err(error) = run_launch_command( - "Post-exit", - &post_exit_command, - &config_for_post_exit, - &invocation_for_post_exit, - &instance_dir_owned, - ) - .await + if !killed_by_user + && let Err(error) = tokio::select! { + result = run_launch_command( + "Post-exit", + &post_exit_command, + &config_for_post_exit, + &invocation_for_post_exit, + &instance_dir_owned, + ) => result, + _ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled), + } { tracing::warn!("[{}] {}", name_for_task, error); crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string()); } finish_config_sync(config_sync_lock, &minecraft_dir_owned, &name_for_task); + let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned); + if let Err(e) = manager.touch_last_played(&name_for_task) { + tracing::warn!( + "Failed to update last_played for '{}': {}", + name_for_task, + e + ); + } + crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now()); + crate::instance::runtime::cleanup_kill_sender(&name_for_task); if code == Some(0) || killed_by_user { crate::instance::runtime::remove(&name_for_task); tracing::debug!( @@ -1004,17 +1084,6 @@ pub async fn launch( pushed_at: std::time::Instant::now(), }); } - - let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned); - if let Err(e) = manager.touch_last_played(&name_for_task) { - tracing::warn!( - "Failed to update last_played for '{}': {}", - name_for_task, - e - ); - } - crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now()); - crate::instance::runtime::cleanup_kill_sender(&name_for_task); }); Ok(()) diff --git a/src/instance/launch/output.rs b/src/instance/launch/output.rs new file mode 100644 index 0000000..6fe02d9 --- /dev/null +++ b/src/instance/launch/output.rs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt}; + +use super::parser::LogStream; + +pub(super) type LogWriter = Arc>>; + +pub(super) async fn capture( + reader: impl tokio::io::AsyncRead + Unpin, + stream: LogStream, + sender: tokio::sync::mpsc::Sender<(LogStream, String)>, + writer: LogWriter, +) { + use std::io::Write; + let mut reader = tokio::io::BufReader::new(reader); + loop { + let mut bytes = Vec::new(); + match (&mut reader) + .take(64 * 1024) + .read_until(b'\n', &mut bytes) + .await + { + Ok(0) => break, + Ok(_) => {} + Err(error) => { + tracing::warn!("Minecraft output read failed: {error}"); + break; + } + } + if let Ok(mut file) = writer.lock() + && let Some(file) = file.as_mut() + && let Err(error) = file.write_all(&bytes) + { + tracing::warn!("Minecraft log write failed: {error}"); + } + let line = String::from_utf8_lossy(&bytes) + .trim_end_matches(['\r', '\n']) + .to_owned(); + if sender.send((stream, line)).await.is_err() { + break; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn invalid_utf8_and_long_lines_keep_following_output() { + let mut bytes = vec![b'x'; 128 * 1024]; + bytes.extend_from_slice(b"\ninvalid \xff\nlast\n"); + let (sender, mut receiver) = tokio::sync::mpsc::channel(8); + capture( + bytes.as_slice(), + LogStream::Stdout, + sender, + Default::default(), + ) + .await; + let mut lines = Vec::new(); + while let Some((_, line)) = receiver.recv().await { + lines.push(line); + } + assert!(lines.iter().all(|line| line.len() <= 64 * 1024)); + assert!(lines.iter().any(|line| line == "invalid �")); + assert_eq!(lines.last().unwrap(), "last"); + } +} diff --git a/src/instance/launch/parser.rs b/src/instance/launch/parser.rs index f92cf90..5dfcf40 100644 --- a/src/instance/launch/parser.rs +++ b/src/instance/launch/parser.rs @@ -121,7 +121,10 @@ impl MinecraftLogParser { // only hard starts split events. this keeps stacktraces and native // loader bursts together even when they arrive one line at a time. - if should_split(current.kind, analysis.kind) { + if should_split(current.kind, analysis.kind) + || current.lines.len() >= 128 + || current.lines.iter().map(String::len).sum::() >= 64 * 1024 + { let finished = self.current.take().map(finish_event); self.current = Some(PendingEvent::new(stream, line, normalized, analysis)); finished.into_iter().collect() diff --git a/src/instance/launch/patches.rs b/src/instance/launch/patches.rs index 64ce74a..da18e68 100644 --- a/src/instance/launch/patches.rs +++ b/src/instance/launch/patches.rs @@ -7,54 +7,124 @@ use std::path::{Path, PathBuf}; +use super::LaunchError; +use crate::launch_profile::{model::LaunchProfile, system::JavaPlatform}; + const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j"; +#[derive(Debug)] pub struct LwjglifyPatches { - pub jvm_args: Vec, - pub main_class: String, - // extra args inserted before game args (used by the shim to pass - // the real main class name) - pub extra_args: Vec, + pub profile: LaunchProfile, + patches_path: PathBuf, } -pub async fn apply( +pub fn load( minecraft_dir: &Path, - lib_dir: &Path, - classpath: &mut Vec, -) -> Option { + platform: &JavaPlatform, +) -> Result, LaunchError> { + use sha1::Digest; + use std::io::Read; + let mods_dir = minecraft_dir.join("mods"); - let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?; + let Some(lwjgl3ify_jar) = find_lwjgl3ify_jar(&mods_dir)? else { + return Ok(None); + }; + let file = std::fs::File::open(&lwjgl3ify_jar)?; + let mut archive = zip::ZipArchive::new(file).map_err(|error| { + LaunchError::Parse(format!( + "Invalid lwjgl3ify jar {}: {error}", + lwjgl3ify_jar.display() + )) + })?; + let entry = archive + .by_name("me/eigenraven/lwjgl3ify/relauncher/version.json") + .map_err(|error| { + LaunchError::Parse(format!( + "lwjgl3ify bundled client profile is missing in {}: {error}", + lwjgl3ify_jar.display() + )) + })?; + let mut profile: LaunchProfile = serde_json::from_reader(entry)?; + if profile + .main_class + .as_deref() + .is_none_or(|main| main.trim().is_empty()) + || profile.arguments.is_none() + || profile + .java_version + .as_ref() + .is_none_or(|version| version.major_version == 0) + { + return Err(LaunchError::Parse( + "lwjgl3ify bundled client profile is missing mainClass, arguments or javaVersion" + .into(), + )); + } + for lib in &profile.libraries { + if lib + .downloads + .as_ref() + .is_none_or(|downloads| downloads.artifact.is_none() && lib.natives.is_none()) + { + return Err(LaunchError::Parse(format!( + "lwjgl3ify bundled library {} is missing download metadata", + lib.name + ))); + } + } + select_lwjgl_natives(&mut profile, platform)?; + + let patch_artifact = profile + .libraries + .iter() + .find(|lib| lib.name.ends_with(":forgePatches")) + .and_then(|lib| lib.downloads.as_ref()) + .and_then(|downloads| downloads.artifact.as_ref()) + .ok_or_else(|| { + LaunchError::Parse( + "lwjgl3ify bundled profile is missing the forgePatches artifact".into(), + ) + })?; + let mut payload = Vec::new(); + archive + .by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip") + .map_err(|error| { + LaunchError::Parse(format!( + "lwjgl3ify forgePatches payload is missing: {error}" + )) + })? + .read_to_end(&mut payload)?; + if payload.len() as u64 != patch_artifact.size + || !format!("{:x}", sha1::Sha1::digest(&payload)).eq_ignore_ascii_case(&patch_artifact.sha1) + { + return Err(LaunchError::Parse( + "lwjgl3ify embedded forgePatches does not match its bundled profile".into(), + )); + } + profile + .libraries + .retain(|lib| !lib.name.ends_with(":forgePatches")); // rfb only scans jars for plugin metadata. keeping the extracted // forgePatches payload as a zip makes it skip rfb-asm-safety and // rfb-modern-java, which GTNH needs on modern Java. - let patches_dest = minecraft_dir.join(".forge-patches.jar"); + let patches_path = minecraft_dir.join(".forge-patches.jar"); + crate::storage::write_atomic(&patches_path, &payload)?; + Ok(Some(LwjglifyPatches { + profile, + patches_path, + })) +} - if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) { - tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}"); - return None; - } - - classpath.insert(0, patches_dest.clone()); - - let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default(); - - // RFB requires its own classloader to be the system classloader, and - // its Main class handles bootstrapping into launchwrapper. - // the other flags match lwjgl3ify's java9args.txt. - jvm_args.extend([ - "-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader" - .to_string(), - "-Dfile.encoding=UTF-8".to_string(), - ]); - - // forge patches replace launchwrapper, asm, and old lwjgl2. - // lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3 - // must be on the classpath (matching what prism does). - strip_replaced_libs(classpath); - add_lwjgl3(lib_dir, classpath); - - replace_log4j_fixed(lib_dir, classpath).await; +pub async fn apply( + patches: LwjglifyPatches, + minecraft_dir: &Path, + lib_dir: &Path, + classpath: &mut Vec, +) -> Result<(String, Vec, Vec), LaunchError> { + classpath.insert(0, patches.patches_path); + replace_log4j_fixed(lib_dir, classpath).await?; + let mut jvm_args = Vec::new(); // on java 24+, SecurityManager.getClassContext() was reimplemented to use // StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to @@ -63,7 +133,7 @@ pub async fn apply( // ThrowableProxy... infinite recursion. we break the loop by providing a // log4j config that sets the root level to INFO, so the debug() call in // LaunchClassLoader is a no-op and never creates a ThrowableProxy. - write_log4j_config(minecraft_dir, &mut jvm_args); + write_log4j_config(minecraft_dir, &mut jvm_args)?; // RfbSystemClassLoader discovers plugins differently depending on whether // the main class is loaded by the JVM directly or through the system @@ -72,81 +142,57 @@ pub async fn apply( // ClassCircularityErrors. we use a tiny shim jar that loads the real main // class through ClassLoader.getSystemClassLoader().loadClass(), matching // how prism's EntryPoint does it. - let shim_path = deploy_shim(minecraft_dir); + let shim_path = deploy_shim(minecraft_dir)?; classpath.insert(0, shim_path); - Some(LwjglifyPatches { + Ok(( + "RmclShim".to_owned(), + vec![ + patches + .profile + .main_class + .expect("validated client main class"), + ], jvm_args, - main_class: "RmclShim".to_string(), - extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()], - }) + )) } const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmcl-shim.jar")); -fn deploy_shim(minecraft_dir: &Path) -> PathBuf { +fn deploy_shim(minecraft_dir: &Path) -> std::io::Result { let dest = minecraft_dir.join(".rmcl-shim.jar"); - if let Err(e) = std::fs::write(&dest, SHIM_JAR) { - tracing::warn!("Failed to write rmcl-shim.jar: {e}"); - } - dest + crate::storage::write_atomic(&dest, SHIM_JAR)?; + Ok(dest) } -fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option { - let entries = std::fs::read_dir(mods_dir).ok()?; - for entry in entries.flatten() { +fn find_lwjgl3ify_jar(mods_dir: &Path) -> std::io::Result> { + let entries = match std::fs::read_dir(mods_dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let mut found = None; + for entry in entries { + let entry = entry?; let name = entry.file_name(); let name = name.to_string_lossy(); if name.starts_with("lwjgl3ify") && name.ends_with(".jar") { - return Some(entry.path()); - } - } - None -} - -fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> { - use std::io::Read; - - let file = std::fs::File::open(lwjgl3ify_jar)?; - let mut archive = zip::ZipArchive::new(file) - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; - let mut entry = archive - .by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip") - .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?; - let mut buf = Vec::new(); - entry.read_to_end(&mut buf)?; - std::fs::write(dest, &buf) -} - -fn parse_add_opens(patches_archive: &Path) -> Option> { - use std::io::Read; - - let file = std::fs::File::open(patches_archive).ok()?; - let mut archive = zip::ZipArchive::new(file).ok()?; - let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?; - let mut manifest = String::new(); - entry.read_to_string(&mut manifest).ok()?; - - // manifest continuation lines start with a single space - let manifest = manifest.replace("\r\n ", "").replace("\n ", ""); - - let mut args = Vec::new(); - for line in manifest.lines() { - if let Some(value) = line.strip_prefix("Add-Opens: ") { - for module_package in value.split_whitespace() { - args.push("--add-opens".to_string()); - args.push(format!("{module_package}=ALL-UNNAMED")); + if found.is_some() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Multiple lwjgl3ify jars found in mods", + )); } + found = Some(entry.path()); } } - - Some(args) + Ok(found) } // strips libraries from the classpath that are replaced by forge patches // or not needed with lwjgl3ify. matches what prism's component system does: // no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs. -fn strip_replaced_libs(classpath: &mut Vec) { +pub fn strip_replaced_libs(profile: &mut LaunchProfile) { let replaced = [ "launchwrapper-", "asm-all-", @@ -157,76 +203,83 @@ fn strip_replaced_libs(classpath: &mut Vec) { "guava-15.", ]; - classpath.retain(|entry| { - let name = entry - .file_name() - .map(|n| n.to_string_lossy()) - .unwrap_or_default(); - let dominated = replaced.iter().any(|prefix| name.starts_with(prefix)); + profile.libraries.retain(|lib| { + if lib.name.starts_with("org.lwjgl.lwjgl:") { + return false; + } + let name = lib.name.split(':').collect::>(); + let filename = match name.as_slice() { + [_, artifact, version, ..] => format!("{artifact}-{version}"), + _ => return true, + }; + let dominated = replaced.iter().any(|prefix| filename.starts_with(prefix)); if dominated { - tracing::info!("Stripping {name} from classpath (replaced by forge-patches)"); + tracing::info!("Stripping {} (replaced by forge-patches)", lib.name); } !dominated }); } -// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls -// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system -// classpath for this to work. prism includes these via its org.lwjgl3 -// component; we add them from the meta library cache. -fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec) { - let lwjgl3_modules = [ - "lwjgl", - "lwjgl-freetype", - "lwjgl-glfw", - "lwjgl-jemalloc", - "lwjgl-openal", - "lwjgl-opengl", - "lwjgl-stb", - "lwjgl-tinyfd", - ]; - - let os_classifier = match std::env::consts::OS { - "macos" => "natives-macos", - "windows" => "natives-windows", - _ => "natives-linux", +// The bundled profile names natives as separate Maven artifacts and uses +// OS-only rules for multiple CPU variants. Select exactly the selected JVM's variant. +fn select_lwjgl_natives( + profile: &mut LaunchProfile, + platform: &JavaPlatform, +) -> Result<(), LaunchError> { + let classifier = match (platform.os_name, platform.arch.as_str(), platform.bitness) { + ("osx", "arm64", 64) => "natives-macos-arm64", + ("osx", "x86_64", 64) => "natives-macos", + ("windows", "arm64", 64) => "natives-windows-arm64", + ("windows", "x86", 32) => "natives-windows-x86", + ("windows", "x86_64", 64) => "natives-windows", + ("linux", "arm64", 64) => "natives-linux-arm64", + ("linux", "arm", 32) => "natives-linux-arm32", + ("linux", "ppc64le", 64) => "natives-linux-ppc64le", + ("linux", "x86_64", 64) => "natives-linux", + _ => { + return Err(LaunchError::Parse(format!( + "lwjgl3ify does not support Java {} {} ({}-bit)", + platform.os_name, platform.arch, platform.bitness + ))); + } }; - - // insert lwjgl3 jars right after forge patches (position 1+) - let mut insert_pos = 1.min(classpath.len()); - for module in &lwjgl3_modules { - let base = if *module == "lwjgl" { - lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar") - } else { - lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module)) - }; - if base.exists() { - classpath.insert(insert_pos, base); - insert_pos += 1; + let native = |name: &str| -> Option<(String, String)> { + let parts: Vec<_> = name.split(':').collect(); + match parts.as_slice() { + ["org.lwjgl", artifact, _, variant] if variant.starts_with("natives-") => { + Some(((*artifact).to_owned(), (*variant).to_owned())) + } + ["org.lwjgl", artifact, _] => artifact + .split_once("-natives-") + .map(|(module, variant)| (module.to_owned(), format!("natives-{variant}"))), + _ => None, } - - let natives = if *module == "lwjgl" { - lib_dir.join(format!( - "org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar" - )) - } else { - lib_dir.join(format!( - "org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar", - module, os_classifier - )) + }; + let mut native_modules = std::collections::HashSet::new(); + let mut selected = std::collections::HashSet::new(); + profile.libraries.retain(|lib| { + let Some((module, variant)) = native(&lib.name) else { + return true; }; - if natives.exists() { - classpath.insert(insert_pos, natives); - insert_pos += 1; + native_modules.insert(module.clone()); + if variant == classifier { + selected.insert(module); + true + } else { + false } + }); + if let Some(missing) = native_modules.difference(&selected).next() { + return Err(LaunchError::Parse(format!( + "lwjgl3ify bundled profile has no {classifier} for {missing}" + ))); } - - tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1); + Ok(()) } // Suppresses LaunchClassLoader's debug() call to avoid the // ThrowableProxy -> SecurityManager -> StackWalker recursion on Java 24+. -fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec) { +fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec) -> std::io::Result<()> { let config_path = minecraft_dir.join(".rmcl-log4j2.xml"); let config = r#" @@ -255,15 +308,13 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec) { "#; - if let Err(e) = std::fs::write(&config_path, config) { - tracing::warn!("Failed to write log4j2 config: {e}"); - return; - } + crate::storage::write_atomic(&config_path, config.as_bytes())?; jvm_args.push(format!( "-Dlog4j.configurationFile={}", config_path.display() )); + Ok(()) } // replaces log4j-api and log4j-core 2.0-beta9 in the classpath with @@ -272,7 +323,7 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec) { // on java 24+ uses StackWalker internally, triggering class loading // through LaunchClassLoader, which triggers more logging, infinite // recursion, stack overflow. the fixed builds patch this out. -async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) { +async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) -> Result<(), LaunchError> { let replacements = [ ( "log4j-api-2.0-beta9.jar", @@ -287,20 +338,18 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) { ]; for (old_name, fixed_rel, url) in &replacements { + if !classpath + .iter() + .any(|entry| entry.file_name().is_some_and(|name| name == *old_name)) + { + continue; + } let fixed_path = lib_dir.join(fixed_rel); if !fixed_path.exists() { tracing::info!("Downloading patched {old_name}..."); - if let Some(parent) = fixed_path.parent() { - let _ = tokio::fs::create_dir_all(parent).await; - } let client = crate::net::HttpClient::new(); - if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await { - tracing::error!( - "Failed to download patched {old_name}: {e}, continuing with unpatched version" - ); - continue; - } + crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await?; } for entry in classpath.iter_mut() { @@ -313,6 +362,7 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) { } } } + Ok(()) } #[cfg(test)] diff --git a/src/instance/loader/forge.rs b/src/instance/loader/forge.rs index 343fc08..71eb954 100644 --- a/src/instance/loader/forge.rs +++ b/src/instance/loader/forge.rs @@ -4,7 +4,7 @@ // Old Forge installers cannot run headless, so their profiles and libraries // must be extracted from the jar instead. -use std::path::Path; +use std::{collections::BTreeMap, path::Path}; use async_trait::async_trait; @@ -48,17 +48,24 @@ impl ModLoaderInstaller for ForgeInstaller { instance_dir: &Path, meta_dir: &Path, ) -> Result<(), InstallError> { + let settings = crate::config::SETTINGS.read().clone(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &Default::default(), + ); self.install_with_java( client, game_version, loader_version, instance_dir, meta_dir, - None, + settings.paths.effective_java_path(), + &environment, ) .await } + #[allow(clippy::too_many_arguments)] async fn install_with_java( &self, client: &HttpClient, @@ -67,6 +74,7 @@ impl ModLoaderInstaller for ForgeInstaller { instance_dir: &Path, meta_dir: &Path, java_path: Option<&str>, + environment: &BTreeMap, ) -> Result<(), InstallError> { let installer_jar = instance_dir .join(crate::storage::MINECRAFT_DIR_NAME) @@ -93,16 +101,9 @@ impl ModLoaderInstaller for ForgeInstaller { return Err(e); } } else { - let java_path = java_path.map(str::to_owned).unwrap_or_else(|| { - crate::config::SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - .unwrap_or_else(crate::instance::java::detect_java_path) - }); - tracing::debug!("Running Forge installer with Java {}", java_path); - if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await { + if let Err(e) = + run_forge_installer(&installer_jar, instance_dir, java_path, environment).await + { let _ = tokio::fs::remove_file(&installer_jar).await; return Err(InstallError::Installer(e)); } @@ -127,19 +128,26 @@ impl ModLoaderInstaller for ForgeInstaller { pub async fn run_forge_installer( installer_path: &Path, instance_dir: &Path, - java_path: &str, + java_path: Option<&str>, + environment: &BTreeMap, ) -> Result<(), InstallerError> { use tokio::process::Command; set_action("Running Forge installer..."); + let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?; + let java_path = + crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment); + tracing::debug!("Running Forge installer with Java {}", java_path); - let output = match Command::new(java_path) - .arg("-jar") - .arg(installer_path) - .arg("--installClient") - .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) - .output() - .await + let output = match crate::instance::process::output( + Command::new(&java_path) + .arg("-jar") + .arg(std::path::absolute(installer_path)?) + .arg("--installClient") + .current_dir(&minecraft_dir) + .envs(environment), + ) + .await { Ok(o) => o, Err(e) => { @@ -347,12 +355,7 @@ pub(crate) async fn install_forge_from_profile( // inheritsFrom field - implicitly inherits from the configured game // version so vanilla libraries layer in via resolve(). // - // we use serde_json::to_vec (not the pretty-print variant via - // save_profile_json) so the written file is content-faithful: every - // field present in the installer's versionInfo round-trips. key order - // and whitespace may differ from the original installer JSON because - // the source is a serde_json::Value (which doesn't preserve order), - // but no field is silently dropped. + // Keep unknown installer fields instead of round-tripping a stripped profile model. let serialized = serde_json::to_vec(version_info).map_err(|e| { InstallError::Installer(InstallerError::Profile(format!( "Failed to serialize Forge profile: {e}" diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 4e18c94..5c17800 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -8,7 +8,7 @@ pub mod neoforge; mod quilt; mod vanilla; -use std::path::Path; +use std::{collections::BTreeMap, path::Path}; use async_trait::async_trait; use thiserror::Error; @@ -63,6 +63,7 @@ pub trait ModLoaderInstaller: Send + Sync { meta_dir: &Path, ) -> Result<(), InstallError>; + #[allow(clippy::too_many_arguments)] async fn install_with_java( &self, client: &HttpClient, @@ -70,9 +71,9 @@ pub trait ModLoaderInstaller: Send + Sync { loader_version: &str, instance_dir: &Path, meta_dir: &Path, - java_path: Option<&str>, + _java_path: Option<&str>, + _environment: &BTreeMap, ) -> Result<(), InstallError> { - let _ = java_path; self.install(client, game_version, loader_version, instance_dir, meta_dir) .await } diff --git a/src/instance/loader/neoforge.rs b/src/instance/loader/neoforge.rs index 8f16ee8..7039117 100644 --- a/src/instance/loader/neoforge.rs +++ b/src/instance/loader/neoforge.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -use std::path::Path; +use std::{collections::BTreeMap, path::Path}; use async_trait::async_trait; @@ -45,17 +45,24 @@ impl ModLoaderInstaller for NeoForgeInstaller { instance_dir: &Path, meta_dir: &Path, ) -> Result<(), InstallError> { + let settings = crate::config::SETTINGS.read().clone(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &Default::default(), + ); self.install_with_java( client, game_version, loader_version, instance_dir, meta_dir, - None, + settings.paths.effective_java_path(), + &environment, ) .await } + #[allow(clippy::too_many_arguments)] async fn install_with_java( &self, client: &HttpClient, @@ -64,6 +71,7 @@ impl ModLoaderInstaller for NeoForgeInstaller { instance_dir: &Path, meta_dir: &Path, java_path: Option<&str>, + environment: &BTreeMap, ) -> Result<(), InstallError> { let installer_jar = instance_dir .join(crate::storage::MINECRAFT_DIR_NAME) @@ -73,16 +81,9 @@ impl ModLoaderInstaller for NeoForgeInstaller { neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?; - let java_path = java_path.map(str::to_owned).unwrap_or_else(|| { - crate::config::SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - .unwrap_or_else(crate::instance::java::detect_java_path) - }); - tracing::debug!("Running NeoForge installer with Java {}", java_path); - if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await { + if let Err(e) = + run_neoforge_installer(&installer_jar, instance_dir, java_path, environment).await + { let _ = tokio::fs::remove_file(&installer_jar).await; return Err(InstallError::Installer(e)); } @@ -102,20 +103,27 @@ impl ModLoaderInstaller for NeoForgeInstaller { pub async fn run_neoforge_installer( installer_path: &Path, instance_dir: &Path, - java_path: &str, + java_path: Option<&str>, + environment: &BTreeMap, ) -> Result<(), InstallerError> { use tokio::process::Command; set_action("Running NeoForge installer..."); + let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?; + let java_path = + crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment); + tracing::debug!("Running NeoForge installer with Java {}", java_path); - let output = match Command::new(java_path) - .arg(format!("-Duser.home={}", instance_dir.display())) - .arg("-jar") - .arg(installer_path) - .arg("--installClient") - .current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)) - .output() - .await + let output = match crate::instance::process::output( + Command::new(&java_path) + .arg("-jar") + .arg(std::path::absolute(installer_path)?) + .arg("--installClient") + .arg(&minecraft_dir) + .current_dir(&minecraft_dir) + .envs(environment), + ) + .await { Ok(o) => o, Err(e) => { diff --git a/src/instance/loader/vanilla.rs b/src/instance/loader/vanilla.rs index 8dc0520..7e49781 100644 --- a/src/instance/loader/vanilla.rs +++ b/src/instance/loader/vanilla.rs @@ -1,9 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// vanilla "installer". doesn't actually install anything since the launch -// process already handles downloading vanilla assets/libraries. this just -// exists so vanilla fits the same ModLoaderInstaller trait as everyone else. +// InstanceManager prepares vanilla artifacts; this implements the shared loader contract. use std::path::Path; diff --git a/src/instance/manager.rs b/src/instance/manager.rs index 6a46f29..0948fd9 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -123,7 +123,13 @@ impl InstanceManager { loader_version: Option<&str>, instance_dir: &std::path::Path, ) -> Result { + let settings = crate::config::SETTINGS.read().clone(); + let instance_dir = std::path::absolute(instance_dir)?; let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &Default::default(), + ); tracing::debug!( "Preparing Minecraft directory for '{}': {}", name, @@ -134,6 +140,11 @@ impl InstanceManager { std::fs::create_dir_all(&path)?; tracing::trace!("Ensured instance subdirectory {}", path.display()); } + let java_path = crate::instance::java::resolve_java_path_in( + settings.paths.effective_java_path(), + &minecraft_dir, + &environment, + ); // forge insists on this file existing, even if it's empty json. thanks forge. let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json"); @@ -203,7 +214,19 @@ impl InstanceManager { crate::storage::write_atomic(&meta_json_path, &raw_meta_bytes)?; tracing::debug!("Saved version meta to {}", meta_json_path.display()); - crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?; + let runtime = crate::instance::java::probe_java_in( + Path::new(&java_path), + &minecraft_dir, + &environment, + ) + .await?; + crate::net::mojang::download_libraries_for_platform( + &self.client, + &version_meta, + &self.meta_dir, + &runtime.platform, + ) + .await?; crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?; @@ -225,12 +248,14 @@ impl InstanceManager { name ); installer - .install( + .install_with_java( &self.client, game_version, effective_loader_version, - instance_dir, + &instance_dir, &self.meta_dir, + Some(&java_path), + &environment, ) .await .map_err(|e| match e { @@ -240,7 +265,7 @@ impl InstanceManager { } })?; - let defaults = crate::config::SETTINGS.read().defaults.clone(); + let defaults = &settings.defaults; let config = InstanceConfig { name: name.to_string(), game_version: game_version.to_string(), @@ -273,6 +298,23 @@ impl InstanceManager { } pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> { + validate_name(&config.name)?; + let settings = crate::config::SETTINGS.read().clone(); + let instance_dir = std::path::absolute(self.instances_dir.join(&config.name))?; + let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(&minecraft_dir)?; + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &config.environment, + ); + let java_path = crate::instance::java::resolve_java_path_in( + config + .java_path + .as_deref() + .or(settings.paths.effective_java_path()), + &minecraft_dir, + &environment, + ); let task = crate::feedback::progress::ProgressTask::start(format!( "Rebuilding runtime for '{}'", config.name @@ -352,7 +394,19 @@ impl InstanceManager { if fetched_meta { crate::storage::write_atomic(&meta_path, &raw_meta)?; } - crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?; + let runtime = crate::instance::java::probe_java_in( + Path::new(&java_path), + &minecraft_dir, + &environment, + ) + .await?; + crate::net::mojang::download_libraries_for_platform( + &self.client, + &version_meta, + &self.meta_dir, + &runtime.platform, + ) + .await?; crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?; if config.loader != ModLoader::Vanilla { @@ -368,9 +422,10 @@ impl InstanceManager { &self.client, &config.game_version, loader_version, - &self.instances_dir.join(&config.name), + &instance_dir, &self.meta_dir, - config.java_path.as_deref(), + Some(&java_path), + &environment, ) .await .map_err(|error| match error { diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 6145a76..8b73d8b 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -11,6 +11,7 @@ pub mod loader; pub mod logs; pub mod manager; pub mod models; +mod process; pub mod runtime; pub mod screenshots; diff --git a/src/instance/process.rs b/src/instance/process.rs new file mode 100644 index 0000000..ae75d1b --- /dev/null +++ b/src/instance/process.rs @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::io; +use tokio::process::{Child, Command}; + +/// Own descendants until completion or cancellation. +pub(super) fn spawn_owned(command: &mut Command) -> io::Result<(Child, ProcessTree)> { + command.kill_on_drop(true); + #[cfg(unix)] + { + command.process_group(0); + let child = command.spawn()?; + let tree = ProcessTree(Some( + child.id().expect("newly spawned child has an ID") as i32 + )); + Ok((child, tree)) + } + #[cfg(windows)] + { + windows::spawn(command) + } +} + +pub(super) async fn output(command: &mut Command) -> io::Result { + command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()); + let (child, _tree) = spawn_owned(command)?; + child.wait_with_output().await +} + +#[cfg(unix)] +pub(super) struct ProcessTree(Option); + +#[cfg(unix)] +impl ProcessTree { + pub(super) fn detach(mut self) -> io::Result<()> { + self.0 = None; + Ok(()) + } +} + +#[cfg(unix)] +impl Drop for ProcessTree { + fn drop(&mut self) { + let Some(group) = self.0 else { + return; + }; + // SAFETY: a negative PID addresses only the group created for this command. + if unsafe { libc::kill(-group, libc::SIGKILL) } == -1 { + let error = io::Error::last_os_error(); + if error.raw_os_error() != Some(libc::ESRCH) { + tracing::warn!("Failed to terminate process group {group}: {error}"); + } + } + } +} + +#[cfg(windows)] +pub(super) struct ProcessTree { + _job: std::os::windows::io::OwnedHandle, +} + +#[cfg(windows)] +impl ProcessTree { + pub(super) fn detach(self) -> io::Result<()> { + windows::set_kill_on_close(&self._job, false) + } +} + +#[cfg(windows)] +mod windows { + use super::*; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use windows_sys::Win32::{ + Foundation::{HANDLE, INVALID_HANDLE_VALUE}, + System::{ + Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, + Thread32Next, + }, + JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, + SetInformationJobObject, + }, + Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME}, + }, + }; + + fn own_handle(handle: HANDLE) -> io::Result { + if handle.is_null() || handle == INVALID_HANDLE_VALUE { + Err(io::Error::last_os_error()) + } else { + // SAFETY: these APIs return a new handle owned by the caller. + Ok(unsafe { OwnedHandle::from_raw_handle(handle) }) + } + } + + pub(super) fn set_kill_on_close(job: &OwnedHandle, kill: bool) -> io::Result<()> { + let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION { + BasicLimitInformation: + windows_sys::Win32::System::JobObjects::JOBOBJECT_BASIC_LIMIT_INFORMATION { + LimitFlags: if kill { + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + } else { + 0 + }, + ..Default::default() + }, + ..Default::default() + }; + // SAFETY: the buffer has the required size and lives through the call. + if unsafe { + SetInformationJobObject( + job.as_raw_handle(), + JobObjectExtendedLimitInformation, + (&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(), + std::mem::size_of_val(&limits) as u32, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + + pub(super) fn spawn(command: &mut Command) -> io::Result<(Child, ProcessTree)> { + // SAFETY: null security/name pointers request a private, unnamed job. + let job = own_handle(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) })?; + set_kill_on_close(&job, true)?; + // Suspend before job assignment so the shell cannot spawn unowned children. + command.creation_flags(CREATE_SUSPENDED); + let child = command.spawn()?; + let process = child + .raw_handle() + .ok_or_else(|| io::Error::other("Process handle is unavailable"))?; + // SAFETY: both handles are live and the child has not started running. + if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process) } == 0 { + return Err(io::Error::last_os_error()); + } + let tree = ProcessTree { _job: job }; + resume_main_thread(child.id().expect("newly spawned child has an ID"))?; + Ok((child, tree)) + } + + // Tokio retains the process handle but not the primary thread handle. + fn resume_main_thread(pid: u32) -> io::Result<()> { + // SAFETY: the snapshot and entry buffer are owned here. + let snapshot = own_handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) })?; + let mut entry = THREADENTRY32 { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let mut found = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) }; + while found != 0 { + if entry.th32OwnerProcessID == pid { + // A suspended, newly-created process has only its primary thread. + let thread = own_handle(unsafe { + OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) + })?; + if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX { + return Err(io::Error::last_os_error()); + } + return Ok(()); + } + found = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) }; + } + Err(io::Error::other(format!( + "Cannot find the primary thread of process {pid}" + ))) + } +} diff --git a/src/instance/runtime.rs b/src/instance/runtime.rs index c2d19e5..605fdb9 100644 --- a/src/instance/runtime.rs +++ b/src/instance/runtime.rs @@ -17,14 +17,11 @@ pub enum RunState { pub static RUNNING: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); -// queued up so the TUI event loop can flush these to disk in batch, -// the child process monitor shouldn't be writing config files directly +// The monitor persists timestamps; the TUI drains these to update its cached instances. type PendingLastPlayed = Arc)>>>; pub static PENDING_LAST_PLAYED: LazyLock = LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); -// oneshot channels to signal a running instance to stop. -// send_kill fires the channel, the launch task receives it and kills the child process. type KillSenders = Arc>>>; pub static KILL_SENDERS: LazyLock = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new()))); @@ -114,6 +111,28 @@ pub fn cleanup_kill_sender(name: &str) { } } +pub(crate) fn lock_instance( + root: &std::path::Path, + name: &str, +) -> Result { + crate::instance::manager::validate_name(name)?; + let locks = root.join(".rmcl-locks"); + std::fs::create_dir_all(&locks)?; + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(locks.join(format!("{name}.lock")))?; + match file.try_lock() { + Ok(()) => Ok(file), + Err(std::fs::TryLockError::WouldBlock) => Err( + crate::instance::manager::InstanceError::InstanceRunning(name.to_owned()), + ), + Err(std::fs::TryLockError::Error(error)) => Err(error.into()), + } +} + #[cfg(test)] #[path = "tests/runtime.rs"] mod tests; diff --git a/src/instance/tests/launch/parser.rs b/src/instance/tests/launch/parser.rs index d82c1f6..662b34b 100644 --- a/src/instance/tests/launch/parser.rs +++ b/src/instance/tests/launch/parser.rs @@ -1,6 +1,22 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +#[test] +fn plain_output_emits_before_eof_and_bounds_pending_lines() { + let mut parser = super::MinecraftLogParser::new(); + let mut emitted = Vec::new(); + for _ in 0..300 { + emitted.extend(parser.push_line(super::LogStream::Stdout, "plain output")); + } + assert!(!emitted.is_empty()); + emitted.extend(parser.flush()); + assert_eq!( + emitted.iter().map(|event| event.lines.len()).sum::(), + 300 + ); + assert!(emitted.iter().all(|event| event.lines.len() <= 128)); +} + use super::*; fn parse_all(lines: &[(LogStream, &str)]) -> Vec { diff --git a/src/instance/tests/launch/patches.rs b/src/instance/tests/launch/patches.rs index b144d3c..1eb9af4 100644 --- a/src/instance/tests/launch/patches.rs +++ b/src/instance/tests/launch/patches.rs @@ -2,132 +2,241 @@ // SPDX-License-Identifier: GPL-3.0-only use super::*; +use crate::launch_profile::model::Library; +use serde_json::json; use std::io::Write; fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf { let path = tmp.join(name); let file = std::fs::File::create(&path).unwrap(); let mut zip = zip::ZipWriter::new(file); - let opts: zip::write::SimpleFileOptions = Default::default(); for (filename, bytes) in entries { - zip.start_file(*filename, opts).unwrap(); + zip.start_file(*filename, zip::write::SimpleFileOptions::default()) + .unwrap(); zip.write_all(bytes).unwrap(); } zip.finish().unwrap(); path } +fn lib(name: &str) -> Library { + Library { + name: name.to_owned(), + ..Default::default() + } +} + #[test] fn strip_replaced_libs_removes_dominated_prefixes() { - let mut classpath = vec![ - PathBuf::from("/libs/launchwrapper-1.12.jar"), - PathBuf::from("/libs/asm-all-5.0.3.jar"), - PathBuf::from("/libs/lwjgl-2.9.4.jar"), - PathBuf::from("/libs/lwjgl_util-2.9.4.jar"), - PathBuf::from("/libs/commons-compress-1.4.1.jar"), - PathBuf::from("/libs/commons-io-2.4.jar"), - PathBuf::from("/libs/guava-15.0.jar"), - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/guava-21.0.jar"), - ]; - strip_replaced_libs(&mut classpath); + let mut profile = LaunchProfile { + libraries: [ + "net.minecraft:launchwrapper:1.12", + "org.ow2.asm:asm-all:5.0.3", + "org.lwjgl.lwjgl:lwjgl:2.9.4", + "org.lwjgl.lwjgl:lwjgl_util:2.9.4", + "org.apache.commons:commons-compress:1.4.1", + "commons-io:commons-io:2.4", + "com.google.guava:guava:15.0", + "org.apache.logging.log4j:log4j-core:2.0", + "com.google.guava:guava:21.0", + ] + .into_iter() + .map(lib) + .collect(), + ..Default::default() + }; + strip_replaced_libs(&mut profile); assert_eq!( - classpath, - vec![ - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/guava-21.0.jar"), + profile + .libraries + .iter() + .map(|lib| lib.name.as_str()) + .collect::>(), + [ + "org.apache.logging.log4j:log4j-core:2.0", + "com.google.guava:guava:21.0", ] ); } #[test] fn strip_replaced_libs_keeps_unrelated_entries() { - let mut classpath = vec![ - PathBuf::from("/libs/log4j-core-2.0.jar"), - PathBuf::from("/libs/mixin-0.8.5.jar"), - ]; - let original = classpath.clone(); - strip_replaced_libs(&mut classpath); - assert_eq!(classpath, original); + let mut profile = LaunchProfile { + libraries: vec![ + lib("org.apache.logging.log4j:log4j-core:2.0"), + lib("org.spongepowered:mixin:0.8.5"), + ], + ..Default::default() + }; + let original = profile.clone(); + strip_replaced_libs(&mut profile); + assert_eq!(profile, original); +} + +fn bundled_profile() -> LaunchProfile { + // Same three-part native coordinates and overlapping OS rules as release 3.0.35. + let mut libraries = Vec::new(); + for module in ["lwjgl", "lwjgl-sdl", "lwjgl-spng"] { + libraries.push(json!({"name":format!("org.lwjgl:{module}:3.4.2"), "downloads":{"artifact":{ + "url":format!("https://example.invalid/{module}-3.4.2.jar"), "sha1":"0".repeat(40), "size":1, + }}})); + for (classifier, os) in [ + ("natives-linux", "linux"), + ("natives-linux-arm64", "linux"), + ("natives-macos", "osx"), + ("natives-macos-arm64", "osx"), + ("natives-windows", "windows"), + ("natives-windows-x86", "windows"), + ("natives-windows-arm64", "windows"), + ] { + libraries.push(json!({"name":format!("org.lwjgl:{module}-{classifier}:3.4.2"), + "rules":[{"action":"allow", "os":{"name":os}}], "downloads":{"artifact":{ + "url":format!("https://example.invalid/{module}-3.4.2-{classifier}.jar"), "sha1":"0".repeat(40), "size":1, + }}})); + } + } + serde_json::from_value(json!({"id":"lwjgl3ify-client", "mainClass":"com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread", + "javaVersion":{"majorVersion":25}, "libraries":libraries, + "arguments":{"game":["--username", "${auth_player_name}"], "jvm":[ + {"rules":[{"action":"allow", "os":{"name":"osx"}}], "value":"-XstartOnFirstThread"}, + "--add-opens", "java.base/java.lang=ALL-UNNAMED", + "-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader", + ]}, + })).unwrap() } #[test] -fn parse_add_opens_extracts_module_args() { - let tmp = tempfile::tempdir().unwrap(); - let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n"; - let zip_path = make_zip( - tmp.path(), +fn bundled_natives_follow_selected_java_on_all_platforms() { + for (os, arch, bits, expected) in [ + ("Linux", "amd64", "64", "natives-linux"), + ("Linux", "aarch64", "64", "natives-linux-arm64"), + ("Mac OS X", "amd64", "64", "natives-macos"), + ("Mac OS X", "aarch64", "64", "natives-macos-arm64"), + ("Windows 10", "x86", "32", "natives-windows-x86"), + ("Windows 10", "amd64", "64", "natives-windows"), + ("Windows 10", "aarch64", "64", "natives-windows-arm64"), + ] { + let platform = JavaPlatform::from_java_properties(os, arch, bits, "10.0").unwrap(); + let mut profile = bundled_profile(); + select_lwjgl_natives(&mut profile, &platform).unwrap(); + assert_eq!(profile.libraries.len(), 6); + let natives: Vec<_> = profile + .libraries + .iter() + .filter(|lib| lib.name.contains("-natives-")) + .collect(); + assert_eq!(natives.len(), 3); + assert!( + natives + .iter() + .all(|lib| lib.name.ends_with(&format!("-{expected}:3.4.2"))) + ); + } + let mut profile = bundled_profile(); + profile + .libraries + .retain(|lib| !lib.name.contains("lwjgl-spng-natives-windows-x86")); + let platform = JavaPlatform::from_java_properties("Windows 10", "x86", "32", "10.0").unwrap(); + assert!( + select_lwjgl_natives(&mut profile, &platform) + .unwrap_err() + .to_string() + .contains("lwjgl-spng") + ); +} + +fn write_mod(temp: &Path, mut profile: LaunchProfile) -> PathBuf { + use sha1::Digest; + let payload = make_zip( + temp, "patches.zip", - &[("META-INF/MANIFEST.MF", manifest)], + &[("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n")], ); - let args = parse_add_opens(&zip_path).expect("parsed"); + let payload = std::fs::read(payload).unwrap(); + profile.libraries.push(serde_json::from_value(json!({"name":"com.github.GTNewHorizons:lwjgl3ify:3.0.35:forgePatches", + "downloads":{"artifact":{"url":"https://example.invalid/forgePatches.jar", "sha1":format!("{:x}", sha1::Sha1::digest(&payload)), "size":payload.len()}} + })).unwrap()); + let mods = temp.join("mods"); + std::fs::create_dir_all(&mods).unwrap(); + make_zip( + &mods, + "lwjgl3ify-3.0.35.jar", + &[ + ( + "me/eigenraven/lwjgl3ify/relauncher/version.json", + &serde_json::to_vec(&profile).unwrap(), + ), + ( + "me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip", + &payload, + ), + ], + ) +} + +#[tokio::test] +async fn shim_forwards_the_metadata_client_entrypoint_and_payload_is_a_jar() { + let temp = tempfile::tempdir().unwrap(); + write_mod(temp.path(), bundled_profile()); + let platform = + JavaPlatform::from_java_properties("Mac OS X", "amd64", "64", "10.15.7").unwrap(); + let patches = load(temp.path(), &platform).unwrap().unwrap(); assert_eq!( - args, - vec![ - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "--add-opens", - "java.base/java.util=ALL-UNNAMED", - ] + patches.profile.java_version.as_ref().unwrap().major_version, + 25 ); -} - -#[test] -fn parse_add_opens_handles_continuation_lines() { - // jar manifests wrap long lines: the line ends with a trailing space, - // then the next physical line starts with a leading space marker. - // when joined per the MANIFEST.MF spec, the trailing space remains - // and the leading space marker is consumed, so the two values stay - // separated by exactly one space when split_whitespace runs. - let tmp = tempfile::tempdir().unwrap(); - let manifest = - b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n"; - let zip_path = make_zip( - tmp.path(), - "patches-continuation.zip", - &[("META-INF/MANIFEST.MF", manifest)], + assert!( + !patches + .profile + .libraries + .iter() + .any(|lib| lib.name.ends_with(":forgePatches")) ); - let args = parse_add_opens(&zip_path).expect("parsed"); + let mut classpath = Vec::new(); + let (main, extra, _) = apply( + patches, + temp.path(), + &temp.path().join("libraries"), + &mut classpath, + ) + .await + .unwrap(); + assert_eq!(main, "RmclShim"); assert_eq!( - args, - vec![ - "--add-opens", - "java.base/java.lang=ALL-UNNAMED", - "--add-opens", - "java.base/sun.security.util=ALL-UNNAMED", - ] + extra, + ["com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread"] + ); + assert_eq!(classpath[1], temp.path().join(".forge-patches.jar")); + let mut shim = zip::ZipArchive::new(std::fs::File::open(&classpath[0]).unwrap()).unwrap(); + assert!(shim.by_name("RmclShim.class").is_ok()); +} + +#[test] +fn broken_or_missing_bundled_metadata_is_an_error() { + let temp = tempfile::tempdir().unwrap(); + let platform = JavaPlatform::from_java_properties("Linux", "amd64", "64", "6.0").unwrap(); + assert!(load(temp.path(), &platform).unwrap().is_none()); + let mut incomplete = bundled_profile(); + incomplete.java_version = None; + write_mod(temp.path(), incomplete); + assert!( + load(temp.path(), &platform) + .unwrap_err() + .to_string() + .contains("javaVersion") + ); + let jar = write_mod(temp.path(), bundled_profile()); + std::fs::write(&jar, b"broken jar").unwrap(); + assert!(load(temp.path(), &platform).is_err()); + make_zip( + jar.parent().unwrap(), + "lwjgl3ify-3.0.35.jar", + &[("other.txt", b"no metadata")], + ); + assert!( + load(temp.path(), &platform) + .unwrap_err() + .to_string() + .contains("bundled client profile") ); } - -#[test] -fn parse_add_opens_returns_none_when_manifest_missing() { - let tmp = tempfile::tempdir().unwrap(); - let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]); - assert!(parse_add_opens(&zip_path).is_none()); -} - -#[test] -fn parse_add_opens_returns_none_for_missing_file() { - let tmp = tempfile::tempdir().unwrap(); - assert!(parse_add_opens(&tmp.path().join("missing.zip")).is_none()); -} - -#[test] -fn add_lwjgl3_inserts_only_jars_that_exist() { - let tmp = tempfile::tempdir().unwrap(); - let lib_dir = tmp.path(); - - // pre-create only the lwjgl core jar; everything else absent so the - // function should skip them silently. proves we don't insert paths - // for jars that aren't there. - let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar"); - std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap(); - std::fs::write(&core_jar, b"jar").unwrap(); - - let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")]; - add_lwjgl3(lib_dir, &mut classpath); - - assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar")); - assert_eq!(classpath[1], core_jar); - assert_eq!(classpath.len(), 2); -} diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs index 1017018..9f64390 100644 --- a/src/instance/tests/launch/pipeline.rs +++ b/src/instance/tests/launch/pipeline.rs @@ -1,6 +1,32 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +#[tokio::test] +async fn dropping_the_kill_sender_does_not_request_cancellation_or_repoll_a_completed_receiver() { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let mut receiver = Some(receiver); + drop(sender); + for _ in 0..2 { + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(5), + super::wait_for_kill(&mut receiver) + ) + .await + .is_err() + ); + } + let (sender, request) = tokio::sync::oneshot::channel(); + receiver = Some(request); + sender.send(()).unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + super::wait_for_kill(&mut receiver), + ) + .await + .unwrap(); +} + use super::*; #[rstest::rstest] @@ -173,9 +199,7 @@ fn preferred_account_falls_back_to_the_active_account() { ); } -#[cfg(unix)] -#[tokio::test] -async fn launch_commands_receive_instance_environment() { +fn hook_fixture() -> (tempfile::TempDir, InstanceConfig, LaunchInvocation) { use chrono::Utc; let temp = tempfile::tempdir().unwrap(); @@ -218,9 +242,20 @@ async fn launch_commands_receive_instance_environment() { environment: config.environment.clone(), working_dir: minecraft.clone(), }; + (temp, config, invocation) +} + +#[tokio::test] +async fn launch_commands_receive_instance_environment() { + let (temp, config, invocation) = hook_fixture(); let command = LaunchCommand { enabled: true, - command: "printf '%s|%s' \"$CUSTOM_VALUE\" \"$INST_NAME\" > hook-result".to_owned(), + command: if cfg!(windows) { + "echo %CUSTOM_VALUE%^|%INST_NAME%>hook-result" + } else { + "printf '%s|%s' \"$CUSTOM_VALUE\" \"$INST_NAME\" > hook-result" + } + .to_owned(), }; run_launch_command("Pre-launch", &command, &config, &invocation, temp.path()) @@ -228,16 +263,91 @@ async fn launch_commands_receive_instance_environment() { .unwrap(); assert_eq!( - std::fs::read_to_string(minecraft.join("hook-result")).unwrap(), + std::fs::read_to_string(invocation.working_dir.join("hook-result")) + .unwrap() + .trim_end(), "available|Hook Test" ); } -// exercises the early-return branch of migrate_legacy_meta_if_needed. -// a profile with either arguments or minecraftArguments is not legacy -// and must produce Ok(None) without touching the network. covers both -// shapes in one parameterised test so a regression that drops one of -// the two predicate conditions is caught. +#[cfg(windows)] +#[tokio::test] +async fn windows_hooks_preserve_quoted_paths_arguments_redirection_and_expansion() { + let (temp, config, invocation) = hook_fixture(); + let script = invocation.working_dir.join("hook script with spaces.cmd"); + std::fs::write(&script, "@echo off\r\necho %1\r\necho %CUSTOM_VALUE%\r\necho %INST_NAME%\r\necho stderr value 1>&2\r\n").unwrap(); + let command = LaunchCommand { + enabled: true, + command: format!( + "\"{}\" \"argument with spaces & |\" > \"result file.txt\" 2> \"error file.txt\"", + script.display() + ), + }; + run_launch_command("Pre-launch", &command, &config, &invocation, temp.path()) + .await + .unwrap(); + let stdout = std::fs::read_to_string(invocation.working_dir.join("result file.txt")).unwrap(); + assert_eq!( + stdout.lines().collect::>(), + ["\"argument with spaces & |\"", "available", "Hook Test"] + ); + assert_eq!( + std::fs::read_to_string(invocation.working_dir.join("error file.txt")) + .unwrap() + .trim(), + "stderr value" + ); +} + +#[tokio::test] +async fn cancelling_a_hook_terminates_its_descendants() { + let (temp, config, invocation) = hook_fixture(); + let command = LaunchCommand { enabled: true, command: if cfg!(windows) { + "powershell.exe -NoProfile -NonInteractive -Command \"[IO.File]::WriteAllText('child-ready','ready'); Start-Sleep -Milliseconds 1200; [IO.File]::WriteAllText('escaped','escaped')\"" + } else { + "(printf ready > child-ready; sleep 1; printf escaped > escaped) & wait" + }.to_owned() }; + { + let future = run_launch_command("Pre-launch", &command, &config, &invocation, temp.path()); + tokio::pin!(future); + let ready = async { + while !invocation.working_dir.join("child-ready").is_file() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }; + tokio::select! { + result = &mut future => panic!("hook ended before cancellation: {result:?}"), + result = tokio::time::timeout(std::time::Duration::from_secs(15), ready) => result.unwrap(), + } + // Dropping the future must close the job/kill the group, not only its shell. + } + tokio::time::sleep(std::time::Duration::from_millis(1600)).await; + assert!( + !invocation.working_dir.join("escaped").exists(), + "hook descendant survived cancellation" + ); +} + +#[tokio::test] +async fn completed_hooks_can_leave_an_intentional_background_command() { + let (temp, config, invocation) = hook_fixture(); + let command = LaunchCommand { enabled: true, command: if cfg!(windows) { + "start \"\" /B powershell.exe -NoProfile -NonInteractive -Command \"Start-Sleep -Milliseconds 600; [IO.File]::WriteAllText('background-finished','done')\" >nul 2>nul" + } else { + "(sleep 0.6; printf done > background-finished) >/dev/null 2>&1 &" + }.to_owned() }; + run_launch_command("Pre-launch", &command, &config, &invocation, temp.path()) + .await + .unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(15), async { + while !invocation.working_dir.join("background-finished").is_file() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("completed hook's background command was terminated"); +} + #[rstest::rstest] #[case::modern_arguments(true, false)] #[case::legacy_minecraft_arguments(false, true)] @@ -268,9 +378,6 @@ async fn migrate_legacy_meta_skips_when_arguments_present( ); } -// each loader maps to a distinct directory-naming branch. one rstest -// exercises every variant so a regression that misorders the match -// arms in installer_version_dir_name is caught. #[rstest::rstest] #[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))] #[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))] @@ -289,11 +396,6 @@ fn installer_version_dir_name_per_loader( ); } -// exercises the modern-profile early-return in -// migrate_legacy_loader_profile_if_needed. any of inheritsFrom, -// arguments, minecraftArguments present (or game_arguments absent) -// means "not legacy" and the function must return Ok(None) without -// touching the installer JSON path. #[tokio::test] async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { use LaunchProfile; @@ -350,8 +452,6 @@ async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() { async fn migrate_legacy_loader_profile_skips_fabric() { // a fresh upstream Fabric profile happens to match the "legacy" // shape (no inheritsFrom, no arguments, no minecraftArguments). - // make sure the migration helper recognises this is Fabric and - // returns Ok(None) instead of erroring with "reinstall Fabric". use LaunchProfile; use chrono::Utc; use tempfile::TempDir; diff --git a/src/instance/tests/loader/forge.rs b/src/instance/tests/loader/forge.rs index 14a1ed8..a8aac4c 100644 --- a/src/instance/tests/loader/forge.rs +++ b/src/instance/tests/loader/forge.rs @@ -3,9 +3,6 @@ use super::*; -// builds an in-memory zip in a tempdir with the given json as -// install_profile.json. lets the legacy-install-profile detector be -// tested without an actual forge installer. fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf { use std::io::Write; let path = tmp.join("installer.jar"); diff --git a/src/instance/tests/loader/installers.rs b/src/instance/tests/loader/installers.rs index 9ba0fde..cc042bd 100644 --- a/src/instance/tests/loader/installers.rs +++ b/src/instance/tests/loader/installers.rs @@ -3,9 +3,6 @@ use super::*; -// the factory maps every ModLoader variant to its concrete installer. -// covering all five arms catches a misordered match or a copy-paste typo -// that would route, say, NeoForge to the Forge installer. #[rstest::rstest] #[case::vanilla(ModLoader::Vanilla)] #[case::forge(ModLoader::Forge)] @@ -24,8 +21,7 @@ fn save_installer_profile_copies_raw_bytes_verbatim() { let instance_dir = tmp.path().join("instance"); let meta_dir = tmp.path().join("meta"); - // a synthetic installer version JSON with the modern arguments - // object - exactly the shape we used to strip. + // Preserve modern JVM arguments that older rmcl caches stripped. let installer_json = br#"{ "id": "1.20.1-forge-47.2.0", "inheritsFrom": "1.20.1", @@ -111,10 +107,6 @@ fn profile_filenames_match_launch_cache_names( ); } -// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge -// install_profile.json must deserialise as a LaunchProfile so the -// launch flow's render_args + resolve pipeline can consume it. no -// filesystem round-trip; serde_json directly on the literal bytes. #[test] fn legacy_forge_version_info_deserialises_as_launch_profile() { let bytes = br#"{ @@ -158,10 +150,6 @@ fn legacy_forge_version_info_deserialises_as_launch_profile() { assert!(profile.libraries[0].downloads.is_none()); } -// shape-pinning test: a synthetic upstream fabric profile (no -// inheritsFrom, no arguments, libraries with name+url) must -// deserialise as a LaunchProfile so the install path can write it -// through to disk and the launch flow can read it back. #[test] fn raw_fabric_profile_bytes_parse_as_launch_profile() { let bytes = br#"{ @@ -190,3 +178,179 @@ fn raw_fabric_profile_bytes_parse_as_launch_profile() { Some("https://maven.fabricmc.net/") ); } + +fn recording_java(temp: &Path) -> String { + let path = temp.join(if cfg!(windows) { + "installer java.cmd" + } else { + "installer java.sh" + }); + #[cfg(windows)] + std::fs::write(&path, "@echo off\r\n(echo %~1\r\necho %~2\r\necho %~3\r\necho %~4\r\n)>installer-args.txt\r\necho %CD%>installer-cwd.txt\r\n(echo %INSTALLER_CONTEXT%\r\necho %INSTALLER_GLOBAL%\r\n)>installer-env.txt\r\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::write( + &path, + "#!/bin/sh\nprintf '%s\\n' \"$@\" > installer-args.txt\npwd > installer-cwd.txt\nprintf '%s\\n' \"$INSTALLER_CONTEXT\" \"$INSTALLER_GLOBAL\" > installer-env.txt\n", + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + path.to_string_lossy().into_owned() +} + +#[rstest::rstest] +#[case::forge(false)] +#[case::neoforge(true)] +#[tokio::test] +async fn installers_use_merged_environment_and_minecraft_cwd(#[case] neoforge: bool) { + let temp = tempfile::tempdir().unwrap(); + let instance = temp.path().join("instance with spaces"); + let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(&minecraft).unwrap(); + let installer = minecraft.join("neoforge installer.jar"); + let java = recording_java(temp.path()); + let environment = crate::instance::java::merge_environment( + &BTreeMap::from([ + ("PATH".to_owned(), "missing-global-java".to_owned()), + ("INSTALLER_CONTEXT".to_owned(), "global".to_owned()), + ("INSTALLER_GLOBAL".to_owned(), "global-only".to_owned()), + ]), + &BTreeMap::from([ + ( + "PATH".to_owned(), + temp.path().to_string_lossy().into_owned(), + ), + ("INSTALLER_CONTEXT".to_owned(), "selected".to_owned()), + ]), + ); + let java_name = Path::new(&java).file_name().unwrap().to_str().unwrap(); + if neoforge { + super::neoforge::run_neoforge_installer( + &installer, + &instance, + Some(java_name), + &environment, + ) + .await + .unwrap(); + } else { + super::forge::run_forge_installer(&installer, &instance, Some(java_name), &environment) + .await + .unwrap(); + } + let args = std::fs::read_to_string(minecraft.join("installer-args.txt")).unwrap(); + let args: Vec<_> = args.lines().collect(); + assert_eq!( + &args[..3], + ["-jar", &installer.to_string_lossy(), "--installClient"] + ); + if neoforge { + assert_eq!(args[3], minecraft.to_string_lossy()); + } else { + assert!(args[3..].iter().all(|arg| arg.trim().is_empty())); + } + let cwd = std::fs::read_to_string(minecraft.join("installer-cwd.txt")).unwrap(); + assert_eq!( + Path::new(cwd.trim()).canonicalize().unwrap(), + minecraft.canonicalize().unwrap() + ); + assert!(!args.iter().any(|arg| arg.starts_with("-Duser.home="))); + assert_eq!( + std::fs::read_to_string(minecraft.join("installer-env.txt")) + .unwrap() + .lines() + .map(str::trim) + .collect::>(), + ["selected", "global-only"] + ); +} + +#[tokio::test] +async fn cancelled_installers_do_not_leave_java_or_its_descendants_running() { + let fixture = tempfile::tempdir().unwrap(); + let classes = fixture.path().join("classes"); + std::fs::create_dir_all(&classes).unwrap(); + let source = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/InstallerLifetimeFixture.java"); + let compiler = std::process::Command::new("javac") + .args(["-source", "8", "-target", "8"]) + .arg("-d") + .arg(&classes) + .arg(source) + .output() + .unwrap(); + assert!( + compiler.status.success(), + "{}", + String::from_utf8_lossy(&compiler.stderr) + ); + let jar = fixture.path().join("installer fixture.jar"); + let packer = std::process::Command::new("jar") + .arg("cfe") + .arg(&jar) + .arg("InstallerLifetimeFixture") + .arg("-C") + .arg(&classes) + .arg(".") + .output() + .unwrap(); + assert!( + packer.status.success(), + "{}", + String::from_utf8_lossy(&packer.stderr) + ); + let java = crate::instance::java::resolve_java_path_in( + None, + &std::env::current_dir().unwrap(), + &Default::default(), + ); + for neoforge in [false, true] { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join(crate::storage::MINECRAFT_DIR_NAME); + std::fs::create_dir_all(&minecraft).unwrap(); + { + let future = async { + if neoforge { + super::neoforge::run_neoforge_installer( + &jar, + temp.path(), + Some(&java), + &Default::default(), + ) + .await + } else { + super::forge::run_forge_installer( + &jar, + temp.path(), + Some(&java), + &Default::default(), + ) + .await + } + }; + tokio::pin!(future); + let ready = async { + while !minecraft.join("installer-ready").is_file() + || !minecraft.join("installer-child-ready").is_file() + { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }; + tokio::select! { + result = &mut future => panic!("installer exited before cancellation: {result:?}"), + result = tokio::time::timeout(std::time::Duration::from_secs(15), ready) => result.unwrap(), + } + } + tokio::time::sleep(std::time::Duration::from_millis(1600)).await; + assert!( + !minecraft.join("installer-survived").exists(), + "Java process survived installer cancellation" + ); + assert!( + !minecraft.join("installer-child-survived").exists(), + "Java descendant survived installer cancellation" + ); + } +} diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index 385fe80..2b6f040 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -311,3 +311,147 @@ fn instance_names_are_portable_components() { assert!(validate_name(name).is_ok(), "{name}"); } } + +#[cfg(unix)] +#[test] +fn runtime_repair_uses_selected_java_cwd_environment_and_platform() { + use sha1::{Digest, Sha1}; + use std::collections::BTreeMap; + use std::io::{Cursor, Write}; + use std::os::unix::fs::PermissionsExt; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + const ROOT: &str = "RMCL_RUNTIME_CONTEXT_TEST"; + let Some(root) = std::env::var_os(ROOT) else { + let temp = + tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "instance::manager::tests::runtime_repair_uses_selected_java_cwd_environment_and_platform", + "--nocapture", + ]) + .env(ROOT, temp.path()) + .env("HOME", temp.path()) + .env("XDG_CONFIG_HOME", temp.path().join("config")) + .current_dir(temp.path()) + .status() + .unwrap(); + assert!(status.success()); + return; + }; + let root = PathBuf::from(root); + let config_dir = crate::config::get_config_path(); + assert!(config_dir.starts_with(&root)); + std::fs::create_dir_all(&config_dir).unwrap(); + let mut settings = crate::config::Config::default(); + settings.paths.java_path = Some("context-java".to_owned()); + settings.defaults.environment = BTreeMap::from([ + ("PATH".to_owned(), "global-bin".to_owned()), + ("JAVA_HOME".to_owned(), "missing-home".to_owned()), + ("RUNTIME_GLOBAL".to_owned(), "global-only".to_owned()), + ("RUNTIME_SHARED".to_owned(), "global".to_owned()), + ]); + std::fs::write( + config_dir.join("config.toml"), + toml::to_string(&settings).unwrap(), + ) + .unwrap(); + + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + let server = MockServer::start().await; + let client_jar = b"client"; + let assets = br#"{"objects":{}}"#; + for (endpoint, body) in [("/client.jar", client_jar.as_slice()), ("/assets.json", assets.as_slice())] { + Mock::given(method("GET")) + .and(path(endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body.to_vec())) + .expect(3) + .mount(&server).await; + } + let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); + archive.start_file("native.bin", zip::write::SimpleFileOptions::default()).unwrap(); + archive.write_all(b"selected-native").unwrap(); + let native = archive.finish().unwrap().into_inner(); + let hash = |bytes: &[u8]| format!("{:x}", Sha1::digest(bytes)); + let manager = InstanceManager::new("instances", "meta"); + let metadata = crate::storage::MetadataPaths::new(&manager.meta_dir); + + for (name, os, java_os, java_arch, arch, bits) in [ + ("global", "linux", "Linux", "aarch64", "arm64", 64), + ("override", "windows", "Windows 11", "i386", "x86", 32), + ("relative", "osx", "Mac OS X", "amd64", "x86_64", 64), + ] { + let mut config = dummy_config(name); + config.game_version = name.to_owned(); + let minecraft = root.join("instances").join(name).join(crate::storage::MINECRAFT_DIR_NAME); + let bin = if name == "global" { "global-bin" } else { "instance-bin" }; + let java = minecraft.join(bin).join("context-java"); + std::fs::create_dir_all(java.parent().unwrap()).unwrap(); + std::fs::write(&java, "#!/bin/sh\nprintf '%s\\n' \"$0\" > probe-java.txt\npwd > probe-cwd.txt\nprintf '%s\\n' \"$RUNTIME_GLOBAL\" \"$RUNTIME_SHARED\" > probe-env.txt\nprintf 'java.version = 25\\nos.name = %s\\nos.arch = %s\\nsun.arch.data.model = %s\\nos.version = fixture-os\\n' \"$RUNTIME_OS\" \"$RUNTIME_ARCH\" \"$RUNTIME_BITS\" >&2\n").unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + config.environment = BTreeMap::from([ + ("RUNTIME_OS".to_owned(), java_os.to_owned()), + ("RUNTIME_ARCH".to_owned(), java_arch.to_owned()), + ("RUNTIME_BITS".to_owned(), bits.to_string()), + ("RUNTIME_SHARED".to_owned(), "instance".to_owned()), + ]); + if name != "global" { + config.environment.insert("PATH".to_owned(), bin.to_owned()); + } + if name == "relative" { + config.java_path = Some("./instance-bin/context-java".to_owned()); + } + + let mut libraries = Vec::new(); + for (library_os, library_arch) in [("linux", "arm64"), ("windows", "x86"), ("osx", "x86_64")] { + let mut classifiers = serde_json::Map::new(); + for native_bits in [32, 64] { + let endpoint = format!("/{name}-{library_os}-{native_bits}.jar"); + Mock::given(method("GET")) + .and(path(&endpoint)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(native.clone())) + .expect(u64::from(library_os == os && native_bits == bits)) + .mount(&server).await; + classifiers.insert(format!("natives-{native_bits}"), serde_json::json!({ + "url": format!("{}{endpoint}", server.uri()), + "path": format!("{name}/{library_os}-{native_bits}.jar"), + "sha1": hash(&native), "size": native.len() + })); + } + libraries.push(serde_json::json!({ + "name": format!("example:{library_os}:1"), + "rules": [{ "action": "allow", "os": { "name": library_os, "arch": library_arch, "version": "^fixture-os$" } }], + "natives": { (library_os): "natives-${arch}" }, + "downloads": { "classifiers": classifiers } + })); + } + let version_dir = metadata.versions().join(name); + std::fs::create_dir_all(&version_dir).unwrap(); + std::fs::write(version_dir.join("meta.json"), serde_json::to_vec(&serde_json::json!({ + "id": name, "mainClass": "fixture.Main", "arguments": { "game": [], "jvm": [] }, + "assetIndex": { "id": name, "url": format!("{}/assets.json", server.uri()), "sha1": hash(assets) }, + "downloads": { "client": { "url": format!("{}/client.jar", server.uri()), "sha1": hash(client_jar), "size": client_jar.len() } }, + "libraries": libraries + })).unwrap()).unwrap(); + + manager.repair_runtime_cache(&config).await.unwrap(); + let selected_java = std::fs::read_to_string(minecraft.join("probe-java.txt")).unwrap(); + assert_eq!(Path::new(selected_java.trim()), java); + let cwd = std::fs::read_to_string(minecraft.join("probe-cwd.txt")).unwrap(); + assert_eq!(Path::new(cwd.trim()).canonicalize().unwrap(), minecraft.canonicalize().unwrap()); + assert_eq!(std::fs::read_to_string(minecraft.join("probe-env.txt")).unwrap(), "global-only\ninstance\n"); + assert_eq!(std::fs::read(version_dir.join("natives").join(format!("{os}-{arch}-{bits}")).join("native.bin")).unwrap(), b"selected-native"); + for (library_os, _) in [("linux", "arm64"), ("windows", "x86"), ("osx", "x86_64")] { + for native_bits in [32, 64] { + assert_eq!(metadata.libraries().join(name).join(format!("{library_os}-{native_bits}.jar")).exists(), library_os == os && native_bits == bits); + } + } + } + }); +} diff --git a/src/launch_profile/model.rs b/src/launch_profile/model.rs index f1920ec..67b87a7 100644 --- a/src/launch_profile/model.rs +++ b/src/launch_profile/model.rs @@ -29,8 +29,7 @@ pub struct LaunchProfile { // present only in rmcl <= 0.3.0's stripped loader-profile shape. // we deserialize it so the launch-time legacy-detection predicate // can confirm "this really is our old format, not an upstream - // profile that happens to omit arguments". skipped on serialize so - // we never propagate this field outward. + // profile that happens to omit arguments". The resolver discards this field. #[serde(default, skip_serializing_if = "Option::is_none")] pub game_arguments: Option>, } @@ -66,16 +65,29 @@ pub struct Library { pub downloads: Option, pub rules: Option>, pub url: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub natives: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub extract: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct LibraryDownloads { pub artifact: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub classifiers: Option>, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +pub struct LibraryExtract { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exclude: Option>, } #[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct Artifact { pub url: String, + #[serde(default)] pub path: String, pub sha1: String, pub size: u64, diff --git a/src/launch_profile/resolve.rs b/src/launch_profile/resolve.rs index 1ed40c8..ade2492 100644 --- a/src/launch_profile/resolve.rs +++ b/src/launch_profile/resolve.rs @@ -1,15 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// merge semantics (per the mojang launcher and the major third-party -// launchers that interoperate with it): -// - scalar fields: child wins if Some, else parent. -// - libraries and arguments: parent ++ child (parent first). child -// entries are appended after parent's. -// - merge_into preserves parent's inherits_from so resolve() can keep -// walking; resolve() clears the final result's inherits_from after -// the loop exits. - use std::path::Path; use super::model::{Arguments, LaunchProfile}; @@ -111,6 +102,14 @@ pub async fn resolve( let mut depth = 0; while let Some(parent_id) = current.inherits_from.clone() { + if !crate::storage::safe_relative_path(Path::new(&parent_id)) + || Path::new(&parent_id).components().count() != 1 + { + return Err(ResolveError::ParseError( + parent_id, + "Invalid inherited version ID".to_owned(), + )); + } depth += 1; if depth > MAX_INHERITANCE_DEPTH { return Err(ResolveError::DepthExceeded(MAX_INHERITANCE_DEPTH)); diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index 36dddb2..adfed2d 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -16,7 +16,7 @@ pub struct OsCondition { pub arch: Option, // mojang occasionally constrains natives selection on os.version with a // regex. rare in practice - when present, it's a substring/anchor match - // against the host OS version reported by `system::mojang_os_version`. + // against os.version reported by the selected Java runtime. pub version: Option, } diff --git a/src/launch_profile/system.rs b/src/launch_profile/system.rs index e6f834d..5d185f6 100644 --- a/src/launch_profile/system.rs +++ b/src/launch_profile/system.rs @@ -1,9 +1,73 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// Mojang names some things differently from rust's std::env::consts (e.g. macOS -// is "osx" in mojang profile rules), so this module is the single source -// of truth for translating. +use std::path::{Path, PathBuf}; + +// Native libraries and rules describe the Java process, which can have a +// different architecture from the launcher (for example, Intel Java on macOS ARM). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JavaPlatform { + pub os_name: &'static str, + pub arch: String, + pub bitness: u32, + pub os_version: String, +} + +impl JavaPlatform { + pub fn from_java_properties( + os_name: &str, + arch: &str, + bitness: &str, + os_version: &str, + ) -> std::io::Result { + let invalid = |message| std::io::Error::new(std::io::ErrorKind::InvalidData, message); + let os_name = match os_name { + name if name.starts_with("Windows") => "windows", + "Mac OS X" | "macOS" | "Darwin" => "osx", + "Linux" => "linux", + other => return Err(invalid(format!("Unsupported Java os.name: {other}"))), + }; + let arch = match arch { + "amd64" | "x86_64" | "x64" => "x86_64", + "x86" | "i386" | "i486" | "i586" | "i686" => "x86", + "aarch64" | "arm64" => "arm64", + other => other, + }; + if arch.is_empty() + || !arch + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + { + return Err(invalid(format!("Invalid Java os.arch: {arch}"))); + } + let bitness = match bitness { + "32" => 32, + "64" => 64, + other => { + return Err(invalid(format!( + "Invalid Java sun.arch.data.model: {other}" + ))); + } + }; + if os_version.is_empty() { + return Err(invalid("Missing Java os.version".to_owned())); + } + Ok(Self { + os_name, + arch: arch.to_owned(), + bitness, + os_version: os_version.to_owned(), + }) + } + + pub fn natives_directory(&self, meta_dir: &Path, version: &str) -> PathBuf { + crate::storage::MetadataPaths::new(meta_dir) + .versions() + .join(version) + .join("natives") + .join(format!("{}-{}-{}", self.os_name, self.arch, self.bitness)) + } +} pub fn mojang_os_name() -> &'static str { match std::env::consts::OS { @@ -11,29 +75,3 @@ pub fn mojang_os_name() -> &'static str { other => other, } } - -pub fn mojang_arch_name() -> &'static str { - match std::env::consts::ARCH { - "x86" => "x86", - "x86_64" => "x86_64", - "aarch64" => "arm64", - other => other, - } -} - -// the host OS version string. mojang rules occasionally constrain natives -// selection on os.version with a regex (e.g. macOS 10.x-only natives). -// rust's stdlib doesn't expose this, so we read it where it's cheap and -// reliable: linux via /proc/sys/kernel/osrelease, other platforms return -// empty. when the host string is empty, version-gated rules don't match -// (conservative default in the rule evaluator) - which is fine because -// real-world profiles using os.version are vanishingly rare. -pub fn mojang_os_version() -> String { - #[cfg(target_os = "linux")] - { - if let Ok(s) = std::fs::read_to_string("/proc/sys/kernel/osrelease") { - return s.trim().to_string(); - } - } - String::new() -} diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 34ad1d6..1caefdf 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -51,7 +51,6 @@ pub fn substitute(input: &str, ctx: &TemplateContext) -> String { rest = &after_open[close_rel + 1..]; } None => { - // unclosed `${...` - emit the rest literally and stop. out.push_str("${"); out.push_str(after_open); return out; @@ -72,10 +71,21 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option { "classpath" => ctx.classpath.to_string(), "game_directory" => ctx.game_directory.display().to_string(), "assets_root" => ctx.assets_root.display().to_string(), + "game_assets" => ctx + .assets_root + .join("virtual") + .join(ctx.assets_index_name) + .display() + .to_string(), "assets_index_name" => ctx.assets_index_name.to_string(), "auth_player_name" => ctx.auth_player_name.to_string(), "auth_uuid" => ctx.auth_uuid.to_string(), "auth_access_token" => ctx.auth_access_token.to_string(), + "auth_session" => format!( + "token:{}:{}", + ctx.auth_access_token, + ctx.auth_uuid.replace('-', "") + ), "auth_xuid" => ctx.auth_xuid.to_string(), "user_type" => ctx.user_type.to_string(), "user_properties" => ctx.user_properties.to_string(), diff --git a/src/launch_profile/tests/render.rs b/src/launch_profile/tests/render.rs index 37fc962..58e1f64 100644 --- a/src/launch_profile/tests/render.rs +++ b/src/launch_profile/tests/render.rs @@ -6,10 +6,6 @@ use crate::launch_profile::model::Arguments; use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction}; use std::path::PathBuf; -// owns the path buffers + FeatureSet so each test just calls -// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs -// and a RuleContext inline. all tests use linux/x86_64; if a test needs -// a different OS it sets it explicitly. struct Fixture { lib: PathBuf, nat: PathBuf, @@ -181,10 +177,6 @@ fn missing_main_class_returns_error() { #[tokio::test] async fn end_to_end_resolve_then_render_modern_forge_shape() { - // exercises the full pipeline: load a synthetic vanilla profile - // from disk, load a synthetic loader profile with inheritsFrom, - // resolve the chain, then render args. catches integration bugs - // that unit tests of each layer would miss. use crate::launch_profile::resolve; use tempfile::TempDir; diff --git a/src/launch_profile/tests/resolve.rs b/src/launch_profile/tests/resolve.rs index 2eaadaf..771ebb8 100644 --- a/src/launch_profile/tests/resolve.rs +++ b/src/launch_profile/tests/resolve.rs @@ -277,6 +277,29 @@ async fn resolve_returns_unchanged_when_no_inherits_from() { assert!(resolved.inherits_from.is_none()); } +#[tokio::test] +async fn inheritance_rejects_paths_outside_the_versions_directory() { + let temp = tempfile::tempdir().unwrap(); + let outside = temp.path().join("cache/minecraft/outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write( + outside.join("meta.json"), + serde_json::to_vec(&empty_profile("outside")).unwrap(), + ) + .unwrap(); + for id in [ + "../outside".to_owned(), + outside.to_string_lossy().into_owned(), + ] { + let mut child = empty_profile("child"); + child.inherits_from = Some(id); + assert!(matches!( + resolve(child, temp.path()).await, + Err(ResolveError::ParseError(_, _)) + )); + } +} + #[tokio::test] async fn resolve_single_level_inheritance_merges_parent() { let tmp = TempDir::new().unwrap(); diff --git a/src/launch_profile/tests/templates.rs b/src/launch_profile/tests/templates.rs index db84c30..54811f5 100644 --- a/src/launch_profile/tests/templates.rs +++ b/src/launch_profile/tests/templates.rs @@ -4,10 +4,6 @@ use super::*; use std::path::PathBuf; -// owns the path buffers so tests don't have to declare them inline; the -// ctx() method borrows from self to build a TemplateContext with the -// standard set of values. windows() returns a fixture with backslash -// paths so the OS-independence test stays self-contained. struct Fixture { lib: PathBuf, nat: PathBuf, @@ -129,3 +125,17 @@ fn custom_resolution_is_substituted_when_present() { "1920x1080" ); } + +#[test] +fn legacy_164_arguments_resolve_session_and_virtual_assets() { + let fixture = Fixture::unix(); + let mut context = fixture.ctx(); + context.assets_index_name = "legacy"; + let args = substitute( + "--username ${auth_player_name} --session ${auth_session} --version ${version_name} --gameDir ${game_directory} --assetsDir ${game_assets}", + &context, + ); + assert!(!args.contains("${")); + assert!(args.contains("--session token:token:00000000000000000000000000000000")); + assert!(args.contains(&fixture.assets.join("virtual/legacy").display().to_string())); +} diff --git a/src/net/mojang.rs b/src/net/mojang.rs index 64a32a1..acce1cd 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -2,12 +2,8 @@ // SPDX-License-Identifier: GPL-3.0-only use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, path::{Path, PathBuf}, - sync::{ - Arc, - atomic::{AtomicU64, Ordering}, - }, }; use serde::{Deserialize, Serialize}; @@ -15,6 +11,9 @@ use tokio::task::JoinSet; use super::{HttpClient, NetError, download_file}; use crate::feedback::progress::{clear, set_action, set_progress, set_sub_action}; +use crate::launch_profile::{model, system::JavaPlatform}; + +pub use model::{Artifact, LibraryDownloads, LibraryExtract}; const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net"; @@ -85,32 +84,6 @@ pub struct Library { pub extract: Option, } -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct LibraryExtract { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub exclude: Option>, -} - -#[derive(Debug, Clone, Deserialize, Serialize)] -pub struct LibraryDownloads { - pub artifact: Option, - // classifier -> download info (same shape as artifact). populated on - // libraries that declare `natives`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub classifiers: Option>, -} - -#[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, -} - #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct JavaVersion { @@ -120,6 +93,8 @@ pub struct JavaVersion { #[derive(Debug, Clone, Deserialize, Serialize)] pub struct AssetIndexContent { pub objects: HashMap, + #[serde(default, rename = "virtual")] + pub virtual_assets: bool, } #[derive(Debug, Clone, Deserialize, Serialize)] @@ -269,33 +244,77 @@ pub async fn download_libraries( client: &HttpClient, meta: &VersionMeta, meta_dir: &Path, +) -> Result<(), NetError> { + let java = crate::instance::java::resolve_java_path(None); + let runtime = crate::instance::java::probe_java(Path::new(&java)).await?; + download_libraries_for_platform(client, meta, meta_dir, &runtime.platform).await +} + +pub async fn download_libraries_for_platform( + client: &HttpClient, + meta: &VersionMeta, + meta_dir: &Path, + platform: &JavaPlatform, +) -> Result<(), NetError> { + if !crate::storage::safe_relative_path(Path::new(&meta.id)) + || Path::new(&meta.id).components().count() != 1 + { + return Err(NetError::Parse(format!( + "Invalid Minecraft version ID: {}", + meta.id + ))); + } + let libraries: Vec<_> = meta + .libraries + .iter() + .map(|lib| model::Library { + name: lib.name.clone(), + downloads: Some(lib.downloads.clone()), + rules: lib.rules.clone(), + natives: lib.natives.clone(), + extract: lib.extract.clone(), + ..Default::default() + }) + .collect(); + download_profile_libraries( + client, + &libraries, + &crate::storage::MetadataPaths::new(meta_dir).libraries(), + &platform.natives_directory(meta_dir, &meta.id), + platform, + &crate::launch_profile::rules::FeatureSet::default(), + ) + .await +} + +pub(crate) async fn download_profile_libraries( + client: &HttpClient, + libraries: &[model::Library], + lib_dir: &Path, + natives_dir: &Path, + platform: &JavaPlatform, + features: &crate::launch_profile::rules::FeatureSet, ) -> Result<(), NetError> { set_action("Downloading libraries..."); tracing::debug!( - "Resolving {} libraries for Minecraft {}", - meta.libraries.len(), - meta.id + "Resolving {} libraries for Java {} {}", + libraries.len(), + platform.os_name, + platform.arch ); - let features = crate::launch_profile::rules::FeatureSet::default(); - let host_os_version = crate::launch_profile::system::mojang_os_version(); let rule_ctx = crate::launch_profile::rules::RuleContext { - os_name: crate::launch_profile::system::mojang_os_name(), - os_version: &host_os_version, - arch: crate::launch_profile::system::mojang_arch_name(), - features: &features, + os_name: platform.os_name, + os_version: &platform.os_version, + arch: &platform.arch, + features, }; - let natives_dir = crate::storage::MetadataPaths::new(meta_dir) - .versions() - .join(&meta.id) - .join("natives"); - let mut downloads: Vec<(String, PathBuf, String, String, u64)> = 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)> = Vec::new(); - for library in &meta.libraries { + for library in libraries { if let Some(rules) = &library.rules && !crate::launch_profile::rules::evaluate(rules, &rule_ctx) { @@ -303,20 +322,16 @@ pub async fn download_libraries( continue; } - if let Some(artifact) = &library.downloads.artifact { - let rel = library_relative_path(library, artifact.path.as_str()).ok_or_else(|| { - NetError::Parse(format!("Invalid library path for {}", library.name)) - })?; - let destination = crate::storage::MetadataPaths::new(meta_dir) - .libraries() - .join(&rel); + if let Some(artifact) = library.downloads.as_ref().and_then(|d| d.artifact.as_ref()) { + let rel = library_artifact_path(library)?.expect("artifact has a path"); + let destination = lib_dir.join(&rel); if verify_cached(&destination, &artifact.sha1, artifact.size) { - tracing::trace!("Library already cached: {}", rel); + tracing::trace!("Library already cached: {}", rel.display()); } else { downloads.push(( artifact.url.clone(), destination, - rel, + rel.to_string_lossy().into_owned(), artifact.sha1.clone(), artifact.size, )); @@ -324,18 +339,24 @@ pub async fn download_libraries( } // native classifier jar (pre-1.13 era libraries). the jar itself is - // cached alongside the other libraries; its contents get unpacked - // into versions//natives where java.library.path points. + // cached alongside the other libraries; extraction is isolated by Java architecture. 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)) + .and_then(|n| n.get(platform.os_name)) + .map(|classifier| classifier.replace("${arch}", &platform.bitness.to_string())) { + let info = library + .downloads + .as_ref() + .and_then(|downloads| downloads.classifiers.as_ref()) + .and_then(|classifiers| classifiers.get(&classifier)) + .ok_or_else(|| { + NetError::Parse(format!( + "Library {} declares missing native classifier {classifier}", + library.name + )) + })?; // the maven fallback must carry the classifier: it selects // --.jar, not the base jar. let rel = if !info.path.is_empty() { @@ -355,9 +376,7 @@ pub async fn download_libraries( library.name ))); } - let destination = crate::storage::MetadataPaths::new(meta_dir) - .libraries() - .join(&rel); + let destination = lib_dir.join(&rel); if !verify_cached(&destination, &info.sha1, info.size) { downloads.push(( info.url.clone(), @@ -386,23 +405,44 @@ pub async fn download_libraries( clear(); result?; - for (jar, exclude) in &natives_jars { - extract_natives(jar, &natives_dir, exclude)?; + if !natives_jars.is_empty() { + std::fs::create_dir_all(natives_dir)?; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(natives_dir.join(".extract.lock"))?; + lock.lock()?; + for (jar, exclude) in &natives_jars { + extract_natives(jar, natives_dir, exclude)?; + } } Ok(()) } -fn library_relative_path(library: &Library, recorded_path: &str) -> Option { - let path = if recorded_path.is_empty() { - crate::instance::loader::maven::maven_coord_to_path(&library.name)? - } else { - recorded_path.to_owned() +pub(crate) fn library_artifact_path(library: &model::Library) -> Result, NetError> { + let recorded_path = match &library.downloads { + Some(downloads) => match &downloads.artifact { + Some(artifact) => &artifact.path, + // A classifier-only library belongs in the extraction directory, not the classpath. + None => return Ok(None), + }, + None => "", }; - crate::storage::safe_relative_path(Path::new(&path)).then_some(path) + let path = if recorded_path.is_empty() { + crate::instance::loader::maven::maven_coord_to_path(&library.name) + } else { + Some(recorded_path.to_owned()) + } + .filter(|path| crate::storage::safe_relative_path(Path::new(path))) + .ok_or_else(|| NetError::Parse(format!("Invalid library path for {}", library.name)))?; + Ok(Some(PathBuf::from(path))) } fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), NetError> { + use std::io::Read; 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())))?; @@ -432,11 +472,22 @@ fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), Ne continue; } let out_path = dest.join(&rel); - if let Some(parent) = out_path.parent() { - std::fs::create_dir_all(parent)?; + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes)?; + // Reusing a loaded DLL must not truncate or replace it on another launch. + let cached = match std::fs::read(&out_path) { + Ok(cached) => Some(cached), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(NetError::Parse(format!( + "Could not read native {}: {error}", + out_path.display() + ))); + } + }; + if cached.as_deref() != Some(bytes.as_slice()) { + crate::storage::write_atomic(&out_path, &bytes)?; } - let mut out = std::fs::File::create(&out_path)?; - std::io::copy(&mut entry, &mut out)?; } Ok(()) } @@ -509,6 +560,7 @@ pub async fn download_assets_from( }; let mut downloads = Vec::new(); + let mut hashes = HashSet::new(); for object in asset_index.objects.values() { if object.hash.len() != 40 || !object.hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { clear(); @@ -526,7 +578,7 @@ pub async fn download_assets_from( .join(prefix) .join(&object.hash); - if verify_cached(&destination, &object.hash, object.size) { + if !hashes.insert(&object.hash) || verify_cached(&destination, &object.hash, object.size) { continue; } @@ -541,18 +593,32 @@ pub async fn download_assets_from( if downloads.is_empty() { tracing::info!("All assets already cached"); + } else if let Err(error) = run_parallel_downloads(client, downloads, true).await { clear(); - return Ok(()); + return Err(error); + } + if asset_index.virtual_assets { + let assets = crate::storage::MetadataPaths::new(meta_dir).assets(); + for (name, object) in &asset_index.objects { + if !crate::storage::safe_relative_path(Path::new(name)) { + clear(); + return Err(NetError::Parse(format!( + "Invalid virtual asset path: {name}" + ))); + } + let destination = assets.join("virtual").join(&meta.asset_index.id).join(name); + if !verify_cached(&destination, &object.hash, object.size) { + let source = assets + .join("objects") + .join(&object.hash[..2]) + .join(&object.hash); + let bytes = tokio::fs::read(source).await?; + crate::storage::write_atomic(&destination, &bytes)?; + } + } } - - tracing::debug!( - "Downloading {} missing asset(s) from index {}", - downloads.len(), - meta.asset_index.id - ); - let result = run_parallel_downloads(client, downloads, true).await; clear(); - result + Ok(()) } // Continue other downloads after one fails; report the first error afterward. @@ -567,7 +633,7 @@ async fn run_parallel_downloads( total_downloads, MAX_CONCURRENT_DOWNLOADS ); - let completed = Arc::new(AtomicU64::new(0)); + let mut completed = 0; let mut queue = downloads.into_iter(); let mut set = JoinSet::new(); @@ -585,9 +651,9 @@ async fn run_parallel_downloads( while let Some(join_result) = set.join_next().await { match join_result { Ok(Ok(label)) => { - let finished = completed.fetch_add(1, Ordering::SeqCst) + 1; + completed += 1; if report_count_progress { - set_progress(finished, total_downloads); + set_progress(completed, total_downloads); } set_sub_action(label); } diff --git a/tests/fixtures/InstallerLifetimeFixture.java b/tests/fixtures/InstallerLifetimeFixture.java new file mode 100644 index 0000000..0a90335 --- /dev/null +++ b/tests/fixtures/InstallerLifetimeFixture.java @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +import java.nio.file.Files; +import java.nio.file.Paths; + +public final class InstallerLifetimeFixture { + public static void main(String[] args) throws Exception { + boolean child = args.length != 0 && args[0].equals("child"); + if (!child) { + String java = Paths.get(System.getProperty("java.home"), "bin", + System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java").toString(); + new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"), + "InstallerLifetimeFixture", "child").inheritIO().start(); + } + String prefix = child ? "installer-child" : "installer"; + Files.write(Paths.get(prefix + "-ready"), new byte[] {1}); + Thread.sleep(1200); + Files.write(Paths.get(prefix + "-survived"), new byte[] {1}); + } +} diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index e235c78..06c3d61 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -8,7 +8,7 @@ use serde_json::json; use tempfile::TempDir; use rmcl::instance::launch::{ - LaunchAuth, LaunchError, build_launch_invocation, supports_quick_play, + LaunchAuth, LaunchError, build_launch_invocation_with_settings, supports_quick_play, }; use rmcl::instance::models::{InstanceConfig, ModLoader}; @@ -16,6 +16,24 @@ const PLAYER: &str = "TestPlayer"; const PLAYER_UUID: &str = "00000000-0000-0000-0000-000000000001"; const PLAYER_TOKEN: &str = "secret-access-token"; +async fn build_launch_invocation( + config: &InstanceConfig, + instances_dir: &Path, + meta_dir: &Path, + auth: &LaunchAuth<'_>, + quick_play_world: Option<&str>, +) -> Result { + build_launch_invocation_with_settings( + config, + instances_dir, + meta_dir, + auth, + quick_play_world, + &rmcl::config::Config::default(), + ) + .await +} + fn test_auth() -> LaunchAuth<'static> { LaunchAuth { username: PLAYER, @@ -42,9 +60,7 @@ fn make_config_with( loader_version: loader_version.map(str::to_owned), created: Utc::now(), last_played: None, - // pinned to a deterministic value so detect_java_path is never - // invoked and tests don't depend on the host's java install. - java_path: Some("/usr/bin/java-test".into()), + java_path: Some(default_fake_java()), memory_max: None, memory_min: None, jvm_args: Vec::new(), @@ -62,22 +78,117 @@ fn make_config_with( } } -#[cfg(unix)] fn fake_java(tmp: &TempDir, major: u32) -> String { - use std::os::unix::fs::PermissionsExt; + fake_java_platform(tmp, major, &host_java_platform()) +} - let path = tmp.path().join(format!("java-{major}")); +fn host_java_platform() -> rmcl::launch_profile::system::JavaPlatform { + rmcl::launch_profile::system::JavaPlatform::from_java_properties( + match std::env::consts::OS { + "windows" => "Windows 10", + "macos" => "Mac OS X", + _ => "Linux", + }, + std::env::consts::ARCH, + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + }, + "10.0", + ) + .unwrap() +} + +fn default_fake_java() -> String { + static JAVA: std::sync::OnceLock<(TempDir, String)> = std::sync::OnceLock::new(); + JAVA.get_or_init(|| { + let temp = tempfile::tempdir().unwrap(); + let java = fake_java(&temp, 25); + (temp, java) + }) + .1 + .clone() +} + +fn fake_java_platform( + tmp: &TempDir, + major: u32, + platform: &rmcl::launch_profile::system::JavaPlatform, +) -> String { + let os_name = match platform.os_name { + "windows" => "Windows 10", + "osx" => "Mac OS X", + _ => "Linux", + }; + let text = format!( + "java.version = {major}.0.1\nos.name = {os_name}\nos.arch = {}\nsun.arch.data.model = {}\nos.version = {}", + platform.arch, platform.bitness, platform.os_version + ); + let path = tmp.path().join(format!( + "java probe-{major}-{}.{}", + platform.arch, + if cfg!(windows) { "cmd" } else { "sh" } + )); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::write( + &path, + format!( + "#!/bin/sh\nprintf '%s\\n' {} >&2\n", + text.lines() + .map(|line| format!("'{line}'")) + .collect::>() + .join(" ") + ), + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + #[cfg(windows)] std::fs::write( &path, - format!("#!/bin/sh\necho 'openjdk version \"{major}.0.1\"' >&2\n"), + format!( + "@echo off\r\n{}\r\n", + text.lines() + .map(|line| format!("echo {line} 1>&2")) + .collect::>() + .join("\r\n") + ), ) .unwrap(); - let mut permissions = std::fs::metadata(&path).unwrap().permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(&path, permissions).unwrap(); path.to_string_lossy().into_owned() } +fn cache_fixture_artifacts(meta_dir: &Path, profile: &mut serde_json::Value) { + use sha1::Digest; + let bytes = b"synthetic jar"; + if let Some(libraries) = profile["libraries"].as_array_mut() { + for library in libraries { + let name = library["name"].as_str().unwrap().to_owned(); + if let Some(artifact) = library["downloads"] + .get_mut("artifact") + .filter(|value| value.is_object()) + { + let path = artifact["path"] + .as_str() + .filter(|path| !path.is_empty()) + .map(str::to_owned) + .or_else(|| rmcl::instance::loader::maven::maven_coord_to_path(&name)) + .unwrap(); + let dest = rmcl::storage::MetadataPaths::new(meta_dir) + .libraries() + .join(path); + std::fs::create_dir_all(dest.parent().unwrap()).unwrap(); + std::fs::write(dest, bytes).unwrap(); + artifact["sha1"] = json!(format!("{:x}", sha1::Sha1::digest(bytes))); + artifact["size"] = json!(bytes.len()); + } + } + } +} + struct Fixture { _tmp: TempDir, instances_dir: PathBuf, @@ -85,7 +196,7 @@ struct Fixture { } impl Fixture { - fn new(instance_name: &str, game_version: &str, vanilla_meta: serde_json::Value) -> Self { + fn new(instance_name: &str, game_version: &str, mut vanilla_meta: serde_json::Value) -> Self { let tmp = tempfile::tempdir().unwrap(); let instances_dir = tmp.path().join("instances"); let meta_dir = tmp.path().join("meta"); @@ -94,6 +205,7 @@ impl Fixture { std::fs::create_dir_all(&instance_minecraft).unwrap(); std::fs::create_dir_all(meta_dir.join("cache/minecraft/libraries")).unwrap(); + cache_fixture_artifacts(&meta_dir, &mut vanilla_meta); std::fs::create_dir_all(meta_dir.join("cache/loaders/profiles")).unwrap(); let version_dir = meta_dir.join("cache/minecraft/versions").join(game_version); std::fs::create_dir_all(&version_dir).unwrap(); @@ -110,7 +222,8 @@ impl Fixture { } } - fn write_loader_profile(&self, filename: &str, content: serde_json::Value) { + fn write_loader_profile(&self, filename: &str, mut content: serde_json::Value) { + cache_fixture_artifacts(&self.meta_dir, &mut content); std::fs::write( self.meta_dir.join("cache/loaders/profiles").join(filename), serde_json::to_vec_pretty(&content).unwrap(), @@ -166,7 +279,6 @@ fn modern_vanilla_meta(id: &str) -> serde_json::Value { }) } -#[cfg(unix)] fn modern_vanilla_meta_with_java(id: &str, java_major: u32) -> serde_json::Value { let mut meta = modern_vanilla_meta(id); meta["javaVersion"] = json!({ @@ -204,15 +316,11 @@ async fn vanilla_modern_builds_complete_invocation() { .await .unwrap(); - assert_eq!(inv.java, "/usr/bin/java-test"); + assert_eq!(inv.java, config.java_path.as_deref().unwrap()); assert_eq!(inv.main_class, "net.minecraft.client.main.Main"); assert!(inv.extra_args.is_empty()); - let expected_natives = fx - .meta_dir - .join("cache/minecraft/versions") - .join("1.20.1") - .join("natives"); + let expected_natives = host_java_platform().natives_directory(&fx.meta_dir, "1.20.1"); let actual_natives = inv .jvm_args .iter() @@ -283,7 +391,6 @@ async fn quick_play_passes_the_selected_save_folder() { ); } -#[cfg(unix)] #[tokio::test] async fn launch_fails_when_selected_java_is_older_than_profile_requires() { let fx = Fixture::new( @@ -322,7 +429,8 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { assert_eq!(inv.main_class, "net.minecraft.launchwrapper.Launch"); - assert_eq!(inv.jvm_args.len(), 2); + assert_eq!(inv.jvm_args.len(), 3); + assert!(inv.jvm_args[2].starts_with("-Djava.library.path=")); assert!(inv.jvm_args[0].starts_with("-Xms")); assert!(inv.jvm_args[1].starts_with("-Xmx")); @@ -333,6 +441,38 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { assert!(joined.contains("--userType msa")); } +#[tokio::test] +async fn missing_or_empty_artifact_paths_use_maven_coordinates() { + for path in [None, Some("")] { + let mut meta = modern_vanilla_meta("1.20.1"); + let artifact = meta["libraries"][0]["downloads"]["artifact"] + .as_object_mut() + .unwrap(); + if let Some(path) = path { + artifact.insert("path".to_owned(), json!(path)); + } else { + artifact.remove("path"); + } + let fixture = Fixture::new("artifact", "1.20.1", meta); + let invocation = build_launch_invocation( + &make_config("artifact", "1.20.1", ModLoader::Vanilla), + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + assert!( + invocation.classpath.contains( + &rmcl::storage::MetadataPaths::new(&fixture.meta_dir) + .libraries() + .join("org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar") + ) + ); + } +} + #[tokio::test] async fn forge_modern_includes_add_opens() { let fx = Fixture::new("f1", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -423,9 +563,9 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() { "expected local fmlloader on classpath: {:?}", inv.classpath ); - let meta_candidate = fx - .meta_dir - .join("libraries/net/minecraftforge/fmlloader/1.20.1-47.2.0/fmlloader-1.20.1-47.2.0.jar"); + let meta_candidate = rmcl::storage::MetadataPaths::new(&fx.meta_dir) + .libraries() + .join("net/minecraftforge/fmlloader/1.20.1-47.2.0/fmlloader-1.20.1-47.2.0.jar"); assert!( !inv.classpath.contains(&meta_candidate), "meta-dir candidate should not be on classpath when local exists" @@ -612,7 +752,9 @@ async fn rule_disallow_excludes_library() { .await .unwrap(); - let denied = fx.meta_dir.join("libraries/com/denied/lib/1.0/lib-1.0.jar"); + let denied = rmcl::storage::MetadataPaths::new(&fx.meta_dir) + .libraries() + .join("com/denied/lib/1.0/lib-1.0.jar"); assert!( !inv.classpath.contains(&denied), "denied library was included: {:?}", @@ -790,3 +932,362 @@ async fn legacy_loader_profile_missing_installer_json_errors() { "expected Parse error about missing installer JSON, got: {err:?}" ); } + +#[tokio::test] +async fn rules_and_natives_directory_follow_the_selected_java_properties() { + for (os, arch, bits, normalized) in [ + ("Windows 10", "x86", "32", "x86"), + ("Windows 10", "amd64", "64", "x86_64"), + ("Mac OS X", "x86_64", "64", "x86_64"), + ("Mac OS X", "aarch64", "64", "arm64"), + ("Linux", "amd64", "64", "x86_64"), + ] { + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + os, arch, bits, "10.0", + ) + .unwrap(); + let mut meta = modern_vanilla_meta("1.16.5"); + for cpu in ["x86", "x86_64", "arm64"] { + meta["libraries"].as_array_mut().unwrap().push(json!({ + "name":format!("test:only-{cpu}:1"), "rules":[{"action":"allow", "os":{"arch":cpu}}], + })); + } + meta["arguments"]["jvm"] + .as_array_mut() + .unwrap() + .push(json!({ + "rules":[{"action":"allow", "os":{"name":"windows", "version":"^10\\."}}], + "value":["-Dos.name=Windows 10", "-Dos.version=10.0"], + })); + let fixture = Fixture::new("java rules", "1.16.5", meta); + let mut config = make_config("java rules", "1.16.5", ModLoader::Vanilla); + config.java_path = Some(fake_java_platform(&fixture._tmp, 25, &platform)); + let invocation = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + let cpu_jars: Vec<_> = invocation + .classpath + .iter() + .filter(|path| path.to_string_lossy().contains("only-")) + .collect(); + assert_eq!(cpu_jars.len(), 1); + assert!(cpu_jars[0].ends_with(format!("only-{normalized}-1.jar"))); + assert!(invocation.jvm_args.contains(&format!( + "-Djava.library.path={}", + platform + .natives_directory(&fixture.meta_dir, "1.16.5") + .display() + ))); + assert_eq!( + invocation + .jvm_args + .contains(&"-Dos.version=10.0".to_owned()), + platform.os_name == "windows" + ); + } +} + +fn zip_entries(entries: &[(&str, &[u8])]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +fn install_test_lwjgl3ify(fixture: &Fixture, base_url: &str) { + use sha1::Digest; + let bytes = b"declared library bytes"; + let mut libraries = Vec::new(); + for module in ["lwjgl", "lwjgl-sdl", "lwjgl-spng"] { + libraries.push(json!({"name":format!("org.lwjgl:{module}:3.4.2"), "downloads":{"artifact":{ + "url":format!("{base_url}/{module}-3.4.2.jar"), "sha1":format!("{:x}", sha1::Sha1::digest(bytes)), "size":bytes.len(), + }}})); + for (classifier, os) in [ + ("natives-linux", "linux"), + ("natives-linux-arm64", "linux"), + ("natives-macos", "osx"), + ("natives-macos-arm64", "osx"), + ("natives-windows", "windows"), + ("natives-windows-x86", "windows"), + ("natives-windows-arm64", "windows"), + ] { + libraries.push( + json!({"name":format!("org.lwjgl:{module}-{classifier}:3.4.2"), + "rules":[{"action":"allow", "os":{"name":os}}], "downloads":{"artifact":{ + "url":format!("{base_url}/{module}-3.4.2-{classifier}.jar"), + "sha1":format!("{:x}", sha1::Sha1::digest(bytes)), "size":bytes.len(), + }}}), + ); + } + } + let payload = zip_entries(&[("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n")]); + libraries.push(json!({"name":"com.github.GTNewHorizons:lwjgl3ify:3.0.35:forgePatches", "downloads":{"artifact":{ + "url":format!("{base_url}/forgePatches.jar"), "sha1":format!("{:x}", sha1::Sha1::digest(&payload)), "size":payload.len(), + }}})); + let profile = json!({"id":"lwjgl3ify-client", "mainClass":"com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread", + "javaVersion":{"majorVersion":25}, "libraries":libraries, + "arguments":{"game":["--username", "${auth_player_name}", "--tweakClass", "metadata.ClientTweaker"], "jvm":[ + {"rules":[{"action":"allow", "os":{"name":"osx"}}], "value":"-XstartOnFirstThread"}, + "--add-opens", "java.base/java.lang=ALL-UNNAMED", "--enable-native-access", "ALL-UNNAMED", + "-Djava.library.path=${natives_directory}", "-cp", "${classpath}", + "-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader", + ]}, + }); + let mods = fixture.instances_dir.join("patched/minecraft/mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write( + mods.join("lwjgl3ify-3.0.35.jar"), + zip_entries(&[ + ( + "me/eigenraven/lwjgl3ify/relauncher/version.json", + &serde_json::to_vec(&profile).unwrap(), + ), + ( + "me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip", + &payload, + ), + ]), + ) + .unwrap(); + fixture.write_loader_profile("forge-1.7.10-10.13.4.1614.json", json!({ + "id":"forge-1.7.10", "inheritsFrom":"1.7.10", "mainClass":"net.minecraft.launchwrapper.Launch", + "libraries":[{"name":"net.minecraft:launchwrapper:1.12"}, {"name":"org.lwjgl.lwjgl:lwjgl-platform:2.9.4"}], + "arguments":{"game":["--tweakClass", "old.parent.Tweaker"], "jvm":["-Dold.parent.jvm=true"]}, + })); +} + +#[tokio::test] +async fn lwjgl3ify_empty_cache_downloads_exact_metadata_and_renders_client_startup() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + for (os, arch, bits, classifier) in [ + ("Linux", "amd64", "64", "natives-linux"), + ("Linux", "aarch64", "64", "natives-linux-arm64"), + ("Mac OS X", "amd64", "64", "natives-macos"), + ("Mac OS X", "aarch64", "64", "natives-macos-arm64"), + ("Windows 10", "x86", "32", "natives-windows-x86"), + ("Windows 10", "amd64", "64", "natives-windows"), + ("Windows 10", "aarch64", "64", "natives-windows-arm64"), + ] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200).set_body_bytes(b"declared library bytes".to_vec()), + ) + .expect(6) + .mount(&server) + .await; + let fixture = Fixture::new("patched", "1.7.10", legacy_vanilla_meta("1.7.10")); + install_test_lwjgl3ify(&fixture, &server.uri()); + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + os, arch, bits, "10.0", + ) + .unwrap(); + let mut config = + make_config_with("patched", "1.7.10", ModLoader::Forge, Some("10.13.4.1614")); + config.java_path = Some(fake_java_platform(&fixture._tmp, 25, &platform)); + for _ in 0..2 { + let invocation = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + assert_eq!(invocation.main_class, "RmclShim"); + assert_eq!( + invocation.extra_args, + ["com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread"] + ); + assert_eq!( + invocation + .jvm_args + .contains(&"-XstartOnFirstThread".to_owned()), + platform.os_name == "osx" + ); + assert!( + invocation + .jvm_args + .windows(2) + .any(|args| args == ["--enable-native-access", "ALL-UNNAMED"]) + ); + assert!( + invocation + .jvm_args + .windows(2) + .any(|args| args[0] == "-cp" && args[1] == invocation.classpath_string) + ); + assert!( + invocation + .game_args + .contains(&"metadata.ClientTweaker".to_owned()) + ); + assert!( + !invocation + .game_args + .contains(&"old.parent.Tweaker".to_owned()) + ); + assert!( + !invocation + .jvm_args + .contains(&"-Dold.parent.jvm=true".to_owned()) + ); + assert!(invocation.game_args.contains(&PLAYER.to_owned())); + let natives: Vec<_> = invocation + .classpath + .iter() + .filter(|path| path.to_string_lossy().contains("-natives-")) + .collect(); + assert_eq!(natives.len(), 3); + assert!(natives.iter().all(|path| { + path.to_string_lossy() + .contains(&format!("-{classifier}-3.4.2.jar")) + })); + for path in invocation.classpath.iter().filter(|path| { + path.to_string_lossy().contains("org/lwjgl") + || path.to_string_lossy().contains("org\\lwjgl") + }) { + assert_eq!(std::fs::read(path).unwrap(), b"declared library bytes"); + } + assert!( + !invocation + .classpath + .iter() + .any(|path| path.to_string_lossy().contains("2.9.4") + || path.to_string_lossy().contains("launchwrapper-")) + ); + } + server.verify().await; + } +} + +#[tokio::test] +async fn lwjgl3ify_download_failure_does_not_launch_with_missing_libraries() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + let fixture = Fixture::new("patched", "1.7.10", legacy_vanilla_meta("1.7.10")); + install_test_lwjgl3ify(&fixture, &server.uri()); + let config = make_config_with("patched", "1.7.10", ModLoader::Forge, Some("10.13.4.1614")); + let error = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap_err(); + assert!(matches!(error, LaunchError::Download(_)), "{error}"); +} + +#[tokio::test] +async fn selected_java_is_resolved_and_probed_in_the_launch_environment_and_cwd() { + let fixture = Fixture::new("context", "1.20.1", modern_vanilla_meta("1.20.1")); + let minecraft = fixture.instances_dir.join("context/minecraft"); + std::fs::write(minecraft.join("expected-cwd"), b"ready").unwrap(); + let bin = fixture._tmp.path().join("custom java bin"); + std::fs::create_dir_all(&bin).unwrap(); + let name = if cfg!(windows) { + "context-java.cmd" + } else { + "context-java" + }; + let java = bin.join(name); + let original = fake_java(&fixture._tmp, 25); + let mut script = std::fs::read_to_string(original).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + script = script.replacen("#!/bin/sh\n", "#!/bin/sh\n[ \"$PROBE_CONTEXT\" = instance ] && [ -f expected-cwd ] || exit 77\nprintf '%s' \"$PROBE_CONTEXT\" > probe-context\n", 1); + std::fs::write(&java, &script).unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + #[cfg(windows)] + { + script = script.replacen("@echo off\r\n", "@echo off\r\nif not \"%PROBE_CONTEXT%\"==\"instance\" exit /b 77\r\nif not exist expected-cwd exit /b 78\r\necho %PROBE_CONTEXT%>probe-context\r\n", 1); + std::fs::write(&java, &script).unwrap(); + } + let mut settings = rmcl::config::Config::default(); + settings + .defaults + .environment + .insert("PATH".into(), "missing-global-path".into()); + settings + .defaults + .environment + .insert("PROBE_CONTEXT".into(), "global".into()); + let mut config = make_config("context", "1.20.1", ModLoader::Vanilla); + config.java_path = Some(name.into()); + config.environment.insert( + if cfg!(windows) { "path" } else { "PATH" }.into(), + bin.to_string_lossy().into_owned(), + ); + config.environment.insert( + if cfg!(windows) { + "probe_context" + } else { + "PROBE_CONTEXT" + } + .into(), + "instance".into(), + ); + let invocation = build_launch_invocation_with_settings( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + &settings, + ) + .await + .unwrap(); + assert_eq!( + Path::new(&invocation.java).canonicalize().unwrap(), + java.canonicalize().unwrap() + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("probe-context")) + .unwrap() + .trim(), + "instance" + ); + assert_eq!(invocation.working_dir, minecraft); + let cwd = invocation.working_dir.clone(); + let environment = invocation.environment.clone(); + let installation = tokio::task::spawn_blocking(move || { + rmcl::instance::java::inspect_installation_in(Path::new(name), &cwd, &environment) + }) + .await + .unwrap() + .unwrap(); + assert_eq!( + installation.path.canonicalize().unwrap(), + java.canonicalize().unwrap() + ); + assert_eq!(installation.version.as_deref(), Some("25.0.1")); + if cfg!(windows) { + assert_eq!( + invocation + .environment + .keys() + .filter(|key| key.eq_ignore_ascii_case("PATH")) + .count(), + 1 + ); + } +} diff --git a/tests/net_mojang.rs b/tests/net_mojang.rs index 3fd4c9c..25f450f 100644 --- a/tests/net_mojang.rs +++ b/tests/net_mojang.rs @@ -8,10 +8,36 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; use rmcl::net::HttpClient; use rmcl::net::mojang::{ Artifact, AssetIndex, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads, - VersionEntry, VersionMeta, download_assets, download_assets_from, download_libraries, - fetch_version_manifest_from, fetch_version_meta_with_raw, + VersionEntry, VersionMeta, download_assets, download_assets_from, + download_libraries_for_platform, fetch_version_manifest_from, fetch_version_meta_with_raw, }; +fn test_platform() -> rmcl::launch_profile::system::JavaPlatform { + rmcl::launch_profile::system::JavaPlatform::from_java_properties( + match std::env::consts::OS { + "windows" => "Windows 10", + "macos" => "Mac OS X", + _ => "Linux", + }, + std::env::consts::ARCH, + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + }, + "10.0", + ) + .unwrap() +} + +async fn download_libraries( + client: &HttpClient, + meta: &VersionMeta, + meta_dir: &std::path::Path, +) -> Result<(), rmcl::net::NetError> { + download_libraries_for_platform(client, meta, meta_dir, &test_platform()).await +} + fn sha1(bytes: &[u8]) -> String { use sha1::Digest; format!("{:x}", sha1::Sha1::digest(bytes)) @@ -299,8 +325,10 @@ async fn download_assets_from_writes_index_and_assets() { let server = MockServer::start().await; let hash = sha1(b"asset-bytes"); let index = serde_json::to_vec(&json!({ + "virtual": true, "objects": { - "minecraft/lang/en_us.json": {"hash": hash, "size": b"asset-bytes".len()} + "minecraft/lang/en_us.json": {"hash": hash, "size": b"asset-bytes".len()}, + "lang/en_us.lang": {"hash": hash, "size": b"asset-bytes".len()} } })) .unwrap(); @@ -335,6 +363,20 @@ async fn download_assets_from_writes_index_and_assets() { .join(&hash); assert!(asset_path.exists(), "asset file missing"); assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes"); + for name in ["minecraft/lang/en_us.json", "lang/en_us.lang"] { + assert_eq!( + std::fs::read( + tmp.path() + .join("cache/minecraft/assets/virtual/5") + .join(name) + ) + .unwrap(), + b"asset-bytes" + ); + } + download_assets_from(&HttpClient::new(), &meta, tmp.path(), &cdn_base) + .await + .unwrap(); } #[tokio::test] @@ -509,7 +551,14 @@ async fn download_libraries_downloads_and_extracts_natives() { downloads: LibraryDownloads { artifact: None, classifiers: Some(std::collections::HashMap::from([( - "natives-linux".to_string(), + format!( + "natives-linux-{}", + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + } + ), Artifact { url: format!("{server_uri}/lwjgl-natives.jar"), path: "org/lwjgl/lwjgl/lwjgl/2.9.4/lwjgl-2.9.4-natives-linux.jar" @@ -522,7 +571,7 @@ async fn download_libraries_downloads_and_extracts_natives() { rules: None, natives: Some(std::collections::HashMap::from([( rmcl::launch_profile::system::mojang_os_name().to_string(), - "natives-linux".to_string(), + "natives-linux-${arch}".to_string(), )])), extract: Some(rmcl::net::mojang::LibraryExtract { exclude: Some(vec!["META-INF/".to_string()]), @@ -541,18 +590,151 @@ async fn download_libraries_downloads_and_extracts_natives() { ); assert_eq!(std::fs::read(&cached_jar).unwrap(), jar_bytes); - let extracted = tmp - .path() - .join("cache/minecraft/versions/test/natives/lib/native.so"); + let natives = test_platform().natives_directory(tmp.path(), "test"); + let extracted = natives.join("lib/native.so"); assert_eq!( std::fs::read(&extracted).unwrap(), b"native-bits", "natives payload must be unpacked next to java.library.path" ); + let original_permissions = std::fs::metadata(&extracted).unwrap().permissions(); + let modified = std::fs::metadata(&extracted).unwrap().modified().unwrap(); + let mut protected = original_permissions.clone(); + protected.set_readonly(true); + std::fs::set_permissions(&extracted, protected).unwrap(); + let reuse = download_libraries(&HttpClient::new(), &meta, tmp.path()).await; + std::fs::set_permissions(&extracted, original_permissions).unwrap(); + reuse.expect("unchanged natives must be reusable without replacing a protected/loaded library"); + assert_eq!( + std::fs::metadata(&extracted).unwrap().modified().unwrap(), + modified + ); + std::fs::write(&extracted, b"corrupted extraction").unwrap(); + download_libraries(&HttpClient::new(), &meta, tmp.path()) + .await + .unwrap(); + assert_eq!(std::fs::read(&extracted).unwrap(), b"native-bits"); assert!( - !tmp.path() - .join("cache/minecraft/versions/test/natives/META-INF") - .exists(), + !natives.join("META-INF").exists(), "extract.exclude prefixes must be skipped" ); } + +fn native_zip(payload: &[u8]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("native.dll", zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(payload).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[tokio::test] +async fn selected_java_bitness_controls_downloads_and_extraction_is_isolated() { + let server = MockServer::start().await; + let mut classifiers = serde_json::Map::new(); + for bits in [32, 64] { + let bytes = native_zip(bits.to_string().as_bytes()); + let url = format!("/native-{bits}.jar"); + Mock::given(method("GET")) + .and(path(&url)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .expect(1) + .mount(&server) + .await; + classifiers.insert( + format!("natives-windows-{bits}"), + json!({ + "url":format!("{}{url}", server.uri()), "sha1":sha1(&bytes), "size":bytes.len(), + }), + ); + } + let mut meta = meta_with_one_library(&server.uri()); + meta.libraries = serde_json::from_value(json!([{ + "name":"tv.twitch:twitch-platform:5.16", "downloads":{"classifiers":classifiers}, + "natives":{"windows":"natives-windows-${arch}"}, + "rules":[{"action":"allow", "os":{"name":"windows", "version":"^10\\."}}], + }])) + .unwrap(); + let temp = tempfile::tempdir().unwrap(); + for (arch, bits) in [("x86", "32"), ("amd64", "64")] { + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + arch, + bits, + "10.0", + ) + .unwrap(); + download_libraries_for_platform(&HttpClient::new(), &meta, temp.path(), &platform) + .await + .unwrap(); + let natives = platform.natives_directory(temp.path(), &meta.id); + assert_eq!( + std::fs::read(natives.join("native.dll")).unwrap(), + bits.as_bytes() + ); + } + // The second extraction must leave the first architecture's payload intact. + let java32 = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + "x86", + "32", + "10.0", + ) + .unwrap(); + assert_eq!( + std::fs::read( + java32 + .natives_directory(temp.path(), &meta.id) + .join("native.dll") + ) + .unwrap(), + b"32" + ); + assert!( + !temp + .path() + .join("cache/minecraft/versions") + .join(&meta.id) + .join("natives/native.dll") + .exists() + ); + let old_windows = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 7", + "x86", + "32", + "6.1", + ) + .unwrap(); + let other = tempfile::tempdir().unwrap(); + download_libraries_for_platform(&HttpClient::new(), &meta, other.path(), &old_windows) + .await + .unwrap(); + assert!( + !old_windows + .natives_directory(other.path(), &meta.id) + .exists() + ); +} + +#[tokio::test] +async fn missing_selected_native_classifier_is_reported() { + let mut meta = meta_with_one_library("https://example.invalid"); + meta.libraries = serde_json::from_value(json!([{ + "name":"tv.twitch:twitch-platform:5.16", "downloads":{"classifiers":{}}, + "natives":{"windows":"natives-windows-${arch}"}, + }])) + .unwrap(); + let java32 = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + "x86", + "32", + "10.0", + ) + .unwrap(); + let temp = tempfile::tempdir().unwrap(); + let error = download_libraries_for_platform(&HttpClient::new(), &meta, temp.path(), &java32) + .await + .unwrap_err(); + assert!(error.to_string().contains("natives-windows-32")); +}