aboutsummaryrefslogtreecommitdiffstats
path: root/frame-steamos/template.py
blob: eff1810d72fcb0e8f57ce4e9ad05036f0e123ce2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#!/usr/bin/python3 -I
# SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski>
# SPDX-License-Identifier: CC0-1.0

"""A minimally intrusive Frame SteamOS patcher.

This file is generated.

See https://kramkow.ski/project/steamvr-patches.html and
https://the-tk.com/cgit/steamvr-patches/about/ for more information.
"""

import argparse
import hashlib
import json
import os
import subprocess
import sys
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path

MARKER = "x-valve-please-fix"
RUNTIME = Path(os.environ.get("RUNTIME_DIRECTORY", "/run/patcher"))


@dataclass(frozen=True)
class Edit:
    offset: int
    replacement: bytes


@dataclass(frozen=True)
class Patch:
    original_hash: bytes
    patched_hash: bytes
    edits: tuple[Edit, ...]

    @classmethod
    def from_dict(cls, data: dict) -> "Patch":
        return cls(
            bytes.fromhex(data["original_hash"]),
            bytes.fromhex(data["patched_hash"]),
            tuple(
                Edit(offset, bytes.fromhex(replacement))
                for offset, replacement in data["edits"]
            ),
        )

    def apply_to(self, data: bytes) -> bytes:
        result = BytesIO(data)
        for edit in self.edits:
            result.seek(edit.offset)
            result.write(edit.replacement)
        patched = result.getvalue()
        if hashlib.sha256(patched).digest() != self.patched_hash:
            raise ValueError("patched file checksum mismatch")
        return patched


# Please refer to the source code (linked at the top of this file) if you want
# to know how this data was generated
PATCH_DATA = {}
PATCHES = {name: Patch.from_dict(data) for name, data in PATCH_DATA.items()}


def start():
    skipped = False
    for name, patch in PATCHES.items():
        target = Path(name).resolve(strict=True)
        data = target.read_bytes()
        checksum = hashlib.sha256(data).digest()
        if checksum != patch.original_hash:
            print(
                f"Skipping {target}: unrecognised checksum {checksum.hex()}",
                file=sys.stderr,
            )
            skipped = True
            continue
        patched = patch.apply_to(data)
        source = RUNTIME / hashlib.sha256(os.fsencode(target)).hexdigest()
        source.parent.mkdir(parents=True, exist_ok=True)
        source.write_bytes(patched)
        attributes = target.stat()
        os.chown(source, attributes.st_uid, attributes.st_gid)
        source.chmod(attributes.st_mode)
        subprocess.run(
            ["mount", "-o", f"bind,ro,{MARKER}", str(source), str(target)],
            check=True,
        )
        print(f"Patched {target}", file=sys.stderr)
    if skipped:
        raise SystemExit(1)


def stop():
    result = subprocess.run(
        [
            "findmnt",
            "--mtab",
            "--options",
            MARKER,
            "--json",
            "--output",
            "TARGET",
        ],
        capture_output=True,
        text=True,
    )
    if (
        result.returncode == 1
        and not result.stdout.strip()
        and not result.stderr.strip()
    ):
        return
    result.check_returncode()
    for target in reversed(
        [
            Path(row["target"])
            for row in json.loads(result.stdout).get("filesystems", [])
        ]
    ):
        subprocess.run(["umount", str(target)], check=True)
        print(f"Unmounted {target}", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("action", choices=("start", "stop"))
    args = parser.parse_args()
    if args.action == "start":
        start()
    else:
        stop()


if __name__ == "__main__":
    main()