diff --git a/docs/FORMATS.md b/docs/FORMATS.md index abbb610..6d6c0de 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -56,6 +56,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.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` | | archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6ec1248..d0cde04 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -626,6 +626,18 @@ local list: { Entry } = { return require("@formats/archive/tar") end, }, + { + name = "vpk", + category = "archive", + path = "archive/vpk", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, + load = function() + return require("@formats/archive/vpk") + end, + }, { name = "wad", category = "archive", diff --git a/src/Formats/archive/vpk/init.luau b/src/Formats/archive/vpk/init.luau new file mode 100644 index 0000000..ca1a624 --- /dev/null +++ b/src/Formats/archive/vpk/init.luau @@ -0,0 +1,324 @@ +--!strict +-- archive/vpk: Valve VPK archives (Source / Source 2: version 1 and 2 directory files, "pak01_dir.vpk"), read into the +-- standard Archive and written from any Archive value. Reading: the extension / path / name tree, preload bytes +-- (stored in the tree) followed by the data, data embedded in the directory file (archive index 0x7fff) or in the +-- numbered part files "_NNN.vpk", found through opts.resolve(fileName) / opts.files[fileName] (the name comes +-- from opts.name, "x_dir.vpk" -> "x_000.vpk", default "pak01"); each entry's CRC-32 is checked on read; version 2's +-- MD5 section is kept in meta. Writing: one self-contained directory file (every entry embedded, no preload), +-- version 2 by default with its tree / chunk / file MD5s (version = 1 for the older header). Written from the +-- Valve Developer Community VPK file format page; no code taken. +-- Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Md5 = require("@formats/core/Md5") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Vpk = { + name = "vpk", + category = "archive", + extensions = { "vpk" }, + mime = { "application/x-vpk" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" }, + caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + verify: boolean?, -- check each entry's CRC-32 on read (default true) + resolve: ((name: string) -> (buffer | string)?)?, -- the part files ("pak01_000.vpk", ...) + files: { [string]: buffer | string }?, + name: string?, -- the directory file's name ("pak01_dir.vpk"), for the part file names + maxEntries: number?, -- default 1e6 +} +export type EncodeOptions = { version: number? } -- 1 or 2 (default: the source's, else 2) + +-- ------------------------------------------------------------------------------------------------ constants +local SIGNATURE = 0x55AA1234 +local EMBEDDED = 0x7FFF + +-- ------------------------------------------------------------------------------------------------ sniff +function Vpk.sniff(r: Bytes.Reader): number + if r:remaining() < 12 or r:peek(4) ~= "\x34\x12\xAA\x55" then + return 0 + end + local v = r:peekU8(4) + return if v == 1 or v == 2 then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Vpk.encode(archive, opts) +end + +-- the part file `index` as a buffer (cached per archive) +local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?) + local cache: { [number]: buffer } = {} + local prefix = "pak01" + if opts and type(opts.name) == "string" then + local base = string.match(opts.name, "([^/\\]+)$") or opts.name + prefix = string.match(base, "^(.*)_dir%.[vV][pP][kK]$") or string.match(base, "^(.*)%.[vV][pP][kK]$") or base + end + return function(index: number): (buffer?, Err.Err?) + local hit = cache[index] + if hit then + return hit, nil + end + local name = string.format("%s_%03d.vpk", prefix, index) + local data: any = nil + if opts and type(opts.files) == "table" then + data = opts.files[name] + end + if data == nil and opts and type(opts.resolve) == "function" then + local ok, v = pcall(opts.resolve, name) + data = if ok then v else nil + end + local b = Bytes.toBuffer(data) + if not b then + return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)") + end + cache[index] = b + return b, nil + end +end + +local function loader(r: Bytes.Reader, e: any, dataBase: number, part: (number) -> (buffer?, Err.Err?), verify: boolean): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local src: buffer, at: number + if e.archiveIndex == EMBEDDED then + src, at = r.buf, r.base + dataBase + e.archiveOffset + if dataBase + e.archiveOffset + e.length > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end") + end + else + local b, err = part(e.archiveIndex) + if not b then + return nil, err + end + src, at = b, e.archiveOffset + if at + e.length > buffer.len(b) then + return nil, Err.new(Err.TRUNCATED, "entry " .. e.name .. " past the end of part " .. e.archiveIndex) + end + end + local out = buffer.create(e.preloadLength + e.length) + buffer.copy(out, 0, r.buf, e.preloadAt, e.preloadLength) + buffer.copy(out, e.preloadLength, src, at, e.length) + if verify and Crc32.of(out) ~= e.crc32 then + return nil, Err.new(Err.CHECKSUM, "entry " .. e.name .. ": CRC-32 mismatch") + end + return out, nil + end +end + +function Vpk.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local sig, version, treeSize = r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if sig ~= SIGNATURE then + return nil, Err.new(Err.CORRUPT, "bad signature", 0) + end + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "VPK version " .. version, 4) + end + local v2: any = nil + if version == 2 then + v2 = { fileDataSize = r:u32le(), archiveMd5Size = r:u32le(), otherMd5Size = r:u32le(), signatureSize = r:u32le() } + if r.err then + return nil, r.err + end + end + local headerLen = r:tell() - r.base + if headerLen + treeSize > r.limit - r.base then + return nil, Err.new(Err.TRUNCATED, "tree past the end", 8) + end + local t = r:sub(headerLen, treeSize) + local a = Archive.new("vpk", encode) + local part = partLoader(opts) + local verify = not (opts and opts.verify == false) + local maxEntries = opts and opts.maxEntries or 1e6 + local count = 0 + local parts: { [number]: boolean } = {} + local dataBase = headerLen + treeSize + while true do + local ext = t:cstring() + if t.err then + return nil, t.err + end + if ext == "" then + break + end + while true do + local path = t:cstring() + if t.err then + return nil, t.err + end + if path == "" then + break + end + while true do + local name = t:cstring() + if t.err then + return nil, t.err + end + if name == "" then + break + end + local e: any = { crc32 = t:u32le(), preloadLength = t:u16le(), archiveIndex = t:u16le(), archiveOffset = t:u32le(), length = t:u32le() } + local term = t:u16le() + e.preloadAt = t.pos + t:skip(e.preloadLength) + if t.err then + return nil, t.err + end + if term ~= 0xFFFF then + return nil, Err.new(Err.CORRUPT, "bad entry terminator", t:tell() + headerLen) + end + count += 1 + if count > maxEntries then + return nil, Err.new(Err.LIMIT, "too many entries") + end + local full = (if path == " " then "" else path .. "/") .. name .. (if ext == " " then "" else "." .. ext) + e.name = full + if e.archiveIndex ~= EMBEDDED then + parts[e.archiveIndex] = true + end + Archive.put(a, { + name = full, + size = e.preloadLength + e.length, + dir = false, + method = "store", + crc32 = e.crc32, + archiveIndex = if e.archiveIndex == EMBEDDED then nil else e.archiveIndex, + preload = e.preloadLength, + load = loader(r, e, dataBase, part, verify), + }) + end + end + end + local partList: { number } = {} + for k in parts do + table.insert(partList, k) + end + table.sort(partList) + a.meta.source = { format = "vpk", version = version, entries = count, parts = partList } + if v2 then + local md5At = dataBase + v2.fileDataSize + if v2.otherMd5Size == 48 and md5At + v2.archiveMd5Size + 48 <= r.limit - r.base then + local m = r:sub(md5At + v2.archiveMd5Size, 48) + v2.treeMd5, v2.chunkHashesMd5, v2.fileMd5 = m:string(16), m:string(16), m:string(16) + end + a.meta.source.v2 = v2 + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Vpk.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local version = opts and opts.version or (if type(src) == "table" and src.format == "vpk" then src.version else nil) or 2 + if version ~= 1 and version ~= 2 then + return nil, Err.new(Err.ARG, "version must be 1 or 2") + end + -- group by extension, then path, keeping first-seen order + local exts: { string } = {} + local byExt: { [string]: { paths: { string }, byPath: { [string]: { { name: string, data: buffer } } } } } = {} + for _, it in items do + if not it.entry.dir then + local full = string.gsub(it.entry.name, "\\", "/") + local dir, file = string.match(full, "^(.*)/([^/]*)$") + if not dir then + dir, file = " ", full + end + local stem, ext = string.match(file :: string, "^(.*)%.([^.]*)$") + if not stem or stem == "" then + stem, ext = file, " " + end + if stem == "" or dir == "" or string.find(full, "\0", 1, true) then + return nil, Err.new(Err.ARG, "bad entry name: " .. it.entry.name) + end + local g = byExt[ext :: string] + if not g then + g = { paths = {}, byPath = {} } + byExt[ext :: string] = g + table.insert(exts, ext :: string) + end + local l = g.byPath[dir :: string] + if not l then + l = {} + g.byPath[dir :: string] = l + table.insert(g.paths, dir :: string) + end + table.insert(l, { name = stem :: string, data = it.data }) + end + end + local tree = Bytes.writer() + local data = Bytes.writer() + for _, ext in exts do + tree:cstring(ext) + local g = byExt[ext] + for _, path in g.paths do + tree:cstring(path) + for _, f in g.byPath[path] do + tree:cstring(f.name) + tree:u32le(Crc32.of(f.data)) + tree:u16le(0) + tree:u16le(EMBEDDED) + tree:u32le(data:tell()) + tree:u32le(buffer.len(f.data)) + tree:u16le(0xFFFF) + data:bytes(f.data) + end + tree:u8(0) + end + tree:u8(0) + end + tree:u8(0) + local tb, db = tree:finish(), data:finish() + local w = Bytes.writer(buffer.len(tb) + buffer.len(db) + 128) + w:u32le(SIGNATURE) + w:u32le(version) + w:u32le(buffer.len(tb)) + if version == 2 then + w:u32le(buffer.len(db)) + w:u32le(0) + w:u32le(48) + w:u32le(0) + end + w:bytes(tb) + w:bytes(db) + if version == 2 then + local treeMd5 = Md5.new() + treeMd5:update(tb) + local tmd = treeMd5:digest() + local chunkMd5 = Md5.new():digest() + local file = Md5.new() + local sofar = w:finish() + file:update(sofar) + file:update(buffer.fromstring(tmd .. chunkMd5)) + local out = Bytes.writer(buffer.len(sofar) + 48) + out:bytes(sofar) + out:string(tmd) + out:string(chunkMd5) + out:string(file:digest()) + return out:finish(), nil + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(version?) -> an empty VPK Archive (version 2 by default): a:add(name, data); a:write() +function Vpk.new(version: number?): any + local a = Archive.new("vpk", encode) + a.meta.source = { format = "vpk", version = version or 2 } + return a +end + +return Vpk diff --git a/tests/archive/vpk.luau b/tests/archive/vpk.luau new file mode 100644 index 0000000..fe92edf --- /dev/null +++ b/tests/archive/vpk.luau @@ -0,0 +1,132 @@ +-- archive/vpk tests: version 1 and 2 directory files written by Python's vpk package list the entries it reads back +-- (names, sizes, CRC-32s); a multi-part archive (part files through opts.files and opts.resolve, preload bytes, an +-- embedded entry); our writer's version 1 / 2 output read back by the vpk package (MD5 verify for version 2) and by +-- us; CRC checks; errors; the fuzz pass. Fixtures: tools/fixtures/vpk.py. +local T = require("@tests/T") +local F = require("@formats") +local Vpk = require("@formats/archive/vpk") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/vpk") +local Src = require("@tests/gen/vpk_src") + +local t = T.suite("vpk") +t:eq(Vpk.name, "vpk", "name") + +local function check(a: any, want: { any }, label: string) + local by = {} + for _, e in a:list() do + by[e.name] = e + end + t:eq(#a:list(), #want, label .. ": entry count") + for _, w in want do + local e = by[w.name] + t:check(e, label .. ": has " .. w.name) + if e then + t:eq(e.size, w.size, label .. ": size " .. w.name) + local b, err = a:read(w.name) + t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err)) + t:eq(Crc32.of(b), w.crc, label .. ": data " .. w.name) + end + end +end + +-- 1. Python's vpk package +for _, c in Fx.cases do + local a, err = Vpk.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + check(a, c.entries, c.name) + t:eq(a.meta.source.version, c.version, c.name .. ": version") + t:eq(F.detect(c.data), "vpk", c.name .. ": F.detect") + if c.version == 2 then + t:check(a.meta.source.v2.fileMd5 and #a.meta.source.v2.fileMd5 == 16, c.name .. ": MD5 section") + end +end + +-- 2. multi-part +do + local m = Fx.multi + local a = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir)), { files = m.parts, name = "maps/pak01_dir.vpk" }) + check(a, m.entries, "multi (opts.files)") + t:eq(#a.meta.source.parts, 2, "two part files") + local asked = {} + local b = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir)), { + resolve = function(name: string): string? + table.insert(asked, name) + return m.parts[name] + end, + }) + check(b, m.entries, "multi (opts.resolve, default pak01 name)") + t:check(table.find(asked, "pak01_001.vpk") ~= nil, "resolve gets the part file name") + local c = Vpk.decode(Bytes.reader(buffer.fromstring(m.dir))) + local _, e = c:read("materials/a.vmt") + t:check(e and e.code == Err.UNSUPPORTED, "missing part: " .. tostring(e)) + t:eq(buffer.tostring((c:read("root.txt"))), "embedded", "embedded entry without the parts") + -- multi-part -> single file + local one = F.load(F.save(b) :: buffer) + check(one, m.entries, "multi -> one directory file") +end + +-- 3. our writer, read back by the vpk package and by us +for k, v in Fx.ours do + t:check(v.ok, k .. ": the vpk package verifies our MD5s") + t:eq(#v.entries, #Fx.want, k .. ": the vpk package lists every entry") + for i, w in Fx.want do + local g = v.entries[i] + t:check(g and g.name == w.name and g.size == w.size and g.crc == w.crc, k .. ": " .. w.name) + end + local a = Vpk.new(v.version) + for _, f in Src do + a:add(f.name, f.data) + end + check(Vpk.decode(Bytes.reader(a:write() :: buffer)), Fx.want, k .. ": round trip") +end + +-- 4. errors +do + local c = Fx.cases[2] + local bad = buffer.fromstring(c.data) + -- flip a byte in the last entry's data (before the 48-byte MD5 section) + local at = #c.data - 49 + buffer.writeu8(bad, at, bit32.bxor(buffer.readu8(bad, at), 0xFF)) + local a = Vpk.decode(Bytes.reader(bad)) + local failed = 0 + for _, e in a:list() do + local _, err = a:read(e.name) + if err and err.code == Err.CHECKSUM then + failed += 1 + end + end + t:eq(failed, 1, "a damaged entry fails its CRC") + local nv = Vpk.decode(Bytes.reader(bad), { verify = false }) + local ok = true + for _, e in nv:list() do + ok = ok and nv:read(e.name) ~= nil + end + t:check(ok, "verify = false") + local _, e1 = Vpk.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 40)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated tree: " .. tostring(e1)) + local v3 = buffer.fromstring(c.data) + buffer.writeu32(v3, 4, 3) + local _, e2 = Vpk.decode(Bytes.reader(v3)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 3") + local _, e3 = Vpk.new(3):write() + t:check(e3 and e3.code == Err.ARG, "write version 3") +end + +local samples = { Fx.multi.dir } +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local a = Vpk.decode(Bytes.reader(b), { files = Fx.multi.parts }) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 60 }) + +t:done() diff --git a/tools/fixtures/_vpk_encode.luau b/tools/fixtures/_vpk_encode.luau new file mode 100644 index 0000000..3b1db18 --- /dev/null +++ b/tools/fixtures/_vpk_encode.luau @@ -0,0 +1,20 @@ +-- tools/fixtures/_vpk_encode.luau: run by tools/fixtures/vpk.py under the luau CLI: writes the files of +-- tests/gen/vpk_src as VPK version 1 and 2 with our encoder and prints "\t" lines for Python's vpk +-- package to read back (and verify the version 2 MD5s). +local Vpk = require("@formats/archive/vpk") +local Src = require("@tests/gen/vpk_src") + +local function hex(b: buffer): string + local s = buffer.tostring(b) + return (string.gsub(s, ".", function(c: string): string + return string.format("%02x", string.byte(c)) + end)) +end + +for _, version in { 1, 2 } do + local a = Vpk.new(version) + for _, f in Src do + a:add(f.name, f.data) + end + print("v" .. version .. "\t" .. hex(a:write() :: buffer)) +end diff --git a/tools/fixtures/vpk.py b/tools/fixtures/vpk.py new file mode 100644 index 0000000..4175026 --- /dev/null +++ b/tools/fixtures/vpk.py @@ -0,0 +1,122 @@ +# Valve VPK fixtures (tools/fixtures.py). References: +# - Python's vpk package (nix python3Packages.vpk) writes version 1 and 2 directory files (data embedded, MD5 +# section) from a folder of random files; its reader lists them (names, sizes, CRC-32s); +# - a multi-part archive written here from the VDC layout: a pak01_dir.vpk whose entries live in pak01_000.vpk / +# pak01_001.vpk, with preload bytes in the tree, plus an embedded one; +# - our encoder's output (tools/fixtures/_vpk_encode.luau through the luau CLI) read back by the vpk package, with +# version 2's MD5 verify(): verdicts in `ours`. +# tests/gen/vpk_src.luau { { name, data } } (the files) +# tests/gen/vpk.luau { cases = { { name, data, version, entries = { { name, size, crc } } } }, multi = { dir, +# parts = { [name] = data }, entries }, ours = { v1 = { ok, entries }, v2 = ... } } +import importlib.util, json, os, shutil, struct, tempfile, zlib + +INPUTS = ["src/Formats/archive/vpk", "tools/fixtures/_vpk_encode.luau"] + + +def luau_encode(ctx, script): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m.luau_encode(ctx, script) + +READ = r""" +import json, sys, vpk, zlib +out = {} +for name, path in json.loads(sys.stdin.read()).items(): + p = vpk.open(path) + ents = [] + for f in sorted(p): + d = p.get_file(f).read() + ents.append({"name": f, "size": len(d), "crc": zlib.crc32(d)}) + ok = True + if p.version == 2: + try: + ok = bool(p.verify()) + except Exception as e: + ok = False + out[name] = {"version": p.version, "entries": ents, "ok": ok} +print(json.dumps(out)) +""" + +WRITE = r""" +import json, sys, vpk +args = json.loads(sys.stdin.read()) +n = vpk.new(args["src"]) +n.version = args["version"] +n.save(args["out"]) +""" + + +def files(rng): + out = [("scripts/game.txt", b"\"game\" { }\n"), ("materials/brick/wall01.vmt", b"LightmappedGeneric { }"), + ("materials/brick/wall01.vtf", rng.randbytes(3000)), ("models/props/crate.mdl", rng.randbytes(2048)), + ("models/props/crate.vvd", rng.randbytes(777)), ("readme.txt", b"root file"), ("sound/empty.wav", b""), + ("maps/de_test.bsp", rng.randbytes(5000))] + return out + + +def multi(rng): + # entries: (path, ext, name, preload, archive index, data) + ents = [("materials", "vmt", "a", b"pre", 0, b"material a body"), ("materials", "vmt", "b", b"", 1, rng.randbytes(500)), + ("models", "mdl", "c", b"\x01\x02", 0, rng.randbytes(300)), (" ", "txt", "root", b"", 0x7fff, b"embedded"), + ("sound", "wav", "d", b"only preload", 1, b"")] + parts = {0: bytearray(), 1: bytearray()} + embedded = bytearray() + tree = bytearray() + exts = [] + for e in ents: + if e[1] not in exts: + exts.append(e[1]) + for ext in exts: + tree += ext.encode() + b"\0" + paths = [] + for e in ents: + if e[1] == ext and e[0] not in paths: + paths.append(e[0]) + for path in paths: + tree += path.encode() + b"\0" + for (p, x, name, pre, idx, data) in ents: + if p == path and x == ext: + target = embedded if idx == 0x7fff else parts[idx] + off = len(target) + target += data + tree += name.encode() + b"\0" + struct.pack("