diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f2e7aa8..7f1b9f0 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -52,6 +52,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` | | archive | adf | .adf | yes | - | variants: "ofs", "ffs" | `tests/archive/adf.luau` | | archive | applesingle | .as .applesingle .appledouble | yes | yes | forks: true, variants: "applesingle", "appledouble" | `tests/archive/applesingle.luau` | +| archive | arj | .arj | yes | - | methods: "store", "arj1", "arj2", "arj3", "arj4" | `tests/archive/arj.luau` | | archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 38ccaaf..37d3ecf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -578,6 +578,18 @@ local list: { Entry } = { return require("@formats/archive/applesingle") end, }, + { + name = "arj", + category = "archive", + path = "archive/arj", + 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" } }, + load = function() + return require("@formats/archive/arj") + end, + }, { name = "binhex", category = "archive", diff --git a/src/Formats/archive/arj/init.luau b/src/Formats/archive/arj/init.luau new file mode 100644 index 0000000..c38b075 --- /dev/null +++ b/src/Formats/archive/arj/init.luau @@ -0,0 +1,229 @@ +--!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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Lzh = require("@formats/codecs/compress/Lzh") +local Archive = require("@formats/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 +local function dosTime(v: number): number? + local time, date = v % 65536, v // 65536 + if date == 0 then + return nil + end + local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) + if m < 1 or m > 12 or d < 1 then + return nil + end + local yy = if m <= 2 then y - 1 else y + local era = yy // 400 + local yoe = yy - era * 400 + local doy = (153 * (if m > 2 then m - 3 else m + 9) + 2) // 5 + d - 1 + local days = era * 146097 + yoe * 365 + yoe // 4 - yoe // 100 + doy - 719468 + return days * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +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 = dosTime(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 = dosTime(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 diff --git a/tests/archive/arj.luau b/tests/archive/arj.luau new file mode 100644 index 0000000..b9528a0 --- /dev/null +++ b/tests/archive/arj.luau @@ -0,0 +1,58 @@ +-- archive/arj tests: archives by ARJ 3.10 with methods 0 .. 4 (stored, the LHA-style Huffman methods 1 .. 3, method +-- 4) give the files `arj x` extracts (names, sizes, data CRCs); header and data CRC errors, truncation; the fuzz +-- pass. Fixtures: tools/fixtures/arj.py. +local T = require("@tests/T") +local F = require("@formats") +local Arj = require("@formats/archive/arj") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/arj") + +local t = T.suite("arj") +t:eq(Arj.name, "arj", "name") + +local samples = {} +for _, c in Fx.cases do + local a, err = Arj.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name, false) + end + t:eq(F.detect(c.data), "arj", c.name .. ": detect") + table.insert(samples, string.sub(c.data, 1, 3000)) +end + +-- errors +local data = Fx.cases[2].data -- -m1 +local function code(s: string): string? + local _, e = Arj.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +local hdr = string.sub(data, 1, 10) .. string.char((string.byte(data, 11) + 1) % 256) .. string.sub(data, 12) +t:eq(code(hdr), Err.CHECKSUM, "main header CRC") +t:eq(code(string.sub(data, 1, #data // 2)), Err.TRUNCATED, "cut") +t:eq(code("\96\234\30\0"), Err.TRUNCATED, "short header") +t:eq(code("PK\3\4xxxx"), Err.CORRUPT, "not arj") +local mid = #data // 2 + 1000 +local bad = Arj.decode(Bytes.reader(buffer.fromstring(string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 0x10)) .. string.sub(data, mid + 1)))) :: any +local failed = 0 +for _, e in bad:list() do + local b, err = bad:read(e.name) + if not b then + failed += 1 + t:check(err.code == Err.CHECKSUM or err.code == Err.CORRUPT, "flipped data: " .. tostring(err)) + end +end +t:eq(failed, 1, "one entry fails after a flipped data byte") + +t:fuzz("decode", function(b: buffer) + local r = Arj.decode(Bytes.reader(b)) + if r then + for _, e in r:list() do + r:read(e.name) + end + end + return r +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/fixtures/arj.py b/tools/fixtures/arj.py new file mode 100644 index 0000000..747861b --- /dev/null +++ b/tools/fixtures/arj.py @@ -0,0 +1,33 @@ +# ARJ fixtures (tools/fixtures.py): archives made by the open-source ARJ 3.10 (nixpkgs#arj, run as a tool) with methods +# -m0 (stored) and -m1 .. -m4, recursing into a directory tree (-r), with an archive comment; the reference data is +# what `arj x` extracts again. +# tests/gen/arj.luau { cases = { { name, data, entries = { { name, size, crc } } } } } +import importlib.util, os, zlib + +_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py")) +A = importlib.util.module_from_spec(_s) +_s.loader.exec_module(A) + +INPUTS = ["tools/fixtures/_arch2.py"] + + +def generate(ctx): + rng = ctx.rng(31) + tmp = A.tmpdir() + try: + work = os.path.join(tmp, "w") + A.tree(A.FILES + [("dir/sub/text.txt", b"the quick brown fox jumps over the lazy dog\n" * 400), + ("dir/rand.bin", rng.randbytes(40000)), ("dir/runs.bin", b"\0" * 30000 + b"\xff" * 7000)], work) + names = [n for n, _ in A.FILES] + ["dir"] + cases = [] + for m in ("0", "1", "2", "3", "4"): + arc = os.path.join(tmp, "m%s.arj" % m) + A.tool(["arj"], ["arj", "a", "-m" + m, "-r", "-y", arc] + names, cwd=work) + out = os.path.join(tmp, "x" + m) + os.makedirs(out) + A.tool(["arj"], ["arj", "x", "-y", arc], cwd=out) + ents = [{"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c} for n, c in A.read_tree(out).items()] + cases.append({"name": "arj -m" + m, "data": open(arc, "rb").read(), "entries": ents}) + ctx.emit("arj", {"cases": cases}) + finally: + A.rmtree(tmp)