Cnass commited on
Commit
08cc82b
·
verified ·
1 Parent(s): d28f927

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +44 -0
  2. app.py +211 -0
  3. deobfuscate.py +345 -0
  4. requirements.txt +2 -0
  5. rpyc_patcher.py +198 -0
  6. setup.py +17 -0
  7. unrpyc.py +598 -0
Dockerfile ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Temel Python imajını alıyoruz
2
+ FROM python:3.9-slim
3
+
4
+ # Gerekli grafik ve indirme araçlarını kuruyoruz
5
+ RUN apt-get update && apt-get install -y \
6
+ wget \
7
+ bzip2 \
8
+ unzip \
9
+ libgl1 \
10
+ libglib2.0-0 \
11
+ libsm6 \
12
+ libxext6 \
13
+ libxrender1 \
14
+ && rm -rf /var/lib/apt/lists/*
15
+
16
+ # 1. MOTOR: Ren'Py 7.5.3 (Python 2 - Eski ve Yaygın Oyunlar İçin)
17
+ RUN wget https://www.renpy.org/dl/7.5.3/renpy-7.5.3-sdk.tar.bz2 && \
18
+ tar -xf renpy-7.5.3-sdk.tar.bz2 && \
19
+ rm renpy-7.5.3-sdk.tar.bz2
20
+
21
+ # 2. MOTOR: Ren'Py 8.1.3 (Python 3 - Yeni Nesil Oyunlar İçin)
22
+ RUN wget https://www.renpy.org/dl/8.1.3/renpy-8.1.3-sdk.tar.bz2 && \
23
+ tar -xf renpy-8.1.3-sdk.tar.bz2 && \
24
+ rm renpy-8.1.3-sdk.tar.bz2
25
+
26
+ # Çalışma klasörümüzü ayarlıyoruz
27
+ WORKDIR /app
28
+
29
+ # Python kütüphanelerini yüklüyoruz
30
+ COPY requirements.txt .
31
+ RUN pip install --no-cache-dir -r requirements.txt
32
+
33
+ # Dosyalarımızı kopyalıyoruz
34
+ COPY . .
35
+
36
+ # Her iki motora da çalışma izni veriyoruz
37
+ RUN chmod +x /renpy-7.5.3-sdk/renpy.sh
38
+ RUN chmod +x /renpy-8.1.3-sdk/renpy.sh
39
+
40
+ # Web sunucusu portunu açıyoruz
41
+ EXPOSE 5000
42
+
43
+ # Uygulamayı başlatıyoruz
44
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import shutil
4
+ import base64
5
+ import struct
6
+ import zlib
7
+ import pickle
8
+ import sys
9
+ import traceback
10
+ from flask import Flask, request, jsonify
11
+ from decompiler import magic, renpycompat
12
+
13
+ sys.setrecursionlimit(50000)
14
+
15
+ app = Flask(__name__)
16
+
17
+ # --- 1. YARDIMCI VE ZIRHLI ÇEVİRİ FONKSİYONLARI ---
18
+ def unescape_wp_string(s):
19
+ if not isinstance(s, str): return s
20
+ s = s.replace('\\n', '\n')
21
+ s = s.replace('\\"', '"')
22
+ s = s.replace('\\ ', ' ')
23
+ s = s.replace('\\\\', '\\')
24
+ return s.replace('\r', '')
25
+
26
+ def apply_translation(text, translations):
27
+ """AST Zırhı: Sadece birebir eşleşen metinleri değiştirir. 'at' kelimesi kodları bozamaz."""
28
+ if not isinstance(text, (str, bytes)): return text
29
+ is_bytes = isinstance(text, bytes)
30
+ text_str = text.decode('utf-8', 'ignore') if is_bytes else text
31
+
32
+ for k, v in translations.items():
33
+ # Başındaki ve sonundaki tırnakları temizleyerek saf eşleşme ara
34
+ clean_k = k[1:-1] if len(k) >= 2 and k[0] in ('"', "'") and k[-1] == k[0] else k
35
+ clean_v = v[1:-1] if len(v) >= 2 and v[0] in ('"', "'") and v[-1] == v[0] else v
36
+
37
+ if text_str == clean_k:
38
+ return clean_v.encode('utf-8') if is_bytes else clean_v
39
+ return text
40
+
41
+ # --- 2. AST MOTORU (Düz Metni Bozmadan Sadece Hedefi Vurur) ---
42
+ def patch_ast(obj, translations, visited=None):
43
+ if visited is None: visited = set()
44
+ if obj is None or isinstance(obj, (int, float, bool, str, bytes)): return
45
+
46
+ obj_id = id(obj)
47
+ if obj_id in visited: return
48
+ visited.add(obj_id)
49
+
50
+ if isinstance(obj, list):
51
+ for i in range(len(obj)):
52
+ if isinstance(obj[i], (str, bytes)):
53
+ obj[i] = apply_translation(obj[i], translations)
54
+ else:
55
+ patch_ast(obj[i], translations, visited)
56
+ elif isinstance(obj, tuple):
57
+ for item in obj:
58
+ patch_ast(item, translations, visited)
59
+ elif isinstance(obj, dict):
60
+ for k, v in list(obj.items()):
61
+ if isinstance(v, (str, bytes)):
62
+ obj[k] = apply_translation(v, translations)
63
+ else:
64
+ patch_ast(v, translations, visited)
65
+ elif hasattr(obj, '__dict__'):
66
+ class_name = type(obj).__name__
67
+
68
+ # Ren'Py Sınıflarına Göre Filtre
69
+ if class_name in ('Say', 'TranslateSay') and hasattr(obj, 'what'):
70
+ obj.what = apply_translation(obj.what, translations)
71
+ elif class_name in ('Menu', 'TranslateMenu') and hasattr(obj, 'items'):
72
+ new_items = []
73
+ for item in obj.items:
74
+ label = apply_translation(item[0], translations)
75
+ new_items.append((label, item[1], item[2]) if len(item) >= 3 else (label,) + item[1:])
76
+ obj.items = new_items
77
+ elif class_name == 'TranslateString' and hasattr(obj, 'new'):
78
+ obj.new = apply_translation(obj.new, translations)
79
+
80
+ FORBIDDEN_KEYS = {'old', 'language', 'identifier', 'filename', 'name', 'label', 'parameters'}
81
+ for k, v in list(obj.__dict__.items()):
82
+ if k in FORBIDDEN_KEYS: continue
83
+ if class_name in ('Say', 'TranslateSay') and k == 'what': continue
84
+ if class_name in ('Menu', 'TranslateMenu') and k == 'items': continue
85
+ if class_name == 'TranslateString' and k == 'new': continue
86
+
87
+ if isinstance(v, (str, bytes)):
88
+ text_len = len(v) if isinstance(v, str) else len(v.decode('utf-8', 'ignore'))
89
+ if text_len >= 2:
90
+ setattr(obj, k, apply_translation(v, translations))
91
+ else:
92
+ patch_ast(v, translations, visited)
93
+
94
+ # --- 3. ENDPOINT'LER ---
95
+ @app.route('/decompile', methods=['POST'])
96
+ def decompile_rpyc():
97
+ """Okuma kısmı eskisi gibi Unrpyc kullanılarak düz metne dönüştürülür."""
98
+ data = request.json
99
+ if not data or 'filedata' not in data:
100
+ return jsonify({"error": "Dosya verisi bulunamadı."}), 400
101
+
102
+ try:
103
+ file_data = base64.b64decode(data['filedata'])
104
+ filename = data.get('filename', 'temp.rpyc')
105
+ rpy_filename = filename.replace('.rpyc', '.rpy')
106
+
107
+ with open(filename, 'wb') as f:
108
+ f.write(file_data)
109
+
110
+ subprocess.run(['python', 'unrpyc.py', filename], check=True)
111
+
112
+ with open(rpy_filename, 'r', encoding='utf-8') as f:
113
+ rpy_content = f.read()
114
+
115
+ if os.path.exists(filename): os.remove(filename)
116
+ if os.path.exists(rpy_filename): os.remove(rpy_filename)
117
+
118
+ return jsonify({"success": True, "rpy_content": rpy_content})
119
+
120
+ except Exception as e:
121
+ return jsonify({"error": str(e)}), 500
122
+
123
+ @app.route('/patch', methods=['POST'])
124
+ def patch_endpoint():
125
+ """Derleme (Compile) işlemi kaldırıldı. Orijinal dosya doğrudan güvenle yamalanır."""
126
+ data = request.get_json()
127
+ if not data or 'filedata' not in data or 'translations' not in data:
128
+ return jsonify({"error": "Eksik veri gönderildi."}), 400
129
+
130
+ try:
131
+ file_bytes = base64.b64decode(data['filedata'])
132
+ raw_translations = data['translations']
133
+
134
+ # Sadece geçerli ve değiştirilmiş çevirileri al
135
+ clean_translations = {}
136
+ for k, v in raw_translations.items():
137
+ clean_k = unescape_wp_string(k)
138
+ clean_v = unescape_wp_string(v)
139
+ if clean_k.strip() and clean_k != clean_v:
140
+ clean_translations[clean_k] = clean_v
141
+
142
+ # --- AST MOTORU İLE DOĞRUDAN PAKETLEME (Çökme %0) ---
143
+ if file_bytes.startswith(b"RENPY RPC2"):
144
+ position = 10
145
+ chunks = []
146
+ while True:
147
+ slot, start, length = struct.unpack("III", file_bytes[position:position+12])
148
+ position += 12
149
+ if slot == 0: break
150
+ chunks.append({"slot": slot, "start": start, "length": length})
151
+
152
+ payloads = {}
153
+ for c in chunks:
154
+ chunk_data = file_bytes[c["start"] : c["start"] + c["length"]]
155
+ if c["slot"] == 1:
156
+ raw_pickle = zlib.decompress(chunk_data)
157
+ orig_proto = 2
158
+ if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
159
+ orig_proto = raw_pickle[1]
160
+ ast_tree = renpycompat.pickle_loads(raw_pickle)
161
+ patch_ast(ast_tree, clean_translations)
162
+ payloads[1] = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
163
+ elif c["slot"] == 2:
164
+ try:
165
+ # Slot 2 loglarına giren 'at' komutlarını engelle
166
+ raw_source = zlib.decompress(chunk_data).decode('utf-8')
167
+ for k, v in clean_translations.items():
168
+ if '"' in k or "'" in k:
169
+ raw_source = raw_source.replace(k, v)
170
+ payloads[2] = zlib.compress(raw_source.encode('utf-8'))
171
+ except Exception:
172
+ payloads[2] = chunk_data
173
+ else:
174
+ payloads[c["slot"]] = chunk_data
175
+
176
+ new_dir = bytearray()
177
+ current_offset = 10 + (len(chunks) + 1) * 12
178
+ for c in chunks:
179
+ data = payloads[c["slot"]]
180
+ new_dir.extend(struct.pack("III", c["slot"], current_offset, len(data)))
181
+ current_offset += len(data)
182
+ new_dir.extend(struct.pack("III", 0, 0, 0))
183
+
184
+ new_file = bytearray(b"RENPY RPC2")
185
+ new_file.extend(new_dir)
186
+ for c in chunks:
187
+ new_file.extend(payloads[c["slot"]])
188
+
189
+ new_rpyc_bytes = bytes(new_file)
190
+ else:
191
+ raw_pickle = zlib.decompress(file_bytes)
192
+ orig_proto = 2
193
+ if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
194
+ orig_proto = raw_pickle[1]
195
+ ast_tree = renpycompat.pickle_loads(raw_pickle)
196
+ patch_ast(ast_tree, clean_translations)
197
+ new_rpyc_bytes = zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
198
+
199
+ return jsonify({
200
+ 'success': True,
201
+ 'patched_file': base64.b64encode(new_rpyc_bytes).decode('utf-8')
202
+ })
203
+
204
+ except Exception as e:
205
+ error_msg = traceback.format_exc()
206
+ print("PATCH ERROR:", error_msg)
207
+ return jsonify({'error': str(e)}), 500
208
+
209
+ if __name__ == '__main__':
210
+ port = int(os.environ.get("PORT", 5000))
211
+ app.run(host='0.0.0.0', port=port)
deobfuscate.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2021-2024 CensoredUsername
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in
11
+ # all copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+
22
+
23
+ # This file contains documented strategies used against known obfuscation techniques and
24
+ # some machinery to test them against.
25
+
26
+ # Architecture is pretty simple. There's at least two steps in unpacking the rpyc format.
27
+ # RPYC2 is an archive format that can contain multiple streams (referred to as slots)
28
+ # The first step is extracting the slot from it, which is done by one of the extractors.
29
+ # These all give a blob that's either still zlib-compressed or just the raw slot
30
+ # (some methods rely on the zlib compression to figure out the slot length)
31
+ # Then, there's 0 or more steps of decrypting the data in that slot. This ends up often
32
+ # being layers of base64, string-escape, hex-encoding, zlib-compression, etc.
33
+ # We handle this by just trying these by checking if they fit.
34
+
35
+ import base64
36
+ import struct
37
+ import zlib
38
+ from collections import Counter
39
+
40
+ from decompiler.renpycompat import pickle_safe_loads
41
+
42
+ # Extractors are simple functions of (fobj, slotno) -> bytes
43
+ # They raise ValueError if they fail
44
+ EXTRACTORS = []
45
+ def extractor(f):
46
+ EXTRACTORS.append(f)
47
+ return f
48
+
49
+ # Decryptors are simple functions of (bytes, Counter) ->bytes
50
+ # They return None if they fail. If they return their input they're also considered to have failed.
51
+ DECRYPTORS = []
52
+ def decryptor(f):
53
+ DECRYPTORS.append(f)
54
+ return f
55
+
56
+
57
+ # Add game-specific custom extraction / decryption logic here
58
+
59
+ # End of custom extraction/decryption logic
60
+
61
+
62
+ @extractor
63
+ def extract_slot_rpyc(f, slot):
64
+ """
65
+ Slot extractor for a file that's in the actual rpyc format
66
+ """
67
+ f.seek(0)
68
+ data = f.read()
69
+ if data[:10] != b'RENPY RPC2':
70
+ raise ValueError("Incorrect Header")
71
+
72
+ position = 10
73
+ slots = {}
74
+
75
+ while position + 12 <= len(data):
76
+ slotid, start, length = struct.unpack("<III", data[position:position + 12])
77
+ if (slotid, start, length) == (0, 0, 0):
78
+ break
79
+
80
+ if start + length >= len(data):
81
+ raise ValueError("Broken slot entry")
82
+
83
+ slots[slotid] = (start, length)
84
+ position += 12
85
+ else:
86
+ raise ValueError("Broken slot header structure")
87
+
88
+ if slot not in slots:
89
+ raise ValueError("Unknown slot id")
90
+
91
+ start, length = slots[slot]
92
+ return data[start:start + length]
93
+
94
+ @extractor
95
+ def extract_slot_legacy(f, slot):
96
+ """
97
+ Slot extractor for the legacy format
98
+ """
99
+ if slot != 1:
100
+ raise ValueError("Legacy format only supports 1 slot")
101
+
102
+ f.seek(0)
103
+ data = f.read()
104
+
105
+ try:
106
+ data = zlib.decompress(data)
107
+ except zlib.error:
108
+ raise ValueError("Legacy format did not contain a zlib blob")
109
+
110
+ return data
111
+
112
+ @extractor
113
+ def extract_slot_headerscan(f, slot):
114
+ """
115
+ Slot extractor for things that changed the magic and so moved the header around.
116
+ """
117
+ f.seek(0)
118
+ data = f.read()
119
+
120
+ position = 0
121
+ while position + 36 < len(data):
122
+ a, b, c, d, e, f, g, h, i = struct.unpack("<IIIIIIIII", data[position:position + 36])
123
+ if a == 1 and d == 2 and g == 0 and b + c == e:
124
+ break
125
+ position += 1
126
+
127
+ else:
128
+ raise ValueError("Couldn't find a header")
129
+
130
+ slots = {}
131
+ while position + 12 <= len(data):
132
+ slotid, start, length = struct.unpack("<III", data[position:position + 12])
133
+ if (slotid, start, length) == (0, 0, 0):
134
+ break
135
+
136
+ if start + length >= len(data):
137
+ raise ValueError("Broken slot entry")
138
+
139
+ slots[slotid] = (start, length)
140
+ position += 12
141
+ else:
142
+ raise ValueError("Broken slot header structure")
143
+
144
+ if slot not in slots:
145
+ raise ValueError("Unknown slot id")
146
+
147
+ start, length = slots[slot]
148
+ return data[start:start + length]
149
+
150
+ @extractor
151
+ def extract_slot_zlibscan(f, slot):
152
+ """
153
+ Slot extractor for things that fucked with the header structure to the point where it's
154
+ easier to just not bother with it and instead we just look for valid zlib chunks directly.
155
+ """
156
+ f.seek(0)
157
+ data = f.read()
158
+
159
+ start_positions = []
160
+
161
+ for i in range(len(data) - 1):
162
+ if data[i] != 0x78:
163
+ continue
164
+
165
+ if (data[i] * 256 + data[i + 1]) % 31 != 0:
166
+ continue
167
+
168
+ start_positions.append(i)
169
+
170
+ chunks = []
171
+ for position in start_positions:
172
+ try:
173
+ chunk = zlib.decompress(data[position:])
174
+ except zlib.error:
175
+ continue
176
+ chunks.append(chunk)
177
+
178
+ if slot > len(chunks):
179
+ raise ValueError("Zlibscan did not find enough chunks")
180
+
181
+ return chunks[slot - 1]
182
+
183
+
184
+ @decryptor
185
+ def decrypt_zlib(data, count):
186
+ try:
187
+ return zlib.decompress(data)
188
+ except zlib.error:
189
+ return None
190
+
191
+ @decryptor
192
+ def decrypt_hex(data, count):
193
+ if not all(i in b"abcdefABCDEF0123456789" for i in count.keys()):
194
+ return None
195
+ try:
196
+ return data.decode("hex")
197
+ except Exception:
198
+ return None
199
+
200
+ @decryptor
201
+ def decrypt_base64(data, count):
202
+ if not all(i in b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=\n"
203
+ for i in count.keys()):
204
+ return None
205
+ try:
206
+ return base64.b64decode(data)
207
+ except Exception:
208
+ return None
209
+
210
+ @decryptor
211
+ def decrypt_string_escape(data, count):
212
+ if not all(i >= 0x20 and i < 0x80 for i in count.keys()):
213
+ return None
214
+ try:
215
+ newdata = data.decode("unicode-escape").encode('latin1')
216
+ except Exception:
217
+ return None
218
+ if newdata == data:
219
+ return None
220
+ return newdata
221
+
222
+
223
+ def assert_is_normal_rpyc(f):
224
+ """
225
+ Analyze the structure of a single rpyc file object for correctness.
226
+ Does not actually say anything about the _contents_ of that section, just that we were
227
+ able to slice it out of there.
228
+
229
+ If successful, returns the uncompressed contents of the first storage slot.
230
+ """
231
+
232
+ f.seek(0)
233
+ header = f.read(1024)
234
+ f.seek(0)
235
+
236
+ if header[:10] != b'RENPY RPC2':
237
+ # either legacy, or someone messed with the header
238
+
239
+ # assuming legacy, see if this thing is a valid zlib blob
240
+ raw_data = f.read()
241
+ f.seek(0)
242
+
243
+ try:
244
+ uncompressed = zlib.decompress(raw_data)
245
+ except zlib.error:
246
+ raise ValueError(
247
+ "Did not find RENPY RPC2 header, but interpretation as legacy file failed")
248
+
249
+ return uncompressed
250
+
251
+ else:
252
+ if len(header) < 46:
253
+ # 10 bytes header + 4 * 9 bytes content table
254
+ return ValueError("File too short")
255
+
256
+ a, b, c, d, e, f, g, h, i = struct.unpack("<IIIIIIIII", header[10:46])
257
+
258
+ # does the header format match default ren'py generated files?
259
+ if not (a == 1 and b == 46 and d == 2 and (g, h, i) == (0, 0, 0) and b + c == e):
260
+ return ValueError("Header data is abnormal, did the format gain extra fields?")
261
+
262
+ f.seek(b)
263
+ raw_data = f.read(c)
264
+ f.seek(0)
265
+ if len(raw_data) != c:
266
+ return ValueError("Header data is incompatible with file length")
267
+
268
+ try:
269
+ uncompressed = zlib.decompress(raw_data)
270
+ except zlib.error:
271
+ return ValueError("Slot 1 did not contain a zlib blob")
272
+
273
+ if not uncompressed.endswith("."):
274
+ return ValueError("Slot 1 did not contain a simple pickle")
275
+
276
+ return uncompressed
277
+
278
+
279
+ def read_ast(f, context):
280
+ diagnosis = ["Attempting to deobfuscate file:"]
281
+
282
+ raw_datas = set()
283
+
284
+ for extractor in EXTRACTORS:
285
+ try:
286
+ data = extractor(f, 1)
287
+ except ValueError as e:
288
+ # inside f-string braces "\" are not allowed before py3.12, so we use chr() till
289
+ # this our minimum py is
290
+ diagnosis.append(f'strategy {extractor.__name__} failed: {chr(10).join(e.args)}')
291
+ else:
292
+ diagnosis.append(f'strategy {extractor.__name__} success')
293
+ raw_datas.add(data)
294
+
295
+ if not raw_datas:
296
+ diagnosis.append("All strategies failed. Unable to extract data")
297
+ raise ValueError("\n".join(diagnosis))
298
+
299
+ if len(raw_datas) != 1:
300
+ diagnosis.append("Strategies produced different results. Trying all options")
301
+
302
+ data = None
303
+ for raw_data in raw_datas:
304
+ try:
305
+ data, stmts, d = try_decrypt_section(raw_data)
306
+ except ValueError as e:
307
+ diagnosis.append("\n".join(e.args))
308
+ else:
309
+ diagnosis.extend(d)
310
+ context.log("\n".join(diagnosis))
311
+ return stmts
312
+
313
+ diagnosis.append("All strategies failed. Unable to deobfuscate data")
314
+ raise ValueError("\n".join(diagnosis))
315
+
316
+
317
+ def try_decrypt_section(raw_data):
318
+ diagnosis = []
319
+
320
+ layers = 0
321
+ while layers < 10:
322
+ # can we load it yet?
323
+ try:
324
+ data, stmts = pickle_safe_loads(raw_data)
325
+ except Exception:
326
+ pass
327
+ else:
328
+ return data, stmts, diagnosis
329
+
330
+ layers += 1
331
+ count = Counter(raw_data)
332
+
333
+ for decryptor in DECRYPTORS:
334
+ newdata = decryptor(raw_data, count)
335
+ if newdata is None:
336
+ continue
337
+ else:
338
+ raw_data = newdata
339
+ diagnosis.append(f'performed a round of {decryptor.__name__}')
340
+ break
341
+ else:
342
+ break
343
+
344
+ diagnosis.append("Did not know how to decrypt data.")
345
+ raise ValueError("\n".join(diagnosis))
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Flask==3.1.3
2
+ gunicorn==22.0.0
rpyc_patcher.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import struct
2
+ import zlib
3
+ import pickle
4
+ import sys
5
+ from decompiler import magic, renpycompat
6
+
7
+ sys.setrecursionlimit(50000)
8
+
9
+ def unescape_wp_string(s):
10
+ """WordPress'ten gelen metinleri formatlar."""
11
+ if not isinstance(s, str): return s
12
+ s = s.replace('\\n', '\n')
13
+ s = s.replace('\\"', '"')
14
+ s = s.replace('\\ ', ' ')
15
+ s = s.replace('\\\\', '\\')
16
+ return s.replace('\r', '')
17
+
18
+ def apply_translation(text, translations):
19
+ """Sadece BİREBİR eşleşen metinleri güvenle çevirir (AST Çökmesini Önler)."""
20
+ if not isinstance(text, (str, bytes)): return text
21
+ is_bytes = isinstance(text, bytes)
22
+ text_str = text.decode('utf-8', 'ignore') if is_bytes else text
23
+
24
+ # Sadece birebir eşleşme (Tam Metin Eşleşmesi)
25
+ # Çünkü substring replace ('her' kelimesinin 'her room'u bozması gibi) AST'yi çökertir.
26
+ for k, v in translations.items():
27
+ clean_k = k
28
+ clean_v = v
29
+
30
+ # Eğer anahtarın başında ve sonunda tırnak varsa (örn: '"her room"') AST'deki tırnaksız haliyle eşleştir
31
+ if len(k) >= 2 and k[0] in ('"', "'") and k[-1] == k[0]:
32
+ clean_k = k[1:-1]
33
+ if len(v) >= 2 and v[0] in ('"', "'") and v[-1] == v[0]:
34
+ clean_v = v[1:-1]
35
+
36
+ if text_str == clean_k:
37
+ return clean_v.encode('utf-8') if is_bytes else clean_v
38
+
39
+ return text
40
+
41
+ def patch_ast(obj, translations, visited=None):
42
+ """Geliştiricinin ipucuna göre hedeflenmiş kusursuz AST Yamalayıcı."""
43
+ if visited is None: visited = set()
44
+ if obj is None or isinstance(obj, (int, float, bool, str, bytes)): return
45
+
46
+ obj_id = id(obj)
47
+ if obj_id in visited: return
48
+ visited.add(obj_id)
49
+
50
+ if isinstance(obj, list):
51
+ for i in range(len(obj)):
52
+ if isinstance(obj[i], (str, bytes)):
53
+ obj[i] = apply_translation(obj[i], translations)
54
+ else:
55
+ patch_ast(obj[i], translations, visited)
56
+
57
+ elif isinstance(obj, tuple):
58
+ for item in obj:
59
+ patch_ast(item, translations, visited)
60
+
61
+ elif isinstance(obj, dict):
62
+ # Sözlük boyutu değişimi (RuntimeError) hatalarını engellemek için list() kullanılır
63
+ for k, v in list(obj.items()):
64
+ if isinstance(v, (str, bytes)):
65
+ obj[k] = apply_translation(v, translations)
66
+ else:
67
+ patch_ast(v, translations, visited)
68
+
69
+ elif hasattr(obj, '__dict__'):
70
+ class_name = type(obj).__name__
71
+
72
+ # --- 1. GİZLİ SINIFLAR ---
73
+ if class_name in ('Say', 'TranslateSay') and hasattr(obj, 'what'):
74
+ obj.what = apply_translation(obj.what, translations)
75
+
76
+ elif class_name in ('Menu', 'TranslateMenu') and hasattr(obj, 'items'):
77
+ new_items = []
78
+ for item in obj.items:
79
+ label = apply_translation(item[0], translations)
80
+ if len(item) >= 3:
81
+ new_items.append((label, item[1], item[2]))
82
+ else:
83
+ new_items.append((label,) + item[1:])
84
+ obj.items = new_items
85
+
86
+ elif class_name == 'TranslateString':
87
+ if hasattr(obj, 'new'):
88
+ obj.new = apply_translation(obj.new, translations)
89
+
90
+ # --- 2. GÜVENLİ DERİN TARAMA ---
91
+ FORBIDDEN_KEYS = {'old', 'language', 'identifier', 'filename', 'name', 'label', 'parameters'}
92
+
93
+ for k, v in list(obj.__dict__.items()):
94
+ if k in FORBIDDEN_KEYS: continue
95
+ if class_name in ('Say', 'TranslateSay') and k == 'what': continue
96
+ if class_name in ('Menu', 'TranslateMenu') and k == 'items': continue
97
+ if class_name == 'TranslateString' and k == 'new': continue
98
+
99
+ if isinstance(v, (str, bytes)):
100
+ text_len = len(v) if isinstance(v, str) else len(v.decode('utf-8', 'ignore'))
101
+ if text_len >= 2:
102
+ setattr(obj, k, apply_translation(v, translations))
103
+ else:
104
+ patch_ast(v, translations, visited)
105
+
106
+ def is_safe_to_replace(k):
107
+ """RenPy script kodlarını ve sistem komutlarını koruyan güçlü filtre."""
108
+ k_strip = k.strip()
109
+ if len(k_strip) < 2: return False
110
+
111
+ # Sadece küçük harflerden oluşan kısa komut kelimelerini engelle (at, on, idle, hover vb.)
112
+ if k_strip.isalpha() and k_strip.islower() and len(k_strip) <= 6:
113
+ return False
114
+
115
+ forbidden_starts = ["SetVariable", "Jump", "Call", "Show", "Hide", "Play", "Stop", "action ", "at ", "imagebutton", "textbutton"]
116
+ for f in forbidden_starts:
117
+ if k_strip.startswith(f):
118
+ return False
119
+
120
+ return True
121
+
122
+ def process_rpyc_file(file_bytes, raw_translations):
123
+ """Tüm parçaları %100 orijinal format ve protokolünde birleştiren Ana Motor."""
124
+ sorted_keys = sorted(raw_translations.keys(), key=len, reverse=True)
125
+ clean_translations = {}
126
+ for k in sorted_keys:
127
+ clean_k = unescape_wp_string(k)
128
+ clean_v = unescape_wp_string(raw_translations[k])
129
+
130
+ # Sadece ÇEVRİLMİŞ olanları ve SİSTEM KODU OLMAYANLARI işleme dahil et
131
+ if clean_k.strip() and clean_k != clean_v:
132
+ if is_safe_to_replace(clean_k):
133
+ clean_translations[clean_k] = clean_v
134
+
135
+ if file_bytes.startswith(b"RENPY RPC2"):
136
+ position = 10
137
+ chunks = []
138
+
139
+ while True:
140
+ slot, start, length = struct.unpack("III", file_bytes[position:position+12])
141
+ position += 12
142
+ if slot == 0: break
143
+ chunks.append({"slot": slot, "start": start, "length": length})
144
+
145
+ payloads = {}
146
+
147
+ for c in chunks:
148
+ chunk_data = file_bytes[c["start"] : c["start"] + c["length"]]
149
+
150
+ if c["slot"] == 1:
151
+ raw_pickle = zlib.decompress(chunk_data)
152
+ orig_proto = 2
153
+ if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
154
+ orig_proto = raw_pickle[1]
155
+
156
+ ast_tree = renpycompat.pickle_loads(raw_pickle)
157
+ patch_ast(ast_tree, clean_translations)
158
+
159
+ new_pickle = pickle.dumps(ast_tree, protocol=orig_proto)
160
+ payloads[1] = zlib.compress(new_pickle)
161
+
162
+ elif c["slot"] == 2:
163
+ try:
164
+ raw_source = zlib.decompress(chunk_data).decode('utf-8')
165
+ for k, v in clean_translations.items():
166
+ raw_source = raw_source.replace(k, v)
167
+ payloads[2] = zlib.compress(raw_source.encode('utf-8'))
168
+ except Exception:
169
+ payloads[2] = chunk_data
170
+ else:
171
+ payloads[c["slot"]] = chunk_data
172
+
173
+ new_dir = bytearray()
174
+ current_offset = 10 + (len(chunks) + 1) * 12
175
+
176
+ for c in chunks:
177
+ data = payloads[c["slot"]]
178
+ new_dir.extend(struct.pack("III", c["slot"], current_offset, len(data)))
179
+ current_offset += len(data)
180
+
181
+ new_dir.extend(struct.pack("III", 0, 0, 0))
182
+
183
+ new_file = bytearray(b"RENPY RPC2")
184
+ new_file.extend(new_dir)
185
+ for c in chunks:
186
+ new_file.extend(payloads[c["slot"]])
187
+
188
+ return bytes(new_file)
189
+
190
+ else:
191
+ raw_pickle = zlib.decompress(file_bytes)
192
+ orig_proto = 2
193
+ if len(raw_pickle) >= 2 and raw_pickle[0] == 0x80:
194
+ orig_proto = raw_pickle[1]
195
+ ast_tree = renpycompat.pickle_loads(raw_pickle)
196
+ patch_ast(ast_tree, clean_translations)
197
+ return zlib.compress(pickle.dumps(ast_tree, protocol=orig_proto))
198
+
setup.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from setuptools import setup
3
+
4
+ def readme():
5
+ with open('README.md') as f:
6
+ return f.read()
7
+ setup(
8
+ name='unrpyc',
9
+ version='0.1',
10
+ description='Tool to decompile Ren\'Py compiled .rpyc script files.',
11
+ long_description=readme(),
12
+ url='https://github.com/CensoredUsername/unrpyc',
13
+ py_modules=['unrpyc', '.deobfuscate'],
14
+ packages=['decompiler'],
15
+ scripts=['unrpyc.py'],
16
+ zip_safe=False,
17
+ )
unrpyc.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2012-2024 Yuri K. Schlesner, CensoredUsername, Jackmcbarn
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+
24
+ __title__ = "Unrpyc"
25
+ __version__ = 'v2.0.3'
26
+ __url__ = "https://github.com/CensoredUsername/unrpyc"
27
+
28
+
29
+ import argparse
30
+ import glob
31
+ import struct
32
+ import sys
33
+ import traceback
34
+ import zlib
35
+ from pathlib import Path
36
+
37
+ try:
38
+ # this script is often used in environments where multiprocessing is not available
39
+ # or broken. So test if it's available, and then actually use it by creating a Lock
40
+ # because it lazily loads its C-backend and that might be missing.
41
+ from multiprocessing import Lock, Pool, cpu_count, current_process, freeze_support
42
+ import _multiprocessing
43
+ Lock()
44
+
45
+ except ImportError:
46
+ traceback.print_exc(file=sys.stdout)
47
+ print("The multiprocessing module is not available or broken! Proceeding with single threaded "
48
+ "decompilation. This will be slow.\n")
49
+
50
+ # Mock the parts of multiprocessing that we need
51
+ def cpu_count():
52
+ return 1
53
+
54
+ # needed in case people use py2exe on the tool
55
+ def freeze_support():
56
+ pass
57
+
58
+ class Pool:
59
+ """
60
+ A minimal single-threaded mock of the multiprocessing.Pool class.
61
+ """
62
+
63
+ def __init__(self, processes=None, initializer=None, initargs=None):
64
+ pass
65
+
66
+ def imap(self, func, iterable, chunksize=1):
67
+ # In Python 3, the built-in map() returns a lazy iterator,
68
+ # which is exactly what is needed to mimic pool.imap.
69
+ return map(func, iterable)
70
+
71
+ def close(self):
72
+ pass
73
+
74
+ def join(self):
75
+ pass
76
+
77
+ def __enter__(self):
78
+ return self
79
+
80
+ def __exit__(self, exc_type, exc_val, exc_tb):
81
+ pass
82
+
83
+ import decompiler
84
+ import deobfuscate
85
+ from decompiler import astdump, translate
86
+ from decompiler.renpycompat import (pickle_safe_loads, pickle_safe_dumps, pickle_loads,
87
+ pickle_detect_python2)
88
+
89
+
90
+ class Context:
91
+ def __init__(self):
92
+ # list of log lines to print
93
+ self.log_contents = []
94
+
95
+ # any exception that occurred
96
+ self.error = None
97
+
98
+ # state of what case was encountered
99
+ # options:
100
+ # error: (default) an unexpected exception was raised
101
+ # ok: the process concluded successfully
102
+ # bad_header: the given file cannot be parsed as a normal rpyc file
103
+ # skip: the given file was skipped due to a preexisting output file
104
+ self.state = "error"
105
+
106
+ # return value from the worker, if any
107
+ self.value = None
108
+
109
+ def log(self, message):
110
+ self.log_contents.append(message)
111
+
112
+ def set_error(self, error):
113
+ self.error = error
114
+
115
+ def set_result(self, value):
116
+ self.value = value
117
+
118
+ def set_state(self, state):
119
+ self.state = state
120
+
121
+
122
+ class BadRpycException(Exception):
123
+ """Exception raised when we couldn't parse the rpyc archive format"""
124
+ pass
125
+
126
+
127
+ # API
128
+
129
+ def read_ast_from_file(in_file, context):
130
+ # Reads rpyc v1 or v2 file
131
+ # v1 files are just a zlib compressed pickle blob containing some data and the ast
132
+ # v2 files contain a basic archive structure that can be parsed to find the same blob
133
+ raw_contents = in_file.read()
134
+ file_start = raw_contents[:50]
135
+ is_rpyc_v1 = False
136
+
137
+ if not raw_contents.startswith(b"RENPY RPC2"):
138
+ # if the header isn't present, it should be a RPYC V1 file, which is just the blob
139
+ contents = raw_contents
140
+ is_rpyc_v1 = True
141
+
142
+ else:
143
+ # parse the archive structure
144
+ position = 10
145
+ chunks = {}
146
+ have_errored = False
147
+
148
+ for expected_slot in range(1, 0xFFFFFFFF):
149
+ slot, start, length = struct.unpack("III", raw_contents[position: position + 12])
150
+
151
+ if slot == 0:
152
+ break
153
+
154
+ if slot != expected_slot and not have_errored:
155
+ have_errored = True
156
+
157
+ context.log(
158
+ "Warning: Encountered an unexpected slot structure. It is possible the \n"
159
+ " file header structure has been changed.")
160
+
161
+ position += 12
162
+
163
+ chunks[slot] = raw_contents[start: start + length]
164
+
165
+ if 1 not in chunks:
166
+ context.set_state('bad_header')
167
+ raise BadRpycException(
168
+ "Unable to find the right slot to load from the rpyc file. The file header "
169
+ f"structure has been changed. File header: {file_start}")
170
+
171
+ contents = chunks[1]
172
+
173
+ try:
174
+ contents = zlib.decompress(contents)
175
+ except Exception:
176
+ context.set_state('bad_header')
177
+ raise BadRpycException(
178
+ "Did not find a zlib compressed blob where it was expected. Either the header has been "
179
+ f"modified or the file structure has been changed. File header: {file_start}") from None
180
+
181
+ # add some detection of ren'py 7 files
182
+ if is_rpyc_v1 or pickle_detect_python2(contents):
183
+ version = "6" if is_rpyc_v1 else "7"
184
+
185
+ context.log(
186
+ "Warning: analysis found signs that this .rpyc file was generated by ren'py \n"
187
+ f' version {version} or below, while this unrpyc version targets ren\'py \n'
188
+ " version 8. Decompilation will still be attempted, but errors or incorrect \n"
189
+ " decompilation might occur. ")
190
+
191
+ _, stmts = pickle_safe_loads(contents)
192
+ return stmts
193
+
194
+
195
+ def get_ast(in_file, try_harder, context):
196
+ """
197
+ Opens the rpyc file at path in_file to load the contained AST.
198
+ If try_harder is True, an attempt will be made to work around obfuscation techniques.
199
+ Else, it is loaded as a normal rpyc file.
200
+ """
201
+ with in_file.open('rb') as in_file:
202
+ if try_harder:
203
+ ast = deobfuscate.read_ast(in_file, context)
204
+ else:
205
+ ast = read_ast_from_file(in_file, context)
206
+ return ast
207
+
208
+
209
+ def decompile_rpyc(input_filename, context, overwrite=False, try_harder=False, dump=False,
210
+ comparable=False, no_pyexpr=False, translator=None, init_offset=False,
211
+ sl_custom_names=None):
212
+
213
+ # Output filename is input filename but with .rpy extension
214
+ if dump:
215
+ ext = '.txt'
216
+ elif input_filename.suffix == ('.rpyc'):
217
+ ext = '.rpy'
218
+ elif input_filename.suffix == ('.rpymc'):
219
+ ext = '.rpym'
220
+ out_filename = input_filename.with_suffix(ext)
221
+
222
+
223
+ if not overwrite and out_filename.exists():
224
+ context.log(f'Skipping {input_filename}. {out_filename.name} already exists.')
225
+ context.set_state('skip')
226
+ return
227
+
228
+ context.log(f'Decompiling {input_filename} to {out_filename.name} ...')
229
+ ast = get_ast(input_filename, try_harder, context)
230
+
231
+ with out_filename.open('w', encoding='utf-8') as out_file:
232
+ if dump:
233
+ astdump.pprint(out_file, ast, comparable=comparable, no_pyexpr=no_pyexpr)
234
+ else:
235
+ options = decompiler.Options(log=context.log_contents, translator=translator,
236
+ init_offset=init_offset, sl_custom_names=sl_custom_names)
237
+
238
+ decompiler.pprint(out_file, ast, options)
239
+
240
+ context.set_state('ok')
241
+
242
+
243
+ def worker_tl(arg_tup):
244
+ """
245
+ This file implements the first pass of the translation feature. It gathers TL-data from the
246
+ given rpyc files, to be used by the common worker to translate while decompiling.
247
+ arg_tup is (args, filename). Returns the gathered TL data in the context.
248
+ """
249
+ args, filename = arg_tup
250
+ context = Context()
251
+
252
+ try:
253
+ context.log(f'Extracting translations from {filename}...')
254
+ ast = get_ast(filename, args.try_harder, context)
255
+
256
+ tl_inst = translate.Translator(args.translate, True)
257
+ tl_inst.translate_dialogue(ast)
258
+
259
+ # this object has to be sent back to the main process, for which it needs to be pickled.
260
+ # the default pickler cannot pickle fake classes correctly, so manually handle that here.
261
+ context.set_result(pickle_safe_dumps((tl_inst.dialogue, tl_inst.strings)))
262
+ context.set_state("ok")
263
+
264
+ except Exception as e:
265
+ context.set_error(e)
266
+ context.log(f'Error while extracting translations from {filename}:')
267
+ context.log(traceback.format_exc())
268
+
269
+ return context
270
+
271
+
272
+ def worker_common(arg_tup):
273
+ """
274
+ The core of unrpyc. arg_tup is (args, filename). This worker will unpack the file at filename,
275
+ decompile it, and write the output to it's corresponding rpy file.
276
+ """
277
+
278
+ args, filename = arg_tup
279
+ context = Context()
280
+
281
+ if args.translator:
282
+ args.translator = pickle_loads(args.translator)
283
+
284
+ try:
285
+ decompile_rpyc(
286
+ filename, context, overwrite=args.clobber, try_harder=args.try_harder,
287
+ dump=args.dump, no_pyexpr=args.no_pyexpr, comparable=args.comparable,
288
+ init_offset=args.init_offset, sl_custom_names=args.sl_custom_names,
289
+ translator=args.translator)
290
+
291
+ except Exception as e:
292
+ context.set_error(e)
293
+ context.log(f'Error while decompiling {filename}:')
294
+ context.log(traceback.format_exc())
295
+
296
+ return context
297
+
298
+
299
+ def run_workers(worker, common_args, private_args, parallelism):
300
+ """
301
+ Runs worker in parallel using multiprocessing, with a max of `parallelism` processes.
302
+ Workers are called as worker((common_args, private_args[i])).
303
+ Workers should return an instance of `Context` as return value.
304
+ """
305
+
306
+ worker_args = ((common_args, x) for x in private_args)
307
+
308
+ results = []
309
+ with Pool(parallelism) as pool:
310
+ for result in pool.imap(worker, worker_args, 1):
311
+ results.append(result)
312
+
313
+ for line in result.log_contents:
314
+ print(line)
315
+
316
+ print("")
317
+
318
+ return results
319
+
320
+
321
+ def parse_sl_custom_names(unparsed_arguments):
322
+ # parse a list of strings in the format
323
+ # classname=name-nchildren into {classname: (name, nchildren)}
324
+ parsed_arguments = {}
325
+ for argument in unparsed_arguments:
326
+ content = argument.split("=")
327
+ if len(content) != 2:
328
+ raise Exception(f'Bad format in custom sl displayable registration: "{argument}"')
329
+
330
+ classname, name = content
331
+ split = name.split("-")
332
+ if len(split) == 1:
333
+ amount = "many"
334
+
335
+ elif len(split) == 2:
336
+ name, amount = split
337
+ if amount == "0":
338
+ amount = 0
339
+ elif amount == "1":
340
+ amount = 1
341
+ elif amount == "many":
342
+ pass
343
+ else:
344
+ raise Exception(
345
+ f'Bad child node count in custom sl displayable registration: "{argument}"')
346
+
347
+ else:
348
+ raise Exception(
349
+ f'Bad format in custom sl displayable registration: "{argument}"')
350
+
351
+ parsed_arguments[classname] = (name, amount)
352
+
353
+ return parsed_arguments
354
+
355
+
356
+ def plural_s(n, unit):
357
+ """Correctly uses the plural form of 'unit' when 'n' is not one"""
358
+ return f"1 {unit}" if n == 1 else f"{n} {unit}s"
359
+
360
+
361
+ def main():
362
+ if not sys.version_info[:2] >= (3, 9):
363
+ raise Exception(
364
+ f"'{__title__} {__version__}' must be executed with Python 3.9 or later.\n"
365
+ f"You are running {sys.version}")
366
+
367
+ # argparse usage: python3 unrpyc.py [-c] [--try-harder] [-d] [-p] file [file ...]
368
+ cc_num = cpu_count()
369
+ ap = argparse.ArgumentParser(description="Decompile .rpyc/.rpymc files")
370
+
371
+ ap.add_argument(
372
+ 'file',
373
+ type=str,
374
+ nargs='+',
375
+ help="The filenames to decompile. "
376
+ "All .rpyc files in any sub-/directories passed will also be decompiled.")
377
+
378
+ ap.add_argument(
379
+ '-c',
380
+ '--clobber',
381
+ dest='clobber',
382
+ action='store_true',
383
+ help="Overwrites output files if they already exist.")
384
+
385
+ ap.add_argument(
386
+ '--try-harder',
387
+ dest="try_harder",
388
+ action="store_true",
389
+ help="Tries some workarounds against common obfuscation methods. This is a lot slower.")
390
+
391
+ ap.add_argument(
392
+ '-p',
393
+ '--processes',
394
+ dest='processes',
395
+ action='store',
396
+ type=int,
397
+ choices=list(range(1, cc_num)),
398
+ default=cc_num - 1 if cc_num > 2 else 1,
399
+ help="Use the specified number or processes to decompile. "
400
+ "Defaults to the amount of hw threads available minus one, disabled when multiprocessing is "
401
+ "unavailable.")
402
+
403
+ astdump = ap.add_argument_group('astdump options', 'All unrpyc options related to ast-dumping.')
404
+ astdump.add_argument(
405
+ '-d',
406
+ '--dump',
407
+ dest='dump',
408
+ action='store_true',
409
+ help="Instead of decompiling, pretty print the ast to a file")
410
+
411
+ astdump.add_argument(
412
+ '--comparable',
413
+ dest='comparable',
414
+ action='store_true',
415
+ help="Only for dumping, remove several false differences when comparing dumps. "
416
+ "This suppresses attributes that are different even when the code is identical, such as "
417
+ "file modification times. ")
418
+
419
+ astdump.add_argument(
420
+ '--no-pyexpr',
421
+ dest='no_pyexpr',
422
+ action='store_true',
423
+ help="Only for dumping, disable special handling of PyExpr objects, instead printing them "
424
+ "as strings. This is useful when comparing dumps from different versions of Ren'Py. It "
425
+ "should only be used if necessary, since it will cause loss of information such as line "
426
+ "numbers.")
427
+
428
+ ap.add_argument(
429
+ '--no-init-offset',
430
+ dest='init_offset',
431
+ action='store_false',
432
+ help="By default, unrpyc attempts to guess when init offset statements were used and insert "
433
+ "them. This is always safe to do for ren'py 8, but as it is based on a heuristic it can be "
434
+ "disabled. The generated code is exactly equivalent, only slightly more cluttered.")
435
+
436
+ ap.add_argument(
437
+ '--register-sl-displayable',
438
+ dest="sl_custom_names",
439
+ type=str,
440
+ nargs='+',
441
+ help="Accepts mapping separated by '=', "
442
+ "where the first argument is the name of the user-defined displayable object, "
443
+ "and the second argument is a string containing the name of the displayable, "
444
+ "potentially followed by a '-', and the amount of children the displayable takes"
445
+ "(valid options are '0', '1' or 'many', with 'many' being the default)")
446
+
447
+ ap.add_argument(
448
+ '-t',
449
+ '--translate',
450
+ dest='translate',
451
+ type=str,
452
+ action='store',
453
+ help="Changes the dialogue language in the decompiled script files, using a translation "
454
+ "already present in the tl dir.")
455
+
456
+ ap.add_argument(
457
+ '--version',
458
+ action='version',
459
+ version=f"{__title__} {__version__}")
460
+
461
+ args = ap.parse_args()
462
+
463
+ # Catch impossible arg combinations so they don't produce strange errors or fail silently
464
+ if (args.no_pyexpr or args.comparable) and not args.dump:
465
+ ap.error("Options '--comparable' and '--no_pyexpr' require '--dump'.")
466
+
467
+ if args.dump and args.translate:
468
+ ap.error("Options '--translate' and '--dump' cannot be used together.")
469
+
470
+ if args.sl_custom_names is not None:
471
+ try:
472
+ args.sl_custom_names = parse_sl_custom_names(args.sl_custom_names)
473
+ except Exception as e:
474
+ print("\n".join(e.args))
475
+ return
476
+
477
+ def glob_or_complain(inpath):
478
+ """Expands wildcards and casts output to pathlike state."""
479
+ retval = [Path(elem).resolve(strict=True) for elem in glob.glob(inpath, recursive=True)]
480
+ if not retval:
481
+ print(f'Input path not found: {inpath}')
482
+ return retval
483
+
484
+ def traverse(inpath):
485
+ """
486
+ Filters from input path for rpyc/rpymc files and returns them. Recurses into all given
487
+ directories by calling itself.
488
+ """
489
+ if inpath.is_file() and inpath.suffix in ['.rpyc', '.rpymc']:
490
+ yield inpath
491
+ elif inpath.is_dir():
492
+ for item in inpath.iterdir():
493
+ yield from traverse(item)
494
+
495
+ # Check paths from argparse through globing and pathlib. Constructs a tasklist with all
496
+ # `Ren'Py compiled files` the app was assigned to process.
497
+ worklist = []
498
+ for entry in args.file:
499
+ for globitem in glob_or_complain(entry):
500
+ for elem in traverse(globitem):
501
+ worklist.append(elem)
502
+
503
+ # Check if we actually have files. Don't worry about no parameters passed,
504
+ # since ArgumentParser catches that
505
+ if not worklist:
506
+ print("Found no script files to decompile.")
507
+ return
508
+
509
+ if args.processes > len(worklist):
510
+ args.processes = len(worklist)
511
+
512
+ print(f"Found {plural_s(len(worklist), 'file')} to process. "
513
+ f"Performing decompilation using {plural_s(args.processes, 'worker')}.")
514
+
515
+ # If a big file starts near the end, there could be a long time with only one thread running,
516
+ # which is inefficient. Avoid this by starting big files first.
517
+ worklist.sort(key=lambda x: x.stat().st_size, reverse=True)
518
+
519
+ translation_errors = 0
520
+ args.translator = None
521
+ if args.translate:
522
+ # For translation, we first need to analyse all files for translation data.
523
+ # We then collect all of these back into the main process, and build a
524
+ # datastructure of all of them. This datastructure is then passed to
525
+ # all decompiling processes.
526
+ # Note: because this data contains some FakeClasses, Multiprocessing cannot
527
+ # pass it between processes (it pickles them, and pickle will complain about
528
+ # these). Therefore, we need to manually pickle and unpickle it.
529
+
530
+ print("Step 1: analysing files for translations.")
531
+ results = run_workers(worker_tl, args, worklist, args.processes)
532
+
533
+ print('Compiling extracted translations.')
534
+ tl_dialogue = {}
535
+ tl_strings = {}
536
+ for entry in results:
537
+ if entry.state != "ok":
538
+ translation_errors += 1
539
+
540
+ if entry.value:
541
+ new_dialogue, new_strings = pickle_loads(entry.value)
542
+ tl_dialogue.update(new_dialogue)
543
+ tl_strings.update(new_strings)
544
+
545
+ translator = translate.Translator(None)
546
+ translator.dialogue = tl_dialogue
547
+ translator.strings = tl_strings
548
+ args.translator = pickle_safe_dumps(translator)
549
+
550
+ print("Step 2: decompiling.")
551
+
552
+ results = run_workers(worker_common, args, worklist, args.processes)
553
+
554
+ success = sum(result.state == "ok" for result in results)
555
+ skipped = sum(result.state == "skip" for result in results)
556
+ failed = sum(result.state == "error" for result in results)
557
+ broken = sum(result.state == "bad_header" for result in results)
558
+
559
+ print("")
560
+ print(f"{55 * '-'}")
561
+ print(f"{__title__} {__version__} results summary:")
562
+ print(f"{55 * '-'}")
563
+ print(f"Processed {plural_s(len(results), 'file')}.")
564
+
565
+ print(f"> {plural_s(success, 'file')} were successfully decompiled.")
566
+
567
+ if broken:
568
+ print(f"> {plural_s(broken, 'file')} did not have the correct header, "
569
+ "these were ignored.")
570
+
571
+ if failed:
572
+ print(f"> {plural_s(failed, 'file')} failed to decompile due to errors.")
573
+
574
+ if skipped:
575
+ print(f"> {plural_s(skipped, 'file')} were skipped as the output file already existed.")
576
+
577
+ if translation_errors:
578
+ print(f"> {plural_s(translation_errors, 'file')} failed translation extraction.")
579
+
580
+
581
+ if skipped:
582
+ print("")
583
+ print("To overwrite existing files instead of skipping them, use the --clobber flag.")
584
+
585
+ if broken:
586
+ print("")
587
+ print("To attempt to bypass modifications to the file header, use the --try-harder flag.")
588
+
589
+ if failed:
590
+ print("")
591
+ print("Errors were encountered during decompilation. Check the log for more information.")
592
+ print("When making a bug report, please include this entire log.")
593
+
594
+ if __name__ == '__main__':
595
+ if sys.platform == "win32":
596
+ freeze_support()
597
+
598
+ main()