--!strict -- archive/vpk: Valve VPK v1 / v2 directory files (Valve Developer Community page; no code taken): preload bytes, -- embedded (index 0x7fff) or part-file data ("_NNN.vpk"), CRC-32 checked; writes one self-contained v2 file -- with its MD5s. Not supported: Respawn (Titanfall) VPKs, signature checks, writing multi-part archives. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Input = require("@rosetta/core/Input") local Crc32 = require("@rosetta/core/Crc32") local Md5 = require("@rosetta/core/Md5") local Archive = require("@rosetta/containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Vpk = { name = "vpk", category = "archive", extensions = { "vpk" }, mime = { "application/x-vpk" }, deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" }, caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true }, } -- ------------------------------------------------------------------------------------------------ types export type DecodeOptions = { verify: boolean?, -- default true resolve: ((name: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, name: string?, -- "pak01_dir.vpk" -> "pak01_000.vpk" 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 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 b = Input.sibling(opts, name) 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 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