113 lines
5.2 KiB
Python
113 lines
5.2 KiB
Python
"""Replace APK members and preserve the original ZIP metadata of all entries."""
|
|
|
|
import argparse
|
|
import os
|
|
import struct
|
|
import zipfile
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
|
|
LOCAL_HEADER = struct.Struct("<IHHHHHIIIHH")
|
|
CENTRAL_FIXED_SIZE = 46
|
|
OLD_SIGNATURES = (".SF", ".RSA", ".DSA", ".EC", "MANIFEST.MF")
|
|
|
|
|
|
def is_obsolete_signature(name: str) -> bool:
|
|
return name.startswith("META-INF/") and name.upper().endswith(OLD_SIGNATURES)
|
|
|
|
|
|
def repack(source: Path, replacement: Path, member: str, output: Path) -> None:
|
|
repack_members(source, {member: replacement}, output)
|
|
|
|
|
|
def repack_members(source: Path, replacements: dict[str, Path], output: Path) -> None:
|
|
temporary = output.with_name(output.name + ".tmp")
|
|
if temporary.exists():
|
|
raise FileExistsError(f"Temporary output already exists: {temporary}")
|
|
replacements_data = {name: path.read_bytes() for name, path in replacements.items()}
|
|
with source.open("rb") as src, zipfile.ZipFile(src) as zin, temporary.open("xb") as dst:
|
|
offsets = {}
|
|
for info in zin.infolist():
|
|
if is_obsolete_signature(info.filename):
|
|
continue
|
|
|
|
src.seek(info.header_offset)
|
|
fields = LOCAL_HEADER.unpack(src.read(LOCAL_HEADER.size))
|
|
local_size = LOCAL_HEADER.size + fields[-2] + fields[-1] + info.compress_size
|
|
src.seek(info.header_offset)
|
|
local_record = src.read(local_size)
|
|
if len(local_record) != local_size:
|
|
raise IOError(f"Truncated local record: {info.filename}")
|
|
|
|
if info.filename in replacements_data:
|
|
replacement_data = replacements_data[info.filename]
|
|
if info.flag_bits & 0x08:
|
|
raise ValueError("A streamed data descriptor is not supported here")
|
|
compressed = replacement_data
|
|
if info.compress_type == zipfile.ZIP_DEFLATED:
|
|
compressor = zlib.compressobj(6, zlib.DEFLATED, -15)
|
|
compressed = compressor.compress(replacement_data) + compressor.flush()
|
|
elif info.compress_type != zipfile.ZIP_STORED:
|
|
raise ValueError(f"Unsupported compression method: {info.compress_type}")
|
|
info.CRC = zlib.crc32(replacement_data) & 0xFFFFFFFF
|
|
info.compress_size = len(compressed)
|
|
info.file_size = len(replacement_data)
|
|
patched = bytearray(local_record)
|
|
struct.pack_into("<III", patched, 14, info.CRC, info.compress_size, info.file_size)
|
|
local_record = bytes(patched[:LOCAL_HEADER.size + fields[-2] + fields[-1]]) + compressed
|
|
|
|
offsets[info.filename] = dst.tell()
|
|
dst.write(local_record)
|
|
|
|
missing = replacements_data.keys() - offsets.keys()
|
|
if missing:
|
|
raise ValueError(f"Replacement members missing: {sorted(missing)}")
|
|
central_offset = dst.tell()
|
|
infos = {info.filename: info for info in zin.infolist()}
|
|
for info in zin.infolist():
|
|
if is_obsolete_signature(info.filename):
|
|
continue
|
|
if info.extra or info.comment:
|
|
raise ValueError("Extra fields and entry comments are not supported")
|
|
|
|
# Read the source central directory once; entry sizes and names are unchanged.
|
|
source_start = zin.start_dir
|
|
src.seek(source_start)
|
|
source_central = src.read()
|
|
pos = 0
|
|
remaining = {name for name in infos if not is_obsolete_signature(name)}
|
|
while pos < len(source_central):
|
|
if source_central[pos:pos + 4] != b"PK\x01\x02":
|
|
break
|
|
fields = struct.unpack_from("<IHHHHHHIIIHHHHHII", source_central, pos)
|
|
name_len, extra_len, comment_len = fields[10:13]
|
|
record_len = CENTRAL_FIXED_SIZE + name_len + extra_len + comment_len
|
|
name_bytes = source_central[pos + CENTRAL_FIXED_SIZE:pos + CENTRAL_FIXED_SIZE + name_len]
|
|
name = name_bytes.decode("utf-8" if fields[3] & 0x800 else "cp437")
|
|
if not is_obsolete_signature(name):
|
|
record = bytearray(source_central[pos:pos + record_len])
|
|
struct.pack_into("<I", record, 42, offsets[name])
|
|
info = infos[name]
|
|
struct.pack_into("<III", record, 16, info.CRC, info.compress_size, info.file_size)
|
|
dst.write(record)
|
|
remaining.remove(name)
|
|
pos += record_len
|
|
if remaining:
|
|
raise ValueError(f"Central directory entries missing: {sorted(remaining)}")
|
|
central_size = dst.tell() - central_offset
|
|
count = len(infos) - sum(is_obsolete_signature(name) for name in infos)
|
|
dst.write(struct.pack("<IHHHHIIH", 0x06054B50, 0, 0, count, count,
|
|
central_size, central_offset, 0))
|
|
os.replace(temporary, output)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("source", type=Path)
|
|
parser.add_argument("replacement", type=Path)
|
|
parser.add_argument("output", type=Path)
|
|
parser.add_argument("--member", default="assets/MYRMain.app")
|
|
args = parser.parse_args()
|
|
repack(args.source, args.replacement, args.member, args.output)
|