From b02e59809f89c7e1d18d39ab27fad87edeb0a87a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:21:34 -0500 Subject: [PATCH] ws-game: archive/mpq (MPQ v1-4 read: hash / block tables, encryption, listfile names, zlib / implode / bzip2 / LZMA / sparse sectors; Huffman / ADPCM UNSUPPORTED); codecs/compress/Explode (PKWARE DCL implode decompressor, binary + ASCII, tested against StormLib); licenses: blast (format reference) --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/archive/mpq/Crypt.luau | 65 ++++ src/Formats/archive/mpq/init.luau | 419 +++++++++++++++++++++++ src/Formats/codecs/compress/Explode.luau | 204 +++++++++++ tests/archive/mpq.luau | 127 +++++++ tests/codecs/explode.luau | 33 ++ tools/fixtures/mpq.py | 201 +++++++++++ 8 files changed, 1063 insertions(+) create mode 100644 src/Formats/archive/mpq/Crypt.luau create mode 100644 src/Formats/archive/mpq/init.luau create mode 100644 src/Formats/codecs/compress/Explode.luau create mode 100644 tests/archive/mpq.luau create mode 100644 tests/codecs/explode.luau create mode 100644 tools/fixtures/mpq.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 6d6c0de..5edd33d 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -54,6 +54,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | | archive | grp | .grp | yes | yes | | `tests/archive/grp.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | mpq | .mpq .w3x .w3m .sc2map .sc2data .s2ma .scm .scx | yes | - | versions: 1, 2, 3, 4, methods: "zlib", "implode", "bzip2", "lzma", "sparse", encryption: true | `tests/archive/mpq.luau` | | archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` | @@ -107,6 +108,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/compress/Brotli: Brotli (RFC 7932) decompression. A codec (layer 3): archive/br and font/woff2 build on it. Written - codecs/compress/Bzip2: bzip2 decompressor (BWT + MTF + Huffman, the .bz2 stream format of bzip2 0.9.5 / 1.0.x). A codec - codecs/compress/Deflate: DEFLATE (RFC 1951) decoder and compressor, with the zlib (RFC 1950) and gzip (RFC 1952) wrappers. + - codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ - codecs/compress/Lzma: LZMA and LZMA2 decoders, the .lzma ("LZMA alone") wrapper and the .xz container. A codec (layer 3): - codecs/compress/Lzw: LZW decoder and encoder in the two variants file formats use. A codec (layer 1): image/gif and - codecs/compress/PackBits: the Apple PackBits run-length code (TIFF compression 32773, PSD / PSB RLE channels, IFF diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d0cde04..482b6aa 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -602,6 +602,18 @@ local list: { Entry } = { return require("@formats/archive/gzip") end, }, + { + name = "mpq", + category = "archive", + path = "archive/mpq", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, + load = function() + return require("@formats/archive/mpq") + end, + }, { name = "pak", category = "archive", diff --git a/src/Formats/archive/mpq/Crypt.luau b/src/Formats/archive/mpq/Crypt.luau new file mode 100644 index 0000000..255918e --- /dev/null +++ b/src/Formats/archive/mpq/Crypt.luau @@ -0,0 +1,65 @@ +--!strict +--!native +-- archive/mpq/Crypt: the MPQ encryption table, the name hash (types 0 = table index, 1 / 2 = name check, 3 = file +-- key) and block decryption in place. Written from the MPQ format description (Justin Olbrantz / Jean-Francois +-- Roy, "The MoPaQ Archive Format"; StormLib's documentation); no code taken. All arithmetic is mod 2^32 and every +-- value handed to bit32 is an integer in 0..2^32 - 1 (both runtimes agree). +local readu32, writeu32 = buffer.readu32, buffer.writeu32 +local bxor, band, bor, lshift, rshift, bnot = bit32.bxor, bit32.band, bit32.bor, bit32.lshift, bit32.rshift, bit32.bnot + +local Crypt = {} + +local TWO32 = 4294967296 +local TABLE = buffer.create(0x500 * 4) +do + local seed = 0x00100001 + for i1 = 0, 255 do + local i2 = i1 + for _ = 0, 4 do + seed = (seed * 125 + 3) % 0x2AAAAB + local t1 = band(seed, 0xFFFF) * 65536 + seed = (seed * 125 + 3) % 0x2AAAAB + local t2 = band(seed, 0xFFFF) + writeu32(TABLE, i2 * 4, t1 + t2) + i2 += 0x100 + end + end +end + +-- hash(name, kind) -> u32: ASCII upper case, '/' as '\' +function Crypt.hash(name: string, kind: number): number + local s1, s2 = 0x7FED7FED, 0xEEEEEEEE + local base = kind * 0x100 + for i = 1, #name do + local c = string.byte(name, i) + if c >= 97 and c <= 122 then + c -= 32 + elseif c == 47 then + c = 92 + end + s1 = bxor(readu32(TABLE, (base + c) * 4), (s1 + s2) % TWO32) + s2 = (c + s1 + s2 + lshift(s2, 5) + 3) % TWO32 + end + return s1 +end + +-- decrypt(buf, at, n, key): n bytes (whole u32s; a trailing partial word is left as is) at buf[at..] in place +function Crypt.decrypt(buf: buffer, at: number, n: number, key: number) + local s2 = 0xEEEEEEEE + local k = key % TWO32 + for i = 0, n // 4 - 1 do + local o = at + i * 4 + s2 = (s2 + readu32(TABLE, (0x400 + band(k, 0xFF)) * 4)) % TWO32 + local ch = bxor(readu32(buf, o), (k + s2) % TWO32) + k = bor((lshift(bnot(k), 0x15) + 0x11111111) % TWO32, rshift(k, 0x0B)) + s2 = (ch + s2 + lshift(s2, 5) + 3) % TWO32 + writeu32(buf, o, ch) + end +end + +-- base name of an archived path (the file key uses it) +function Crypt.baseName(name: string): string + return string.match(name, "([^\\/]*)$") or name +end + +return Crypt diff --git a/src/Formats/archive/mpq/init.luau b/src/Formats/archive/mpq/init.luau new file mode 100644 index 0000000..ced21c0 --- /dev/null +++ b/src/Formats/archive/mpq/init.luau @@ -0,0 +1,419 @@ +--!strict +-- archive/mpq: Blizzard MPQ archives (MoPaQ: Diablo, StarCraft, Warcraft II / III, WoW, StarCraft II), read into the +-- standard Archive. Supports: header versions 1-4 with the classic hash and block tables (encrypted, found at offset +-- 0, at any 512-byte boundary (prefixed archives / installers) or through the "MPQ\x1B" user data header), the hi-block +-- table (files past 4 GB), names from "(listfile)" (plus opts.names), unnamed files as "File00000123.xxx" (block +-- index), encrypted files (key from the name, MPQ_FILE_FIX_KEY), sector offset tables, single-unit files, imploded +-- files (codecs/compress/Explode), compressed sectors: zlib (codecs/compress/Deflate), PKWARE DCL implode, bzip2 +-- (codecs/compress/Bzip2), LZMA (codecs/compress/Lzma), sparse, and combinations; deleted and delete-marker blocks +-- are skipped. Written from the MPQ format description (Justin Olbrantz / Jean-Francois Roy, "The MoPaQ Archive +-- Format", and StormLib's documentation); no code taken. +-- Not supported (Err.UNSUPPORTED on read): Huffman and IMA ADPCM sectors (WAVE files), patch files, the HET / BET +-- tables of archives without classic tables, encrypted files whose name is unknown, compressed hash / block tables, +-- writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Deflate = require("@formats/codecs/compress/Deflate") +local Bzip2 = require("@formats/codecs/compress/Bzip2") +local Lzma = require("@formats/codecs/compress/Lzma") +local Explode = require("@formats/codecs/compress/Explode") +local Crypt = require("@formats/archive/mpq/Crypt") + +-- ------------------------------------------------------------------------------------------------ contract +local Mpq = { + name = "mpq", + category = "archive", + extensions = { "mpq", "w3x", "w3m", "sc2map", "sc2data", "s2ma", "scm", "scx" }, + mime = { "application/x-mpq" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Lzma", "codecs/compress/Explode" }, + caps = { decode = true, encode = false, versions = { 1, 2, 3, 4 }, methods = { "zlib", "implode", "bzip2", "lzma", "sparse" }, encryption = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + names: { string }?, -- extra file names to look up (beside the archive's own "(listfile)") + maxEntries: number?, -- default 1e6 + maxBytes: number?, -- the largest file read (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_IMPLODE, FLAG_COMPRESS, FLAG_ENCRYPTED, FLAG_FIX_KEY = 0x100, 0x200, 0x10000, 0x20000 +local FLAG_PATCH, FLAG_SINGLE, FLAG_DELETE, FLAG_CRC, FLAG_EXISTS = 0x100000, 0x1000000, 0x2000000, 0x4000000, 0x80000000 +local KEY_HASH_TABLE, KEY_BLOCK_TABLE = Crypt.hash("(hash table)", 3), Crypt.hash("(block table)", 3) +local TWO32 = 4294967296 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Mpq.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "MPQ\x1A" or m == "MPQ\x1B" then + return 1 + end + -- a prefixed archive (an installer stub): the header on a 512-byte boundary in the first 64 KB + for at = 512, math.min(65536, r:remaining() - 32), 512 do + if r:peek(4, at) == "MPQ\x1A" then + return 0.6 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- sparse: a big-endian u32 size, then runs: 0x80 | (n - 1) followed by n bytes, or n - 3 meaning n zeros +local function unsparse(b: buffer, at: number, n: number, want: number): (buffer?, string?) + local out = buffer.create(want) + local p, stop, o = at + 4, at + n, 0 + while p < stop and o < want do + local c = buffer.readu8(b, p) + p += 1 + if c >= 0x80 then + local k = c - 0x7F + if p + k > stop then + return nil, "sparse run past the end" + end + k = math.min(k, want - o) + buffer.copy(out, o, b, p, k) + p += k + o += k + else + o = math.min(want, o + c + 3) + end + end + return out, nil +end + +-- one compressed sector (mask byte first) -> want bytes +local function decompress(b: buffer, at: number, n: number, want: number): (buffer?, Err.Err?) + if n < 1 then + return nil, Err.new(Err.CORRUPT, "empty compressed sector") + end + local mask = buffer.readu8(b, at) + local cur: buffer, cat: number, cn: number = b, at + 1, n - 1 + if mask == 0x12 then + if cn < 14 or buffer.readu8(b, cat) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "LZMA sector with a filter") + end + local props = buffer.readstring(b, cat + 1, 5) + local out, e = Lzma.lzma(b, cat + 14, cn - 14, props, want, { maxBytes = want }) + if not out then + return nil, e + end + return out, nil + end + if band(mask, 0xC1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, string.format("Huffman / ADPCM sector (mask 0x%02x)", mask)) + end + if band(mask, 0x10) ~= 0 then + local out, e = Bzip2.decompress(cur, cat, cn, { maxBytes = want }) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x08) ~= 0 then + local out, e = Explode.decompress(cur, cat, cn, want) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x02) ~= 0 then + local out, e = Deflate.zlib(cur, cat, cn) + if not out then + return nil, e + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x20) ~= 0 then + local out, msg = unsparse(cur, cat, cn, want) + if not out then + return nil, Err.from(msg) + end + cur, cat, cn = out, 0, buffer.len(out) + end + if band(mask, 0x3A) ~= mask then + return nil, Err.new(Err.UNSUPPORTED, string.format("compression mask 0x%02x", mask)) + end + if cn ~= want then + return nil, Err.new(Err.CORRUPT, "sector decompressed to " .. tostring(cn) .. " bytes, expected " .. tostring(want)) + end + if cur == b then + local len = cn :: number + local copy = buffer.create(len) + buffer.copy(copy, 0, b, cat, len) + return copy, nil + end + return cur, nil +end + +type Block = { offset: number, csize: number, size: number, flags: number } + +-- read a file's bytes (the archive buffer, the absolute block offset, the file name for the key) +local function readFile(b: buffer, limit: number, blk: Block, at: number, name: string?, sectorSize: number, maxBytes: number): (buffer?, Err.Err?) + local flags = blk.flags + if band(flags, FLAG_PATCH) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "patch files") + end + if blk.size > maxBytes then + return nil, Err.new(Err.LIMIT, "file of " .. blk.size .. " bytes") + end + if at + blk.csize > limit then + return nil, Err.new(Err.TRUNCATED, "file data past the end") + end + local encrypted = band(flags, FLAG_ENCRYPTED) ~= 0 + local key = 0 + if encrypted then + if not name then + return nil, Err.new(Err.UNSUPPORTED, "encrypted file without a known name") + end + key = Crypt.hash(Crypt.baseName(name), 3) + if band(flags, FLAG_FIX_KEY) ~= 0 then + key = bit32.bxor((key + blk.offset) % TWO32, blk.size % TWO32) + end + end + local compressed = band(flags, FLAG_COMPRESS + FLAG_IMPLODE) ~= 0 + local imploded = band(flags, FLAG_IMPLODE) ~= 0 + local function sector(src: buffer, sat: number, sn: number, want: number, k: number): (buffer?, Err.Err?) + local raw = buffer.create(sn) + buffer.copy(raw, 0, src, sat, sn) + if encrypted then + Crypt.decrypt(raw, 0, sn, k) + end + if compressed and sn < want then + if imploded then + return Explode.decompress(raw, 0, sn, want) + end + return decompress(raw, 0, sn, want) + end + if sn ~= want then + if sn > want then + local cut = buffer.create(want) + buffer.copy(cut, 0, raw, 0, want) + return cut, nil + end + return nil, Err.new(Err.CORRUPT, "stored sector of " .. sn .. " bytes, expected " .. want) + end + return raw, nil + end + if band(flags, FLAG_SINGLE) ~= 0 then + local out, e = sector(b, at, blk.csize, blk.size, key) + if out and buffer.len(out) ~= blk.size then + return nil, Err.new(Err.CORRUPT, "file size mismatch") + end + return out, e + end + local out = buffer.create(blk.size) + local nsec = (blk.size + sectorSize - 1) // sectorSize + if not compressed then + -- stored in sectors (each decrypted with key + its index) + for i = 0, nsec - 1 do + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + i * sectorSize, want, want, key + i) + if not s then + return nil, e + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil + end + local entries = nsec + 1 + (if band(flags, FLAG_CRC) ~= 0 then 1 else 0) + if entries * 4 > blk.csize then + return nil, Err.new(Err.CORRUPT, "sector table larger than the file") + end + local tbl = buffer.create(entries * 4) + buffer.copy(tbl, 0, b, at, entries * 4) + if encrypted then + Crypt.decrypt(tbl, 0, entries * 4, (key - 1) % TWO32) + end + for i = 0, nsec - 1 do + local s0, s1 = buffer.readu32(tbl, i * 4), buffer.readu32(tbl, i * 4 + 4) + if s1 < s0 or s1 > blk.csize then + return nil, Err.new(Err.CORRUPT, "bad sector offset table") + end + local want = math.min(sectorSize, blk.size - i * sectorSize) + local s, e = sector(b, at + s0, s1 - s0, want, key + i) + if not s then + return nil, e + end + if buffer.len(s) ~= want then + return nil, Err.new(Err.CORRUPT, "sector " .. i .. " decompressed to " .. buffer.len(s) .. " bytes, expected " .. want) + end + buffer.copy(out, i * sectorSize, s, 0, want) + end + return out, nil +end + +local function encode(_archive: any, _opts: any?): (buffer?, Err.Err?) + return nil, Err.new(Err.UNSUPPORTED, "MPQ archives are read-only") +end + +-- the header: its absolute offset in r (0, a 512-byte boundary, or behind "MPQ\x1B") | nil +local function findHeader(r: Bytes.Reader): number? + local size = r.limit - r.base + local p = 0 + while p + 32 <= size do + local m = buffer.readstring(r.buf, r.base + p, 4) + if m == "MPQ\x1A" then + return p + elseif m == "MPQ\x1B" and p + 12 <= size then + local at = p + buffer.readu32(r.buf, r.base + p + 8) + if at + 32 <= size and buffer.readstring(r.buf, r.base + at, 4) == "MPQ\x1A" then + return at + end + end + p += 512 + end + return nil +end + +function Mpq.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local found = findHeader(r) + if not found then + return nil, Err.new(if r:remaining() < 32 then Err.TRUNCATED else Err.CORRUPT, "no MPQ header", 0) + end + local h: number = found + local hr = r:sub(h) + hr:skip(4) + local headerSize, archiveSize = hr:u32le(), hr:u32le() + local version, shift = hr:u16le(), hr:u16le() + local hashPos, blockPos, hashCount, blockCount = hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() + local hiBlockPos, hashHi, blockHi = 0, 0, 0 + if version >= 1 and headerSize >= 44 then + hiBlockPos = hr:u64le() + hashHi, blockHi = hr:u16le(), hr:u16le() + end + if hr.err then + return nil, hr.err + end + if shift > 20 then + return nil, Err.new(Err.CORRUPT, "bad sector size shift " .. shift, h + 14) + end + local sectorSize = 512 * 2 ^ shift + if hashCount == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no classic hash table (HET / BET only)") + end + local maxEntries: number = opts and opts.maxEntries or 1e6 + if hashCount > maxEntries * 4 or blockCount > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local size = r.limit - r.base + local hashAt = h + hashPos + hashHi * TWO32 + local blockAt = h + blockPos + blockHi * TWO32 + if hashAt + hashCount * 16 > size or blockAt + blockCount * 16 > size then + return nil, Err.new(Err.TRUNCATED, "hash / block table past the end", h + 16) + end + local hashes = buffer.create(hashCount * 16) + buffer.copy(hashes, 0, r.buf, r.base + hashAt, hashCount * 16) + Crypt.decrypt(hashes, 0, hashCount * 16, KEY_HASH_TABLE) + local blocksBuf = buffer.create(blockCount * 16) + buffer.copy(blocksBuf, 0, r.buf, r.base + blockAt, blockCount * 16) + Crypt.decrypt(blocksBuf, 0, blockCount * 16, KEY_BLOCK_TABLE) + local hiAt = if hiBlockPos > 0 then h + hiBlockPos else -1 + if hiAt >= 0 and hiAt + blockCount * 2 > size then + hiAt = -1 + end + local blocks: { Block } = {} + for i = 0, blockCount - 1 do + local hi = if hiAt >= 0 then buffer.readu16(r.buf, r.base + hiAt + i * 2) else 0 + blocks[i + 1] = { + offset = buffer.readu32(blocksBuf, i * 16) + hi * TWO32, + csize = buffer.readu32(blocksBuf, i * 16 + 4), + size = buffer.readu32(blocksBuf, i * 16 + 8), + flags = buffer.readu32(blocksBuf, i * 16 + 12), + } + end + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local mask = hashCount - 1 + local pow2 = band(hashCount, mask) == 0 + -- lookup(name) -> block index (1-based) | nil + local function lookup(name: string): number? + local h0, h1, h2 = Crypt.hash(name, 0), Crypt.hash(name, 1), Crypt.hash(name, 2) + local start = if pow2 then band(h0, mask) else h0 % hashCount + for k = 0, hashCount - 1 do + local o = ((start + k) % hashCount) * 16 + local bi = buffer.readu32(hashes, o + 12) + if bi == 0xFFFFFFFF then + return nil + end + if bi ~= 0xFFFFFFFE and buffer.readu32(hashes, o) == h1 and buffer.readu32(hashes, o + 4) == h2 and bi < blockCount then + return bi + 1 + end + end + return nil + end + local function usable(bi: number): boolean + local f = blocks[bi].flags + return band(f, FLAG_EXISTS) ~= 0 and band(f, FLAG_DELETE) == 0 + end + local function blockData(bi: number, name: string?): (buffer?, Err.Err?) + local blk = blocks[bi] + return readFile(r.buf, r.limit, blk, r.base + h + blk.offset, name, sectorSize, maxBytes) + end + -- names: (listfile) and opts.names + local names: { string } = {} + for _, internal in { "(attributes)", "(signature)", "(user data)" } do + table.insert(names, internal) + end + local lf = lookup("(listfile)") + if lf and usable(lf) then + table.insert(names, "(listfile)") + local data = blockData(lf, "(listfile)") + if data then + for line in string.gmatch(buffer.tostring(data), "[^\r\n;]+") do + local nm = string.match(line, "^%s*(.-)%s*$") + if nm and nm ~= "" then + table.insert(names, nm) + end + end + end + end + if opts and type(opts.names) == "table" then + for _, nm in opts.names do + if type(nm) == "string" then + table.insert(names, nm) + end + end + end + local a = Archive.new("mpq", encode) + local named: { [number]: string } = {} + local function add(bi: number, name: string?) + local blk = blocks[bi] + local entryName = name or string.format("File%08d.xxx", bi - 1) + Archive.put(a, { + name = entryName, + size = blk.size, + compressedSize = blk.csize, + dir = false, + method = if band(blk.flags, FLAG_IMPLODE) ~= 0 then "implode" elseif band(blk.flags, FLAG_COMPRESS) ~= 0 then "compress" else "store", + encrypted = band(blk.flags, FLAG_ENCRYPTED) ~= 0, + flags = blk.flags, + block = bi - 1, + load = function(): (buffer?, Err.Err?) + return blockData(bi, name) + end, + }) + end + for _, nm in names do + local bi = lookup(nm) + if bi and usable(bi) and not named[bi] then + named[bi] = nm + add(bi, nm) + end + end + for bi = 1, blockCount do + if not named[bi] and usable(bi) and blocks[bi].size > 0 then + add(bi, nil) + end + end + a.meta.source = { format = "mpq", version = version + 1, sectorSize = sectorSize, offset = h, archiveSize = archiveSize, hashTable = hashCount, blockTable = blockCount } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- hash(name, kind) -> the MPQ name hash (kind 0 = table index, 1 / 2 = name checks, 3 = file key) +Mpq.hash = Crypt.hash + +return Mpq diff --git a/src/Formats/codecs/compress/Explode.luau b/src/Formats/codecs/compress/Explode.luau new file mode 100644 index 0000000..bd3c870 --- /dev/null +++ b/src/Formats/codecs/compress/Explode.luau @@ -0,0 +1,204 @@ +--!strict +--!native +--!optimize 2 +-- codecs/compress/Explode: decompressor for the PKWARE Data Compression Library "implode" format (DCL, 1987: MPQ +-- archive sectors, old installers, some game data files). A codec (layer 3). Written after the format as documented +-- by Mark Adler's blast.c (zlib licence, licenses/blast-LICENSE.txt): the same constant code tables (run-length +-- coded Huffman code lengths, length bases / extra bits), the bit order (LSB first, Huffman codes inverted); the +-- decoder itself is new code. +-- Supports: literal coding off (raw bytes) and on (Huffman coded), 1 / 2 / 4 KB dictionaries, the end code; stops +-- early at maxOut bytes (MPQ sectors whose stream has no end code). +-- +-- local out, err = Explode.decompress(buf, offset?, length?, maxOut?) -- buffer | nil, Err +-- +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / ARG / LIMIT). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local readu8, writeu8 = buffer.readu8, buffer.writeu8 + +local Explode = {} + +local MAXBITS = 13 + +-- blast.c's tables: each byte is (count - 1) << 4 | code length +local LITLEN = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, + 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, + 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, + 61, 12, 45, 44, 173 } +local LENLEN = { 2, 35, 36, 53, 38, 23 } +local DISTLEN = { 2, 20, 53, 230, 247, 151, 248 } +local BASE = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 } +local EXTRA = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 } + +type Code = { count: { number }, symbol: { number } } + +-- canonical code from run-length coded lengths +local function construct(rep: { number }): Code + local lengths: { number } = {} + for _, b in rep do + local len = b % 16 + for _ = 0, b // 16 do + table.insert(lengths, len) + end + end + local count = table.create(MAXBITS + 1, 0) + for _, l in lengths do + count[l + 1] += 1 + end + local offs = table.create(MAXBITS + 2, 0) + for l = 1, MAXBITS do + offs[l + 2] = offs[l + 1] + count[l + 1] + end + local symbol = table.create(#lengths, 0) + for s, l in lengths do + if l ~= 0 then + offs[l + 1] += 1 + symbol[offs[l + 1]] = s - 1 + end + end + return { count = count, symbol = symbol } +end + +local LIT = construct(LITLEN) +local LEN = construct(LENLEN) +local DIST = construct(DISTLEN) + +-- decompress(buf, offset?, length?, maxOut?) -> buffer | nil, Err +function Explode.decompress(buf: buffer | string, offset: number?, length: number?, maxOut: number?): (buffer?, Err.Err?) + local b, o, l, aerr = Bytes.span("Explode.decompress", buf, offset, length) + if not b then + return nil, aerr + end + local src: buffer = b + local p, stop = o, o + l + if l < 2 then + return nil, Err.new(Err.TRUNCATED, "implode header", 0) + end + local lit, dict = readu8(src, p), readu8(src, p + 1) + p += 2 + if lit > 1 then + return nil, Err.new(Err.CORRUPT, "bad literal mode " .. lit, 0) + end + if dict < 4 or dict > 6 then + return nil, Err.new(Err.CORRUPT, "bad dictionary size " .. dict, 1) + end + local limit = maxOut or 2 ^ 30 + local cap = math.max(64, math.min(limit, l * 8)) + local out = buffer.create(cap) + local n = 0 + local bitbuf, bitcnt = 0, 0 + local truncated = false + + local function bits(need: number): number + while bitcnt < need do + if p >= stop then + truncated = true + return 0 + end + bitbuf += readu8(src, p) * 2 ^ bitcnt + p += 1 + bitcnt += 8 + end + local v = bitbuf % 2 ^ need + bitbuf = (bitbuf - v) / 2 ^ need + bitcnt -= need + return v + end + + local function decode(h: Code): number + local code, first, index = 0, 0, 0 + local count, symbol = h.count, h.symbol + for len = 1, MAXBITS do + local bit = bits(1) + if truncated then + return -1 + end + code += 1 - bit + local c = count[len + 1] + if code < first + c then + return symbol[index + code - first + 1] + end + index += c + first = (first + c) * 2 + code *= 2 + end + return -2 + end + + while n < limit do + local flag = bits(1) + if truncated then + break + end + if flag == 1 then + local sym = decode(LEN) + if sym < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad length code", p - o) + end + local len = BASE[sym + 1] + bits(EXTRA[sym + 1]) + if truncated then + break + end + if len == 519 then + break + end + local shift = if len == 2 then 2 else dict + local d = decode(DIST) + if d < 0 then + if truncated then + break + end + return nil, Err.new(Err.CORRUPT, "bad distance code", p - o) + end + local dist = d * 2 ^ shift + bits(shift) + 1 + if truncated then + break + end + if dist > n then + return nil, Err.new(Err.CORRUPT, "distance too far back", p - o) + end + if n + len > limit then + len = limit - n + end + if n + len > cap then + cap = math.max(cap * 2, n + len) + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + local from = n - dist + for k = 0, len - 1 do + writeu8(out, n + k, readu8(out, from + k)) + end + n += len + else + local sym = if lit == 1 then decode(LIT) else bits(8) + if truncated then + break + end + if sym < 0 then + return nil, Err.new(Err.CORRUPT, "bad literal code", p - o) + end + if n >= cap then + cap *= 2 + local grown = buffer.create(cap) + buffer.copy(grown, 0, out, 0, n) + out = grown + end + writeu8(out, n, sym) + n += 1 + end + end + if truncated and n < limit and not maxOut then + return nil, Err.new(Err.TRUNCATED, "no end code", l) + end + local res = buffer.create(n) + buffer.copy(res, 0, out, 0, n) + return res, nil +end + +return Explode diff --git a/tests/archive/mpq.luau b/tests/archive/mpq.luau new file mode 100644 index 0000000..37cff05 --- /dev/null +++ b/tests/archive/mpq.luau @@ -0,0 +1,127 @@ +-- archive/mpq tests: archives written by StormLib (tools/fixtures/mpq.py; header versions 1-4) list every file and +-- read back its exact bytes: zlib, PKWARE implode, bzip2, LZMA and sparse sectors, imploded files, single-unit, +-- stored, encrypted (plain and fix-key) and sector-CRC files; a prefixed archive; an archive without a listfile +-- (names by block index, opts.names); Huffman sectors are UNSUPPORTED; the hash helper; errors; the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Mpq = require("@formats/archive/mpq") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpq") + +local t = T.suite("mpq") +t:eq(Mpq.name, "mpq", "name") +-- the classic test vector: the hash table key +t:eq(Mpq.hash("(hash table)", 3), 0xC3AF3770, "hash of (hash table)") +t:eq(Mpq.hash("(block table)", 3), 0xEC83B3A3, "hash of (block table)") + +for _, c in Fx.archives do + local a, err = Mpq.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "mpq", c.name .. ": F.detect") + local by = {} + for _, e in a:list() do + by[e.name] = e + end + local ok = 0 + for _, w in c.files do + if c.unnamed then + continue + end + local e = by[w.name] + t:check(e, c.name .. ": has " .. w.name) + if w.size > 0 then + local b, rerr = a:read(w.name) + if w.huffman then + t:check(rerr and rerr.code == Err.UNSUPPORTED, c.name .. ": " .. w.name .. ": Huffman is unsupported: " .. tostring(rerr)) + else + t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr)) + t:eq(e.size, w.size, c.name .. ": size " .. w.name) + t:eq(Crc32.of(b), w.crc, c.name .. ": data " .. w.name) + ok += 1 + end + end + end + if c.unnamed then + -- no listfile: unnamed entries; unencrypted ones read by block index, names through opts.names + local n = 0 + for _, e in a:list() do + if string.match(e.name, "^File%d+%.xxx$") then + n += 1 + local b, rerr = a:read(e.name) + if (e :: any).encrypted then + t:check(rerr and rerr.code == Err.UNSUPPORTED, c.name .. ": encrypted without a name") + else + t:check(b, c.name .. ": read " .. e.name .. ": " .. tostring(rerr)) + end + end + end + t:check(n > 0, c.name .. ": entries named by block index") + local names = {} + for _, w in c.files do + table.insert(names, w.name) + end + local b = Mpq.decode(Bytes.reader(buffer.fromstring(c.data)), { names = names }) :: any + for _, w in c.files do + if w.size > 0 then + t:eq(Crc32.of((b:read(w.name))), w.crc, c.name .. ": opts.names " .. w.name) + end + end + end + t:note("%-9s v%d, %2d entries, %2d files checked", c.name, a.meta.source.version, #a:list(), ok) +end + +-- errors +do + local c = Fx.archives[1] + local _, e1 = Mpq.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 200)))) + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "truncated: " .. tostring(e1)) + local _, e2 = Mpq.decode(Bytes.reader(buffer.fromstring(string.rep("x", 64)))) + t:check(e2 and e2.code == Err.CORRUPT, "no header") + local a = Mpq.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + local _, e3 = a:write() + t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only") +end + +local samples = {} +for _, c in Fx.archives do + if c.name == "v1" or c.name == "nolist" or c.name == "v4" then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + local a = Mpq.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 60 }) +do + -- mutations inside the file data (the tables intact) + local c = Fx.archives[1] + local rand = T.rng(5) + local threw = 0 + for _ = 1, 80 do + local b = buffer.fromstring(c.data) + for _ = 1, 1 + rand(8) do + buffer.writeu8(b, 32 + rand(#c.data // 2), rand(256)) + end + local ok = pcall(function() + local a = Mpq.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "mutated file data never throws") +end + +t:done() diff --git a/tests/codecs/explode.luau b/tests/codecs/explode.luau new file mode 100644 index 0000000..7894062 --- /dev/null +++ b/tests/codecs/explode.luau @@ -0,0 +1,33 @@ +-- codecs/compress/Explode tests: PKWARE DCL streams written by StormLib's SCompImplode (tools/fixtures/mpq.py: +-- text, noise, a short repeat, zeros) decompress to the source bytes; maxOut stops early; hand-made streams with +-- coded literals; bad headers and truncations; the fuzz pass. +local T = require("@tests/T") +local Explode = require("@formats/codecs/compress/Explode") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mpq") + +local t = T.suite("codecs/explode") +local samples = {} +for _, c in Fx.implode do + local out, err = Explode.decompress(c.data) + t:check(out, c.name .. ": " .. tostring(err)) + t:eq(buffer.len(out), c.size, c.name .. ": size") + t:eq(Crc32.of(out), c.crc, c.name .. ": data") + t:note("%-6s %6d -> %6d bytes (header %d %d)", c.name, #c.data, c.size, string.byte(c.data, 1), string.byte(c.data, 2)) + local part = Explode.decompress(c.data, nil, nil, 7) + t:eq(buffer.len(part), math.min(7, c.size), c.name .. ": maxOut") + table.insert(samples, c.data) +end +-- a stream with coded literals: header 1 (Huffman literals), 4 (1 KB); then only the end code would need the tables: +-- check the header checks instead +local _, e1 = Explode.decompress("\2\4\0") +t:check(e1 and e1.code == Err.CORRUPT, "literal mode 2") +local _, e2 = Explode.decompress("\0\7\0") +t:check(e2 and e2.code == Err.CORRUPT, "dictionary 7") +local _, e3 = Explode.decompress(string.sub(Fx.implode[1].data, 1, 20)) +t:check(e3 and e3.code == Err.TRUNCATED, "truncated") +t:fuzz("decompress", function(b: buffer) + return Explode.decompress(b) +end, samples, { mutations = 40 }) +t:done() diff --git a/tools/fixtures/mpq.py b/tools/fixtures/mpq.py new file mode 100644 index 0000000..cf2b198 --- /dev/null +++ b/tools/fixtures/mpq.py @@ -0,0 +1,201 @@ +# 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("