202 lines
11 KiB
Python
202 lines
11 KiB
Python
# MPQ fixtures (tools/fixtures.py). StormLib (nix stormlib, through ctypes) writes the archives from random files:
|
|
# header versions 1-4, every sector compression it offers (zlib, PKWARE implode, bzip2, LZMA, sparse + zlib /
|
|
# bzip2), MPQ_FILE_IMPLODE files, single-unit files, encrypted files (plain and fix-key), sector CRCs, several
|
|
# sector sizes, a (listfile) and (attributes); one archive behind a 1024-byte prefix, one without a listfile (files
|
|
# named by block index), one with a Huffman (WAVE) sector. Raw PKWARE DCL streams from StormLib's SCompImplode
|
|
# (binary and ASCII modes, 1 / 2 / 4 KB dictionaries) for codecs/compress/Explode.
|
|
# tests/gen/mpq.luau { archives = { { name, data, version, files = { { name, size, crc } }, unnamed? } },
|
|
# implode = { { name, data, size, crc } }, huffman = data }
|
|
import ctypes, json, os, shutil, subprocess, tempfile, zlib
|
|
|
|
INPUTS = []
|
|
|
|
CODE = r"""
|
|
import ctypes, json, os, sys, zlib
|
|
args = json.loads(sys.stdin.read())
|
|
lib = ctypes.CDLL(args["lib"])
|
|
lib.SFileCreateArchive.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p)]
|
|
lib.SFileAddFileEx.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32]
|
|
lib.SFileCloseArchive.argtypes = [ctypes.c_void_p]
|
|
lib.SFileSetMaxFileCount.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
|
|
lib.SCompImplode.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), ctypes.c_void_p, ctypes.c_int]
|
|
lib.SCompImplode.restype = ctypes.c_int
|
|
out = {}
|
|
for a in args["archives"]:
|
|
h = ctypes.c_void_p()
|
|
path = a["path"].encode()
|
|
if os.path.exists(path):
|
|
os.remove(path)
|
|
if not lib.SFileCreateArchive(path, a["create"], 64, ctypes.byref(h)):
|
|
raise SystemExit("create failed: %s" % a["path"])
|
|
for f in a["files"]:
|
|
if not lib.SFileAddFileEx(h, f["src"].encode(), f["name"].encode(), f["flags"], f["comp"], f["comp"]):
|
|
raise SystemExit("add failed: %s %s" % (f["name"], ctypes.get_errno()))
|
|
lib.SFileCloseArchive(h)
|
|
lib.SFileOpenArchive.argtypes = [ctypes.c_char_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p)]
|
|
lib.SFileHasFile.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
present = {}
|
|
for a in args["archives"]:
|
|
h = ctypes.c_void_p()
|
|
if not lib.SFileOpenArchive(a["path"].encode(), 0, 0x100, ctypes.byref(h)):
|
|
raise SystemExit("open failed: %s" % a["path"])
|
|
present[a["name"]] = [f["name"] for f in a["files"] if lib.SFileHasFile(h, f["name"].encode())]
|
|
lib.SFileCloseArchive(h)
|
|
res = []
|
|
for s in args["implode"]:
|
|
data = open(s["src"], "rb").read()
|
|
buf = ctypes.create_string_buffer(len(data) * 2 + 64)
|
|
n = ctypes.c_int(len(buf))
|
|
src = ctypes.create_string_buffer(data, len(data))
|
|
# SCompImplode always uses binary mode, dictionary by size; StormLib picks 4 KB for big inputs
|
|
ok = lib.SCompImplode(buf, ctypes.byref(n), src, len(data))
|
|
res.append({"name": s["name"], "data": buf.raw[:n.value].hex(), "size": len(data), "crc": zlib.crc32(data)})
|
|
# pklib's implode() directly: ASCII (coded literals) and binary modes, every dictionary size
|
|
READ = ctypes.CFUNCTYPE(ctypes.c_uint, ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_uint), ctypes.c_void_p)
|
|
WRITE = ctypes.CFUNCTYPE(None, ctypes.POINTER(ctypes.c_char), ctypes.POINTER(ctypes.c_uint), ctypes.c_void_p)
|
|
lib.implode.argtypes = [READ, WRITE, ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]
|
|
for s in args["modes"]:
|
|
data = open(s["src"], "rb").read()
|
|
state = {"pos": 0, "out": bytearray()}
|
|
def rd(buf, size, param):
|
|
n = min(size[0], len(data) - state["pos"])
|
|
ctypes.memmove(buf, data[state["pos"]:state["pos"] + n], n)
|
|
state["pos"] += n
|
|
return n
|
|
def wr(buf, size, param):
|
|
state["out"] += ctypes.string_at(buf, size[0])
|
|
rcb, wcb = READ(rd), WRITE(wr)
|
|
work = ctypes.create_string_buffer(65536)
|
|
lib.implode(rcb, wcb, work, None, ctypes.byref(ctypes.c_uint(s["type"])), ctypes.byref(ctypes.c_uint(s["dsize"])))
|
|
res.append({"name": s["name"], "data": bytes(state["out"]).hex(), "size": len(data), "crc": zlib.crc32(data)})
|
|
print(json.dumps({"implode": res, "present": present}))
|
|
"""
|
|
|
|
IMPLODE, COMPRESS, ENCRYPTED, FIX_KEY, SINGLE, SECTOR_CRC, REPLACE = 0x100, 0x200, 0x10000, 0x20000, 0x1000000, 0x4000000, 0x80000000
|
|
ZLIB, PKWARE, BZIP2, SPARSE, LZMA, HUFF, ADPCM_MONO = 0x02, 0x08, 0x10, 0x20, 0x12, 0x01, 0x40
|
|
|
|
|
|
# an independent MPQ crypt (the format description's algorithm) to delete the (listfile) hash entry of "nolist"
|
|
def crypt_table():
|
|
t, seed = [0] * 0x500, 0x00100001
|
|
for i1 in range(256):
|
|
i2 = i1
|
|
for _ in range(5):
|
|
seed = (seed * 125 + 3) % 0x2AAAAB
|
|
t1 = (seed & 0xFFFF) << 16
|
|
seed = (seed * 125 + 3) % 0x2AAAAB
|
|
t[i2] = t1 | (seed & 0xFFFF)
|
|
i2 += 0x100
|
|
return t
|
|
|
|
|
|
CT = crypt_table()
|
|
M = 0xFFFFFFFF
|
|
|
|
|
|
def mpq_hash(s, kind):
|
|
s1, s2 = 0x7FED7FED, 0xEEEEEEEE
|
|
for c in s.upper().replace("/", "\\").encode():
|
|
s1 = CT[kind * 0x100 + c] ^ ((s1 + s2) & M)
|
|
s2 = (c + s1 + s2 + (s2 << 5) + 3) & M
|
|
return s1
|
|
|
|
|
|
def crypt(words, key, decrypt):
|
|
s2, out = 0xEEEEEEEE, []
|
|
for v in words:
|
|
s2 = (s2 + CT[0x400 + (key & 0xFF)]) & M
|
|
ch = v ^ ((key + s2) & M)
|
|
key = ((((~key) << 0x15) + 0x11111111) & M) | (key >> 0x0B)
|
|
s2 = ((ch if decrypt else v) + s2 + (s2 << 5) + 3) & M
|
|
out.append(ch)
|
|
return out
|
|
|
|
|
|
def drop_listfile(data):
|
|
import struct
|
|
hash_pos, n = struct.unpack_from("<I", data, 16)[0], struct.unpack_from("<I", data, 24)[0]
|
|
words = list(struct.unpack_from("<%dI" % (n * 4), data, hash_pos))
|
|
key = mpq_hash("(hash table)", 3)
|
|
plain = crypt(words, key, True)
|
|
a, b = mpq_hash("(listfile)", 1), mpq_hash("(listfile)", 2)
|
|
for i in range(n):
|
|
if plain[i * 4] == a and plain[i * 4 + 1] == b:
|
|
plain[i * 4 + 3] = 0xFFFFFFFE
|
|
enc = crypt(plain, key, False)
|
|
out = bytearray(data)
|
|
struct.pack_into("<%dI" % (n * 4), out, hash_pos, *enc)
|
|
return bytes(out)
|
|
|
|
|
|
def lib_path():
|
|
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#stormlib"], capture_output=True, check=True).stdout.decode().split()[0]
|
|
return os.path.join(out, "lib", "libstorm.so")
|
|
|
|
|
|
def generate(ctx):
|
|
rng = ctx.rng(41)
|
|
tmp = tempfile.mkdtemp(prefix="formats-mpq-")
|
|
try:
|
|
def file(name, data):
|
|
p = os.path.join(tmp, "src_" + str(abs(hash(name)) % 10 ** 9) + "_" + str(len(data)))
|
|
open(p, "wb").write(data)
|
|
return p
|
|
text = b"".join(b"line %d of a text file with some repetition\n" % i for i in range(400))
|
|
sparse = bytes(3000) + rng.randbytes(100) + bytes(9000)
|
|
noise = rng.randbytes(9000)
|
|
content = [
|
|
("units\\human\\footman.txt", text, COMPRESS, ZLIB),
|
|
("units\\orc\\grunt.txt", text, COMPRESS, PKWARE),
|
|
("data\\bz.dat", text + noise, COMPRESS, BZIP2),
|
|
("data\\lzma.dat", text, COMPRESS, LZMA),
|
|
("data\\sparse.dat", sparse, COMPRESS, SPARSE | ZLIB),
|
|
("data\\sparsebz.dat", sparse, COMPRESS, SPARSE | BZIP2),
|
|
("data\\noise.bin", noise, COMPRESS, ZLIB),
|
|
("old\\imploded.txt", text, IMPLODE, PKWARE),
|
|
("single\\unit.txt", text, COMPRESS | SINGLE, ZLIB),
|
|
("single\\stored.bin", noise[:777], SINGLE, 0),
|
|
("stored\\plain.bin", noise, 0, 0),
|
|
("secret\\enc.txt", text, COMPRESS | ENCRYPTED, ZLIB),
|
|
("secret\\fixkey.txt", text, COMPRESS | ENCRYPTED | FIX_KEY, ZLIB),
|
|
("secret\\stored.bin", noise, ENCRYPTED, 0),
|
|
("secret\\single.txt", text, COMPRESS | ENCRYPTED | SINGLE, ZLIB),
|
|
("crc\\sectors.txt", text, COMPRESS | SECTOR_CRC, ZLIB),
|
|
("empty.txt", b"", COMPRESS, ZLIB),
|
|
("tiny.txt", b"x", COMPRESS, ZLIB),
|
|
]
|
|
specs = []
|
|
for name, create, sel in [("v1", 0x00100000 | 0x00200000, None), ("v2", 0x01100000, None), ("v3", 0x02100000, None),
|
|
("v4", 0x03100000, None), ("nolist", 0, 6), ("v1-basic", 0x00100000, 3)]:
|
|
files = content if sel is None else content[:sel]
|
|
if name.startswith("v3") or name.startswith("v4"):
|
|
files = [f for f in files if not (f[2] & IMPLODE)]
|
|
specs.append({"name": name, "path": os.path.join(tmp, name + ".mpq"), "create": create,
|
|
"files": [{"name": n, "src": file(n, d), "flags": fl | REPLACE, "comp": c} for n, d, fl, c in files],
|
|
"want": files})
|
|
# a WAVE-style Huffman sector (Huffman + ADPCM is what Blizzard uses for .wav)
|
|
specs.append({"name": "huffman", "path": os.path.join(tmp, "huffman.mpq"), "create": 0x00100000,
|
|
"files": [{"name": "sound\\a.wav", "src": file("wav", text), "flags": COMPRESS | REPLACE, "comp": HUFF | ZLIB}],
|
|
"want": [("sound\\a.wav", text, COMPRESS, HUFF | ZLIB)]})
|
|
imp = [{"name": "text", "src": file("i1", text)}, {"name": "noise", "src": file("i2", noise[:5000])},
|
|
{"name": "small", "src": file("i3", b"abcabcabcabcabcabc")}, {"name": "zeros", "src": file("i4", bytes(20000))}]
|
|
modes = [{"name": "ascii-%d" % d, "src": file("m1", text), "type": 1, "dsize": d} for d in (1024, 2048, 4096)]
|
|
modes += [{"name": "binary-%d" % d, "src": file("m2", text + noise[:3000]), "type": 0, "dsize": d} for d in (1024, 2048)]
|
|
modes += [{"name": "ascii-noise", "src": file("m3", noise[:4000]), "type": 1, "dsize": 4096}]
|
|
send = [{k: v for k, v in s.items() if k != "want"} for s in specs]
|
|
res = json.loads(ctx.python([], CODE, input=json.dumps({"lib": lib_path(), "archives": send, "implode": imp, "modes": modes}).encode()))
|
|
present = res["present"]
|
|
res = res["implode"]
|
|
archives = []
|
|
for s in specs:
|
|
data = open(s["path"], "rb").read()
|
|
if s["name"] == "nolist":
|
|
data = drop_listfile(data)
|
|
if s["name"] == "v1-basic":
|
|
data = b"\x7f" * 1024 + data # a prefixed archive (installer stub): the header at a 512-byte boundary
|
|
archives.append({"name": s["name"], "data": data, "unnamed": s["name"] == "nolist",
|
|
"files": [{"name": n, "size": len(d), "crc": zlib.crc32(d), "huffman": bool(c & HUFF)} for n, d, fl, c in s["want"] if n in present[s["name"]]]})
|
|
implode = [{"name": r["name"], "data": bytes.fromhex(r["data"]), "size": r["size"], "crc": r["crc"]} for r in res]
|
|
finally:
|
|
shutil.rmtree(tmp)
|
|
ctx.emit("mpq", {"archives": archives, "implode": implode})
|