Files
libretro/installer/paths.py
T
Abdessamad Derraz e9f6fe43a0 refactor: split the installer into a package
install.py held 31,575 lines and 1,370 definitions in one module. Its
source is now installer/, 45 modules by concern, each importing from the
others what it uses, so ruff and mypy read every module on its own.

scripts/build_installer.py joins them back into install.py in import
order, with one block of standard library imports and the zlib and
unicodedata guard. It refuses an import from outside the standard
library, a name two modules define, an import cycle, a renamed import
and an import-time read of a name from a later module. install.py stays
one stdlib-only file for the bootstraps, the launchers and PyPI.

The split was written by a script, statement by statement: every
top-level statement of the old file is in the new one with the same AST.
Two tests that located code by its neighbour now read it by name.
2026-11-18 01:37:28 +01:00

333 lines
13 KiB
Python

"""Where each entry of a file list lands, kept under its BIOS folder."""
from __future__ import annotations
import http.client
import json
import os
import re
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import NamedTuple
from installer.text import _CONTROLS
def _read_limited_json(
response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False
) -> object:
"""Read a bounded UTF-8 JSON response, its bytes as they came with raw.
A body shorter than its Content-Length is a dropped connection, raised
as one so the caller retries: parsed, the cut read as an invalid file
list and the run ended without the network advice.
"""
raw_length = response.headers.get("Content-Length") if response.headers else None
expected: int | None = None
if raw_length:
try:
expected = int(raw_length)
except ValueError:
expected = None
if expected is not None and expected > limit:
raise ValueError(f"{label} exceeds {limit} bytes")
try:
payload = response.read(limit + 1)
except http.client.IncompleteRead as exc:
raise ConnectionError(
f"{label} cut after {len(exc.partial)} bytes"
) from exc
if len(payload) > limit:
raise ValueError(f"{label} exceeds {limit} bytes")
if expected is not None and len(payload) < expected:
raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes")
if raw:
return payload
try:
return json.loads(payload.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValueError(f"invalid {label}: {exc}") from exc
def _path_characters(value: object, field: str, colons: bool = True) -> str:
"""The character rules every manifest-controlled relative path meets.
No backslash, control character, empty segment, trailing slash or drive
prefix, and at most 1024 characters: on Windows a backslash or a C:
segment leaves the folder the path is joined to. A segment that Windows
reads as a drive (C:x, any segment of one letter and a colon in front)
or that ends with a colon is refused wherever it stands, since a later
segment is joined as a drive-relative path. ``colons`` keeps a colon
inside a name: RetroDECK's ares reads bios/snes:st018.data.rom on Linux.
A Windows host refuses it all the same, as an alternate data stream of
the file before the colon.
"""
if not isinstance(value, str) or not value or len(value) > 1024:
raise ValueError(f"invalid {field}")
if (
"\\" in value
or _CONTROLS.search(value)
or "//" in value
or value.endswith("/")
or re.match(r"^[A-Za-z]:", value)
):
# A control character is refused with NUL: a pack's member named
# x<ESC>]0;PWN<BEL>.bin set the window title in the progress line,
# and the file was written under that name.
raise ValueError(f"unsafe {field}: {value!r}")
for part in value.split("/"):
if ":" not in part:
continue
if (
PureWindowsPath(part).drive or part.endswith(":")
or not colons or os.name == "nt"
):
raise ValueError(f"unsafe {field}: {value!r}")
return value
def _safe_relative_path(value: object, field: str, colons: bool = True) -> PurePosixPath:
"""Validate a manifest-controlled relative POSIX path."""
path = PurePosixPath(_path_characters(value, field, colons))
if path.is_absolute() or any(part in ("", ".", "..") for part in path.parts):
raise ValueError(f"unsafe {field}: {value!r}")
return path
# The most folders a roms root climbs from the BIOS folder: two, as the rom
# folders files of MinUI, NextUI, MyMinUI (../../Roms) and muOS (../../ROMS)
# record it (platforms/romfolders/*.yml, roms_root.from_bios).
MAX_ROMS_UPS = 2
def _roms_relation(value: object, field: str) -> tuple[int, PurePosixPath]:
"""A roms root relative to the BIOS folder: (folders up, names down).
"." is the BIOS folder itself. Any other value climbs one to
MAX_ROMS_UPS folders, then names plain folders: nothing climbs again
once it went down, and nothing goes down without climbing first.
"""
if value == ".":
return 0, PurePosixPath()
path = PurePosixPath(_path_characters(value, field, colons=False))
parts = path.parts
ups = next((i for i, part in enumerate(parts) if part != ".."), len(parts))
names = parts[ups:]
if (
path.is_absolute() or not 1 <= ups <= MAX_ROMS_UPS
or any(part in ("", ".", "..") for part in names)
):
raise ValueError(f"unsafe {field}: {value!r}")
return ups, PurePosixPath(*names)
# The roots a list places files below by their place relative to the BIOS
# folder: the roms root (ROCKNIX's /storage/roms) and the frontend's
# configs folder (Batocera's /userdata/system/configs).
RELATIVE_ROOTS = ("roms", "configs")
def _relative_root(bios_path: Path, from_bios: str, root: str = "roms") -> Path | None:
"""A relative root of a BIOS folder, on the host's own path type.
The BIOS folder's ancestor at the depth the relation climbs, then the
named folders below it. None when the joined and normalized path is
anything else.
"""
ups, names = _roms_relation(from_bios, f"{root}_directory.from_bios")
if ups > len(bios_path.parents):
return None
ancestor = bios_path if not ups else bios_path.parents[ups - 1]
expected = ancestor.joinpath(*names.parts)
joined = Path(os.path.normpath(bios_path.joinpath(*PurePosixPath(from_bios).parts)))
if joined != Path(os.path.normpath(expected)) or not _lexically_under(joined, ancestor):
return None
return expected
def _lexically_under(candidate: Path, root: Path) -> bool:
"""Whether a path built from checked parts stays below *root*."""
try:
Path(os.path.normpath(candidate)).relative_to(Path(os.path.normpath(root)))
except ValueError:
return False
return True
def _within(candidate: Path, root: Path) -> bool:
"""Whether *candidate* stays under *root* once both are resolved."""
try:
(root / candidate.name).resolve().relative_to(root)
except (OSError, ValueError):
return False
return True
def _safe_target_dir(value: object, field: str) -> str:
"""Validate a manifest-controlled standalone-copy directory.
These name emulator install directories, so unlike a BIOS destination they
are legitimately absolute and outside the BIOS tree. What they must never
do is climb: a '..' anywhere turns "copy next to the emulator" into "write
wherever the manifest likes".
"""
if not isinstance(value, str) or not value or len(value) > 2048:
raise ValueError(f"invalid {field}")
if _CONTROLS.search(value):
raise ValueError(f"unsafe {field}: {value!r}")
parts = re.split(r"[\\/]", value)
if any(part == ".." for part in parts):
raise ValueError(f"unsafe {field}: {value!r}")
return value
# A platform whose folders move one by one: root -> {folder under the root:
# where it is now}. RetroDECK's per-folder move (RetroDECK 7786a849,
# functions/api_data_processing.sh:913-935) records each new place in
# retrodeck.json paths.<folder>_path (config/retrodeck/retrodeck.json:3-23),
# and its manifest places files under bios/ and roms/ of the home folder.
_MOVED_FOLDERS: dict[Path, dict[str, Path]] = {}
def _record_moved_folders(root: Path, retrodeck_json: Path) -> None:
"""Each RetroDECK folder that is no longer <home>/<name>."""
try:
paths = json.loads(retrodeck_json.read_text(encoding="utf-8", errors="replace"))["paths"]
except (OSError, ValueError, KeyError, TypeError):
return
if not isinstance(paths, dict):
return
moved = {}
for key, value in paths.items():
name = key[:-len("_path")] if key.endswith("_path") else ""
if name and name != "rd_home" and isinstance(value, str) and value.strip():
place = Path(value.strip())
if place != root / name:
moved[name] = place
if moved:
_MOVED_FOLDERS[root] = moved
# Resolved folder -> the same folder as the run names it: /sdcard is a link
# to /storage/emulated/0 on Android, and one result named the BIOS folder
# /sdcard/RetroArch/system and its backup in /storage/emulated/0/RetroArch.
_SPELLED: dict[Path, Path] = {}
def _note_spelling(root: Path) -> Path:
"""root resolved, its own spelling recorded for every path shown below
the link it goes through (spelled)."""
given, resolved = Path(os.path.abspath(root)), root.resolve()
named, real = given, resolved
while named.name == real.name and named != named.parent and real != real.parent:
named, real = named.parent, real.parent
if named != real:
try:
if Path(os.path.realpath(named)) == real:
_SPELLED[real] = named
except (OSError, ValueError):
pass
return resolved
def spelled(path: Path | str) -> Path:
"""path in the form the run names its folders: below a link the BIOS
folder was named through, the link's name (_note_spelling)."""
path = Path(path)
for real in sorted(_SPELLED, key=lambda each: len(each.parts), reverse=True):
if path == real or real in path.parents:
return _SPELLED[real] / path.relative_to(real)
return path
def _destination_path(root: Path, value: object) -> Path:
"""Place a manifest destination below *root*.
The manifest cannot climb: _safe_relative_path refuses absolute paths,
drive letters and '..'. Symbolic links met under the root are the
user's own layout and are followed. EmuDeck links bios/shadps4/sys_modules
into shadPS4's data directory, and the file has to land where the
emulator reads it.
"""
relative = _safe_relative_path(value, "dest")
moved = _MOVED_FOLDERS.get(root, {})
if len(relative.parts) > 1 and relative.parts[0] in moved:
return moved[relative.parts[0]].resolve() / Path(*relative.parts[1:])
return _note_spelling(root) / Path(*relative.parts)
class SavePlace(NamedTuple):
"""The save directory a frontend's config names, whether it hands each
core a folder of its own below it (RetroArch's sort_savefiles_enable,
runloop.c runloop_path_set_redirect), and whether the file list's dests
hold that folder (its save_directory.by_core)."""
directory: Path
by_core: bool
listed_by_core: bool = True
# BIOS folder -> where the files read below its frontend's save directory go,
# set once the save directory is known (save_directory_for).
_SAVE_DIRS: dict[Path, SavePlace] = {}
# (BIOS folder, root) -> the platform's roms or configs folder, set by
# place_relative_entries.
_RELATIVE_DIRS: dict[tuple[Path, str], Path] = {}
# (BIOS folder, emulator key) -> the emulator folder, set by
# place_emulator_entries.
_EMULATOR_DIRS: dict[tuple[Path, str], Path] = {}
def _entry_place(root: Path, entry: dict) -> tuple[Path, object]:
"""The folder an entry's dest is relative to, and the dest.
An entry with root: save is relative to the save directory the frontend
hands the core, below the BIOS folder's frontend save directory and the
core's own folder where the frontend sorts saves by core. Any other is
relative to the BIOS folder.
"""
if entry.get("root") in RELATIVE_ROOTS:
folder = _RELATIVE_DIRS.get((root, entry["root"]))
if folder is None:
raise ValueError(f"no {entry['root']} folder known for {entry.get('dest')}")
return folder, entry.get("dest")
if entry.get("root") == "emulators":
key, _, rest = str(entry.get("dest")).partition("/")
folder = _EMULATOR_DIRS.get((root, key))
if folder is None:
raise ValueError(f"no emulator folder known for {entry.get('dest')}")
return folder, rest
if entry.get("root") != "save":
return root, entry.get("dest")
place = _SAVE_DIRS.get(root)
if place is None:
raise ValueError(f"no save directory known for {entry.get('dest')}")
dest = entry.get("dest")
folder = entry.get("core_folder")
# No core_folder: the core reads the same place whether the frontend
# sorts saves by core or not (an empty library_name, or Cemu adding its
# own folder only where the directory is not named after it).
if folder and isinstance(dest, str) and place.by_core != place.listed_by_core:
if place.listed_by_core:
dest = dest.split("/", 1)[1] if "/" in dest else dest
else:
dest = f"{folder}/{dest}"
return place.directory, dest
def _entry_path(root: Path, entry: dict) -> Path:
"""Where an entry is written, as _entry_place places it."""
return _destination_path(*_entry_place(root, entry))
def _entry_key(entry: dict) -> str:
"""What tells one entry of the list from another: its dest, below the
BIOS folder, below the save directory or in an emulator's own folder.
KNULLI lists its own fbneo/hiscore.dat in the BIOS tree and FB Alpha
2012's below the save directory, two files under one dest. NUL never
appears in a dest."""
dest = str(entry.get("dest"))
root = entry.get("root")
if root == "emulator":
# A path in one emulator's own folder: two emulators read two files.
return f"emulator\0{','.join(entry.get('cores') or [])}\0{dest}"
return f"{root}\0{dest}" if root in ("save", "emulators", *RELATIVE_ROOTS) else dest