diff --git a/docs/USAGE.md b/docs/USAGE.md index 4bfe8aa4..a525d7c2 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -61,3 +61,7 @@ python tuxbox.py run --offline /path/to/game ``` Run `python tuxbox.py inspect /path/to/game` to see the executable TuxBox will launch and what it found in the package’s `.bin` files. For Frosty, its shipping symbols can also turn addresses from the log into function names. [Symbol lookup example](MATRIX_AWAKENS.md#what-carries-over-to-projectscarlett) + +### Headless verification on Linux + +When the Wine or Proton backend has neither DISPLAY nor WAYLAND_DISPLAY, set `TUXBOX_VERIFY_HEADLESS=1` explicitly to allow `verify` to start a temporary, authenticated Xvfb display (install Xvfb using your distribution). It selects an explicit number in :100–:199, skipping existing lock files, sockets, Hyprland-style socket aliases and abstract Unix sockets; it fails rather than falling back to automatic display selection. Existing graphical sessions are unchanged. Only use this option on a headless test host or where you accept starting an additional server. GPU receipts still identify the actual adapter. The live-server unit test is separately opt-in via `TUXBOX_TEST_HEADLESS_XVFB=1`; ordinary unit tests do not start Xvfb. diff --git a/project_tuxbox/verify.py b/project_tuxbox/verify.py index fc813c59..fb1e7374 100644 --- a/project_tuxbox/verify.py +++ b/project_tuxbox/verify.py @@ -189,12 +189,22 @@ def xauthority_entry(cookie): return struct.pack(">H", 0xFFFF) + b"".join(struct.pack(">H", len(f)) + f for f in fields) -def _free_display_number(start=2, attempts=16): - """Pick a display number free of lock files and sockets, or None.""" +def _free_display_number(start=2, attempts=16, *, directory=Path("/tmp"), unix_table=Path("/proc/net/unix")): + """Pick a display without a lock, pathname (including Hyprland's alias) or abstract socket.""" + try: + # Abstract Unix-domain sockets may survive without a filesystem entry. + names = {fields[-1] for line in unix_table.read_text().splitlines()[1:] + if len(fields := line.split(maxsplit=7)) == 8} + except OSError: + return None # Cannot prove availability; fail closed. for candidate in range(start, start + attempts): - if Path(f"/tmp/.X{candidate}-lock").exists(): + path = directory / ".X11-unix" / f"X{candidate}" + alias = path.with_name(path.name + "_") + lock = directory / f".X{candidate}-lock" + if any(os.path.lexists(p) for p in (path, alias, lock)): continue - if Path(f"/tmp/.X11-unix/X{candidate}").exists(): + if any(name in names for p in (path, alias) + for name in (str(p), "@" + str(p))): continue return candidate return None @@ -436,7 +446,68 @@ def expect_reflected(output): host.env[name] = value +@contextmanager +def headless_display(host): + """Give Linux guest checks an authenticated X server when no session was inherited.""" + if (sys.platform != "linux" or host.backend not in ("wine", "proton") + or host.env.get("DISPLAY") or host.env.get("WAYLAND_DISPLAY")): + yield + return + if host.env.get("TUXBOX_VERIFY_HEADLESS") != "1": + raise ValueError("No graphical session; supply DISPLAY or opt in with TUXBOX_VERIFY_HEADLESS=1") + xvfb = shutil.which("Xvfb") + if not xvfb: + raise ValueError("Headless guest checks need Xvfb or an accessible graphical session") + # Never let -displayfd choose a number. Some rootless compositors own + # X_ and/or an abstract socket even when X appears absent. + display = _free_display_number(start=100, attempts=100) + if display is None: + raise ValueError("No verifiably free private Xvfb display in :100-:199") + with tempfile.TemporaryDirectory(prefix="tuxbox-xvfb-") as directory: + auth = Path(directory) / "Xauthority" + descriptor = os.open(auth, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "wb") as stream: + stream.write(xauthority_entry(os.urandom(16))) + read, write = os.pipe() + try: + server = subprocess.Popen([xvfb, f":{display}", "-displayfd", str(write), "-screen", "0", + "2560x1440x24", "-nolisten", "tcp", "-auth", str(auth)], + pass_fds=(write,), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except OSError: + os.close(read) + raise + finally: + os.close(write) + saved = {key: host.env.get(key) for key in ("DISPLAY", "XAUTHORITY")} + try: + number = os.read(read, 32) if select.select([read], [], [], 10)[0] else b"" + if number.strip() != str(display).encode("ascii") or server.poll() is not None: + raise ValueError("Private Xvfb did not acquire the requested display") + host.env.update(DISPLAY=f":{int(number)}", XAUTHORITY=str(auth)) + print(f"verify: private headless Xvfb display {host.env['DISPLAY']}", flush=True) + yield + finally: + for key, value in saved.items(): + if value is None: + host.env.pop(key, None) + else: + host.env[key] = value + os.close(read) + server.terminate() + try: + server.wait(timeout=5) + except subprocess.TimeoutExpired: + server.kill() + server.wait() + + def verify(host, output, adapter, selected=None, samples=1): + with headless_display(host): + return _verify(host, output, adapter, selected, samples) + + +def _verify(host, output, adapter, selected=None, samples=1): if adapter and not re.fullmatch(r"[0-9a-fA-F]{4}:[0-9a-fA-F]{4}", adapter): raise ValueError("Adapter must be a PCI vendor:device pair in hexadecimal") if not selected: @@ -699,7 +770,8 @@ def exports_receipt(_imports): if "present" in selected: # The desktop's rootless XWayland can't be sampled; present into a private rootful # Xwayland instead, and fail fast with the cause if that isn't possible either. - capture = screen_capture_problem() + capture = screen_capture_problem(display=host.env.get("DISPLAY", ""), + xauthority=host.env.get("XAUTHORITY")) server = private_x_server(work, adapter=adapter) if capture else nullcontext() saved = {key: host.env.get(key) for key in ("DISPLAY", "XAUTHORITY", "MESA_VK_WSI_DEBUG")} with server as private: diff --git a/tests/test_verify.py b/tests/test_verify.py index c9957d68..d47ad973 100644 --- a/tests/test_verify.py +++ b/tests/test_verify.py @@ -1,5 +1,9 @@ from contextlib import contextmanager import unittest +import os +import shutil +import sys +from types import SimpleNamespace from unittest import mock from pathlib import Path @@ -7,7 +11,7 @@ import tempfile from project_tuxbox.verify import ( - lanes_imports, missing_provider_imports, private_x_server, screen_capture_problem, xauthority_entry) + _free_display_number, headless_display, lanes_imports, missing_provider_imports, private_x_server, screen_capture_problem, xauthority_entry) class PrivateXServerTests(unittest.TestCase): @@ -77,6 +81,109 @@ def xwayland(_path, display, _auth, _geometry, _timeout, options=()): probe.assert_not_called() self.assertEqual(started, [()]) +class HeadlessDisplayTests(unittest.TestCase): + def test_existing_session_and_native_backend_are_unchanged(self): + for backend, env in (("proton", {"DISPLAY": ":0"}), + ("wine", {"WAYLAND_DISPLAY": "wayland-0"}), + ("native", {})): + with self.subTest(backend=backend, env=env), \ + mock.patch("project_tuxbox.verify.sys.platform", "linux"), \ + mock.patch("project_tuxbox.verify.subprocess.Popen") as launch: + host = SimpleNamespace(backend=backend, env=dict(env)) + with headless_display(host): + self.assertEqual(host.env, env) + launch.assert_not_called() + + def test_headless_start_requires_explicit_permission(self): + host = SimpleNamespace(backend="proton", env={}) + with mock.patch("project_tuxbox.verify.sys.platform", "linux"), \ + mock.patch("project_tuxbox.verify.subprocess.Popen") as launch: + with self.assertRaisesRegex(ValueError, "opt in"): + with headless_display(host): + self.fail("must not start server") + launch.assert_not_called() + + def test_occupied_display_aliases_locks_and_abstract_sockets(self): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + sockets = directory / ".X11-unix" + sockets.mkdir() + (sockets / "X100").touch() + (sockets / "X101_").touch() + (directory / ".X102-lock").touch() + (sockets / "X103").symlink_to(sockets / "missing") + table = directory / "unix" + table.write_text("Num RefCount Protocol Flags Type St Inode Path\n" + f"000: 00000002 00000000 00010000 0001 01 1 @{sockets / 'X104'}\n" + f"000: 00000002 00000000 00010000 0001 01 2 {sockets / 'X105_'}\n") + self.assertEqual(_free_display_number(100, 8, directory=directory, unix_table=table), 106) + self.assertIsNone(_free_display_number(100, 6, directory=directory, unix_table=table)) + self.assertIsNone(_free_display_number(100, 8, directory=directory, unix_table=directory / "absent")) + + def test_no_verified_free_display_does_not_launch(self): + host = SimpleNamespace(backend="proton", env={"TUXBOX_VERIFY_HEADLESS": "1"}) + with mock.patch("project_tuxbox.verify.sys.platform", "linux"), \ + mock.patch("project_tuxbox.verify.shutil.which", return_value="/usr/bin/Xvfb"), \ + mock.patch("project_tuxbox.verify._free_display_number", return_value=None), \ + mock.patch("project_tuxbox.verify.subprocess.Popen") as launch: + with self.assertRaisesRegex(ValueError, "No verifiably free"): + with headless_display(host): + self.fail("must not start server") + launch.assert_not_called() + + def test_explicit_number_must_match_server_receipt(self): + host = SimpleNamespace(backend="proton", env={"TUXBOX_VERIFY_HEADLESS": "1"}) + with mock.patch("project_tuxbox.verify.sys.platform", "linux"), \ + mock.patch("project_tuxbox.verify.shutil.which", return_value="/usr/bin/Xvfb"), \ + mock.patch("project_tuxbox.verify._free_display_number", return_value=123), \ + mock.patch("project_tuxbox.verify.subprocess.Popen") as launch, \ + mock.patch("project_tuxbox.verify.select.select", return_value=([1], [], [])), \ + mock.patch("project_tuxbox.verify.os.read", return_value=b"0\n"): + with self.assertRaisesRegex(ValueError, "did not acquire"): + with headless_display(host): + self.fail("must not start guest") + self.assertEqual(launch.call_args.args[0][:2], ["/usr/bin/Xvfb", ":123"]) + launch.return_value.terminate.assert_called_once() + self.assertNotIn("DISPLAY", host.env) + + def test_missing_xvfb_reports_the_actual_requirement(self): + host = SimpleNamespace(backend="proton", env={"TUXBOX_VERIFY_HEADLESS": "1"}) + with mock.patch("project_tuxbox.verify.sys.platform", "linux"), \ + mock.patch("project_tuxbox.verify.shutil.which", return_value=None): + with self.assertRaisesRegex(ValueError, "Headless guest checks need Xvfb"): + with headless_display(host): + self.fail("must not start guest checks") + + @unittest.skipUnless(sys.platform == "linux" and shutil.which("Xvfb") + and os.environ.get("TUXBOX_TEST_HEADLESS_XVFB") == "1", + "requires explicit TUXBOX_TEST_HEADLESS_XVFB=1 and Xvfb") + def test_private_cookie_and_environment_cleanup_even_on_error(self): + host = SimpleNamespace(backend="proton", env={"XAUTHORITY": "/old", "TUXBOX_VERIFY_HEADLESS": "1"}) + def sockets(): + paths = [*Path("/tmp/.X11-unix").glob("X*"), *Path("/tmp").glob(".X*-lock")] + return {p: (p.lstat().st_dev, p.lstat().st_ino, p.lstat().st_mode) for p in paths} + existing = sockets() + before = os.environ.copy() + with self.assertRaisesRegex(RuntimeError, "guest failed"): + with headless_display(host): + display = host.env["DISPLAY"] + cookie = Path(host.env["XAUTHORITY"]) + self.assertRegex(display, r"^:1[0-9]{2}$") + self.assertEqual(existing, {p: sockets().get(p) for p in existing}) + self.assertEqual(cookie.stat().st_mode & 0o777, 0o600) + self.assertIsNone(screen_capture_problem(display=display, xauthority=str(cookie))) + if shutil.which("xdpyinfo"): + env = dict(os.environ, DISPLAY=display, XAUTHORITY=str(cookie)) + import subprocess + probe = subprocess.run(["xdpyinfo"], env=env, capture_output=True, timeout=5) + self.assertEqual(probe.returncode, 0, probe.stderr.decode(errors="replace")) + raise RuntimeError("guest failed") + self.assertFalse(cookie.exists()) + self.assertEqual(host.env, {"XAUTHORITY": "/old", "TUXBOX_VERIFY_HEADLESS": "1"}) + self.assertEqual(existing, {p: sockets().get(p) for p in existing}) + self.assertEqual(os.environ, before) + + class ScreenCaptureTests(unittest.TestCase): def test_only_an_x_display_on_linux_is_probed(self): with mock.patch("project_tuxbox.verify.ctypes.CDLL") as load: