rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,530 @@
|
||||
--!strict
|
||||
-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain):
|
||||
-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams /
|
||||
-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and
|
||||
-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it).
|
||||
local Text = require("@rosetta/codecs/text/Text")
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
|
||||
local Header = {}
|
||||
|
||||
export type Coder = { id: string, numIn: number, numOut: number, props: buffer }
|
||||
export type Folder = {
|
||||
coders: { Coder },
|
||||
bindPairs: { { inIndex: number, outIndex: number } },
|
||||
packed: { number }, -- in-stream index of each packed stream
|
||||
unpackSizes: { number }, -- per out stream
|
||||
crc: number?,
|
||||
firstPack: number, -- index of the folder's first pack stream (0-based)
|
||||
numSub: number, -- substreams (files) in the folder
|
||||
}
|
||||
export type Streams = {
|
||||
packPos: number,
|
||||
packSizes: { number },
|
||||
folders: { Folder },
|
||||
subSizes: { number }, -- every substream, folder by folder
|
||||
subCrcs: { [number]: number }, -- 1-based substream index -> CRC
|
||||
}
|
||||
export type File = {
|
||||
name: string,
|
||||
emptyStream: boolean,
|
||||
emptyFile: boolean,
|
||||
anti: boolean,
|
||||
mtime: number?,
|
||||
attributes: number?,
|
||||
}
|
||||
export type Parsed = { streams: Streams?, files: { File }, encoded: Streams? }
|
||||
|
||||
local K = {
|
||||
End = 0x00,
|
||||
Header = 0x01,
|
||||
ArchiveProperties = 0x02,
|
||||
AdditionalStreamsInfo = 0x03,
|
||||
MainStreamsInfo = 0x04,
|
||||
FilesInfo = 0x05,
|
||||
PackInfo = 0x06,
|
||||
UnPackInfo = 0x07,
|
||||
SubStreamsInfo = 0x08,
|
||||
Size = 0x09,
|
||||
CRC = 0x0A,
|
||||
Folder = 0x0B,
|
||||
CodersUnPackSize = 0x0C,
|
||||
NumUnPackStream = 0x0D,
|
||||
EmptyStream = 0x0E,
|
||||
EmptyFile = 0x0F,
|
||||
Anti = 0x10,
|
||||
Name = 0x11,
|
||||
MTime = 0x14,
|
||||
WinAttributes = 0x15,
|
||||
EncodedHeader = 0x17,
|
||||
Dummy = 0x19,
|
||||
}
|
||||
Header.K = K
|
||||
|
||||
local Fail = {}
|
||||
|
||||
local function bad(r: Bytes.Reader, msg: string, code: string?): never
|
||||
error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0)
|
||||
end
|
||||
|
||||
local function check(r: Bytes.Reader)
|
||||
if r.err then
|
||||
error(setmetatable({ err = r.err }, Fail), 0)
|
||||
end
|
||||
end
|
||||
|
||||
local function byte(r: Bytes.Reader): number
|
||||
local v = r:u8()
|
||||
check(r)
|
||||
return v
|
||||
end
|
||||
|
||||
-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes
|
||||
local function number(r: Bytes.Reader): number
|
||||
local first = byte(r)
|
||||
local mask = 0x80
|
||||
local value = 0
|
||||
for i = 0, 7 do
|
||||
if bit32.band(first, mask) == 0 then
|
||||
local high = bit32.band(first, mask - 1)
|
||||
return value + high * 2 ^ (8 * i)
|
||||
end
|
||||
value += byte(r) * 2 ^ (8 * i)
|
||||
mask = bit32.rshift(mask, 1)
|
||||
end
|
||||
return value
|
||||
end
|
||||
|
||||
-- a count bounded by the bytes left (every counted item takes at least `min` bytes)
|
||||
local function count(r: Bytes.Reader, min: number?): number
|
||||
local n = number(r)
|
||||
if n * (min or 1) > r:remaining() + 1 then
|
||||
bad(r, "count " .. n .. " is larger than the header")
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
local function bits(r: Bytes.Reader, n: number): { boolean }
|
||||
local out = table.create(n, false)
|
||||
local cur, mask = 0, 0
|
||||
for i = 1, n do
|
||||
if mask == 0 then
|
||||
cur = byte(r)
|
||||
mask = 0x80
|
||||
end
|
||||
out[i] = bit32.band(cur, mask) ~= 0
|
||||
mask = bit32.rshift(mask, 1)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- bits preceded by an "all defined" byte
|
||||
local function defined(r: Bytes.Reader, n: number): { boolean }
|
||||
if byte(r) ~= 0 then
|
||||
return table.create(n, true)
|
||||
end
|
||||
return bits(r, n)
|
||||
end
|
||||
|
||||
local function digests(r: Bytes.Reader, n: number): { [number]: number }
|
||||
local def = defined(r, n)
|
||||
local out = {}
|
||||
for i = 1, n do
|
||||
if def[i] then
|
||||
out[i] = r:u32le()
|
||||
end
|
||||
end
|
||||
check(r)
|
||||
return out
|
||||
end
|
||||
|
||||
local function packInfo(r: Bytes.Reader, s: Streams)
|
||||
s.packPos = number(r)
|
||||
local n = count(r)
|
||||
while true do
|
||||
local t = byte(r)
|
||||
if t == K.End then
|
||||
break
|
||||
elseif t == K.Size then
|
||||
for i = 1, n do
|
||||
s.packSizes[i] = number(r)
|
||||
end
|
||||
elseif t == K.CRC then
|
||||
digests(r, n)
|
||||
else
|
||||
bad(r, "unexpected property " .. t .. " in pack info")
|
||||
end
|
||||
end
|
||||
if #s.packSizes ~= n then
|
||||
bad(r, "missing pack sizes")
|
||||
end
|
||||
end
|
||||
|
||||
local function folder(r: Bytes.Reader): Folder
|
||||
local ncoders = count(r)
|
||||
if ncoders == 0 or ncoders > 64 then
|
||||
bad(r, "bad coder count " .. ncoders)
|
||||
end
|
||||
local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 }
|
||||
local totalIn, totalOut = 0, 0
|
||||
for _ = 1, ncoders do
|
||||
local flags = byte(r)
|
||||
if bit32.band(flags, 0x80) ~= 0 then
|
||||
bad(r, "alternative coder methods", Err.UNSUPPORTED)
|
||||
end
|
||||
local idSize = bit32.band(flags, 0x0F)
|
||||
local id = r:string(idSize)
|
||||
check(r)
|
||||
local nin, nout = 1, 1
|
||||
if bit32.band(flags, 0x10) ~= 0 then
|
||||
nin = number(r)
|
||||
nout = number(r)
|
||||
if nin > 64 or nout > 64 then
|
||||
bad(r, "bad coder stream count")
|
||||
end
|
||||
end
|
||||
local props = buffer.create(0)
|
||||
if bit32.band(flags, 0x20) ~= 0 then
|
||||
local n = count(r)
|
||||
props = r:bytes(n)
|
||||
check(r)
|
||||
end
|
||||
table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props })
|
||||
totalIn += nin
|
||||
totalOut += nout
|
||||
end
|
||||
if totalOut == 0 then
|
||||
bad(r, "a folder without output")
|
||||
end
|
||||
for _ = 1, totalOut - 1 do
|
||||
local i, o = number(r), number(r)
|
||||
table.insert(f.bindPairs, { inIndex = i, outIndex = o })
|
||||
end
|
||||
local npacked = totalIn - (totalOut - 1)
|
||||
if npacked < 1 then
|
||||
bad(r, "bad bind pairs")
|
||||
end
|
||||
if npacked == 1 then
|
||||
for i = 0, totalIn - 1 do
|
||||
local bound = false
|
||||
for _, bp in f.bindPairs do
|
||||
if bp.inIndex == i then
|
||||
bound = true
|
||||
end
|
||||
end
|
||||
if not bound then
|
||||
table.insert(f.packed, i)
|
||||
break
|
||||
end
|
||||
end
|
||||
if #f.packed ~= 1 then
|
||||
bad(r, "no packed stream")
|
||||
end
|
||||
else
|
||||
for _ = 1, npacked do
|
||||
table.insert(f.packed, number(r))
|
||||
end
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
-- the folder's main out stream: the one no bind pair consumes
|
||||
function Header.mainOut(f: Folder): number?
|
||||
local total = 0
|
||||
for _, c in f.coders do
|
||||
total += c.numOut
|
||||
end
|
||||
for o = 0, total - 1 do
|
||||
local bound = false
|
||||
for _, bp in f.bindPairs do
|
||||
if bp.outIndex == o then
|
||||
bound = true
|
||||
end
|
||||
end
|
||||
if not bound then
|
||||
return o
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Header.unpackSize(f: Folder): number
|
||||
local m = Header.mainOut(f)
|
||||
return if m then f.unpackSizes[m + 1] or 0 else 0
|
||||
end
|
||||
|
||||
local function unpackInfo(r: Bytes.Reader, s: Streams)
|
||||
if byte(r) ~= K.Folder then
|
||||
bad(r, "expected the folder list")
|
||||
end
|
||||
local n = count(r)
|
||||
if byte(r) ~= 0 then
|
||||
bad(r, "external folders", Err.UNSUPPORTED)
|
||||
end
|
||||
for i = 1, n do
|
||||
s.folders[i] = folder(r)
|
||||
end
|
||||
if byte(r) ~= K.CodersUnPackSize then
|
||||
bad(r, "expected the coder unpack sizes")
|
||||
end
|
||||
for _, f in s.folders do
|
||||
local total = 0
|
||||
for _, c in f.coders do
|
||||
total += c.numOut
|
||||
end
|
||||
for k = 1, total do
|
||||
f.unpackSizes[k] = number(r)
|
||||
end
|
||||
end
|
||||
while true do
|
||||
local t = byte(r)
|
||||
if t == K.End then
|
||||
break
|
||||
elseif t == K.CRC then
|
||||
local d = digests(r, n)
|
||||
for i = 1, n do
|
||||
s.folders[i].crc = d[i]
|
||||
end
|
||||
else
|
||||
bad(r, "unexpected property " .. t .. " in unpack info")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function subStreamsInfo(r: Bytes.Reader, s: Streams)
|
||||
local t = byte(r)
|
||||
if t == K.NumUnPackStream then
|
||||
for _, f in s.folders do
|
||||
f.numSub = count(r, 0)
|
||||
end
|
||||
t = byte(r)
|
||||
end
|
||||
local sizes = s.subSizes
|
||||
if t == K.Size then
|
||||
for _, f in s.folders do
|
||||
if f.numSub > 0 then
|
||||
local sum = 0
|
||||
for _ = 1, f.numSub - 1 do
|
||||
local v = number(r)
|
||||
sum += v
|
||||
table.insert(sizes, v)
|
||||
end
|
||||
local total = Header.unpackSize(f)
|
||||
if sum > total then
|
||||
bad(r, "substream sizes exceed the folder")
|
||||
end
|
||||
table.insert(sizes, total - sum)
|
||||
end
|
||||
end
|
||||
t = byte(r)
|
||||
else
|
||||
for _, f in s.folders do
|
||||
if f.numSub > 1 then
|
||||
bad(r, "missing substream sizes")
|
||||
elseif f.numSub == 1 then
|
||||
table.insert(sizes, Header.unpackSize(f))
|
||||
end
|
||||
end
|
||||
end
|
||||
-- CRCs for the streams whose folder CRC does not already cover them
|
||||
local unknown = 0
|
||||
for _, f in s.folders do
|
||||
if not (f.numSub == 1 and f.crc) then
|
||||
unknown += f.numSub
|
||||
end
|
||||
end
|
||||
while t ~= K.End do
|
||||
if t == K.CRC then
|
||||
local d = digests(r, unknown)
|
||||
local k, si = 1, 1
|
||||
for _, f in s.folders do
|
||||
if f.numSub == 1 and f.crc then
|
||||
s.subCrcs[si] = f.crc
|
||||
si += 1
|
||||
else
|
||||
for _ = 1, f.numSub do
|
||||
s.subCrcs[si] = d[k]
|
||||
k += 1
|
||||
si += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
bad(r, "unexpected property " .. t .. " in substreams info")
|
||||
end
|
||||
t = byte(r)
|
||||
end
|
||||
end
|
||||
|
||||
local function streamsInfo(r: Bytes.Reader): Streams
|
||||
local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
|
||||
local sawSub = false
|
||||
while true do
|
||||
local t = byte(r)
|
||||
if t == K.End then
|
||||
break
|
||||
elseif t == K.PackInfo then
|
||||
packInfo(r, s)
|
||||
elseif t == K.UnPackInfo then
|
||||
unpackInfo(r, s)
|
||||
elseif t == K.SubStreamsInfo then
|
||||
subStreamsInfo(r, s)
|
||||
sawSub = true
|
||||
else
|
||||
bad(r, "unexpected property " .. t .. " in streams info")
|
||||
end
|
||||
end
|
||||
if not sawSub then
|
||||
for i, f in s.folders do
|
||||
f.numSub = 1
|
||||
table.insert(s.subSizes, Header.unpackSize(f))
|
||||
if f.crc then
|
||||
s.subCrcs[i] = f.crc
|
||||
end
|
||||
end
|
||||
end
|
||||
local p = 0
|
||||
for _, f in s.folders do
|
||||
f.firstPack = p
|
||||
p += #f.packed
|
||||
end
|
||||
if p > #s.packSizes then
|
||||
bad(r, "folders use more pack streams than exist")
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
local function utf16(b: buffer, o: number, n: number): string
|
||||
return Text.utf16(b, o, n, false)
|
||||
end
|
||||
|
||||
local function filesInfo(r: Bytes.Reader): { File }
|
||||
local n = count(r, 0)
|
||||
if n > 1000000 then
|
||||
bad(r, "too many files", Err.LIMIT)
|
||||
end
|
||||
local files: { File } = table.create(n) :: { File }
|
||||
for i = 1, n do
|
||||
files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false }
|
||||
end
|
||||
local empties: { number } = {}
|
||||
while true do
|
||||
local t = byte(r)
|
||||
if t == K.End then
|
||||
break
|
||||
end
|
||||
local size = number(r)
|
||||
if size > r:remaining() then
|
||||
bad(r, "file property past the header")
|
||||
end
|
||||
local pr = r:slice(size)
|
||||
check(r)
|
||||
if t == K.EmptyStream then
|
||||
local v = bits(pr, n)
|
||||
empties = {}
|
||||
for i = 1, n do
|
||||
files[i].emptyStream = v[i]
|
||||
if v[i] then
|
||||
table.insert(empties, i)
|
||||
end
|
||||
end
|
||||
elseif t == K.EmptyFile or t == K.Anti then
|
||||
local v = bits(pr, #empties)
|
||||
for k, i in empties do
|
||||
if t == K.EmptyFile then
|
||||
files[i].emptyFile = v[k]
|
||||
else
|
||||
files[i].anti = v[k]
|
||||
end
|
||||
end
|
||||
elseif t == K.Name then
|
||||
if byte(pr) ~= 0 then
|
||||
bad(pr, "external names", Err.UNSUPPORTED)
|
||||
end
|
||||
local b = pr.buf
|
||||
local p = pr.pos
|
||||
for i = 1, n do
|
||||
local q = p
|
||||
while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do
|
||||
q += 2
|
||||
end
|
||||
if q + 1 >= pr.limit then
|
||||
bad(pr, "unterminated name")
|
||||
end
|
||||
files[i].name = utf16(b, p, q - p)
|
||||
p = q + 2
|
||||
end
|
||||
elseif t == K.MTime or t == K.WinAttributes then
|
||||
local def = defined(pr, n)
|
||||
if byte(pr) ~= 0 then
|
||||
bad(pr, "external file properties", Err.UNSUPPORTED)
|
||||
end
|
||||
for i = 1, n do
|
||||
if def[i] then
|
||||
if t == K.MTime then
|
||||
local ft = pr:u64le()
|
||||
files[i].mtime = math.floor(ft / 1e7 - 11644473600)
|
||||
else
|
||||
files[i].attributes = pr:u32le()
|
||||
end
|
||||
end
|
||||
end
|
||||
check(pr)
|
||||
end
|
||||
-- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped
|
||||
end
|
||||
return files
|
||||
end
|
||||
|
||||
local function header(r: Bytes.Reader): Parsed
|
||||
local p: Parsed = { streams = nil, files = {}, encoded = nil }
|
||||
while true do
|
||||
local t = byte(r)
|
||||
if t == K.End then
|
||||
break
|
||||
elseif t == K.ArchiveProperties then
|
||||
while true do
|
||||
local pt = byte(r)
|
||||
if pt == 0 then
|
||||
break
|
||||
end
|
||||
r:skip(number(r))
|
||||
check(r)
|
||||
end
|
||||
elseif t == K.AdditionalStreamsInfo then
|
||||
streamsInfo(r)
|
||||
elseif t == K.MainStreamsInfo then
|
||||
p.streams = streamsInfo(r)
|
||||
elseif t == K.FilesInfo then
|
||||
p.files = filesInfo(r)
|
||||
else
|
||||
bad(r, "unexpected property " .. t .. " in the header")
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to
|
||||
-- decode and parse again.
|
||||
function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?)
|
||||
local r = Bytes.reader(b, o, n)
|
||||
local ok, res = pcall(function(): Parsed
|
||||
local t = byte(r)
|
||||
if t == K.Header then
|
||||
return header(r)
|
||||
elseif t == K.EncodedHeader then
|
||||
return { streams = nil, files = {}, encoded = streamsInfo(r) }
|
||||
end
|
||||
return bad(r, "bad header type " .. t)
|
||||
end)
|
||||
if ok then
|
||||
return res, nil
|
||||
end
|
||||
if type(res) == "table" and getmetatable(res :: any) == Fail then
|
||||
return nil, (res :: any).err
|
||||
end
|
||||
error(res, 0)
|
||||
end
|
||||
|
||||
return Header
|
||||
@@ -0,0 +1,391 @@
|
||||
--!strict
|
||||
-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose
|
||||
-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed)
|
||||
-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate / BZip2 /
|
||||
-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) with BCJ (x86, PowerPC, ARM,
|
||||
-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes,
|
||||
-- Windows / Unix attributes, folder and file CRC-32s (verified on read).
|
||||
-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): PPMd, BCJ2, Deflate64, other
|
||||
-- plug-in codecs (Brotli, LZ4, ...), AES encryption, multi-volume archives, external header references; writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
|
||||
local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Header = require("@rosetta/archive/7z/Header")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local SevenZip = {
|
||||
name = "7z",
|
||||
category = "archive",
|
||||
extensions = { "7z" },
|
||||
mime = { "application/x-7z-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/compress/Lzma", "codecs/compress/Deflate", "codecs/compress/Bzip2", "codecs/compress/Zstd", "containers/Archive", "codecs/text/Text" },
|
||||
caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30)
|
||||
checkCrc: boolean?, -- verify CRC-32s on read (default true)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "7z\188\175\39\28"
|
||||
|
||||
-- method id -> xz filter id (BCJ / delta)
|
||||
local FILTERS: { [string]: number } = {
|
||||
["\3\3\1\3"] = 0x04, -- x86
|
||||
["\3\3\2\5"] = 0x05, -- PowerPC
|
||||
["\3\3\5\1"] = 0x07, -- ARM
|
||||
["\3\3\7\1"] = 0x08, -- ARM-Thumb
|
||||
["\3\3\8\5"] = 0x09, -- SPARC
|
||||
["\10"] = 0x0A, -- ARM64
|
||||
["\3"] = 0x03, -- delta
|
||||
}
|
||||
local NAMES: { [string]: string } = {
|
||||
["\0"] = "copy",
|
||||
["\3\1\1"] = "lzma",
|
||||
["\33"] = "lzma2",
|
||||
["\4\1\8"] = "deflate",
|
||||
["\4\1\9"] = "deflate64",
|
||||
["\4\2\2"] = "bzip2",
|
||||
["\3\4\1"] = "ppmd",
|
||||
["\3\3\1\27"] = "bcj2",
|
||||
["\6\241\7\1"] = "aes",
|
||||
["\4\247\17\1"] = "zstd",
|
||||
["\4\247\17\2"] = "brotli",
|
||||
["\3\3\1\3"] = "bcj",
|
||||
["\3\3\2\5"] = "ppc",
|
||||
["\3\3\5\1"] = "arm",
|
||||
["\3\3\7\1"] = "armt",
|
||||
["\3\3\8\5"] = "sparc",
|
||||
["\10"] = "arm64",
|
||||
["\3"] = "delta",
|
||||
}
|
||||
|
||||
local function methodName(id: string): string
|
||||
local n = NAMES[id]
|
||||
if n then
|
||||
return n
|
||||
end
|
||||
local hex = {}
|
||||
for i = 1, #id do
|
||||
table.insert(hex, string.format("%02x", string.byte(id, i)))
|
||||
end
|
||||
return "method " .. table.concat(hex)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function SevenZip.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(6) == MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream
|
||||
type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number }
|
||||
|
||||
local function packStart(ctx: Ctx, s: Header.Streams, index: number): number
|
||||
local p = ctx.base + 32 + s.packPos
|
||||
for i = 1, index do
|
||||
p += s.packSizes[i]
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?)
|
||||
-- coder -> first in / out stream index
|
||||
local inBase, outBase = {}, {}
|
||||
local ni, no = 0, 0
|
||||
for i, c in f.coders do
|
||||
inBase[i], outBase[i] = ni, no
|
||||
ni += c.numIn
|
||||
no += c.numOut
|
||||
end
|
||||
local depth = 0
|
||||
local function out(outIdx: number): (buffer?, Err.Err?)
|
||||
depth += 1
|
||||
if depth > 32 then
|
||||
return nil, Err.new(Err.CORRUPT, "coder graph too deep")
|
||||
end
|
||||
local ci
|
||||
for i, c in f.coders do
|
||||
if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then
|
||||
ci = i
|
||||
end
|
||||
end
|
||||
if not ci then
|
||||
return nil, Err.new(Err.CORRUPT, "bad bind pair")
|
||||
end
|
||||
local c = f.coders[ci]
|
||||
if c.numIn ~= 1 or c.numOut ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)")
|
||||
end
|
||||
local size = f.unpackSizes[outIdx + 1] or 0
|
||||
if size > ctx.maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size))
|
||||
end
|
||||
-- the coder's input: another coder's output, or a packed stream
|
||||
local inIdx = inBase[ci]
|
||||
local src: buffer, so: number, sl: number
|
||||
local bound = nil
|
||||
for _, bp in f.bindPairs do
|
||||
if bp.inIndex == inIdx then
|
||||
bound = bp.outIndex
|
||||
end
|
||||
end
|
||||
if bound then
|
||||
local b, e = out(bound)
|
||||
if not b then
|
||||
return nil, e
|
||||
end
|
||||
src = b
|
||||
so = 0
|
||||
sl = buffer.len(b)
|
||||
else
|
||||
local k = table.find(f.packed, inIdx)
|
||||
if not k then
|
||||
return nil, Err.new(Err.CORRUPT, "unbound coder input")
|
||||
end
|
||||
local pi = f.firstPack + k - 1
|
||||
if pi >= #s.packSizes then
|
||||
return nil, Err.new(Err.CORRUPT, "missing pack stream")
|
||||
end
|
||||
so = packStart(ctx, s, pi)
|
||||
sl = s.packSizes[pi + 1]
|
||||
if so + sl > ctx.limit or so < ctx.base then
|
||||
return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so)
|
||||
end
|
||||
src = ctx.buf
|
||||
end
|
||||
local id = c.id
|
||||
local opts: { maxBytes: number?, verify: boolean? } = { maxBytes = ctx.maxBytes }
|
||||
if id == "\0" then
|
||||
if sl < size then
|
||||
return nil, Err.new(Err.TRUNCATED, "short stored stream")
|
||||
end
|
||||
local b = buffer.create(size)
|
||||
buffer.copy(b, 0, src, so, size)
|
||||
return b, nil
|
||||
elseif id == "\3\1\1" then
|
||||
if buffer.len(c.props) < 5 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad LZMA properties")
|
||||
end
|
||||
local b, e = Lzma.lzma(src, so, sl, c.props, size, opts)
|
||||
return b, if b then nil else e
|
||||
elseif id == "\33" then
|
||||
local b, e = Lzma.lzma2(src, so, sl, nil, size, opts)
|
||||
return b, if b then nil else e
|
||||
elseif id == "\4\1\8" then
|
||||
local b, e = Deflate.inflate(src, so, sl, size)
|
||||
return b, if b then nil else e
|
||||
elseif id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames)
|
||||
local b, e
|
||||
if id == "\4\2\2" then
|
||||
b, e = Bzip2.decompress(src, so, sl, opts)
|
||||
else
|
||||
b, e = Zstd.decompress(src, so, sl, opts)
|
||||
end
|
||||
if not b then
|
||||
return nil, e
|
||||
end
|
||||
if buffer.len(b) ~= size then
|
||||
return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size")
|
||||
end
|
||||
return b, nil
|
||||
elseif FILTERS[id] then
|
||||
if sl ~= size then
|
||||
return nil, Err.new(Err.CORRUPT, "filter size mismatch")
|
||||
end
|
||||
local b = buffer.create(size)
|
||||
buffer.copy(b, 0, src, so, size)
|
||||
local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props)
|
||||
if not ok then
|
||||
return nil, e
|
||||
end
|
||||
return b, nil
|
||||
end
|
||||
return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported")
|
||||
end
|
||||
local main = Header.mainOut(f)
|
||||
if not main then
|
||||
return nil, Err.new(Err.CORRUPT, "folder without a main output")
|
||||
end
|
||||
return out(main)
|
||||
end
|
||||
|
||||
local function folderMethod(f: Header.Folder): string
|
||||
local names = {}
|
||||
for _, c in f.coders do
|
||||
table.insert(names, methodName(c.id))
|
||||
end
|
||||
return table.concat(names, "+")
|
||||
end
|
||||
|
||||
function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30
|
||||
local checkCrc = o.checkCrc ~= false
|
||||
local b, base, limit = r.buf, r.base, r.limit
|
||||
if limit - base < 32 then
|
||||
return nil, Err.new(Err.TRUNCATED, "truncated signature header", base)
|
||||
end
|
||||
if buffer.readstring(b, base, 6) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad 7z signature", base)
|
||||
end
|
||||
if buffer.readu8(b, base + 6) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6)
|
||||
end
|
||||
if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then
|
||||
return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8)
|
||||
end
|
||||
local hr = Bytes.reader(b, base + 12, 20)
|
||||
local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le()
|
||||
local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes }
|
||||
local a = Archive.new("7z")
|
||||
if nextSize == 0 then
|
||||
return a, nil -- an empty archive
|
||||
end
|
||||
local ho = base + 32 + nextOff
|
||||
if nextOff < 0 or ho + nextSize > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12)
|
||||
end
|
||||
if Crc32.raw(b, ho, nextSize) ~= nextCrc then
|
||||
return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho)
|
||||
end
|
||||
local hbuf, hoff, hlen = b, ho, nextSize
|
||||
local parsed
|
||||
for _ = 1, 4 do
|
||||
local p, perr = Header.parse(hbuf, hoff, hlen)
|
||||
if not p then
|
||||
return nil, perr
|
||||
end
|
||||
if not p.encoded then
|
||||
parsed = p
|
||||
break
|
||||
end
|
||||
-- an encoded header: decode folder 1 of its streams, then parse again
|
||||
local es = p.encoded
|
||||
local f = es.folders[1]
|
||||
if not f then
|
||||
return nil, Err.new(Err.CORRUPT, "encoded header without a folder")
|
||||
end
|
||||
local hb, herr = decodeFolder(ctx, es, f)
|
||||
if not hb then
|
||||
return nil, herr
|
||||
end
|
||||
if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch")
|
||||
end
|
||||
hbuf = hb
|
||||
hoff = 0
|
||||
hlen = buffer.len(hb)
|
||||
end
|
||||
if not parsed then
|
||||
return nil, Err.new(Err.CORRUPT, "nested encoded headers")
|
||||
end
|
||||
local s: Header.Streams = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} }
|
||||
a.meta.folders = #s.folders
|
||||
a.meta.solid = false
|
||||
-- folder caches and the substream -> folder map
|
||||
local cache: { [number]: buffer } = {}
|
||||
local subFolder: { number }, subOffset: { number } = {}, {}
|
||||
do
|
||||
local si = 1
|
||||
for fi, f in s.folders do
|
||||
if f.numSub > 1 then
|
||||
a.meta.solid = true
|
||||
end
|
||||
local off = 0
|
||||
for _ = 1, f.numSub do
|
||||
subFolder[si], subOffset[si] = fi, off
|
||||
off += s.subSizes[si] or 0
|
||||
si += 1
|
||||
end
|
||||
if off > Header.unpackSize(f) then
|
||||
return nil, Err.new(Err.CORRUPT, "substreams exceed their folder")
|
||||
end
|
||||
end
|
||||
end
|
||||
local function folderData(fi: number): (buffer?, Err.Err?)
|
||||
local c = cache[fi]
|
||||
if c then
|
||||
return c, nil
|
||||
end
|
||||
local f = s.folders[fi]
|
||||
local d, e = decodeFolder(ctx, s, f)
|
||||
if not d then
|
||||
return nil, e
|
||||
end
|
||||
if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch")
|
||||
end
|
||||
cache[fi] = d
|
||||
return d, nil
|
||||
end
|
||||
local si = 0
|
||||
for _, file in parsed.files do
|
||||
if file.anti then
|
||||
continue
|
||||
end
|
||||
local attr = file.attributes
|
||||
local isDir = file.emptyStream and not file.emptyFile
|
||||
if attr and bit32.band(attr, 0x10) ~= 0 then
|
||||
isDir = true
|
||||
end
|
||||
local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil
|
||||
local e: Archive.Entry = {
|
||||
name = file.name,
|
||||
size = 0,
|
||||
dir = isDir,
|
||||
mtime = file.mtime,
|
||||
attributes = attr,
|
||||
mode = mode,
|
||||
}
|
||||
if not file.emptyStream then
|
||||
si += 1
|
||||
local idx = si
|
||||
local fi = subFolder[idx]
|
||||
if not fi then
|
||||
return nil, Err.new(Err.CORRUPT, "more files than streams")
|
||||
end
|
||||
local size = s.subSizes[idx]
|
||||
e.size = size
|
||||
e.method = folderMethod(s.folders[fi])
|
||||
if s.folders[fi].numSub == 1 then
|
||||
local pk = 0
|
||||
for k = 1, #s.folders[fi].packed do
|
||||
pk += s.packSizes[s.folders[fi].firstPack + k] or 0
|
||||
end
|
||||
e.compressedSize = pk
|
||||
end
|
||||
e.crc = s.subCrcs[idx]
|
||||
e.load = function(): (buffer?, Err.Err?)
|
||||
local d, derr = folderData(fi)
|
||||
if not d then
|
||||
return nil, derr
|
||||
end
|
||||
local off = subOffset[idx]
|
||||
if off + size > buffer.len(d) then
|
||||
return nil, Err.new(Err.CORRUPT, "substream past its folder")
|
||||
end
|
||||
local out = buffer.create(size)
|
||||
buffer.copy(out, 0, d, off, size)
|
||||
local want = s.subCrcs[idx]
|
||||
if checkCrc and want and Crc32.raw(out, 0, size) ~= want then
|
||||
return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
Archive.put(a, e)
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return SevenZip
|
||||
@@ -0,0 +1,288 @@
|
||||
--!strict
|
||||
-- archive/adf: Amiga disk images (.adf: 880 KB double density, 1.76 MB high density, and other sizes holding an
|
||||
-- AmigaDOS volume without a partition table) read as an Archive: the boot block's DOS type (OFS / FFS, international,
|
||||
-- directory cache: meta.fs / meta.intl / meta.dircache), the root block (volume name, dates), directories through
|
||||
-- their 72-slot hash tables and hash chains, files through their header and extension block tables (FFS) or the
|
||||
-- OFS data block chain, soft links (entry.link) and hard links (entry.hardlink = the path linked to; a hard-linked
|
||||
-- file reads its target's data). Protection bits (entry.protect, AmigaDOS order: bit 0 = delete forbidden ...),
|
||||
-- comments (entry.comment) and dates (days / minutes / ticks since 1978-01-01, as unix seconds) are mapped; names are
|
||||
-- ISO-8859-1. Header block checksums are verified (Err.CHECKSUM). Written from the AmigaDOS file system description
|
||||
-- (the ADF-FAQ by Laurent Clévy). Not supported: writing, long-name file systems (DOS\6 / DOS\7), RDB hard-disk
|
||||
-- images (use the partition contents), dircache blocks (not needed to read).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Adf = {
|
||||
name = "adf",
|
||||
category = "archive",
|
||||
extensions = { "adf" },
|
||||
mime = { "application/x-amiga-disk-format" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, variants = { "ofs", "ffs" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 65536
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local BS = 512
|
||||
local HT = 72 -- hash table slots in a 512-byte block
|
||||
local T_HEADER, T_DATA, T_LIST = 2, 8, 16
|
||||
local ST_ROOT, ST_USERDIR, ST_SOFTLINK, ST_LINKDIR, ST_FILE, ST_LINKFILE = 1, 2, 3, 4, -3, -4
|
||||
local EPOCH = 252460800 -- 1978-01-01 in unix seconds
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Adf.sniff(r: Bytes.Reader): number
|
||||
local n = r:size()
|
||||
if n < 4 * BS or n % BS ~= 0 then
|
||||
return 0
|
||||
end
|
||||
local h = r:peek(4)
|
||||
if string.sub(h, 1, 3) ~= "DOS" or string.byte(h, 4) > 5 then
|
||||
return 0
|
||||
end
|
||||
return if n == 901120 or n == 1802240 then 0.95 else 0.6
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function latin1(s: string): string
|
||||
if not string.find(s, "[\128-\255]") then
|
||||
return s
|
||||
end
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = utf8.char(string.byte(s, i))
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
type Disk = { b: buffer, base: number, blocks: number }
|
||||
|
||||
local function u32(d: Disk, blk: number, off: number): number
|
||||
local o = d.base + blk * BS + off
|
||||
return buffer.readu8(d.b, o) * 16777216 + buffer.readu8(d.b, o + 1) * 65536 + buffer.readu8(d.b, o + 2) * 256 + buffer.readu8(d.b, o + 3)
|
||||
end
|
||||
|
||||
local function i32(d: Disk, blk: number, off: number): number
|
||||
local v = u32(d, blk, off)
|
||||
return if v >= 0x80000000 then v - 0x100000000 else v
|
||||
end
|
||||
|
||||
local function bstr(d: Disk, blk: number, off: number, max: number): string
|
||||
local o = d.base + blk * BS + off
|
||||
local n = math.min(buffer.readu8(d.b, o), max)
|
||||
return latin1(buffer.readstring(d.b, o + 1, n))
|
||||
end
|
||||
|
||||
local function checksumOk(d: Disk, blk: number): boolean
|
||||
local sum = 0
|
||||
for i = 0, BS - 4, 4 do
|
||||
sum = (sum + u32(d, blk, i)) % 0x100000000
|
||||
end
|
||||
return sum == 0
|
||||
end
|
||||
|
||||
local function date(d: Disk, blk: number, off: number): number
|
||||
return (u32(d, blk, off) * 86400 + u32(d, blk, off + 4) * 60 + u32(d, blk, off + 8) // 50) + EPOCH
|
||||
end
|
||||
|
||||
-- the data blocks of a file header (FFS: the header and extension tables; OFS uses the same tables)
|
||||
local function dataBlocks(d: Disk, hdr: number, maxBlocks: number): ({ number }?, string?)
|
||||
local out = {}
|
||||
local blk = hdr
|
||||
local seen: { [number]: boolean } = {}
|
||||
while blk ~= 0 do
|
||||
if blk < 2 or blk >= d.blocks or seen[blk] then
|
||||
return nil, "bad extension block " .. blk
|
||||
end
|
||||
seen[blk] = true
|
||||
if blk ~= hdr and (u32(d, blk, 0) ~= T_LIST or not checksumOk(d, blk)) then
|
||||
return nil, "bad extension block " .. blk
|
||||
end
|
||||
local n = u32(d, blk, 8)
|
||||
if n > HT then
|
||||
return nil, "bad block count in " .. blk
|
||||
end
|
||||
for k = 0, n - 1 do
|
||||
local db = u32(d, blk, 24 + (HT - 1 - k) * 4)
|
||||
if db < 2 or db >= d.blocks then
|
||||
return nil, "bad data block " .. db
|
||||
end
|
||||
table.insert(out, db)
|
||||
if #out > maxBlocks then
|
||||
return nil, "more data blocks than the disk has"
|
||||
end
|
||||
end
|
||||
blk = u32(d, blk, BS - 8)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
local function readFile(d: Disk, hdr: number, ofs: boolean): (buffer?, string?)
|
||||
local size = u32(d, hdr, BS - 188)
|
||||
if size > d.blocks * BS then
|
||||
return nil, "file larger than the disk"
|
||||
end
|
||||
local list, err = dataBlocks(d, hdr, d.blocks)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
local out = buffer.create(size)
|
||||
local o = 0
|
||||
for _, db in list do
|
||||
if o >= size then
|
||||
break
|
||||
end
|
||||
if ofs then
|
||||
if u32(d, db, 0) ~= T_DATA then
|
||||
return nil, "data block " .. db .. " is not an OFS data block"
|
||||
end
|
||||
local n = math.min(u32(d, db, 12), 488, size - o)
|
||||
buffer.copy(out, o, d.b, d.base + db * BS + 24, n)
|
||||
o += n
|
||||
else
|
||||
local n = math.min(BS, size - o)
|
||||
buffer.copy(out, o, d.b, d.base + db * BS, n)
|
||||
o += n
|
||||
end
|
||||
end
|
||||
if o < size then
|
||||
return nil, "file data ends early"
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
function Adf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r:size()
|
||||
if n < 4 * BS or n % BS ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "not a whole number of 512-byte blocks")
|
||||
end
|
||||
local h = r:peek(4)
|
||||
if string.sub(h, 1, 3) ~= "DOS" then
|
||||
return nil, Err.new(Err.CORRUPT, "no DOS boot block")
|
||||
end
|
||||
local flags = string.byte(h, 4)
|
||||
if flags > 5 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "DOS\\" .. flags .. " (long names) file systems")
|
||||
end
|
||||
local d: Disk = { b = r.buf, base = r.base, blocks = n // BS }
|
||||
local ofs = bit32.band(flags, 1) == 0
|
||||
local root = (d.blocks - 1 + 2) // 2
|
||||
if u32(d, root, 0) ~= T_HEADER or i32(d, root, BS - 4) ~= ST_ROOT then
|
||||
return nil, Err.new(Err.CORRUPT, "no root block at " .. root)
|
||||
end
|
||||
if not checksumOk(d, root) then
|
||||
return nil, Err.new(Err.CHECKSUM, "root block checksum")
|
||||
end
|
||||
local a = Archive.new("adf")
|
||||
a.meta.volume = bstr(d, root, BS - 80, 30)
|
||||
a.meta.fs = if ofs then "ofs" else "ffs"
|
||||
a.meta.intl = flags >= 2
|
||||
a.meta.dircache = flags >= 4
|
||||
a.meta.dosType = flags
|
||||
a.meta.modified = date(d, root, BS - 92)
|
||||
a.meta.created = date(d, root, BS - 28)
|
||||
a.meta.source = { format = "adf", fs = a.meta.fs, blocks = d.blocks }
|
||||
local maxEntries = o.maxEntries or 65536
|
||||
local count = 0
|
||||
local pathOf: { [number]: string } = {}
|
||||
local links: { { entry: any, target: number } } = {}
|
||||
local visited: { [number]: boolean } = { [root] = true }
|
||||
|
||||
local function walk(dir: number, prefix: string): (boolean, Err.Err?)
|
||||
for slot = 0, HT - 1 do
|
||||
local blk = u32(d, dir, 24 + slot * 4)
|
||||
while blk ~= 0 do
|
||||
if blk < 2 or blk >= d.blocks or visited[blk] then
|
||||
return false, Err.new(Err.CORRUPT, "bad or looping hash chain at block " .. blk)
|
||||
end
|
||||
visited[blk] = true
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return false, Err.new(Err.LIMIT, "more than maxEntries entries")
|
||||
end
|
||||
if u32(d, blk, 0) ~= T_HEADER then
|
||||
return false, Err.new(Err.CORRUPT, "block " .. blk .. " is not a header block")
|
||||
end
|
||||
if not checksumOk(d, blk) then
|
||||
return false, Err.new(Err.CHECKSUM, "header block " .. blk .. " checksum")
|
||||
end
|
||||
local name = prefix .. bstr(d, blk, BS - 80, 30)
|
||||
local st = i32(d, blk, BS - 4)
|
||||
local e: any = {
|
||||
name = name,
|
||||
size = 0,
|
||||
dir = false,
|
||||
mtime = date(d, blk, BS - 92),
|
||||
protect = u32(d, blk, BS - 192),
|
||||
comment = bstr(d, blk, BS - 184, 79),
|
||||
method = "store",
|
||||
}
|
||||
if e.comment == "" then
|
||||
e.comment = nil
|
||||
end
|
||||
if st == ST_USERDIR then
|
||||
e.name = name .. "/"
|
||||
e.dir = true
|
||||
pathOf[blk] = e.name
|
||||
Archive.put(a, e)
|
||||
local ok, err = walk(blk, e.name)
|
||||
if not ok then
|
||||
return false, err
|
||||
end
|
||||
elseif st == ST_FILE then
|
||||
e.size = u32(d, blk, BS - 188)
|
||||
pathOf[blk] = name
|
||||
local hb = blk
|
||||
e.load = function(): (buffer?, Err.Err?)
|
||||
local data, err = readFile(d, hb, ofs)
|
||||
if not data then
|
||||
return nil, Err.new(Err.CORRUPT, tostring(err))
|
||||
end
|
||||
return data, nil
|
||||
end
|
||||
Archive.put(a, e)
|
||||
elseif st == ST_SOFTLINK then
|
||||
local lo = d.base + blk * BS + 24
|
||||
local s = buffer.readstring(d.b, lo, BS - 24 - 200)
|
||||
e.link = latin1(string.match(s, "^[^%z]*") or "")
|
||||
e.type = "symlink"
|
||||
Archive.put(a, e)
|
||||
elseif st == ST_LINKFILE or st == ST_LINKDIR then
|
||||
e.type = "hardlink"
|
||||
e.dir = st == ST_LINKDIR
|
||||
if e.dir then
|
||||
e.name = name .. "/"
|
||||
end
|
||||
Archive.put(a, e)
|
||||
table.insert(links, { entry = e, target = u32(d, blk, BS - 44) })
|
||||
end
|
||||
blk = u32(d, blk, BS - 16)
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
local ok, err = walk(root, "")
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
-- hard links: the linked path, and a file link reads its target's data
|
||||
for _, l in links do
|
||||
local target = pathOf[l.target]
|
||||
l.entry.hardlink = target
|
||||
if target and not l.entry.dir then
|
||||
local te = a._byName[target]
|
||||
if te then
|
||||
l.entry.size = te.size
|
||||
l.entry.load = te.load
|
||||
end
|
||||
end
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Adf
|
||||
@@ -0,0 +1,190 @@
|
||||
--!strict
|
||||
-- archive/applesingle: AppleSingle (magic 0x00051600) and AppleDouble (0x00051607) files, versions 1 and 2 (RFC 1740):
|
||||
-- the entry table with the data fork (1), resource fork (2), real name (3), comment (4), file dates (8, version 2:
|
||||
-- seconds since 2000-01-01; version 1's file info (7) as Mac dates) and Finder info (9: type, creator, flags).
|
||||
-- Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a resource fork the
|
||||
-- entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime / comment); the name is the real name
|
||||
-- entry, else the file name without the "._" AppleDouble prefix (opts.name), else "data". An AppleDouble file holds
|
||||
-- no data fork: only its resource fork entry is listed, and meta.double = true. Writes version 2 AppleSingle (or AppleDouble with
|
||||
-- opts.double) from any Archive's first Mac file or a buffer. Written from RFC 1740. Not supported: icon, ProDOS /
|
||||
-- MS-DOS / AFP info entries (kept in meta.entries as id + length).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local MacFile = require("@rosetta/containers/MacFile")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local AppleSingle = {
|
||||
name = "applesingle",
|
||||
category = "archive",
|
||||
extensions = { "as", "applesingle", "appledouble" },
|
||||
mime = { "application/applefile", "multipart/appledouble" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/MacFile" },
|
||||
caps = { decode = true, encode = true, forks = true, variants = { "applesingle", "appledouble" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { name: string?, maxBytes: number? } -- name: the file name (the api passes it)
|
||||
export type EncodeOptions = {
|
||||
double: boolean?, -- write AppleDouble (no data fork) instead of AppleSingle (default false)
|
||||
name: string?, -- the name of a buffer / string value (default "data")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local SINGLE, DOUBLE = 0x00051600, 0x00051607
|
||||
local Y2K = 946684800 -- 2000-01-01 in unix seconds
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function AppleSingle.sniff(r: Bytes.Reader): number
|
||||
local h = r:peek(8)
|
||||
if #h < 8 then
|
||||
return 0
|
||||
end
|
||||
local magic = string.sub(h, 1, 4)
|
||||
local ver = string.sub(h, 5, 8)
|
||||
if (magic == "\0\5\22\0" or magic == "\0\5\22\7") and (ver == "\0\1\0\0" or ver == "\0\2\0\0") then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return AppleSingle.encode(a, o)
|
||||
end
|
||||
|
||||
local function i32(v: number): number
|
||||
return if v >= 0x80000000 then v - 0x100000000 else v
|
||||
end
|
||||
|
||||
function AppleSingle.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local magic, ver = r:u32be(), r:u32be()
|
||||
r:skip(16)
|
||||
local count = r:u16be()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if (magic ~= SINGLE and magic ~= DOUBLE) or (ver ~= 0x10000 and ver ~= 0x20000) then
|
||||
return nil, Err.new(Err.CORRUPT, "not AppleSingle / AppleDouble")
|
||||
end
|
||||
local size = r:size()
|
||||
local info: MacFile.Info = { name = "", data = buffer.create(0), rsrc = buffer.create(0), type = "\0\0\0\0", creator = "\0\0\0\0", flags = 0 }
|
||||
local others = {}
|
||||
local total = 0
|
||||
for _ = 1, count do
|
||||
local id, off, len = r:u32be(), r:u32be(), r:u32be()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if off + len > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. id .. " past the end")
|
||||
end
|
||||
total += len
|
||||
if total > (o.maxBytes or 2 ^ 30) then
|
||||
return nil, Err.new(Err.LIMIT, "entries larger than maxBytes")
|
||||
end
|
||||
local e = r:sub(off, len)
|
||||
if id == 1 then
|
||||
info.data = e:bytes(len)
|
||||
elseif id == 2 then
|
||||
info.rsrc = e:bytes(len)
|
||||
elseif id == 3 then
|
||||
info.name = MacFile.name(e:string(len))
|
||||
elseif id == 4 then
|
||||
info.comment = MacFile.name(e:string(len))
|
||||
elseif id == 8 and len >= 8 then
|
||||
local c, m = e:u32be(), e:u32be()
|
||||
info.created = if c == 0x80000000 then nil else i32(c) + Y2K
|
||||
info.modified = if m == 0x80000000 then nil else i32(m) + Y2K
|
||||
elseif id == 7 and len >= 12 and ver == 0x10000 then
|
||||
local c, m = e:u32be(), e:u32be()
|
||||
info.created, info.modified = MacFile.fromMac(c), MacFile.fromMac(m)
|
||||
elseif id == 9 and len >= 10 then
|
||||
info.type, info.creator = e:string(4), e:string(4)
|
||||
info.flags = e:u16be()
|
||||
else
|
||||
table.insert(others, { id = id, length = len })
|
||||
end
|
||||
end
|
||||
if info.name == "" then
|
||||
local n = if type(o.name) == "string" then string.match(o.name, "([^/\\]+)$") else nil
|
||||
info.name = if n then (string.match(n, "^%._(.+)$") or n) else "data"
|
||||
end
|
||||
local a = Archive.new("applesingle", encoder)
|
||||
MacFile.put(a, info, magic == DOUBLE)
|
||||
a.meta.double = magic == DOUBLE
|
||||
a.meta.entries = others
|
||||
a.meta.stream = magic == SINGLE and buffer.len(info.rsrc) == 0
|
||||
a.meta.source = { format = "applesingle", variant = if magic == DOUBLE then "appledouble" else "applesingle", version = ver // 0x10000 }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function AppleSingle.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local files, err = MacFile.collect(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
local f = files[1]
|
||||
if not f then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local name = MacFile.roman(f.name)
|
||||
local function date(t: number?): number
|
||||
if type(t) ~= "number" then
|
||||
return 0x80000000
|
||||
end
|
||||
return math.clamp(math.floor(t - Y2K), -0x80000000, 0x7FFFFFFF) % 0x100000000
|
||||
end
|
||||
local dates = Bytes.writer(16)
|
||||
dates:u32be(date(f.created or f.modified))
|
||||
dates:u32be(date(f.modified))
|
||||
dates:u32be(0x80000000)
|
||||
dates:u32be(0x80000000)
|
||||
local finder = Bytes.writer(32)
|
||||
finder:string(f.type)
|
||||
finder:string(f.creator)
|
||||
finder:u16be(f.flags)
|
||||
finder:string(string.rep("\0", 22))
|
||||
local entries: { { any } } = { { 3, buffer.fromstring(name) } }
|
||||
if f.comment then
|
||||
table.insert(entries, { 4, buffer.fromstring(MacFile.roman(f.comment)) })
|
||||
end
|
||||
table.insert(entries, { 8, dates:finish() })
|
||||
table.insert(entries, { 9, finder:finish() })
|
||||
if not o.double then
|
||||
table.insert(entries, { 1, f.data })
|
||||
end
|
||||
if buffer.len(f.rsrc) > 0 or o.double then
|
||||
table.insert(entries, { 2, f.rsrc })
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:u32be(if o.double then DOUBLE else SINGLE)
|
||||
w:u32be(0x20000)
|
||||
w:string(string.rep("\0", 16))
|
||||
w:u16be(#entries)
|
||||
local off = 26 + 12 * #entries
|
||||
for _, e in entries do
|
||||
w:u32be(e[1])
|
||||
w:u32be(off)
|
||||
w:u32be(buffer.len(e[2]))
|
||||
off += buffer.len(e[2])
|
||||
end
|
||||
for _, e in entries do
|
||||
w:bytes(e[2])
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty AppleSingle Archive: a:add(name, data); add "name.rsrc" for a resource fork
|
||||
function AppleSingle.new(): any
|
||||
local a = Archive.new("applesingle", encoder)
|
||||
a.meta.source = { format = "applesingle" }
|
||||
return a
|
||||
end
|
||||
|
||||
return AppleSingle
|
||||
@@ -0,0 +1,410 @@
|
||||
--!strict
|
||||
-- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/"
|
||||
-- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard
|
||||
-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not
|
||||
-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their
|
||||
-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and
|
||||
-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed
|
||||
-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and
|
||||
-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written
|
||||
-- library needs ranlib), writing .deb control data (any entries write as a plain ar).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Tar = require("@rosetta/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ar = {
|
||||
name = "ar",
|
||||
category = "archive",
|
||||
extensions = { "a", "ar", "deb", "lib" },
|
||||
mime = { "application/x-archive", "application/vnd.debian.binary-package" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu"
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "!<arch>\n"
|
||||
local HEADER = 60
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ar.sniff(r: Bytes.Reader): number
|
||||
if r:peek(8) == MAGIC then
|
||||
return if r:peek(13, 68) == "debian-binary" then 1 else 0.9
|
||||
end
|
||||
return if r:peek(8) == "!<thin>\n" then 0.5 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, at, n)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function decimal(s: string): number?
|
||||
local d = string.match(s, "^%s*(%d+)%s*$")
|
||||
return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil)
|
||||
end
|
||||
|
||||
-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names
|
||||
local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } }
|
||||
local out = {}
|
||||
local w = if wide then 8 else 4
|
||||
if n < w then
|
||||
return out
|
||||
end
|
||||
local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o))
|
||||
if count * w + w > n then
|
||||
return out
|
||||
end
|
||||
local s = o + w + count * w
|
||||
local e = o + n
|
||||
for i = 0, count - 1 do
|
||||
local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4)))
|
||||
local q = s
|
||||
while q < e and buffer.readu8(b, q) ~= 0 do
|
||||
q += 1
|
||||
end
|
||||
table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off })
|
||||
s = q + 1
|
||||
if s > e then
|
||||
break
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings
|
||||
local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } }
|
||||
local out = {}
|
||||
if n < 8 then
|
||||
return out
|
||||
end
|
||||
local rb = buffer.readu32(b, o)
|
||||
if rb % 8 ~= 0 or rb + 8 > n then
|
||||
return out
|
||||
end
|
||||
local strs = o + 8 + rb
|
||||
local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs)
|
||||
for i = 0, rb // 8 - 1 do
|
||||
local sx = buffer.readu32(b, o + 4 + i * 8)
|
||||
if sx < strn then
|
||||
local q = strs + sx
|
||||
while q < strs + strn and buffer.readu8(b, q) ~= 0 do
|
||||
q += 1
|
||||
end
|
||||
table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) })
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab)
|
||||
local function controlFields(s: string): { [string]: string }
|
||||
local out: { [string]: string } = {}
|
||||
local last: string? = nil
|
||||
for line in string.gmatch(s, "([^\n]*)\n?") do
|
||||
local c = string.sub(line, 1, 1)
|
||||
if (c == " " or c == "\t") and last then
|
||||
out[last] ..= "\n" .. string.sub(line, 2)
|
||||
else
|
||||
local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$")
|
||||
if k then
|
||||
out[k], last = v :: string, k
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- control.tar[.ext] -> the control file's fields, or nil
|
||||
local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }?
|
||||
local ext = string.match(name, "^control%.tar%.?(%w*)$")
|
||||
local raw: buffer?
|
||||
local opts: any = { maxBytes = maxBytes }
|
||||
if ext == "" then
|
||||
raw = buffer.create(n)
|
||||
buffer.copy(raw :: buffer, 0, b, o, n)
|
||||
elseif ext == "gz" then
|
||||
raw = Deflate.gunzip(b, o, n)
|
||||
elseif ext == "xz" then
|
||||
raw = Lzma.xz(b, o, n, opts)
|
||||
elseif ext == "lzma" then
|
||||
raw = Lzma.alone(b, o, n, opts)
|
||||
elseif ext == "zst" then
|
||||
raw = Zstd.decompress(b, o, n, opts)
|
||||
elseif ext == "bz2" then
|
||||
raw = Bzip2.decompress(b, o, n, opts)
|
||||
end
|
||||
if not raw then
|
||||
return nil
|
||||
end
|
||||
local list = Tar.read(raw)
|
||||
for _, e in list or {} do
|
||||
if (e.name == "./control" or e.name == "control") and e.type == "0" then
|
||||
return controlFields(buffer.readstring(raw, e.offset, e.size))
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Ar.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxEntries = o.maxEntries or 1e6
|
||||
local b, base, e = r.buf, r.base, r.limit
|
||||
if r:peek(8) == "!<thin>\n" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base)
|
||||
end
|
||||
if r:peek(8) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", base)
|
||||
end
|
||||
local a = Archive.new("ar", encode)
|
||||
local variant = "gnu"
|
||||
local longNames: string? = nil
|
||||
local symbols: { { name: string, offset: number } }? = nil
|
||||
local offsets: { [number]: string } = {} -- header offset (from the start) -> member name
|
||||
local count = 0
|
||||
local p = base + 8
|
||||
while p < e do
|
||||
local c = buffer.readu8(b, p)
|
||||
if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then
|
||||
break -- trailing padding (bsdtar fills its last 10240-byte block with zeros)
|
||||
end
|
||||
if p + HEADER > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "member header past the end", p)
|
||||
end
|
||||
if buffer.readstring(b, p + 58, 2) ~= "`\n" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad member header", p + 58)
|
||||
end
|
||||
local rawName = buffer.readstring(b, p, 16)
|
||||
local mtime = decimal(buffer.readstring(b, p + 16, 12))
|
||||
local uid = decimal(buffer.readstring(b, p + 28, 6))
|
||||
local gid = decimal(buffer.readstring(b, p + 34, 6))
|
||||
local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$")
|
||||
local size = decimal(buffer.readstring(b, p + 48, 10))
|
||||
if not (mtime and uid and gid and modeS and size) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad member header field", p)
|
||||
end
|
||||
local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number
|
||||
local data = p + HEADER
|
||||
if data + size > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "member data past the end", data)
|
||||
end
|
||||
local nextP = data + size + size % 2
|
||||
local name = string.gsub(rawName, " +$", "")
|
||||
local dataSize = size
|
||||
if string.sub(name, 1, 3) == "#1/" then
|
||||
local n = tonumber(string.sub(name, 4))
|
||||
if not n or n > size then
|
||||
return nil, Err.new(Err.CORRUPT, "bad BSD name length", p)
|
||||
end
|
||||
name = buffer.readstring(b, data, n)
|
||||
local z = string.find(name, "\0", 1, true)
|
||||
if z then
|
||||
name = string.sub(name, 1, z - 1)
|
||||
end
|
||||
data += n
|
||||
dataSize -= n
|
||||
variant = "bsd"
|
||||
elseif name == "//" then
|
||||
longNames = buffer.readstring(b, data, size)
|
||||
p = nextP
|
||||
continue
|
||||
elseif name == "/" or name == "/SYM64/" then
|
||||
symbols = sysvSymbols(b, data, size, name == "/SYM64/")
|
||||
p = nextP
|
||||
continue
|
||||
elseif string.match(name, "^/%d+$") then
|
||||
local off = tonumber(string.sub(name, 2)) :: number
|
||||
if not longNames or off >= #longNames then
|
||||
return nil, Err.new(Err.CORRUPT, "long name outside the name table", p)
|
||||
end
|
||||
local s = string.match(longNames, "^([^\n]*)", off + 1) :: string
|
||||
name = string.gsub(s, "/$", "")
|
||||
elseif string.sub(name, -1) == "/" then
|
||||
name = string.sub(name, 1, -2)
|
||||
end
|
||||
if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then
|
||||
symbols = bsdSymbols(b, data, dataSize)
|
||||
variant = "bsd"
|
||||
p = nextP
|
||||
continue
|
||||
end
|
||||
if name == "" then
|
||||
return nil, Err.new(Err.CORRUPT, "empty member name", p)
|
||||
end
|
||||
offsets[p - base] = name
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
|
||||
end
|
||||
Archive.put(a, {
|
||||
name = name,
|
||||
size = dataSize,
|
||||
dir = false,
|
||||
mtime = mtime,
|
||||
uid = uid,
|
||||
gid = gid,
|
||||
mode = bit32.band(mode, 0xFFF),
|
||||
armode = modeS,
|
||||
method = "store",
|
||||
load = if dataSize > 0 then lazy(b, data, dataSize) else nil,
|
||||
})
|
||||
p = nextP
|
||||
end
|
||||
if symbols then
|
||||
local out = {}
|
||||
for _, s in symbols do
|
||||
table.insert(out, { name = s.name, member = offsets[s.offset] })
|
||||
end
|
||||
a.meta.symbols = out
|
||||
end
|
||||
a.meta.source = { format = "ar", variant = variant }
|
||||
-- Debian packages
|
||||
local list = a._entries
|
||||
if list[1] and list[1].name == "debian-binary" then
|
||||
a.meta.source.variant = "deb"
|
||||
local v = a:read("debian-binary")
|
||||
a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil
|
||||
for _, ent in list do
|
||||
if string.match(ent.name, "^data%.tar") then
|
||||
a.meta.payload = ent.name
|
||||
elseif string.match(ent.name, "^control%.tar") then
|
||||
local cb = a:read(ent.name)
|
||||
if cb then
|
||||
a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function pad(s: string, n: number): string
|
||||
return s .. string.rep(" ", n - #s)
|
||||
end
|
||||
|
||||
local function header(name: string, e: any, size: number): string?
|
||||
local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0)
|
||||
local uid = if type(e.uid) == "number" then e.uid else 0
|
||||
local gid = if type(e.gid) == "number" then e.gid else 0
|
||||
local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode
|
||||
else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4)
|
||||
local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) }
|
||||
local w = { 12, 6, 6, 8, 10 }
|
||||
for i, s in f do
|
||||
if #s > w[i] or string.find(s, "[^%d]") then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n"
|
||||
end
|
||||
|
||||
function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
|
||||
local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu")
|
||||
if variant ~= "gnu" and variant ~= "bsd" then
|
||||
return nil, Err.new(Err.ARG, "variant must be gnu or bsd")
|
||||
end
|
||||
local files = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
if not e.dir and (e.type == nil or e.type == "0") then
|
||||
local data, err = it.read()
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(files, { e = e, data = data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(1024)
|
||||
w:string(MAGIC)
|
||||
-- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table
|
||||
local table_: { string } = {}
|
||||
local nameOf: { string } = {}
|
||||
local tsize = 0
|
||||
for i, f in files do
|
||||
local name: string = f.e.name
|
||||
if string.find(name, "\n") or name == "" then
|
||||
return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar")
|
||||
end
|
||||
if variant == "gnu" then
|
||||
if #name > 15 or string.find(name, "[/ ]") then
|
||||
nameOf[i] = "/" .. tsize
|
||||
table.insert(table_, name .. "/\n")
|
||||
tsize += #name + 2
|
||||
else
|
||||
nameOf[i] = name .. "/"
|
||||
end
|
||||
end
|
||||
end
|
||||
if #table_ > 0 then
|
||||
local t = table.concat(table_)
|
||||
if #t % 2 == 1 then
|
||||
t ..= "\n"
|
||||
end
|
||||
w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t)
|
||||
end
|
||||
for i, f in files do
|
||||
local name: string = f.e.name
|
||||
local size = buffer.len(f.data)
|
||||
local prefix = ""
|
||||
local field = nameOf[i]
|
||||
if variant == "bsd" then
|
||||
if #name > 16 or string.find(name, " ") then
|
||||
field = "#1/" .. #name
|
||||
prefix = name
|
||||
else
|
||||
field = name
|
||||
end
|
||||
end
|
||||
local h = header(field, f.e, size + #prefix)
|
||||
if not h then
|
||||
return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header")
|
||||
end
|
||||
w:string(h)
|
||||
w:string(prefix)
|
||||
w:bytes(f.data)
|
||||
if (size + #prefix) % 2 == 1 then
|
||||
w:string("\n")
|
||||
end
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" })
|
||||
function Ar.new(): any
|
||||
local a = Archive.new("ar", encode)
|
||||
a.meta.source = { format = "ar", variant = "gnu" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Ar
|
||||
@@ -0,0 +1,212 @@
|
||||
--!strict
|
||||
-- archive/arj: ARJ archives (Robert Jung) read into an Archive: the main header (archive name, comment, host OS,
|
||||
-- dates) and every local header (CRC-32 checked), files stored (method 0), compressed with methods 1..3 (the LHA-style
|
||||
-- static Huffman LZSS of codecs/compress/Lzh, "lh6" tables) or 4 (codecs/compress/Lzh "arj4"), directories (file type
|
||||
-- 3), DOS times (read as UTC), file modes, comments; each file's CRC-32 is verified when read (Err.CHECKSUM).
|
||||
-- Written from the ARJ technical information (arj's technote.txt). Not supported: garbled (encrypted) files,
|
||||
-- multi-volume archives (entries continued to / from another volume), chapters, writing (Err.UNSUPPORTED for those
|
||||
-- entries / calls).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
local Lzh = require("@rosetta/codecs/compress/Lzh")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Arj = {
|
||||
name = "arj",
|
||||
category = "archive",
|
||||
extensions = { "arj" },
|
||||
mime = { "application/x-arj" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Lzh", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, methods = { "store", "arj1", "arj2", "arj3", "arj4" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
|
||||
maxEntries: number?, -- default 65536
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local OS = { [0] = "msdos", "primos", "unix", "amiga", "macos", "os2", "appleiigs", "atarist", "next", "vaxvms", "win95", "win32" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Arj.sniff(r: Bytes.Reader): number
|
||||
local h = r:peek(4)
|
||||
if #h == 4 and string.byte(h, 1) == 0x60 and string.byte(h, 2) == 0xEA then
|
||||
local size = string.byte(h, 3) + string.byte(h, 4) * 256
|
||||
return if size > 0 and size <= 2600 then 0.9 else 0
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Header = { fields: Bytes.Reader, name: string, comment: string, size: number, at: number, next: number }
|
||||
|
||||
-- the header block at p: 60 EA, size, the basic header, its CRC-32, extended headers; nil at the end marker
|
||||
local function block(r: Bytes.Reader, p: number): (Header?, string?)
|
||||
local h = r:sub(p, 4)
|
||||
local id1, id2, size = h:u8(), h:u8(), h:u16le()
|
||||
if h.err then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
if id1 ~= 0x60 or id2 ~= 0xEA then
|
||||
return nil, "bad header id"
|
||||
end
|
||||
if size == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
if size > 2600 then
|
||||
return nil, "header too large"
|
||||
end
|
||||
if p + 4 + size + 4 > r:size() then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local crc = r:sub(p + 4 + size, 4):u32le()
|
||||
if Crc32.of(r.buf, r.base + p + 4, size) ~= crc then
|
||||
return nil, "checksum: header CRC-32 mismatch"
|
||||
end
|
||||
local f = r:sub(p + 4, size)
|
||||
local first = f:u8()
|
||||
if first < 30 or first > size then
|
||||
return nil, "bad first header size"
|
||||
end
|
||||
f:seek(first)
|
||||
local name = f:cstring()
|
||||
local comment = f:cstring()
|
||||
-- extended headers
|
||||
local q = p + 4 + size + 4
|
||||
local guard = 0
|
||||
while true do
|
||||
local e = r:sub(q, 2)
|
||||
local n = e:u16le()
|
||||
if e.err then
|
||||
return nil, "truncated extended header"
|
||||
end
|
||||
q += 2
|
||||
if n == 0 then
|
||||
break
|
||||
end
|
||||
q += n + 4
|
||||
guard += 1
|
||||
if guard > 256 or q > r:size() then
|
||||
return nil, "truncated extended header"
|
||||
end
|
||||
end
|
||||
f:seek(0)
|
||||
return { fields = f, name = name, comment = comment, size = size, at = p, next = q }, nil
|
||||
end
|
||||
|
||||
function Arj.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local maxEntries = o.maxEntries or 65536
|
||||
local main, err = block(r, 0)
|
||||
if not main then
|
||||
return nil, Err.from(err or "no main header", r.base)
|
||||
end
|
||||
local a = Archive.new("arj")
|
||||
local mf = main.fields
|
||||
mf:skip(1)
|
||||
local version, minVersion, host = mf:u8(), mf:u8(), mf:u8()
|
||||
local flags = mf:u8()
|
||||
mf:skip(3)
|
||||
local created = mf:u32le()
|
||||
a.meta.archive = main.name
|
||||
a.meta.comment = if main.comment ~= "" then main.comment else nil
|
||||
a.meta.os = OS[host]
|
||||
a.meta.created = Archive.fromDos(created)
|
||||
a.meta.source = { format = "arj", version = version, minVersion = minVersion, flags = flags }
|
||||
local p = main.next
|
||||
local count = 0
|
||||
while true do
|
||||
local h, herr = block(r, p)
|
||||
if herr then
|
||||
return nil, Err.from(herr, r.base + p)
|
||||
end
|
||||
if not h then
|
||||
break
|
||||
end
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
|
||||
end
|
||||
local f = h.fields
|
||||
f:skip(1)
|
||||
f:skip(2)
|
||||
local hostOs = f:u8()
|
||||
local fl = f:u8()
|
||||
local method = f:u8()
|
||||
local ftype = f:u8()
|
||||
f:skip(1)
|
||||
local stamp = f:u32le()
|
||||
local packed, size, crc = f:u32le(), f:u32le(), f:u32le()
|
||||
f:skip(2)
|
||||
local mode = f:u16le()
|
||||
local dataAt = h.next
|
||||
if dataAt + packed > r:size() then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. h.name .. " data past the end", r.base + dataAt)
|
||||
end
|
||||
local name = string.gsub(h.name, "\\", "/")
|
||||
local isDir = ftype == 3
|
||||
if isDir and string.sub(name, -1) ~= "/" then
|
||||
name ..= "/"
|
||||
end
|
||||
local e: any = {
|
||||
name = name,
|
||||
size = if isDir then 0 else size,
|
||||
compressedSize = packed,
|
||||
method = if method == 0 then "store" else "arj" .. method,
|
||||
mtime = Archive.fromDos(stamp),
|
||||
dir = isDir,
|
||||
mode = mode,
|
||||
os = OS[hostOs],
|
||||
comment = if h.comment ~= "" then h.comment else nil,
|
||||
fileType = ftype,
|
||||
}
|
||||
if ftype ~= 4 then -- 4: a volume label, not a file
|
||||
if not isDir and size > 0 then
|
||||
if size > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
|
||||
end
|
||||
local buf, at = r.buf, r.base + dataAt
|
||||
e.load = function(): (buffer?, Err.Err?)
|
||||
if bit32.band(fl, 0x01) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "garbled (encrypted) entries")
|
||||
end
|
||||
if bit32.band(fl, 0x0C) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "an entry split across volumes")
|
||||
end
|
||||
local out: buffer?, derr: string?
|
||||
if method == 0 then
|
||||
if packed < size then
|
||||
return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
|
||||
end
|
||||
out = buffer.create(size)
|
||||
buffer.copy(out :: buffer, 0, buf, at, size)
|
||||
elseif method >= 1 and method <= 3 then
|
||||
out, derr = Lzh.decode(buf, at, packed, size, "lh6")
|
||||
elseif method == 4 then
|
||||
out, derr = Lzh.decode(buf, at, packed, size, "arj4")
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "method " .. method)
|
||||
end
|
||||
if not out then
|
||||
return nil, Err.from(derr)
|
||||
end
|
||||
if Crc32.of(out) ~= crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch")
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
Archive.put(a, e)
|
||||
end
|
||||
p = dataAt + packed
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Arj
|
||||
@@ -0,0 +1,254 @@
|
||||
--!strict
|
||||
-- archive/binhex: BinHex 4.0 (.hqx) files: the 6-bit text encoding, the RLE90 run-length layer, the header (name,
|
||||
-- type / creator, Finder flags) and the data and resource forks, each with its CRC-16/XMODEM (verified:
|
||||
-- Err.CHECKSUM). Decodes to an Archive in the containers/MacFile convention (the data fork is the entry `name`, a
|
||||
-- resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags); writes any Archive's first Mac file
|
||||
-- (or a buffer) back, 64 characters a line, as BinHex 4.0 tools do. Written from the BinHex 4.0 definition (Peter
|
||||
-- Lewis' / RFC 1741 notes). Not supported: BinHex 2 / 3 / 5 (BinHex 5 is MacBinary inside BinHex 4: unwrap it with
|
||||
-- archive/macbinary), several files in one .hqx (only the first is read).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc16 = require("@rosetta/core/Crc16")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local MacFile = require("@rosetta/containers/MacFile")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Binhex = {
|
||||
name = "binhex",
|
||||
category = "archive",
|
||||
extensions = { "hqx", "hcx" },
|
||||
mime = { "application/mac-binhex40" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
|
||||
caps = { decode = true, encode = true, forks = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number? } -- default 2^30
|
||||
export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local ALPHABET = "!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr"
|
||||
local VALUE: { [number]: number } = {}
|
||||
for i = 1, 64 do
|
||||
VALUE[string.byte(ALPHABET, i)] = i - 1
|
||||
end
|
||||
local BANNER = "(This file must be converted with BinHex"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Binhex.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(2048)
|
||||
local at = string.find(head, BANNER, 1, true)
|
||||
if not at then
|
||||
return 0
|
||||
end
|
||||
return if at == 1 then 1 else 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the 6-bit characters between the colons -> bytes, then RLE90 expanded (nil, message on bad input)
|
||||
local function unhex(text: string, maxBytes: number): (buffer?, string?)
|
||||
local banner = string.find(text, BANNER, 1, true)
|
||||
if not banner then
|
||||
return nil, "no BinHex banner"
|
||||
end
|
||||
local start = string.find(text, ":", banner, true)
|
||||
if not start then
|
||||
return nil, "truncated: no data start"
|
||||
end
|
||||
local raw = Bytes.writer(#text)
|
||||
local acc, nbits = 0, 0
|
||||
local closed = false
|
||||
for i = start + 1, #text do
|
||||
local c = string.byte(text, i)
|
||||
if c == 58 then -- ":"
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
local v = VALUE[c]
|
||||
if v then
|
||||
acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFFFF), 6), v)
|
||||
nbits += 6
|
||||
if nbits >= 8 then
|
||||
nbits -= 8
|
||||
raw:u8(bit32.band(bit32.rshift(acc, nbits), 255))
|
||||
end
|
||||
elseif c ~= 10 and c ~= 13 and c ~= 9 and c ~= 32 then
|
||||
return nil, string.format("bad character 0x%02x", c)
|
||||
end
|
||||
end
|
||||
if not closed then
|
||||
return nil, "truncated: no closing colon"
|
||||
end
|
||||
local src = raw:finish()
|
||||
-- RLE90: 0x90 n repeats the previous byte n - 1 more times; 0x90 0 is a literal 0x90
|
||||
local out = Bytes.writer(buffer.len(src) * 2)
|
||||
local n = buffer.len(src)
|
||||
local prev = 0
|
||||
local i = 0
|
||||
while i < n do
|
||||
local c = buffer.readu8(src, i)
|
||||
if c == 0x90 and i + 1 < n then
|
||||
local count = buffer.readu8(src, i + 1)
|
||||
i += 2
|
||||
if count == 0 then
|
||||
out:u8(0x90)
|
||||
prev = 0x90
|
||||
else
|
||||
if out:tell() + count > maxBytes then
|
||||
return nil, "limit: data larger than maxBytes"
|
||||
end
|
||||
for _ = 2, count do
|
||||
out:u8(prev)
|
||||
end
|
||||
end
|
||||
else
|
||||
out:u8(c)
|
||||
prev = c
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return Binhex.encode(a, o)
|
||||
end
|
||||
|
||||
function Binhex.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local b, err = unhex(buffer.readstring(r.buf, r.base, r.limit - r.base), maxBytes)
|
||||
if not b then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
local h = Bytes.reader(b)
|
||||
local nameLen = h:u8()
|
||||
local name = h:string(nameLen)
|
||||
h:skip(1) -- version
|
||||
local ftype, creator = h:string(4), h:string(4)
|
||||
local flags = h:u16be()
|
||||
local dlen, rlen = h:u32be(), h:u32be()
|
||||
local hcrc = h:u16be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if Crc16.ccitt(b, 0, h:tell() - 2) ~= hcrc then
|
||||
return nil, Err.new(Err.CHECKSUM, "header CRC mismatch")
|
||||
end
|
||||
if dlen + rlen > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "forks larger than maxBytes")
|
||||
end
|
||||
local forks = {}
|
||||
for k, len in { dlen, rlen } do
|
||||
local at = h:tell()
|
||||
local fork = h:bytes(len)
|
||||
local crc = h:u16be()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if Crc16.ccitt(b, at, len) ~= crc then
|
||||
return nil, Err.new(Err.CHECKSUM, (if k == 1 then "data" else "resource") .. " fork CRC mismatch")
|
||||
end
|
||||
forks[k] = fork
|
||||
end
|
||||
local a = Archive.new("binhex", encoder)
|
||||
MacFile.put(a, { name = MacFile.name(name), data = forks[1], rsrc = forks[2], type = ftype, creator = creator, flags = flags })
|
||||
a.meta.stream = rlen == 0
|
||||
a.meta.source = { format = "binhex" }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Binhex.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local files, err = MacFile.collect(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
local f = files[1]
|
||||
if not f then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local name = MacFile.roman(f.name)
|
||||
if #name < 1 or #name > 63 then
|
||||
return nil, Err.new(Err.ARG, "the name must be 1..63 bytes")
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:u8(#name)
|
||||
w:string(name)
|
||||
w:u8(0)
|
||||
w:string(f.type)
|
||||
w:string(f.creator)
|
||||
w:u16be(f.flags)
|
||||
w:u32be(buffer.len(f.data))
|
||||
w:u32be(buffer.len(f.rsrc))
|
||||
local hdr = w:finish()
|
||||
local body = Bytes.writer()
|
||||
for _, part in { hdr, f.data, f.rsrc } do
|
||||
body:bytes(part)
|
||||
body:u16be(Crc16.ccitt(part, 0, buffer.len(part)))
|
||||
end
|
||||
local src = body:finish()
|
||||
-- RLE90
|
||||
local rle = Bytes.writer(buffer.len(src) + 16)
|
||||
local n = buffer.len(src)
|
||||
local i = 0
|
||||
while i < n do
|
||||
local c = buffer.readu8(src, i)
|
||||
local run = 1
|
||||
while i + run < n and run < 255 and buffer.readu8(src, i + run) == c do
|
||||
run += 1
|
||||
end
|
||||
if c == 0x90 then
|
||||
rle:u8(0x90)
|
||||
rle:u8(0)
|
||||
run = 1
|
||||
else
|
||||
rle:u8(c)
|
||||
if run >= 3 then
|
||||
rle:u8(0x90)
|
||||
rle:u8(run)
|
||||
else
|
||||
run = 1
|
||||
end
|
||||
end
|
||||
i += run
|
||||
end
|
||||
local bytes = rle:finish()
|
||||
-- 6-bit characters, 64 to a line (the first line includes the colon)
|
||||
local chars = { ":" }
|
||||
local col = 1
|
||||
local acc, nbits = 0, 0
|
||||
local function put(v: number)
|
||||
table.insert(chars, string.sub(ALPHABET, v + 1, v + 1))
|
||||
col += 1
|
||||
if col == 64 then
|
||||
table.insert(chars, "\n")
|
||||
col = 0
|
||||
end
|
||||
end
|
||||
for k = 0, buffer.len(bytes) - 1 do
|
||||
acc = bit32.bor(bit32.lshift(bit32.band(acc, 0xFF), 8), buffer.readu8(bytes, k))
|
||||
nbits += 8
|
||||
while nbits >= 6 do
|
||||
nbits -= 6
|
||||
put(bit32.band(bit32.rshift(acc, nbits), 63))
|
||||
end
|
||||
end
|
||||
if nbits > 0 then
|
||||
put(bit32.band(bit32.lshift(acc, 6 - nbits), 63))
|
||||
end
|
||||
table.insert(chars, ":\n")
|
||||
return buffer.fromstring("(This file must be converted with BinHex 4.0)\n" .. table.concat(chars)), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty BinHex Archive: a:add(name, data, { macType, macCreator }); add "name.rsrc" for a resource fork
|
||||
function Binhex.new(): any
|
||||
local a = Archive.new("binhex", encoder)
|
||||
a.meta.source = { format = "binhex" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Binhex
|
||||
@@ -0,0 +1,76 @@
|
||||
--!strict
|
||||
-- archive/br: a Brotli (RFC 7932) stream as a single-entry archive (meta.stream: the api unwraps a .tar.br to the tar
|
||||
-- inside). Decoding through codecs/compress/Brotli. The entry is named after opts.name without ".br" (else "data").
|
||||
-- Supports: read (eager decompression). Not supported: write (no Brotli compressor). Brotli has no magic number:
|
||||
-- sniff accepts only data that decodes cleanly (the whole stream for small files, a 64 KB prefix for big ones), at a
|
||||
-- low confidence, so the extension decides between candidates.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Brotli = require("@rosetta/codecs/compress/Brotli")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Br = {
|
||||
name = "br",
|
||||
category = "archive",
|
||||
extensions = { "br" },
|
||||
mime = { "application/x-brotli" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Brotli", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, stream = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
name: string?, -- the file name (the api passes it): the entry is named after it
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local SNIFF_WHOLE = 262144 -- streams up to this size are decoded whole by sniff
|
||||
local SNIFF_PREFIX = 65536
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Br.sniff(r: Bytes.Reader): number
|
||||
local n = r:remaining()
|
||||
if n == 0 then
|
||||
return 0
|
||||
end
|
||||
if n <= SNIFF_WHOLE then
|
||||
local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = 2 ^ 26 })
|
||||
if out and consumed == r.limit then
|
||||
return if buffer.len(out) > 0 then 0.3 else 0.05
|
||||
end
|
||||
return 0
|
||||
end
|
||||
local _, err = Brotli.decompress(r.buf, r.pos, SNIFF_PREFIX, { maxBytes = 2 ^ 22 })
|
||||
if err and (err.code == Err.TRUNCATED or err.code == Err.LIMIT) then
|
||||
return 0.05
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Br.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local n = r:remaining()
|
||||
local out, consumed = Brotli.decompress(r.buf, r.pos, n, { maxBytes = opts and opts.maxBytes })
|
||||
if not out then
|
||||
local e: Err.Err = consumed
|
||||
e.message = string.gsub(e.message, "^brotli: ", "")
|
||||
return nil, e
|
||||
end
|
||||
local a = Archive.new("br")
|
||||
a.meta.stream = true
|
||||
a.meta.compressedSize = consumed - r.pos
|
||||
Archive.put(a, {
|
||||
name = Archive.streamName(opts, Br.extensions),
|
||||
size = buffer.len(out),
|
||||
compressedSize = consumed - r.pos,
|
||||
method = "brotli",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Br
|
||||
@@ -0,0 +1,64 @@
|
||||
--!strict
|
||||
-- archive/bz2: a .bz2 file as a single-stream archive: one entry, the decompressed data (codecs/compress/Bzip2; concatenated
|
||||
-- streams are joined, as bzip2 -d does). The entry is named after the file without its .bz2 (".tbz2" -> ".tar"),
|
||||
-- else "data"; the api unwraps a .tar.bz2 into the tar inside (meta.stream). New in rosetta. Not supported:
|
||||
-- writing (codecs/compress/Bzip2 has no compressor), randomised blocks (bzip2 0.9.0 and older).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Bz2 = {
|
||||
name = "bz2",
|
||||
category = "archive",
|
||||
extensions = { "bz2", "tbz2", "tbz" },
|
||||
mime = { "application/x-bzip2" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "codecs/compress/Bzip2" },
|
||||
caps = { decode = true, encode = false, stream = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse larger output (default 2^30)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Bz2.sniff(r: Bytes.Reader): number
|
||||
local h = r:peek(10)
|
||||
if #h < 10 or string.sub(h, 1, 3) ~= "BZh" then
|
||||
return 0
|
||||
end
|
||||
local lv = string.byte(h, 4)
|
||||
if lv < 0x31 or lv > 0x39 then
|
||||
return 0
|
||||
end
|
||||
local magic = string.sub(h, 5, 10)
|
||||
if magic == "\x31\x41\x59\x26\x53\x59" or magic == "\x17\x72\x45\x38\x50\x90" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Bz2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local out, consumed = Bzip2.decompress(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes })
|
||||
if not out then
|
||||
return nil, consumed
|
||||
end
|
||||
local a = Archive.new("bz2")
|
||||
a.meta.stream = true
|
||||
Archive.put(a, {
|
||||
name = Archive.streamName(opts, Bz2.extensions),
|
||||
size = buffer.len(out),
|
||||
compressedSize = consumed - r.base,
|
||||
method = "bzip2",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Bz2
|
||||
@@ -0,0 +1,42 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3
|
||||
-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format
|
||||
-- description ([MS-CAB] 2.4, CFDATA.csum).
|
||||
|
||||
local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len
|
||||
local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift
|
||||
|
||||
local Sum = {}
|
||||
|
||||
-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum)
|
||||
function Sum.of(buf: buffer, off: number, len: number, seed: number): number
|
||||
if off < 0 or len <= 0 or off + len > blen(buf) then
|
||||
return seed
|
||||
end
|
||||
local s = seed
|
||||
local p = off
|
||||
local stop = off + len - len % 4
|
||||
while p < stop do
|
||||
s = bxor(s, readu32(buf, p))
|
||||
p += 4
|
||||
end
|
||||
local rem = len % 4
|
||||
local tail = 0
|
||||
if rem == 3 then
|
||||
tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2))
|
||||
elseif rem == 2 then
|
||||
tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1))
|
||||
elseif rem == 1 then
|
||||
tail = readu8(buf, p)
|
||||
end
|
||||
return bxor(s, tail)
|
||||
end
|
||||
|
||||
-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData)
|
||||
function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number
|
||||
return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536)
|
||||
end
|
||||
|
||||
return Sum
|
||||
@@ -0,0 +1,427 @@
|
||||
--!strict
|
||||
-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and
|
||||
-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose
|
||||
-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum
|
||||
-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local
|
||||
-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM)
|
||||
-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same
|
||||
-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the
|
||||
-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a
|
||||
-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one),
|
||||
-- signed / self-extracting stubs before the header.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Lzx = require("@rosetta/codecs/compress/Lzx")
|
||||
local Quantum = require("@rosetta/codecs/compress/Quantum")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Sum = require("@rosetta/archive/cab/Sum")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Cab = {
|
||||
name = "cab",
|
||||
category = "archive",
|
||||
extensions = { "cab" },
|
||||
mime = { "application/vnd.ms-cab-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzx", "codecs/compress/Quantum", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "mszip", "lzx", "quantum" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30)
|
||||
maxEntries: number?, -- default 65535
|
||||
verify: boolean?, -- check the data block checksums (default true)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
compression: ("mszip" | "none")?, -- default "mszip"
|
||||
level: number?, -- deflate level 0..9 (default 6)
|
||||
setId: number?, -- the cabinet set id (default 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004
|
||||
local ATTR_UTF8 = 0x80
|
||||
local METHOD = { [0] = "store", "mszip", "quantum", "lzx" }
|
||||
local BLOCK = 32768
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Cab.sniff(r: Bytes.Reader): number
|
||||
if r:peek(8) == "MSCF\0\0\0\0" then
|
||||
return 1
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
type Folder = {
|
||||
dataAt: number, -- offset of the first CFDATA (relative to the reader)
|
||||
blocks: number,
|
||||
type: number, -- typeCompress
|
||||
index: number,
|
||||
}
|
||||
type Block = { at: number, len: number, size: number }
|
||||
|
||||
-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next
|
||||
-- cabinet (a block with cbUncomp 0)
|
||||
local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?)
|
||||
local list: { Block } = {}
|
||||
local p = f.dataAt
|
||||
local total = 0
|
||||
for i = 1, f.blocks do
|
||||
local h = r:sub(p, 8)
|
||||
local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le()
|
||||
if h.err then
|
||||
return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p)
|
||||
end
|
||||
local at = p + 8 + dataReserve
|
||||
if at + cbData > r:size() then
|
||||
return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p)
|
||||
end
|
||||
if cbUncomp == 0 then
|
||||
return list, total, true
|
||||
end
|
||||
if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then
|
||||
return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p)
|
||||
end
|
||||
total += cbUncomp
|
||||
if total > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "folder larger than maxBytes")
|
||||
end
|
||||
table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp })
|
||||
p = at + cbData
|
||||
end
|
||||
return list, total, false
|
||||
end
|
||||
|
||||
-- the decompressed data of a folder's blocks
|
||||
local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?)
|
||||
local method = bit32.band(typ, 15)
|
||||
local out = buffer.create(total)
|
||||
if method == 0 then
|
||||
local o = 0
|
||||
for _, b in list do
|
||||
if b.len ~= b.size then
|
||||
return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at)
|
||||
end
|
||||
buffer.copy(out, o, buf, b.at, b.len)
|
||||
o += b.len
|
||||
end
|
||||
return out, nil
|
||||
elseif method == 1 then
|
||||
local spans: { { offset: number, length: number, size: number } } = {}
|
||||
for _, b in list do
|
||||
table.insert(spans, { offset = b.at, length = b.len, size = b.size })
|
||||
end
|
||||
return Deflate.mszip(buf, spans)
|
||||
elseif method == 3 then
|
||||
local bits = bit32.band(bit32.rshift(typ, 8), 31)
|
||||
local n = 0
|
||||
for _, b in list do
|
||||
n += b.len
|
||||
end
|
||||
local src = buffer.create(n)
|
||||
local o = 0
|
||||
for _, b in list do
|
||||
buffer.copy(src, o, buf, b.at, b.len)
|
||||
o += b.len
|
||||
end
|
||||
local res, err = Lzx.decode(src, 0, n, total, bits)
|
||||
if not res then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
return res, nil
|
||||
elseif method == 2 then
|
||||
local res, err = Quantum.decode(buf, list, total, bit32.band(bit32.rshift(typ, 8), 31))
|
||||
if not res then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
return res, nil
|
||||
end
|
||||
return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method)
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Cab.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local maxEntries = o.maxEntries or 65535
|
||||
local verify = o.verify ~= false
|
||||
if not r:match("MSCF") then
|
||||
return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base)
|
||||
end
|
||||
r:skip(4)
|
||||
local cbCabinet = r:u32le()
|
||||
r:skip(4)
|
||||
local coffFiles = r:u32le()
|
||||
r:skip(4)
|
||||
local minor, major = r:u8(), r:u8()
|
||||
local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le()
|
||||
local setId, iCabinet = r:u16le(), r:u16le()
|
||||
local headerReserve, folderReserve, dataReserve = 0, 0, 0
|
||||
if bit32.band(flags, FLAG_RESERVE) ~= 0 then
|
||||
headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8()
|
||||
end
|
||||
local a = Archive.new("cab", encode)
|
||||
local meta: any = a.meta
|
||||
if headerReserve > 0 then
|
||||
meta.reserve = r:bytes(headerReserve)
|
||||
end
|
||||
if bit32.band(flags, FLAG_PREV) ~= 0 then
|
||||
meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256)
|
||||
end
|
||||
if bit32.band(flags, FLAG_NEXT) ~= 0 then
|
||||
meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256)
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if major ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor)
|
||||
end
|
||||
meta.setId, meta.cabinet = setId, iCabinet
|
||||
meta.source = {
|
||||
format = "cab",
|
||||
version = major .. "." .. minor,
|
||||
size = cbCabinet,
|
||||
flags = flags,
|
||||
reserve = { header = headerReserve, folder = folderReserve, data = dataReserve },
|
||||
}
|
||||
-- folders
|
||||
local folders: { Folder } = {}
|
||||
local methods = {}
|
||||
for i = 1, cFolders do
|
||||
local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le()
|
||||
r:skip(folderReserve)
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i }
|
||||
local m = METHOD[bit32.band(typ, 15)]
|
||||
methods[i] = {
|
||||
method = m or ("type " .. bit32.band(typ, 15)),
|
||||
window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil,
|
||||
level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil,
|
||||
blocks = nblocks,
|
||||
}
|
||||
end
|
||||
meta.folders = methods
|
||||
if cFiles == 0 or cFolders == 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "a cabinet without files or folders")
|
||||
end
|
||||
if cFiles > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than maxEntries files")
|
||||
end
|
||||
-- the folder cache: the last decompressed folder
|
||||
local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false
|
||||
local function folderData(f: Folder): (buffer?, Err.Err?, boolean?)
|
||||
if cachedIndex == f.index then
|
||||
return cachedData, nil, cachedRuns
|
||||
end
|
||||
local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes)
|
||||
if not list then
|
||||
return nil, total, false
|
||||
end
|
||||
local data, err = inflateFolder(r.buf, list, total, f.type)
|
||||
if not data then
|
||||
return nil, err, false
|
||||
end
|
||||
cachedIndex, cachedData, cachedRuns = f.index, data, runs == true
|
||||
return data, nil, runs
|
||||
end
|
||||
-- files
|
||||
local fr = r:sub(coffFiles)
|
||||
for _ = 1, cFiles do
|
||||
local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le()
|
||||
local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le()
|
||||
local raw = fr:cstring(65536)
|
||||
if fr.err then
|
||||
return nil, fr.err
|
||||
end
|
||||
local name = string.gsub(raw, "\\", "/")
|
||||
local spanned: string? = nil
|
||||
local folder: Folder?
|
||||
if iFolder == 0xFFFD or iFolder == 0xFFFF then
|
||||
spanned = "a file continued from the previous cabinet"
|
||||
folder = folders[1]
|
||||
elseif iFolder == 0xFFFE then
|
||||
spanned = "a file continued in the next cabinet"
|
||||
folder = folders[#folders]
|
||||
else
|
||||
folder = folders[iFolder + 1]
|
||||
if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then
|
||||
spanned = "a folder continued from the previous cabinet"
|
||||
end
|
||||
end
|
||||
if not folder then
|
||||
return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder)
|
||||
end
|
||||
local fo = folder :: Folder
|
||||
if size > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
|
||||
end
|
||||
local e: any = {
|
||||
name = name,
|
||||
size = size,
|
||||
method = METHOD[bit32.band(fo.type, 15)] or "unknown",
|
||||
mtime = Archive.fromDos(date * 65536 + time),
|
||||
dir = false,
|
||||
attributes = bit32.band(attribs, 0xFF7F),
|
||||
utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0,
|
||||
folder = fo.index,
|
||||
offset = offset,
|
||||
readonly = bit32.band(attribs, 0x01) ~= 0,
|
||||
executable = bit32.band(attribs, 0x40) ~= 0,
|
||||
}
|
||||
if spanned then
|
||||
e.spanned = true
|
||||
end
|
||||
if size > 0 or spanned then
|
||||
e.load = function(): (buffer?, Err.Err?)
|
||||
if spanned then
|
||||
return nil, Err.new(Err.UNSUPPORTED, spanned :: string)
|
||||
end
|
||||
local data, err, runs = folderData(fo)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
if offset + size > buffer.len(data) then
|
||||
if runs then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet")
|
||||
end
|
||||
return nil, Err.new(Err.CORRUPT, "file past the end of its folder")
|
||||
end
|
||||
local out = buffer.create(size)
|
||||
buffer.copy(out, 0, data, offset, size)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
Archive.put(a, e)
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names)
|
||||
function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local compression = o.compression or "mszip"
|
||||
if compression ~= "mszip" and compression ~= "none" then
|
||||
return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"")
|
||||
end
|
||||
local level = o.level or 6
|
||||
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "level must be 0..9")
|
||||
end
|
||||
local files, ferr = Archive.files(archive)
|
||||
if not files then
|
||||
return nil, ferr
|
||||
end
|
||||
if #files == 0 then
|
||||
return nil, Err.new(Err.ARG, "a cabinet needs at least one file")
|
||||
end
|
||||
if #files > 65535 then
|
||||
return nil, Err.new(Err.ARG, "more than 65535 files")
|
||||
end
|
||||
local total = 0
|
||||
for _, f in files do
|
||||
total += buffer.len(f.data)
|
||||
end
|
||||
if total > 0x7FFF8000 then
|
||||
return nil, Err.new(Err.ARG, "more than 2 GB of data")
|
||||
end
|
||||
-- the folder data, in 32 KB blocks
|
||||
local folder = buffer.create(total)
|
||||
local p = 0
|
||||
for _, f in files do
|
||||
buffer.copy(folder, p, f.data, 0, buffer.len(f.data))
|
||||
p += buffer.len(f.data)
|
||||
end
|
||||
local data = Bytes.writer(total // 2 + 64)
|
||||
local nblocks = 0
|
||||
local s = 0
|
||||
while s < total do
|
||||
local n = math.min(BLOCK, total - s)
|
||||
local chunk = buffer.create(n)
|
||||
buffer.copy(chunk, 0, folder, s, n)
|
||||
local payload: buffer
|
||||
if compression == "mszip" then
|
||||
local z, zerr = Deflate.compress(chunk, { level = level })
|
||||
if not z then
|
||||
return nil, zerr
|
||||
end
|
||||
payload = buffer.create(buffer.len(z) + 2)
|
||||
buffer.writeu16(payload, 0, 0x4B43)
|
||||
buffer.copy(payload, 2, z, 0, buffer.len(z))
|
||||
else
|
||||
payload = chunk
|
||||
end
|
||||
local len = buffer.len(payload)
|
||||
data:u32le(Sum.block(payload, 0, len, n))
|
||||
data:u16le(len)
|
||||
data:u16le(n)
|
||||
data:bytes(payload)
|
||||
nblocks += 1
|
||||
s += n
|
||||
end
|
||||
local blob = data:finish()
|
||||
-- names and the file table
|
||||
local table_ = Bytes.writer(64 + #files * 32)
|
||||
local offset = 0
|
||||
for _, f in files do
|
||||
local e: any = f.entry
|
||||
local name = string.gsub(f.name, "/", "\\")
|
||||
local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20
|
||||
if string.find(name, "[\128-\255]") then
|
||||
attribs = bit32.bor(attribs, ATTR_UTF8)
|
||||
end
|
||||
local stamp = Archive.toDos(e.mtime)
|
||||
table_:u32le(buffer.len(f.data))
|
||||
table_:u32le(offset)
|
||||
table_:u16le(0)
|
||||
table_:u16le(stamp // 65536)
|
||||
table_:u16le(stamp % 65536)
|
||||
table_:u16le(attribs)
|
||||
table_:cstring(name)
|
||||
offset += buffer.len(f.data)
|
||||
end
|
||||
local fileTable = table_:finish()
|
||||
local nfolders = 1
|
||||
local coffFiles = 36 + 8 * nfolders
|
||||
local dataAt = coffFiles + buffer.len(fileTable)
|
||||
local size = dataAt + buffer.len(blob)
|
||||
local w = Bytes.writer(size)
|
||||
w:string("MSCF")
|
||||
w:u32le(0)
|
||||
w:u32le(size)
|
||||
w:u32le(0)
|
||||
w:u32le(coffFiles)
|
||||
w:u32le(0)
|
||||
w:u8(3)
|
||||
w:u8(1)
|
||||
w:u16le(nfolders)
|
||||
w:u16le(#files)
|
||||
w:u16le(0)
|
||||
w:u16le(o.setId or 0)
|
||||
w:u16le(0)
|
||||
w:u32le(dataAt)
|
||||
w:u16le(nblocks)
|
||||
w:u16le(if compression == "mszip" then 1 else 0)
|
||||
w:bytes(fileTable)
|
||||
w:bytes(blob)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" })
|
||||
function Cab.new(): any
|
||||
local a = Archive.new("cab", encode)
|
||||
a.meta.source = { format = "cab" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Cab
|
||||
@@ -0,0 +1,172 @@
|
||||
--!strict
|
||||
-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the
|
||||
-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc
|
||||
-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters),
|
||||
-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor,
|
||||
-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1")
|
||||
-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Cpio = require("@rosetta/containers/Cpio")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local CpioFormat = {
|
||||
name = "cpio",
|
||||
category = "archive",
|
||||
extensions = { "cpio" },
|
||||
mime = { "application/x-cpio" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
verify: boolean?, -- crc archives: check the data sums (default true)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc"
|
||||
format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default
|
||||
block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function CpioFormat.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(6)
|
||||
if m == "070701" or m == "070702" or m == "070707" then
|
||||
return 1
|
||||
end
|
||||
local b2 = r:peek(2)
|
||||
if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, at, n)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return CpioFormat.encode(archive, opts)
|
||||
end
|
||||
|
||||
function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts)
|
||||
if not list then
|
||||
return nil, info
|
||||
end
|
||||
local a = Archive.new("cpio", encode)
|
||||
for _, e in list do
|
||||
local data = e.type == "0" and e.size > 0
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = if data then e.size else 0,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
mode = bit32.band(e.mode, 0xFFF),
|
||||
uid = e.uid,
|
||||
gid = e.gid,
|
||||
type = e.type,
|
||||
link = e.link,
|
||||
hardlink = e.hardlink,
|
||||
nlink = e.nlink,
|
||||
ino = e.ino,
|
||||
devmajor = e.devmajor,
|
||||
devminor = e.devminor,
|
||||
rdevmajor = e.rdevmajor,
|
||||
rdevminor = e.rdevminor,
|
||||
method = "store",
|
||||
load = if data then lazy(r.buf, e.offset, e.size) else nil,
|
||||
})
|
||||
end
|
||||
a.meta.source = { format = "cpio", variant = info.format }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function num(v: any): number?
|
||||
return if type(v) == "number" then v else nil
|
||||
end
|
||||
|
||||
function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local index: { [string]: number } = {}
|
||||
for i, it in items do
|
||||
index[it.entry.name] = index[it.entry.name] or i
|
||||
end
|
||||
-- tar hard links ("1"): the same inode as their target, which counts the links
|
||||
local links: { [number]: number } = {}
|
||||
local target: { [number]: number } = {}
|
||||
for i, it in items do
|
||||
local e: any = it.entry
|
||||
if e.type == "1" and type(e.link) == "string" and index[e.link] then
|
||||
local t = index[e.link]
|
||||
target[i] = t
|
||||
links[t] = (links[t] or 1) + 1
|
||||
end
|
||||
end
|
||||
local list: { Cpio.WriteEntry } = {}
|
||||
for i, it in items do
|
||||
local e: any = it.entry
|
||||
local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0"
|
||||
local src = target[i]
|
||||
local ino, nlink = num(e.ino), num(e.nlink)
|
||||
if src then
|
||||
typ, ino, nlink = "0", src, links[src]
|
||||
elseif links[i] then
|
||||
ino, nlink = i, links[i]
|
||||
end
|
||||
local data: buffer? = nil
|
||||
if typ == "0" then
|
||||
local b, err = (items[src or i] :: any).read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local mode = num(e.mode)
|
||||
table.insert(list, {
|
||||
name = e.name,
|
||||
data = data,
|
||||
type = typ,
|
||||
link = if type(e.link) == "string" and typ == "2" then e.link else nil,
|
||||
mode = if mode then bit32.band(mode, 0xFFF) else nil,
|
||||
uid = num(e.uid),
|
||||
gid = num(e.gid),
|
||||
nlink = nlink,
|
||||
mtime = num(e.mtime),
|
||||
ino = ino,
|
||||
devmajor = num(e.devmajor),
|
||||
devminor = num(e.devminor),
|
||||
rdevmajor = num(e.rdevmajor),
|
||||
rdevminor = num(e.rdevminor),
|
||||
})
|
||||
end
|
||||
-- opts.format may also be the api's format name ("cpio"): the variant default then
|
||||
local o: any = opts or {}
|
||||
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
|
||||
local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc"
|
||||
local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own)
|
||||
return Cpio.write(list, { format = variant, block = o.block })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write()
|
||||
function CpioFormat.new(): any
|
||||
local a = Archive.new("cpio", encode)
|
||||
a.meta.source = { format = "cpio" }
|
||||
return a
|
||||
end
|
||||
|
||||
return CpioFormat
|
||||
@@ -0,0 +1,424 @@
|
||||
--!strict
|
||||
-- archive/d64: Commodore disk images as an Archive: D64 (1541: 35 / 40 / 42 tracks, with or without the error-info
|
||||
-- block), D71 (1571: 70 tracks, double sided) and D81 (1581: 80 tracks of 40 sectors). The BAM / header (disk name and
|
||||
-- id in meta.disk / meta.id), the directory chain, and every file's sector chain; PRG / SEQ / USR / REL files are
|
||||
-- entries (entry.type, entry.blocks, entry.locked, entry.closed; REL files read their data chain, the side sectors are
|
||||
-- skipped), deleted entries are skipped, unclosed ("splat") files are flagged closed = false. Names are PETSCII
|
||||
-- translated as VICE's c1541 does (0x41..0x5A -> a..z, 0xC1..0xDA and 0x61..0x7A -> A..Z, other bytes to U+E0xx so the
|
||||
-- name survives a round trip); entry.rawName keeps the 16 bytes. Writes D64 (35 tracks) / D71 / D81 images from any
|
||||
-- Archive (files as PRG, or entry.type), allocating sectors near the directory track with interleave 10 as CBM DOS
|
||||
-- does (not the same sectors as a real drive). Written from the 1541 / 1571 / 1581 DOS documentation (Peter Schepers'
|
||||
-- disk format notes). Not supported: GEOS VLIR files (read as their first chain), 1581 partitions (CBM type) contents.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local D64 = {
|
||||
name = "d64",
|
||||
category = "archive",
|
||||
extensions = { "d64", "d71", "d81" },
|
||||
mime = { "application/x-d64" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, variants = { "d64", "d71", "d81" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 4096
|
||||
export type EncodeOptions = {
|
||||
variant: ("d64" | "d71" | "d81")?, -- default: the variant read, else "d64"
|
||||
disk: string?, -- disk name (default "rosetta" / the name read)
|
||||
id: string?, -- two-character disk id (default "fl")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local TYPES = { [0] = "del", "seq", "prg", "usr", "rel", "cbm", "dir" }
|
||||
local TYPE_CODE: { [string]: number } = { del = 0, seq = 1, prg = 2, usr = 3, rel = 4 }
|
||||
|
||||
type Geometry = { kind: string, tracks: number, offsets: { number }, spt: { number }, dirTrack: number, total: number }
|
||||
|
||||
local function geometry(kind: string, tracks: number): Geometry
|
||||
local offsets, spt = {}, {}
|
||||
local o = 0
|
||||
for t = 1, tracks do
|
||||
local n
|
||||
if kind == "d81" then
|
||||
n = 40
|
||||
else
|
||||
local s = if kind == "d71" and t > 35 then t - 35 else t
|
||||
n = if s <= 17 then 21 elseif s <= 24 then 19 elseif s <= 30 then 18 else 17
|
||||
end
|
||||
offsets[t], spt[t] = o, n
|
||||
o += n * 256
|
||||
end
|
||||
return { kind = kind, tracks = tracks, offsets = offsets, spt = spt, dirTrack = if kind == "d81" then 40 else 18, total = o }
|
||||
end
|
||||
|
||||
-- image sizes -> geometry (sizes with the error-info block appended too)
|
||||
local function detect(len: number): Geometry?
|
||||
for _, g in { { "d64", 35 }, { "d64", 40 }, { "d64", 42 }, { "d71", 70 }, { "d81", 80 } } :: { { any } } do
|
||||
local geo = geometry(g[1] :: string, g[2] :: number)
|
||||
local sectors = geo.total // 256
|
||||
if len == geo.total or (g[1] ~= "d81" and len == geo.total + sectors) then
|
||||
return geo
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function D64.sniff(r: Bytes.Reader): number
|
||||
local geo = detect(r:size())
|
||||
if not geo then
|
||||
return 0
|
||||
end
|
||||
-- the BAM / header sector: dir track link and DOS version byte
|
||||
local h = r:sub(geo.offsets[geo.dirTrack], 256)
|
||||
local t, s, v = h:u8(), h:u8(), h:u8()
|
||||
if geo.kind == "d81" then
|
||||
return if t == 40 and s == 3 and v == 0x44 then 0.9 else 0.3
|
||||
end
|
||||
return if t == 18 and s == 1 and (v == 0x41 or v == 0) then 0.9 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function petscii(raw: string): string
|
||||
local out = table.create(#raw)
|
||||
for i = 1, #raw do
|
||||
local c = string.byte(raw, i)
|
||||
if c >= 0x41 and c <= 0x5A then
|
||||
out[i] = string.char(c + 32)
|
||||
elseif c >= 0xC1 and c <= 0xDA then
|
||||
out[i] = string.char(c - 0x80)
|
||||
elseif c >= 0x61 and c <= 0x7A then
|
||||
out[i] = string.char(c - 32)
|
||||
elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then
|
||||
out[i] = string.char(c)
|
||||
else
|
||||
out[i] = utf8.char(0xE000 + c)
|
||||
end
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
local function toPetscii(name: string): string
|
||||
local out = {}
|
||||
if not utf8.len(name) then
|
||||
return string.sub(name, 1, 16)
|
||||
end
|
||||
for _, c in utf8.codes(name) do
|
||||
local b
|
||||
if c >= 0x61 and c <= 0x7A then
|
||||
b = c - 32
|
||||
elseif c >= 0x41 and c <= 0x5A then
|
||||
b = c + 0x80
|
||||
elseif c >= 0xE000 and c <= 0xE0FF then
|
||||
b = c - 0xE000
|
||||
elseif c >= 0x20 and c <= 0x40 and c ~= 0x2F then
|
||||
b = c
|
||||
else
|
||||
b = 0x3F
|
||||
end
|
||||
table.insert(out, string.char(b))
|
||||
end
|
||||
return string.sub(table.concat(out), 1, 16)
|
||||
end
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return D64.encode(a, o)
|
||||
end
|
||||
|
||||
-- the bytes of a sector chain starting at (t, s); nil, message when it leaves the disk or loops
|
||||
local function chain(b: buffer, base: number, geo: Geometry, t: number, s: number): (buffer?, string?)
|
||||
local w = Bytes.writer()
|
||||
local seen: { [number]: boolean } = {}
|
||||
while t ~= 0 do
|
||||
if t < 1 or t > geo.tracks or s >= geo.spt[t] then
|
||||
return nil, string.format("chain leaves the disk at %d/%d", t, s)
|
||||
end
|
||||
local key = t * 256 + s
|
||||
if seen[key] then
|
||||
return nil, string.format("chain loops at %d/%d", t, s)
|
||||
end
|
||||
seen[key] = true
|
||||
local o = base + geo.offsets[t] + s * 256
|
||||
local nt, ns = buffer.readu8(b, o), buffer.readu8(b, o + 1)
|
||||
if nt == 0 then
|
||||
local last = math.max(ns, 1)
|
||||
if last >= 2 then
|
||||
w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, last - 1)))
|
||||
end
|
||||
else
|
||||
w:bytes(buffer.fromstring(buffer.readstring(b, o + 2, 254)))
|
||||
end
|
||||
t, s = nt, ns
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
function D64.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local geo = detect(r:size())
|
||||
if not geo then
|
||||
return nil, Err.new(Err.CORRUPT, "not a D64 / D71 / D81 image size (" .. r:size() .. " bytes)")
|
||||
end
|
||||
local b, base = r.buf, r.base
|
||||
local hdr = base + geo.offsets[geo.dirTrack]
|
||||
local nameAt, idAt = if geo.kind == "d81" then 0x04 else 0x90, if geo.kind == "d81" then 0x16 else 0xA2
|
||||
local diskRaw = buffer.readstring(b, hdr + nameAt, 16)
|
||||
local a = Archive.new("d64", encoder)
|
||||
a.meta.disk = petscii((string.gsub(diskRaw, "\160+$", "")))
|
||||
a.meta.id = petscii(buffer.readstring(b, hdr + idAt, 2))
|
||||
a.meta.variant = geo.kind
|
||||
a.meta.tracks = geo.tracks
|
||||
a.meta.errorInfo = r:size() ~= geo.total
|
||||
a.meta.source = { format = "d64", variant = geo.kind, tracks = geo.tracks }
|
||||
-- the directory chain
|
||||
local t, s = buffer.readu8(b, hdr), buffer.readu8(b, hdr + 1)
|
||||
local seen: { [number]: boolean } = {}
|
||||
local count = 0
|
||||
local maxEntries = o.maxEntries or 4096
|
||||
while t ~= 0 do
|
||||
if t < 1 or t > geo.tracks or s >= geo.spt[t] or seen[t * 256 + s] then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("bad directory sector %d/%d", t, s))
|
||||
end
|
||||
seen[t * 256 + s] = true
|
||||
local so = base + geo.offsets[t] + s * 256
|
||||
for k = 0, 7 do
|
||||
local e = so + k * 32
|
||||
local ft = buffer.readu8(b, e + 2)
|
||||
local kind = bit32.band(ft, 15)
|
||||
if ft ~= 0 and kind ~= 0 then
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than maxEntries directory entries")
|
||||
end
|
||||
local raw = buffer.readstring(b, e + 5, 16)
|
||||
local name = petscii((string.gsub(raw, "\160+$", "")))
|
||||
local base_name, n = name, 2
|
||||
while a._byName[name] do
|
||||
name = base_name .. ";" .. n
|
||||
n += 1
|
||||
end
|
||||
local ty = TYPES[kind] or "?"
|
||||
local entry: any = {
|
||||
name = name,
|
||||
rawName = raw,
|
||||
type = ty,
|
||||
closed = bit32.band(ft, 0x80) ~= 0,
|
||||
locked = bit32.band(ft, 0x40) ~= 0,
|
||||
blocks = buffer.readu16(b, e + 30),
|
||||
dir = false,
|
||||
method = "store",
|
||||
}
|
||||
if ty == "cbm" or ty == "dir" then
|
||||
entry.size = 0
|
||||
else
|
||||
local data, err = chain(b, base, geo, buffer.readu8(b, e + 3), buffer.readu8(b, e + 4))
|
||||
if not data then
|
||||
return nil, Err.new(Err.CORRUPT, name .. ": " .. tostring(err))
|
||||
end
|
||||
entry.size = buffer.len(data)
|
||||
entry.data = data
|
||||
if ty == "rel" then
|
||||
entry.recordLength = buffer.readu8(b, e + 23)
|
||||
end
|
||||
end
|
||||
Archive.put(a, entry)
|
||||
end
|
||||
end
|
||||
t, s = buffer.readu8(b, so), buffer.readu8(b, so + 1)
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- BAM layout per variant: where each track's free count + bitmap lives
|
||||
local function bamEntry(geo: Geometry, img: buffer, t: number): (number, number, number)
|
||||
-- returns (offset of the free count, offset of the bitmap, bitmap bytes)
|
||||
local dir = geo.offsets[geo.dirTrack]
|
||||
if geo.kind == "d81" then
|
||||
local side = if t <= 40 then 1 else 2
|
||||
local tt = if t <= 40 then t else t - 40
|
||||
local o = dir + side * 256 + 0x10 + (tt - 1) * 6
|
||||
return o, o + 1, 5
|
||||
end
|
||||
if t <= 35 then
|
||||
local o = dir + 4 + (t - 1) * 4
|
||||
return o, o + 1, 3
|
||||
end
|
||||
-- d71 side 2: counts at 18/0 0xDD.., bitmaps on track 53 sector 0
|
||||
return dir + 0xDD + (t - 36), geo.offsets[53] + (t - 36) * 3, 3
|
||||
end
|
||||
|
||||
local function setFree(geo: Geometry, img: buffer, t: number, s: number, free: boolean)
|
||||
local co, bo = bamEntry(geo, img, t)
|
||||
local byte = bo + bit32.rshift(s, 3)
|
||||
local mask = bit32.lshift(1, bit32.band(s, 7))
|
||||
local cur = buffer.readu8(img, byte)
|
||||
local isFree = bit32.band(cur, mask) ~= 0
|
||||
if free and not isFree then
|
||||
buffer.writeu8(img, byte, bit32.bor(cur, mask))
|
||||
buffer.writeu8(img, co, buffer.readu8(img, co) + 1)
|
||||
elseif not free and isFree then
|
||||
buffer.writeu8(img, byte, bit32.band(cur, bit32.bnot(mask)))
|
||||
buffer.writeu8(img, co, buffer.readu8(img, co) - 1)
|
||||
end
|
||||
end
|
||||
|
||||
function D64.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local variant = o.variant or (if type(value) == "table" and type(value.meta) == "table" and value.meta.variant then value.meta.variant else "d64")
|
||||
if variant ~= "d64" and variant ~= "d71" and variant ~= "d81" then
|
||||
return nil, Err.new(Err.ARG, "variant must be d64, d71 or d81")
|
||||
end
|
||||
local files, err = Archive.files(value, "data")
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
local geo = geometry(variant, if variant == "d64" then 35 elseif variant == "d71" then 70 else 80)
|
||||
local img = buffer.create(geo.total)
|
||||
local dirT = geo.dirTrack
|
||||
local dir = geo.offsets[dirT]
|
||||
local diskName = toPetscii(o.disk or (if type(value) == "table" and type(value.meta) == "table" and type(value.meta.disk) == "string" then value.meta.disk else "rosetta"))
|
||||
local id = toPetscii(o.id or "fl")
|
||||
local function pad16(s: string): string
|
||||
return s .. string.rep("\160", 16 - #s)
|
||||
end
|
||||
-- header / BAM
|
||||
local firstDir
|
||||
if variant == "d81" then
|
||||
buffer.writestring(img, dir, "\40\3\68\0")
|
||||
buffer.writestring(img, dir + 4, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "3D" .. "\160\160")
|
||||
for side = 1, 2 do
|
||||
local bo = dir + side * 256
|
||||
buffer.writestring(img, bo, if side == 1 then "\40\2\68\187" else "\0\255\68\187")
|
||||
buffer.writestring(img, bo + 4, string.sub(id .. " ", 1, 2) .. "\192\0")
|
||||
end
|
||||
firstDir = 3
|
||||
else
|
||||
buffer.writestring(img, dir, "\18\1\65" .. (if variant == "d71" then "\128" else "\0"))
|
||||
buffer.writestring(img, dir + 0x90, pad16(diskName) .. "\160\160" .. string.sub(id .. " ", 1, 2) .. "\160" .. "2A" .. "\160\160\160\160")
|
||||
firstDir = 1
|
||||
end
|
||||
for t = 1, geo.tracks do
|
||||
for s = 0, geo.spt[t] - 1 do
|
||||
setFree(geo, img, t, s, true)
|
||||
end
|
||||
end
|
||||
-- system sectors: the header / BAM sectors and the first directory sector
|
||||
local used = { [dirT * 256 + 0] = true, [dirT * 256 + firstDir] = true }
|
||||
if variant == "d81" then
|
||||
used[dirT * 256 + 1], used[dirT * 256 + 2] = true, true
|
||||
elseif variant == "d71" then
|
||||
for s = 0, geo.spt[53] - 1 do
|
||||
used[53 * 256 + s] = true
|
||||
end
|
||||
end
|
||||
for k in used do
|
||||
setFree(geo, img, k // 256, k % 256, false)
|
||||
end
|
||||
local maxDirSectors = geo.spt[dirT] - firstDir
|
||||
if #files > maxDirSectors * 8 then
|
||||
return nil, Err.new(Err.LIMIT, "too many files for one directory track")
|
||||
end
|
||||
-- allocation: tracks nearest the directory track first, interleave 10
|
||||
local order = {}
|
||||
for d = 1, geo.tracks do
|
||||
for _, t in { dirT - d, dirT + d } do
|
||||
if t >= 1 and t <= geo.tracks and t ~= dirT and not (variant == "d71" and t == 53) then
|
||||
table.insert(order, t)
|
||||
end
|
||||
end
|
||||
end
|
||||
local ti, lastS = 1, -10
|
||||
local function alloc(): (number?, number?)
|
||||
while ti <= #order do
|
||||
local t = order[ti]
|
||||
local n = geo.spt[t]
|
||||
for k = 0, n - 1 do
|
||||
local s = (lastS + 10 + k) % n
|
||||
if not used[t * 256 + s] then
|
||||
used[t * 256 + s] = true
|
||||
setFree(geo, img, t, s, false)
|
||||
lastS = s
|
||||
return t, s
|
||||
end
|
||||
end
|
||||
ti += 1
|
||||
lastS = -10
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
local dirSector, slot = firstDir, 0
|
||||
local dirSectors = { firstDir }
|
||||
for _, f in files do
|
||||
local data = f.data
|
||||
local n = buffer.len(data)
|
||||
local blocks = math.max(1, math.ceil(n / 254))
|
||||
local first_t, first_s = 0, 0
|
||||
local prev = -1
|
||||
for k = 0, blocks - 1 do
|
||||
local t, s = alloc()
|
||||
if not t or not s then
|
||||
return nil, Err.new(Err.LIMIT, "disk full")
|
||||
end
|
||||
local so = geo.offsets[t] + s * 256
|
||||
if prev < 0 then
|
||||
first_t, first_s = t, s
|
||||
else
|
||||
buffer.writeu8(img, prev, t)
|
||||
buffer.writeu8(img, prev + 1, s)
|
||||
end
|
||||
local len = math.min(254, n - k * 254)
|
||||
if len > 0 then
|
||||
buffer.copy(img, so + 2, data, k * 254, len)
|
||||
end
|
||||
buffer.writeu8(img, so + 1, if k == blocks - 1 then len + 1 else 0)
|
||||
prev = so
|
||||
end
|
||||
if slot == 8 then
|
||||
-- next directory sector on the directory track (interleave 3)
|
||||
local nextS = nil
|
||||
for k = 0, geo.spt[dirT] - 1 do
|
||||
local s = (dirSector + 3 + k) % geo.spt[dirT]
|
||||
if not used[dirT * 256 + s] then
|
||||
nextS = s
|
||||
break
|
||||
end
|
||||
end
|
||||
if not nextS then
|
||||
return nil, Err.new(Err.LIMIT, "directory full")
|
||||
end
|
||||
used[dirT * 256 + nextS] = true
|
||||
setFree(geo, img, dirT, nextS, false)
|
||||
buffer.writeu8(img, dir + dirSector * 256, dirT)
|
||||
buffer.writeu8(img, dir + dirSector * 256 + 1, nextS)
|
||||
dirSector, slot = nextS, 0
|
||||
table.insert(dirSectors, nextS)
|
||||
end
|
||||
local e = dir + dirSector * 256 + slot * 32
|
||||
local ty: number = if type(f.entry.type) == "string" and TYPE_CODE[f.entry.type] then TYPE_CODE[f.entry.type] :: number else 2
|
||||
buffer.writeu8(img, e + 2, 0x80 + ty)
|
||||
buffer.writeu8(img, e + 3, first_t)
|
||||
buffer.writeu8(img, e + 4, first_s)
|
||||
local raw = if type(f.entry.rawName) == "string" and #f.entry.rawName == 16 then (string.gsub(f.entry.rawName, "\160+$", "")) else toPetscii(f.name)
|
||||
buffer.writestring(img, e + 5, pad16(raw))
|
||||
buffer.writeu16(img, e + 30, blocks)
|
||||
slot += 1
|
||||
end
|
||||
buffer.writeu8(img, dir + dirSector * 256 + 1, 0xFF)
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(variant?) -> an empty disk: a:add(name, data); a:write({ disk = "name", id = "ab" })
|
||||
function D64.new(variant: string?): any
|
||||
local a = Archive.new("d64", encoder)
|
||||
a.meta.variant = variant or "d64"
|
||||
a.meta.source = { format = "d64" }
|
||||
return a
|
||||
end
|
||||
|
||||
return D64
|
||||
@@ -0,0 +1,124 @@
|
||||
--!strict
|
||||
-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the
|
||||
-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3
|
||||
-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the
|
||||
-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy
|
||||
-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a
|
||||
-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Fat = require("@rosetta/containers/Fat")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local FatFormat = {
|
||||
name = "fat",
|
||||
category = "archive",
|
||||
extensions = { "img", "ima", "vfd", "flp", "fat" },
|
||||
mime = { "application/x-fat-image" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" },
|
||||
caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself)
|
||||
maxEntries: number?, -- default 65536
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440)
|
||||
label: string?, -- volume label
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function FatFormat.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 512 then
|
||||
return 0
|
||||
end
|
||||
local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos)
|
||||
if not v then
|
||||
return 0
|
||||
end
|
||||
return if v.partition then 0.6 else 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return FatFormat.encode(a, o)
|
||||
end
|
||||
|
||||
function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition })
|
||||
if not v then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
local list, lerr = Fat.list(v, o.maxEntries)
|
||||
if not list then
|
||||
return nil, Err.from(lerr)
|
||||
end
|
||||
local a = Archive.new("fat", encoder)
|
||||
for _, e in list do
|
||||
local entry = e
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = e.size,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
attr = e.attr,
|
||||
shortName = e.shortName,
|
||||
method = "store",
|
||||
load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?)
|
||||
local b, rerr = Fat.read(v :: Fat.Volume, entry)
|
||||
if not b then
|
||||
return nil, Err.from(rerr)
|
||||
end
|
||||
return b, nil
|
||||
end,
|
||||
})
|
||||
end
|
||||
a.meta.fat = v.bits
|
||||
a.meta.label = v.label
|
||||
a.meta.oem = v.oem
|
||||
a.meta.partition = v.partition
|
||||
a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local files: { Fat.WriteFile } = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local data: buffer? = nil
|
||||
if not e.dir then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime })
|
||||
end
|
||||
local img, err = Fat.write(files, { size = o.size, label = o.label })
|
||||
if not img then
|
||||
return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err))
|
||||
end
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" })
|
||||
function FatFormat.new(): any
|
||||
local a = Archive.new("fat", encoder)
|
||||
a.meta.source = { format = "fat" }
|
||||
return a
|
||||
end
|
||||
|
||||
return FatFormat
|
||||
@@ -0,0 +1,115 @@
|
||||
--!strict
|
||||
-- archive/grp: Build engine GRP archives (Duke Nukem 3D, Shadow Warrior, Blood: "KenSilverman", a u32 file count,
|
||||
-- 16-byte entries of a 12-byte name and a u32 size, then the files back to back), read into the standard Archive
|
||||
-- (entries read lazily) and written from any Archive value (names upper-cased to 8.3 by the caller's choice: they
|
||||
-- are stored as given, at most 12 bytes). Written from Ken Silverman's GRP description (kenbuild); no code taken.
|
||||
-- Not supported: the "GRP 2" / RFF / SSI variants.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Grp = {
|
||||
name = "grp",
|
||||
category = "archive",
|
||||
extensions = { "grp" },
|
||||
mime = { "application/x-build-grp" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
|
||||
caps = { decode = true, encode = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { upper: boolean? } -- upper-case the names (Build looks them up case-insensitively; default false)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "KenSilverman"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Grp.sniff(r: Bytes.Reader): number
|
||||
return Sniff.magic(r, MAGIC)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Grp.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Grp.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
if not r:match(MAGIC) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local count = r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many entries: " .. count)
|
||||
end
|
||||
if count * 16 > r:remaining() then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 12)
|
||||
end
|
||||
local a = Archive.new("grp", encode)
|
||||
local at = 16 + count * 16
|
||||
local size = r.limit - r.base
|
||||
for i = 0, count - 1 do
|
||||
local name = r:fixed(12)
|
||||
local n = r:u32le()
|
||||
if at + n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", 16 + i * 16)
|
||||
end
|
||||
Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) })
|
||||
at += n
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
a.meta.source = { format = "grp", entries = count }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Grp.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items, err = Archive.collect(archive)
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local files: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local name = it.entry.name
|
||||
if opts and opts.upper then
|
||||
name = string.upper(name)
|
||||
end
|
||||
if #name > 12 then
|
||||
return nil, Err.new(Err.ARG, "name longer than 12 bytes: " .. name)
|
||||
end
|
||||
table.insert(files, { name = name, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(MAGIC)
|
||||
w:u32le(#files)
|
||||
for _, f in files do
|
||||
w:string(f.name)
|
||||
w:fill(0, 12 - #f.name)
|
||||
w:u32le(buffer.len(f.data))
|
||||
end
|
||||
for _, f in files do
|
||||
w:bytes(f.data)
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty GRP Archive: a:add(name, data); a:write()
|
||||
function Grp.new(): any
|
||||
local a = Archive.new("grp", encode)
|
||||
a.meta.source = { format = "grp" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Grp
|
||||
@@ -0,0 +1,187 @@
|
||||
--!strict
|
||||
-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the
|
||||
-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
|
||||
-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
|
||||
-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
|
||||
-- inner tar, meta.compression = "gzip"). Deflate is codecs/compress/Deflate. Not supported: FHCRC verification.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Tar = require("@rosetta/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Gzip = {
|
||||
name = "gzip",
|
||||
category = "archive",
|
||||
extensions = { "gz", "tgz", "gzip" },
|
||||
mime = { "application/gzip" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/compress/Deflate", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, stream = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME
|
||||
export type EncodeOptions = {
|
||||
level: number?, -- 0..9, default 6
|
||||
name: string?, -- FNAME (default: the entry's name; none for a buffer)
|
||||
mtime: number?, -- MTIME (default: the entry's mtime, else 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Gzip.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(3) == "\31\139\8" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent)
|
||||
local function header(b: buffer, o: number, e: number): { [string]: any }
|
||||
local h: { [string]: any } = {}
|
||||
if o + 10 > e then
|
||||
return h
|
||||
end
|
||||
local flg = buffer.readu8(b, o + 3)
|
||||
h.mtime = buffer.readu32(b, o + 4)
|
||||
h.os = buffer.readu8(b, o + 9)
|
||||
local q = o + 10
|
||||
if bit32.band(flg, 4) ~= 0 and q + 2 <= e then
|
||||
q += 2 + buffer.readu16(b, q)
|
||||
end
|
||||
for _, f in { { 8, "name" }, { 16, "comment" } } :: { { any } } do
|
||||
if bit32.band(flg, f[1]) ~= 0 then
|
||||
local s = q
|
||||
while q < e and buffer.readu8(b, q) ~= 0 do
|
||||
q += 1
|
||||
end
|
||||
if q < e then
|
||||
h[f[2]] = buffer.readstring(b, s, q - s)
|
||||
end
|
||||
q += 1
|
||||
end
|
||||
end
|
||||
return h
|
||||
end
|
||||
|
||||
function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local h = header(r.buf, r.base, r.limit)
|
||||
local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
|
||||
return Gzip.encode(arc, o)
|
||||
end)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "gzip", os = h.os }
|
||||
a.meta.comment = h.comment
|
||||
local name = h.name
|
||||
if not name or name == "" or string.find(name, "[/\\]") then
|
||||
name = Archive.streamName(opts, Gzip.extensions)
|
||||
end
|
||||
Archive.put(a, {
|
||||
name = name,
|
||||
size = buffer.len(out),
|
||||
compressedSize = r.limit - r.base,
|
||||
method = "deflate",
|
||||
mtime = if h.mtime and h.mtime > 0 then h.mtime :: number else nil,
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local level = if o.level == nil then 6 else o.level
|
||||
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "level must be 0..9")
|
||||
end
|
||||
local data: buffer
|
||||
local name: string? = o.name
|
||||
local mtime: number = o.mtime or 0
|
||||
if type(value) == "buffer" then
|
||||
data = value
|
||||
elseif type(value) == "string" then
|
||||
data = buffer.fromstring(value)
|
||||
else
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
|
||||
end
|
||||
local files: typeof(items) = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
table.insert(files, it)
|
||||
end
|
||||
end
|
||||
if #files == 1 and #items == 1 then
|
||||
local b, err = files[1].read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
name = name or files[1].entry.name
|
||||
mtime = o.mtime or files[1].entry.mtime or 0
|
||||
else
|
||||
-- several entries: a tar inside
|
||||
local list = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local b = nil
|
||||
if not e.dir then
|
||||
local rb, err = it.read()
|
||||
if not rb then
|
||||
return nil, err
|
||||
end
|
||||
b = rb
|
||||
end
|
||||
table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode })
|
||||
end
|
||||
local t, terr = Tar.write(list)
|
||||
if not t then
|
||||
return nil, terr
|
||||
end
|
||||
data = t
|
||||
end
|
||||
end
|
||||
if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then
|
||||
mtime = 0
|
||||
end
|
||||
local raw, cerr = Deflate.compress(data, { level = level })
|
||||
if not raw then
|
||||
return nil, cerr
|
||||
end
|
||||
local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0))
|
||||
w:string("\31\139\8")
|
||||
w:u8(if name then 8 else 0)
|
||||
w:u32le(math.floor(mtime))
|
||||
w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0)
|
||||
w:u8(255)
|
||||
if name then
|
||||
local z = string.find(name, "\0", 1, true)
|
||||
w:cstring(if z then string.sub(name, 1, z - 1) else name)
|
||||
end
|
||||
w:bytes(raw)
|
||||
w:u32le(Crc32.raw(data, 0, buffer.len(data)))
|
||||
w:u32le(buffer.len(data) % 4294967296)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz)
|
||||
function Gzip.new(data: (buffer | string)?, name: string?): any
|
||||
local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
|
||||
return Gzip.encode(arc, o)
|
||||
end)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "gzip" }
|
||||
if data then
|
||||
a:add(name or "data", data)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Gzip
|
||||
@@ -0,0 +1,75 @@
|
||||
--!strict
|
||||
-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660:
|
||||
-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories;
|
||||
-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files.
|
||||
-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts
|
||||
-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El
|
||||
-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one.
|
||||
-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored
|
||||
-- bytes), multi-session images (the first session).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Iso9660 = require("@rosetta/containers/Iso9660")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Iso = {
|
||||
name = "iso",
|
||||
category = "archive",
|
||||
extensions = { "iso" },
|
||||
mime = { "application/x-iso9660-image" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
|
||||
caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Iso.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts)
|
||||
if not list then
|
||||
return nil, info
|
||||
end
|
||||
local a = Archive.new("iso")
|
||||
local b, limit = r.buf, r.limit
|
||||
for _, e in list do
|
||||
local data = e.type == "0" and e.size > 0
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = e.size,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
type = e.type,
|
||||
mode = e.mode,
|
||||
uid = e.uid,
|
||||
gid = e.gid,
|
||||
nlink = e.nlink,
|
||||
link = e.link,
|
||||
rdev = e.rdev,
|
||||
hidden = e.hidden,
|
||||
method = if e.zisofs then "zisofs" else "store",
|
||||
load = if data
|
||||
then function(): (buffer?, Err.Err?)
|
||||
return Iso9660.extract(b, e, limit)
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
end
|
||||
a.meta.boot = info.boot
|
||||
info.boot = nil
|
||||
a.meta.iso = info
|
||||
a.meta.source = { format = "iso", tree = info.tree }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Iso
|
||||
@@ -0,0 +1,434 @@
|
||||
--!strict
|
||||
-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their
|
||||
-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS
|
||||
-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7,
|
||||
-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read.
|
||||
-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower
|
||||
-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header
|
||||
-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu
|
||||
-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc),
|
||||
-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or
|
||||
-- at the first header found in the first 64 KB).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc16 = require("@rosetta/core/Crc16")
|
||||
local Lzh = require("@rosetta/codecs/compress/Lzh")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Lha = {
|
||||
name = "lha",
|
||||
category = "archive",
|
||||
extensions = { "lzh", "lha", "lzs" },
|
||||
mime = { "application/x-lzh-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
|
||||
maxEntries: number?, -- default 65536
|
||||
}
|
||||
export type EncodeOptions = {}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local METHODS: { [string]: boolean } = {
|
||||
["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true,
|
||||
["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true,
|
||||
["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
local function isHeader(s: string): boolean
|
||||
if #s < 22 then
|
||||
return false
|
||||
end
|
||||
local m = string.sub(s, 3, 7)
|
||||
local level = string.byte(s, 21)
|
||||
return METHODS[m] == true and level <= 3
|
||||
end
|
||||
|
||||
function Lha.sniff(r: Bytes.Reader): number
|
||||
if isHeader(r:peek(22)) then
|
||||
return 0.95
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them)
|
||||
local function path(s: string): string
|
||||
s = string.gsub(s, "[\\\255]", "/")
|
||||
local parts = {}
|
||||
for part in string.gmatch(s, "[^/]+") do
|
||||
if part ~= "." and part ~= ".." then
|
||||
table.insert(parts, part)
|
||||
end
|
||||
end
|
||||
return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "")
|
||||
end
|
||||
|
||||
type Header = {
|
||||
method: string,
|
||||
packed: number,
|
||||
size: number,
|
||||
mtime: number?,
|
||||
level: number,
|
||||
name: string,
|
||||
dir: string?,
|
||||
crc: number?,
|
||||
mode: number?,
|
||||
uid: number?,
|
||||
gid: number?,
|
||||
uname: string?,
|
||||
gname: string?,
|
||||
attr: number?,
|
||||
comment: string?,
|
||||
os: string?,
|
||||
dataAt: number,
|
||||
}
|
||||
|
||||
-- the extended headers from offset p (size field width w), until a zero size; returns the end offset
|
||||
local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?)
|
||||
local size = first
|
||||
local guard = 0
|
||||
while size ~= 0 do
|
||||
guard += 1
|
||||
if guard > 4096 or size < w + 1 or p + size > limit then
|
||||
return nil, "bad extended header"
|
||||
end
|
||||
local e = r:sub(p, size)
|
||||
local kind = e:u8()
|
||||
local body = size - 1 - w
|
||||
if kind == 0x01 then
|
||||
h.name = e:string(body)
|
||||
elseif kind == 0x02 then
|
||||
h.dir = e:string(body)
|
||||
elseif kind == 0x3F or kind == 0x71 then
|
||||
h.comment = e:string(body)
|
||||
elseif kind == 0x40 and body >= 2 then
|
||||
h.attr = e:u16le()
|
||||
elseif kind == 0x50 and body >= 2 then
|
||||
h.mode = e:u16le()
|
||||
elseif kind == 0x51 and body >= 4 then
|
||||
h.gid, h.uid = e:u16le(), e:u16le()
|
||||
elseif kind == 0x52 then
|
||||
h.gname = e:string(body)
|
||||
elseif kind == 0x53 then
|
||||
h.uname = e:string(body)
|
||||
elseif kind == 0x54 and body >= 4 then
|
||||
h.mtime = e:u32le()
|
||||
elseif kind == 0x42 and body >= 16 then
|
||||
h.packed, h.size = e:u64le(), e:u64le()
|
||||
end
|
||||
e:seek(size - w)
|
||||
local nextSize = if w == 2 then e:u16le() else e:u32le()
|
||||
if e.err then
|
||||
return nil, "truncated extended header"
|
||||
end
|
||||
p += size
|
||||
size = nextSize
|
||||
end
|
||||
return p, nil
|
||||
end
|
||||
|
||||
local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386",
|
||||
[0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt",
|
||||
[0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" }
|
||||
|
||||
-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker
|
||||
local function header(r: Bytes.Reader, p: number): (Header?, string?)
|
||||
local limit = r:size()
|
||||
if p >= limit or r:sub(p, 1):u8() == 0 then
|
||||
return nil, nil
|
||||
end
|
||||
if p + 22 > limit then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local s = r:sub(p, 26)
|
||||
local b0 = s:u8()
|
||||
s:u8()
|
||||
local method = s:string(5)
|
||||
local packed, size, stamp = s:u32le(), s:u32le(), s:u32le()
|
||||
s:u8()
|
||||
local level = s:u8()
|
||||
if not METHODS[method] then
|
||||
return nil, "bad method " .. method
|
||||
end
|
||||
local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 }
|
||||
if level == 0 or level == 1 then
|
||||
local hsize = b0 + 2
|
||||
if p + hsize > limit or hsize < 24 then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
local hr = r:sub(p + 21, hsize - 21)
|
||||
local nlen = hr:u8()
|
||||
h.name = hr:string(nlen)
|
||||
h.crc = hr:u16le()
|
||||
h.mtime = Archive.fromDos(stamp)
|
||||
if level == 0 then
|
||||
-- an optional Unix extension: 'U', mtime, mode, uid, gid
|
||||
if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then
|
||||
h.os = if hr:u8() == 0x55 then "unix" else "os68k"
|
||||
h.mtime = hr:u32le()
|
||||
h.mode = hr:u16le()
|
||||
h.uid, h.gid = hr:u16le(), hr:u16le()
|
||||
end
|
||||
h.dataAt = p + hsize
|
||||
else
|
||||
h.os = OS[hr:u8()]
|
||||
local first = r:sub(p + hsize - 2, 2):u16le()
|
||||
local e, err = extended(r, p + hsize, 2, first, h, limit)
|
||||
if not e then
|
||||
return nil, err
|
||||
end
|
||||
h.packed = packed - (e - (p + hsize))
|
||||
h.dataAt = e
|
||||
end
|
||||
if hr.err then
|
||||
return nil, "truncated header"
|
||||
end
|
||||
elseif level == 2 then
|
||||
local total = r:sub(p, 2):u16le()
|
||||
local hr = r:sub(p + 21, 5)
|
||||
h.crc = hr:u16le()
|
||||
local osByte = hr:u8()
|
||||
h.os = OS[osByte]
|
||||
if osByte == 0x4B then
|
||||
total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates)
|
||||
end
|
||||
local first = hr:u16le()
|
||||
h.mtime = stamp
|
||||
local e, err = extended(r, p + 26, 2, first, h, limit)
|
||||
if not e or hr.err then
|
||||
return nil, err or "truncated header"
|
||||
end
|
||||
h.dataAt = p + total
|
||||
if total < 26 or h.dataAt > limit then
|
||||
return nil, "bad level 2 header size"
|
||||
end
|
||||
elseif level == 3 then
|
||||
local hr = r:sub(p + 21, 11)
|
||||
h.crc = hr:u16le()
|
||||
h.os = OS[hr:u8()]
|
||||
local total = hr:u32le()
|
||||
local first = hr:u32le()
|
||||
h.mtime = stamp
|
||||
local e, err = extended(r, p + 32, 4, first, h, limit)
|
||||
if not e or hr.err then
|
||||
return nil, err or "truncated header"
|
||||
end
|
||||
h.dataAt = p + total
|
||||
if total < 32 or h.dataAt > limit then
|
||||
return nil, "bad level 3 header size"
|
||||
end
|
||||
else
|
||||
return nil, "unsupported: header level " .. level
|
||||
end
|
||||
return h, nil
|
||||
end
|
||||
|
||||
local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" }
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return Lha.encode(a, o)
|
||||
end
|
||||
|
||||
function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local maxEntries = o.maxEntries or 65536
|
||||
local p = 0
|
||||
-- a self-extracting stub: find the first header
|
||||
if not isHeader(r:peek(22)) then
|
||||
local head = r:peek(65536)
|
||||
local at = nil
|
||||
for k = 1, #head - 22 do
|
||||
if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then
|
||||
at = k - 1
|
||||
break
|
||||
end
|
||||
end
|
||||
if not at then
|
||||
return nil, Err.new(Err.CORRUPT, "no LHA header")
|
||||
end
|
||||
p = at
|
||||
end
|
||||
local a = Archive.new("lha", encoder)
|
||||
local count = 0
|
||||
local levels = {}
|
||||
while true do
|
||||
local h, err = header(r, p)
|
||||
if err then
|
||||
return nil, Err.from(err, r.base + p)
|
||||
end
|
||||
if not h then
|
||||
break
|
||||
end
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
|
||||
end
|
||||
levels[h.level] = true
|
||||
if h.packed < 0 or h.dataAt + h.packed > r:size() then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt)
|
||||
end
|
||||
-- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do
|
||||
local os = h.os
|
||||
if os == nil or os == "msdos" or os == "atari" or os == "os2" then
|
||||
if not string.find(h.name .. (h.dir or ""), "%l") then
|
||||
h.name = string.lower(h.name)
|
||||
h.dir = if h.dir then string.lower(h.dir) else nil
|
||||
end
|
||||
end
|
||||
-- the full path (a Unix symlink "name|target" may be split across the directory and file name headers)
|
||||
local name = path(h.name)
|
||||
if h.dir and h.dir ~= "" then
|
||||
local d = path(h.dir)
|
||||
if string.sub(d, -1) ~= "/" then
|
||||
d ..= "/"
|
||||
end
|
||||
name = d .. name
|
||||
end
|
||||
local link: string? = nil
|
||||
local bar = string.find(name, "|", 1, true)
|
||||
if bar then
|
||||
name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1)
|
||||
end
|
||||
local isDir = h.method == "lhd"
|
||||
if isDir and link == nil and string.sub(name, -1) ~= "/" then
|
||||
name ..= "/"
|
||||
end
|
||||
local e: any = {
|
||||
name = name,
|
||||
size = if isDir or link then 0 else h.size,
|
||||
compressedSize = h.packed,
|
||||
method = h.method,
|
||||
mtime = h.mtime,
|
||||
dir = isDir and link == nil,
|
||||
mode = h.mode,
|
||||
uid = h.uid,
|
||||
gid = h.gid,
|
||||
uname = h.uname,
|
||||
gname = h.gname,
|
||||
attr = h.attr,
|
||||
comment = h.comment,
|
||||
os = h.os,
|
||||
level = h.level,
|
||||
crc = h.crc,
|
||||
}
|
||||
if link then
|
||||
e.link = link
|
||||
e.type = "symlink"
|
||||
elseif not isDir and h.size > 0 then
|
||||
if h.size > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
|
||||
end
|
||||
local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc
|
||||
local buf, base = r.buf, r.base
|
||||
e.load = function(): (buffer?, Err.Err?)
|
||||
local out: buffer?, derr: string?
|
||||
if method == "lh0" or method == "lz4" then
|
||||
if packed < size then
|
||||
return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
|
||||
end
|
||||
out = buffer.create(size)
|
||||
buffer.copy(out :: buffer, 0, buf, base + at, size)
|
||||
elseif LZH_METHOD[method] then
|
||||
out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method])
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "method " .. method)
|
||||
end
|
||||
if not out then
|
||||
return nil, Err.from(derr)
|
||||
end
|
||||
if crc and Crc16.arc(out, 0, size) ~= crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch")
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
Archive.put(a, e)
|
||||
p = h.dataAt + h.packed
|
||||
end
|
||||
a.meta.source = { format = "lha", levels = levels }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local out = Bytes.writer()
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local data = buffer.create(0)
|
||||
if not e.dir then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local full = string.gsub(e.name, "/+$", "")
|
||||
local dirPart, base = string.match(full, "^(.*/)([^/]*)$")
|
||||
if not dirPart then
|
||||
dirPart, base = "", full
|
||||
end
|
||||
if e.dir then
|
||||
dirPart, base = full .. "/", ""
|
||||
end
|
||||
local h = Bytes.writer()
|
||||
h:u16le(0) -- total size, patched
|
||||
h:string(if e.dir then "-lhd-" else "-lh0-")
|
||||
h:u32le(buffer.len(data))
|
||||
h:u32le(buffer.len(data))
|
||||
h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0)
|
||||
h:u8(0x20)
|
||||
h:u8(2)
|
||||
h:u16le(Crc16.arc(data, 0, buffer.len(data)))
|
||||
h:u8(0x55) -- 'U'nix
|
||||
-- extended headers: [type][body][size of the next one]; the first size ends the base header
|
||||
local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } }
|
||||
if dirPart ~= "" then
|
||||
table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) })
|
||||
end
|
||||
if type(e.mode) == "number" then
|
||||
local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000)
|
||||
table.insert(exts, { 0x50, string.char(m % 256, m // 256) })
|
||||
end
|
||||
h:u16le(#exts[1][2] + 3)
|
||||
for i, x in exts do
|
||||
h:u8(x[1])
|
||||
h:string(x[2])
|
||||
h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0)
|
||||
end
|
||||
local hb = h:finish()
|
||||
local total = buffer.len(hb)
|
||||
if total > 65535 then
|
||||
return nil, Err.new(Err.ARG, "header too long for " .. e.name)
|
||||
end
|
||||
buffer.writeu16(hb, 0, total)
|
||||
-- the header CRC covers the whole header with its own field zero
|
||||
local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27
|
||||
buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total))
|
||||
out:bytes(hb)
|
||||
out:bytes(data)
|
||||
end
|
||||
out:u8(0)
|
||||
return out:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data)
|
||||
function Lha.new(): any
|
||||
local a = Archive.new("lha", encoder)
|
||||
a.meta.source = { format = "lha" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Lha
|
||||
@@ -0,0 +1,353 @@
|
||||
--!strict
|
||||
-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the
|
||||
-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api
|
||||
-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy
|
||||
-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed
|
||||
-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified
|
||||
-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks
|
||||
-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size;
|
||||
-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported:
|
||||
-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Lz4 = require("@rosetta/codecs/compress/Lz4")
|
||||
local Xxh32 = require("@rosetta/codecs/compress/Xxh32")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Lz4Format = {
|
||||
name = "lz4",
|
||||
category = "archive",
|
||||
extensions = { "lz4", "tlz4" },
|
||||
mime = { "application/x-lz4" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, legacy = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool)
|
||||
blockChecksum: boolean?, -- default false
|
||||
contentChecksum: boolean?, -- default true
|
||||
contentSize: boolean?, -- store the content size (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = 0x184D2204
|
||||
local LEGACY = 0x184C2102
|
||||
local LEGACY_BLOCK = 8 * 1048576
|
||||
local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Lz4Format.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m == "\4\34\77\24" then
|
||||
return 1
|
||||
elseif m == "\2\33\76\24" then
|
||||
return 0.9
|
||||
elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then
|
||||
-- a skippable frame (zstd shares the magic): an LZ4 frame after it
|
||||
local h = r:peek(4, 4)
|
||||
if #h == 4 then
|
||||
local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216
|
||||
if r:peek(4, 8 + n) == "\4\34\77\24" then
|
||||
return 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function skippable(m: number): boolean
|
||||
return m >= 0x184D2A50 and m <= 0x184D2A5F
|
||||
end
|
||||
|
||||
type Out = { buf: buffer, n: number, max: number }
|
||||
|
||||
-- room for k more bytes in the output (doubling, up to max) | false
|
||||
local function room(out: Out, k: number): boolean
|
||||
local need = out.n + k
|
||||
if need > out.max then
|
||||
return false
|
||||
end
|
||||
if need > buffer.len(out.buf) then
|
||||
local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max))
|
||||
buffer.copy(nb, 0, out.buf, 0, out.n)
|
||||
out.buf = nb
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- one LZ4 frame at p -> the input offset after it | nil, Err
|
||||
local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?)
|
||||
if p + 7 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", p)
|
||||
end
|
||||
local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5)
|
||||
if bit32.rshift(flg, 6) ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4)
|
||||
end
|
||||
if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4)
|
||||
end
|
||||
local independent = bit32.band(flg, 0x20) ~= 0
|
||||
local blockSum = bit32.band(flg, 0x10) ~= 0
|
||||
local hasSize = bit32.band(flg, 0x08) ~= 0
|
||||
local contentSum = bit32.band(flg, 0x04) ~= 0
|
||||
local hasDict = bit32.band(flg, 0x01) ~= 0
|
||||
local bmax = SIZES[bit32.rshift(bd, 4)]
|
||||
if not bmax then
|
||||
return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5)
|
||||
end
|
||||
local q = p + 6
|
||||
local size: number? = nil
|
||||
if hasSize then
|
||||
if q + 8 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
|
||||
end
|
||||
size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296
|
||||
q += 8
|
||||
end
|
||||
if hasDict then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q)
|
||||
end
|
||||
if q + 1 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
|
||||
end
|
||||
local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255)
|
||||
if hc ~= buffer.readu8(b, q) then
|
||||
return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q)
|
||||
end
|
||||
q += 1
|
||||
if size and out.n + size > out.max then
|
||||
return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p)
|
||||
end
|
||||
local start = out.n
|
||||
while true do
|
||||
if q + 4 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block header past the end", q)
|
||||
end
|
||||
local bs = buffer.readu32(b, q)
|
||||
q += 4
|
||||
if bs == 0 then
|
||||
break
|
||||
end
|
||||
local raw = bit32.band(bs, 0x80000000) ~= 0
|
||||
local n = bit32.band(bs, 0x7FFFFFFF)
|
||||
if n > bmax then
|
||||
return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4)
|
||||
end
|
||||
if q + n + (if blockSum then 4 else 0) > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
|
||||
end
|
||||
if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then
|
||||
return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n)
|
||||
end
|
||||
if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
if raw then
|
||||
buffer.copy(out.buf, out.n, b, q, n)
|
||||
out.n += n
|
||||
else
|
||||
local lim = math.min(out.n + bmax, buffer.len(out.buf))
|
||||
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start)
|
||||
if not dEnd then
|
||||
if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
return nil, Err.from(msg, q)
|
||||
end
|
||||
out.n = dEnd
|
||||
end
|
||||
q += n + (if blockSum then 4 else 0)
|
||||
end
|
||||
if contentSum then
|
||||
if q + 4 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q)
|
||||
end
|
||||
if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then
|
||||
return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q)
|
||||
end
|
||||
q += 4
|
||||
end
|
||||
if size and out.n - start ~= size then
|
||||
return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6)
|
||||
end
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows
|
||||
local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?)
|
||||
local q = p + 4
|
||||
while q + 4 <= e do
|
||||
local n = buffer.readu32(b, q)
|
||||
if n == MAGIC or n == LEGACY or skippable(n) then
|
||||
break
|
||||
end
|
||||
q += 4
|
||||
if q + n > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
|
||||
end
|
||||
if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf))
|
||||
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim)
|
||||
if not dEnd then
|
||||
return nil, Err.from(msg, q)
|
||||
end
|
||||
out.n = dEnd
|
||||
q += n
|
||||
end
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err
|
||||
function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
|
||||
local verify = not (opts and opts.verify == false)
|
||||
local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes }
|
||||
local p, e = o, o + n
|
||||
local frames = 0
|
||||
while p + 4 <= e do
|
||||
local m = buffer.readu32(b, p)
|
||||
local q, err
|
||||
if m == MAGIC then
|
||||
q, err = frame(b, p, e, out, verify)
|
||||
frames += 1
|
||||
elseif m == LEGACY then
|
||||
q, err = legacy(b, p, e, out)
|
||||
frames += 1
|
||||
elseif skippable(m) then
|
||||
if p + 8 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
|
||||
end
|
||||
q = p + 8 + buffer.readu32(b, p + 4)
|
||||
if q > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
|
||||
end
|
||||
elseif frames > 0 then
|
||||
break -- trailing data after the frames (as lz4 -d, which warns)
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", p)
|
||||
end
|
||||
if not q then
|
||||
return nil, err
|
||||
end
|
||||
p = q :: number
|
||||
end
|
||||
if frames == 0 then
|
||||
return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o)
|
||||
end
|
||||
local res = buffer.create(out.n)
|
||||
buffer.copy(res, 0, out.buf, 0, out.n)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Lz4Format.encode(value, opts)
|
||||
end
|
||||
|
||||
function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, err = Lz4Format.decompress(r.buf, r.base, n, o)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("lz4", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" }
|
||||
local name = Archive.streamName(o, { "lz4" })
|
||||
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
|
||||
if stem and ext and string.lower(ext) == "tlz4" then
|
||||
name = stem .. ".tar"
|
||||
end
|
||||
Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out })
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- compress(data, opts?) -> one LZ4 frame | nil, Err
|
||||
function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local op: EncodeOptions = opts or {}
|
||||
local bsize = op.blockSize or 4194304
|
||||
local bd = nil
|
||||
for k, v in SIZES do
|
||||
if v == bsize then
|
||||
bd = k
|
||||
end
|
||||
end
|
||||
if not bd then
|
||||
return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304")
|
||||
end
|
||||
local blockSum = op.blockChecksum == true
|
||||
local contentSum = op.contentChecksum ~= false
|
||||
local withSize = op.contentSize == true
|
||||
local w = Bytes.writer(n + n // 200 + 64)
|
||||
w:u32le(MAGIC)
|
||||
local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0)
|
||||
w:u8(flg)
|
||||
w:u8(bd * 16)
|
||||
if withSize then
|
||||
w:u32le(n % 4294967296)
|
||||
w:u32le(n // 4294967296)
|
||||
end
|
||||
local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255)
|
||||
w:u8(hc)
|
||||
local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1))))
|
||||
local p = o
|
||||
while p < o + n do
|
||||
local k = math.min(bsize, o + n - p)
|
||||
local c = Lz4.encodeInto(b, p, k, scratch, 0)
|
||||
local at = w.pos
|
||||
if c < k then
|
||||
w:u32le(c)
|
||||
local q = w:reserve(c)
|
||||
buffer.copy(w.buf, q, scratch, 0, c)
|
||||
w.pos = q + c
|
||||
else
|
||||
w:u32le(k + 0x80000000)
|
||||
local q = w:reserve(k)
|
||||
buffer.copy(w.buf, q, b, p, k)
|
||||
w.pos = q + k
|
||||
end
|
||||
if blockSum then
|
||||
local len = w.pos - at - 4
|
||||
w:u32le(Xxh32.hash(w.buf, at + 4, len))
|
||||
end
|
||||
p += k
|
||||
end
|
||||
w:u32le(0)
|
||||
if contentSum then
|
||||
w:u32le(Xxh32.hash(b, o, n))
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame
|
||||
function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local data, err = Archive.streamData(value)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
return Lz4Format.compress(data, opts)
|
||||
end
|
||||
|
||||
return Lz4Format
|
||||
@@ -0,0 +1,201 @@
|
||||
--!strict
|
||||
-- archive/macbinary: MacBinary I, II and III files (a 128-byte header with the name, type / creator, Finder flags,
|
||||
-- dates and fork lengths, then the data and resource forks padded to 128 bytes, then the Get Info comment). II / III
|
||||
-- headers carry a CRC-16/XMODEM (verified: Err.CHECKSUM), III the 'mBIN' signature; MacBinary I is recognised by its
|
||||
-- zero bytes and sane lengths. Decodes to an Archive in the containers/MacFile convention (the data fork is the entry
|
||||
-- `name`, a resource fork the entry `name.rsrc`, with macType / macCreator / finderFlags / created / mtime /
|
||||
-- comment); writes MacBinary III (readable as II) from any Archive's first Mac file or a buffer. Written from the
|
||||
-- MacBinary II / III specifications (Yves Lempereur et al.). Not supported: the secondary header's content (skipped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc16 = require("@rosetta/core/Crc16")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local MacFile = require("@rosetta/containers/MacFile")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local MacBinary = {
|
||||
name = "macbinary",
|
||||
category = "archive",
|
||||
extensions = { "bin", "macbin" },
|
||||
mime = { "application/x-macbinary" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc16", "containers/Archive", "containers/MacFile" },
|
||||
caps = { decode = true, encode = true, forks = true, variants = { "I", "II", "III" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number? } -- default 2^30
|
||||
export type EncodeOptions = { name: string? } -- the name of a buffer / string value (default "data")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- version(b, o, len) -> "III" / "II" / "I" / nil: which MacBinary header sits at o
|
||||
local function version(b: buffer, o: number, len: number): string?
|
||||
if len < 128 then
|
||||
return nil
|
||||
end
|
||||
local u8 = function(i: number): number
|
||||
return buffer.readu8(b, o + i)
|
||||
end
|
||||
if u8(0) ~= 0 or u8(74) ~= 0 then
|
||||
return nil
|
||||
end
|
||||
local nameLen = u8(1)
|
||||
if nameLen < 1 or nameLen > 63 then
|
||||
return nil
|
||||
end
|
||||
local function be32(i: number): number
|
||||
return u8(i) * 16777216 + u8(i + 1) * 65536 + u8(i + 2) * 256 + u8(i + 3)
|
||||
end
|
||||
local dlen, rlen = be32(83), be32(87)
|
||||
if dlen > 0x7FFFFFFF or rlen > 0x7FFFFFFF then
|
||||
return nil
|
||||
end
|
||||
local crc = u8(124) * 256 + u8(125)
|
||||
if crc == Crc16.ccitt(b, o, 124) and (crc ~= 0 or u8(122) >= 129) then
|
||||
return if buffer.readstring(b, o + 102, 4) == "mBIN" then "III" else "II"
|
||||
end
|
||||
if buffer.readstring(b, o + 102, 4) == "mBIN" then
|
||||
return nil -- III with a bad CRC
|
||||
end
|
||||
-- MacBinary I: byte 82 zero, bytes 99..125 zero, the forks within the file
|
||||
if u8(82) ~= 0 then
|
||||
return nil
|
||||
end
|
||||
for i = 99, 125 do
|
||||
if u8(i) ~= 0 then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
local need = 128 + math.ceil(dlen / 128) * 128 + rlen
|
||||
return if need <= len + 127 then "I" else nil
|
||||
end
|
||||
|
||||
function MacBinary.sniff(r: Bytes.Reader): number
|
||||
local n = math.min(r:remaining(), 128)
|
||||
if n < 128 then
|
||||
return 0
|
||||
end
|
||||
local v = version(r.buf, r.base + r.pos, r.limit - r.base - r.pos)
|
||||
return if v == "III" then 0.95 elseif v == "II" then 0.8 elseif v == "I" then 0.3 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return MacBinary.encode(a, o)
|
||||
end
|
||||
|
||||
local function pad(n: number): number
|
||||
return math.ceil(n / 128) * 128
|
||||
end
|
||||
|
||||
function MacBinary.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local len = r.limit - r.base
|
||||
local v = version(r.buf, r.base, len)
|
||||
if not v then
|
||||
if len >= 128 and buffer.readstring(r.buf, r.base + 102, 4) == "mBIN" then
|
||||
return nil, Err.new(Err.CHECKSUM, "header CRC mismatch")
|
||||
end
|
||||
return nil, Err.new(if len < 128 then Err.TRUNCATED else Err.CORRUPT, "not a MacBinary header")
|
||||
end
|
||||
local h = r:sub(0, 128)
|
||||
h:seek(1)
|
||||
local name = h:string(h:u8())
|
||||
h:seek(65)
|
||||
local ftype, creator = h:string(4), h:string(4)
|
||||
local flagsHi = h:u8()
|
||||
h:seek(83)
|
||||
local dlen, rlen = h:u32be(), h:u32be()
|
||||
local created, modified = h:u32be(), h:u32be()
|
||||
local commentLen = h:u16be()
|
||||
local flagsLo = h:u8()
|
||||
h:seek(120)
|
||||
local secondary = h:u16be()
|
||||
if v == "I" then
|
||||
commentLen, flagsLo, secondary = 0, 0, 0
|
||||
end
|
||||
if dlen + rlen > (o.maxBytes or 2 ^ 30) then
|
||||
return nil, Err.new(Err.LIMIT, "forks larger than maxBytes")
|
||||
end
|
||||
r:seek(128 + pad(secondary))
|
||||
local data = r:bytes(dlen)
|
||||
r:seek(128 + pad(secondary) + pad(dlen))
|
||||
local rsrc = r:bytes(rlen)
|
||||
local comment: string? = nil
|
||||
if commentLen > 0 and r:seek(128 + pad(secondary) + pad(dlen) + pad(rlen)) then
|
||||
comment = MacFile.name(r:string(math.min(commentLen, r:remaining())))
|
||||
end
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local a = Archive.new("macbinary", encoder)
|
||||
MacFile.put(a, {
|
||||
name = MacFile.name(name),
|
||||
data = data,
|
||||
rsrc = rsrc,
|
||||
type = ftype,
|
||||
creator = creator,
|
||||
flags = flagsHi * 256 + flagsLo,
|
||||
created = MacFile.fromMac(created),
|
||||
modified = MacFile.fromMac(modified),
|
||||
comment = comment,
|
||||
})
|
||||
a.meta.stream = rlen == 0
|
||||
a.meta.source = { format = "macbinary", version = v }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function MacBinary.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local files, err = MacFile.collect(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
local f = files[1]
|
||||
if not f then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local name = MacFile.roman(f.name)
|
||||
if #name < 1 or #name > 63 then
|
||||
return nil, Err.new(Err.ARG, "the name must be 1..63 bytes")
|
||||
end
|
||||
local dlen, rlen = buffer.len(f.data), buffer.len(f.rsrc)
|
||||
local comment = if f.comment then MacFile.roman(f.comment) else ""
|
||||
local out = buffer.create(128 + pad(dlen) + pad(rlen) + #comment)
|
||||
buffer.writeu8(out, 1, #name)
|
||||
buffer.writestring(out, 2, name)
|
||||
buffer.writestring(out, 65, f.type)
|
||||
buffer.writestring(out, 69, f.creator)
|
||||
buffer.writeu8(out, 73, bit32.rshift(f.flags, 8))
|
||||
local function be32(at: number, v: number)
|
||||
buffer.writeu32(out, at, bit32.byteswap(v))
|
||||
end
|
||||
be32(83, dlen)
|
||||
be32(87, rlen)
|
||||
be32(91, MacFile.toMac(f.created or f.modified))
|
||||
be32(95, MacFile.toMac(f.modified))
|
||||
buffer.writeu8(out, 99, bit32.rshift(#comment, 8))
|
||||
buffer.writeu8(out, 100, bit32.band(#comment, 255))
|
||||
buffer.writeu8(out, 101, bit32.band(f.flags, 255))
|
||||
buffer.writestring(out, 102, "mBIN")
|
||||
buffer.writeu8(out, 122, 130)
|
||||
buffer.writeu8(out, 123, 129)
|
||||
local crc = Crc16.ccitt(out, 0, 124)
|
||||
buffer.writeu8(out, 124, bit32.rshift(crc, 8))
|
||||
buffer.writeu8(out, 125, bit32.band(crc, 255))
|
||||
buffer.copy(out, 128, f.data)
|
||||
buffer.copy(out, 128 + pad(dlen), f.rsrc)
|
||||
buffer.writestring(out, 128 + pad(dlen) + pad(rlen), comment)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty MacBinary Archive: a:add(name, data); add "name.rsrc" for a resource fork
|
||||
function MacBinary.new(): any
|
||||
local a = Archive.new("macbinary", encoder)
|
||||
a.meta.source = { format = "macbinary" }
|
||||
return a
|
||||
end
|
||||
|
||||
return MacBinary
|
||||
@@ -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("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
|
||||
local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
local Explode = require("@rosetta/codecs/compress/Explode")
|
||||
local Crypt = require("@rosetta/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,135 @@
|
||||
--!strict
|
||||
-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the
|
||||
-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored
|
||||
-- bytes) and written from any Archive value. Written from the format description in the Quake source release
|
||||
-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken.
|
||||
-- Not supported: Daikatana's compressed PAK entries.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Sniff = require("@rosetta/core/Sniff")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Pak = {
|
||||
name = "pak",
|
||||
category = "archive",
|
||||
extensions = { "pak", "sin" },
|
||||
mime = { "application/x-pak" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, variants = { "quake", "sin" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Pak.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 then
|
||||
return 0
|
||||
end
|
||||
return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9))
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Pak.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local magic = r:string(4)
|
||||
local dirOfs, dirLen = r:u32le(), r:u32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil
|
||||
if not variant then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local nameLen = VARIANTS[variant].nameLen
|
||||
local entrySize = nameLen + 8
|
||||
local size = r.limit - r.base
|
||||
if dirOfs + dirLen > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 4)
|
||||
end
|
||||
if dirLen % entrySize ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8)
|
||||
end
|
||||
local count = dirLen // entrySize
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many entries: " .. count)
|
||||
end
|
||||
local a = Archive.new("pak", encode)
|
||||
local d = r:sub(dirOfs, dirLen)
|
||||
for i = 0, count - 1 do
|
||||
local name = d:fixed(nameLen)
|
||||
local at, n = d:u32le(), d:u32le()
|
||||
if d.err then
|
||||
return nil, d.err
|
||||
end
|
||||
if at + n > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize)
|
||||
end
|
||||
Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) })
|
||||
end
|
||||
a.meta.source = { format = "pak", variant = variant, entries = count }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Pak.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 variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake"
|
||||
local v = VARIANTS[variant]
|
||||
if not v then
|
||||
return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant))
|
||||
end
|
||||
local files: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local name = string.gsub(it.entry.name, "\\", "/")
|
||||
if #name >= v.nameLen then
|
||||
return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name)
|
||||
end
|
||||
table.insert(files, { name = name, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(v.magic)
|
||||
w:u32le(0)
|
||||
w:u32le(0)
|
||||
local offsets: { number } = {}
|
||||
for i, f in files do
|
||||
offsets[i] = w:tell()
|
||||
w:bytes(f.data)
|
||||
end
|
||||
local dirOfs = w:tell()
|
||||
for i, f in files do
|
||||
w:string(f.name)
|
||||
w:fill(0, v.nameLen - #f.name)
|
||||
w:u32le(offsets[i])
|
||||
w:u32le(buffer.len(f.data))
|
||||
end
|
||||
w:setU32le(4, dirOfs)
|
||||
w:setU32le(8, w:tell() - dirOfs)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write()
|
||||
function Pak.new(variant: ("quake" | "sin")?): any
|
||||
local a = Archive.new("pak", encode)
|
||||
a.meta.source = { format = "pak", variant = variant or "quake" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Pak
|
||||
@@ -0,0 +1,333 @@
|
||||
--!strict
|
||||
-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
|
||||
-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
|
||||
-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
|
||||
-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
|
||||
-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
|
||||
-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
|
||||
-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
|
||||
-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
|
||||
-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Deflate = require("@rosetta/codecs/compress/Deflate")
|
||||
local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
local Bzip2 = require("@rosetta/codecs/compress/Bzip2")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Cpio = require("@rosetta/containers/Cpio")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Rpm = {
|
||||
name = "rpm",
|
||||
category = "archive",
|
||||
extensions = { "rpm" },
|
||||
mime = { "application/x-rpm" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- the largest decompressed payload (default 2^30)
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local LEAD_MAGIC = "\237\171\238\219"
|
||||
local HEADER_MAGIC = "\142\173\232\1"
|
||||
local RPMFILE_GHOST = 64
|
||||
|
||||
-- the tags meta.rpm names
|
||||
local NAMES: { [number]: string } = {
|
||||
[1000] = "name",
|
||||
[1001] = "version",
|
||||
[1002] = "release",
|
||||
[1003] = "epoch",
|
||||
[1004] = "summary",
|
||||
[1005] = "description",
|
||||
[1006] = "buildtime",
|
||||
[1007] = "buildhost",
|
||||
[1009] = "size",
|
||||
[1010] = "distribution",
|
||||
[1011] = "vendor",
|
||||
[1014] = "license",
|
||||
[1015] = "packager",
|
||||
[1016] = "group",
|
||||
[1020] = "url",
|
||||
[1021] = "os",
|
||||
[1022] = "arch",
|
||||
[1044] = "sourcerpm",
|
||||
[1047] = "provides",
|
||||
[1049] = "requires",
|
||||
[1124] = "payloadFormat",
|
||||
[1125] = "payloadCompressor",
|
||||
[1126] = "payloadFlags",
|
||||
[5009] = "longsize",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Rpm.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == LEAD_MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a header structure at p -> { [tag] = value }, end offset | nil, Err
|
||||
local function header(b: buffer, p: number, e: number): (any, any)
|
||||
if p + 16 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
|
||||
end
|
||||
if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
|
||||
end
|
||||
local n = bit32.byteswap(buffer.readu32(b, p + 8))
|
||||
local hsize = bit32.byteswap(buffer.readu32(b, p + 12))
|
||||
local index = p + 16
|
||||
local store = index + n * 16
|
||||
if n > 0x10000 or hsize > 0x10000000 then
|
||||
return nil, Err.new(Err.LIMIT, "header too large", p)
|
||||
end
|
||||
if store + hsize > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header data past the end", p)
|
||||
end
|
||||
local tags: { [number]: any } = {}
|
||||
local se = store + hsize
|
||||
for i = 0, n - 1 do
|
||||
local q = index + i * 16
|
||||
local tag = bit32.byteswap(buffer.readu32(b, q))
|
||||
local typ = bit32.byteswap(buffer.readu32(b, q + 4))
|
||||
local off = bit32.byteswap(buffer.readu32(b, q + 8))
|
||||
local count = bit32.byteswap(buffer.readu32(b, q + 12))
|
||||
local d = store + off
|
||||
if off > hsize then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0
|
||||
if width > 0 then
|
||||
if d + count * width > se then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
local v = table.create(count)
|
||||
for k = 0, count - 1 do
|
||||
local x = d + k * width
|
||||
v[k + 1] = if width == 1 then buffer.readu8(b, x)
|
||||
elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1))
|
||||
elseif width == 4 then bit32.byteswap(buffer.readu32(b, x))
|
||||
else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4))
|
||||
end
|
||||
tags[tag] = v
|
||||
elseif typ == 7 then
|
||||
if d + count > se then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
tags[tag] = buffer.readstring(b, d, count)
|
||||
elseif typ == 6 or typ == 8 or typ == 9 then
|
||||
local v = {}
|
||||
local s = d
|
||||
local want = if typ == 6 then 1 else count
|
||||
if want > hsize then
|
||||
return nil, Err.new(Err.CORRUPT, "bad string count", q)
|
||||
end
|
||||
for _ = 1, want do
|
||||
local z = s
|
||||
while z < se and buffer.readu8(b, z) ~= 0 do
|
||||
z += 1
|
||||
end
|
||||
if z >= se then
|
||||
return nil, Err.new(Err.CORRUPT, "unterminated string", s)
|
||||
end
|
||||
table.insert(v, buffer.readstring(b, s, z - s))
|
||||
s = z + 1
|
||||
end
|
||||
tags[tag] = if typ == 6 then v[1] else v
|
||||
end
|
||||
end
|
||||
return tags, se
|
||||
end
|
||||
|
||||
-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
|
||||
local function files(tags: { [number]: any }): { any }
|
||||
local names: { string } = {}
|
||||
local bn, dn, di = tags[1117], tags[1118], tags[1116]
|
||||
if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then
|
||||
for i, base in bn do
|
||||
local d = dn[(di[i] or 0) + 1]
|
||||
names[i] = (if type(d) == "string" then d else "") .. base
|
||||
end
|
||||
elseif type(tags[1027]) == "table" then
|
||||
names = tags[1027]
|
||||
end
|
||||
local sizes = tags[5008] or tags[1028] or {}
|
||||
local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {}
|
||||
local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {}
|
||||
local out = {}
|
||||
for i, n in names do
|
||||
table.insert(out, {
|
||||
name = n,
|
||||
size = sizes[i] or 0,
|
||||
mode = modes[i] or 0,
|
||||
mtime = mtimes[i] or 0,
|
||||
link = if links[i] and links[i] ~= "" then links[i] else nil,
|
||||
user = users[i],
|
||||
group = groups[i],
|
||||
flags = flags[i] or 0,
|
||||
})
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function strip(name: string): string
|
||||
return (string.gsub(name, "^%.?/+", ""))
|
||||
end
|
||||
|
||||
-- the payload: decompressed, then its cpio entries by stripped name
|
||||
local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
|
||||
local n = e - p
|
||||
local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
|
||||
local raw: buffer?, err: any
|
||||
local m = if n >= 6 then buffer.readstring(b, p, 6) else ""
|
||||
if string.sub(m, 1, 2) == "\31\139" then
|
||||
raw, err = Deflate.gunzip(b, p, n)
|
||||
elseif m == "\253" .. "7zXZ\0" then
|
||||
raw, err = Lzma.xz(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 3) == "BZh" then
|
||||
raw, err = Bzip2.decompress(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 4) == "\40\181\47\253" then
|
||||
raw, err = Zstd.decompress(b, p, n, opts)
|
||||
elseif compressor == "lzma" then
|
||||
raw, err = Lzma.alone(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 5) == "07070" then
|
||||
raw = buffer.create(n)
|
||||
buffer.copy(raw :: buffer, 0, b, p, n)
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p)
|
||||
end
|
||||
if not raw then
|
||||
return nil, err
|
||||
end
|
||||
if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)")
|
||||
end
|
||||
local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries })
|
||||
if not list then
|
||||
return nil, cerr
|
||||
end
|
||||
local by = {}
|
||||
for _, ent in list do
|
||||
by[strip(ent.name)] = ent
|
||||
end
|
||||
return { buf = raw, by = by }, nil
|
||||
end
|
||||
|
||||
function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local b, base, e = r.buf, r.base, r.limit
|
||||
if e - base < 96 then
|
||||
return nil, Err.new(Err.TRUNCATED, "lead past the end", base)
|
||||
end
|
||||
if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad lead magic", base)
|
||||
end
|
||||
local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5)
|
||||
local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7))
|
||||
local leadName = buffer.readstring(b, base + 10, 66)
|
||||
leadName = string.match(leadName, "^[^%z]*") :: string
|
||||
if major < 3 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4)
|
||||
end
|
||||
local sig, sigEnd = header(b, base + 96, e)
|
||||
if not sig then
|
||||
return nil, sigEnd
|
||||
end
|
||||
local hp = base + (sigEnd - base + 7) // 8 * 8
|
||||
local tags, hEnd = header(b, hp, e)
|
||||
if not tags then
|
||||
return nil, hEnd
|
||||
end
|
||||
local a = Archive.new("rpm")
|
||||
local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } }
|
||||
for tag, key in NAMES do
|
||||
local v = tags[tag]
|
||||
if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value
|
||||
v = v[1]
|
||||
end
|
||||
info[key] = v
|
||||
end
|
||||
a.meta.rpm = info
|
||||
a.meta.source = { format = "rpm", compressor = info.payloadCompressor }
|
||||
if info.payloadFormat and info.payloadFormat ~= "cpio" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd)
|
||||
end
|
||||
local cache: any = nil
|
||||
local cacheErr: Err.Err? = nil
|
||||
local function entry(name: string): (any, Err.Err?)
|
||||
if not cache and not cacheErr then
|
||||
cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o)
|
||||
end
|
||||
if not cache then
|
||||
return nil, cacheErr
|
||||
end
|
||||
local ent = cache.by[name]
|
||||
if not ent then
|
||||
return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload")
|
||||
end
|
||||
return ent, nil
|
||||
end
|
||||
local list = files(tags)
|
||||
if #list > (o.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many files")
|
||||
end
|
||||
for _, f in list do
|
||||
if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then
|
||||
continue
|
||||
end
|
||||
local name = strip(f.name)
|
||||
local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0"
|
||||
local data = typ == "0" and f.size > 0
|
||||
Archive.put(a, {
|
||||
name = name,
|
||||
size = if data then f.size else 0,
|
||||
dir = typ == "5",
|
||||
mtime = f.mtime,
|
||||
mode = bit32.band(f.mode, 0xFFF),
|
||||
type = typ,
|
||||
link = if typ == "2" then f.link else nil,
|
||||
uname = f.user,
|
||||
gname = f.group,
|
||||
method = if info.payloadCompressor then info.payloadCompressor else "store",
|
||||
load = if data
|
||||
then function(): (buffer?, Err.Err?)
|
||||
local ent, err = entry(name)
|
||||
if not ent then
|
||||
return nil, err
|
||||
end
|
||||
local out = buffer.create(ent.size)
|
||||
buffer.copy(out, 0, cache.buf, ent.offset, ent.size)
|
||||
return out, nil
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
|
||||
function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local a, err = Rpm.decode(r, opts)
|
||||
if not a then
|
||||
return nil, err
|
||||
end
|
||||
local p = r.base + 96
|
||||
local _, sigEnd = header(r.buf, p, r.limit)
|
||||
local hp = r.base + (sigEnd - r.base + 7) // 8 * 8
|
||||
local _, hEnd = header(r.buf, hp, r.limit)
|
||||
local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {})
|
||||
if not pl then
|
||||
return nil, perr
|
||||
end
|
||||
return pl.buf, nil
|
||||
end
|
||||
|
||||
return Rpm
|
||||
@@ -0,0 +1,120 @@
|
||||
--!strict
|
||||
-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value
|
||||
-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() +
|
||||
-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which
|
||||
-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format).
|
||||
-- Not supported: sparse files, multi-volume archives.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Tar = require("@rosetta/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local TarFormat = {
|
||||
name = "tar",
|
||||
category = "archive",
|
||||
extensions = { "tar" },
|
||||
mime = { "application/x-tar" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function TarFormat.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 512 then
|
||||
return 0
|
||||
end
|
||||
if not Tar.valid(r.buf, r.pos) then
|
||||
return 0
|
||||
end
|
||||
return if r:peek(5, 257) == "ustar" then 0.95 else 0.6
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, at, n)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return TarFormat.encode(archive, opts)
|
||||
end
|
||||
|
||||
function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("tar", encode)
|
||||
for _, e in list do
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = e.size,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
mode = e.mode,
|
||||
uid = e.uid,
|
||||
gid = e.gid,
|
||||
uname = e.uname,
|
||||
gname = e.gname,
|
||||
type = e.type,
|
||||
link = e.link,
|
||||
method = "store",
|
||||
load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size),
|
||||
})
|
||||
end
|
||||
a.meta.source = { format = "tar" }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local list: { Tar.WriteEntry } = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local data: buffer? = nil
|
||||
if not e.dir and e.type ~= "1" and e.type ~= "2" then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
table.insert(list, {
|
||||
name = e.name,
|
||||
data = data,
|
||||
dir = e.dir,
|
||||
type = if type(e.type) == "string" and #e.type == 1 then e.type else nil,
|
||||
link = if type(e.link) == "string" then e.link else nil,
|
||||
mode = if type(e.mode) == "number" then e.mode else nil,
|
||||
uid = if type(e.uid) == "number" then e.uid else nil,
|
||||
gid = if type(e.gid) == "number" then e.gid else nil,
|
||||
uname = if type(e.uname) == "string" then e.uname else nil,
|
||||
gname = if type(e.gname) == "string" then e.gname else nil,
|
||||
mtime = if type(e.mtime) == "number" then e.mtime else nil,
|
||||
})
|
||||
end
|
||||
return Tar.write(list, opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write()
|
||||
function TarFormat.new(): any
|
||||
local a = Archive.new("tar", encode)
|
||||
a.meta.source = { format = "tar" }
|
||||
return a
|
||||
end
|
||||
|
||||
return TarFormat
|
||||
@@ -0,0 +1,276 @@
|
||||
--!strict
|
||||
-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin <mode> <name>" block of a
|
||||
-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode);
|
||||
-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each
|
||||
-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and
|
||||
-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils
|
||||
-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings
|
||||
-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Base64 = require("@rosetta/core/Base64")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Uu = {
|
||||
name = "uu",
|
||||
category = "archive",
|
||||
extensions = { "uu", "uue", "xxe", "b64" },
|
||||
mime = { "text/x-uuencode" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
|
||||
export type EncodeOptions = {
|
||||
variant: ("uu" | "xx" | "base64")?, -- default "uu"
|
||||
mode: number?, -- file mode when the entry has none (default 0o644)
|
||||
name: string?, -- the name of a buffer / string value (default "data")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
local XX_VALUE: { [number]: number } = {}
|
||||
for i = 1, 64 do
|
||||
XX_VALUE[string.byte(XX, i)] = i - 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Uu.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(4096)
|
||||
if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then
|
||||
return 0.9
|
||||
end
|
||||
if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the value of character c in a variant, or nil
|
||||
local function value(c: number, xx: boolean): number?
|
||||
if xx then
|
||||
return XX_VALUE[c]
|
||||
end
|
||||
if c >= 32 and c <= 96 then
|
||||
return bit32.band(c - 32, 63)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- does a data line fit the variant: every character valid and the length matching the count character
|
||||
local function fits(line: string, xx: boolean): boolean
|
||||
local n = value(string.byte(line, 1) or 0, xx)
|
||||
if not n then
|
||||
return false
|
||||
end
|
||||
local need = math.ceil(n / 3) * 4
|
||||
if #line - 1 < need or #line - 1 > need + 2 then
|
||||
return false
|
||||
end
|
||||
for i = 2, need + 1 do
|
||||
if not value(string.byte(line, i), xx) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line)
|
||||
local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?)
|
||||
local total = 0
|
||||
for _, l in lines do
|
||||
total += value(string.byte(l, 1) or 0, xx) or 0
|
||||
end
|
||||
if total > maxBytes then
|
||||
return nil, "limit: data larger than maxBytes"
|
||||
end
|
||||
local out = buffer.create(total)
|
||||
local o = 0
|
||||
for li, l in lines do
|
||||
local n = value(string.byte(l, 1) or 0, xx) or 0
|
||||
local p = 2
|
||||
local left = n
|
||||
while left > 0 do
|
||||
local a = value(string.byte(l, p) or 0, xx)
|
||||
local b = value(string.byte(l, p + 1) or 0, xx)
|
||||
local c = value(string.byte(l, p + 2) or 0, xx) or 0
|
||||
local d = value(string.byte(l, p + 3) or 0, xx) or 0
|
||||
if not a or not b then
|
||||
return nil, "bad character in line " .. li
|
||||
end
|
||||
local v = a * 262144 + b * 4096 + c * 64 + d
|
||||
for k = 2, 0, -1 do
|
||||
if left > 0 then
|
||||
buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255))
|
||||
o += 1
|
||||
left -= 1
|
||||
end
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
type Block = { name: string, mode: number, variant: string, data: buffer }
|
||||
|
||||
local function parse(text: string, maxBytes: number): ({ Block }?, string?)
|
||||
local lines = string.split(text, "\n")
|
||||
local blocks: { Block } = {}
|
||||
local i = 1
|
||||
while i <= #lines do
|
||||
local line = string.gsub(lines[i], "\r$", "")
|
||||
local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$")
|
||||
if not b64 then
|
||||
mode, name = string.match(line, "^begin ([0-7]+) (.+)$")
|
||||
end
|
||||
if mode and name then
|
||||
local body: { string } = {}
|
||||
local closed = false
|
||||
i += 1
|
||||
while i <= #lines do
|
||||
local l = string.gsub(lines[i], "\r$", "")
|
||||
if (b64 and l == "====") or (not b64 and l == "end") then
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
table.insert(body, l)
|
||||
i += 1
|
||||
end
|
||||
if not closed then
|
||||
return nil, "truncated: block " .. name .. " has no end line"
|
||||
end
|
||||
local data, variant
|
||||
if b64 then
|
||||
local d, err = Base64.decode(table.concat(body))
|
||||
if not d then
|
||||
return nil, "block " .. name .. ": " .. tostring(err)
|
||||
end
|
||||
data, variant = d, "base64"
|
||||
else
|
||||
-- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines
|
||||
local data_lines: { string } = {}
|
||||
for _, l in body do
|
||||
if l ~= "" then
|
||||
table.insert(data_lines, l)
|
||||
end
|
||||
end
|
||||
local uuOk, xxOk = true, true
|
||||
for _, l in data_lines do
|
||||
uuOk = uuOk and fits(l, false)
|
||||
xxOk = xxOk and fits(l, true)
|
||||
end
|
||||
local xx = xxOk and not uuOk
|
||||
if not uuOk and not xxOk then
|
||||
return nil, "block " .. name .. ": lines are neither uuencode nor xxencode"
|
||||
end
|
||||
local d, err = decodeLines(data_lines, xx, maxBytes)
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
data, variant = d, if xx then "xx" else "uu"
|
||||
end
|
||||
table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data })
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
if #blocks == 0 then
|
||||
return nil, "no begin line"
|
||||
end
|
||||
return blocks, nil
|
||||
end
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return Uu.encode(a, o)
|
||||
end
|
||||
|
||||
function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30)
|
||||
if not blocks then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
local a = Archive.new("uu", encoder)
|
||||
for _, b in blocks do
|
||||
Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data })
|
||||
end
|
||||
a.meta.stream = #a:list() == 1
|
||||
a.meta.source = { format = "uu", variant = blocks[1].variant }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function encodeLines(data: buffer, xx: boolean, out: { string })
|
||||
local n = buffer.len(data)
|
||||
local function ch(v: number): string
|
||||
if xx then
|
||||
return string.sub(XX, v + 1, v + 1)
|
||||
end
|
||||
return if v == 0 then "`" else string.char(v + 32)
|
||||
end
|
||||
local p = 0
|
||||
while p < n do
|
||||
local len = math.min(45, n - p)
|
||||
local parts = { ch(len) }
|
||||
for q = p, p + len - 1, 3 do
|
||||
local b0 = buffer.readu8(data, q)
|
||||
local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0
|
||||
local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0
|
||||
local v = b0 * 65536 + b1 * 256 + b2
|
||||
table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63)))
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
p += len
|
||||
end
|
||||
table.insert(out, ch(0))
|
||||
end
|
||||
|
||||
function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local variant = o.variant or "uu"
|
||||
if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then
|
||||
return nil, Err.new(Err.ARG, "variant must be uu, xx or base64")
|
||||
end
|
||||
local files, err = Archive.files(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
if #files == 0 then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local out: { string } = {}
|
||||
for _, f in files do
|
||||
if string.find(f.name, "[\r\n]") then
|
||||
return nil, Err.new(Err.ARG, "file names may not contain line breaks")
|
||||
end
|
||||
local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4)
|
||||
local m = string.format("%o", bit32.band(mode, 0xFFF))
|
||||
if variant == "base64" then
|
||||
table.insert(out, "begin-base64 " .. m .. " " .. f.name)
|
||||
local s = Base64.encode(f.data)
|
||||
for p = 1, #s, 60 do
|
||||
table.insert(out, string.sub(s, p, p + 59))
|
||||
end
|
||||
table.insert(out, "====")
|
||||
else
|
||||
table.insert(out, "begin " .. m .. " " .. f.name)
|
||||
encodeLines(f.data, variant == "xx", out)
|
||||
table.insert(out, "end")
|
||||
end
|
||||
end
|
||||
return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant })
|
||||
function Uu.new(): any
|
||||
local a = Archive.new("uu", encoder)
|
||||
a.meta.source = { format = "uu" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Uu
|
||||
@@ -0,0 +1,317 @@
|
||||
--!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("@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?, -- 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 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
|
||||
-- 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
|
||||
@@ -0,0 +1,441 @@
|
||||
--!strict
|
||||
-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS,
|
||||
-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a
|
||||
-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with
|
||||
-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the
|
||||
-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one
|
||||
-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z
|
||||
-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not
|
||||
-- supported.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Polygon = require("@rosetta/codecs/model/Polygon")
|
||||
|
||||
local Map = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Lump = { buf: buffer, at: number, size: number }
|
||||
export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? }
|
||||
export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? }
|
||||
export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number }
|
||||
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number }
|
||||
export type MapData = {
|
||||
format: "doom" | "hexen",
|
||||
things: { Thing },
|
||||
linedefs: { Linedef },
|
||||
sidedefs: { Sidedef },
|
||||
vertices: { number }, -- x1, y1, x2, y2, ...
|
||||
sectors: { Sector },
|
||||
}
|
||||
-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows
|
||||
export type Textures = {
|
||||
size: (kind: string, name: string) -> (number?, number?),
|
||||
image: ((kind: string, name: string) -> Types.Image?)?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ parse
|
||||
local function name8(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
local function side(v: number): number?
|
||||
return if v == 0xFFFF then nil else v + 1
|
||||
end
|
||||
|
||||
-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump)
|
||||
function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?)
|
||||
for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do
|
||||
if not lumps[k] then
|
||||
return nil, "map has no " .. k
|
||||
end
|
||||
end
|
||||
local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} }
|
||||
local v = lumps.VERTEXES
|
||||
for i = 0, v.size // 4 - 1 do
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4))
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2))
|
||||
end
|
||||
local s = lumps.SECTORS
|
||||
for i = 0, s.size // 26 - 1 do
|
||||
local o = s.at + i * 26
|
||||
table.insert(m.sectors, {
|
||||
floor = readi16(s.buf, o),
|
||||
ceiling = readi16(s.buf, o + 2),
|
||||
floorFlat = name8(s.buf, o + 4),
|
||||
ceilingFlat = name8(s.buf, o + 12),
|
||||
light = readi16(s.buf, o + 20),
|
||||
special = readu16(s.buf, o + 22),
|
||||
tag = readu16(s.buf, o + 24),
|
||||
})
|
||||
end
|
||||
local sd = lumps.SIDEDEFS
|
||||
for i = 0, sd.size // 30 - 1 do
|
||||
local o = sd.at + i * 30
|
||||
table.insert(m.sidedefs, {
|
||||
xoff = readi16(sd.buf, o),
|
||||
yoff = readi16(sd.buf, o + 2),
|
||||
upper = name8(sd.buf, o + 4),
|
||||
lower = name8(sd.buf, o + 12),
|
||||
middle = name8(sd.buf, o + 20),
|
||||
sector = readu16(sd.buf, o + 28) + 1,
|
||||
})
|
||||
end
|
||||
local l = lumps.LINEDEFS
|
||||
local ls = if hexen then 16 else 14
|
||||
for i = 0, l.size // ls - 1 do
|
||||
local o = l.at + i * ls
|
||||
local b = l.buf
|
||||
if hexen then
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu8(b, o + 6),
|
||||
args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) },
|
||||
front = side(readu16(b, o + 12)),
|
||||
back = side(readu16(b, o + 14)),
|
||||
})
|
||||
else
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu16(b, o + 6),
|
||||
tag = readu16(b, o + 8),
|
||||
front = side(readu16(b, o + 10)),
|
||||
back = side(readu16(b, o + 12)),
|
||||
})
|
||||
end
|
||||
end
|
||||
local t = lumps.THINGS
|
||||
if t then
|
||||
local ts = if hexen then 20 else 10
|
||||
for i = 0, t.size // ts - 1 do
|
||||
local o = t.at + i * ts
|
||||
local b = t.buf
|
||||
if hexen then
|
||||
table.insert(m.things, {
|
||||
tid = readi16(b, o),
|
||||
x = readi16(b, o + 2),
|
||||
y = readi16(b, o + 4),
|
||||
z = readi16(b, o + 6),
|
||||
angle = readi16(b, o + 8),
|
||||
type = readu16(b, o + 10),
|
||||
flags = readu16(b, o + 12),
|
||||
special = readu8(b, o + 14),
|
||||
args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) },
|
||||
})
|
||||
else
|
||||
table.insert(m.things, {
|
||||
x = readi16(b, o),
|
||||
y = readi16(b, o + 2),
|
||||
angle = readi16(b, o + 4),
|
||||
type = readu16(b, o + 6),
|
||||
flags = readu16(b, o + 8),
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sector outlines
|
||||
-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1;
|
||||
-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks;
|
||||
-- chains that do not close are dropped
|
||||
local function loops(m: MapData): { [number]: { { number } } }
|
||||
local edges: { [number]: { { number } } } = {}
|
||||
local nv = #m.vertices // 2
|
||||
local function add(sec: number, a: number, b: number)
|
||||
local e = edges[sec] or {}
|
||||
edges[sec] = e
|
||||
table.insert(e, { a, b })
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local fs = ld.front and m.sidedefs[ld.front]
|
||||
local bs = ld.back and m.sidedefs[ld.back]
|
||||
local f = fs and fs.sector
|
||||
local b = bs and bs.sector
|
||||
if f ~= b then
|
||||
if f and m.sectors[f] then
|
||||
add(f, ld.v1, ld.v2)
|
||||
end
|
||||
if b and m.sectors[b] then
|
||||
add(b, ld.v2, ld.v1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local V = m.vertices
|
||||
local out: { [number]: { { number } } } = {}
|
||||
for sec, list in edges do
|
||||
local from: { [number]: { number } } = {}
|
||||
for i, e in list do
|
||||
local l = from[e[1]] or {}
|
||||
from[e[1]] = l
|
||||
table.insert(l, i)
|
||||
end
|
||||
local used: { [number]: boolean } = {}
|
||||
local res: { { number } } = {}
|
||||
for start = 1, #list do
|
||||
if not used[start] then
|
||||
used[start] = true
|
||||
local loop = { list[start][1] }
|
||||
local cur = start
|
||||
local closed = false
|
||||
for _ = 1, #list do
|
||||
local e = list[cur]
|
||||
local at = e[2]
|
||||
if at == loop[1] then
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
table.insert(loop, at)
|
||||
local cands = from[at]
|
||||
local best, bestT = nil :: number?, math.huge
|
||||
if cands then
|
||||
local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2]
|
||||
for _, c in cands do
|
||||
if not used[c] then
|
||||
local n2 = list[c][2]
|
||||
local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2]
|
||||
local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy)
|
||||
if t < bestT then
|
||||
best, bestT = c, t
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if not best then
|
||||
break
|
||||
end
|
||||
used[best] = true
|
||||
cur = best
|
||||
end
|
||||
if closed and #loop >= 3 then
|
||||
table.insert(res, loop)
|
||||
end
|
||||
end
|
||||
end
|
||||
out[sec] = res
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #loop
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2]
|
||||
local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2]
|
||||
if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } }
|
||||
|
||||
local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4
|
||||
|
||||
-- scene(m, tex, name) -> Scene
|
||||
function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
|
||||
local batches: { [string]: Batch } = {}
|
||||
local order: { string } = {}
|
||||
local function batch(kind: string, tname: string): Batch
|
||||
local key = kind .. ":" .. tname
|
||||
local b = batches[key]
|
||||
if not b then
|
||||
b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} }
|
||||
batches[key] = b
|
||||
table.insert(order, key)
|
||||
end
|
||||
return b
|
||||
end
|
||||
local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number)
|
||||
local p, n, t = b.pos, b.nrm, b.uv
|
||||
p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z
|
||||
n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz
|
||||
t[#t + 1], t[#t + 2] = u, v
|
||||
end
|
||||
local V = m.vertices
|
||||
local nv = #V // 2
|
||||
-- floors and ceilings
|
||||
local secLoops = loops(m)
|
||||
for sec, ls in secLoops do
|
||||
local s = m.sectors[sec]
|
||||
local flat: { { number } } = {}
|
||||
for li, loop in ls do
|
||||
local f: { number } = {}
|
||||
for _, vi in loop do
|
||||
table.insert(f, V[vi * 2 - 1])
|
||||
table.insert(f, V[vi * 2])
|
||||
end
|
||||
flat[li] = f
|
||||
end
|
||||
local tris = Polygon.triangulate(flat)
|
||||
for pass = 1, 2 do
|
||||
local tname = if pass == 1 then s.floorFlat else s.ceilingFlat
|
||||
local fw, fh = tex.size("flat", tname)
|
||||
local w, h = fw or 64, fh or 64
|
||||
local z = if pass == 1 then s.floor else s.ceiling
|
||||
local b = batch("flat", tname)
|
||||
local nz = if pass == 1 then 1 else -1
|
||||
for k = 1, #tris, 6 do
|
||||
for c = 0, 2 do
|
||||
local cc = if pass == 1 then c else 2 - c
|
||||
local loop = ls[tris[k + cc * 2]]
|
||||
local vi = loop[tris[k + cc * 2 + 1]]
|
||||
local x, y = V[vi * 2 - 1], V[vi * 2]
|
||||
vert(b, x, y, z, 0, 0, nz, x / w, -y / h)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- walls
|
||||
local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number)
|
||||
if tname == "-" or tname == "" or zt <= zb then
|
||||
return
|
||||
end
|
||||
local tw, th = tex.size("texture", tname)
|
||||
local w, h = tw or 64, th or 128
|
||||
local b = batch("texture", tname)
|
||||
local dx, dy = x2 - x1, y2 - y1
|
||||
local l = math.sqrt(dx * dx + dy * dy)
|
||||
local nx, ny = dy / l, -dx / l
|
||||
local u0, u1 = xoff / w, (xoff + len) / w
|
||||
local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zb, nx, ny, 0, u1, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zt, nx, ny, 0, u0, vt)
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2]
|
||||
local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2)
|
||||
for sideN = 1, 2 do
|
||||
local sdi = if sideN == 1 then ld.front else ld.back
|
||||
local odi = if sideN == 1 then ld.back else ld.front
|
||||
local sd = sdi and m.sidedefs[sdi]
|
||||
local me = sd and m.sectors[sd.sector]
|
||||
if sd and me then
|
||||
local x1, y1, x2, y2 = ax, ay, bx, by
|
||||
if sideN == 2 then
|
||||
x1, y1, x2, y2 = bx, by, ax, ay
|
||||
end
|
||||
local od = odi and m.sidedefs[odi]
|
||||
local other = od and m.sectors[od.sector]
|
||||
if not other then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling
|
||||
quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
else
|
||||
if other.floor > me.floor then
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor
|
||||
quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY"
|
||||
if other.ceiling < me.ceiling and not sky then
|
||||
local th = select(2, tex.size("texture", sd.upper)) or 128
|
||||
local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th
|
||||
quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling)
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi
|
||||
quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the scene
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local mesh: Types.Mesh = { name = name, primitives = {} }
|
||||
local texIndex: { [string]: number } = {}
|
||||
for _, key in order do
|
||||
local b = batches[key]
|
||||
local n = #b.pos // 3
|
||||
if n > 0 then
|
||||
local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
|
||||
for i = 1, n * 3 do
|
||||
writef32(pb, (i - 1) * 4, b.pos[i])
|
||||
writef32(nb, (i - 1) * 4, b.nrm[i])
|
||||
end
|
||||
for i = 1, n * 2 do
|
||||
writef32(ub, (i - 1) * 4, b.uv[i])
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
writeu32(ib, i * 4, i)
|
||||
end
|
||||
local ti = texIndex[key]
|
||||
if not ti then
|
||||
table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } })
|
||||
ti = #scene.textures
|
||||
texIndex[key] = ti
|
||||
end
|
||||
local mat = Scene.material(b.name)
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = ti }
|
||||
mat.extras = { wad = { kind = b.kind } }
|
||||
table.insert(scene.materials, mat)
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(pb, "f32", 3, n),
|
||||
NORMAL = Scene.accessor(nb, "f32", 3, n),
|
||||
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, n),
|
||||
mode = "triangles" :: any,
|
||||
material = #scene.materials,
|
||||
extras = { wad = { kind = b.kind, texture = b.name } },
|
||||
})
|
||||
end
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
scene.nodes[1] = { name = name, children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
-- things, on the floor of the sector under them
|
||||
for i, th in m.things do
|
||||
local z = th.z or 0
|
||||
for sec, ls in secLoops do
|
||||
local inside = false
|
||||
for _, loop in ls do
|
||||
if insideLoop(V, loop, th.x, th.y) then
|
||||
inside = not inside
|
||||
end
|
||||
end
|
||||
if inside then
|
||||
z += m.sectors[sec].floor
|
||||
break
|
||||
end
|
||||
end
|
||||
local a = math.rad(th.angle) / 2
|
||||
table.insert(scene.nodes, {
|
||||
name = "thing " .. i,
|
||||
children = {},
|
||||
translation = { th.x, th.y, z },
|
||||
rotation = { 0, 0, math.sin(a), math.cos(a) },
|
||||
extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } },
|
||||
})
|
||||
table.insert(scene.nodes[1].children, #scene.nodes)
|
||||
end
|
||||
return scene
|
||||
end
|
||||
|
||||
return Map
|
||||
@@ -0,0 +1,109 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column
|
||||
-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of
|
||||
-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative)
|
||||
-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip).
|
||||
-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's
|
||||
-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end.
|
||||
local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Picture = {}
|
||||
|
||||
-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it)
|
||||
function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number)
|
||||
if n < 8 then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
local w, h = readu16(b, at), readu16(b, at + 2)
|
||||
if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local o = readu32(b, at + 8 + x * 4)
|
||||
if o < 8 + w * 4 or o >= n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
end
|
||||
return w, h, readi16(b, at + 4), readi16(b, at + 6)
|
||||
end
|
||||
|
||||
-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed)
|
||||
function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?)
|
||||
local stop = at + n
|
||||
for x = 0, w - 1 do
|
||||
local p = at + readu32(b, at + 8 + x * 4)
|
||||
local top = -1
|
||||
while true do
|
||||
if p >= stop then
|
||||
return false, "column " .. x .. " runs past the end"
|
||||
end
|
||||
local delta = readu8(b, p)
|
||||
if delta == 255 then
|
||||
break
|
||||
end
|
||||
if p + 3 > stop then
|
||||
return false, "post header past the end"
|
||||
end
|
||||
local len = readu8(b, p + 1)
|
||||
top = if delta <= top then top + delta else delta
|
||||
if p + 4 + len > stop then
|
||||
return false, "post past the end"
|
||||
end
|
||||
local src = p + 3
|
||||
for k = 0, len - 1 do
|
||||
local y = top + k
|
||||
if y < h then
|
||||
writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4))
|
||||
end
|
||||
end
|
||||
p += 4 + len
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits)
|
||||
function Picture.flatSize(n: number): (number?, number)
|
||||
if n == 4096 then
|
||||
return 64, 64
|
||||
elseif n == 4160 then
|
||||
return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding
|
||||
elseif n == 8192 then
|
||||
return 64, 128
|
||||
elseif n == 12800 then
|
||||
return 64, 200 -- Heretic / Hexen scrolling flats
|
||||
end
|
||||
local s = math.floor(math.sqrt(n) + 0.5)
|
||||
if s * s == n and s > 0 then
|
||||
return s, s
|
||||
end
|
||||
if n > 0 and n % 64 == 0 then
|
||||
return 64, n // 64
|
||||
end
|
||||
return nil, 0
|
||||
end
|
||||
|
||||
-- flat(b, at, w, h, pal, out): raw indexes, row by row
|
||||
function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer)
|
||||
for i = 0, w * h - 1 do
|
||||
writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4))
|
||||
end
|
||||
end
|
||||
|
||||
-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy),
|
||||
-- clipped (composite wall textures from patches)
|
||||
function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number)
|
||||
local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1
|
||||
for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do
|
||||
local so, d = y * sw, (y + oy) * dw + ox
|
||||
for x = x0, x1 do
|
||||
local v = readu32(src, (so + x) * 4)
|
||||
if v ~= 0 then
|
||||
writeu32(dst, (d + x) * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Picture
|
||||
@@ -0,0 +1,474 @@
|
||||
--!strict
|
||||
-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the
|
||||
-- standard Archive and written from any Archive value, plus the lumps as game data:
|
||||
-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map
|
||||
-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer
|
||||
-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image
|
||||
-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0)
|
||||
-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES)
|
||||
-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts)
|
||||
-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene
|
||||
-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map)
|
||||
-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps
|
||||
-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again
|
||||
-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom
|
||||
-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken.
|
||||
-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant,
|
||||
-- big-endian (Jaguar) WADs, compressed Jaguar lumps.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
local Pixels = require("@rosetta/codecs/image/Pixels")
|
||||
local Picture = require("@rosetta/archive/wad/Picture")
|
||||
local Map = require("@rosetta/archive/wad/Map")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wad = {
|
||||
name = "wad",
|
||||
category = "archive",
|
||||
extensions = { "wad" },
|
||||
mime = { "application/x-doom" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD"
|
||||
export type Lump = {
|
||||
name: string, -- the lump name as stored (upper case)
|
||||
entry: string, -- the Archive entry name
|
||||
index: number, -- 1-based position in the directory
|
||||
offset: number,
|
||||
size: number,
|
||||
namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers)
|
||||
map: string?, -- the map this lump belongs to
|
||||
marker: boolean?, -- a zero-size marker (F_START, MAP01, ...)
|
||||
}
|
||||
export type MapOptions = {
|
||||
textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true)
|
||||
palette: number?, -- PLAYPAL palette index (default 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAP_LUMPS: { [string]: boolean } = {
|
||||
THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true,
|
||||
SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true,
|
||||
MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true,
|
||||
}
|
||||
-- namespace markers: first letter(s) before _START / _END
|
||||
local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches",
|
||||
P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps",
|
||||
TX = "textures", HI = "hires", A = "acs", V = "voices" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Wad.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 then
|
||||
return 0
|
||||
end
|
||||
local m = r:peek(4)
|
||||
if m ~= "IWAD" and m ~= "PWAD" then
|
||||
return 0
|
||||
end
|
||||
return 0.9
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Wad.encode(archive, opts)
|
||||
end
|
||||
|
||||
local function nameAt(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local kind = r:string(4)
|
||||
local count, dirOfs = r:i32le(), r:i32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if count < 0 or dirOfs < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "negative directory field", 4)
|
||||
end
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many lumps: " .. count)
|
||||
end
|
||||
if dirOfs + count * 16 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 8)
|
||||
end
|
||||
local a = Archive.new("wad", encode)
|
||||
local lumps: { Lump } = {}
|
||||
local seen: { [string]: number } = {}
|
||||
local b = r.buf
|
||||
local ns: string? = nil
|
||||
local map: string? = nil
|
||||
local udmf = false
|
||||
for i = 0, count - 1 do
|
||||
local o = r.base + dirOfs + i * 16
|
||||
local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4)
|
||||
local name = nameAt(b, o + 8)
|
||||
if n < 0 or at < 0 or (n > 0 and at + n > size) then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16)
|
||||
end
|
||||
-- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map
|
||||
local nextName = if i + 1 < count then nameAt(b, o + 24) else ""
|
||||
local inMap: string? = nil
|
||||
if map then
|
||||
if udmf then
|
||||
inMap = map
|
||||
if name == "ENDMAP" then
|
||||
map = nil
|
||||
end
|
||||
elseif MAP_LUMPS[name] then
|
||||
inMap = map
|
||||
else
|
||||
map = nil
|
||||
end
|
||||
end
|
||||
local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP")
|
||||
if isMapMarker then
|
||||
map, udmf = name, nextName == "TEXTMAP"
|
||||
end
|
||||
-- namespaces
|
||||
local marker: boolean = false
|
||||
local pre = string.match(name, "^(%w+)_START$")
|
||||
local post = string.match(name, "^(%w+)_END$")
|
||||
if pre and NAMESPACES[pre] then
|
||||
ns = NAMESPACES[pre]
|
||||
marker = true
|
||||
elseif post and NAMESPACES[post] then
|
||||
ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil
|
||||
marker = true
|
||||
end
|
||||
local entry = if inMap then inMap .. "/" .. name else name
|
||||
local k = seen[entry]
|
||||
if k then
|
||||
k += 1
|
||||
seen[entry] = k
|
||||
entry = entry .. "~" .. k
|
||||
else
|
||||
seen[entry] = 1
|
||||
end
|
||||
local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil }
|
||||
table.insert(lumps, lump)
|
||||
Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) })
|
||||
end
|
||||
a.meta.source = { format = "wad", type = kind, lumps = count }
|
||||
a.meta.wad = { lumps = lumps, buf = b, base = r.base }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Wad.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 kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD"
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.ARG, "type must be IWAD or PWAD")
|
||||
end
|
||||
local list: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name
|
||||
base = string.upper((string.gsub(base, "~%d+$", "")))
|
||||
if #base > 8 or #base == 0 then
|
||||
return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name)
|
||||
end
|
||||
table.insert(list, { name = base, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(kind)
|
||||
w:u32le(#list)
|
||||
w:u32le(0)
|
||||
local offs: { number } = {}
|
||||
for i, l in list do
|
||||
offs[i] = w:tell()
|
||||
w:bytes(l.data)
|
||||
end
|
||||
local dirOfs = w:tell()
|
||||
for i, l in list do
|
||||
w:u32le(offs[i])
|
||||
w:u32le(buffer.len(l.data))
|
||||
w:string(l.name)
|
||||
w:fill(0, 8 - #l.name)
|
||||
end
|
||||
w:setU32le(8, dirOfs)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
local function info(a: any): any
|
||||
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil
|
||||
end
|
||||
|
||||
-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given
|
||||
local function find(w: any, name: string, ns: string?): Lump?
|
||||
local up = string.upper(name)
|
||||
local best: Lump? = nil
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and not l.map then
|
||||
if ns == nil or l.namespace == ns then
|
||||
best = l
|
||||
elseif not best then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
if best and ns and best.namespace ~= ns then
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and l.namespace == ns then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write()
|
||||
function Wad.new(kind: ("IWAD" | "PWAD")?): any
|
||||
local a = Archive.new("wad", encode)
|
||||
a.meta.source = { format = "wad", type = kind or "PWAD" }
|
||||
return a
|
||||
end
|
||||
|
||||
-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD)
|
||||
function Wad.lumps(a: any): { Lump }?
|
||||
local w = info(a)
|
||||
return w and w.lumps
|
||||
end
|
||||
|
||||
-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err
|
||||
function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local l = find(w, "PLAYPAL")
|
||||
local i = index or 0
|
||||
if not l or l.size < (i + 1) * 768 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i)
|
||||
end
|
||||
return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil
|
||||
end
|
||||
|
||||
-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic)
|
||||
-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding.
|
||||
function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local kind = opts and opts.kind
|
||||
local l = find(w, name, if kind == "flat" then "flats" else nil)
|
||||
if not l then
|
||||
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
|
||||
end
|
||||
local pal, perr = Wad.palette(a, opts and opts.palette)
|
||||
if not pal then
|
||||
return nil, perr
|
||||
end
|
||||
local at = w.base + l.offset
|
||||
local pw, ph, left, top = Picture.header(w.buf, at, l.size)
|
||||
local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw))
|
||||
if asFlat then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
if not fw then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat")
|
||||
end
|
||||
local img = Types.Image.new(fw, fh)
|
||||
Picture.flat(w.buf, at, fw, fh, pal, img.pixels)
|
||||
img.meta.source = { format = "wad", kind = "flat", lump = l.name }
|
||||
return img, nil
|
||||
end
|
||||
if not pw then
|
||||
return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture")
|
||||
end
|
||||
local img = Types.Image.new(pw, ph)
|
||||
local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph)
|
||||
if not ok then
|
||||
return nil, Err.from(msg, l.offset)
|
||||
end
|
||||
img.meta.offset = { left, top }
|
||||
img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } }
|
||||
local function textureDefs(w: any): { [string]: any }
|
||||
if w.textures then
|
||||
return w.textures
|
||||
end
|
||||
local defs: { [string]: any } = {}
|
||||
w.textures = defs
|
||||
local pn = find(w, "PNAMES")
|
||||
local names: { string } = {}
|
||||
if pn and pn.size >= 4 then
|
||||
local at = w.base + pn.offset
|
||||
local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8)
|
||||
for i = 0, n - 1 do
|
||||
names[i + 1] = nameAt(w.buf, at + 4 + i * 8)
|
||||
end
|
||||
end
|
||||
for _, tl in { "TEXTURE1", "TEXTURE2" } do
|
||||
local l = find(w, tl)
|
||||
if l and l.size >= 4 then
|
||||
local r = Bytes.reader(w.buf, w.base + l.offset, l.size)
|
||||
local n = r:i32le()
|
||||
if n > 0 and n * 4 <= l.size - 4 then
|
||||
for i = 0, n - 1 do
|
||||
r:seek(4 + i * 4)
|
||||
local o = r:i32le()
|
||||
if o > 0 and o + 22 <= l.size then
|
||||
r:seek(o)
|
||||
local tname = string.upper(r:fixed(8))
|
||||
r:skip(4)
|
||||
local tw, th = r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
local pc = r:i16le()
|
||||
local patches = {}
|
||||
for _ = 1, math.max(0, pc) do
|
||||
local px, py, pi = r:i16le(), r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
if names[pi + 1] then
|
||||
table.insert(patches, { x = px, y = py, patch = names[pi + 1] })
|
||||
end
|
||||
end
|
||||
if not r.err and tw > 0 and th > 0 and defs[tname] == nil then
|
||||
defs[tname] = { width = tw, height = th, patches = patches }
|
||||
end
|
||||
r.err = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return defs
|
||||
end
|
||||
|
||||
-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette)
|
||||
function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local def = textureDefs(w)[string.upper(name)]
|
||||
if not def then
|
||||
return nil, Err.new(Err.ARG, "no texture named " .. tostring(name))
|
||||
end
|
||||
if def.width * def.height > 4096 * 4096 then
|
||||
return nil, Err.new(Err.LIMIT, "texture too big")
|
||||
end
|
||||
local img = Types.Image.new(def.width, def.height)
|
||||
for _, p in def.patches do
|
||||
local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" })
|
||||
if pimg then
|
||||
Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- maps(a) -> { map names } in file order
|
||||
function Wad.maps(a: any): { string }
|
||||
local w = info(a)
|
||||
local out: { string } = {}
|
||||
if w then
|
||||
local seen: { [string]: boolean } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map and not seen[l.map] then
|
||||
seen[l.map] = true
|
||||
table.insert(out, l.map)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references)
|
||||
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local up = string.upper(name)
|
||||
local lumps: { [string]: Map.Lump } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map == up and lumps[l.name] == nil then
|
||||
lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size }
|
||||
end
|
||||
end
|
||||
if not next(lumps) then
|
||||
return nil, Err.new(Err.ARG, "no map named " .. tostring(name))
|
||||
end
|
||||
if lumps.TEXTMAP then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps")
|
||||
end
|
||||
local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
|
||||
if not m then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and
|
||||
-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes
|
||||
-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData
|
||||
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
|
||||
local m, err = Wad.mapData(a, name)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
local w = info(a)
|
||||
local defs = textureDefs(w)
|
||||
local images = not (opts and opts.textures == false)
|
||||
local cache: { [string]: any } = {}
|
||||
local pal = opts and opts.palette
|
||||
local function image(kind: string, tname: string): Types.Image?
|
||||
local key = kind .. ":" .. tname
|
||||
local c = cache[key]
|
||||
if c == nil then
|
||||
local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal })
|
||||
c = img or false
|
||||
cache[key] = c
|
||||
end
|
||||
return if c then c else nil
|
||||
end
|
||||
local tex: Map.Textures = {
|
||||
size = function(kind: string, tname: string): (number?, number?)
|
||||
if kind == "texture" then
|
||||
local d = defs[tname]
|
||||
if d then
|
||||
return d.width, d.height
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
local l = find(w, tname, "flats")
|
||||
if l then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
return fw, fh
|
||||
end
|
||||
return nil, nil
|
||||
end,
|
||||
image = if images then image else nil,
|
||||
}
|
||||
local scene = Map.scene(m, tex, string.upper(name))
|
||||
scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Wad
|
||||
@@ -0,0 +1,101 @@
|
||||
--!strict
|
||||
-- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") files, read as single-stream archives holding one
|
||||
-- entry (the decompressed data). Built on codecs/compress/Lzma. Supports: concatenated streams, stream padding, every block
|
||||
-- layout, checks none / CRC-32 / CRC-64 (verified; SHA-256 is not verified), filters LZMA2, delta and the BCJ filters
|
||||
-- x86 / PowerPC / ARM / ARM-Thumb / SPARC / ARM64. Not supported: writing, IA-64 / RISC-V filters.
|
||||
-- The entry is named after the file (opts.name without .xz / .lzma; .txz -> .tar), else "data". meta.stream = true:
|
||||
-- the api unwraps an inner archive (a .tar.xz loads as the tar).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Lzma = require("@rosetta/codecs/compress/Lzma")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Xz = {
|
||||
name = "xz",
|
||||
category = "archive",
|
||||
extensions = { "xz", "txz", "lzma" },
|
||||
mime = { "application/x-xz", "application/x-lzma" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, stream = true, filters = { "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local XZ_MAGIC = "\253" .. "7zXZ\0"
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
-- .lzma files have no magic: props byte < 225 (0x5D for every preset), a dictionary size of 2^n or 2^n + 2^(n-1),
|
||||
-- a size of -1 or under 2^40, and a 0 range coder byte
|
||||
local function aloneScore(r: Bytes.Reader): number
|
||||
local h = r:peek(14)
|
||||
if #h < 14 then
|
||||
return 0
|
||||
end
|
||||
local d = string.byte(h, 1)
|
||||
if d >= 225 or string.byte(h, 14) ~= 0 then
|
||||
return 0
|
||||
end
|
||||
local dict = string.byte(h, 2) + string.byte(h, 3) * 256 + string.byte(h, 4) * 65536 + string.byte(h, 5) * 16777216
|
||||
local okDict = false
|
||||
for n = 12, 31 do
|
||||
if dict == 2 ^ n or (n < 31 and dict == 2 ^ n + 2 ^ (n - 1)) then
|
||||
okDict = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not okDict then
|
||||
return 0
|
||||
end
|
||||
local s = string.sub(h, 6, 13)
|
||||
if s ~= string.rep("\255", 8) and (string.byte(h, 11) ~= 0 or string.byte(h, 12) ~= 0 or string.byte(h, 13) ~= 0) then
|
||||
return 0
|
||||
end
|
||||
return if d == 0x5D then 0.4 else 0.2
|
||||
end
|
||||
|
||||
function Xz.sniff(r: Bytes.Reader): number
|
||||
if r:peek(6) == XZ_MAGIC then
|
||||
return 1
|
||||
end
|
||||
return aloneScore(r)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Xz.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, res
|
||||
local method
|
||||
if r:peek(6) == XZ_MAGIC then
|
||||
out, res = Lzma.xz(r.buf, r.base, n, o)
|
||||
method = "lzma2"
|
||||
else
|
||||
out, res = Lzma.alone(r.buf, r.base, n, o)
|
||||
method = "lzma"
|
||||
end
|
||||
if not out then
|
||||
return nil, res
|
||||
end
|
||||
local a = Archive.new("xz")
|
||||
a.meta.stream = true
|
||||
a.meta.container = if method == "lzma" then "lzma" else "xz"
|
||||
Archive.put(a, {
|
||||
name = Archive.streamName(o, Xz.extensions),
|
||||
size = buffer.len(out),
|
||||
compressedSize = n,
|
||||
method = method,
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Xz
|
||||
@@ -0,0 +1,277 @@
|
||||
--!strict
|
||||
-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive:
|
||||
-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart
|
||||
-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified
|
||||
-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a
|
||||
-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one
|
||||
-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space
|
||||
-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc32 = require("@rosetta/core/Crc32")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Yenc = {
|
||||
name = "yenc",
|
||||
category = "archive",
|
||||
extensions = { "yenc", "ync" },
|
||||
mime = { "application/x-yenc" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, multipart = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
|
||||
export type EncodeOptions = {
|
||||
line: number?, -- characters per line (default 128)
|
||||
name: string?, -- the name of a buffer / string value (default "data")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Yenc.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(4096)
|
||||
if string.match(head, "^=ybegin ") then
|
||||
return 0.95
|
||||
end
|
||||
return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- key=value fields of a keyword line; name= runs to the end of the line
|
||||
local function fields(line: string): { [string]: string }
|
||||
local f: { [string]: string } = {}
|
||||
local s, name = string.match(line, "^(.-)name=(.*)$")
|
||||
if s then
|
||||
f.name = string.gsub(name :: string, "%s+$", "")
|
||||
line = s
|
||||
end
|
||||
for k, v in string.gmatch(line, "(%w+)=(%S+)") do
|
||||
f[k] = v
|
||||
end
|
||||
return f
|
||||
end
|
||||
|
||||
-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out)
|
||||
local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number
|
||||
local lim = buffer.len(out)
|
||||
local esc = false
|
||||
for p = i, j - 1 do
|
||||
local c = buffer.readu8(src, p)
|
||||
if c == 13 or c == 10 then
|
||||
continue
|
||||
end
|
||||
if c == 61 and not esc then
|
||||
esc = true
|
||||
continue
|
||||
end
|
||||
if esc then
|
||||
c -= 64
|
||||
esc = false
|
||||
end
|
||||
if o < lim then
|
||||
buffer.writeu8(out, o, (c - 42) % 256)
|
||||
end
|
||||
o += 1
|
||||
end
|
||||
return o
|
||||
end
|
||||
|
||||
-- count the decoded bytes of the data lines [i, j)
|
||||
local function countData(src: buffer, i: number, j: number): number
|
||||
local n, esc = 0, false
|
||||
for p = i, j - 1 do
|
||||
local c = buffer.readu8(src, p)
|
||||
if c ~= 13 and c ~= 10 then
|
||||
if c == 61 and not esc then
|
||||
esc = true
|
||||
else
|
||||
esc = false
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? }
|
||||
type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? }
|
||||
|
||||
local function hex(s: string?): number?
|
||||
return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil
|
||||
end
|
||||
|
||||
local function parse(b: buffer, base: number, limit: number): ({ File }?, string?)
|
||||
local files: { File } = {}
|
||||
local byName: { [string]: File } = {}
|
||||
local p = base
|
||||
local cur: File? = nil
|
||||
local part: Part? = nil
|
||||
while p < limit do
|
||||
local nl = p
|
||||
while nl < limit and buffer.readu8(b, nl) ~= 10 do
|
||||
nl += 1
|
||||
end
|
||||
local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y"
|
||||
if isKey then
|
||||
local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "")
|
||||
local kw = string.match(line, "^=y(%a+)")
|
||||
local f = fields(line)
|
||||
if kw == "begin" then
|
||||
local name = f.name
|
||||
local size = tonumber(f.size or "")
|
||||
if not name or name == "" or not size or size < 0 then
|
||||
return nil, "=ybegin without name or size"
|
||||
end
|
||||
local file: File? = byName[name]
|
||||
if not file then
|
||||
local nf: File = { name = name :: string, size = size, parts = {}, total = tonumber(f.total or "") }
|
||||
byName[name] = nf
|
||||
table.insert(files, nf)
|
||||
file = nf
|
||||
end
|
||||
cur = file
|
||||
part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") }
|
||||
elseif kw == "part" and part then
|
||||
local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "")
|
||||
if not first or not last or first < 1 or last < first - 1 then
|
||||
return nil, "bad =ypart range"
|
||||
end
|
||||
part.first, part.last = first - 1, last
|
||||
part.from, part.to = nl + 1, nl + 1
|
||||
elseif kw == "end" and part and cur then
|
||||
part.pcrc = hex(f.pcrc32)
|
||||
if f.crc32 then
|
||||
cur.crc = hex(f.crc32)
|
||||
end
|
||||
local size = tonumber(f.size or "")
|
||||
if size and size ~= part.last - part.first then
|
||||
return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")"
|
||||
end
|
||||
table.insert(cur.parts, part)
|
||||
part = nil
|
||||
end
|
||||
elseif part then
|
||||
part.to = nl + 1
|
||||
end
|
||||
p = nl + 1
|
||||
end
|
||||
if part then
|
||||
return nil, "truncated: no =yend"
|
||||
end
|
||||
if #files == 0 then
|
||||
return nil, "no =ybegin line"
|
||||
end
|
||||
return files, nil
|
||||
end
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return Yenc.encode(a, o)
|
||||
end
|
||||
|
||||
function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local b = r.buf
|
||||
local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b)))
|
||||
if not files then
|
||||
return nil, Err.from(perr)
|
||||
end
|
||||
local a = Archive.new("yenc", encoder)
|
||||
local incomplete = {}
|
||||
for _, f in files do
|
||||
if f.size > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes")
|
||||
end
|
||||
local out = buffer.create(f.size)
|
||||
local covered = 0
|
||||
for _, pt in f.parts do
|
||||
local n = countData(b, pt.from, pt.to)
|
||||
if n ~= pt.last - pt.first or pt.last > f.size then
|
||||
return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first))
|
||||
end
|
||||
local tmp = buffer.create(n)
|
||||
decodeData(b, pt.from, pt.to, tmp, 0)
|
||||
if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then
|
||||
return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch")
|
||||
end
|
||||
buffer.copy(out, pt.first, tmp, 0, n)
|
||||
covered += n
|
||||
end
|
||||
local whole = covered == f.size
|
||||
if whole and f.crc and Crc32.of(out) ~= f.crc then
|
||||
return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch")
|
||||
end
|
||||
if not whole then
|
||||
table.insert(incomplete, f.name)
|
||||
end
|
||||
Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole })
|
||||
end
|
||||
a.meta.stream = #files == 1
|
||||
a.meta.incomplete = if #incomplete > 0 then incomplete else nil
|
||||
a.meta.source = { format = "yenc" }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local lineLen = o.line or 128
|
||||
if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then
|
||||
return nil, Err.new(Err.ARG, "line must be 2..997")
|
||||
end
|
||||
local files, err = Archive.files(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
if #files == 0 then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
for _, f in files do
|
||||
if string.find(f.name, "[\r\n]") then
|
||||
return nil, Err.new(Err.ARG, "file names may not contain line breaks")
|
||||
end
|
||||
local data = f.data
|
||||
local n = buffer.len(data)
|
||||
w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name))
|
||||
local col = 0
|
||||
for i = 0, n - 1 do
|
||||
local c = (buffer.readu8(data, i) + 42) % 256
|
||||
local critical = c == 0 or c == 10 or c == 13 or c == 61
|
||||
if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then
|
||||
critical = true
|
||||
elseif not critical and c == 46 and col == 0 then
|
||||
critical = true
|
||||
end
|
||||
if critical then
|
||||
w:u8(61)
|
||||
w:u8((c + 64) % 256)
|
||||
col += 2
|
||||
else
|
||||
w:u8(c)
|
||||
col += 1
|
||||
end
|
||||
if col >= lineLen and i < n - 1 then
|
||||
w:string("\r\n")
|
||||
col = 0
|
||||
end
|
||||
end
|
||||
if n > 0 then
|
||||
w:string("\r\n")
|
||||
end
|
||||
w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data)))
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line })
|
||||
function Yenc.new(): any
|
||||
local a = Archive.new("yenc", encoder)
|
||||
a.meta.source = { format = "yenc" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Yenc
|
||||
@@ -0,0 +1,98 @@
|
||||
--!strict
|
||||
-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
|
||||
-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
|
||||
-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
|
||||
-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
|
||||
-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local UnixCompress = require("@rosetta/codecs/compress/UnixCompress")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Z = {
|
||||
name = "z",
|
||||
category = "archive",
|
||||
extensions = { "z", "taz", "tz" },
|
||||
mime = { "application/x-compress" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
maxBits: number?, -- 9..16 (compress -b), default 16
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Z.sniff(r: Bytes.Reader): number
|
||||
if r:peek(2) ~= "\31\157" then
|
||||
return 0
|
||||
end
|
||||
local f = r:peekU8(2)
|
||||
return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the entry name: the file name without .Z; .taz / .tz name a tar
|
||||
local function entryName(opts: DecodeOptions): string
|
||||
local name = Archive.streamName(opts, { "z" })
|
||||
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
|
||||
if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then
|
||||
return stem .. ".tar"
|
||||
end
|
||||
return name
|
||||
end
|
||||
|
||||
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Z.encode(value, opts)
|
||||
end
|
||||
|
||||
function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, err = UnixCompress.decompress(r.buf, r.base, n, o)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 }
|
||||
Archive.put(a, {
|
||||
name = entryName(o),
|
||||
size = buffer.len(out),
|
||||
compressedSize = n,
|
||||
method = "lzw",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local data, err = Archive.streamData(value)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(data?, name?) -> a .Z Archive holding one entry
|
||||
function Z.new(data: (buffer | string)?, name: string?): any
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z" }
|
||||
if data then
|
||||
a:add(name or "data", data)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Z
|
||||
@@ -0,0 +1,238 @@
|
||||
--!strict
|
||||
-- archive/zip: ZIP archives as the standard Archive (Types.Archive: list / read / add / write) on containers/Zip.
|
||||
-- Absorbed from zip-luau 121d4b0 (same author, no third-party code; the reader, now containers/Zip) plus a new
|
||||
-- writer. Supports: reading stored and deflated entries (CRC-checked), ZIP64, data descriptors, archive comments,
|
||||
-- prefixed archives (self-extractors), UTF-8 names, case-insensitive / basename lookup; writing stored and deflated
|
||||
-- entries (codecs/compress/Deflate), unchanged entries copied without recompressing, ZIP64 when needed.
|
||||
-- Not supported: encryption (traditional PKWARE or AES), compression methods other than store / deflate (bzip2,
|
||||
-- LZMA, zstd entries are listed but not readable), multi-disk archives.
|
||||
--
|
||||
-- local a = Zip.decode(Bytes.reader(buf)) -- or F.archive.load(buf)
|
||||
-- for _, e in a:list() do print(e.name, e.size, e.method) end
|
||||
-- local data = a:read("dir/file.txt")
|
||||
-- a:add("new.txt", "hello", { level = 9 }) -- or { method = "store", mtime = os.time() }
|
||||
-- local out = a:write({ comment = "made here" }) -- or Zip.encode(a) / F.save(a, nil, { format = "zip" })
|
||||
-- local b = Zip.create() -- an empty archive
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Container = require("@rosetta/containers/Zip")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Zip = {
|
||||
name = "zip",
|
||||
category = "archive",
|
||||
extensions = { "zip", "wsz" },
|
||||
mime = { "application/zip", "application/x-zip-compressed" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, methods = { "store", "deflate" }, zip64 = true },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = {
|
||||
verify: boolean?, -- check every entry's CRC-32 on read (default true)
|
||||
}
|
||||
export type AddOptions = Container.AddOptions
|
||||
export type WriteOptions = Container.FinishOptions
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local METHODS = { [0] = "store", [8] = "deflate", [9] = "deflate64", [12] = "bzip2", [14] = "lzma", [93] = "zstd", [95] = "xz", [99] = "aes" }
|
||||
|
||||
local Archive = {}
|
||||
Archive.__index = Archive
|
||||
|
||||
local function new(zip: any, verify: boolean): any
|
||||
local a = setmetatable({
|
||||
kind = "archive",
|
||||
format = "zip",
|
||||
meta = { source = { format = "zip" }, comment = if zip then zip.comment else nil, zip64 = if zip then zip.zip64 else nil },
|
||||
_zip = zip,
|
||||
_verify = verify,
|
||||
_order = {} :: { string },
|
||||
_items = {} :: { [string]: any },
|
||||
}, Archive)
|
||||
if zip then
|
||||
for _, e in zip:list() do
|
||||
if a._items[e.name] == nil then
|
||||
table.insert(a._order, e.name)
|
||||
end
|
||||
a._items[e.name] = { raw = e }
|
||||
end
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Zip.sniff(r: Bytes.Reader): number
|
||||
local s = r:peek(4)
|
||||
-- ZIP-based formats (docx, jar, 3mf, ...) score higher in their own sniff
|
||||
if s == "PK\3\4" or s == "PK\5\6" then
|
||||
return 0.6
|
||||
end
|
||||
if string.sub(s, 1, 2) == "MZ" then
|
||||
return 0 -- a self-extractor opens with Zip.decode / opts.format = "zip"
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decode(r, opts?) -> Archive | nil, Err
|
||||
function Zip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?)
|
||||
local zip, err = Container.open(r)
|
||||
if not zip then
|
||||
return nil, err
|
||||
end
|
||||
return new(zip, not (opts and opts.verify == false)), nil
|
||||
end
|
||||
|
||||
-- create() -> an empty Archive
|
||||
function Zip.create(): Types.Archive
|
||||
return new(nil, true)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- encode(archive, opts?) -> buffer | nil, Err. archive: an Archive (any format's: its entries are read and written
|
||||
-- here), or a plain table { [name] = buffer | string }.
|
||||
function Zip.encode(value: any, opts: WriteOptions?): (buffer?, Err.Err?)
|
||||
if type(value) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "encode: needs an Archive or a { name = data } table")
|
||||
end
|
||||
if getmetatable(value) == Archive then
|
||||
return value:write(opts)
|
||||
end
|
||||
local a = new(nil, true)
|
||||
if value.kind == "archive" and type(value.list) == "function" and type(value.read) == "function" then
|
||||
for _, e in value:list() do
|
||||
if e.dir then
|
||||
a:add(e.name, nil, { mtime = e.mtime })
|
||||
else
|
||||
local data, err = value:read(e.name)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
a:add(e.name, data, { mtime = e.mtime })
|
||||
end
|
||||
end
|
||||
else
|
||||
local names = {}
|
||||
for k, v in value do
|
||||
if type(k) ~= "string" or (type(v) ~= "buffer" and type(v) ~= "string") then
|
||||
return nil, Err.new(Err.ARG, "encode: a { name = data } table needs string names and buffer / string data")
|
||||
end
|
||||
table.insert(names, k)
|
||||
end
|
||||
table.sort(names)
|
||||
for _, k in names do
|
||||
a:add(k, value[k])
|
||||
end
|
||||
end
|
||||
return a:write(opts)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- the Archive methods (Types.Archive)
|
||||
|
||||
-- list() -> { ArchiveEntry } in archive order (+ crc32, comment)
|
||||
function Archive.list(self: any): { Types.ArchiveEntry }
|
||||
local out = {}
|
||||
for _, name in self._order do
|
||||
local it = self._items[name]
|
||||
if it.raw then
|
||||
local e = it.raw
|
||||
table.insert(out, {
|
||||
name = e.name,
|
||||
size = e.size,
|
||||
compressedSize = e.compressedSize,
|
||||
method = METHODS[e.method] or ("method " .. e.method),
|
||||
mtime = e.mtime,
|
||||
dir = e.isDir,
|
||||
crc32 = e.crc32,
|
||||
comment = e.comment,
|
||||
})
|
||||
else
|
||||
table.insert(out, {
|
||||
name = name,
|
||||
size = buffer.len(it.data),
|
||||
compressedSize = nil,
|
||||
method = it.opts.method or "deflate",
|
||||
mtime = it.opts.mtime,
|
||||
dir = string.sub(name, -1) == "/",
|
||||
})
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- read(name) -> buffer | nil, Err: an exact name, else the reader's case-insensitive / basename lookup
|
||||
function Archive.read(self: any, name: string): (buffer?, Err.Err?)
|
||||
if type(name) ~= "string" then
|
||||
return nil, Err.new(Err.ARG, "read: name must be a string")
|
||||
end
|
||||
local it = self._items[name]
|
||||
if it and not it.raw then
|
||||
local copy = buffer.create(buffer.len(it.data))
|
||||
buffer.copy(copy, 0, it.data)
|
||||
return copy, nil
|
||||
end
|
||||
if it then
|
||||
return self._zip:read(it.raw, self._verify)
|
||||
end
|
||||
if self._zip then
|
||||
local e = self._zip:find(name)
|
||||
if e and self._items[e.name] and self._items[e.name].raw == e then
|
||||
return self._zip:read(e, self._verify)
|
||||
end
|
||||
end
|
||||
return nil, Err.new(Err.ARG, "no entry " .. name)
|
||||
end
|
||||
|
||||
-- add(name, data, opts?): add or replace an entry (data: buffer or string; nil for a directory "name/")
|
||||
function Archive.add(self: any, name: string, data: any, opts: AddOptions?)
|
||||
local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0)
|
||||
if self._items[name] == nil then
|
||||
table.insert(self._order, name)
|
||||
end
|
||||
self._items[name] = { data = b, opts = opts or {} }
|
||||
end
|
||||
|
||||
-- remove(name) -> true when there was such an entry
|
||||
function Archive.remove(self: any, name: string): boolean
|
||||
if self._items[name] == nil then
|
||||
return false
|
||||
end
|
||||
self._items[name] = nil
|
||||
local i = table.find(self._order, name)
|
||||
if i then
|
||||
table.remove(self._order, i)
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- write(opts?) -> buffer | nil, Err: the archive with every change; unchanged entries are copied as they are
|
||||
function Archive.write(self: any, opts: WriteOptions?): (buffer?, Err.Err?)
|
||||
local w = Container.writer()
|
||||
for _, name in self._order do
|
||||
local it = self._items[name]
|
||||
local ok, err
|
||||
if it.raw then
|
||||
ok, err = w:addRaw(it.raw, self._zip)
|
||||
else
|
||||
ok, err = w:add(name, it.data, it.opts)
|
||||
end
|
||||
if not ok then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
local o: WriteOptions = opts or {}
|
||||
if o.comment == nil and self.meta.comment and self.meta.comment ~= "" then
|
||||
o = table.clone(o)
|
||||
o.comment = self.meta.comment
|
||||
end
|
||||
return w:finish(o)
|
||||
end
|
||||
|
||||
Zip.Container = Container
|
||||
|
||||
return Zip
|
||||
@@ -0,0 +1,197 @@
|
||||
--!strict
|
||||
-- archive/zoo: Zoo archives (Rahul Dhesi's zoo 1.x / 2.x) read into an Archive: the archive header, the chain of
|
||||
-- directory entries (type 1, and type 2 with long names, directory names, Unix-style attributes and version numbers),
|
||||
-- deleted entries skipped, entries stored (method 0), LZW-compressed (method 1: codecs/compress/Lzw "zoo", 13-bit
|
||||
-- codes) or lzh-compressed (method 2: codecs/compress/Lzh "lh5"); every file's CRC-16 (ARC) is verified when read
|
||||
-- (Err.CHECKSUM). MS-DOS dates read as UTC. Written from zoo 2.10's file format description (zoo.h / ar.h). Not
|
||||
-- supported: writing, file generations beyond keeping the newest (older versions of a name get ";<version>").
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Crc16 = require("@rosetta/core/Crc16")
|
||||
local Lzw = require("@rosetta/codecs/compress/Lzw")
|
||||
local Lzh = require("@rosetta/codecs/compress/Lzh")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Zoo = {
|
||||
name = "zoo",
|
||||
category = "archive",
|
||||
extensions = { "zoo" },
|
||||
mime = { "application/x-zoo" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzw", "codecs/compress/Lzh", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, methods = { "store", "lzw", "lzh" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
|
||||
maxEntries: number?, -- default 65536
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local TAG = 0xFDC4A7DC
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Zoo.sniff(r: Bytes.Reader): number
|
||||
local h = r:peek(24)
|
||||
if #h < 24 then
|
||||
return 0
|
||||
end
|
||||
local tag = string.byte(h, 21) + string.byte(h, 22) * 256 + string.byte(h, 23) * 65536 + string.byte(h, 24) * 16777216
|
||||
if tag ~= TAG then
|
||||
return 0
|
||||
end
|
||||
return if string.sub(h, 1, 4) == "ZOO " then 1 else 0.8
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Zoo.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxBytes = o.maxBytes or 2 ^ 30
|
||||
local maxEntries = o.maxEntries or 65536
|
||||
local h = r:sub(0, 34)
|
||||
local text = h:string(20)
|
||||
local tag, start = h:u32le(), h:u32le()
|
||||
h:skip(4)
|
||||
local major, minor = h:u8(), h:u8()
|
||||
if h.err then
|
||||
return nil, h.err
|
||||
end
|
||||
if tag ~= TAG then
|
||||
return nil, Err.new(Err.CORRUPT, "no zoo tag")
|
||||
end
|
||||
local a = Archive.new("zoo")
|
||||
a.meta.text = string.match(text, "^[^%z\26]*")
|
||||
a.meta.source = { format = "zoo", version = major .. "." .. minor }
|
||||
local p = start
|
||||
local count = 0
|
||||
local seen: { [number]: boolean } = {}
|
||||
local size = r:size()
|
||||
while true do
|
||||
if seen[p] or p < 34 or p + 51 > size then
|
||||
return nil, Err.new(if p + 51 > size then Err.TRUNCATED else Err.CORRUPT, "bad directory entry offset " .. p)
|
||||
end
|
||||
seen[p] = true
|
||||
local e = r:sub(p, size - p)
|
||||
local etag = e:u32le()
|
||||
local etype, method = e:u8(), e:u8()
|
||||
local nextP, dataAt = e:u32le(), e:u32le()
|
||||
local date, time = e:u16le(), e:u16le()
|
||||
local crc = e:u16le()
|
||||
local orig, packed = e:u32le(), e:u32le()
|
||||
e:skip(2)
|
||||
local deleted = e:u8()
|
||||
e:skip(1)
|
||||
local commentAt, commentLen = e:u32le(), e:u16le()
|
||||
local fname = e:fixed(13)
|
||||
if e.err then
|
||||
return nil, e.err
|
||||
end
|
||||
if etag ~= TAG then
|
||||
return nil, Err.new(Err.CORRUPT, "bad directory entry tag", r.base + p)
|
||||
end
|
||||
if nextP == 0 then
|
||||
break
|
||||
end
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
|
||||
end
|
||||
local name, dir = fname, ""
|
||||
local entry: any = {}
|
||||
if etype == 2 then
|
||||
local varLen = e:u16le()
|
||||
e:skip(3) -- tz, dir_crc
|
||||
if varLen > 0 then
|
||||
local v = e:slice(varLen)
|
||||
local nlen, dlen = v:u8(), v:u8()
|
||||
local lname = v:string(nlen)
|
||||
dir = v:string(dlen)
|
||||
if nlen > 0 then
|
||||
name = string.match(lname, "^[^%z]*") or lname
|
||||
end
|
||||
if v:remaining() >= 2 then
|
||||
entry.system = v:u16le()
|
||||
end
|
||||
if v:remaining() >= 3 then
|
||||
local f0, f1, f2 = v:u8(), v:u8(), v:u8()
|
||||
local attr = f0 + f1 * 256 + f2 * 65536
|
||||
if bit32.band(attr, 0x400000) ~= 0 then
|
||||
entry.mode = bit32.band(attr, 0xFFFF)
|
||||
end
|
||||
end
|
||||
if v:remaining() >= 4 then
|
||||
local vflag, ver = v:u16le(), v:u16le()
|
||||
if bit32.band(vflag, 0x40) ~= 0 then
|
||||
entry.version = ver
|
||||
end
|
||||
end
|
||||
end
|
||||
if e.err then
|
||||
return nil, e.err
|
||||
end
|
||||
end
|
||||
dir = string.match(dir, "^[^%z]*") or dir
|
||||
dir = string.gsub(dir, "\\", "/")
|
||||
local full = if dir ~= "" then (string.gsub(dir, "/+$", "")) .. "/" .. name else name
|
||||
full = string.gsub(full, "^/+", "")
|
||||
if deleted == 0 then
|
||||
local key = full
|
||||
if a._byName[key] then
|
||||
key = full .. ";" .. tostring(entry.version or count)
|
||||
end
|
||||
entry.name = key
|
||||
entry.size = orig
|
||||
entry.compressedSize = packed
|
||||
entry.method = if method == 0 then "store" elseif method == 1 then "lzw" elseif method == 2 then "lzh" else "method" .. method
|
||||
entry.mtime = Archive.fromDos(date * 65536 + time)
|
||||
entry.dir = false
|
||||
if commentLen > 0 and commentAt + commentLen <= size then
|
||||
entry.comment = r:sub(commentAt, commentLen):string(commentLen)
|
||||
end
|
||||
if dataAt + packed > size then
|
||||
return nil, Err.new(Err.TRUNCATED, full .. ": data past the end")
|
||||
end
|
||||
if orig > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, full .. ": larger than maxBytes")
|
||||
end
|
||||
if orig > 0 then
|
||||
local buf, at = r.buf, r.base + dataAt
|
||||
entry.load = function(): (buffer?, Err.Err?)
|
||||
local out: buffer?, derr: string?
|
||||
if method == 0 then
|
||||
if packed < orig then
|
||||
return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
|
||||
end
|
||||
out = buffer.create(orig)
|
||||
buffer.copy(out :: buffer, 0, buf, at, orig)
|
||||
elseif method == 1 then
|
||||
local ob = buffer.create(orig)
|
||||
local n, lerr = Lzw.decode(buf, at, packed, ob, 0, orig, "zoo")
|
||||
if n ~= orig then
|
||||
return nil, Err.from(lerr or "corrupt: LZW data ends early")
|
||||
end
|
||||
out = ob
|
||||
elseif method == 2 then
|
||||
out, derr = Lzh.decode(buf, at, packed, orig, "lh5")
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "packing method " .. method)
|
||||
end
|
||||
if not out then
|
||||
return nil, Err.from(derr)
|
||||
end
|
||||
if Crc16.arc(out, 0, orig) ~= crc then
|
||||
return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch")
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
Archive.put(a, entry)
|
||||
end
|
||||
p = nextP
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Zoo
|
||||
@@ -0,0 +1,63 @@
|
||||
--!strict
|
||||
-- archive/zst: a Zstandard-compressed file (.zst, RFC 8878) as a single-stream archive holding one entry, decoded
|
||||
-- through codecs/compress/Zstd. The entry is named after the file without its extension (opts.name; ".tzst" -> ".tar"), else
|
||||
-- "data". The api unwraps it when the entry is itself an archive (.tar.zst loads as the tar). Read-only.
|
||||
-- Not supported: dictionaries, writing.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Zstd = require("@rosetta/codecs/compress/Zstd")
|
||||
local Archive = require("@rosetta/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Zst = {
|
||||
name = "zst",
|
||||
category = "archive",
|
||||
extensions = { "zst", "tzst" },
|
||||
mime = { "application/zstd" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Zstd", "containers/Archive" },
|
||||
caps = { decode = true, encode = false, stream = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse a decompressed size over this (default 2^30)
|
||||
verify: boolean?, -- check the content checksum (default true)
|
||||
name: string?, -- the file name, for the entry name (the api passes it)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Zst.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m == Zstd.MAGIC then
|
||||
return 1
|
||||
end
|
||||
-- a skippable frame (0x184D2A50 .. 0x184D2A5F) is usually followed by a zstd frame
|
||||
if #m == 4 and string.sub(m, 2, 4) == "\42\77\24" and bit32.band(string.byte(m, 1), 0xF0) == 0x50 then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Zst.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local len = r.limit - r.base
|
||||
local out, err = Zstd.decompress(r.buf, r.base, len, { maxBytes = o.maxBytes, verify = o.verify })
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("zst")
|
||||
a.meta.stream = true
|
||||
Archive.put(a, {
|
||||
name = Archive.streamName(o, Zst.extensions),
|
||||
size = buffer.len(out),
|
||||
compressedSize = len,
|
||||
method = "zstd",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Zst
|
||||
Reference in new issue
Block a user