# SPDX-License-Identifier: LGPL-2.1-or-later """Runs one wine-access helper per active Wine prefix. Wine processes are found through /proc. A helper starts in the same prefix, with the same Wine loader and display, pointed at this extension's D-Bus object, and stops once the prefix has been idle for a while. Failed helpers restart with exponential backoff. """ from __future__ import annotations from dataclasses import dataclass, field import hashlib import os from pathlib import Path import shutil import signal import subprocess import tempfile import time from typing import Callable MANAGED_KEY = "ORCA_WINE_ACCESS_MANAGED" IDLE_GRACE_SECONDS = 10.0 MAX_BACKOFF_SECONDS = 60.0 STABLE_RUN_SECONDS = 10.0 LOG_LIMIT_BYTES = 256 * 1024 HELPER_PROGRAM = "wine-access.exe.so" # The files that must stay beside the helper launcher; see the staging in # HelperManager._helper_for. HELPER_SIBLINGS = ("wine-access-menu.dll", "wine-access-menu32.dll", "wine-access-menu-host32.exe") LOADER_NAMES = {"wine", "wine64"} PRELOADER_NAMES = {"wine-preloader", "wine64-preloader"} # Wine's own background processes outlive applications while anything in the # prefix runs, including the helper; they must not keep a prefix active. # xalia.exe is Proton's gamepad overlay, in the same position: it would # otherwise keep the prefix "active" for as long as the helper it keeps # alive holds the wineserver up, so the helper would never stop. WINE_SERVICES = {"services.exe", "explorer.exe", "winedevice.exe", "plugplay.exe", "svchost.exe", "rpcss.exe", "conhost.exe", "tabtip.exe", "wineboot.exe", "winemenubuilder.exe", "start.exe", "wineserver", "xalia.exe"} # Proton launches games through its builtin steam.exe shim, which lingers # the same way. Only the shim's system32/syswow64 home qualifies: a real # Steam client installed in a prefix runs from its own directory and is # an application like any other. WINE_SERVICE_PATHS = ("windows/system32/steam.exe", "windows/syswow64/steam.exe") FORWARDED_ENVIRONMENT = ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", # A client joining a running server (Proton enables # both) must agree on the sync mode. "WINEESYNC", "WINEFSYNC") def helper_candidates() -> list[str]: """Where the helper may be installed, most specific first.""" user = os.environ.get("USER", "") candidates = [ os.environ.get("WINE_ACCESS_HELPER", ""), os.path.expanduser("~/.local/libexec/wine-access/wine-access.exe"), os.path.expanduser("~/.nix-profile/libexec/wine-access/wine-access.exe"), # NixOS per-user profiles don't link libexec; Home Manager's current # generation does. os.path.expanduser("~/.local/state/home-manager/gcroots/current-home/" "home-path/libexec/wine-access/wine-access.exe"), f"/etc/profiles/per-user/{user}/libexec/wine-access/wine-access.exe" if user else "", "/run/current-system/sw/libexec/wine-access/wine-access.exe", "/usr/local/libexec/wine-access/wine-access.exe", "/usr/libexec/wine-access/wine-access.exe", ] return [path for path in candidates if path] def extra_helper_arguments(environment: dict[str, str] = os.environ) -> list[str]: """Extra helper flags from the reader's environment. WINE_ACCESS_NO_DIALOG_READER=1 runs helpers controller-only: no WinEvent hooks, no native hook DLL in applications, no MSAA polling. That is the mode for games whose anti-tamper code objects to injected hooks; their NVDA/Tolk speech still works, standard controls don't. """ if environment.get("WINE_ACCESS_NO_DIALOG_READER", "") not in ("", "0"): return ["--no-dialog-reader"] return [] def controller_only_arguments(programs: set[str], listed, always: bool = False) -> list[str]: """--no-dialog-reader if controller-only applies to these programs. Matching is by lower-case executable file name, as reported by discover(); entries in the user's list may use any case. Settings layers hand string arrays back as lists or tuples depending on the path taken, so any sequence of strings is accepted. """ names = {name.lower() for name in listed if isinstance(name, str) and name and not any( char in name for char in "\n\r\0/\\") } if isinstance(listed, (list, tuple)) else set() # Every helper must know the exclusions before a game exists in /proc. # The native hosts check these names before injecting either hook. arguments = [] for name in sorted(names): arguments.extend(("--exclude-hook-program", name)) if always or programs & names: arguments.append("--no-dialog-reader") return arguments def find_helper() -> str | None: for path in helper_candidates(): if os.access(path, os.X_OK): return path return shutil.which("wine-access.exe") def read_environment(pid: int, proc: Path = Path("/proc")) -> dict[str, str]: try: raw = (proc / str(pid) / "environ").read_bytes() except OSError: return {} result = {} for entry in raw.split(b"\0"): key, sep, value = entry.partition(b"=") if sep: result[key.decode(errors="replace")] = value.decode(errors="replace") return result def program_path(pid: int, proc: Path = Path("/proc")) -> str: """Lower-case argv0 of a process, with Windows separators normalized.""" try: argv0 = (proc / str(pid) / "cmdline").read_bytes().split(b"\0", 1)[0] except OSError: return "" return argv0.decode(errors="replace").replace("\\", "/").lower() def program_name(pid: int, proc: Path = Path("/proc")) -> str: """Lower-case file name of the program a process runs, Windows or Linux.""" return program_path(pid, proc).rsplit("/", 1)[-1] def is_wine_service(pid: int, proc: Path = Path("/proc")) -> bool: """Whether a process is Wine/Proton infrastructure, not an application.""" path = program_path(pid, proc) return (path.rsplit("/", 1)[-1] in WINE_SERVICES or path.endswith(WINE_SERVICE_PATHS)) def prefix_for(environment: dict[str, str]) -> str: """The process's Wine prefix; Wine itself defaults to ~/.wine.""" prefix = environment.get("WINEPREFIX") if not prefix and environment.get("STEAM_COMPAT_DATA_PATH"): prefix = os.path.join(environment["STEAM_COMPAT_DATA_PATH"], "pfx") if not prefix: home = environment.get("HOME") or os.path.expanduser("~") prefix = os.path.join(home, ".wine") return os.path.realpath(os.path.expanduser(prefix)) def _is_protontricks_proxy(path: str) -> bool: """Whether a loader path is Protontricks' Wine proxy script. The proxy dispatches through the Steam Runtime using Protontricks' own session environment (PROTONTRICKS_STEAM_RUNTIME and friends), which the helper does not inherit, and would run the helper inside the container where its host files are not visible. The real Proton loader beside the running preloader is the usable one. """ try: with open(path, "rb") as proxy: return b"PROTONTRICKS_STEAM_RUNTIME" in proxy.read(8192) except OSError: return False def loader_for(pid: int, environment: dict[str, str], proc: Path = Path("/proc")) -> str | None: """The Wine loader that runs this process, or None if it isn't Wine.""" try: executable = os.readlink(proc / str(pid) / "exe") except OSError: return None name = os.path.basename(executable) # Nix wraps programs as .-wrapped beside the real launcher. if name.startswith(".") and name.endswith("-wrapped"): name = name[1:-len("-wrapped")] if name not in LOADER_NAMES | PRELOADER_NAMES: return None configured = environment.get("WINELOADER") if (configured and os.access(configured, os.X_OK) and not _is_protontricks_proxy(configured)): return configured directory = os.path.dirname(executable) for candidate in (name.removesuffix("-preloader"), "wine"): loader = os.path.join(directory, candidate) if os.access(loader, os.X_OK): return loader # Proton keeps preloaders deep under files/lib/wine/-unix with # the loader in files/bin; a system layout resolves the same way # (.../lib/wine/-unix up to the prefix's bin). ancestor = directory for _ in range(5): parent = os.path.dirname(ancestor) if parent == ancestor: break ancestor = parent for candidate in ("wine", "wine64"): loader = os.path.join(ancestor, "bin", candidate) if os.access(loader, os.X_OK): return loader return None def _display(value: str) -> str: """X display without screen number or local host: ':0.0' -> ':0'.""" host, _, rest = value.rpartition(":") if host in ("unix", "localhost"): host = "" return f"{host}:{rest.split('.', 1)[0]}" def _bus(value: str) -> str: """The socket of a D-Bus address, ignoring guid and other keys.""" for part in value.split(";")[0].partition(":")[2].split(","): key, _, setting = part.partition("=") if key in ("path", "abstract"): return setting return value # Steam Play's pressure-vessel puts a filtered proxy of the host session # bus at this fixed path inside the container. It is our bus, proxied — # but the socket path itself exists only inside the container. PRESSURE_VESSEL_BUS = "/run/pressure-vessel/bus" def same_session(environment: dict[str, str], ours: dict[str, str]) -> bool: """Whether a process shares our D-Bus session and display. A helper for another session (another login, or a test's private bus and display) could never reach this reader, so such processes are left alone. """ for key, normal in (("DBUS_SESSION_BUS_ADDRESS", _bus), ("DISPLAY", _display)): theirs, mine = environment.get(key), ours.get(key) if not theirs or not mine or normal(theirs) == normal(mine): continue # A pressure-vessel proxy address cannot be compared with the # host socket it forwards to; the display check still separates # graphical sessions. if key == "DBUS_SESSION_BUS_ADDRESS" and normal(theirs) == PRESSURE_VESSEL_BUS: continue return False return True @dataclass class PrefixState: process: subprocess.Popen | None = None last_seen: float = 0.0 started_at: float = 0.0 failures: int = 0 next_start: float = 0.0 extra_arguments: list[str] = field(default_factory=list) class HelperManager: """Reconciles running helpers with the Wine prefixes in use.""" def __init__( self, reader_arguments: list[str], helper: str | None = None, proc: Path = Path("/proc"), log_directory: Path | None = None, clock: Callable[[], float] = time.monotonic, spawn: Callable[..., subprocess.Popen] = subprocess.Popen, arguments_for: Callable[[set[str]], list[str]] | None = None, ) -> None: self.helper = helper if helper is not None else find_helper() self.reader_arguments = reader_arguments # Extra helper arguments for a prefix's program names, consulted # at each spawn so settings changes need no reader restart. self.arguments_for = arguments_for or (lambda programs: []) self.proc = proc self.log_directory = log_directory or Path( os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state") ) / "orca-wine-access" self.clock = clock self.spawn = spawn self.prefixes: dict[str, PrefixState] = {} # Helpers marked as ours but not started by this instance, e.g. left # running by an Orca that was restarted. self.stale: dict[str, list[int]] = {} def discover(self) -> dict[str, tuple[dict[str, str], str, set[str]]]: """Active prefixes: one process's environment/loader, all program names.""" found: dict[str, tuple[dict[str, str], str, set[str]]] = {} self.stale = {} uid = os.getuid() helpers = {state.process.pid for state in self.prefixes.values() if state.process is not None} try: entries = list(self.proc.iterdir()) except OSError: return found for entry in entries: if not entry.name.isdigit() or int(entry.name) in helpers: continue try: if entry.stat().st_uid != uid: continue except OSError: continue pid = int(entry.name) environment = read_environment(pid, self.proc) if not environment or not same_session(environment, os.environ): continue if environment.get(MANAGED_KEY) == "1": if program_name(pid, self.proc) == HELPER_PROGRAM: self.stale.setdefault(prefix_for(environment), []).append(pid) continue loader = loader_for(pid, environment, self.proc) if loader is None or is_wine_service(pid, self.proc): continue prefix = prefix_for(environment) if prefix in found: found[prefix][2].add(program_name(pid, self.proc)) else: found[prefix] = (environment, loader, {program_name(pid, self.proc)}) return found def poll(self) -> bool: """One reconciliation pass; returns True so it can be a GLib timeout.""" if not self.helper: return True now = self.clock() active = self.discover() for prefix, (environment, loader, programs) in active.items(): state = self.prefixes.setdefault(prefix, PrefixState()) state.last_seen = now self._ensure_running(prefix, state, environment, loader, now, programs) for prefix, state in list(self.prefixes.items()): self._record_exit(state, now) if prefix not in active and now - state.last_seen >= IDLE_GRACE_SECONDS: self._stop(state) del self.prefixes[prefix] return True def _helper_for(self, source: dict[str, str]) -> str: """The helper launcher path this prefix's wineserver can open. A wineserver started inside pressure-vessel resolves unix paths in the container, whose /usr is the Steam Runtime, so a system-installed helper is invisible to it (the spawn fails with "ShellExecuteEx failed: File not found"). The home directory is bound at the same path in both namespaces, so for such prefixes stage a copy of the helper set under the state directory. """ if "PRESSURE_VESSEL_RUNTIME" not in source: return self.helper origin = Path(self.helper) names = [origin.name, origin.name + ".so", *HELPER_SIBLINGS] # Read the complete set before publishing anything. Missing files are # a failed start, never a reason to reuse stale staged siblings. contents = {name: (origin.parent / name).read_bytes() for name in names} digest = hashlib.sha256() for name, data in contents.items(): digest.update(name.encode() + b"\0") digest.update(len(data).to_bytes(8, "big")) digest.update(data) stageRoot = self.log_directory / "helper" stageRoot.mkdir(parents=True, exist_ok=True) stage = stageRoot / digest.hexdigest() if not stage.exists(): with tempfile.TemporaryDirectory(prefix=".stage-", dir=stageRoot) as temporary: pending = Path(temporary) / "complete" pending.mkdir() for name, data in contents.items(): target = pending / name target.write_bytes(data) target.chmod(0o755 if os.access(origin.parent / name, os.X_OK) else 0o644) try: pending.rename(stage) except OSError: # Another supervisor may have published the identical set. if not stage.is_dir(): raise for name, data in contents.items(): if (stage / name).read_bytes() != data: raise OSError("Incomplete or modified staged Wine Access helper") return str(stage / origin.name) def _command(self, source: dict[str, str], programs: set[str]) -> list[str]: return [self._helper_for(source), *self.reader_arguments, *self.arguments_for(programs)] def _ensure_running(self, prefix: str, state: PrefixState, source: dict[str, str], loader: str, now: float, programs: set[str]) -> None: self._record_exit(state, now) if state.process is not None: # A helper can start one pass before the program it serves is # discovered (a loader process shows up first). If that # program turns out to be controller-only, restart the helper # in that mode; never downgrade a running controller-only # helper the same way, or modes would flap with the process # list. if ("--no-dialog-reader" in self.arguments_for(programs) and "--no-dialog-reader" not in state.extra_arguments): self._stop(state) else: return if state.process is not None or now < state.next_start: return stale = self.stale.get(prefix, []) if stale: # Only one helper may own a Wine desktop; retire the leftover one # and start ours on a later pass. for pid in stale: try: os.kill(pid, signal.SIGTERM) except OSError: pass state.next_start = now + 1.0 return environment = os.environ.copy() for key in FORWARDED_ENVIRONMENT: if not source.get(key): continue # The container's bus proxy path is not reachable on the host; # the helper uses our own address for the same bus. if (key == "DBUS_SESSION_BUS_ADDRESS" and _bus(source[key]) == PRESSURE_VESSEL_BUS): continue environment[key] = source[key] environment.update(WINEPREFIX=prefix, WINELOADER=loader, WINEDEBUG="-all") environment[MANAGED_KEY] = "1" log = self._log_file(prefix, programs) try: state.process = self.spawn( self._command(source, programs), env=environment, stdin=subprocess.DEVNULL, stdout=log or subprocess.DEVNULL, stderr=log or subprocess.DEVNULL, start_new_session=True, ) state.started_at = now state.extra_arguments = self.arguments_for(programs) except OSError: self._back_off(state, now) finally: if log is not None: log.close() def _log_file(self, prefix: str, programs: set[str]): try: self.log_directory.mkdir(parents=True, exist_ok=True) name = hashlib.sha256(prefix.encode()).hexdigest()[:12] path = self.log_directory / f"{name}.log" # Keep earlier starts for diagnosis, within a bounded size. mode = "a" if path.exists() and path.stat().st_size < LOG_LIMIT_BYTES else "w" log = open(path, mode, encoding="utf-8") log.write(f"--- {time.strftime('%Y-%m-%d %H:%M:%S')} starting helper for {prefix} " f"programs={sorted(programs)} extra={self.arguments_for(programs)}\n") log.flush() return log except OSError: return None @staticmethod def _back_off(state: PrefixState, now: float) -> None: state.failures += 1 state.next_start = now + min(2 ** state.failures, MAX_BACKOFF_SECONDS) def _record_exit(self, state: PrefixState, now: float) -> None: if state.process is None or state.process.poll() is None: return quick = now - state.started_at < STABLE_RUN_SECONDS state.process = None if quick: self._back_off(state, now) else: state.failures = 0 state.next_start = now @staticmethod def _stop(state: PrefixState) -> None: process, state.process = state.process, None if process is None or process.poll() is not None: return process.terminate() try: process.wait(timeout=2.0) except subprocess.TimeoutExpired: process.kill() process.wait() def shutdown(self) -> None: for state in self.prefixes.values(): self._stop(state) self.prefixes.clear()