Debian Codegraph @

Tools/test-updater.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # requirements: pycryptodome
3 from Crypto.PublicKey import ECC
4 from Crypto.Signature import eddsa
5 from hashlib import sha256
6 from pathlib import Path
7 import base64
8 import configparser
9 import gzip
10 import http.server
11 import json
12 import os
13 import shutil
14 import socketserver
15 import subprocess
16 import sys
17 import tempfile
18 import threading
19 import time
20
21 UPDATE_KEY_TEST = ECC.construct(
22 curve="Ed25519",
23 seed=bytes.fromhex(
24 "543a581db60008bbb978a464e136d686dbc9d594119e928b5276bece3d583d81"
25 ),
26 )
27
28 HTTP_SERVER_ADDR = ("localhost", 8042)
29 DOLPHIN_UPDATE_SERVER_URL = f"http://{HTTP_SERVER_ADDR[0]}:{HTTP_SERVER_ADDR[1]}"
30
31
32 class Manifest:
33 def __init__(self, path: Path):
34 self.path = path
35 self.entries = {}
36 for p in self.path.glob("**/*.*"):
37 if not p.is_file():
38 continue
39 digest = sha256(p.read_bytes()).digest()[:0x10].hex()
40 self.entries[digest] = p.relative_to(self.path).as_posix()
41
42 def get_signed(self):
43 manifest = "".join(
44 f"{name}\t{digest}\n" for digest, name in self.entries.items()
45 )
46 manifest = manifest.encode("utf-8")
47 sig = eddsa.new(UPDATE_KEY_TEST, "rfc8032").sign(manifest)
48 manifest += b"\n" + base64.b64encode(sig) + b"\n"
49 return gzip.compress(manifest)
50
51 def get_path(self, digest):
52 return self.path.joinpath(self.entries.get(digest))
53
54
55 class HTTPRequestHandler(http.server.BaseHTTPRequestHandler):
56 def do_GET(self):
57 if self.path.startswith("/update/check/v1/updater-test"):
58 self.send_response(200)
59 self.end_headers()
60 self.wfile.write(
61 bytes(
62 json.dumps(
63 {
64 "status": "outdated",
65 "content-store": DOLPHIN_UPDATE_SERVER_URL + "/content/",
66 "changelog": [],
67 "old": {"manifest": DOLPHIN_UPDATE_SERVER_URL + "/old"},
68 "new": {
69 "manifest": DOLPHIN_UPDATE_SERVER_URL + "/new",
70 "name": "updater-test",
71 "hash": bytes(range(32)).hex(),
72 },
73 }
74 ),
75 "utf-8",
76 )
77 )
78 elif self.path == "/old":
79 self.send_response(200)
80 self.end_headers()
81 self.wfile.write(self.current.get_signed())
82 elif self.path == "/new":
83 self.send_response(200)
84 self.end_headers()
85 self.wfile.write(self.next.get_signed())
86 elif self.path.startswith("/content/"):
87 self.send_response(200)
88 self.end_headers()
89 digest = "".join(self.path[len("/content/") :].split("/"))
90 path = self.next.get_path(digest)
91 self.wfile.write(gzip.compress(path.read_bytes()))
92 elif self.path.startswith("/update-test-done/"):
93 self.send_response(200)
94 self.end_headers()
95 HTTPRequestHandler.dolphin_pid = int(self.path[len("/update-test-done/") :])
96 self.done.set()
97
98
99 def http_server():
100 with socketserver.TCPServer(HTTP_SERVER_ADDR, HTTPRequestHandler) as httpd:
101 httpd.serve_forever()
102
103
104 def create_entries_in_ini(ini_path: Path, entries: dict):
105 config = configparser.ConfigParser()
106 if ini_path.exists():
107 config.read(ini_path)
108 else:
109 ini_path.parent.mkdir(parents=True, exist_ok=True)
110
111 for section, options in entries.items():
112 if not config.has_section(section):
113 config.add_section(section)
114 for option, value in options.items():
115 config.set(section, option, value)
116
117 with ini_path.open("w") as f:
118 config.write(f)
119
120
121 if __name__ == "__main__":
122 dolphin_bin_path = Path(sys.argv[1])
123
124 threading.Thread(target=http_server, daemon=True).start()
125
126 with tempfile.TemporaryDirectory(suffix=" ¿ 🐬") as tmp_dir:
127 tmp_dir = Path(tmp_dir)
128
129 tmp_dolphin = tmp_dir.joinpath("dolphin")
130 print(f"install to {tmp_dolphin}")
131 shutil.copytree(dolphin_bin_path.parent, tmp_dolphin)
132 tmp_dolphin.joinpath("portable.txt").touch()
133 create_entries_in_ini(
134 tmp_dolphin.joinpath("User/Config/Dolphin.ini"),
135 {
136 "Analytics": {"Enabled": "False", "PermissionAsked": "True"},
137 "AutoUpdate": {"UpdateTrack": "updater-test"},
138 },
139 )
140
141 tmp_dolphin_next = tmp_dir.joinpath("dolphin_next")
142 print(f"install next to {tmp_dolphin_next}")
143 # XXX copies from just-created dir so Dolphin.ini is kept
144 shutil.copytree(tmp_dolphin, tmp_dolphin_next)
145 tmp_dolphin_next.joinpath("updater-test-file").write_text("test")
146 tmp_dolphin_next.joinpath("updater-test-filἑ").write_text("test")
147 with tmp_dolphin_next.joinpath("build_info.txt").open("a") as f:
148 print("test", file=f)
149 for ext in ("exe", "dll"):
150 for path in tmp_dolphin_next.glob("**/*." + ext):
151 data = bytearray(path.read_bytes())
152 richpos = data[:0x200].find(b"Rich")
153 if richpos < 0:
154 continue
155 data[richpos : richpos + 4] = b"DOLP"
156 path.write_bytes(data)
157
158 HTTPRequestHandler.current = Manifest(tmp_dolphin)
159 HTTPRequestHandler.next = Manifest(tmp_dolphin_next)
160 HTTPRequestHandler.done = threading.Event()
161
162 tmp_env = os.environ
163 tmp_env.update({"DOLPHIN_UPDATE_SERVER_URL": DOLPHIN_UPDATE_SERVER_URL})
164 tmp_dolphin_bin = tmp_dolphin.joinpath(dolphin_bin_path.name)
165 result = subprocess.run(tmp_dolphin_bin, env=tmp_env)
166 assert result.returncode == 0
167
168 assert HTTPRequestHandler.done.wait(60 * 2)
169 # works fine but raises exceptions...
170 try:
171 os.kill(HTTPRequestHandler.dolphin_pid, 0)
172 except:
173 pass
174 try:
175 os.waitpid(HTTPRequestHandler.dolphin_pid, 0)
176 except:
177 pass
178
179 failed = False
180 for path in tmp_dolphin_next.glob("**/*.*"):
181 if not path.is_file():
182 continue
183 path_rel = path.relative_to(tmp_dolphin_next)
184 if path_rel.parts[0] == "User":
185 continue
186 new_path = tmp_dolphin.joinpath(path_rel)
187 if not new_path.exists():
188 print(f"missing: {new_path}")
189 failed = True
190 continue
191 if (
192 sha256(new_path.read_bytes()).digest()
193 != sha256(path.read_bytes()).digest()
194 ):
195 print(f"bad digest: {new_path} {path}")
196 failed = True
197 continue
198 assert not failed
199
200 print(tmp_dolphin.joinpath("User/Logs/Updater.log").read_text())
201 # while True: time.sleep(1)