ws-game: archive/vpk (Valve VPK v1 / v2 read incl. multi-part via opts.resolve / opts.files, preload, CRC checks; single-file v1 / v2 write with MD5 section)

This commit is contained in:
4DBug committed 2026-10-31 14:09:50 -05:00
1 parent 5ec3121f65
commit 34d0600109
6 files changed
+611

No files matched your search

+12
View File
@@ -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",
+324
View File
@@ -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 "<name>_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