#!/usr/bin/env python3 """Stage and run the native editor bundle for the Fedora WSL desktop app.""" import argparse import fcntl import hashlib import json import os from pathlib import Path import re import select import shutil import signal import subprocess import sys import tempfile WEB_COMMIT = "e14b7aa169d4fc7acf4162e24acb262c257a8275" WEB_FILES = ("index.html", "styles.css", "favicon.svg", "app.js") NATIVE_FILES = ("latex.tfx", "format-resources.json") EDITOR = "bin/native_editor" RECEIPT = "desktop-bundle.json" PAYLOAD = ( EDITOR, *NATIVE_FILES, "bundle.json", "native-beta.py", "wsl-launch.py", *(f"web/{name}" for name in WEB_FILES), ) INSTANCE_ENV = "TEXRRA_DESKTOP_INSTANCE" def require(condition, message): if not condition: raise ValueError(message) def digest(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def write_json(path, value): path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8") def is_sha(value): return isinstance(value, str) and re.fullmatch(r"[a-f0-9]{64}", value) is not None def git_blob(repo, commit, path): return subprocess.check_output(["git", "-C", repo, "show", f"{commit}:{path}"]) def package_receipt(directory): data = (directory / RECEIPT).read_bytes() receipt = json.loads(data) files = receipt.get("sha256", {}) require(receipt.get("schema") == 1 and set(files) == set(PAYLOAD), "Invalid desktop bundle receipt") require(all(is_sha(value) for value in files.values()), "Invalid desktop bundle hashes") return data, files def check_file(path, expected): require(path.is_file() and not path.is_symlink() and digest(path) == expected, f"Desktop bundle file is missing or has changed: {path}") def prepare(args, repo): artifact = args.artifact_dir.resolve(strict=True) reference = args.reference_bundle.resolve(strict=True) web = args.web_repo.resolve(strict=True) output = args.output.resolve() require(not output.exists(), f"Desktop bundle output already exists: {output}") require(re.fullmatch(r"[a-f0-9]{40}", args.commit), "A full Git commit is required") require((artifact / "source-commit.txt").read_text().strip() == args.commit, "The binary build receipt belongs to a different Git commit") require((artifact / "editor-build.exit").read_text().strip() == "0", "Native editor build did not finish successfully") with (artifact / "editor-build.jsonl").open() as stream: rows = [json.loads(line) for line in stream] required = {"native_editor", "texrra_tex_core"} optimized = { row["target"]["name"] for row in rows if row["reason"] == "compiler-artifact" and row["profile"]["opt_level"] == "3" and not row["profile"]["debug_assertions"] and not row["profile"]["test"] } require(required <= optimized, "Missing opt-level 3 engine and editor build receipts") editor = artifact / "binary/native_editor" editor_sha = (artifact / "binary.sha256").read_text().split()[0] require(is_sha(editor_sha), "Invalid native editor digest in the build receipt") with editor.open("rb") as stream: elf = stream.read(20) require(elf.startswith(b"\x7fELF\x02\x01\x01") and elf[18:20] == b"\x3e\x00", "Desktop backend must be an x86-64 Linux ELF") manifest = json.loads((reference / "bundle.json").read_text(encoding="utf-8")) native_sha = {name: manifest["sha256"][name] for name in NATIVE_FILES} normal_launcher = git_blob(repo, args.commit, "scripts/native-beta.py") require(normal_launcher == (reference / "native-beta.py").read_bytes(), "The frozen bundle and the release disagree on the native Beta launcher") output.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix=".desktop-backend-", dir=output.parent) as temporary: bundle = Path(temporary) / "backend" (bundle / "bin").mkdir(parents=True) (bundle / "web").mkdir() shutil.copyfile(editor, bundle / EDITOR) check_file(bundle / EDITOR, editor_sha) (bundle / EDITOR).chmod(0o700) for name, value in native_sha.items(): shutil.copyfile(reference / name, bundle / name) check_file(bundle / name, value) shutil.copyfile(__file__, bundle / "wsl-launch.py") (bundle / "native-beta.py").write_bytes(normal_launcher) for name in WEB_FILES: (bundle / "web" / name).write_bytes(git_blob(web, WEB_COMMIT, name)) manifest["sha256"] = {EDITOR: editor_sha, **native_sha} write_json(bundle / "bundle.json", manifest) hashes = {EDITOR: editor_sha, **native_sha} hashes.update({name: digest(bundle / name) for name in PAYLOAD if name not in hashes}) write_json(bundle / RECEIPT, { "schema": 1, "native_commit": args.commit, "web_commit": WEB_COMMIT, "sha256": hashes, }) require(not output.exists(), f"Desktop bundle output already exists: {output}") bundle.rename(output) print(f"Desktop backend staged at {output}") def private_home(): data = Path(os.environ.get("XDG_DATA_HOME", "")) if not data.is_absolute(): data = Path.home() / ".local/share" return data / "texrra-desktop" def install(package, home): receipt, files = package_receipt(package) runtime = home / "runtime" runtime.mkdir(mode=0o700, exist_ok=True) destination = runtime / hashlib.sha256(receipt).hexdigest() if destination.exists(): require((destination / RECEIPT).read_bytes() == receipt, "Installed desktop receipt differs") for name, expected in files.items(): check_file(destination / name, expected) return destination with tempfile.TemporaryDirectory(prefix=".install-", dir=runtime) as temporary: bundle = Path(temporary) / "backend" bundle.mkdir(mode=0o700) for name, expected in files.items(): path = bundle / name path.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(package / name, path) check_file(path, expected) (bundle / EDITOR).chmod(0o700) (bundle / RECEIPT).write_bytes(receipt) (bundle / "state").symlink_to(home / "state", target_is_directory=True) bundle.rename(destination) return destination def launch_error(message): detail = " ".join(str(message).splitlines()) print(f"Texrra desktop error {detail}", flush=True) def launch(args): def interrupt(_signum, _frame): raise KeyboardInterrupt def lease_ended(timeout): return select.select([sys.stdin], [], [], timeout)[0] and not os.read(sys.stdin.fileno(), 4096) signal.signal(signal.SIGTERM, interrupt) os.umask(0o077) home = private_home() home.mkdir(mode=0o700, parents=True, exist_ok=True) with (home / "backend.lock").open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as error: raise ValueError("The Texrra desktop backend is already running for this WSL data directory") from error for name in ("projects", "state"): (home / name).mkdir(mode=0o700, exist_ok=True) bundle = install(Path(__file__).resolve().parent, home) if lease_ended(0): return 0 command = [ sys.executable, bundle / "native-beta.py", "web", "--web-dir", bundle / "web", "--projects-dir", home / "projects", "--port", "0", ] with subprocess.Popen(command, stdin=subprocess.DEVNULL, env=dict(os.environ, **{INSTANCE_ENV: args.instance})) as child: try: print(f"Texrra desktop PID {child.pid}", flush=True) while child.poll() is None: if lease_ended(0.25): return 0 launch_error(f"Native editor exited unexpectedly (exit {child.returncode})") return child.returncode or 1 finally: if child.poll() is None: child.terminate() try: child.wait(timeout=3) except subprocess.TimeoutExpired: child.kill() child.wait() def stop(args): require(args.pid > 1, "The desktop backend PID must be greater than one") try: pid = os.pidfd_open(args.pid) except ProcessLookupError: return try: proc = Path(f"/proc/{args.pid}") token = f"{INSTANCE_ENV}={args.instance}".encode() runtime = private_home() / "runtime" environ = (proc / "environ").read_bytes().split(b"\0") command = (proc / "cmdline").read_bytes().split(b"\0") exe = (proc / "exe").readlink() candidates = (exe, Path(os.fsdecode(command[1]))) if len(command) > 1 else (exe,) owned = any(path.is_relative_to(runtime) and path.name in ("native_editor", "native-beta.py") for path in candidates) require(owned and token in environ, "The process does not match this desktop backend") signal.pidfd_send_signal(pid, signal.SIGTERM) except (ProcessLookupError, FileNotFoundError): pass finally: os.close(pid) def main(): repo = Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="action", required=True) stage = commands.add_parser("prepare", help="stage a new installer resource directory") stage.add_argument("output", type=Path) stage.add_argument("--artifact-dir", type=Path, required=True) stage.add_argument("--commit", required=True) stage.add_argument("--reference-bundle", type=Path, default=repo / "target/p4-a4-child-release/browser-bundle") stage.add_argument("--web-repo", type=Path, default=repo.parent / "texrra-web") run = commands.add_parser("launch", help="run the backend while its stdin lease is open") close = commands.add_parser("stop", help="stop only the selected desktop backend") close.add_argument("--pid", type=int, required=True) for command in (run, close): command.add_argument("--instance", required=True) args = parser.parse_args() if args.action != "prepare" and not re.fullmatch(r"[0-9a-f]{16,128}", args.instance): parser.error("--instance must be 16 to 128 lowercase hexadecimal characters") try: if args.action == "prepare": prepare(args, repo) elif args.action == "launch": return launch(args) else: stop(args) except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error: if args.action == "launch": launch_error(error) parser.exit(1, f"{error}\n") except KeyboardInterrupt: return 0 if __name__ == "__main__": sys.exit(main())