Fix an issue that causes create symlink failed when installing java on unix-like platforms.
This commit is contained in:
1 parent
8bde4ef753
commit
1754b01230
15 files changed
+600
-77
No files matched your search
@@ -1,4 +1,4 @@
|
||||
__version__ = '0.1.1'
|
||||
__version__ = '0.1.2'
|
||||
__description__ = """
|
||||
The core library of the *Launcher*
|
||||
|
||||
|
||||
@@ -160,6 +160,12 @@ class FileObject:
|
||||
def exists(self):
|
||||
return self.__path.exists()
|
||||
|
||||
def invalidate_hash_cache(self):
|
||||
self.__sha1 = None
|
||||
self.__sha256 = None
|
||||
self.__sha512 = None
|
||||
self.__md5 = None
|
||||
|
||||
|
||||
def download_file(file: FileObject, overwrite=True, progress_callback: Callable[int]=None) -> FileObject | Exception:
|
||||
"""
|
||||
@@ -180,6 +186,7 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
|
||||
|
||||
logger.debug("Downloading file {} to {}".format(file.url, file))
|
||||
|
||||
file.invalidate_hash_cache() # Clean cache hash
|
||||
try:
|
||||
with requests.get(file.url, stream=True) as r:
|
||||
r.raise_for_status()
|
||||
@@ -203,6 +210,8 @@ def download_file(file: FileObject, overwrite=True, progress_callback: Callable[
|
||||
raise DownloadException(
|
||||
"An error occurred while downloading file {}. {}".format(file.url, e)
|
||||
)
|
||||
finally:
|
||||
file.invalidate_hash_cache()
|
||||
|
||||
if file.expected_sha256 and not file.verify_sha256():
|
||||
raise HashMismatchException("sha256", file.sha256, file.expected_sha256, file.posix_path)
|
||||
|
||||
@@ -24,8 +24,8 @@ class LauncherHTTPException(LauncherException):
|
||||
class HashMismatchException(Exception):
|
||||
def __init__(self, hash_name, got_hash, expected_hash, filepath: str | Path):
|
||||
if type(filepath) == Path: filepath = Path(filepath).absolute().as_posix()
|
||||
self.message = "File {} hash mismatch. Expected hash {}. Got hash {} ({})".format(filepath, got_hash,
|
||||
expected_hash, hash_name)
|
||||
self.message = "File {} hash mismatch. Expected hash {}. Got hash {} ({})".format(filepath, expected_hash, got_hash,
|
||||
hash_name)
|
||||
super().__init__(self.message)
|
||||
|
||||
class UnsupportedPlatformException(LauncherException):
|
||||
|
||||
+66
-29
@@ -4,10 +4,18 @@ import re
|
||||
import shlex
|
||||
|
||||
from core_lib.common.common import get_platform_info
|
||||
from core_lib.common.exception import LauncherException
|
||||
from core_lib.game.library import get_natives_platform_info
|
||||
|
||||
logger = logging.getLogger("Launcher.CoreLib")
|
||||
|
||||
def compare_versions(left: str, right: str) -> int:
|
||||
left_parts = tuple(map(int, left.split(".")))
|
||||
right_parts = tuple(map(int, right.split(".")))
|
||||
length = max(len(left_parts), len(right_parts))
|
||||
left_parts += (0,) * (length - len(left_parts))
|
||||
right_parts += (0,) * (length - len(right_parts))
|
||||
return (left_parts > right_parts) - (left_parts < right_parts)
|
||||
|
||||
def is_argument_allowed(argument: dict | str, allow_features: dict | None = None) -> bool:
|
||||
"""
|
||||
@@ -44,6 +52,7 @@ def is_argument_allowed(argument: dict | str, allow_features: dict | None = None
|
||||
feature_rule = rule.get("features") or {}
|
||||
rule_arch = os_rule.get("arch")
|
||||
rule_version = os_rule.get("version")
|
||||
rule_version_range = os_rule.get("versionRange")
|
||||
|
||||
# Check platform
|
||||
if rule_os is not None and platform_rule_name != rule_os:
|
||||
@@ -69,6 +78,18 @@ def is_argument_allowed(argument: dict | str, allow_features: dict | None = None
|
||||
)
|
||||
continue
|
||||
|
||||
# Check version range
|
||||
if rule_version_range is not None:
|
||||
min_value = rule_version_range.get("min")
|
||||
max_value = rule_version_range.get("max")
|
||||
|
||||
try:
|
||||
if min_value is not None and compare_versions(platform_version, min_value) < 0:
|
||||
continue
|
||||
if max_value is not None and compare_versions(platform_version, max_value) > 0:
|
||||
continue
|
||||
except ValueError:
|
||||
raise LauncherException("Unable to compare versions: SYS_VER: {} MIN: {} MAX: {}".format(platform_version, min_value, max_value))
|
||||
|
||||
# Check feature rule
|
||||
if any(allow_features.get(key, False) != expected for key, expected in feature_rule.items()):
|
||||
@@ -98,7 +119,8 @@ class ArgumentMappings:
|
||||
auth_access_token="", clientid=None, auth_xuid=None,
|
||||
user_type=None, user_properties=None, version_type=None, natives_directory=None,
|
||||
launcher_name=None, launcher_version=None,
|
||||
classpath=None, classpath_separator=None, library_directory=None):
|
||||
classpath=None, classpath_separator=None, library_directory=None,
|
||||
resolution: tuple[int, int] | None = None):
|
||||
self.player_name = player_name
|
||||
self.version_name = version_name
|
||||
self.game_directory = game_directory
|
||||
@@ -111,6 +133,7 @@ class ArgumentMappings:
|
||||
self.auth_xuid = auth_xuid
|
||||
self.user_type = user_type
|
||||
self.user_properties = user_properties
|
||||
self.resolution = resolution
|
||||
if isinstance(user_properties, dict):
|
||||
self.user_properties = json.dumps(
|
||||
user_properties,
|
||||
@@ -194,24 +217,8 @@ def find_game_and_jvm_args(arguments: dict | str) -> tuple[list, list]:
|
||||
return game_args, jvm_args
|
||||
|
||||
|
||||
REMAPPING_ARGUMENTS = {
|
||||
# For some (I don't know) reason, in 26.2, Mojang include some
|
||||
"-Djava.library.path=${natives_directory}/java": "-Djava.library.path=${natives_directory}"
|
||||
}
|
||||
|
||||
|
||||
def hard_remapping_special_arguments(argument: str) -> str:
|
||||
for arg in REMAPPING_ARGUMENTS:
|
||||
new_value = REMAPPING_ARGUMENTS[arg]
|
||||
|
||||
if arg == argument:
|
||||
return new_value
|
||||
|
||||
return argument
|
||||
|
||||
|
||||
def parse_and_generate_arguments(arguments: list | str, mappings: ArgumentMappings, features: dict | None = None) -> \
|
||||
list[str]:
|
||||
list[str]:
|
||||
if features is None:
|
||||
features = {}
|
||||
|
||||
@@ -228,13 +235,8 @@ list[str]:
|
||||
if not is_argument_allowed(argument, allow_features=features):
|
||||
continue
|
||||
|
||||
# Replace some special arguments
|
||||
new_argument = hard_remapping_special_arguments(argument)
|
||||
|
||||
# Each argument (section) may contain multiple items, convert it to list before replace placeholder
|
||||
converted = convert_argument_to_multiple_string(new_argument)
|
||||
|
||||
for item in converted:
|
||||
for item in convert_argument_to_multiple_string(argument):
|
||||
parsed = replace_placeholders(item, placeholders)
|
||||
parsed_arguments.append(parsed)
|
||||
|
||||
@@ -263,24 +265,59 @@ def append_missing_necessary_jvm_arguments(arguments: list, arg_maps: ArgumentMa
|
||||
|
||||
return result
|
||||
|
||||
def add_feature_arguments(arguments: dict, arg_maps: ArgumentMappings, features: dict | None = None) -> list[str]:
|
||||
result = []
|
||||
|
||||
if features is None:
|
||||
return result
|
||||
|
||||
if features.get("has_custom_resolution"):
|
||||
result.append(f"-Dminecraft.overrideResolution={features['resolution']}")
|
||||
|
||||
return result
|
||||
|
||||
def generate_launch_command(arg_maps: ArgumentMappings, main_class: str, java_path: str, full_args: dict | str
|
||||
, features: dict | None = None) -> list[str]:
|
||||
, features: dict | None = None, user_jvm_args: list[str] | None | str = None) -> list[str]:
|
||||
cmd = [java_path]
|
||||
game_args, jvm_args = find_game_and_jvm_args(full_args)
|
||||
parsed_jvm_args = parse_and_generate_arguments(
|
||||
|
||||
if isinstance(user_jvm_args, str):
|
||||
user_jvm_args = shlex.split(user_jvm_args)
|
||||
|
||||
if user_jvm_args is None:
|
||||
# Use manifest recommended user jvm arguments
|
||||
default_args = (
|
||||
full_args.get("default-user-jvm", [])
|
||||
if isinstance(full_args, dict)
|
||||
else []
|
||||
)
|
||||
|
||||
parsed_user_jvm_args = parse_and_generate_arguments(
|
||||
default_args,
|
||||
arg_maps,
|
||||
features=features,
|
||||
)
|
||||
else:
|
||||
# Use jvm arguments that provided by user
|
||||
parsed_user_jvm_args = list(user_jvm_args)
|
||||
|
||||
parsed_manifest_jvm_args = parse_and_generate_arguments(
|
||||
jvm_args,
|
||||
arg_maps,
|
||||
features=features
|
||||
features=features,
|
||||
)
|
||||
|
||||
parsed_game_args = parse_and_generate_arguments(
|
||||
game_args,
|
||||
arg_maps,
|
||||
features=features
|
||||
features=features,
|
||||
)
|
||||
|
||||
# Legacy Minecraft don't have jvm arguments exist in the version library. We need to generate by ourselves
|
||||
parsed_jvm_args = append_missing_necessary_jvm_arguments(parsed_jvm_args, arg_maps)
|
||||
parsed_jvm_args = append_missing_necessary_jvm_arguments(
|
||||
parsed_user_jvm_args + parsed_manifest_jvm_args, # Combine manifest and user jvm arguments together
|
||||
arg_maps,
|
||||
)
|
||||
|
||||
cmd.extend(parsed_jvm_args)
|
||||
cmd.append(main_class)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import logging
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PureWindowsPath
|
||||
from typing import Callable
|
||||
|
||||
from .argument import convert_argument_to_multiple_string, find_game_and_jvm_args, is_argument_allowed
|
||||
from .library import get_natives_platform_info, is_library_allowed, generate_formatted_artifact_with_name, \
|
||||
is_native_allowed, is_legacy_native_allowed, remove_duplicate_artifacts
|
||||
from .libraryx import normalize_library_to_common_struct
|
||||
@@ -64,6 +65,47 @@ def collect_library_artifacts(specific_version_manifest):
|
||||
|
||||
return items
|
||||
|
||||
def locate_natives_extract_dir(jvm_args: list[str | dict], default_extract_dir: Path,
|
||||
features: dict | None = None) -> Path:
|
||||
property_prefix = "-Djava.library.path="
|
||||
placeholder = "${natives_directory}"
|
||||
|
||||
path_value = None
|
||||
for argument in jvm_args:
|
||||
if not is_argument_allowed(argument, allow_features=features):
|
||||
continue
|
||||
for arg in convert_argument_to_multiple_string(argument):
|
||||
if arg.startswith(property_prefix):
|
||||
path_value = arg[len(property_prefix):]
|
||||
|
||||
if path_value is None or path_value == placeholder:
|
||||
return default_extract_dir
|
||||
|
||||
if not path_value.startswith(placeholder + "/") and not path_value.startswith(placeholder + "\\"):
|
||||
raise ValueError("Unsupported java.library.path extraction layout")
|
||||
|
||||
suffix = path_value[len(placeholder) + 1:].replace("\\", "/")
|
||||
parts = suffix.split("/")
|
||||
|
||||
if (
|
||||
any(part in ("", ".", "..") for part in parts)
|
||||
or any(char in suffix for char in ":;${}")
|
||||
or PureWindowsPath(suffix).drive
|
||||
):
|
||||
raise ValueError("Invalid native extraction subdirectory")
|
||||
|
||||
root = default_extract_dir.resolve()
|
||||
destination = root.joinpath(*parts).resolve()
|
||||
|
||||
if not destination.is_relative_to(root):
|
||||
raise ValueError("Native extraction directory escapes its root")
|
||||
|
||||
return destination
|
||||
|
||||
def locate_natives_extract_dir_by_manifest(manifest: dict, default_extract_dir: Path,
|
||||
features: dict | None = None) -> Path:
|
||||
_, jvm = find_game_and_jvm_args(manifest.get("arguments") or {})
|
||||
return locate_natives_extract_dir(jvm, default_extract_dir, features=features)
|
||||
|
||||
def collect_native_artifacts(specific_version_manifest):
|
||||
"""
|
||||
@@ -344,7 +386,9 @@ def check_libraries_exists(manifest: dict, libraries_dir: Path):
|
||||
return not_found
|
||||
|
||||
|
||||
def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path):
|
||||
def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *,
|
||||
features: dict | None = None):
|
||||
extract_dir = locate_natives_extract_dir_by_manifest(manifest, natives_dir, features=features)
|
||||
filtered = []
|
||||
|
||||
# Convert current platform and architecture type to same formula
|
||||
@@ -464,17 +508,19 @@ def check_natives_exists(manifest: dict, libraries_dir: Path, natives_dir: Path)
|
||||
return False
|
||||
|
||||
for target in expected:
|
||||
if not (natives_dir / target).exists():
|
||||
if not (extract_dir / target).is_file():
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path) -> bool:
|
||||
def check_full_libraries_exists(manifest: dict, libraries_dir: Path, natives_dir: Path, *,
|
||||
features: dict | None = None) -> bool:
|
||||
natives_exist = check_natives_exists(
|
||||
manifest,
|
||||
libraries_dir,
|
||||
natives_dir,
|
||||
features=features,
|
||||
)
|
||||
missing_libraries = check_libraries_exists(
|
||||
manifest,
|
||||
@@ -555,10 +601,12 @@ def generate_classpath(manifest: dict, libraries_dir: Path, core_file_path: Path
|
||||
return f"{separator}".join(classes)
|
||||
|
||||
|
||||
def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Path,
|
||||
def download_full_libraries(manifest: dict, libraries_dir: Path, default_natives_dir: Path,
|
||||
progress_callback: Callable[[str, float], None] = None,
|
||||
redownload_callback: Callable[
|
||||
[list[FileObject]], tuple[bool, list[FileObject]]] = None) -> None:
|
||||
[list[FileObject]], tuple[bool, list[FileObject]]] = None, *,
|
||||
features: dict | None = None) -> None:
|
||||
natives_dir = locate_natives_extract_dir_by_manifest(manifest, default_natives_dir, features=features)
|
||||
# libraries
|
||||
libraries = collect_library_artifacts(manifest)
|
||||
|
||||
@@ -593,4 +641,4 @@ def download_full_libraries(manifest: dict, libraries_dir: Path, natives_dir: Pa
|
||||
else:
|
||||
raise DependencyException(
|
||||
"Certain libraries download failed. Unable to continue unzip process.\n"
|
||||
)
|
||||
)
|
||||
+69
-33
@@ -164,19 +164,20 @@ def get_support_runtime_manifest(root_runtime_manifest: dict, require_component:
|
||||
@dataclass
|
||||
class RuntimeCheckResult:
|
||||
# file and dir
|
||||
skip: bool
|
||||
is_executable: bool
|
||||
target_path: FileObject | Path | None
|
||||
|
||||
# symlink only
|
||||
is_symlink: bool
|
||||
source_path: Path
|
||||
source_path: Path | str | None
|
||||
|
||||
def _check_runtime_file(relative_path, source_path: str | None, file_type: str, sha1: str | None, size: str | None, url: str | None,
|
||||
executable: bool, runtime_dir: Path, no_hash_check: bool = False) -> RuntimeCheckResult:
|
||||
full_path = runtime_dir / Path(relative_path)
|
||||
source_path = (runtime_dir / Path(source_path)) if source_path else None
|
||||
source_path = Path(source_path) if source_path else None
|
||||
|
||||
result = RuntimeCheckResult(is_executable=executable, target_path=None, is_symlink=False, source_path=source_path)
|
||||
result = RuntimeCheckResult(skip=False, is_executable=executable, target_path=None, is_symlink=False, source_path=source_path)
|
||||
|
||||
if (not sha1 and not no_hash_check) and file_type == "file":
|
||||
raise RuntimeManifestDataException(
|
||||
@@ -221,16 +222,25 @@ def _check_runtime_file(relative_path, source_path: str | None, file_type: str,
|
||||
suffix
|
||||
)
|
||||
)
|
||||
else:
|
||||
result.target_path = target_file
|
||||
result.skip = True
|
||||
|
||||
result.target_path = target_file
|
||||
elif file_type == "directory":
|
||||
target_file = Path(full_path)
|
||||
|
||||
if not target_file.exists() or not target_file.is_dir():
|
||||
result.target_path = target_file
|
||||
result.target_path = target_file
|
||||
if target_file.exists() and target_file.is_dir():
|
||||
result.skip = True
|
||||
elif file_type == "link":
|
||||
if not Path(full_path).is_symlink() or os.readlink(full_path) != source_path:
|
||||
result.target_path = Path(full_path)
|
||||
result.is_symlink = True
|
||||
result.target_path = Path(full_path)
|
||||
|
||||
if not isinstance(source_path, Path):
|
||||
raise RuntimeManifestDataException(
|
||||
"Invalid source path: {}".format(source_path)
|
||||
)
|
||||
|
||||
if Path(full_path).is_symlink() and os.readlink(full_path) == source_path.as_posix():
|
||||
result.skip = True
|
||||
else:
|
||||
raise RuntimeManifestDataException(
|
||||
"Unsupported file type: {}".format(file_type)
|
||||
@@ -281,9 +291,10 @@ def collect_runtime_files(manifest: dict, runtime_dir: Path, max_workers=RUNTIME
|
||||
for future in as_completed(futures):
|
||||
result: RuntimeCheckResult = future.result()
|
||||
target_path = result.target_path
|
||||
skip = result.skip
|
||||
|
||||
if not target_path:
|
||||
logger.debug("No target path found, skip process: {}".format(target_path))
|
||||
if skip:
|
||||
logger.debug("Skip file: {}".format(target_path))
|
||||
continue
|
||||
|
||||
if not isinstance(target_path, (FileObject, Path)):
|
||||
@@ -295,23 +306,15 @@ def collect_runtime_files(manifest: dict, runtime_dir: Path, max_workers=RUNTIME
|
||||
target_list.append(target_path)
|
||||
elif isinstance(target_path, Path):
|
||||
if result.is_symlink:
|
||||
result_symlinks.append({""})
|
||||
if not isinstance(result.source_path, (str, Path)):
|
||||
raise RuntimeManifestDataException(
|
||||
"Invalid source path: {}".format(result.source_path)
|
||||
)
|
||||
|
||||
result_symlinks.append({"destination": target_path, "source": result.source_path})
|
||||
else:
|
||||
result_dirs.append(target_path)
|
||||
|
||||
if result.target_path and isinstance(result.target_path, FileObject) and not result.is_executable:
|
||||
result_files.append(result.target_path)
|
||||
elif result.target_path and isinstance(result.target_path, FileObject) and result.is_executable:
|
||||
result_executables.append(result.target_path)
|
||||
elif result.target_path and isinstance(result.target_path, Path):
|
||||
if result.is_symlink:
|
||||
if not result.source_path:
|
||||
raise RuntimeManifestDataException("Runtime data missing symlink source path.")
|
||||
|
||||
result_symlinks.append({"destination": result.target_path, "source": result.source_path})
|
||||
else:
|
||||
result_dirs.append(result.target_path)
|
||||
|
||||
if not use_raw:
|
||||
logger.warning(
|
||||
"The \"raw\" flag is not enabled, but the launcher does not support compressed files yet. "
|
||||
@@ -350,17 +353,41 @@ def post_process_runtime_dir(dirs: list[Path], executables: list[Path | FileObje
|
||||
future.result()
|
||||
|
||||
for value in symlinks:
|
||||
dest_path = value.get("destination")
|
||||
source_path = value.get("source")
|
||||
dest_path_raw: str | Path | None = value.get("destination")
|
||||
source_path_raw: str | Path | None = value.get("source")
|
||||
|
||||
if source_path_raw is None:
|
||||
raise LauncherException("Invalid source path: {}".format(source_path_raw))
|
||||
|
||||
if dest_path_raw is None:
|
||||
raise LauncherException("Invalid destination path: {}".format(dest_path_raw))
|
||||
|
||||
source_path = source_path_raw if isinstance(source_path_raw, Path) else Path(source_path_raw)
|
||||
dest_path = dest_path_raw if isinstance(dest_path_raw, Path) else Path(dest_path_raw)
|
||||
|
||||
# ignore existing
|
||||
if Path(source_path).is_symlink() and os.readlink(source_path) == dest_path:
|
||||
return
|
||||
if Path(dest_path).is_symlink() and os.readlink(dest_path) == str(source_path):
|
||||
continue
|
||||
|
||||
try:
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if dest_path.is_symlink():
|
||||
if os.readlink(dest_path) == str(source_path):
|
||||
continue
|
||||
dest_path.unlink()
|
||||
elif dest_path.is_dir():
|
||||
dest_path.rmdir()
|
||||
elif dest_path.exists():
|
||||
raise LauncherException(
|
||||
f"Cannot create symlink: destination is an existing file: {dest_path}"
|
||||
)
|
||||
|
||||
os.symlink(source_path, dest_path)
|
||||
except Exception as exc:
|
||||
raise LauncherException(f"Failed to symlink {source_path} to {dest_path}: {exc}")
|
||||
raise LauncherException(
|
||||
f"Failed to create symlink {dest_path} -> {source_path}: {exc}"
|
||||
) from exc
|
||||
|
||||
def download_java_runtimes(component: str, runtime_dir: Path, no_hash_check: bool = False,
|
||||
progress_callback: Callable[[str, float], None] = None,
|
||||
@@ -405,6 +432,15 @@ def download_java_runtimes(component: str, runtime_dir: Path, no_hash_check: boo
|
||||
"Unable to download some runtime files.\n"
|
||||
)
|
||||
|
||||
post_process_runtime_dir(dirs, executables, symlinks, max_workers=max_check_workers)
|
||||
all_executables = [
|
||||
runtime_dir / relative_path
|
||||
for relative_path, data in manifest.get("files", {}).items()
|
||||
if data.get("type") == "file" and data.get("executable", False)
|
||||
]
|
||||
|
||||
return
|
||||
post_process_runtime_dir(
|
||||
dirs,
|
||||
all_executables,
|
||||
symlinks,
|
||||
max_workers=max_check_workers,
|
||||
)
|
||||
Reference in new issue
Block a user