From 3243291877bfd8adf6428d1d49d64ab5cdecd49d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:11:03 -0500 Subject: [PATCH] ws-arch2: archive/binhex, archive/macbinary (I / II / III), archive/applesingle (AppleSingle / AppleDouble v1 / v2), read + write, over the new containers/MacFile (fork convention, Mac OS Roman names, 1904 dates) --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 36 +++ src/Formats/archive/applesingle/init.luau | 190 ++++++++++++++++ src/Formats/archive/binhex/init.luau | 254 ++++++++++++++++++++++ src/Formats/archive/macbinary/init.luau | 201 +++++++++++++++++ src/Formats/archive/yenc/init.luau | 9 +- src/Formats/containers/MacFile.luau | 158 ++++++++++++++ tests/archive/_mac.luau | 78 +++++++ tests/archive/applesingle.luau | 23 ++ tests/archive/binhex.luau | 26 +++ tests/archive/macbinary.luau | 24 ++ tools/fixtures/_arch2_ours.luau | 7 + tools/fixtures/mac.py | 147 +++++++++++++ 13 files changed, 1152 insertions(+), 4 deletions(-) create mode 100644 src/Formats/archive/applesingle/init.luau create mode 100644 src/Formats/archive/binhex/init.luau create mode 100644 src/Formats/archive/macbinary/init.luau create mode 100644 src/Formats/containers/MacFile.luau create mode 100644 tests/archive/_mac.luau create mode 100644 tests/archive/applesingle.luau create mode 100644 tests/archive/binhex.luau create mode 100644 tests/archive/macbinary.luau create mode 100644 tools/fixtures/mac.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dce27b6..6dada56 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -50,9 +50,12 @@ 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 | 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` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | macbinary | .bin .macbin | yes | yes | forks: true, variants: "I", "II", "III" | `tests/archive/macbinary.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6b3d61d..a6be552 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -554,6 +554,30 @@ local list: { Entry } = { return require("@formats/archive/7z") end, }, + { + name = "applesingle", + category = "archive", + path = "archive/applesingle", + 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" } }, + load = function() + return require("@formats/archive/applesingle") + end, + }, + { + name = "binhex", + category = "archive", + path = "archive/binhex", + 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 }, + load = function() + return require("@formats/archive/binhex") + end, + }, { name = "br", category = "archive", @@ -590,6 +614,18 @@ local list: { Entry } = { return require("@formats/archive/gzip") end, }, + { + name = "macbinary", + category = "archive", + path = "archive/macbinary", + 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" } }, + load = function() + return require("@formats/archive/macbinary") + end, + }, { name = "tar", category = "archive", diff --git a/src/Formats/archive/applesingle/init.luau b/src/Formats/archive/applesingle/init.luau new file mode 100644 index 0000000..9954039 --- /dev/null +++ b/src/Formats/archive/applesingle/init.luau @@ -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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local MacFile = require("@formats/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 diff --git a/src/Formats/archive/binhex/init.luau b/src/Formats/archive/binhex/init.luau new file mode 100644 index 0000000..8a15128 --- /dev/null +++ b/src/Formats/archive/binhex/init.luau @@ -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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc16 = require("@formats/core/Crc16") +local Archive = require("@formats/containers/Archive") +local MacFile = require("@formats/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 diff --git a/src/Formats/archive/macbinary/init.luau b/src/Formats/archive/macbinary/init.luau new file mode 100644 index 0000000..75e3eba --- /dev/null +++ b/src/Formats/archive/macbinary/init.luau @@ -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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc16 = require("@formats/core/Crc16") +local Archive = require("@formats/containers/Archive") +local MacFile = require("@formats/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 diff --git a/src/Formats/archive/yenc/init.luau b/src/Formats/archive/yenc/init.luau index 253c103..23997cb 100644 --- a/src/Formats/archive/yenc/init.luau +++ b/src/Formats/archive/yenc/init.luau @@ -124,11 +124,12 @@ local function parse(b: buffer, base: number, limit: number): ({ File }?, string if not name or name == "" or not size or size < 0 then return nil, "=ybegin without name or size" end - local file = byName[name] + local file: File? = byName[name] if not file then - file = { name = name, size = size, parts = {}, total = tonumber(f.total or "") } - byName[name] = file - table.insert(files, file :: File) + 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 "") } diff --git a/src/Formats/containers/MacFile.luau b/src/Formats/containers/MacFile.luau new file mode 100644 index 0000000..be198aa --- /dev/null +++ b/src/Formats/containers/MacFile.luau @@ -0,0 +1,158 @@ +--!strict +-- containers/MacFile: classic Mac OS files (a data fork, a resource fork and Finder info) as Archive entries, shared by +-- the Mac encodings (archive/binhex, archive/macbinary, archive/applesingle). The convention (unar's "visible forks"): +-- the data fork is the entry `name`, a non-empty resource fork is a second entry `name .. ".rsrc"` with +-- entry.fork = "resource"; both carry macType / macCreator (4-character strings), finderFlags, created / mtime (unix +-- seconds) and comment. Writers pair them back with collect(). +-- +-- MacFile.put(archive, { name = "Read Me", data = buf, rsrc = buf2, type = "TEXT", creator = "ttxt" }) +-- local files, err = MacFile.collect(value, defaultName) -- { MacFile.Info } from any Archive / buffer / string +-- MacFile.name(macRomanBytes) -> UTF-8 MacFile.roman(utf8) -> Mac OS Roman bytes +-- MacFile.fromMac(secondsSince1904) -> unix seconds MacFile.toMac(unix) -> seconds since 1904 (u32, clamped) +-- New code. Never throws. +local Err = require("@formats/core/Err") +local Archive = require("@formats/containers/Archive") + +local MacFile = {} + +export type Info = { + name: string, + data: buffer, + rsrc: buffer, + type: string, -- 4 bytes ("\0\0\0\0" when unknown) + creator: string, + flags: number, -- Finder flags (16 bits) + created: number?, -- unix seconds + modified: number?, + comment: string?, +} + +local MAC_EPOCH = 2082844800 -- seconds from 1904-01-01 to 1970-01-01 + +function MacFile.fromMac(s: number): number? + return if s == 0 then nil else s - MAC_EPOCH +end + +function MacFile.toMac(unix: number?): number + if type(unix) ~= "number" or unix ~= unix then + return 0 + end + return math.clamp(math.floor(unix + MAC_EPOCH), 0, 0xFFFFFFFF) +end + +-- Mac OS Roman bytes 0x80..0xFF +local ROMAN = { + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, + 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, + 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, + 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, + 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4, + 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7, +} +local FROM_UNICODE: { [number]: number } = {} +for i, u in ROMAN do + FROM_UNICODE[u] = 127 + i +end + +-- name(bytes) -> UTF-8 of a Mac OS Roman string (ASCII passes through) +function MacFile.name(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + local c = string.byte(s, i) + out[i] = if c < 128 then string.char(c) else utf8.char(ROMAN[c - 127]) + end + return table.concat(out) +end + +-- roman(utf8) -> Mac OS Roman bytes ("?" for characters it lacks; invalid UTF-8 passes through as bytes) +function MacFile.roman(s: string): string + if not string.find(s, "[\128-\255]") or not utf8.len(s) then + return s + end + local out = {} + for _, c in utf8.codes(s) do + table.insert(out, if c < 128 then string.char(c) else string.char(FROM_UNICODE[c] or 63)) + end + return table.concat(out) +end + +local function four(s: any): string + if type(s) ~= "string" then + return "\0\0\0\0" + end + return string.sub(s .. "\0\0\0\0", 1, 4) +end + +-- put(archive, info, noData?): the data fork entry (unless noData: AppleDouble files carry none; or it is empty and +-- there is a resource fork) and, when non-empty, the resource fork entry +function MacFile.put(a: any, f: Info, noData: boolean?) + local common = { + macType = f.type, + macCreator = f.creator, + finderFlags = f.flags, + created = f.created, + mtime = f.modified, + comment = f.comment, + dir = false, + } + local e: any = table.clone(common) + e.name, e.size, e.data, e.fork = f.name, buffer.len(f.data), f.data, "data" + if not noData and (buffer.len(f.data) > 0 or buffer.len(f.rsrc) == 0) then + Archive.put(a, e) + end + if buffer.len(f.rsrc) > 0 then + local r: any = table.clone(common) + r.name, r.size, r.data, r.fork = f.name .. ".rsrc", buffer.len(f.rsrc), f.rsrc, "resource" + Archive.put(a, r) + end +end + +-- collect(value, name?) -> the Mac files of any Archive (resource fork entries joined to their data fork entry), a +-- buffer or a string (one data fork named name, default "data") +function MacFile.collect(value: any, name: string?): ({ Info }?, Err.Err?) + local files, err = Archive.files(value, name) + if not files then + return nil, err + end + local out: { Info } = {} + local byName: { [string]: Info } = {} + local function get(n: string, e: any): Info + local f = byName[n] + if not f then + f = { + name = n, + data = buffer.create(0), + rsrc = buffer.create(0), + type = four(e.macType), + creator = four(e.macCreator), + flags = if type(e.finderFlags) == "number" then bit32.band(e.finderFlags, 0xFFFF) else 0, + created = if type(e.created) == "number" then e.created else nil, + modified = if type(e.mtime) == "number" then e.mtime else nil, + comment = if type(e.comment) == "string" then e.comment else nil, + } + byName[n] = f + table.insert(out, f) + end + return f :: Info + end + -- data forks first, so a resource fork finds its file whatever the order + for _, it in files do + if it.entry.fork ~= "resource" then + get(it.name, it.entry).data = it.data + end + end + for _, it in files do + if it.entry.fork == "resource" then + local base = string.match(it.name, "^(.*)%.rsrc$") or it.name + get(base, it.entry).rsrc = it.data + end + end + return out, nil +end + +return MacFile diff --git a/tests/archive/_mac.luau b/tests/archive/_mac.luau new file mode 100644 index 0000000..75d0967 --- /dev/null +++ b/tests/archive/_mac.luau @@ -0,0 +1,78 @@ +-- shared by tests/archive/{binhex,macbinary,applesingle}.luau: run(name, module) checks the format's cases of +-- tools/fixtures/mac.py against The Unarchiver's listings (fork names, sizes, data CRCs, type / creator), our writer's +-- output read by unar (fixture step), round trips with a resource fork and Finder info, and the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/mac") + +return function(name: string, mod: any, encodeVariants: { any }): (any, { string }) + local t = T.suite(name) + t:eq(mod.name, name, "name") + local samples = {} + local n = 0 + for _, c in Fx.cases do + if c.format == name then + n += 1 + local a, err = mod.decode(Bytes.reader(buffer.fromstring(c.data)), { name = "x" }) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name) + local by = {} + for _, e in a:list() do + by[e.name] = e + end + for _, w in c.entries do + local e = by[w.name] + if e and w.macType then + t:eq(e.macType, w.macType, c.name .. ": type") + t:eq(e.macCreator, w.macCreator, c.name .. ": creator") + end + end + end + t:eq(F.detect(c.data), name, c.name .. ": detect") + table.insert(samples, c.data) + end + end + t:check(n > 0, "has cases") + for _, o in Fx.ours do + if o.format == name then + t:check(o.ok, "unar reads our output (" .. o.variant .. "): " .. o.detail) + end + end + -- round trips: Finder info, dates, a resource fork + for _, opts in encodeVariants do + local a = mod.new() + a:add("Caf\u{e9}", "data fork", { mtime = 1700000000 }) + a:add("Caf\u{e9}.rsrc", string.rep("R", 300), {}) + local d = a._byName["Caf\u{e9}"] + d.macType, d.macCreator, d.finderFlags = "TEXT", "ttxt", 0x0100 + a._byName["Caf\u{e9}.rsrc"].fork = "resource" + local out, err = a:write(opts) + t:check(out, "write: " .. tostring(err)) + local back = out and mod.decode(Bytes.reader(out)) + t:check(back, "round trip decodes") + if back then + local list = back:list() + local by = {} + for _, e in list do + by[e.name] = e + end + local rs = by["Caf\u{e9}.rsrc"] + t:check(rs and rs.size == 300 and rs.fork == "resource", "round trip resource fork") + t:eq(Crc32.of((back:read("Caf\u{e9}.rsrc"))), Crc32.string(string.rep("R", 300)), "round trip resource data") + local df = by["Caf\u{e9}"] + local fi = df or rs + t:check(fi and fi.macType == "TEXT" and fi.macCreator == "ttxt" and fi.finderFlags == 0x0100, "round trip Finder info") + if not (opts and opts.double) then + t:eq(buffer.tostring((back:read("Caf\u{e9}"))), "data fork", "round trip data fork") + if name ~= "binhex" then + t:eq(df and df.mtime, 1700000000, "round trip mtime") + end + end + end + end + return t, samples +end diff --git a/tests/archive/applesingle.luau b/tests/archive/applesingle.luau new file mode 100644 index 0000000..0e6ca9d --- /dev/null +++ b/tests/archive/applesingle.luau @@ -0,0 +1,23 @@ +-- archive/applesingle tests: the applesingle cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar, +-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass. +local Mod = require("@formats/archive/applesingle") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local run = require("@tests/archive/_mac") + +local t, samples = run("applesingle", Mod, { {}, { double = true } }) +local function code(s: string): string? + local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +local good = buffer.tostring(Mod.encode("hello", { name = "h" }) :: buffer) +t:eq(code(string.sub(good, 1, 30)), Err.TRUNCATED, "entry table cut") +t:eq(code(string.sub(good, 1, #good - 2)), Err.TRUNCATED, "entry past the end") +t:eq(code("\0\5\22\0\0\3\0\0" .. string.rep("\0", 20)), Err.CORRUPT, "bad version") +-- the AppleDouble name comes from the file name without "._" +local d = Mod.decode(Bytes.reader(Mod.encode("x", { double = true, name = "" }) :: buffer), { name = "dir/._Report" }) :: any +t:check(d and d.meta.double, "appledouble flag") +t:fuzz("decode", function(b: buffer) + return Mod.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/archive/binhex.luau b/tests/archive/binhex.luau new file mode 100644 index 0000000..d8a14aa --- /dev/null +++ b/tests/archive/binhex.luau @@ -0,0 +1,26 @@ +-- archive/binhex tests: the binhex cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar, +-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass. +local Mod = require("@formats/archive/binhex") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local run = require("@tests/archive/_mac") + +local t, samples = run("binhex", Mod, { {} }) +local function code(s: string): string? + local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +local good = buffer.tostring(Mod.encode("hello binhex", { name = "h" }) :: buffer) +-- flip one data character (keeps the 6-bit alphabet): a CRC mismatch somewhere +local i = #good - 10 +local c = string.sub(good, i, i) +local bad = string.sub(good, 1, i - 1) .. (if c == "!" then "\"" else "!") .. string.sub(good, i + 1) +t:eq(code(bad), Err.CHECKSUM, "flipped character") +t:eq(code(string.sub(good, 1, #good - 3)), Err.TRUNCATED, "no closing colon") +t:eq(code("nothing"), Err.CORRUPT, "no banner") +t:eq(code("(This file must be converted with BinHex 4.0)\n:~~~:"), Err.CORRUPT, "bad character") +t:eq((select(2, Mod.encode({})) :: any).code, Err.ARG, "encode a non-archive") +t:fuzz("decode", function(b: buffer) + return Mod.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/archive/macbinary.luau b/tests/archive/macbinary.luau new file mode 100644 index 0000000..465f183 --- /dev/null +++ b/tests/archive/macbinary.luau @@ -0,0 +1,24 @@ +-- archive/macbinary tests: the macbinary cases of tools/fixtures/mac.py against The Unarchiver's listings, our output read by unar, +-- round trips with a resource fork and Finder info (tests/archive/_mac.luau), errors, the fuzz pass. +local Mod = require("@formats/archive/macbinary") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local run = require("@tests/archive/_mac") + +local t, samples = run("macbinary", Mod, { {} }) +local function code(s: string): string? + local _, e = Mod.decode(Bytes.reader(buffer.fromstring(s))) + return e and e.code +end +local good = Mod.encode("hello macbinary", { name = "h" }) :: buffer +local bad = buffer.create(buffer.len(good)) +buffer.copy(bad, 0, good) +buffer.writeu8(bad, 70, 1) +t:eq(code(buffer.tostring(bad)), Err.CHECKSUM, "header CRC") +t:eq(code(string.sub(buffer.tostring(good), 1, 140)), Err.TRUNCATED, "short data fork") +t:eq(code(string.rep("\1", 200)), Err.CORRUPT, "not MacBinary") +t:eq(code("short"), Err.TRUNCATED, "short header") +t:fuzz("decode", function(b: buffer) + return Mod.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:done() diff --git a/tools/fixtures/_arch2_ours.luau b/tools/fixtures/_arch2_ours.luau index b6bdc95..ed23662 100644 --- a/tools/fixtures/_arch2_ours.luau +++ b/tools/fixtures/_arch2_ours.luau @@ -32,6 +32,13 @@ end for _, f in files do a:add(f[1], f[2], { mtime = 1700000000, mode = 0x1A4 }) end +if opts.mac then + -- a Mac file: type / creator / flags on the data fork, a resource fork entry + local e = a._byName["hello.txt"] + e.macType, e.macCreator, e.finderFlags = "TEXT", "ttxt", 0x0100 + a:add("hello.txt.rsrc", content(700, 3), { mtime = 1700000000 }) + a._byName["hello.txt.rsrc"].fork = "resource" +end local out, err = a:write(opts) if not out then error(tostring(err)) diff --git a/tools/fixtures/mac.py b/tools/fixtures/mac.py new file mode 100644 index 0000000..fb8c624 --- /dev/null +++ b/tools/fixtures/mac.py @@ -0,0 +1,147 @@ +# Mac encodings fixtures (tools/fixtures.py) for archive/binhex, archive/macbinary and archive/applesingle: files with +# data and resource forks, type / creator / Finder flags and dates, imported into an HFS volume by hfsutils (`hcopy -m` +# of a MacBinary we build here) and exported by hfsutils as MacBinary II (`hcopy -m`) and BinHex 4.0 (`hcopy -b`); +# AppleSingle / AppleDouble v1 and v2 built here per RFC 1740. Every case's reference listing (but AppleSingle v1's, +# which unar does not read) comes from The Unarchiver (`lsar -j`, `unar -forks visible`: names, fork sizes, type / creator, data CRCs). Our writers' output +# (tools/fixtures/_arch2_ours.luau with a resource fork) is listed and extracted by unar the same way. +# tests/gen/mac.luau { cases = { { format, name, data, entries = { { name, size, crc, macType?, macCreator? } } } }, +# ours = { { format, variant?, ok, detail } } } +import importlib.util, json, os, shutil, struct, 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", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/binhex", + "src/Formats/archive/macbinary", "src/Formats/archive/applesingle", "src/Formats/containers/MacFile.luau"] +PKGS = ["hfsutils", "unar"] +MAC_EPOCH = 2082844800 + + +def crc16(data): + c = 0 + for b in data: + c ^= b << 8 + for _ in range(8): + c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF + return c + + +def macbinary(name, data, rsrc, ftype, creator, flags, mtime): + h = bytearray(128) + nm = name.encode("mac_roman") + h[1] = len(nm) + h[2:2 + len(nm)] = nm + h[65:73] = ftype + creator + h[73] = flags >> 8 + struct.pack_into(">IIII", h, 83, len(data), len(rsrc), mtime + MAC_EPOCH, mtime + MAC_EPOCH) + h[101] = flags & 255 + h[122], h[123] = 129, 129 + struct.pack_into(">H", h, 124, crc16(bytes(h[:124]))) + pad = lambda b: b + b"\0" * (-len(b) % 128) + return bytes(h) + pad(data) + pad(rsrc) + + +def apple(magic, version, entries): + filler = b"Macintosh " if version == 1 else b"\0" * 16 + hdr = struct.pack(">II16sH", magic, version << 16, filler, len(entries)) + off, tab, body = len(hdr) + 12 * len(entries), b"", b"" + for i, d in entries: + tab += struct.pack(">III", i, off + len(body), len(d)) + body += d + return hdr + tab + body + + +def listing(path, outdir, known): + """unar's view: [{name, size, crc, rsrc, macType, macCreator}]; names unar %-escaped become the known name""" + j = json.loads(A.tool(PKGS, ["lsar", "-j", path])) + A.tool(PKGS, ["unar", "-q", "-f", "-forks", "visible", "-o", outdir, path]) + out = [] + for e in j["lsarContents"]: + name = raw = e["XADFileName"] + if "%" in name and "%" not in known: + name = known + rsrc = bool(e.get("XADIsResourceFork")) + if rsrc and not e.get("XADFileSize"): + continue # an empty resource fork: not an entry in our convention + fn = os.path.join(outdir, raw + (".rsrc" if rsrc else "")) + b = open(fn, "rb").read() if os.path.exists(fn) else b"" + if rsrc: # unar writes the resource fork as AppleDouble: take entry 2 + n = struct.unpack_from(">H", b, 24)[0] + for k in range(n): + i, o, l = struct.unpack_from(">III", b, 26 + 12 * k) + if i == 2: + b = b[o:o + l] + d = {"name": name + (".rsrc" if rsrc else ""), "size": e.get("XADFileSize", 0), "crc": zlib.crc32(b)} + if "XADFileType" in e: + d["macType"] = struct.pack(">I", e["XADFileType"]).decode("latin-1") + d["macCreator"] = struct.pack(">I", e["XADFileCreator"]).decode("latin-1") + out.append(d) + if any(e["name"].endswith(".rsrc") for e in out): # an empty data fork beside a resource fork: no entry + out = [e for e in out if e["size"] or e["name"].endswith(".rsrc")] + return out + + +def generate(ctx): + rng = ctx.rng(17) + files = [ + ("Read Me", b"Hello from the data fork\r" * 40, rng.randbytes(1500), b"TEXT", b"ttxt", 0x0100), + ("Appé π", rng.randbytes(3000) + b"\x90" * 300 + b"\x90\x00\x90", b"", b"APPL", b"????", 0), + ("rsrc only", b"", bytes(range(256)) * 4 + b"\x00" * 600, b"rsrc", b"RSED", 0x2000), + ("runs", b"A" * 1000 + b"\x90" * 7 + b"B" * 2, b"\x90\x90", b"BINA", b"tool", 0), + ] + tmp = A.tmpdir() + cases = [] + try: + vol = os.path.join(tmp, "v.hfs") + with open(vol, "wb") as f: + f.truncate(4 * 1024 * 1024) + script = ["hformat -l Fixtures v.hfs >/dev/null"] + for k, (name, data, rsrc, t, c, fl) in enumerate(files): + open(os.path.join(tmp, "in%d.bin" % k), "wb").write(macbinary(name, data, rsrc, t, c, fl, A.MTIME)) + script.append("hcopy -m in%d.bin :" % k) + for k, (name, *_ ) in enumerate(files): + script.append("hcopy -m ':%s' out%d.bin" % (name, k)) + script.append("hcopy -b ':%s' out%d.hqx" % (name, k)) + script.append("humount") + # hfsutils names are Mac OS Roman bytes: the script file is written in that encoding + script.insert(1, "hmount v.hfs >/dev/null") + open(os.path.join(tmp, "run.sh"), "wb").write(("set -e\n" + "\n".join(script) + "\n").encode("mac_roman")) + A.tool(PKGS, ["sh", "run.sh"], cwd=tmp) + for k, (name, data, rsrc, t, c, fl) in enumerate(files): + for fmt, fn in (("macbinary", "out%d.bin" % k), ("binhex", "out%d.hqx" % k)): + p = os.path.join(tmp, fn) + cases.append({"format": fmt, "name": "hfsutils %s %s" % (fmt, name), "data": open(p, "rb").read(), "entries": listing(p, os.path.join(tmp, "x" + fn), name)}) + # AppleSingle v2, AppleDouble v2, AppleSingle v1 + fi = t + c + struct.pack(">H", fl) + b"\0" * 22 + dates = struct.pack(">iiii", A.MTIME - 946684800, A.MTIME - 946684800, -2 ** 31, -2 ** 31) + nm = name.encode("mac_roman") + for label, blob in ( + ("applesingle v2", apple(0x51600, 2, [(3, nm), (8, dates), (9, fi), (1, data), (2, rsrc)])), + ("appledouble v2", apple(0x51607, 2, [(9, fi), (2, rsrc), (3, nm)])), + ("applesingle v1", apple(0x51600, 1, [(3, nm), (7, struct.pack(">III", A.MTIME + MAC_EPOCH, A.MTIME + MAC_EPOCH, 0) + b"\0" * 4), (9, fi), (1, data), (2, rsrc)])), + ): + p = os.path.join(tmp, "as%d-%s" % (k, label.replace(" ", ""))) + open(p, "wb").write(blob) + if label.endswith("v1"): # unar reads version 2 only: the entries we built + ents = [{"name": name, "size": len(data), "crc": zlib.crc32(data), "macType": t.decode(), "macCreator": c.decode()}] if data or not rsrc else [] + if rsrc: + ents.append({"name": name + ".rsrc", "size": len(rsrc), "crc": zlib.crc32(rsrc)}) + else: + ents = listing(p, p + ".x", name) + cases.append({"format": "applesingle", "name": "%s %s" % (label, name), "data": blob, "entries": ents}) + ours = [] + for fmt, opts in (("binhex", "mac=true"), ("macbinary", "mac=true"), ("applesingle", "mac=true"), ("applesingle", "mac=true,double=true")): + blob = A.ours(ctx, fmt, opts) + p = os.path.join(tmp, "ours-" + fmt + opts.replace(",", "").replace("=", "")) + open(p, "wb").write(blob) + got = {e["name"]: e for e in listing(p, p + ".x", "hello.txt")} + hello, rs = A.FILES[0][1], A.content(700, 3) + want = {"hello.txt.rsrc": zlib.crc32(rs)} + if "double" not in opts: + want["hello.txt"] = zlib.crc32(hello) + ok = all(n in got and got[n]["crc"] == c for n, c in want.items()) and all(e.get("macType") == "TEXT" for e in got.values()) + ours.append({"format": fmt, "variant": opts, "ok": ok, "detail": json.dumps(list(got.values()))}) + ctx.emit("mac", {"cases": cases, "ours": ours}) + finally: + shutil.rmtree(tmp)