diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 7361df6..09df9b9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -50,6 +50,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` | | font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` | | 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 | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d2cc30a..8afbe1f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -554,6 +554,18 @@ local list: { Entry } = { return require("@formats/archive/7z") end, }, + { + name = "adf", + category = "archive", + path = "archive/adf", + extensions = { "adf" }, + mime = { "application/x-amiga-disk-format" }, + deps = { "core/Err", "core/Bytes", "containers/Archive" }, + caps = { decode = true, encode = false, variants = { "ofs", "ffs" } }, + load = function() + return require("@formats/archive/adf") + end, + }, { name = "applesingle", category = "archive", diff --git a/src/Formats/archive/adf/init.luau b/src/Formats/archive/adf/init.luau new file mode 100644 index 0000000..ecf641c --- /dev/null +++ b/src/Formats/archive/adf/init.luau @@ -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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/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 diff --git a/tests/archive/adf.luau b/tests/archive/adf.luau new file mode 100644 index 0000000..ff0775d --- /dev/null +++ b/tests/archive/adf.luau @@ -0,0 +1,75 @@ +-- archive/adf tests: DD / HD images formatted OFS, FFS, FFS international, OFS / FFS with directory cache by amitools' +-- xdftool, holding nested directories, an empty file, a file with extension blocks and an ISO-8859-1 name, list the +-- files xdftool reads back (names, sizes, data CRCs, directories, a set date), volume name and file system; errors +-- (root block checksum, bad hash chains); the fuzz pass. Fixtures: tools/fixtures/adf.py (images gzip-compressed). +local T = require("@tests/T") +local F = require("@formats") +local Adf = require("@formats/archive/adf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Deflate = require("@formats/codecs/compress/Deflate") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/adf") + +local t = T.suite("adf") +t:eq(Adf.name, "adf", "name") + +local first: buffer? = nil +for _, c in Fx.cases do + local gz = buffer.fromstring(c.gz) + local data = Deflate.gunzip(gz, 0, buffer.len(gz)) :: buffer + first = first or data + local a, err = Adf.decode(Bytes.reader(data)) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name) + t:eq(a.meta.volume, c.volume, c.name .. ": volume") + t:eq(a.meta.fs, c.fs, c.name .. ": fs") + t:eq(a._byName.readme.protect, 3, c.name .. ": protect rw (the D and E bits set: active low)") + end + t:eq(F.detect(data), "adf", c.name .. ": detect") +end + +-- errors +local img = first :: buffer +local function code(b: buffer): string? + local _, e = Adf.decode(Bytes.reader(b)) + return e and e.code +end +local bad = buffer.create(buffer.len(img)) +buffer.copy(bad, 0, img) +buffer.writeu8(bad, 880 * 512 + 433, 0x7A) -- the volume name: root checksum fails +t:eq(code(bad), Err.CHECKSUM, "root checksum") +t:eq(code(buffer.create(1000)), Err.CORRUPT, "not blocks") +t:eq(code(buffer.create(4096)), Err.CORRUPT, "no boot block") +local dos6 = buffer.create(4096) +buffer.writestring(dos6, 0, "DOS\6") +t:eq(code(dos6), Err.UNSUPPORTED, "long-name file system") + +-- fuzz: mutations concentrated on the root and directory blocks (a whole image is mostly free blocks) +local rand = T.rng(7) +local threw = 0 +for i = 1, 300 do + local m = buffer.create(buffer.len(img)) + buffer.copy(m, 0, img) + for _ = 1, 1 + rand(4) do + local blk = if rand(2) == 0 then 880 else rand(1760) + buffer.writeu8(m, blk * 512 + rand(512), rand(256)) + end + local ok = pcall(function() + local a = Adf.decode(Bytes.reader(m)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + end) + if not ok then + threw += 1 + end +end +t:eq(threw, 0, "mutated images never throw") +t:fuzz("decode", function(b: buffer) + return Adf.decode(Bytes.reader(b)) +end, { buffer.tostring(img) }, { mutations = 20, garbage = 20 }) +t:done() diff --git a/tools/fixtures/adf.py b/tools/fixtures/adf.py new file mode 100644 index 0000000..7fef3d1 --- /dev/null +++ b/tools/fixtures/adf.py @@ -0,0 +1,59 @@ +# Amiga ADF fixtures (tools/fixtures.py): DD and HD images formatted as OFS, FFS, FFS international and OFS / FFS with +# directory cache by amitools' `xdftool` (PyPI amitools through `uvx`), filled with a tree (nested directories, an +# empty file, a file large enough for extension blocks, Latin-1 names, protection bits, a set date; amitools 0.8.1's +# `comment` command fails, so comments are not covered); each +# file read back by `xdftool read` for the reference data, protection / dates from `xdftool list`. +# The images are emitted gzip-compressed (mostly empty blocks). +# tests/gen/adf.luau { cases = { { name, gz, volume, fs, entries = { { name, size?, crc?, dir?, comment?, mtime? } } } } } +import calendar, gzip, importlib.util, os, shutil, time, 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 xdf(args, cwd): + return A.tool(["uv"], ["uvx", "--from", "amitools==0.8.1", "xdftool"] + args, cwd=cwd).decode("latin-1") + + +def generate(ctx): + rng = ctx.rng(1985) + tmp = A.tmpdir() + try: + files = [("readme", b"Amiga readme\n" * 20), ("empty", b""), ("s/startup-sequence", b"echo hello\n"), + ("deep/a/b/c/leaf.bin", rng.randbytes(1500)), ("big.bin", rng.randbytes(100000)), + ("café ü", b"latin-1 name\n")] + for i, (_, d) in enumerate(files): + open(os.path.join(tmp, "f%d" % i), "wb").write(d) + cases = [] + for fs, size in (("ofs", "dd"), ("ffs", "dd"), ("ffs+intl", "dd"), ("ofs+dc", "dd"), ("ffs+dc", "dd"), ("ffs", "hd")): + img = "t-%s-%s.adf" % (fs.replace("+", "_"), size) + cmd = [img, "-f", "create", "size=1760K" if size == "hd" else "size=880K", "+", "format", "Vol " + fs, fs] + dirs = set() + for i, (name, _) in enumerate(files): + parts = name.split("/")[:-1] + for k in range(1, len(parts) + 1): + d = "/".join(parts[:k]) + if d not in dirs: + dirs.add(d) + cmd += ["+", "makedir", d] + cmd += ["+", "write", "f%d" % i, name] + cmd += ["+", "protect", "readme", "rw", "+", "time", "readme", "01.02.1993 10:20:30.00"] + xdf(cmd, tmp) + ents = [{"name": d + "/", "dir": True} for d in sorted(dirs)] + for i, (name, d) in enumerate(files): + out = os.path.join(tmp, "out%d" % i) + xdf([img, "read", name, out], tmp) + rd = open(out, "rb").read() + assert rd == d, (img, name) + e = {"name": name, "size": len(d), "crc": zlib.crc32(d)} + if name == "readme": + e["mtime"] = calendar.timegm((1993, 2, 1, 10, 20, 30)) + ents.append(e) + cases.append({"name": img, "gz": gzip.compress(open(os.path.join(tmp, img), "rb").read(), mtime=0), "volume": "Vol " + fs, + "fs": "ofs" if fs.startswith("ofs") else "ffs", "entries": ents, "listing": xdf([img, "list"], tmp)}) + ctx.emit("adf", {"cases": cases}) + finally: + shutil.rmtree(tmp)