Coverage for src/romfarmer/engine/transforms/ps3.py: 71%

85 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""PS3 decrypt transform — PS3Dec ISO decryption. 

2 

3Extracted from ``romfarmer.stages.transform_ps3.TransformPS3Stage``. 

4Runs ``PS3Dec`` to decrypt an encrypted PS3 ISO using a ``.dkey`` file. 

5""" 

6 

7from __future__ import annotations 

8 

9import logging 

10import re 

11import shutil 

12import subprocess 

13import zipfile 

14from collections.abc import Mapping 

15from pathlib import Path 

16 

17from .base import Transform, TransformError, pinned_env 

18 

19logger = logging.getLogger(__name__) 

20 

21_DEFAULT_TOOL = Path("tools/bin/ps3dec") 

22 

23 

24class PS3DecTransform: 

25 """Decrypt a PS3 ISO using PS3Dec. 

26 

27 Expected inputs: 

28 inputs[0]: encrypted ISO file 

29 inputs[1]: .dkey file 

30 

31 Recognised params: 

32 ps3dec_path: override path to PS3Dec binary 

33 output_name: explicit output filename (default: same stem + .iso) 

34 """ 

35 

36 name = "ps3dec" 

37 

38 def run( 

39 self, 

40 inputs: list[Path], 

41 params: Mapping[str, str], 

42 scratch: Path, 

43 ) -> list[Path]: 

44 if len(inputs) < 2: 

45 raise TransformError("PS3DecTransform requires 2 inputs: [encrypted_iso, dkey_file]") 

46 

47 iso_file, dkey_file = inputs[0], inputs[1] 

48 tool = self._find_tool(params.get("ps3dec_path")) 

49 if tool is None: 

50 raise TransformError("PS3Dec not found; install it or set ps3dec_path param") 

51 

52 output_name = params.get("output_name", iso_file.stem + ".iso") 

53 output_path = scratch / output_name 

54 

55 result = subprocess.run( 

56 [ 

57 str(tool), 

58 "dec", 

59 "key", 

60 dkey_file.read_text().strip(), 

61 str(iso_file), 

62 str(output_path), 

63 ], 

64 capture_output=True, 

65 text=True, 

66 check=False, 

67 timeout=3600, 

68 env=pinned_env(), 

69 ) 

70 if result.returncode != 0: 

71 raise TransformError(f"PS3Dec failed for {iso_file.name}: {result.stderr[:500]}") 

72 if not output_path.exists(): 

73 raise TransformError(f"PS3Dec did not produce expected output {output_path}") 

74 return [output_path] 

75 

76 @staticmethod 

77 def _find_tool(override: str | None) -> Path | None: 

78 if override: 

79 p = Path(override).resolve() 

80 return p if p.exists() else None 

81 if _DEFAULT_TOOL.exists(): 

82 return _DEFAULT_TOOL.resolve() 

83 for candidate in ("PS3Dec", "ps3dec"): 

84 found = shutil.which(candidate) 

85 if found: 

86 return Path(found).resolve() 

87 return None 

88 

89 

90_dec: Transform = PS3DecTransform() 

91 

92 

93class Ps3DkeyLookupTransform: 

94 """Locate a PS3 disc's ``.dkey`` in a Redump "Disc Keys TXT" zip. 

95 

96 This is a zero-CAS-input action: the key is found purely from 

97 filesystem params (``keys_directory`` + ``stem``), the same pattern 

98 used by ``source_action`` for the original source file. 

99 

100 Recognised params: 

101 keys_directory: directory containing ``<stem>.zip`` key archives 

102 stem: the disc's base name (source ZIP stem) used to find the key 

103 """ 

104 

105 name = "ps3-dkey-lookup" 

106 

107 def run( 

108 self, 

109 inputs: list[Path], 

110 params: Mapping[str, str], 

111 scratch: Path, 

112 ) -> list[Path]: 

113 keys_dir = params.get("keys_directory") 

114 stem = params.get("stem") 

115 if not keys_dir or not stem: 

116 raise TransformError( 

117 "Ps3DkeyLookupTransform requires 'keys_directory' and 'stem' params" 

118 ) 

119 

120 keys_path = Path(keys_dir) 

121 key_zip = keys_path / f"{stem}.zip" 

122 if not key_zip.exists(): 

123 # Redump disc-key archives sometimes omit revision markers that 

124 # appear in the Retool-filtered DAT name. 

125 base_stem = re.sub(r"\s*\(Rev \d+\)", "", stem) 

126 key_zip = keys_path / f"{base_stem}.zip" 

127 if not key_zip.exists(): 

128 raise TransformError(f"No disc key found for '{stem}' in {keys_path}") 

129 

130 with zipfile.ZipFile(key_zip, "r") as zf: 

131 dkey_names = [n for n in zf.namelist() if n.lower().endswith(".dkey")] 

132 if not dkey_names: 

133 raise TransformError(f"No .dkey member in {key_zip.name}") 

134 dkey_hex = zf.read(dkey_names[0]).decode("ascii").strip() 

135 

136 if len(dkey_hex) != 32: 

137 raise TransformError(f"Invalid disc key length {len(dkey_hex)} in {key_zip.name}") 

138 

139 out = scratch / f"{stem}.dkey" 

140 out.write_text(dkey_hex) 

141 return [out] 

142 

143 

144_dkey: Transform = Ps3DkeyLookupTransform() 

145 

146 

147class Ps3ExtractTreeTransform: 

148 """Extract a decrypted PS3 ISO into its JB folder (``PS3_GAME/`` tree). 

149 

150 Expected inputs: 

151 inputs[0]: decrypted ISO file 

152 

153 Output is a *directory* (kind ``"tree"``) — the Executor ingests it via 

154 the CAS tree store rather than as a single-file blob. 

155 """ 

156 

157 name = "ps3-extract-tree" 

158 

159 def run( 

160 self, 

161 inputs: list[Path], 

162 params: Mapping[str, str], 

163 scratch: Path, 

164 ) -> list[Path]: 

165 if not inputs: 

166 raise TransformError("Ps3ExtractTreeTransform requires 1 input: [decrypted_iso]") 

167 

168 iso_file = inputs[0] 

169 sevenzip = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za") 

170 if sevenzip is None: 

171 raise TransformError("7z not found; required to extract PS3 ISO contents") 

172 

173 extract_dir = scratch / "extract" 

174 extract_dir.mkdir(parents=True, exist_ok=True) 

175 result = subprocess.run( 

176 [sevenzip, "x", str(iso_file), f"-o{extract_dir}", "-y"], 

177 capture_output=True, 

178 text=True, 

179 check=False, 

180 timeout=3600, 

181 env=pinned_env(), 

182 ) 

183 

184 game_dirs = list(extract_dir.rglob("PS3_GAME")) 

185 if not game_dirs: 

186 raise TransformError( 

187 f"No PS3_GAME directory found after extracting {iso_file.name} " 

188 f"(7z exit {result.returncode}): {result.stderr[:500]}" 

189 ) 

190 if result.returncode != 0: 

191 # PS3 discs are ISO9660+UDF hybrids; 7z frequently reports a 

192 # "Headers Error" / trailing-data warning on the UDF side even 

193 # though every file (including PS3_GAME/) extracted correctly. 

194 # Trust the PS3_GAME check above over the exit code here. 

195 logger.warning( 

196 "7z reported exit %d extracting %s but PS3_GAME/ was found " 

197 "— treating as a benign UDF header warning: %s", 

198 result.returncode, 

199 iso_file.name, 

200 result.stderr[:300], 

201 ) 

202 

203 return [game_dirs[0].parent] 

204 

205 

206_tree: Transform = Ps3ExtractTreeTransform()