Repository navigation
Expand file tree
/
Copy pathupdate.py
More file actions
1667 lines (1525 loc) · 71.1 KB
/
Copy pathupdate.py
File metadata and controls
1667 lines (1525 loc) · 71.1 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 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 (
atomic_write_json,
FROZEN_RUNTIME_DIR_NAME,
FileLockBusyError,
NCT_LICENSE_RELEASE_FILE,
PRESERVED_RELEASE_FILES,
RELEASE_MANIFEST_FILE,
RELEASE_MANIFEST_VERSION,
update_state_file,
update_temp_root,
TOOL_DIR,
VERSION,
display_version,
capture_activity_lock_path,
cleanup_temp_root_if_empty,
cleanup_temporary_file,
compare_versions,
format_bytes,
parse_json,
parse_version,
process_identity,
process_matches_identity,
print_error,
print_warning,
relative_path_parts,
sha256_file,
style_console_text,
windows_file_lock,
)
from config import DEFAULT_CONFIG, ErrorArgumentParser, SingleUseStoreTrueAction, validate_config
UPDATE_STATE_FILE: Path | None = None
UPDATE_ATTEMPTS = 3
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()
TEMP_ROOT: Path | None = None
_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()
def _update_temp_root() -> Path:
return update_temp_root() if TEMP_ROOT is None else TEMP_ROOT
class CaptureActiveError(RuntimeError):
pass
class UpdaterBusyError(RuntimeError):
pass
def _update_state_path() -> Path:
return update_state_file() if UPDATE_STATE_FILE is None else UPDATE_STATE_FILE
def _read_update_state() -> dict[str, Any]:
path = _update_state_path()
if not path.exists():
return {}
try:
text = path.read_text(encoding="utf-8")
except OSError:
raise
try:
value = parse_json(text)
except ValueError as exc:
raise ValueError(f"Invalid update state: {exc}") from exc
if not isinstance(value, dict):
raise ValueError("Update state must be a JSON object.")
for key in ("last_successful_check", "last_failed_check"):
stored = value.get(key)
if stored is not None and (not isinstance(stored, int) or isinstance(stored, bool) or stored < 0):
raise ValueError(f"Update state contains invalid {key}.")
return value
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:
try:
state = _read_update_state()
except (OSError, ValueError):
return True
current = time.time() if now is None else now
successful = _stored_check_time(state, "last_successful_check")
failed = _stored_check_time(state, "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:
if not getattr(sys, "frozen", False):
return
try:
try:
state = _read_update_state()
except ValueError:
# update_state.json is disposable cooldown cache. If it is corrupted,
# replace it with fresh state instead of retrying GitHub on every launch
# until the user manually deletes the file.
state = {}
timestamp = int(time.time() if now is None else now)
if result == "success":
state["last_successful_check"] = timestamp
state.pop("last_failed_check", None)
elif result == "failure":
state["last_failed_check"] = timestamp
state.pop("last_successful_check", None)
elif result == "update_available":
state.pop("last_successful_check", None)
state.pop("last_failed_check", None)
else:
raise ValueError(f"Unknown update check result: {result}")
atomic_write_json(_update_state_path(), state)
except OSError:
pass
def _request(url: str, timeout: float):
request = urllib.request.Request(
url,
headers={
"Accept": "application/vnd.github+json",
"User-Agent": f"NinjaCaptureTool/{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("https://api.github.com/repos/DarkLotus8000/Ninja-Capture-Tool/releases/latest")
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 = "https://github.com/DarkLotus8000/Ninja-Capture-Tool/releases"
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 Capture 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 Capture Tool v{LOCAL_DISPLAY_VERSION} is up to date.")
else:
_record_update_check_result("update_available")
print(f"[Update] Ninja Capture 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 handle_early_update_request(argv: list[str]) -> int | None:
cleanup_relaunched_update_work()
cleanup_stale_update_work()
parser = ErrorArgumentParser(add_help=False, allow_abbrev=False)
group = parser.add_mutually_exclusive_group()
group.add_argument("-a", "--auto-update", action=SingleUseStoreTrueAction)
group.add_argument("-n", "--no-auto-update", action=SingleUseStoreTrueAction)
group.add_argument("-U", "--check-update", action=SingleUseStoreTrueAction)
args, remaining = parser.parse_known_args(argv)
if not args.check_update:
return None
if remaining:
parser.error("--check-update must be used without capture arguments")
return check_update_only()
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 len(parts[0]) != 64 or any(char not in "0123456789abcdefABCDEF" for char in parts[0]):
raise RuntimeError("Release checksum file has an unexpected format.")
if parts[1].lstrip("*") != archive_name:
raise RuntimeError("Release checksum file has an unexpected filename.")
return parts[0].lower()
def _safe_archive_parts(name: str) -> tuple[str, ...]:
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 _validate_release_config(path: Path) -> None:
try:
value = parse_json(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
raise RuntimeError(f"Downloaded release contains invalid config.json: {exc}") from exc
if not isinstance(value, dict):
raise RuntimeError("Downloaded release config.json must contain a JSON object.")
unknown = sorted(set(value) - set(DEFAULT_CONFIG))
if unknown:
raise RuntimeError(f"Downloaded release config.json contains unknown option(s): {', '.join(unknown)}")
config = dict(DEFAULT_CONFIG)
config.update(value)
validate_config(config)
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.")
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 = name.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 normalized:
raise RuntimeError(f"Release manifest contains a duplicate managed path: {name!r}")
if len(digest) != 64 or any(character not in "0123456789abcdefABCDEF" for character in digest):
raise RuntimeError(f"Release manifest contains an invalid SHA-256 for {name!r}.")
normalized[folded] = digest.lower()
return application_version, {name: files[name].lower() for name in files}
def _validate_staged_release_manifest(stage: Path, expected_version: str) -> dict[str, str]:
_validate_staged_release_tree(stage)
application_version, files = _parse_release_manifest(stage / RELEASE_MANIFEST_FILE)
if application_version != expected_version:
raise RuntimeError("Release manifest application version does not match the expected target version.")
actual: set[str] = set()
for path in stage.rglob("*"):
if not path.is_file():
continue
relative = path.relative_to(stage).as_posix()
folded = relative.casefold()
if folded == _RELEASE_MANIFEST_KEY or folded in _PRESERVED_RELEASE_FILE_KEYS:
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 _validate_staged_release_tree(stage: Path) -> None:
"""Reject links, junctions, reparse points, and special files anywhere in stage."""
try:
root_stat = stage.lstat()
except OSError as exc:
raise RuntimeError(f"Could not inspect staged update directory:\n{stage}") from exc
if stat.S_ISLNK(root_stat.st_mode) or _is_reparse_stat(root_stat) or not stat.S_ISDIR(root_stat.st_mode):
raise RuntimeError(
f"Staged update directory must be a real directory, not a symlink, junction, or reparse point:\n{stage}"
)
pending = [stage]
while pending:
directory = pending.pop()
try:
with os.scandir(directory) as entries:
children = list(entries)
except OSError as exc:
raise RuntimeError(f"Could not inspect staged update contents:\n{directory}") from exc
for entry in children:
path = Path(entry.path)
try:
entry_stat = entry.stat(follow_symlinks=False)
except OSError as exc:
raise RuntimeError(f"Could not inspect staged update entry:\n{path}") from exc
if stat.S_ISLNK(entry_stat.st_mode) or _is_reparse_stat(entry_stat):
raise RuntimeError(
f"Staged update contains a symlink, junction, or reparse point:\n{path}"
)
if stat.S_ISDIR(entry_stat.st_mode):
pending.append(path)
elif not stat.S_ISREG(entry_stat.st_mode):
raise RuntimeError(f"Staged update contains an unsupported filesystem entry:\n{path}")
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, and a locally damaged/edited manifest must never make the updater delete
# files speculatively. In either case, simply skip obsolete-file cleanup for this update.
return None
def extract_release_archive(archive_path: Path, destination: Path, release_version: str) -> Path:
expected_root = f"NinjaCaptureTool-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:
clean_name = member.filename.rstrip("/")
if not clean_name:
continue
parts = _safe_archive_parts(clean_name)
if not parts or parts[0] != expected_root:
raise RuntimeError(f"Unexpected release archive root: {member.filename}")
folded = clean_name.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
_ensure_free_space(destination.parent, extracted_size, "extract 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:]
if not relative:
continue
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 = (
"NinjaCaptureTool.exe",
"config.json",
"README.txt",
NCT_LICENSE_RELEASE_FILE,
RELEASE_MANIFEST_FILE,
)
missing = [name for name in required if not (destination / Path(name)).is_file()]
if missing:
raise RuntimeError("Downloaded release is incomplete; missing: " + ", ".join(missing))
runtime = destination / FROZEN_RUNTIME_DIR_NAME
if not runtime.is_dir() or runtime.is_symlink() or next(runtime.iterdir(), None) is None:
raise RuntimeError("Downloaded release is incomplete; runtime directory is missing or empty.")
_validate_release_config(destination / "config.json")
_validate_staged_release_manifest(destination, release_version)
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.")
return destination
def download_release(release: dict[str, Any], work: Path) -> Path:
version = release["version"]
archive_name = f"NinjaCaptureTool-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 Capture 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 _validate_temporary_updater(executable: Path) -> None:
expected = f"Ninja Capture Tool v{LOCAL_DISPLAY_VERSION}"
environment = os.environ.copy()
try:
result = subprocess.run(
[str(executable), UPDATE_INSTALLER_ARGUMENT, "--version"],
cwd=TOOL_DIR,
capture_output=True,
text=True,
timeout=150,
check=False,
env=environment,
)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(
f"Temporary Ninja Capture Tool updater did not respond to --version within 150 seconds: {executable}"
) from exc
except OSError as exc:
raise RuntimeError(f"Temporary Ninja Capture 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 Capture Tool updater failed its version check: {executable}\n{detail}")
if actual != expected:
raise RuntimeError(
"Temporary Ninja Capture 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 = Path(sys.executable).resolve()
if not source.is_file():
raise RuntimeError(f"Ninja Capture Tool executable is missing: {source}")
temporary = work / "NinjaCaptureToolUpdater.exe"
shutil.copy2(source, temporary)
runtime = source.parent / FROZEN_RUNTIME_DIR_NAME
if runtime.exists() or runtime.is_symlink():
if runtime.is_symlink() or not runtime.is_dir():
raise RuntimeError(f"Ninja Capture Tool runtime directory is invalid: {runtime}")
shutil.copytree(runtime, work / FROZEN_RUNTIME_DIR_NAME)
_validate_temporary_updater(temporary)
return temporary
def launch_updater(temporary_updater: Path, stage: Path, argv: list[str], target_version: str) -> None:
# Revalidate the self-copy immediately before handoff. It lives inside this update workspace, so Ninja Capture Tool never needs
# a second shipped executable or the system temporary directory.
_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()
subprocess.Popen(command, cwd=TOOL_DIR, env=environment)
def _update_session_is_active(work: Path) -> bool:
if sys.platform != "win32":
return False
session = work / UPDATE_SESSION_FILE
try:
session_stat = session.lstat()
except FileNotFoundError:
return False
except OSError:
# Metadata that cannot be inspected at all is ambiguous. Leave the
# workspace alone rather than risk deleting 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:
# Corrupt metadata is not a valid live-process identity. Recovery backup
# 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 Capture 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 so callers
# never delete an updater workspace they could not inspect safely.
return _update_work_backup_state(work) is not False
def _validated_cleanup_temp_root() -> Path | None:
temp_root = _update_temp_root()
try:
temp_root.lstat()
except (FileNotFoundError, OSError):
return None
try:
_, validated = _validate_update_temp_root(temp_root, TOOL_DIR)
except RuntimeError:
# Cleanup is optional. If Ninja Capture Tool's temp directory is redirected, on another volume,
# or otherwise unsafe, leave it completely untouched.
return None
return validated
def _validated_cleanup_work(work: Path, temp_root: Path) -> Path | None:
if not _UPDATE_WORK_NAME_RE.fullmatch(work.name) or not _paths_equal(work.parent, temp_root):
return None
try:
work_stat = work.lstat()
except OSError:
return None
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
return Path(os.path.abspath(str(work)))
def cleanup_deferred_update_payload(work: Path, install_dir: Path) -> None:
try:
_, stage = _validate_update_workspace(work / "stage", install_dir)
except RuntimeError:
# The updater is deferring rather than installing. Never perform
# destructive cleanup if the workspace no longer has the exact safe
# shape that was validated for installation.
return
work = stage.parent
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:
child_stat = child.lstat()
if stat.S_ISLNK(child_stat.st_mode) or _is_reparse_stat(child_stat):
continue
if (
child.resolve() == current_executable
or child.name == UPDATE_SESSION_FILE
or (current_executable.parent == work and child.name == FROZEN_RUNTIME_DIR_NAME)
):
continue
_remove_path(child)
except OSError:
# The updater is already deferring safely. Cleanup is best-effort and stale-work cleanup can retry later.
continue
def cleanup_stale_update_work(max_age_seconds: int = 7 * 24 * 60 * 60) -> None:
if max_age_seconds < 0:
return
temp_root = _validated_cleanup_temp_root()
if temp_root is None:
return
cutoff = time.time() - max_age_seconds
try:
candidates = list(temp_root.iterdir())
except OSError:
return
for work in candidates:
work = _validated_cleanup_work(work, temp_root)
if work is None:
continue
try:
if work.lstat().st_mtime > cutoff:
continue
# An unterminated backup means an interrupted/incomplete transaction may need manual recovery.
# Backups from committed installs or fully restored rollbacks are only cleanup debris.
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
# The temporary self-updater runs from inside update_<id>; never remove its directory while it is alive.
if _update_session_is_active(work):
continue
shutil.rmtree(work)
except OSError:
# Startup cleanup is best-effort and must never block normal Ninja Capture Tool use.
continue
cleanup_temp_root_if_empty(temp_root)
def stale_update_recovery_backups(max_age_seconds: int = 7 * 24 * 60 * 60) -> list[Path]:
if max_age_seconds < 0:
return []
temp_root = _validated_cleanup_temp_root()
if temp_root is None:
return []
cutoff = time.time() - max_age_seconds
try:
candidates = list(temp_root.iterdir())
except OSError:
return []
preserved: list[Path] = []
for work in candidates:
work = _validated_cleanup_work(work, temp_root)
if work is None:
continue
try:
if work.lstat().st_mtime > cutoff:
continue
if (
_update_work_backup_state(work) is not True
or _update_session_backup_is_disposable(work)
or _update_session_is_active(work)
):
continue
preserved.append(work)
except OSError:
continue
return sorted(preserved, key=lambda path: path.name.casefold())
def cleanup_relaunched_update_work() -> None:
value = os.environ.pop("NCT_UPDATE_WORK_CLEANUP", None)
if not value:
return
temp_root = _validated_cleanup_temp_root()
if temp_root is None:
return
work = _validated_cleanup_work(Path(value), temp_root)
if work is None:
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
# This flag is set only after a successful handoff or successful rollback. Terminal transaction backups are safe cleanup debris,
# while an unterminated backup remains protected above. The relaunched Ninja Capture Tool can race the final moments of the temporary
# updater exiting, so retry briefly until the updater exits and Windows releases the mapped executable.
for _ in range(50):
if _update_session_is_active(work):
time.sleep(0.1)
continue
try:
shutil.rmtree(work)
break
except FileNotFoundError:
break
except OSError:
time.sleep(0.1)
cleanup_temp_root_if_empty(temp_root)
def handle_automatic_update(
args: argparse.Namespace,
argv: list[str],
configured_auto_update: bool,
) -> int | None:
if os.environ.pop("NCT_SKIP_UPDATE_CHECK_ONCE", None) == "1":
return None
if args.no_auto_update:
return None
enabled = True if args.auto_update else configured_auto_update
if not enabled:
return None
if not getattr(sys, "frozen", False):
if args.auto_update:
print("[Update] Automatic installation is only available in the Windows release executable.", file=sys.stderr)
return None
if not args.auto_update and not automatic_update_check_due():
return None
try:
release = check_for_update()
except KeyboardInterrupt:
print("\nUpdate cancelled.", file=sys.stderr)
return 130
except Exception as exc:
_record_update_check_result("failure")
print_warning(f"Automatic update failed; continuing with v{LOCAL_DISPLAY_VERSION}: {exc}")
return None