Repository navigation
Expand file tree
/
Copy pathpkgviewer.py
More file actions
10694 lines (10019 loc) · 417 KB
/
Copy pathpkgviewer.py
File metadata and controls
10694 lines (10019 loc) · 417 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
"""PKG Viewer - PS2/PS3 (ISO) + PS3 (PKG/folder) + PS4 + PS5 (FIH/CNT) + Switch (NSP/PFS0, XCI/HFS0). Clean dark UI (tkinter) + CLI --info mode."""
import io
import json
import os
import struct
import sys
APP_VERSION = "v1.20.1-pre1" # bump on every release - the updater compares this
UPDATE_REPO = "Loopayeh/pkg-viewer"
SUPPORT_ADDR = "0x839a30D52Ef7D2b53e818b9931efd7FE6F472e50" # USDT (BEP-20)
SUPPORT_URL = ("https://link.trustwallet.com/send?coin=20000714&address="
"0x839a30D52Ef7D2b53e818b9931efd7FE6F472e50"
"&token_id=0x55d398326f99059fF775485246999027B3197955")
def _settings_path():
"""User settings file. Never raises."""
try:
if sys.platform.startswith("win"):
base = os.environ.get("APPDATA") or os.path.expanduser("~")
d = os.path.join(base, "PKGViewer")
else:
d = os.path.join(os.path.expanduser("~"), ".config", "pkgviewer")
os.makedirs(d, exist_ok=True)
return os.path.join(d, "settings.json")
except Exception:
return None
def _load_settings():
try:
p = _settings_path()
if p and os.path.isfile(p):
with open(p, "r", encoding="utf-8-sig") as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except Exception:
pass
return {}
def _save_settings(patch):
try:
p = _settings_path()
if not p:
return
d = _load_settings()
d.update(patch or {})
with open(p, "w", encoding="utf-8") as f:
json.dump(d, f)
except Exception:
pass
# ---------------- rounded buttons (PIL face on a real tk.Button) ----------------
try:
import tkinter as _tk
from tkinter import font as _tkfont
from tkinter import ttk as _ttk
_TK_OK = True
except ImportError:
_tk = None
_tkfont = None
_ttk = None
_TK_OK = False
try:
from PIL import Image as _PILImage, ImageDraw as _PILDraw, ImageTk as _PILImageTk
_PIL_OK = True
except ImportError:
_PILImage = _PILDraw = _PILImageTk = None
_PIL_OK = False
_RBTN_RADIUS = 4
_RBTN_PAD = {"accent": (16, 9), "ghost": (12, 7), "mini": (10, 4),
"mini_accent": (10, 4)}
_RBTN_FACE = {
"accent": {"face": "#4f8ef7", "hover": "#6fa8ff", "pressed": "#3b70c9",
"fg": "#171717", "disabled_face": "#2a2a2a", "disabled_fg": "#8b93a5"},
"ghost": {"face": "#404040", "hover": "#2c3342", "pressed": "#333a44",
"fg": "#f1f3f8", "disabled_face": "#2a2a2a", "disabled_fg": "#8b93a5"},
"mini": {"face": "#404040", "hover": "#2c3342", "pressed": "#333a44",
"fg": "#f1f3f8", "disabled_face": "#2a2a2a", "disabled_fg": "#8b93a5"},
"mini_accent": {"face": "#4f8ef7", "hover": "#6fa8ff", "pressed": "#3b70c9",
"fg": "#171717", "disabled_face": "#2a2a2a", "disabled_fg": "#8b93a5"},
}
_RBTN_DEFAULT_BG = "#171717"
_RBTN_DEFAULT_FONT = ("Segoe UI", 10)
def _rbtn_kind_of(style):
if style and "Ghost" in style:
return "ghost"
return "accent"
def _rbtn_face_image(w, h, radius, color):
s = 3
img = _PILImage.new("RGBA", (w * s, h * s), (0, 0, 0, 0))
_PILDraw.Draw(img).rounded_rectangle([0, 0, w * s - 1, h * s - 1],
radius=radius * s, fill=color)
return img.resize((w, h), _PILImage.LANCZOS)
class RoundedButton(_tk.Button):
"""tk.Button with a rounded-rectangle face rendered by PIL.
Drop-in for the ttk.Button call sites in run_gui: same text /
textvariable / command options, same pack/grid/place API, plus
.config(text=...), .config(style=...) and .config(state=...).
See mkbtn for the PIL-missing fallback.
"""
def __init__(self, parent, text="", textvariable=None, style="Accent.TButton",
kind=None, command=None, bg=_RBTN_DEFAULT_BG,
font=_RBTN_DEFAULT_FONT, radius=_RBTN_RADIUS,
cursor="hand2", **kw):
self._kind = kind or _rbtn_kind_of(style)
self._text = text
self._var = textvariable
self._radius = radius
self._font = _tkfont.Font(font=font)
self._padx, self._pady = _RBTN_PAD[self._kind]
self._pal = _RBTN_FACE[self._kind]
self._imgs = {}
self._pil = {}
self._pressed = False
self._hovered = False
super().__init__(parent, text=text, textvariable=textvariable,
font=font, fg=self._pal["fg"],
activeforeground=self._pal["fg"],
disabledforeground=self._pal["disabled_fg"],
bg=bg, activebackground=bg,
borderwidth=0, relief="flat", highlightthickness=0,
overrelief="flat", padx=0, pady=0, cursor=cursor,
compound="center", command=command, **kw)
self._refresh()
self.bind("<Enter>", lambda _e: self._set_hover(True))
self.bind("<Leave>", lambda _e: self._set_hover(False))
self.bind("<ButtonPress-1>", lambda _e: self._set_pressed(True))
self.bind("<ButtonRelease-1>", lambda _e: self._set_pressed(False))
self._watch_var()
# -- internals --
def _watch_var(self):
if self._var is not None:
try:
self._var.trace_add("write", lambda *_a: self._refresh())
except Exception:
pass
def _label(self):
try:
if self._var is not None:
return self._var.get()
except Exception:
pass
return self._text
def _refresh(self):
label = self._label()
tw = self._font.measure(label) if label else 0
lh = self._font.metrics("linespace")
w = max(tw + 2 * self._padx, 2 * self._radius + 12)
h = lh + 2 * self._pady
pal = self._pal
self._pil = {k: _rbtn_face_image(w, h, self._radius, pal[c])
for k, c in (("normal", "face"), ("hover", "hover"),
("pressed", "pressed"),
("disabled", "disabled_face"))}
self._imgs = {k: _PILImageTk.PhotoImage(im)
for k, im in self._pil.items()}
try:
super().configure(width=w, height=h)
except Exception:
pass
self._show(self._current_face())
def _current_face(self):
try:
st = super().cget("state")
except Exception:
st = "normal"
if st == "disabled":
return "disabled"
if self._pressed:
return "pressed"
if self._hovered:
return "hover"
return "normal"
def _show(self, which):
try:
super().configure(image=self._imgs[which])
except Exception:
pass
def _set_hover(self, on):
self._hovered = on
self._show(self._current_face())
def _set_pressed(self, on):
self._pressed = on
self._show(self._current_face())
# -- ttk-compatible option API --
def configure(self, cnf=None, **kw):
if cnf is None and not kw:
return super().configure()
if isinstance(cnf, dict):
kw = dict(cnf, **kw)
cnf = None
if isinstance(cnf, str) and not kw:
if cnf == "text":
return self._text
return super().configure(cnf)
opts = dict(kw)
dirty = False
if "style" in opts:
kind = _rbtn_kind_of(opts.pop("style"))
if kind != self._kind:
self._kind = kind
self._padx, self._pady = _RBTN_PAD[kind]
self._pal = _RBTN_FACE[kind]
try:
super().configure(fg=self._pal["fg"],
activeforeground=self._pal["fg"])
except Exception:
pass
dirty = True
if "kind" in opts:
kind = opts.pop("kind")
if kind in _RBTN_FACE and kind != self._kind:
self._kind = kind
self._padx, self._pady = _RBTN_PAD[kind]
self._pal = _RBTN_FACE[kind]
dirty = True
if "textvariable" in opts:
self._var = opts.pop("textvariable")
opts["textvariable"] = self._var
self._watch_var()
dirty = True
if "text" in opts:
self._text = opts.pop("text")
opts["text"] = self._text
dirty = True
if "bg" in opts or "background" in opts:
opts["activebackground"] = opts.get("bg", opts.get("background"))
if opts:
try:
super().configure(**opts)
except Exception:
pass
if dirty or "state" in opts:
self._refresh()
return None
config = configure
def cget(self, key):
if key == "text":
return self._text
return super().cget(key)
def __setitem__(self, key, value):
self.configure(**{key: value})
def __getitem__(self, key):
return self.cget(key)
def mkbtn(parent, text="", textvariable=None, style="Accent.TButton",
command=None, bg=_RBTN_DEFAULT_BG, font=_RBTN_DEFAULT_FONT, **kw):
"""Make a rounded button; falls back to ttk.Button without PIL."""
if _TK_OK and _PIL_OK:
return RoundedButton(parent, text=text, textvariable=textvariable,
style=style, command=command, bg=bg, font=font,
**kw)
from tkinter import ttk as _ttk
return _ttk.Button(parent, text=text, textvariable=textvariable,
style=style, command=command, **kw)
class PillLabel(_tk.Label):
"""tk.Label with a rounded-pill face rendered by PIL (for badges).
Same palette, just rounded. Supports .config(text=...), .config(bg=...)
(face color) and textvariable; parent_bg paints the corners.
Falls back to a plain label only via mkpill(has_pil=False) path.
"""
def __init__(self, parent, text="", textvariable=None, bg="#2a2a2a",
fg="#171717", font=_RBTN_DEFAULT_FONT, padx=8, pady=3,
radius=8, parent_bg="#202020", **kw):
self._text = text
self._var = textvariable
self._face = bg
self._parent_bg = parent_bg
self._font = _tkfont.Font(font=font)
self._padx, self._pady = padx, pady
self._radius = radius
self._img = None
self._pil = None
super().__init__(parent, text=text, textvariable=textvariable,
font=font, fg=fg, bg=parent_bg,
borderwidth=0, highlightthickness=0,
padx=0, pady=0, **kw)
self._refresh()
if self._var is not None:
try:
self._var.trace_add("write", lambda *_a: self._refresh())
except Exception:
pass
def _label(self):
try:
if self._var is not None:
return self._var.get()
except Exception:
pass
return self._text
def _refresh(self):
label = self._label()
tw = self._font.measure(label) if label else 0
lh = self._font.metrics("linespace")
w = max(tw + 2 * self._padx, 2 * self._radius + 10)
h = lh + 2 * self._pady
self._pil = _rbtn_face_image(w, h, self._radius, self._face)
self._img = _PILImageTk.PhotoImage(self._pil)
try:
super().configure(image=self._img, compound="center",
width=w, height=h)
except Exception:
pass
def configure(self, cnf=None, **kw):
if cnf is None and not kw:
return super().configure()
if isinstance(cnf, dict):
kw = dict(cnf, **kw)
cnf = None
if isinstance(cnf, str) and not kw:
if cnf == "text":
return self._text
return super().configure(cnf)
opts = dict(kw)
dirty = False
if "text" in opts:
self._text = opts.pop("text")
opts["text"] = self._text
dirty = True
if "textvariable" in opts:
self._var = opts.pop("textvariable")
opts["textvariable"] = self._var
if self._var is not None:
try:
self._var.trace_add("write",
lambda *_a: self._refresh())
except Exception:
pass
dirty = True
if "bg" in opts or "background" in opts:
self._face = opts.pop("bg", opts.pop("background", self._face))
dirty = True
if "fg" in opts or "foreground" in opts:
# badge text color must follow (e.g. white on Nintendo red);
# plain tk.Label draws text over the pill image in this color.
_fg = opts.pop("fg", opts.pop("foreground", None))
if _fg is not None:
try:
super().configure(fg=_fg)
except Exception:
pass
if opts:
try:
super().configure(**opts)
except Exception:
pass
if dirty:
self._refresh()
return None
config = configure
def cget(self, key):
if key == "text":
return self._text
if key in ("bg", "background"):
return self._face
return super().cget(key)
def mkpill(parent, text="", textvariable=None, bg="#2a2a2a", fg="#171717",
font=_RBTN_DEFAULT_FONT, parent_bg="#202020", **kw):
"""Make a rounded pill badge; falls back to tk.Label without PIL."""
if _TK_OK and _PIL_OK:
return PillLabel(parent, text=text, textvariable=textvariable, bg=bg,
fg=fg, font=font, parent_bg=parent_bg, **kw)
return _tk.Label(parent, text=text, textvariable=textvariable, bg=bg,
fg=fg, font=font, **dict({"padx": 8, "pady": 3}, **kw))
CNT_MAGIC = b"\x7fCNT"
FIH_MAGIC = b"\x7fFIH"
LIH_MAGIC = b"\x7fLIH"
PS3_MAGIC = b"\x7fPKG"
PFS0_MAGIC = b"PFS0"
HFS0_MAGIC = b"HFS0"
XCI_MAGIC = b"HEAD"
# PS3 NPDRM (from PyKG / ps3 pkg tools: fixed key, CTR with riv; debug = SHA1-XOR)
PS3_KEY = bytes.fromhex("2e7b71d7c9c9a14ea3221f188828b8f8")
PS3_HDR_FMT = ">4sHHIIIIQQQ48s16s16s"
PS3_ITEM_FMT = ">IIQQII"
PS3_DIR_FLAG = 0x04
try:
from cryptography.hazmat.primitives.ciphers import Cipher as _Cipher
from cryptography.hazmat.primitives.ciphers import algorithms as _Algos
from cryptography.hazmat.primitives.ciphers import modes as _Modes
HAS_PS3_AES = True
except ImportError:
HAS_PS3_AES = False
# ---------------- parsing (verified on samples) ----------------
def u32be(b, o):
return struct.unpack_from(">I", b, o)[0]
def u64be(b, o):
return struct.unpack_from(">Q", b, o)[0]
def u64le(b, o):
return struct.unpack_from("<Q", b, o)[0]
def parse_cnt_entries(f, base, entry_count, entry_table_off):
f.seek(base + entry_table_off)
raw = f.read(entry_count * 32)
ents = []
for i in range(entry_count):
e = raw[i * 32:(i + 1) * 32]
if len(e) < 32:
break
v = struct.unpack(">8I", e)
ents.append({"id": v[0], "name_off": v[1], "f1": v[2], "f2": v[3],
"off": v[4], "size": v[5]})
return ents
def read_name_table(f, base, ents):
nt_entry = next((e for e in ents if e["id"] == 512), None)
if not nt_entry:
return b""
f.seek(base + nt_entry["off"])
return f.read(nt_entry["size"])
def entry_name(nt, off):
end = nt.find(b"\x00", off)
if end < 0:
return ""
return nt[off:end].decode("ascii", errors="replace")
def parse_sfo(data):
out = {}
try:
if data[:4] != b"\x00PSF":
return {"_error": "bad magic %r" % data[:4]}
ver, key_off, data_off, count = struct.unpack_from("<4I", data, 4)
for i in range(count):
eo = 20 + i * 16
key_rel, fmt, dlen, dmax, doff = struct.unpack_from("<HHIII", data, eo)
ks = key_off + key_rel
ke = data.find(b"\x00", ks)
key = data[ks:ke].decode("utf-8", errors="replace")
val_off = data_off + doff
if fmt == 0x0204:
ve = data.find(b"\x00", val_off, val_off + dmax)
if ve < 0:
ve = val_off + dlen
out[key] = data[val_off:ve].decode("utf-8", errors="replace")
elif fmt == 0x0404:
out[key] = struct.unpack_from("<I", data, val_off)[0]
else:
out[key] = data[val_off:val_off + dlen].hex(" ")
return out
except Exception as e:
return {"_error": str(e)}
REGION_NAMES = {"EP": "Europe", "UP": "Americas", "JP": "Japan", "HP": "Asia"}
PS4_CAT_TYPES = {"gd": "Base Game", "ac": "DLC", "gp": "Update"}
def content_region(cid):
"""Region from content-ID prefix (EP0002-... -> Europe)."""
try:
pre = (cid or "").split("-")[0][:2].upper()
return REGION_NAMES.get(pre, pre or "-")
except Exception:
return "-"
def _tid_from_cid(cid):
"""Title ID from a PlayStation Content ID.
UP0949-CUSA04195_00-BRAWLHALLA111315 -> CUSA04195. Used as a fallback
when param.sfo is unreadable (partial/corrupt download) so the Title ID
row is still shown. Never raises.
"""
try:
return (cid or "").split("-")[1].split("_")[0].strip().upper()
except Exception:
return ""
def _tid_from_filename(path):
"""Title ID from a file name (CUSA04195_BRAWLHALLA_... -> CUSA04195)."""
try:
import re as _re
m = _re.search(r"(CUSA\d{5})",
os.path.basename(path or ""), _re.IGNORECASE)
return m.group(1).upper() if m else ""
except Exception:
return ""
def fmt_fw32(v):
"""Decode 32-bit Sony fw int (SFO SYSTEM_VER, e.g. 0x05010000)
nibble-BCD -> '5.01'. Real fw versions are major.minor only,
so the low word is not a version part. Passes anything else
through untouched."""
try:
if isinstance(v, int):
n = v
else:
s = str(v or "").strip()
if s in ("", "-"):
return "-"
if not s.lstrip("+-").isdigit():
return s # already dotted ("05.050.000", "4.80", ...)
n = int(s, 0)
except Exception:
return str(v)
try:
if n == 0:
return "-"
if not (0x01000000 <= n <= 0xFFFFFFFF):
return str(v)
hi, lo = (n >> 24) & 0xFF, (n >> 16) & 0xFF
if (hi >> 4) > 9 or (hi & 0xF) > 9 or \
(lo >> 4) > 9 or (lo & 0xF) > 9:
return str(v) # not BCD -> don't invent a version
major = f"{hi:02X}".lstrip("0") or "0"
return f"{major}.{lo:02X}"
except Exception:
return str(v)
def fmt_fw(v):
"""Decode PS5 fw hex (0x0250...) -> '2.50'. Passes other values through."""
if v is None or v == "":
return "-"
try:
n = v if isinstance(v, int) else int(str(v).strip(), 0)
top = (n >> 48) & 0xFFFF
if not top:
return fmt_fw32(n) # 32-bit Sony fw/SDK int, not raw text
return f"{(top >> 8) & 0xFF:X}.{top & 0xFF:02X}"
except Exception:
return str(v)
def ps4_pkg_type(cat):
if not cat:
return "-"
lab = PS4_CAT_TYPES.get(str(cat).lower())
return lab if lab else str(cat)
def _sdk_fw_text(raw):
"""SDK version from a PS4 param.sfo value -> '5.05' ('' when unknown).
SDK_VER is a 32-bit BCD fw int (0x05050000); PUBTOOLINFO carries the
same number as bare hex (sdk_ver=05050000), so base 16 is needed there
(int("05050000", 0) would reject the leading zero).
"""
try:
if isinstance(raw, int):
return fmt_fw32(raw)
s = str(raw or "").strip()
if not s or s == "-":
return ""
if s.lower().startswith("0x"):
return fmt_fw32(int(s, 16))
if s.isdigit() and len(s) <= 8:
return fmt_fw32(int(s, 16))
return ""
except Exception:
return ""
def ps4_sdk_version(sfo):
"""PS4 SDK version: SDK_VER field, else PUBTOOLINFO sdk_ver=...
Backported PKGs are rebuilt with an older SDK, so this is the row that
gives a backport away; it used to be visible only in the raw dump.
"""
if not isinstance(sfo, dict):
return ""
for key in ("SDK_VER", "SDK_VERSION"):
if key in sfo:
v = _sdk_fw_text(sfo.get(key))
if v and v != "-":
return v
try:
import re as _re
m = _re.search(r"sdk_ver\s*=\s*([0-9A-Fa-f]+)",
str(sfo.get("PUBTOOLINFO", "") or ""))
if m:
v = _sdk_fw_text(m.group(1))
if v and v != "-":
return v
except Exception:
pass
return ""
def cnt_package_type(hdr):
"""FPKG vs retail for PS4 CNT: bit 31 of pkg_type @0x04 (big-endian).
Per psdevwiki/UnPKG: FILE_TYPE_FLAGS_RETAIL = 1 << 31. Retail PKGs
have pkg_type like 0x83000001/0x81000001; fpkg builds (even DUPLEX,
which carry non-zero digest bytes at 0x100..0x200) have it clear
(e.g. 0x00000001/0x40000001). The 0x100..0x200 area holds SHA256
digests, NOT an RSA signature, so zero-testing it is wrong.
"""
try:
if len(hdr) >= 8:
ptype = struct.unpack_from(">I", hdr, 0x04)[0]
if ptype & 0x80000000:
return "OFC (Official)"
return "FPKG (Fake)"
except Exception:
pass
return "-"
def lman_summary(meta_kind, rd):
"""Bottom-bar summary à la LMAN: Type (Fake) (REGION) - vVER - System SYS."""
try:
typ = str(rd.get("Type", "") or "")
pkg = str(rd.get("Package", "") or rd.get("Signature", ""))
if not typ:
# encrypted stubs / table-less kinds have no Type row: use
# the Package label base (e.g. "OFC (Official)" -> "OFC").
typ = pkg
base = typ.split("(")[0].strip() or typ or "-"
fake = ""
if "fake" in pkg.lower() or "fpkg" in pkg.lower():
fake = " (Fake)"
elif "official" in pkg.lower() or pkg.lower().startswith("ofc"):
fake = " (Official)"
region = str(rd.get("Region", "") or "")
short = REGION_SHORT.get(region, region[:2].upper() if region else "-")
ver = (rd.get("Version", "") or rd.get("Content Ver", "") or "-")
ver = str(ver).strip() or "-"
if ver != "-" and not ver.lower().startswith("v"):
ver = "v" + ver
sysv = str(rd.get("Min. System", "") or "").strip()
out = f"{base}{fake} ({short}) - {ver}"
if sysv and sysv != "-":
out += f" - System {sysv}"
return out
except Exception:
return ""
def _param_json_meta(meta):
lp = meta.get("localizedParameters", {})
lang = lp.get("defaultLanguage", "en-US")
title = (lp.get(lang) or {}).get("titleName", "")
cid = meta.get("contentId", "")
cn = meta.get("applicationCategoryType")
ptype = "Application (APP)" if cn == 0 else (f"Type {cn}" if cn is not None else "-")
drm = meta.get("applicationDrmType", "")
extra = [("Title ID", meta.get("titleId", "")),
("Content ID", cid),
("Region", content_region(cid)),
("Type", ptype),
("Content Ver", meta.get("contentVersion", "")),
("Master Ver", meta.get("masterVersion", "")),
("Concept ID", meta.get("conceptId", "")),
("Min. System", fmt_fw(meta.get("requiredSystemSoftwareVersion"))),
("DRM", str(drm).capitalize() if drm else "-"),
("SDK", fmt_fw(meta.get("sdkVersion")))]
return title, extra
def _switch_title_from_filename(path):
"""(title, tid, ver) from Switch naming: Name [TID16][vN]... .nsp/.xci."""
import re as _re
base = os.path.basename(path)
stem, _ = os.path.splitext(base)
tid, ver = "", ""
m = _re.search(r"\[([0-9A-Fa-f]{16})\]", stem)
if m:
tid = m.group(1).upper()
m = _re.search(r"\[v(\d+)\]", stem, _re.IGNORECASE)
if m:
ver = m.group(1)
title = _re.sub(r"\[[^\]]*\]", "", stem).strip(" -_.")
title = _re.sub(r"\s{2,}", " ", title)
return title or stem, tid, ver
def _parse_cnmt_xml(data):
"""Minimal *.cnmt.xml -> dict(Id, Version, Type, RequiredSystemVersion,
PatchId, contents=[{Type, Id, Size}]). Never raises."""
out = {"contents": []}
try:
import xml.etree.ElementTree as _et
root = _et.fromstring(data)
def _txt(tag):
try:
el = root.find(tag)
return (el.text or "").strip() if el is not None else ""
except Exception:
return ""
for k in ("Type", "Id", "Version", "RequiredDownloadSystemVersion",
"RequiredSystemVersion", "PatchId", "Digest",
"KeyGenerationMin"):
v = _txt(k)
if v:
out[k] = v
for c in root.findall("Content"):
try:
def _ct(t):
el = c.find(t)
return (el.text or "").strip() if el is not None else ""
out["contents"].append({"Type": _ct("Type"), "Id": _ct("Id"),
"Size": _ct("Size")})
except Exception:
continue
except Exception:
pass
return out
# ---------------- Switch NCA decrypt (prod.keys) -> NACP title + icon ----------------
# Needs the `cryptography` package (already required for PS3 PKG AES).
# All helpers never raise: they return None/{} when keys or the package
# cannot provide decrypted data. No key material is ever stored in results.
_SWITCH_KEYS_CACHE = {"once": False, "keys": None}
NACP_LANGS = ("AmericanEnglish", "BritishEnglish", "Japanese", "French",
"German", "LatinAmericanSpanish", "Spanish", "Italian",
"Dutch", "CanadianFrench", "Portuguese", "Russian", "Korean",
"TraditionalChinese", "SimplifiedChinese", "BrazilianPortuguese")
def _find_switch_keys():
"""Load Switch prod.keys once -> dict or None. Never raises."""
try:
if _SWITCH_KEYS_CACHE["once"]:
return _SWITCH_KEYS_CACHE["keys"]
_SWITCH_KEYS_CACHE["once"] = True
cands = []
try:
ev = (os.environ.get("SWITCH_PROD_KEYS")
or os.environ.get("PROD_KEYS") or "")
if ev and os.path.isfile(ev):
cands.append(ev)
except Exception:
pass
try:
here = os.path.dirname(os.path.abspath(__file__))
cands.append(os.path.join(here, "prod.keys"))
cands.append(os.path.join(os.getcwd(), "prod.keys"))
except Exception:
pass
try:
if sys.platform.startswith("win"):
base = os.environ.get("APPDATA") or os.path.expanduser("~")
cands.append(os.path.join(base, "PKGViewer", "prod.keys"))
else:
cands.append(os.path.join(os.path.expanduser("~"),
".switch", "prod.keys"))
except Exception:
pass
path = next((p for p in cands if p and os.path.isfile(p)), None)
if not path:
return None
raw = {}
with open(path, "r", encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
try:
raw[k.strip()] = bytes.fromhex(v.strip())
except Exception:
continue
if len(raw.get("header_key", b"")) != 32:
return None
import re as _re
keys = {"header_key": raw["header_key"], "kaek": {},
"titlekek": {}}
for k, v in raw.items():
m = _re.match(r"^key_area_key_(application|ocean|system)_"
r"([0-9a-fA-F]{2})$", k)
if m and len(v) == 16:
keys["kaek"][(m.group(1), int(m.group(2), 16))] = v
continue
m = _re.match(r"^titlekek_([0-9a-fA-F]{2})$", k)
if m and len(v) == 16:
keys["titlekek"][int(m.group(1), 16)] = v
if not keys["kaek"]:
return None
_SWITCH_KEYS_CACHE["keys"] = keys
return keys
except Exception:
return None
def _sw_aes_ecb_dec(key, data):
from cryptography.hazmat.primitives.ciphers import Cipher as _C
from cryptography.hazmat.primitives.ciphers import algorithms as _A
from cryptography.hazmat.primitives.ciphers import modes as _M
d = _C(_A.AES(key), _M.ECB()).decryptor()
return d.update(data) + d.finalize()
def _sw_aes_xts_dec(key, tweak, data):
from cryptography.hazmat.primitives.ciphers import Cipher as _C
from cryptography.hazmat.primitives.ciphers import algorithms as _A
from cryptography.hazmat.primitives.ciphers import modes as _M
d = _C(_A.AES(key), _M.XTS(tweak)).decryptor()
return d.update(data) + d.finalize()
def _switch_nca_control_info(nsp_path, nca_abs_off, tik_bytes, keys):
"""Decrypt a Control NCA -> {title, publisher, display_ver, titles,
icon, icon_name} or None. Reads only header + RomFS tables + NACP +
one icon (fast). Never raises, never returns key material."""
import struct as _st
try:
if not keys or nca_abs_off < 0:
return None
with open(nsp_path, "rb") as f:
f.seek(nca_abs_off)
raw_hdr = f.read(0xC00)
if len(raw_hdr) < 0xC00:
return None
# header: AES-XTS, BE sector tweak (hactool-compatible)
full = b"".join(
_sw_aes_xts_dec(keys["header_key"], s.to_bytes(16, "big"),
raw_hdr[s * 0x200:(s + 1) * 0x200])
for s in range(6))
if full[0x200:0x204] not in (b"NCA3", b"NCA2"):
return None
if full[0x205] != 2: # not a Control NCA
return None
crypto = max(full[0x206], full[0x220])
if crypto:
crypto -= 1
rights = full[0x230:0x240]
if any(rights):
if not tik_bytes or len(tik_bytes) < 0x1CF:
return None
tk = keys["titlekek"].get(crypto)
if tk is None:
return None
sec_key = _sw_aes_ecb_dec(tk, tik_bytes[0x1BF:0x1CF])
else:
kaek_ind = full[0x207]
kind = {0: "application", 1: "ocean",
2: "system"}.get(kaek_ind, "application")
kak = keys["kaek"].get((kind, crypto))
if kak is None:
return None
area = _sw_aes_ecb_dec(kak, full[0x300:0x340])
sec_key = area[32:48]
from cryptography.hazmat.primitives.ciphers import Cipher as _C
from cryptography.hazmat.primitives.ciphers import algorithms as _A
from cryptography.hazmat.primitives.ciphers import modes as _M
def _sec_read(f, secoff, iv_int, rel_off, size):
if size <= 0 or size > 16_000_000:
return b""
lo = rel_off & ~0xF
nblocks = ((rel_off - lo) + size + 15) // 16
c0 = iv_int + (lo >> 4)
e = _C(_A.AES(sec_key), _M.ECB()).encryptor()
ks = e.update(b"".join((c0 + i).to_bytes(16, "big")
for i in range(nblocks))) + e.finalize()
f.seek(secoff + lo)
ct = f.read(nblocks * 16)
if len(ct) < nblocks * 16:
return b""
pt = bytes(a ^ b for a, b in zip(ct, ks))
skip = rel_off - lo
return pt[skip:skip + size]
with open(nsp_path, "rb") as f:
for i in range(4):
start, _end = _st.unpack_from("<II", full, 0x240 + i * 16)
if not start:
continue
fsh = full[0x400 + i * 0x200:0x400 + (i + 1) * 0x200]
if len(fsh) < 0x200 or fsh[3] != 3 or fsh[4] != 3:
continue # need RomFS (3) + AES-CTR (3)
if fsh[0x8:0xC] != b"IVFC":
continue
secoff_rel = start * 0x200
secoff = nca_abs_off + secoff_rel
sctr = fsh[0x140:0x148]
iv_int = int.from_bytes(
bytes(reversed(sctr))
+ (secoff_rel >> 4).to_bytes(8, "big"), "big")
romfs_rel = _st.unpack_from("<Q", fsh,
0x8 + 0x10 + 5 * 0x18)[0]
if romfs_rel > 2_000_000_000:
continue
rh = _sec_read(f, secoff, iv_int, romfs_rel, 0x50)
if len(rh) < 0x50:
continue
vals = _st.unpack("<10Q", rh)
if vals[0] != 0x50:
continue
_hs, _dho, _dhs, dmo, dms, _fho, _fhs, fmo, fms, data_off = vals
if dms > 1_000_000 or fms > 5_000_000:
continue
dirs = _sec_read(f, secoff, iv_int, romfs_rel + dmo, dms)
files = _sec_read(f, secoff, iv_int, romfs_rel + fmo, fms)
if len(dirs) < 24 or not files:
continue
# walk root + one subdir level: [(path, data_off, size)]
found = []
def _files_at(tbl_off):
out, o, seen = [], tbl_off, set()
while (o != 0xFFFFFFFF and o not in seen
and o + 32 <= len(files)):
seen.add(o)
try:
_pa, sib, fo, fs, _h, nl = _st.unpack_from(
"<IIQQII", files, o)
except Exception:
break
if nl > 512 or o + 32 + nl > len(files):
break
try:
nm = files[o + 32:o + 32 + nl].decode("utf-8")
except Exception:
break
if fo + fs < fo: # overflow guard
break
out.append((nm, fo, fs))
o = sib
return out
try:
root_file = _st.unpack_from("<I", dirs, 12)[0]
except Exception:
continue
for nm, fo, fs in _files_at(root_file):
found.append(("", nm, fo, fs))
# one subdir level (some titles nest control data)
try:
_pa, _sib, child, _fi, _h, _nl = _st.unpack_from(
"<6I", dirs, 0)
except Exception:
child = 0xFFFFFFFF
seen_d, stack = set(), [child]
while stack:
do = stack.pop()
if do == 0xFFFFFFFF or do in seen_d or do + 24 > len(dirs):
continue
seen_d.add(do)
try:
_p, sib, ch, fi, _hh, nll = _st.unpack_from(
"<6I", dirs, do)
dn = dirs[do + 24:do + 24 + nll].decode("utf-8")
except Exception:
continue
for nm, fo, fs in _files_at(fi):
found.append((dn, nm, fo, fs))
if ch != 0xFFFFFFFF:
stack.append(ch)
if sib != 0xFFFFFFFF:
stack.append(sib)
low = [(d, n, fo, fs) for d, n, fo, fs in found]
nacp_hit = next((x for x in low
if x[1].lower() == "control.nacp"), None)
if nacp_hit is None: