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)
This commit is contained in:
1 parent
34d0600109
commit
b02e59809f
8 files changed
+1063
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user