Repository navigation
Expand file tree
/
Copy pathupdate.py
More file actions
1626 lines (1487 loc) · 69.7 KB
/
Copy pathupdate.py
File metadata and controls
1626 lines (1487 loc) · 69.7 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import annotations
import argparse
from collections import deque
import errno
import json
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
import time
import urllib.request
import uuid
import zipfile
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from common import (
print_error,
print_warning,
ActiveOperationError,
DATA_DIR,
PRESERVED_RELEASE_FILES,
RELEASE_MANIFEST_FILE,
RELEASE_MANIFEST_VERSION,
TEMP_ROOT,
TOOL_DIR,
VERSION,
ErrorArgumentParser,
SingleUseStoreTrueAction,
cleanup_temp_root_if_empty,
cleanup_temporary_file,
compare_versions,
display_version,
exclusive_operation_activity_lock,
format_bytes,
is_reparse_stat,
is_sha256,
base_name_sort_key,
parse_json,
parse_version,
process_identity,
process_matches_identity,
relative_path_parts,
sha256_file,
style_console_text,
validate_index,
)
UPDATE_CONFIG_FILE = DATA_DIR / "update.json"
GITHUB_RELEASES_API = "https://api.github.com/repos/DarkLotus8000/Ninja-Patch-Tool/releases/latest"
GITHUB_RELEASES_URL = "https://github.com/DarkLotus8000/Ninja-Patch-Tool/releases"
UPDATE_ATTEMPTS = 3
STALE_UPDATE_AGE_SECONDS = 7 * 24 * 60 * 60
UPDATE_INSTALLER_ARGUMENT = "--update-installer"
UPDATE_SESSION_FILE = "update_session.json"
MAX_GITHUB_JSON_BYTES = 4 * 1024 * 1024
MAX_CHECKSUM_BYTES = 4096
LOCAL_DISPLAY_VERSION = display_version()
_UPDATE_WORK_NAME_RE = re.compile(r"^update_[0-9a-f]{32}$", re.IGNORECASE)
_UPDATE_BACKUP_NAME_RE = re.compile(r"^backup_[0-9a-f]{32}$", re.IGNORECASE)
_PRESERVED_RELEASE_FILE_KEYS = frozenset(name.casefold() for name in PRESERVED_RELEASE_FILES)
_RELEASE_MANIFEST_KEY = RELEASE_MANIFEST_FILE.casefold()
class UpdaterBusyError(RuntimeError):
pass
def add_update_arguments(parser: argparse.ArgumentParser) -> None:
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-a",
"--auto-update",
action=SingleUseStoreTrueAction,
help="Force an automatic update check/install for this run, overriding data/update.json",
)
group.add_argument(
"-n",
"--no-auto-update",
action=SingleUseStoreTrueAction,
help="Disable automatic updating for this run, overriding data/update.json",
)
group.add_argument(
"-u",
"--check-update",
action=SingleUseStoreTrueAction,
help="Check GitHub Releases for a newer version without installing it",
)
def _move_file_if_absent_windows(source: Path, destination: Path) -> None:
# FAT/exFAT do not support hard links. MoveFileEx without MOVEFILE_REPLACE_EXISTING gives us the same important
# property on Windows: atomic publication within the directory without overwriting a config another process won.
if sys.platform != "win32":
raise OSError("Atomic non-overwriting update config fallback is Windows-only.")
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.MoveFileExW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD]
kernel32.MoveFileExW.restype = wintypes.BOOL
if kernel32.MoveFileExW(str(source), str(destination), 0x8): # MOVEFILE_WRITE_THROUGH
return
error = ctypes.get_last_error()
if error in {80, 183}: # ERROR_FILE_EXISTS / ERROR_ALREADY_EXISTS
raise FileExistsError(error, "Update configuration already exists.", str(destination))
raise OSError(error, "Could not publish the default update configuration.", str(destination))
def _create_default_update_config() -> None:
UPDATE_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
temporary = UPDATE_CONFIG_FILE.with_name(f"{UPDATE_CONFIG_FILE.name}.{uuid.uuid4().hex}.tmp")
try:
with temporary.open("x", encoding="utf-8", newline="\n") as file:
file.write(json.dumps({"auto_update": True}, indent=2) + "\n")
try:
# Hard-link publication is atomic and never overwrites a config that another process created first.
os.link(temporary, UPDATE_CONFIG_FILE)
except FileExistsError:
pass
except OSError:
try:
_move_file_if_absent_windows(temporary, UPDATE_CONFIG_FILE)
except FileExistsError:
pass
finally:
cleanup_temporary_file(temporary)
def _read_update_config() -> dict[str, Any]:
if not UPDATE_CONFIG_FILE.exists():
_create_default_update_config()
try:
config = parse_json(UPDATE_CONFIG_FILE.read_text(encoding="utf-8"))
except ValueError as exc:
raise ValueError(f"Invalid JSON: {exc}") from exc
if not isinstance(config, dict) or not isinstance(config.get("auto_update"), bool):
raise ValueError('Expected a JSON object containing boolean "auto_update".')
return config
def _write_update_config(config: dict[str, Any]) -> None:
UPDATE_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
temporary = UPDATE_CONFIG_FILE.with_name(f"{UPDATE_CONFIG_FILE.name}.{uuid.uuid4().hex}.tmp")
try:
with temporary.open("x", encoding="utf-8", newline="\n") as file:
file.write(json.dumps(config, indent=2) + "\n")
temporary.replace(UPDATE_CONFIG_FILE)
finally:
cleanup_temporary_file(temporary)
def load_auto_update_setting() -> bool:
try:
return _read_update_config()["auto_update"]
except OSError as exc:
message = "Could not create" if not UPDATE_CONFIG_FILE.exists() else "Could not read"
print_warning(f'{message} {UPDATE_CONFIG_FILE}; automatic updating is disabled for this run: {exc}')
return False
except ValueError as exc:
print_warning(f'Invalid update configuration; automatic updating is disabled for this run: {exc}')
return False
def _stored_check_time(config: dict[str, Any], key: str) -> int | None:
value = config.get(key)
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
return value
return None
def automatic_update_check_due(now: float | None = None) -> bool:
# Cooldown state is best-effort. A damaged/unreadable config must not create a second failure mode here; the normal
# auto-update setting validation already decides whether automatic updating itself is allowed.
try:
config = _read_update_config()
except (OSError, ValueError):
return True
current = time.time() if now is None else now
successful = _stored_check_time(config, "last_successful_check")
failed = _stored_check_time(config, "last_failed_check")
if failed is not None and (successful is None or failed >= successful):
age = current - failed
return age < 0 or age >= 15 * 60
if successful is not None:
age = current - successful
return age < 0 or age >= 24 * 60 * 60
return True
def _record_update_check_result(result: str, now: float | None = None) -> None:
# Source checkouts must not write runtime cooldown state into the repository.
if not getattr(sys, "frozen", False):
return
# State persistence must never turn an otherwise successful update check into a user-visible failure.
try:
config = _read_update_config()
timestamp = int(time.time() if now is None else now)
if result == "success":
config["last_successful_check"] = timestamp
config.pop("last_failed_check", None)
elif result == "failure":
config["last_failed_check"] = timestamp
config.pop("last_successful_check", None)
elif result == "update_available":
# Do not let an earlier no-update cooldown suppress installation after an explicit check discovers a release.
config.pop("last_successful_check", None)
config.pop("last_failed_check", None)
else:
raise ValueError(f"Unknown update check result: {result}")
_write_update_config(config)
except (OSError, ValueError):
pass
def _request(url: str, timeout: float):
request = urllib.request.Request(
url,
headers={
"Accept": "application/vnd.github+json",
"User-Agent": f"NinjaPatchTool/{VERSION}",
"X-GitHub-Api-Version": "2022-11-28",
},
)
return urllib.request.urlopen(request, timeout=timeout)
def _request_json(url: str) -> dict[str, Any]:
with _request(url, 5) as response:
payload = response.read(MAX_GITHUB_JSON_BYTES + 1)
if len(payload) > MAX_GITHUB_JSON_BYTES:
raise RuntimeError("GitHub update metadata response is unexpectedly large.")
try:
result = parse_json(payload)
except ValueError as exc:
raise RuntimeError(f"GitHub returned invalid JSON: {exc}") from exc
if not isinstance(result, dict):
raise RuntimeError("GitHub returned an unexpected response.")
return result
def latest_release() -> dict[str, Any]:
release = _request_json(GITHUB_RELEASES_API)
tag = release.get("tag_name")
assets = release.get("assets")
html_url = release.get("html_url")
if not isinstance(tag, str) or not tag.strip():
raise RuntimeError("Latest GitHub Release does not contain a valid tag name.")
parse_version(tag)
if not isinstance(assets, list):
raise RuntimeError("Latest GitHub Release does not contain an asset list.")
if not isinstance(html_url, str) or not html_url.lower().startswith("https://github.com/"):
html_url = GITHUB_RELEASES_URL
version = tag[1:] if tag[:1].lower() == "v" else tag
return {"version": version, "assets": assets, "url": html_url}
def find_release_asset(release: dict[str, Any], name: str) -> tuple[str, int]:
for asset in release["assets"]:
if not isinstance(asset, dict) or asset.get("name") != name:
continue
url = asset.get("browser_download_url")
size = asset.get("size")
if not isinstance(url, str) or not url.lower().startswith("https://"):
raise RuntimeError(f"GitHub Release asset has an invalid download URL: {name}")
if not isinstance(size, int) or isinstance(size, bool) or size < 0:
raise RuntimeError(f"GitHub Release asset has an invalid or missing size: {name}")
return url, size
raise RuntimeError(f"Required GitHub Release asset is missing: {name}")
def check_for_update() -> dict[str, Any] | None:
release = latest_release()
if compare_versions(release["version"], VERSION) <= 0:
return None
return release
def check_update_only() -> int:
try:
release = latest_release()
comparison = compare_versions(release["version"], VERSION)
if comparison < 0:
_record_update_check_result("success")
print(f"[Update] Local Ninja Patch Tool v{LOCAL_DISPLAY_VERSION} is newer than the latest release v{display_version(str(release['version']))}.")
elif comparison == 0:
_record_update_check_result("success")
print(f"[Update] Ninja Patch Tool v{LOCAL_DISPLAY_VERSION} is up to date.")
else:
_record_update_check_result("update_available")
print(f"[Update] Ninja Patch Tool v{display_version(str(release['version']))} is available.\nCurrent version: v{LOCAL_DISPLAY_VERSION}\nRelease: {release['url']}")
return 0
except KeyboardInterrupt:
print("\nUpdate check cancelled.", file=sys.stderr)
return 130
except Exception as exc:
_record_update_check_result("failure")
print_error(f"Update check failed: {exc}")
return 1
def _legacy_updater_version_info(executable: Path) -> dict[str, str]:
# Read the PE version resource without executing the file. This is deliberately conservative: if the historical
# helper has no usable metadata, cleanup is skipped rather than risking a user-owned updater.exe.
if sys.platform != "win32":
return {}
import ctypes
from ctypes import wintypes
version = ctypes.WinDLL("version", use_last_error=True)
version.GetFileVersionInfoSizeW.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(wintypes.DWORD)]
version.GetFileVersionInfoSizeW.restype = wintypes.DWORD
version.GetFileVersionInfoW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p]
version.GetFileVersionInfoW.restype = wintypes.BOOL
version.VerQueryValueW.argtypes = [
ctypes.c_void_p,
wintypes.LPCWSTR,
ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(wintypes.UINT),
]
version.VerQueryValueW.restype = wintypes.BOOL
ignored = wintypes.DWORD(0)
size = version.GetFileVersionInfoSizeW(str(executable), ctypes.byref(ignored))
if not size:
return {}
buffer = ctypes.create_string_buffer(size)
if not version.GetFileVersionInfoW(str(executable), 0, size, buffer):
return {}
translations: list[tuple[int, int]] = []
pointer = ctypes.c_void_p()
length = wintypes.UINT(0)
if version.VerQueryValueW(buffer, r"\VarFileInfo\Translation", ctypes.byref(pointer), ctypes.byref(length)):
count = int(length.value) // (2 * ctypes.sizeof(ctypes.c_ushort))
values = ctypes.cast(pointer, ctypes.POINTER(ctypes.c_ushort))
translations.extend((int(values[index * 2]), int(values[index * 2 + 1])) for index in range(count))
if (0x0409, 0x04B0) not in translations:
translations.append((0x0409, 0x04B0))
fields = ("ProductName", "ProductVersion", "FileVersion", "FileDescription", "InternalName")
result: dict[str, str] = {}
for language, codepage in translations:
table = f"{language:04X}{codepage:04X}"
for field in fields:
if field in result:
continue
pointer = ctypes.c_void_p()
length = wintypes.UINT(0)
subblock = rf"\StringFileInfo\{table}\{field}"
if (
not version.VerQueryValueW(buffer, subblock, ctypes.byref(pointer), ctypes.byref(length))
or not pointer.value
):
continue
value = ctypes.wstring_at(pointer.value, max(0, int(length.value) - 1)).strip()
if value:
result[field] = value
return result
def _is_known_legacy_updater(executable: Path) -> bool:
try:
info = _legacy_updater_version_info(executable)
except (OSError, ValueError):
return False
if info.get("ProductName", "").strip().casefold() != "ninja patch tool":
return False
identity = " ".join((info.get("FileDescription", ""), info.get("InternalName", ""))).casefold()
if "updater" not in identity:
return False
version = info.get("ProductVersion") or info.get("FileVersion")
if not version:
return False
try:
return compare_versions(version, "1.4") == 0
except ValueError:
return False
def cleanup_legacy_updater_executable() -> None:
# v1.4 shipped a separate updater.exe. Only remove it when the executable identifies itself as that exact legacy
# helper; an unrelated file named updater.exe is user-owned and must be left untouched.
if sys.platform != "win32" or not getattr(sys, "frozen", False):
return
legacy_updater = TOOL_DIR / "updater.exe"
try:
if not legacy_updater.is_file() or legacy_updater.resolve() == Path(sys.executable).resolve():
return
if not _is_known_legacy_updater(legacy_updater):
return
legacy_updater.unlink()
except OSError:
# Migration cleanup is best-effort. A locked or otherwise undeletable legacy helper must never block Ninja Patch Tool.
pass
def handle_early_update_request(argv: list[str]) -> int | None:
# Every release executable contains the installer logic in this update module. A temporary copy of whichever executable
# initiated the update enters this hidden mode and performs the installation after the original process exits.
if argv[:1] == [UPDATE_INSTALLER_ARGUMENT]:
return run_update_installer(argv[1:])
if UPDATE_INSTALLER_ARGUMENT in argv:
print_error("Invalid internal updater arguments.")
return 1
try:
cleanup_legacy_updater_executable()
cleanup_relaunched_update_work()
cleanup_stale_update_work()
parser = ErrorArgumentParser()
add_update_arguments(parser)
args, remaining = parser.parse_known_args(argv)
if not args.check_update:
return None
if remaining:
parser.error("--check-update must be used without operation arguments")
return check_update_only()
except KeyboardInterrupt:
print("\nStartup cancelled.", file=sys.stderr)
return 130
def _ensure_free_space(path: Path, required: int, purpose: str) -> None:
if required <= 0:
return
free = shutil.disk_usage(path).free
if free < required:
raise RuntimeError(
f"Not enough free disk space to {purpose}: {format_bytes(required)} required, {format_bytes(free)} available."
)
class _UpdateProgress:
DISPLAY_DELAY_SECONDS = 0.5
REPORT_INTERVAL_SECONDS = 0.25
SPEED_WINDOW_SECONDS = 1.5
def __init__(self, label: str, total: int, path: str) -> None:
self.label = label
self.total = max(0, total)
self.path = path
self.completed = 0
self.started_at = time.monotonic()
self.last_report = 0.0
self.speed_samples: deque[tuple[float, int]] = deque([(self.started_at, 0)])
self.progress_width = 0
self.finished = False
self.last_plain_percent = -10
self.last_plain_time = self.started_at
@staticmethod
def _interactive_console() -> bool:
try:
return sys.stdout.isatty()
except (AttributeError, OSError, ValueError):
return False
def _record_speed_sample(self, now: float) -> None:
self.speed_samples.append((now, self.completed))
cutoff = now - self.SPEED_WINDOW_SECONDS
while len(self.speed_samples) > 2 and self.speed_samples[1][0] <= cutoff:
self.speed_samples.popleft()
def _message(self, now: float) -> str:
sample_time, sample_size = self.speed_samples[0]
elapsed = max(1e-6, now - sample_time)
speed_bps = max(0, int((self.completed - sample_size) / elapsed))
if self.total > 0:
percent = min(100.0, self.completed * 100.0 / self.total)
return (
f"{self.label} {format_bytes(self.completed)} / {format_bytes(self.total)} ({percent:.1f}%)"
f" | {format_bytes(speed_bps)}/s | {self.path}"
)
return f"{self.label} {format_bytes(self.completed)} | {format_bytes(speed_bps)}/s | {self.path}"
@staticmethod
def _truncate(message: str, width: int) -> str:
if len(message) <= width:
return message
separator = " | "
if separator in message:
prefix, path = message.rsplit(separator, 1)
available = width - len(prefix) - len(separator)
if available >= 4:
message = prefix + separator + "..." + path[-(available - 3):]
if len(message) > width:
message = message[:width] if width <= 3 else message[: width - 3] + "..."
return message
def _render_interactive(self, now: float) -> None:
try:
width = max(1, shutil.get_terminal_size(fallback=(120, 24)).columns - 1)
except OSError:
width = 119
message = self._truncate(self._message(now), width)
styled = style_console_text(message, sys.stdout, status_tokens=True)
padding = max(0, self.progress_width - len(message))
try:
sys.stdout.write("\r" + styled + (" " * padding))
sys.stdout.flush()
except (OSError, ValueError):
self.progress_width = 0
return
self.progress_width = len(message)
def update(self, amount: int) -> None:
self.completed += max(0, amount)
now = time.monotonic()
self._record_speed_sample(now)
if self._interactive_console():
if now - self.started_at < self.DISPLAY_DELAY_SECONDS and self.completed < self.total:
return
if now - self.last_report < self.REPORT_INTERVAL_SECONDS and self.completed < self.total:
return
self.last_report = now
self._render_interactive(now)
return
if self.total <= 0:
return
percent = min(100, self.completed * 100 // self.total)
if percent >= self.last_plain_percent + 10 or now - self.last_plain_time >= 5 or self.completed >= self.total:
print(self._message(now))
self.last_plain_percent = percent
self.last_plain_time = now
def finish(self) -> None:
if self.finished:
return
self.completed = self.total if self.total > 0 else self.completed
now = time.monotonic()
self._record_speed_sample(now)
if self._interactive_console():
self._render_interactive(now)
try:
sys.stdout.write("\n")
sys.stdout.flush()
except (OSError, ValueError):
pass
self.progress_width = 0
elif self.total > 0 and self.last_plain_percent < 100:
print(self._message(now))
self.finished = True
def abort(self) -> None:
if self.progress_width <= 0:
return
try:
sys.stdout.write("\r" + (" " * self.progress_width) + "\r")
sys.stdout.flush()
except (OSError, ValueError):
pass
self.progress_width = 0
def _download_file(
url: str,
destination: Path,
expected_size: int | None = None,
progress_label: str | None = None,
max_size: int | None = None,
) -> None:
temporary = destination.with_name(destination.name + ".part")
temporary.unlink(missing_ok=True)
written = 0
progress = (
_UpdateProgress(progress_label, expected_size, destination.name)
if progress_label is not None and expected_size is not None
else None
)
try:
with _request(url, 30) as response, temporary.open("xb") as output:
while chunk := response.read(256 * 1024):
limits = [value for value in (expected_size, max_size) if value is not None]
limit = min(limits) if limits else None
if limit is not None and written + len(chunk) > limit:
raise RuntimeError(
f"Downloaded update file exceeds the expected size limit: {destination.name}"
)
if output.write(chunk) != len(chunk):
raise RuntimeError(f"Could not completely write downloaded update file: {destination.name}")
written += len(chunk)
if progress is not None:
progress.update(len(chunk))
if expected_size is not None and written != expected_size:
raise RuntimeError(
f"Downloaded size does not match GitHub metadata for {destination.name}: "
f"{format_bytes(written)} instead of {format_bytes(expected_size)}"
)
if progress is not None:
progress.finish()
temporary.replace(destination)
except BaseException:
if progress is not None:
progress.abort()
cleanup_temporary_file(temporary)
raise
def _read_expected_checksum(path: Path, archive_name: str) -> str:
lines = [line.strip() for line in path.read_text(encoding="ascii").splitlines() if line.strip()]
if len(lines) != 1:
raise RuntimeError("Release checksum file must contain exactly one non-empty line.")
parts = lines[0].split()
if len(parts) != 2 or not is_sha256(parts[0]) or parts[1].lstrip("*") != archive_name:
raise RuntimeError("Release checksum file has an unexpected format or filename.")
return parts[0].lower()
def _safe_archive_parts(name: str) -> tuple[str, ...]:
# ZIP member names are POSIX-style. Reject backslashes rather than normalizing them, then apply the same strict
# Windows path rules used by Ninja Patch manifests (reserved devices, ADS syntax, trailing dots/spaces, etc.).
if not name or "\\" in name or "\0" in name:
raise RuntimeError(f"Unsafe update archive path: {name!r}")
try:
return relative_path_parts(name)
except ValueError as exc:
raise RuntimeError(f"Unsafe update archive path: {name!r}") from exc
def _parse_release_manifest(path: Path) -> tuple[str, dict[str, str]]:
try:
value = parse_json(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise RuntimeError(f"Release manifest is invalid: {exc}") from exc
if not isinstance(value, dict) or value.get("format_version") != RELEASE_MANIFEST_VERSION:
raise RuntimeError("Release manifest has an unsupported format version.")
application_version = value.get("application_version")
files = value.get("files")
if not isinstance(application_version, str) or not application_version:
raise RuntimeError("Release manifest has an invalid application version.")
if not isinstance(files, dict):
raise RuntimeError("Release manifest files must be a JSON object.")
seen: set[str] = set()
normalized: dict[str, str] = {}
for name, digest in files.items():
if not isinstance(name, str) or not isinstance(digest, str):
raise RuntimeError("Release manifest contains invalid file metadata.")
try:
parts = relative_path_parts(name)
except ValueError as exc:
raise RuntimeError(f"Release manifest contains an unsafe path: {name!r}") from exc
canonical = "/".join(parts)
folded = canonical.casefold()
if canonical != name or folded in _PRESERVED_RELEASE_FILE_KEYS or folded == _RELEASE_MANIFEST_KEY:
raise RuntimeError(f"Release manifest contains an invalid managed path: {name!r}")
if folded in seen:
raise RuntimeError(f"Release manifest contains a duplicate managed path: {name!r}")
if not is_sha256(digest):
raise RuntimeError(f"Release manifest contains an invalid SHA-256 for {name!r}.")
seen.add(folded)
normalized[name] = digest.lower()
return application_version, normalized
def _validate_staged_release_manifest(stage: Path, release_version: str) -> dict[str, str]:
application_version, files = _parse_release_manifest(stage / RELEASE_MANIFEST_FILE)
if application_version != release_version:
raise RuntimeError("Release manifest application version does not match the downloaded release.")
actual: set[str] = set()
for path in stage.rglob("*"):
if not path.is_file():
continue
relative = path.relative_to(stage).as_posix()
if relative == RELEASE_MANIFEST_FILE or relative in PRESERVED_RELEASE_FILES:
continue
actual.add(relative)
if actual != set(files):
raise RuntimeError("Release manifest does not match the downloaded release files.")
for name, expected in files.items():
target = stage.joinpath(*name.split("/"))
if sha256_file(target).lower() != expected:
raise RuntimeError(f"Release manifest SHA-256 does not match {name!r}.")
return files
def _load_installed_release_manifest(install_dir: Path) -> dict[str, str] | None:
try:
_, files = _parse_release_manifest(install_dir / RELEASE_MANIFEST_FILE)
return files
except (OSError, RuntimeError):
# Older releases have no manifest. A missing, damaged, or locally edited manifest must never make the updater
# delete files speculatively, so obsolete-file cleanup is simply skipped for that upgrade.
return None
def extract_release_archive(archive_path: Path, destination: Path, release_version: str) -> Path:
expected_root = f"NinjaPatchTool-v{release_version}"
seen: set[str] = set()
destination.mkdir(parents=True, exist_ok=False)
with zipfile.ZipFile(archive_path, "r") as archive:
members = archive.infolist()
if not members:
raise RuntimeError("Downloaded release archive is empty.")
extracted_size = 0
for member in members:
parts = _safe_archive_parts(member.filename.rstrip("/"))
if not parts or parts[0] != expected_root:
raise RuntimeError(f"Unexpected release archive root: {member.filename}")
folded = member.filename.rstrip("/").casefold()
if folded in seen:
raise RuntimeError(f"Release archive contains a duplicate path: {member.filename}")
seen.add(folded)
mode = (member.external_attr >> 16) & 0xFFFF
if mode & 0o170000 == 0o120000:
raise RuntimeError(f"Release archive contains a symbolic link: {member.filename}")
if not member.is_dir():
extracted_size += member.file_size
# The staged release remains present while it is copied into the installation, so allow space for both copies.
_ensure_free_space(destination.parent, extracted_size * 2, "extract and install the update")
for member in members:
clean_name = member.filename.rstrip("/")
if not clean_name:
continue
parts = _safe_archive_parts(clean_name)
relative = parts[1:]
target = destination.joinpath(*relative)
if member.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
with archive.open(member, "r") as source, target.open("xb") as output:
shutil.copyfileobj(source, output, length=8 * 1024 * 1024)
required = (
"add_base.exe",
"verify_base.exe",
"make_patch.exe",
"apply_patch.exe",
"README.txt",
RELEASE_MANIFEST_FILE,
"data/index.json",
"data/update.json",
"data/hdiffz.exe",
"data/hpatchz.exe",
)
missing = [name for name in required if not (destination / Path(name)).is_file()]
if missing:
raise RuntimeError("Downloaded release is incomplete; missing: " + ", ".join(missing))
try:
index = parse_json((destination / "data" / "index.json").read_text(encoding="utf-8"))
validate_index(index)
update_config = parse_json((destination / "data" / "update.json").read_text(encoding="utf-8"))
if not isinstance(update_config, dict) or not isinstance(update_config.get("auto_update"), bool):
raise ValueError('update.json must contain boolean "auto_update".')
except (OSError, ValueError) as exc:
raise RuntimeError(f"Downloaded release contains invalid JSON data: {exc}") from exc
licenses = destination / "data" / "licenses"
if not licenses.is_dir() or not any(path.is_file() for path in licenses.iterdir()):
raise RuntimeError("Downloaded release does not contain its license files.")
_validate_staged_release_manifest(destination, release_version)
return destination
def download_release(release: dict[str, Any], work: Path) -> Path:
version = release["version"]
archive_name = f"NinjaPatchTool-v{version}-Windows-x64.zip"
checksum_name = archive_name + ".sha256"
archive_url, archive_size = find_release_asset(release, archive_name)
checksum_url, checksum_size = find_release_asset(release, checksum_name)
if checksum_size > MAX_CHECKSUM_BYTES:
raise RuntimeError("Release checksum asset is unexpectedly large.")
archive_path = work / archive_name
checksum_path = work / checksum_name
_ensure_free_space(work, archive_size + checksum_size, "download the update")
last_error: Exception | None = None
for attempt in range(1, UPDATE_ATTEMPTS + 1):
archive_path.unlink(missing_ok=True)
checksum_path.unlink(missing_ok=True)
try:
print(f"[Update] Downloading Ninja Patch Tool v{display_version(str(version))} (attempt {attempt}/{UPDATE_ATTEMPTS})...")
_download_file(checksum_url, checksum_path, checksum_size, max_size=MAX_CHECKSUM_BYTES)
_download_file(archive_url, archive_path, archive_size, "[Update]")
expected = _read_expected_checksum(checksum_path, archive_name)
actual = sha256_file(archive_path)
if actual.lower() != expected:
raise RuntimeError("Downloaded release SHA-256 does not match its checksum file.")
return archive_path
except Exception as exc:
last_error = exc
if attempt < UPDATE_ATTEMPTS:
print(f"[Update] Download failed (attempt {attempt}/{UPDATE_ATTEMPTS}): {exc}", file=sys.stderr)
time.sleep(attempt)
raise RuntimeError(f"Update download failed after {UPDATE_ATTEMPTS} attempts: {last_error}")
def _current_application_path() -> Path:
executable = Path(sys.executable).resolve()
if not executable.is_file():
raise RuntimeError(f"Current Ninja Patch Tool executable is missing: {executable}")
return executable
def _validate_temporary_updater(executable: Path) -> None:
expected = f"Ninja Patch Tool v{LOCAL_DISPLAY_VERSION}"
try:
result = subprocess.run(
[str(executable), UPDATE_INSTALLER_ARGUMENT, "--version"],
cwd=TOOL_DIR,
capture_output=True,
text=True,
timeout=150,
check=False,
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(
f"Temporary Ninja Patch Tool updater did not respond to --version within 150 seconds: {executable}"
) from exc
except OSError as exc:
raise RuntimeError(f"Temporary Ninja Patch Tool updater could not be started: {executable}: {exc}") from exc
actual = result.stdout.strip()
if result.returncode != 0:
detail = result.stderr.strip() or actual or f"exit code {result.returncode}"
raise RuntimeError(f"Temporary Ninja Patch Tool updater failed its version check: {executable}\n{detail}")
if actual != expected:
raise RuntimeError(
"Temporary Ninja Patch Tool updater version does not match this release.\n"
f"Expected: {expected}\n"
f"Actual: {actual or '(no version output)'}"
)
def _copy_application_for_update(work: Path) -> Path:
source = _current_application_path()
temporary = work / "NinjaPatchToolUpdater.exe"
shutil.copy2(source, temporary)
_validate_temporary_updater(temporary)
return temporary
def launch_updater(temporary_updater: Path, stage: Path, argv: list[str], target_version: str) -> None:
# Revalidate the already-created self-copy immediately before handoff. The copy lives in this update work directory,
# so no system temporary directory or separate shipped updater executable is needed.
_validate_temporary_updater(temporary_updater)
command = [
str(temporary_updater),
UPDATE_INSTALLER_ARGUMENT,
"--install-dir",
str(TOOL_DIR),
"--stage-dir",
str(stage),
"--parent-pid",
str(os.getpid()),
"--target-version",
target_version,
"--relaunch-executable",
str(Path(sys.executable).resolve()),
"--relaunch-cwd",
str(Path.cwd().resolve()),
"--",
*argv,
]
environment = os.environ.copy()
environment["PYINSTALLER_RESET_ENVIRONMENT"] = "1"
subprocess.Popen(command, cwd=TOOL_DIR, env=environment)
def _update_session_is_active(work: Path) -> bool:
session = work / UPDATE_SESSION_FILE
if sys.platform != "win32":
return False
try:
session_stat = session.lstat()
except FileNotFoundError:
return False
except OSError:
# Metadata that cannot be inspected at all is ambiguous. Preserve the
# workspace rather than risking deletion of a live updater.
return True
if stat.S_ISLNK(session_stat.st_mode) or is_reparse_stat(session_stat) or not stat.S_ISREG(session_stat.st_mode):
return False
try:
raw_state = session.read_text(encoding="utf-8")
except OSError:
return True
try:
state = parse_json(raw_state)
except ValueError:
# Malformed metadata is not a valid live-process identity. Backup
# recovery protection is handled separately by _update_work_backup_state().
return False
if not isinstance(state, dict):
return False
pid = state.get("pid")
identity = state.get("process_identity")
if (
not isinstance(pid, int)
or isinstance(pid, bool)
or pid <= 0
or not isinstance(identity, str)
or not identity
):
return False
try:
return process_matches_identity(pid, identity)
except Exception:
# Only uncertainty while inspecting an otherwise valid process identity
# is treated as possibly active.
return True
def _update_session_transaction_state(work: Path) -> str | None:
session = work / UPDATE_SESSION_FILE
try:
session_stat = session.lstat()
except OSError:
return None
if stat.S_ISLNK(session_stat.st_mode) or is_reparse_stat(session_stat) or not stat.S_ISREG(session_stat.st_mode):
return None
try:
state = parse_json(session.read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
if not isinstance(state, dict):
return None
transaction_state = state.get("transaction_state")
return transaction_state if isinstance(transaction_state, str) else None
def _update_session_backup_is_disposable(work: Path) -> bool:
return _update_session_transaction_state(work) in {"committed", "rolled_back"}
def _update_work_backup_state(work: Path) -> bool | None:
"""Return True for a real Ninja Patch Tool backup, False for none, None when inspection is unsafe."""
try:
work_stat = work.lstat()
if stat.S_ISLNK(work_stat.st_mode) or is_reparse_stat(work_stat) or not stat.S_ISDIR(work_stat.st_mode):
return None
for path in work.iterdir():
if not _UPDATE_BACKUP_NAME_RE.fullmatch(path.name):
continue
path_stat = path.lstat()
if stat.S_ISLNK(path_stat.st_mode) or is_reparse_stat(path_stat) or not stat.S_ISDIR(path_stat.st_mode):
return None
return True
return False
except OSError:
return None
def _update_work_has_backup(work: Path) -> bool:
# Unknown/unsafe state is treated conservatively as recovery data.
return _update_work_backup_state(work) is not False
def cleanup_deferred_update_payload(work: Path) -> None:
if _update_work_backup_state(work) is not False:
return
try:
current_executable = Path(sys.executable).resolve()
children = list(work.iterdir())
except OSError:
return
for child in children:
try:
if child.resolve() == current_executable or child.name == UPDATE_SESSION_FILE:
continue
_remove_path(child)
except OSError:
# Deferral is already safe. Stale-work cleanup can retry anything that cannot be removed now.
continue
def cleanup_stale_update_work(max_age_seconds: int = STALE_UPDATE_AGE_SECONDS) -> None:
if max_age_seconds < 0 or not TEMP_ROOT.is_dir():
return
cutoff = time.time() - max_age_seconds
try:
candidates = list(TEMP_ROOT.iterdir())
except OSError:
return
for work in candidates:
if not _UPDATE_WORK_NAME_RE.fullmatch(work.name):
continue
try:
if work.is_symlink() or not work.is_dir() or work.stat().st_mtime > cutoff:
continue
backup_state = _update_work_backup_state(work)
if backup_state is None or (backup_state is True and not _update_session_backup_is_disposable(work)):
continue
if _update_session_is_active(work):
continue
shutil.rmtree(work)
except OSError:
# Startup cleanup is best-effort and must never block normal tool use.
continue
cleanup_temp_root_if_empty(TEMP_ROOT)
def cleanup_relaunched_update_work() -> None:
value = os.environ.pop("NPT_UPDATE_WORK_CLEANUP", None)
if not value:
return
raw_work = Path(value)
try:
if raw_work.is_symlink():
return
expected_parent = TEMP_ROOT.resolve()
work = raw_work.resolve()
except OSError:
return
if work.parent != expected_parent or not _UPDATE_WORK_NAME_RE.fullmatch(work.name) or not work.is_dir():
return
backup_state = _update_work_backup_state(work)
if backup_state is None or (backup_state is True and not _update_session_backup_is_disposable(work)):
return
# The relaunched process can race the final few milliseconds of the temporary
# updater shutting down. Terminal transaction backups are cleanup debris.
for _ in range(50):
if _update_session_is_active(work):
time.sleep(0.1)
continue
try: