Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
1817 lines (1628 loc) · 74.4 KB
/
Copy pathcommon.py
File metadata and controls
1817 lines (1628 loc) · 74.4 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
import errno
import hashlib
import json
import math
import os
import re
import stat
import shutil
import signal
import subprocess
import sys
import threading
import time
import uuid
import urllib.error
import urllib.request
from contextlib import contextmanager
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Any
from urllib.parse import urlsplit
VERSION = "1.5.1"
def display_version(version: str = VERSION) -> str:
parts = version.split(".")
while len(parts) > 2 and parts[-1] == "0":
parts.pop()
return ".".join(parts)
STEAM_CLIENT_VERSION = "1.8.2"
WARFRAME_VERSION_URL = "https://conduit.browse.wf/current-version"
WARFRAME_STEAM_APP_ID = 230410
WARFRAME_STEAM_DEPOT_ID = 230411
STEAM_MANIFEST_MIN_VALID_SIZE = 10 * 1024**3
_WARFRAME_VERSION_RE = re.compile(r"^\d+(?:\.\d+){1,3}$")
ENTRY_SCRIPTS = {
"add_base.py": "Add Base - Ninja Patch Tool",
"verify_base.py": "Verify Base - Ninja Patch Tool",
"make_patch.py": "Make Patch - Ninja Patch Tool",
"apply_patch.py": "Apply Patch - Ninja Patch Tool",
}
RELEASE_MANIFEST_FILE = "data/release_manifest.json"
RELEASE_MANIFEST_VERSION = 1
PRESERVED_RELEASE_FILES = frozenset({"data/index.json", "data/update.json"})
_OPERATION_ACTIVITY_SLOTS = 64
_COLOR_SUPPORT_LOCK = threading.Lock()
_COLOR_SUPPORT_CACHE: dict[int, bool] = {}
_STEAM_APPINFO_CACHE_LOCK = threading.Lock()
_STEAM_APPINFO_CACHE: dict[str, tuple[tuple[int, int], dict[str, object]]] = {}
_STEAM_QUERY_WORKER_ARGUMENT = "--internal-steam-query-worker"
STEAM_QUERY_WORKER_SMOKE_ARGUMENT = "--internal-steam-query-worker-smoke"
STEAM_QUERY_RESULT_PREFIX = "__NINJA_STEAM_RESULT__:"
_SEVERITY_TOKEN_RE = re.compile(r"(?m)^(ERROR:|WARNING:)")
_TRANSIENT_PROGRESS_RE = re.compile(r"(?m)^(\[Update\] )(.+?)( \| )")
def _enable_windows_virtual_terminal(stream) -> bool:
if os.name != "nt":
return True
try:
import ctypes
import msvcrt
handle = msvcrt.get_osfhandle(stream.fileno())
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
mode = ctypes.c_uint32()
if not kernel32.GetConsoleMode(ctypes.c_void_p(handle), ctypes.byref(mode)):
return False
enable_virtual_terminal_processing = 0x0004
if mode.value & enable_virtual_terminal_processing:
return True
return bool(
kernel32.SetConsoleMode(
ctypes.c_void_p(handle),
mode.value | enable_virtual_terminal_processing,
)
)
except (AttributeError, OSError, ValueError):
return False
def console_supports_color(stream) -> bool:
"""Return whether ANSI color is safe for this interactive stream."""
if os.environ.get("NO_COLOR") is not None:
return False
try:
if not stream.isatty():
return False
key = stream.fileno()
except (AttributeError, OSError, ValueError):
return False
with _COLOR_SUPPORT_LOCK:
cached = _COLOR_SUPPORT_CACHE.get(key)
if cached is not None:
return cached
supported = _enable_windows_virtual_terminal(stream)
_COLOR_SUPPORT_CACHE[key] = supported
return supported
def _colored(token: str, color: str) -> str:
return f"{color}{token}\x1b[0m"
def style_console_text(message: str, stream, *, status_tokens: bool = False) -> str:
"""Color semantic console tokens; redirected output remains plain text."""
if not console_supports_color(stream):
return message
def severity_replacement(match: re.Match[str]) -> str:
token = match.group(1)
return _colored(token, "\x1b[31m" if token == "ERROR:" else "\x1b[33m")
styled = _SEVERITY_TOKEN_RE.sub(severity_replacement, message)
if status_tokens:
styled = _TRANSIENT_PROGRESS_RE.sub(
lambda match: match.group(1) + _colored(match.group(2), "\x1b[36m") + match.group(3),
styled,
)
return styled
def print_console(message: object = "", *, file=None, flush: bool = False) -> None:
stream = sys.stdout if file is None else file
print(style_console_text(str(message), stream), file=stream, flush=flush)
def print_error(message: object, *, flush: bool = False) -> None:
print_console(f"ERROR: {message}", file=sys.stderr, flush=flush)
def print_warning(message: object, *, flush: bool = False) -> None:
print_console(f"WARNING: {message}", file=sys.stderr, flush=flush)
def _read_steam_cstring(data: bytes, offset: int) -> tuple[str, int]:
end = data.find(b"\0", offset)
if end < 0:
raise ValueError("Unterminated Steam app-info string.")
try:
value = data[offset:end].decode("utf-8")
except UnicodeDecodeError as exc:
raise ValueError("Steam app-info contains an invalid UTF-8 string.") from exc
return value, end + 1
def _parse_steam_string_table(data: bytes, offset: int) -> list[str]:
if offset < 0 or offset + 4 > len(data):
raise ValueError("Steam app-info string table offset is invalid.")
count = int.from_bytes(data[offset:offset + 4], "little")
offset += 4
if count > 1_000_000:
raise ValueError("Steam app-info string table is implausibly large.")
result: list[str] = []
for _ in range(count):
value, offset = _read_steam_cstring(data, offset)
result.append(value)
return result
def _parse_steam_binary_vdf(data: bytes, *, string_table: list[str] | None = None) -> dict[str, object]:
offset = 0
def read(size: int) -> bytes:
nonlocal offset
end = offset + size
if size < 0 or end > len(data):
raise ValueError("Steam app-info binary VDF is truncated.")
value = data[offset:end]
offset = end
return value
def read_key() -> str:
nonlocal offset
if string_table is None:
value, offset = _read_steam_cstring(data, offset)
return value
index = int.from_bytes(read(4), "little")
if index >= len(string_table):
raise ValueError("Steam app-info binary VDF references an invalid string-table key.")
return string_table[index]
def read_object() -> dict[str, object]:
nonlocal offset
result: dict[str, object] = {}
while True:
value_type = read(1)[0]
if value_type == 0x08:
return result
key = read_key()
if value_type == 0x00:
value: object = read_object()
elif value_type == 0x01:
value, offset = _read_steam_cstring(data, offset)
elif value_type == 0x02:
value = int.from_bytes(read(4), "little", signed=True)
elif value_type == 0x03:
import struct
value = struct.unpack("<f", read(4))[0]
elif value_type == 0x04:
value = int.from_bytes(read(4), "little")
elif value_type == 0x05:
raw = bytearray()
while True:
unit = read(2)
if unit == b"\0\0":
break
raw.extend(unit)
try:
value = bytes(raw).decode("utf-16-le")
except UnicodeDecodeError as exc:
raise ValueError("Steam app-info contains an invalid UTF-16 string.") from exc
elif value_type == 0x06:
value = int.from_bytes(read(4), "little")
elif value_type == 0x07:
value = int.from_bytes(read(8), "little")
elif value_type == 0x0A:
value = int.from_bytes(read(8), "little", signed=True)
elif value_type == 0x0B:
value = read(1)[0]
elif value_type == 0x0C:
value = 0
elif value_type == 0x0D:
value = 1
else:
raise ValueError(f"Unsupported Steam app-info binary VDF type 0x{value_type:02X}.")
result[key] = value
parsed = read_object()
if offset != len(data) and any(byte != 0 for byte in data[offset:]):
raise ValueError("Steam app-info binary VDF has unexpected trailing data.")
return parsed
def _find_steam_appinfo_path() -> Path:
candidates: list[Path] = []
override = os.environ.get("STEAM_PATH")
if override:
candidates.append(Path(override).expanduser())
if sys.platform == "win32":
try:
import winreg
for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
for key_name in (r"Software\Valve\Steam", r"Software\WOW6432Node\Valve\Steam"):
try:
with winreg.OpenKey(hive, key_name) as key:
for value_name in ("SteamPath", "InstallPath", "SteamExe"):
try:
raw, _ = winreg.QueryValueEx(key, value_name)
except OSError:
continue
if isinstance(raw, str) and raw.strip():
path = Path(raw.strip())
candidates.append(path.parent if path.suffix.casefold() == ".exe" else path)
except OSError:
continue
except ImportError:
pass
for variable in ("ProgramFiles(x86)", "ProgramFiles"):
root = os.environ.get(variable)
if root:
candidates.append(Path(root) / "Steam")
else:
home = Path.home()
candidates.extend((home / ".steam" / "steam", home / ".local" / "share" / "Steam"))
seen: set[str] = set()
for root in candidates:
key = str(root).casefold()
if key in seen:
continue
seen.add(key)
path = root / "appcache" / "appinfo.vdf"
if path.is_file():
return path
raise RuntimeError("Steam app-info cache was not found.")
def _optional_nonnegative_int(value: object) -> int | None:
if value is None:
return None
try:
parsed = int(str(value).strip())
except (TypeError, ValueError):
return None
return parsed if parsed >= 0 else None
def _steam_numeric_field(mapping: dict[str, object], key: str, label: str) -> int | None:
if key not in mapping or mapping[key] is None:
return None
parsed = _optional_nonnegative_int(mapping[key])
if parsed is None:
raise RuntimeError(f"Steam app info contains an invalid {label}.")
return parsed
def summarize_steam_live_query_error(error: str | None) -> str:
text = (error or "").strip()
lowered = text.casefold()
if "pysteam-client" in lowered or "no module named 'steam'" in lowered or 'no module named "steam"' in lowered:
return "Steam client dependency missing"
if "timed out" in lowered or "timeout" in lowered:
return "query timed out"
if "anonymous steam login failed" in lowered:
return "anonymous Steam login failed"
if "access token" in lowered:
return "Steam access token unavailable"
if "worker" in lowered and ("tagged result" in lowered or "invalid json" in lowered or "invalid result schema" in lowered):
return "Steam query worker failed"
return "query failed"
def _steam_manifest_status(size: int | None, download_size: int | None) -> str:
# Never trust a changed GID by itself. Warframe depot 230411 briefly published
# the empty manifest 5112463999164762556 on 2026-02-11 before DE replaced it.
# A plausible Warframe base is far larger than 10 GiB, so anything below that
# threshold is invalid. An explicit zero download size is also invalid even if the
# reported installed size looks plausible.
if download_size == 0:
return "invalid"
if size is not None:
return "valid" if size >= STEAM_MANIFEST_MIN_VALID_SIZE else "invalid"
return "unvalidated"
def _steam_manifest_from_app_data(
app_data: dict[str, object],
*,
source_kind: str,
) -> dict[str, object]:
if source_kind not in {"live", "cache"}:
raise ValueError("Steam manifest source kind must be 'live' or 'cache'.")
root = app_data.get("appinfo") if isinstance(app_data.get("appinfo"), dict) else app_data
depots = root.get("depots") if isinstance(root, dict) else None
depot = depots.get(str(WARFRAME_STEAM_DEPOT_ID)) if isinstance(depots, dict) else None
manifests = depot.get("manifests") if isinstance(depot, dict) else None
public = manifests.get("public") if isinstance(manifests, dict) else None
if isinstance(public, (str, int)):
public = {"gid": public}
if not isinstance(public, dict):
raise RuntimeError(f"Warframe depot {WARFRAME_STEAM_DEPOT_ID} has no public manifest in Steam app info.")
try:
manifest_id = int(str(public["gid"]).strip())
except (KeyError, TypeError, ValueError):
raise RuntimeError("Steam app info contains an invalid Warframe public manifest ID.") from None
if manifest_id <= 0 or manifest_id > 0xFFFFFFFFFFFFFFFF:
raise RuntimeError("Steam app info contains an out-of-range Warframe public manifest ID.")
size = _steam_numeric_field(public, "size", "Warframe public manifest size")
download_size = _steam_numeric_field(public, "download", "Warframe public manifest download size")
return {
"manifest_id": manifest_id,
"size": size,
"status": _steam_manifest_status(size, download_size),
"source_kind": source_kind,
}
def read_steam_cached_public_manifest(appinfo_path: Path | None = None) -> dict[str, object]:
"""Read Warframe's public depot manifest from Steam's local app-info cache."""
path = _find_steam_appinfo_path() if appinfo_path is None else appinfo_path
try:
stat_before = path.stat()
except OSError as exc:
raise RuntimeError(f"Could not stat Steam app-info cache {path}: {exc}") from exc
signature = (stat_before.st_size, stat_before.st_mtime_ns)
cache_key = str(path.resolve(strict=False))
with _STEAM_APPINFO_CACHE_LOCK:
cached = _STEAM_APPINFO_CACHE.get(cache_key)
if cached is not None and cached[0] == signature:
return dict(cached[1])
try:
data = path.read_bytes()
except OSError as exc:
raise RuntimeError(f"Could not read Steam app-info cache {path}: {exc}") from exc
if len(data) < 8:
raise RuntimeError("Steam app-info cache is truncated.")
magic = int.from_bytes(data[0:4], "little")
if magic == 0x07564429:
if len(data) < 16:
raise RuntimeError("Steam app-info v41 header is truncated.")
string_table_offset = int.from_bytes(data[8:16], "little")
string_table = _parse_steam_string_table(data, string_table_offset)
offset = 16
entries_end = string_table_offset
elif magic == 0x07564428:
string_table = None
offset = 8
entries_end = len(data)
else:
raise RuntimeError(f"Unsupported Steam app-info format 0x{magic:08X}.")
while offset + 4 <= entries_end:
entry_start = offset
app_id = int.from_bytes(data[offset:offset + 4], "little")
offset += 4
if app_id == 0:
break
if offset + 4 > entries_end:
raise RuntimeError("Steam app-info entry header is truncated.")
entry_size = int.from_bytes(data[offset:offset + 4], "little")
entry_end = entry_start + 8 + entry_size
if entry_size < 60 or entry_end > entries_end:
raise RuntimeError("Steam app-info entry size is invalid.")
if app_id != WARFRAME_STEAM_APP_ID:
offset = entry_end
continue
payload = data[entry_start + 68:entry_end]
try:
app_data = _parse_steam_binary_vdf(payload, string_table=string_table)
except ValueError as exc:
raise RuntimeError(f"Could not parse Warframe Steam app info: {exc}") from exc
result = _steam_manifest_from_app_data(app_data, source_kind="cache")
# Cache only a stable snapshot. If Steam rewrote appinfo.vdf while it was
# being read, return what we parsed but force a fresh read next time.
try:
stat_after = path.stat()
except OSError:
stat_after = None
if stat_after is not None and (stat_after.st_size, stat_after.st_mtime_ns) == signature:
with _STEAM_APPINFO_CACHE_LOCK:
_STEAM_APPINFO_CACHE[cache_key] = (signature, dict(result))
return result
raise RuntimeError(f"Warframe app {WARFRAME_STEAM_APP_ID} was not found in Steam app info.")
def query_steam_public_manifest(timeout: float = 8.0) -> dict[str, object]:
"""Query Valve's Steam network directly through anonymous Steam product info (PICS)."""
try:
from steam.client import SteamClient
except ImportError as exc:
raise RuntimeError(f"pysteam-client[client] {STEAM_CLIENT_VERSION} is required for live Steam manifest queries") from exc
request_timeout = max(1, int(round(timeout)))
def app_data_from_product_info(product_info: object) -> dict[str, object]:
if not isinstance(product_info, dict):
raise RuntimeError("Steam live query returned no product information")
apps = product_info.get("apps")
app_data = apps.get(WARFRAME_STEAM_APP_ID) if isinstance(apps, dict) else None
if app_data is None and isinstance(apps, dict):
app_data = apps.get(str(WARFRAME_STEAM_APP_ID))
if not isinstance(app_data, dict):
raise RuntimeError(f"Steam live query returned no data for app {WARFRAME_STEAM_APP_ID}")
return app_data
client = SteamClient()
try:
result = client.anonymous_login()
try:
result_code = int(result)
except (TypeError, ValueError):
result_code = int(getattr(result, "value", 0))
if result_code != 1:
raise RuntimeError(f"anonymous Steam login failed ({result})")
# Warframe's public app info normally needs no access token. Avoid the
# extra PICS token request unless Valve explicitly marks the response as
# missing one; this keeps the common path faster and more predictable.
app_data = app_data_from_product_info(
client.get_product_info(
apps=[WARFRAME_STEAM_APP_ID],
auto_access_tokens=False,
timeout=request_timeout,
)
)
if app_data.get("_missing_token"):
app_data = app_data_from_product_info(
client.get_product_info(
apps=[WARFRAME_STEAM_APP_ID],
auto_access_tokens=True,
timeout=request_timeout,
)
)
if app_data.get("_missing_token"):
raise RuntimeError(f"Steam live query requires an access token for app {WARFRAME_STEAM_APP_ID}")
return _steam_manifest_from_app_data(app_data, source_kind="live")
except RuntimeError:
raise
except Exception as exc:
raise RuntimeError(str(exc) or exc.__class__.__name__) from exc
finally:
try:
if getattr(client, "logged_on", False):
client.logout()
except Exception:
pass
try:
client.disconnect()
except Exception:
pass
def _steam_query_worker_timeout(argv: list[str] | None = None) -> float | None:
args = list(sys.argv[1:] if argv is None else argv)
if not args or args[0] != _STEAM_QUERY_WORKER_ARGUMENT:
return None
if len(args) != 2:
raise ValueError("Steam query worker requires exactly one timeout argument")
try:
timeout = float(args[1])
except ValueError as exc:
raise ValueError("Steam query worker timeout must be numeric") from exc
if not math.isfinite(timeout) or not 1.0 <= timeout <= 60.0:
raise ValueError("Steam query worker timeout must be between 1 and 60 seconds")
return timeout
def _validate_steam_worker_info(value: object) -> dict[str, object]:
if not isinstance(value, dict):
raise ValueError("Steam query worker returned an invalid info object")
expected_keys = {"manifest_id", "size", "status", "source_kind"}
if set(value) != expected_keys:
raise ValueError("Steam query worker returned an invalid info schema")
manifest_id = value.get("manifest_id")
if not isinstance(manifest_id, int) or isinstance(manifest_id, bool) or not (0 < manifest_id <= 0xFFFFFFFFFFFFFFFF):
raise ValueError("Steam query worker returned an invalid manifest ID")
size = value.get("size")
if size is not None and (not isinstance(size, int) or isinstance(size, bool) or size < 0):
raise ValueError("Steam query worker returned an invalid size")
status = value.get("status")
if status not in {"valid", "invalid", "unvalidated"}:
raise ValueError("Steam query worker returned an invalid manifest status")
if size is None and status == "valid":
raise ValueError("Steam query worker returned inconsistent manifest status")
if isinstance(size, int) and size < STEAM_MANIFEST_MIN_VALID_SIZE and status != "invalid":
raise ValueError("Steam query worker returned inconsistent manifest status")
if isinstance(size, int) and size >= STEAM_MANIFEST_MIN_VALID_SIZE and status == "unvalidated":
raise ValueError("Steam query worker returned inconsistent manifest status")
if value.get("source_kind") != "live":
raise ValueError("Steam query worker returned an unexpected source kind")
return dict(value)
def _emit_steam_query_worker_payload(payload: dict[str, object]) -> None:
sys.stdout.write(STEAM_QUERY_RESULT_PREFIX + json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n")
sys.stdout.flush()
def handle_steam_query_worker_request(argv: list[str] | None = None) -> int | None:
"""Run a hidden Steam worker mode when this process was spawned internally."""
args = list(sys.argv[1:] if argv is None else argv)
if not args or args[0] not in {_STEAM_QUERY_WORKER_ARGUMENT, STEAM_QUERY_WORKER_SMOKE_ARGUMENT}:
return None
if args[0] == STEAM_QUERY_WORKER_SMOKE_ARGUMENT:
if len(args) != 1:
_emit_steam_query_worker_payload({"ok": False, "error": "Steam worker smoke mode accepts no arguments"})
return 2
try:
from steam.client import SteamClient
if SteamClient is None:
raise ImportError("steam.client.SteamClient is unavailable")
except BaseException as exc:
_emit_steam_query_worker_payload({"ok": False, "error": str(exc) or exc.__class__.__name__})
return 1
_emit_steam_query_worker_payload({"ok": True, "smoke": "steam-import"})
return 0
try:
timeout = _steam_query_worker_timeout(args)
except ValueError as exc:
_emit_steam_query_worker_payload({"ok": False, "error": str(exc)})
return 2
assert timeout is not None
try:
payload = {"ok": True, "info": query_steam_public_manifest(timeout=timeout)}
except BaseException as exc:
payload = {"ok": False, "error": str(exc) or exc.__class__.__name__}
_emit_steam_query_worker_payload(payload)
return 0
def _attach_steam_worker_kill_job(process: subprocess.Popen) -> None:
"""Tie a Windows Steam worker to this parent with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE."""
if sys.platform != "win32":
return
import ctypes
from ctypes import wintypes
class JobObjectBasicLimitInformation(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_longlong),
("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", wintypes.DWORD),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t),
("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD),
]
class IoCounters(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ctypes.c_ulonglong),
("WriteOperationCount", ctypes.c_ulonglong),
("OtherOperationCount", ctypes.c_ulonglong),
("ReadTransferCount", ctypes.c_ulonglong),
("WriteTransferCount", ctypes.c_ulonglong),
("OtherTransferCount", ctypes.c_ulonglong),
]
class JobObjectExtendedLimitInformation(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", JobObjectBasicLimitInformation),
("IoInfo", IoCounters),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
kernel32.CreateJobObjectW.restype = wintypes.HANDLE
kernel32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
kernel32.SetInformationJobObject.restype = wintypes.BOOL
kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
job = kernel32.CreateJobObjectW(None, None)
if not job:
raise ctypes.WinError(ctypes.get_last_error())
try:
info = JobObjectExtendedLimitInformation()
info.BasicLimitInformation.LimitFlags = 0x00002000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
raise ctypes.WinError(ctypes.get_last_error())
process_handle = getattr(process, "_handle", None)
if process_handle is None:
raise RuntimeError("Steam query worker process handle is unavailable")
if not kernel32.AssignProcessToJobObject(job, wintypes.HANDLE(int(process_handle))):
raise ctypes.WinError(ctypes.get_last_error())
except Exception:
kernel32.CloseHandle(job)
raise
setattr(process, "_ninja_steam_job_handle", job)
def _close_steam_worker_kill_job(process: subprocess.Popen) -> None:
if sys.platform != "win32":
return
handle = getattr(process, "_ninja_steam_job_handle", None)
if not handle:
return
setattr(process, "_ninja_steam_job_handle", None)
try:
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
kernel32.CloseHandle(handle)
except (AttributeError, OSError, TypeError, ValueError):
pass
def start_steam_query_subprocess(timeout: float = 8.0, *, entry_script: Path | None = None) -> subprocess.Popen:
"""Start a killable child process that performs only the direct Steam live query."""
worker_timeout = max(1.0, min(float(timeout), 60.0))
if getattr(sys, "frozen", False):
command = [sys.executable]
else:
script = (entry_script or Path(sys.argv[0])).resolve()
command = [sys.executable, str(script)]
command.extend((_STEAM_QUERY_WORKER_ARGUMENT, f"{worker_timeout:g}"))
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if sys.platform == "win32" else 0
process = subprocess.Popen(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
creationflags=creationflags,
)
try:
_attach_steam_worker_kill_job(process)
except Exception:
# Parent-death cleanup is additional hardening, not a requirement for
# the live query. The normal deadline/termination path still owns the
# worker if Windows or a host Job Object policy rejects assignment.
pass
return process
def collect_steam_query_subprocess(process: subprocess.Popen) -> tuple[dict[str, object] | None, str | None]:
"""Collect and validate a completed Steam worker result."""
if process.poll() is None:
raise RuntimeError("Steam query worker is still running.")
try:
stdout, _ = process.communicate(timeout=0.25)
except subprocess.TimeoutExpired as exc:
raise RuntimeError("Steam query worker did not close its output pipe.") from exc
finally:
_close_steam_worker_kill_job(process)
tagged = [
line[len(STEAM_QUERY_RESULT_PREFIX):].strip()
for line in (stdout or "").splitlines()
if line.startswith(STEAM_QUERY_RESULT_PREFIX)
]
if not tagged:
return None, f"Steam query worker exited with code {process.returncode} without returning a tagged result"
try:
payload = json.loads(tagged[-1])
except json.JSONDecodeError:
return None, "Steam query worker returned invalid JSON"
if not isinstance(payload, dict):
return None, "Steam query worker returned an invalid result schema"
if payload.get("ok") is True:
if set(payload) != {"ok", "info"}:
return None, "Steam query worker returned an invalid result schema"
try:
return _validate_steam_worker_info(payload.get("info")), None
except ValueError as exc:
return None, str(exc)
if payload.get("ok") is not False or set(payload) != {"ok", "error"}:
return None, "Steam query worker returned an invalid result schema"
error = payload.get("error")
if not isinstance(error, str) or not error.strip():
return None, "Steam query worker failed without a valid error message"
return None, error.strip()
def terminate_steam_query_subprocess(process: subprocess.Popen, *, timeout: float = 1.0) -> None:
"""Hard-stop an internal Steam worker and reap it."""
if process.poll() is not None:
try:
process.communicate(timeout=0.1)
except (OSError, subprocess.TimeoutExpired):
pass
finally:
_close_steam_worker_kill_job(process)
return
try:
process.terminate()
except OSError:
pass
try:
process.wait(timeout=max(0.0, timeout))
except subprocess.TimeoutExpired:
try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=0.5)
except (OSError, subprocess.TimeoutExpired):
pass
try:
process.communicate(timeout=0.1)
except (OSError, subprocess.TimeoutExpired):
pass
finally:
_close_steam_worker_kill_job(process)
def steam_manifest_with_cache_fallback(
live_info: dict[str, object] | None,
live_error: str | None,
) -> tuple[dict[str, object] | None, str | None]:
"""Use the local Steam cache only when the direct Steam worker failed."""
if live_info is not None:
return live_info, None
error = live_error or "unknown Steam query failure"
try:
cached = read_steam_cached_public_manifest()
except Exception as cache_exc:
return None, f"direct Steam live query failed: {error}; local Steam cache fallback failed: {cache_exc}"
cached = dict(cached)
cached["live_error"] = error
return cached, None
class ActiveOperationError(RuntimeError):
pass
def operation_activity_lock_path(install_dir: Path) -> Path:
return install_dir.resolve() / "data" / ".operation.lock"
def _open_operation_activity_file(install_dir: Path):
path = operation_activity_lock_path(install_dir)
path.parent.mkdir(parents=True, exist_ok=True)
file = path.open("a+b")
file.seek(0, 2)
size = file.tell()
if size < _OPERATION_ACTIVITY_SLOTS:
file.write(b"\0" * (_OPERATION_ACTIVITY_SLOTS - size))
file.flush()
return file
def _try_lock_activity_range(file, offset: int, length: int) -> bool:
import msvcrt
file.seek(offset)
try:
msvcrt.locking(file.fileno(), msvcrt.LK_NBLCK, length)
except OSError as exc:
if exc.errno in {errno.EACCES, errno.EDEADLK}:
return False
raise
return True
def _unlock_activity_range(file, offset: int, length: int) -> None:
import msvcrt
file.seek(offset)
msvcrt.locking(file.fileno(), msvcrt.LK_UNLCK, length)
@contextmanager
def operation_activity_lock(install_dir: Path | None = None):
# The updater needs an installation-wide exclusive gate, while normal Ninja Patch Tool operations must still be allowed to run
# concurrently. Windows byte-range locks provide exactly that: every operation owns one byte and the updater locks
# the whole range. The OS releases these locks automatically if a process crashes or is forcibly terminated.
if sys.platform != "win32":
yield
return
root = TOOL_DIR if install_dir is None else install_dir
file = _open_operation_activity_file(root)
slot: int | None = None
try:
for candidate in range(_OPERATION_ACTIVITY_SLOTS):
if _try_lock_activity_range(file, candidate, 1):
slot = candidate
break
if slot is None:
raise RuntimeError(
"Ninja Patch Tool is currently being updated or too many operations are active. "
"Try again after the other activity finishes."
)
yield
finally:
if slot is not None:
try:
_unlock_activity_range(file, slot, 1)
except OSError:
pass
file.close()
@contextmanager
def exclusive_operation_activity_lock(install_dir: Path):
if sys.platform != "win32":
yield
return
file = _open_operation_activity_file(install_dir)
locked = False
try:
locked = _try_lock_activity_range(file, 0, _OPERATION_ACTIVITY_SLOTS)
if not locked:
raise ActiveOperationError("Another Ninja Patch Tool operation is active.")
yield
finally:
if locked:
try:
_unlock_activity_range(file, 0, _OPERATION_ACTIVITY_SLOTS)
except OSError:
pass
file.close()
def windows_user_sid() -> str:
if sys.platform != "win32":
raise RuntimeError("Windows user identity is only available on Windows.")
import ctypes
from ctypes import wintypes
token_query = 0x0008
token_user = 1
error_insufficient_buffer = 122
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
kernel32.CloseHandle.restype = wintypes.BOOL
kernel32.LocalFree.argtypes = [ctypes.c_void_p]
kernel32.LocalFree.restype = ctypes.c_void_p
advapi32.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
advapi32.OpenProcessToken.restype = wintypes.BOOL
advapi32.GetTokenInformation.argtypes = [
wintypes.HANDLE, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)
]
advapi32.GetTokenInformation.restype = wintypes.BOOL
advapi32.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)]
advapi32.ConvertSidToStringSidW.restype = wintypes.BOOL
token = wintypes.HANDLE()
if not advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), token_query, ctypes.byref(token)):
raise ctypes.WinError(ctypes.get_last_error())
try:
size = wintypes.DWORD()
ctypes.set_last_error(0)
advapi32.GetTokenInformation(token, token_user, None, 0, ctypes.byref(size))
error = ctypes.get_last_error()
if size.value == 0 or error not in {0, error_insufficient_buffer}:
raise ctypes.WinError(error)
buffer = ctypes.create_string_buffer(size.value)
if not advapi32.GetTokenInformation(token, token_user, buffer, size.value, ctypes.byref(size)):
raise ctypes.WinError(ctypes.get_last_error())
class SidAndAttributes(ctypes.Structure):
_fields_ = [("sid", ctypes.c_void_p), ("attributes", wintypes.DWORD)]
token_user_data = ctypes.cast(buffer, ctypes.POINTER(SidAndAttributes)).contents
text = wintypes.LPWSTR()
if not advapi32.ConvertSidToStringSidW(token_user_data.sid, ctypes.byref(text)):
raise ctypes.WinError(ctypes.get_last_error())
try:
if not text.value:
raise RuntimeError("Windows returned an empty user SID.")
return text.value
finally:
kernel32.LocalFree(ctypes.cast(text, ctypes.c_void_p))
finally:
kernel32.CloseHandle(token)
def get_tool_dir() -> Path:
if getattr(sys, "frozen", False):
return Path(sys.executable).resolve().parent
return Path(__file__).resolve().parent
TOOL_DIR = get_tool_dir()
DATA_DIR = TOOL_DIR / "data"
INDEX_FILE = DATA_DIR / "index.json"
TEMP_ROOT = TOOL_DIR / "temp"
# Files intentionally excluded from installation identity and patches.
IGNORED_FILENAMES = {"launcher.zip", "launcher.exe", "remotecrashsender.exe"}
IGNORED_ROOT_FILENAMES = {
"bootstrapper setup.exe",
"dwmapi.dll",
"launch with openwf.bat",
"sideloadify-cli.exe",
"sideloadify.exe",
"version.dll",
"wtsapi32.dll",
}
IGNORED_ROOT_DIRECTORIES = {"openwf"}
_PROCESS_LOCKS_GUARD = threading.Lock()
_PROCESS_LOCKS: set[str] = set()
def sha256_file(path: Path) -> str:
with path.open("rb") as file:
return hashlib.file_digest(file, "sha256").hexdigest()
def is_ignored_file(path: Path, root: Path | None = None) -> bool:
if path.name.casefold() in IGNORED_FILENAMES:
return True
if root is not None:
try:
relative = path.relative_to(root)
except ValueError:
return False
elif path.is_absolute():
return False
else:
relative = path
parts = relative.parts
if not parts:
return False
if len(parts) == 1 and parts[0].casefold() in IGNORED_ROOT_FILENAMES:
return True
return parts[0].casefold() in IGNORED_ROOT_DIRECTORIES
def validate_warframe_installation(path: Path, label: str) -> bool:
if (path / "Cache.Windows").is_dir() and (path / "Tools").is_dir() and (path / "Warframe.x64.exe").is_file():
return True
print_error(f'{label} directory is not a Warframe installation root:\n{path}\nExpected at least Cache.Windows, Tools, and Warframe.x64.exe directly inside it.')
return False
def natural_sort_key(value: str):
return tuple((0, int(part)) if part.isdigit() else (1, part.casefold()) for part in re.split(r"(\d+)", value) if part)
def base_name_sort_key(value: str):
match = re.fullmatch(r"(?i)(pre-)?u(\d+(?:\.\d+)*)", value.strip())
if match is None:
return natural_sort_key(value), 1, (), 0
version = tuple(int(part) for part in match.group(2).split("."))
return natural_sort_key("U"), 0, version, 0 if match.group(1) else 1
def parse_version(value: str) -> tuple[int, ...]:
text = value.strip()
if text[:1].lower() == "v":
text = text[1:]
parts = text.split(".")
if len(parts) < 2 or any(not part.isdigit() for part in parts):
raise ValueError(f"Invalid version: {value!r}")
return tuple(int(part) for part in parts)
def compare_versions(left: str, right: str) -> int:
left_parts = parse_version(left)
right_parts = parse_version(right)
width = max(len(left_parts), len(right_parts))
padded_left = left_parts + (0,) * (width - len(left_parts))
padded_right = right_parts + (0,) * (width - len(right_parts))
return (padded_left > padded_right) - (padded_left < padded_right)
def root_sha256_from_files(files: dict[str, dict[str, Any]]) -> str:
root_hash = hashlib.sha256()
for relative in sorted(files):
info = files[relative]
root_hash.update(relative.encode("utf-8") + b"\0" + str(info["size"]).encode("ascii") + b"\0" + info["sha256"].lower().encode("ascii") + b"\n")
return root_hash.hexdigest()