From be534d9b1de86a0c61be11e289dcca06a41dab06 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 08:51:05 -0500 Subject: [PATCH] absorb: containers/Zip (reader from zip-luau 121d4b0 with a direct codecs/Deflate require, Err values; new writer: store/deflate, UTF-8, DOS times, raw copies, ZIP64) + archive/zip (Types.Archive list/read/add/remove/write, create, encode); tests vs Python zipfile --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/archive/zip/init.luau | 238 ++++++++++ src/Formats/containers/Zip/init.luau | 668 +++++++++++++++++++++++++++ tests/archive/zip.luau | 268 +++++++++++ tools/fixtures/zip.py | 161 +++++++ 7 files changed, 1349 insertions(+) create mode 100644 src/Formats/archive/zip/init.luau create mode 100644 src/Formats/containers/Zip/init.luau create mode 100644 tests/archive/zip.luau create mode 100644 tools/fixtures/zip.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index deb0912..37fde15 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 3167a65..cc2e25f 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -12,6 +12,7 @@ | `src/Formats/audio/flac/` | flac-luau 7083d0d (same author), written from RFC 9639 | no licence chosen yet; no third-party code | | `src/Formats/image/bmp/` | bmp-luau b86aed6 (same author), written from the Microsoft BMP documentation | no licence chosen yet; no third-party code | | `tests/fixtures/bmpsuite/` | BMP Suite 2.8 by Jason Summers (generated images) | public domain: [bmpsuite-NOTICE.txt](bmpsuite-NOTICE.txt) | +| `src/Formats/containers/Zip/` (the reader), `src/Formats/archive/zip/` | zip-luau 121d4b0 (same author), written from PKWARE's APPNOTE.TXT 6.3 | no licence chosen yet; no third-party code | | `tests/fixtures/pngsuite/` | PngSuite by Willem van Schaik | [PngSuite-LICENSE.txt](PngSuite-LICENSE.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2503f9d..ba721ff 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "zip", + category = "archive", + path = "archive/zip", + 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 }, + load = function() + return require("@formats/archive/zip") + end, + }, } return list diff --git a/src/Formats/archive/zip/init.luau b/src/Formats/archive/zip/init.luau new file mode 100644 index 0000000..081a7e0 --- /dev/null +++ b/src/Formats/archive/zip/init.luau @@ -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/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("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Container = require("@formats/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 diff --git a/src/Formats/containers/Zip/init.luau b/src/Formats/containers/Zip/init.luau new file mode 100644 index 0000000..1545ce2 --- /dev/null +++ b/src/Formats/containers/Zip/init.luau @@ -0,0 +1,668 @@ +--!strict +--!optimize 2 +-- containers/Zip: the ZIP container (PKWARE APPNOTE 6.3): a reader and a writer. The reader is absorbed from +-- zip-luau 121d4b0 (same author, no third-party code): the end of central directory record (searched back over an +-- archive comment), the central directory, ZIP64 (records, locator, extra fields), a prefix shift (self-extractor +-- stubs), stored and deflated entries with a CRC-32 check, data descriptors, a wrong local header fallback, +-- case-insensitive / basename lookup that skips __MACOSX. The DEFLATE codec is now required directly +-- (codecs/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/Deflate compress, stored +-- when that is not smaller), UTF-8 names, DOS times, raw copies of existing entries, ZIP64 when needed. +-- +-- local zip, err = Zip.open(buf) -- buffer, string or core/Bytes Reader +-- for _, e in zip:list() do print(e.name, e.size) end +-- local data, err = zip:read("Main.bmp") -- exact, then case-insensitive, then by basename; CRC-checked +-- +-- local w = Zip.writer() +-- w:add("readme.txt", "hello", { level = 9 }) -- or { method = "store" }, mtime = unix seconds +-- local file = w:finish({ comment = "..." }) +-- +-- Never throws: corrupt archives and bad arguments return nil, Err. Parsing runs interpreted (it is cold); the native +-- code it reaches (Deflate, Crc32) does not throw either. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/Deflate") + +local Zip = {} +Zip.version = "1.1.0" + +export type Entry = { + name: string, -- the path with "\" turned into "/" + rawName: string, -- the name bytes as stored + index: number, -- position in the central directory, 1-based + size: number, -- uncompressed size + compressedSize: number, + crc32: number, + method: number, -- 0 stored, 8 deflate (others are listed but not readable) + flags: number, -- general purpose bits (1 encrypted, 8 data descriptor, 2048 UTF-8 name) + offset: number, -- local header offset (already corrected for a prefix such as a self-extractor stub) + isDir: boolean, + utf8: boolean, + comment: string, + modified: { year: number, month: number, day: number, hour: number, min: number, sec: number }, + mtime: number, -- the modification time as Unix seconds (the DOS time read as UTC) + time: number, -- the raw DOS time and date + date: number, + attributes: number, -- external attributes + -- central-directory lengths of the name and extra field (a fallback when the local header is wrong) + cdNameLen: number, + cdExtraLen: number, +} + +-- ------------------------------------------------------------------------------------------------ read +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +local SIG_LOCAL, SIG_CD, SIG_EOCD = 0x04034b50, 0x02014b50, 0x06054b50 +local SIG_Z64_EOCD, SIG_Z64_LOC = 0x06064b50, 0x07064b50 + +local function readu64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +local function sigAt(b: buffer, o: number, sig: number): boolean + return o >= 0 and o + 4 <= buffer.len(b) and readu32(b, o) == sig +end + +local function normalize(name: string): string + name = string.gsub(name, "\\", "/") + name = string.gsub(name, "^%./", "") + name = string.gsub(name, "^/+", "") + return name +end + +local function basename(name: string): string + return string.match(name, "([^/]*)/*$") or name +end + +-- junk that shares a basename with real files: macOS resource forks +local function isJunk(name: string): boolean + local l = string.lower(name) + return string.find(l, "__macosx/", 1, true) ~= nil or string.sub(basename(l), 1, 2) == "._" +end + +local Archive = {} +Archive.__index = Archive + + +-- isZip(buf) -> true when buf starts like a zip (a local header, or the end record of an empty archive) +function Zip.isZip(buf: buffer | string): boolean + local b = if type(buf) == "string" then buffer.fromstring(string.sub(buf, 1, 4)) else buf + return sigAt(b, 0, SIG_LOCAL) or sigAt(b, 0, SIG_EOCD) +end + +local function findEocd(b: buffer): number? + local n = buffer.len(b) + local fallback = nil + local stop = math.max(0, n - 22 - 65535) + for p = n - 22, stop, -1 do + if readu8(b, p) == 0x50 and readu32(b, p) == SIG_EOCD then + if p + 22 + readu16(b, p + 20) == n then + return p + end + fallback = fallback or p -- comment length disagrees (trailing junk or a wrong length): keep looking + end + end + return fallback +end + +local function parse(b: buffer): (any, Err.Err?) + local n = buffer.len(b) + if n < 22 then + return nil, Err.new(Err.TRUNCATED, "too small for an end of central directory record") + end + local eocd = findEocd(b) + if not eocd then + return nil, Err.new(Err.CORRUPT, "no end of central directory record") + end + local count = readu16(b, eocd + 10) + local cdSize = readu32(b, eocd + 12) + local cdOff = readu32(b, eocd + 16) + local commentLen = math.min(readu16(b, eocd + 20), n - eocd - 22) + local comment = buffer.readstring(b, eocd + 22, commentLen) + local cdEnd = eocd + -- ZIP64: the locator sits just before the end record + local zip64 = false + if sigAt(b, eocd - 20, SIG_Z64_LOC) then + local z = readu64(b, eocd - 20 + 8) + if not sigAt(b, z, SIG_Z64_EOCD) then + -- a prefix shifted everything: the record directly precedes the locator (56 bytes + extensible data) + local guess = eocd - 20 - 56 + if sigAt(b, guess, SIG_Z64_EOCD) then + z = guess + else + z = -1 + end + end + if z >= 0 and z + 56 <= n then + zip64 = true + count = readu64(b, z + 32) + cdSize = readu64(b, z + 40) + cdOff = readu64(b, z + 48) + cdEnd = z + end + end + if not zip64 and (count == 0xFFFF or cdSize == 0xFFFFFFFF or cdOff == 0xFFFFFFFF) then + return nil, Err.new(Err.CORRUPT, "ZIP64 fields without a ZIP64 record") + end + -- a prefix (self-extractor stub, or a zip appended to another file) shifts every offset + local delta = 0 + if count > 0 and not sigAt(b, cdOff, SIG_CD) then + delta = cdEnd - (cdOff + cdSize) + if not sigAt(b, cdOff + delta, SIG_CD) then + return nil, Err.new(Err.CORRUPT, "central directory not found") + end + end + local entries: { any } = table.create(math.min(count, 65536)) + local p = cdOff + delta + for i = 1, count do + if not sigAt(b, p, SIG_CD) or p + 46 > n then + return nil, Err.new(Err.CORRUPT, string.format("bad central directory entry %d", i), p) + end + local flags = readu16(b, p + 8) + local method = readu16(b, p + 10) + local time, date = readu16(b, p + 12), readu16(b, p + 14) + local crc = readu32(b, p + 16) + local csize, usize = readu32(b, p + 20), readu32(b, p + 24) + local nameLen, extraLen, cmtLen = readu16(b, p + 28), readu16(b, p + 30), readu16(b, p + 32) + local disk = readu16(b, p + 34) + local off = readu32(b, p + 42) + if p + 46 + nameLen + extraLen + cmtLen > n then + return nil, Err.new(Err.TRUNCATED, string.format("central directory entry %d runs past the end", i), p) + end + local raw = buffer.readstring(b, p + 46, nameLen) + -- extra fields: ZIP64 (0x0001) holds the 32-bit fields that are all ones, in this order + local q, qe = p + 46 + nameLen, p + 46 + nameLen + extraLen + while q + 4 <= qe do + local id, sz = readu16(b, q), readu16(b, q + 2) + if id == 0x0001 then + local r, re = q + 4, math.min(q + 4 + sz, qe) + if usize == 0xFFFFFFFF and r + 8 <= re then + usize = readu64(b, r) + r += 8 + end + if csize == 0xFFFFFFFF and r + 8 <= re then + csize = readu64(b, r) + r += 8 + end + if off == 0xFFFFFFFF and r + 8 <= re then + off = readu64(b, r) + r += 8 + end + if disk == 0xFFFF and r + 4 <= re then + disk = readu32(b, r) + end + end + q += 4 + sz + end + local name = normalize(raw) + entries[i] = { + name = name, + rawName = raw, + index = i, + size = usize, + compressedSize = csize, + crc32 = crc, + method = method, + flags = flags, + offset = off + delta, + isDir = string.sub(raw, -1) == "/" or string.sub(raw, -1) == "\\", + utf8 = bit32.band(flags, 0x800) ~= 0, + comment = buffer.readstring(b, qe, cmtLen), + modified = { + year = 1980 + bit32.rshift(date, 9), + month = bit32.band(bit32.rshift(date, 5), 15), + day = bit32.band(date, 31), + hour = bit32.rshift(time, 11), + min = bit32.band(bit32.rshift(time, 5), 63), + sec = bit32.band(time, 31) * 2, + }, + mtime = Zip.unixTime(time, date), + time = time, + date = date, + attributes = readu32(b, p + 38), + cdNameLen = nameLen, + cdExtraLen = extraLen, + } + p = qe + cmtLen + end + local exact, lower, base = {}, {}, {} + for _, e in entries do + if not e.isDir then + exact[e.name] = exact[e.name] or e + local l = string.lower(e.name) + lower[l] = lower[l] or e + if not isJunk(e.name) then + local bn = basename(l) + local prev = base[bn] + -- prefer the shallowest path, then the first in directory order + if not prev or select(2, string.gsub(e.name, "/", "")) < select(2, string.gsub(prev.name, "/", "")) then + base[bn] = e + end + end + end + end + return setmetatable({ + buf = b, + entries = entries, + comment = comment, + zip64 = zip64, + _exact = exact, + _lower = lower, + _base = base, + }, Archive) +end + +-- open(src) -> Archive | nil, Err. src: a buffer, a string, or a core/Bytes Reader (its range is copied when it is a +-- part of a bigger buffer) +function Zip.open(src: any): (any, Err.Err?) + local b: buffer + if type(src) == "string" then + b = buffer.fromstring(src) + elseif type(src) == "buffer" then + b = src + elseif type(src) == "table" and type(src.buf) == "buffer" then + if src.base == 0 and src.limit == buffer.len(src.buf) then + b = src.buf + else + local n = math.max(0, src.limit - src.base) + b = buffer.create(n) + buffer.copy(b, 0, src.buf, src.base, n) + end + else + return nil, Err.new(Err.ARG, "open: expected a buffer, a string or a Reader") + end + local ok, res, err = pcall(parse, b) + if not ok then + return nil, Err.new(Err.CORRUPT, "corrupt archive (" .. tostring(res) .. ")") + end + return res, err +end + +-- every entry (directories included), in central directory order +function Archive.list(self: any): { Entry } + return self.entries +end + +-- find(name) -> entry | nil: the exact path, else the path case-insensitively, else the basename +-- case-insensitively (skins sometimes nest everything in a folder). "\" and "/" are the same; directories and +-- macOS "__MACOSX/" / "._" files never match by basename. +function Archive.find(self: any, name: string): Entry? + local n = normalize(name) + local e = self._exact[n] + if e then + return e + end + local l = string.lower(n) + e = self._lower[l] + if e then + return e + end + return self._base[basename(l)] +end + +local function extract(b: buffer, e: Entry, dataStart: number): (buffer?, any) + local n = buffer.len(b) + if dataStart > n then + return nil, "data starts past the end" + end + if e.method == 0 then + if dataStart + e.size > n then + return nil, "truncated stored data" + end + local out = buffer.create(e.size) + buffer.copy(out, 0, b, dataStart, e.size) + return out + end + local len = math.min(e.compressedSize, n - dataStart) + local out, err = Deflate.inflate(b, dataStart, len, e.size) + if not out then + -- a wrong size in the directory: inflate without it and let the CRC decide + local out2 = Deflate.inflate(b, dataStart, n - dataStart) + if out2 then + return out2 + end + return nil, if type(err) == "table" then err.message else tostring(err) + end + return out +end + +-- the data offset candidates of an entry: the local header's own lengths, then the central directory's (some writers +-- get the local extra length wrong) +function Zip._starts(b: buffer, e: Entry): { number } + local o = e.offset + local starts = {} + if o >= 0 and o + 30 <= buffer.len(b) and readu32(b, o) == SIG_LOCAL then + table.insert(starts, o + 30 + readu16(b, o + 26) + readu16(b, o + 28)) + end + local alt = o + 30 + e.cdNameLen + e.cdExtraLen + if alt ~= starts[1] then + table.insert(starts, alt) + end + if alt ~= o + 30 + e.cdNameLen then + table.insert(starts, o + 30 + e.cdNameLen) + end + return starts +end + +-- read(entry | name, verify = true) -> buffer | nil, Err +function Archive.read(self: any, entry: Entry | string, verify: boolean?): (buffer?, Err.Err?) + local e: Entry? = if type(entry) == "string" then self:find(entry) else entry :: Entry + if not e then + return nil, Err.new(Err.ARG, "no entry " .. tostring(entry)) + end + if e.isDir then + return buffer.create(0), nil + end + if bit32.band(e.flags, 1) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, e.name .. " is encrypted") + end + if e.method ~= 0 and e.method ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, string.format("%s uses compression method %d (only stored and deflate)", e.name, e.method)) + end + local b = self.buf + local n = buffer.len(b) + local o = e.offset + if o < 0 or o + 30 > n then + return nil, Err.new(Err.CORRUPT, e.name .. ": local header out of range", o) + end + local starts = Zip._starts(b, e) + local firstErr: string? = nil + local code = Err.CORRUPT + for _, s in starts do + local out, err = extract(b, e, s) + if out then + if verify == false then + return out, nil + end + if buffer.len(out) ~= e.size then + err = string.format("size %d, expected %d", buffer.len(out), e.size) + else + local c = Deflate.crc32(out) + if c == e.crc32 then + return out, nil + end + err = string.format("CRC-32 mismatch (%08x, expected %08x)", c, e.crc32) + end + end + firstErr = firstErr or err + end + return nil, Err.new(if firstErr and string.find(firstErr, "CRC", 1, true) then Err.CHECKSUM else code, e.name .. ": " .. tostring(firstErr)) +end + +-- readString(entry | name, verify?) -> string | nil, Err +function Archive.readString(self: any, entry: Entry | string, verify: boolean?): (string?, Err.Err?) + local out, err = self:read(entry, verify) + if not out then + return nil, err + end + return buffer.tostring(out), nil +end + +-- ------------------------------------------------------------------------------------------------ write +local Writer = {} +Writer.__index = Writer + +export type AddOptions = { + method: ("deflate" | "store")?, -- default "deflate" (stored instead when deflate does not make it smaller) + level: number?, -- deflate level 0..9 (default 6) + mtime: number?, -- modification time, Unix seconds (UTC); default 1980-01-01 00:00:00 (reproducible output) + comment: string?, + utf8: boolean?, -- set the UTF-8 name flag (default: when the name is not plain ASCII) + attributes: number?, -- external attributes (default: Unix 0644 for files, 0755 + MS-DOS directory for dirs) +} +export type FinishOptions = { + comment: string?, -- the archive comment + zip64: boolean?, -- force the ZIP64 records (default: only when counts, sizes or offsets need them) +} + +-- writer() -> Writer +function Zip.writer(): any + return setmetatable({ files = {} :: { any } }, Writer) +end + +-- days from 1970-01-01 to y-m-d (proleptic Gregorian) +local function civil(z: number): (number, number, number) + z += 719468 + local era = (if z >= 0 then z else z - 146096) // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + local m = if mp < 10 then mp + 3 else mp - 9 + return (if m <= 2 then y + 1 else y), m, d +end +local function daysFrom(y: number, m: number, d: number): number + y = if m <= 2 then y - 1 else y + local era = (if y >= 0 then y else y - 399) // 400 + local yoe = y - era * 400 + local mp = if m > 2 then m - 3 else m + 9 + local doy = (153 * mp + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + return era * 146097 + doe - 719468 +end + +-- Unix seconds -> DOS time, date (clamped to 1980..2107) +function Zip.dosTime(t: number?): (number, number) + if type(t) ~= "number" or t ~= t then + return 0, 0x21 + end + local s = math.floor(t) + local days = s // 86400 + local rem = s - days * 86400 + local y, m, d = civil(days) + if y < 1980 then + return 0, 0x21 + elseif y > 2107 then + y, m, d, rem = 2107, 12, 31, 86399 + end + local time = (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2 + return time, (y - 1980) * 512 + m * 32 + d +end + +-- DOS time, date -> Unix seconds (UTC) +function Zip.unixTime(time: number, date: number): number + local y = 1980 + bit32.rshift(date, 9) + local m = math.clamp(bit32.band(bit32.rshift(date, 5), 15), 1, 12) + local d = math.clamp(bit32.band(date, 31), 1, 31) + return daysFrom(y, m, d) * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2 +end + +local function isAscii(s: string): boolean + return string.find(s, "[\128-\255]") == nil +end + +-- add(name, data, opts?) -> true | false, Err: compresses now (data: buffer or string) +function Writer.add(self: any, name: string, data: any, opts: AddOptions?): (boolean, Err.Err?) + if type(name) ~= "string" or name == "" or #name > 65535 then + return false, Err.new(Err.ARG, "add: bad entry name") + end + local b: buffer + if type(data) == "string" then + b = buffer.fromstring(data) + elseif type(data) == "buffer" then + b = data + elseif data == nil and string.sub(name, -1) == "/" then + b = buffer.create(0) + else + return false, Err.new(Err.ARG, "add: data must be a buffer or a string") + end + local o: AddOptions = opts or {} + local method = o.method or "deflate" + if method ~= "deflate" and method ~= "store" then + return false, Err.new(Err.ARG, "add: method must be deflate or store") + end + local isDir = string.sub(name, -1) == "/" + local n = buffer.len(b) + local comp, code = b, 0 + if method == "deflate" and n > 0 and not isDir then + local z, zerr = Deflate.compress(b, { level = o.level or 6 }) + if not z then + return false, zerr + end + if buffer.len(z) < n then + comp, code = z, 8 + end + end + local time, date = Zip.dosTime(o.mtime) + table.insert(self.files, { + name = name, + method = code, + crc = if n > 0 then Crc32.of(b) else 0, + size = n, + data = comp, + dataOffset = 0, + dataLength = buffer.len(comp), + time = time, + date = date, + comment = o.comment or "", + utf8 = if o.utf8 ~= nil then o.utf8 else not isAscii(name), + attributes = o.attributes or (if isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- addRaw(entry, archive): copy an entry of an opened archive without recompressing it -> true | false, Err +function Writer.addRaw(self: any, e: Entry, archive: any, newName: string?): (boolean, Err.Err?) + local b = archive.buf + local start: number? = nil + for _, s in Zip._starts(b, e) do + if s >= 0 and s + e.compressedSize <= buffer.len(b) then + start = s + break + end + end + if not start or bit32.band(e.flags, 1) ~= 0 then + return false, Err.new(Err.CORRUPT, e.name .. ": cannot copy the entry data") + end + local name = newName or e.name + table.insert(self.files, { + name = name, + method = e.method, + crc = e.crc32, + size = e.size, + data = b, + dataOffset = start, + dataLength = e.compressedSize, + time = e.time or 0, + date = e.date or 0x21, + comment = e.comment or "", + utf8 = e.utf8 or not isAscii(name), + attributes = e.attributes or (if e.isDir then 0x41ED0010 else 0x81A40000), + }) + return true, nil +end + +-- finish(opts?) -> the archive | nil, Err +function Writer.finish(self: any, opts: FinishOptions?): (buffer?, Err.Err?) + local comment = opts and opts.comment or "" + if #comment > 65535 then + return nil, Err.new(Err.ARG, "finish: archive comment over 65535 bytes") + end + local force = opts and opts.zip64 or false + local total = 22 + #comment + 98 + for _, f in self.files do + total += 30 + #f.name + 20 + f.dataLength + 46 + #f.name + 28 + #f.comment + end + if total > 0x3FFFFFFF then + return nil, Err.new(Err.LIMIT, "finish: the archive would be over 1 GiB") + end + local w = Bytes.writer(total) + local offsets = {} + for i, f in self.files do + local off = w:tell() + offsets[i] = off + local big = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local flags = if f.utf8 then 0x800 else 0 + w:u32le(SIG_LOCAL) + w:u16le(if big then 45 else 20) + w:u16le(flags) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if big then 0xFFFFFFFF else f.dataLength) + w:u32le(if big then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if big then 20 else 0) + w:string(f.name) + if big then + w:u16le(1) + w:u16le(16) + w:u64le(f.size) + w:u64le(f.dataLength) + end + w:bytes(f.data, f.dataOffset, f.dataLength) + end + local cdOff = w:tell() + for i, f in self.files do + local off = offsets[i] + local bigSize = force or f.size >= 0xFFFFFFFF or f.dataLength >= 0xFFFFFFFF + local bigOff = force or off >= 0xFFFFFFFF + local extra = (if bigSize then 16 else 0) + (if bigOff then 8 else 0) + local version = if bigSize or bigOff then 45 else 20 + w:u32le(SIG_CD) + w:u16le(0x0300 + version) -- made by: Unix + w:u16le(version) + w:u16le(if f.utf8 then 0x800 else 0) + w:u16le(f.method) + w:u16le(f.time) + w:u16le(f.date) + w:u32le(f.crc) + w:u32le(if bigSize then 0xFFFFFFFF else f.dataLength) + w:u32le(if bigSize then 0xFFFFFFFF else f.size) + w:u16le(#f.name) + w:u16le(if extra > 0 then extra + 4 else 0) + w:u16le(#f.comment) + w:u16le(0) -- disk + w:u16le(0) -- internal attributes + w:u32le(f.attributes) + w:u32le(if bigOff then 0xFFFFFFFF else off) + w:string(f.name) + if extra > 0 then + w:u16le(1) + w:u16le(extra) + if bigSize then + w:u64le(f.size) + w:u64le(f.dataLength) + end + if bigOff then + w:u64le(off) + end + end + w:string(f.comment) + end + local cdSize = w:tell() - cdOff + local count = #self.files + local z64 = force or count >= 0xFFFF or cdOff >= 0xFFFFFFFF or cdSize >= 0xFFFFFFFF + if z64 then + local rec = w:tell() + w:u32le(SIG_Z64_EOCD) + w:u64le(44) + w:u16le(0x032D) + w:u16le(45) + w:u32le(0) + w:u32le(0) + w:u64le(count) + w:u64le(count) + w:u64le(cdSize) + w:u64le(cdOff) + w:u32le(SIG_Z64_LOC) + w:u32le(0) + w:u64le(rec) + w:u32le(1) + end + w:u32le(SIG_EOCD) + w:u16le(0) + w:u16le(0) + w:u16le(if z64 then 0xFFFF else count) + w:u16le(if z64 then 0xFFFF else count) + w:u32le(if z64 then 0xFFFFFFFF else cdSize) + w:u32le(if z64 then 0xFFFFFFFF else cdOff) + w:u16le(#comment) + w:string(comment) + return w:finish(), nil +end + +return Zip diff --git a/tests/archive/zip.luau b/tests/archive/zip.luau new file mode 100644 index 0000000..26efdec --- /dev/null +++ b/tests/archive/zip.luau @@ -0,0 +1,268 @@ +-- archive/zip + containers/Zip tests: generated archives (comment with a fake end record, data descriptors, +-- force_zip64, an all-ZIP64 archive, 66000 entries, a prefix stub, a wrong local header, unicode, empty) read entry by +-- entry against Python's zipfile listing (and every Webamp demo skin when SKINS_DIR is set); lookup rules; bad CRC, +-- encrypted and unsupported entries; the writer (stored / deflated, levels, UTF-8 names, DOS times, comments, ZIP64, +-- raw copies) read back; the Archive API (list / read / add / remove / write, create, encode of a table) and the api; +-- corrupt input never throws. The writer's output was also checked by hand: `unzip -t`, Python zipfile and 7z read it. +-- Ported from zip-luau tests/zip.luau. Fixtures: tools/fixtures/zip.py. +local T = require("@tests/T") +local Zip = require("@formats/containers/Zip") +local ZipF = require("@formats/archive/zip") +local Deflate = require("@formats/codecs/Deflate") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local F = require("@formats") +local Fx = require("@tests/gen/zip_cases") + +local t = T.suite("zip") + +local function dataOf(a: any): string + if a.data then + return a.data + end + return buffer.tostring(Deflate.zlib(buffer.fromstring(a.dataZ)) :: buffer) +end + +-- open an archive and compare it with zipfile's listing; read every entry +local function verify(a: any, label: string): (any, number) + local z, err = Zip.open(dataOf(a)) + t:check(z, label .. ": open: " .. tostring(err)) + local list = z:list() + t:eq(#list, a.count, label .. ": entries") + local bytes = 0 + for i, want in a.entries do + local e = list[i] + t:check(e.rawName == want[1] or e.name == string.gsub(want[1], "\\", "/"), label .. ": name " .. e.rawName) + t:check(e.size == want[2] and e.crc32 == want[3] and e.method == want[4], label .. ": " .. e.name .. " size / crc / method") + local data, rerr = z:read(e) + t:check(data, label .. ": read " .. e.name .. ": " .. tostring(rerr)) + t:check(buffer.len(data :: buffer) == want[2] and Crc32.of(data :: buffer) == want[3], label .. ": " .. e.name .. " content") + bytes += want[2] + end + return z, bytes +end + +local byName = {} +for _, a in Fx.archives do + byName[a.name] = a + a.zip = verify(a, a.name) +end +t:note("%d generated archives match Python zipfile", #Fx.archives) +local total, nent = 0, 0 +for _, s in Fx.skins do + local _, bytes = verify(s, s.name) + total += bytes + nent += s.count +end +if #Fx.skins > 0 then + t:note("%d skins, %d entries, %.2f MB read and CRC-checked", #Fx.skins, nent, total / 1e6) +else + t:note("(no skins: set SKINS_DIR to the Webamp demo skins)") +end + +-- lookup and specifics +do + local z = byName.basic.zip + t:eq(z:find("readme.txt").name, "readme.txt", "find exact") + t:eq(z:find("README.TXT").name, "readme.txt", "find case-insensitive") + t:eq(z:find("main.bmp").name, "Skin/Main.BMP", "find by basename skips __MACOSX") + t:eq(z:find("skin\\MAIN.bmp").name, "Skin/Main.BMP", "find with backslashes") + t:check(z:find("__MACOSX/Skin/._Main.BMP") ~= nil, "junk still found by its full path") + t:check(z:find("Skin/") == nil, "directories are not found") + t:check(z:find("nope.bmp") == nil, "missing") + t:eq(z:find("deep.txt").name, "Skin/sub/deep.txt", "basename in a deeper folder") + t:eq(z:readString("DEEP.TXT"), "deep", "readString by name") + t:eq(z:readString("Other/\u{fc}nicode.txt"), "h\u{e9}llo", "unicode basename") + local u = z:find("sk\u{ef}n/\u{fc}nicode.txt") + t:check(u and u.utf8 and z:readString(u) == "h\u{e9}llo", "unicode name") + local m = z:find("readme.txt").modified + t:check(m.year == 2020 and m.month == 5 and m.day == 17 and m.hour == 13 and m.min == 37 and m.sec == 42, "dos time") + t:eq(z:find("readme.txt").mtime, 1589722662, "mtime (unix seconds)") + local _, e = z:read("nope") + t:check(e and e.code == Err.ARG, "read a missing name") + t:eq(string.sub(byName.comment.zip.comment, 1, 14), "a comment with", "archive comment") + t:check(byName.zip64_by_hand.zip.zip64 and byName.many.zip.zip64, "zip64 records detected") + t:check(bit32.band(byName.descriptors.zip:list()[1].flags, 8) ~= 0, "data descriptor flag") + t:check(not byName.basic.zip.zip64, "basic is not zip64") + t:eq(byName.many.zip:readString("d/65999.txt"), "65999", "last of 66000 entries") + t:eq(#byName.empty.zip:list(), 0, "empty archive") + t:check(Zip.isZip(byName.basic.data) and Zip.isZip(byName.empty.data) and not Zip.isZip("GIF89a"), "isZip") + -- a sub-range reader + local s = byName.basic.data + local big = buffer.create(#s + 10) + buffer.writestring(big, 4, s) + local zs = Zip.open(Bytes.reader(big, 4, #s)) + t:check(zs and zs:readString("readme.txt") ~= nil, "open a sub-range Reader") +end + +-- a bad CRC, encrypted and unsupported entries +do + local data = buffer.fromstring(byName.basic.data) + local z = Zip.open(byName.basic.data) + local st = z:find("stored.bin") + local p = st.offset + 30 + buffer.readu16(data, st.offset + 26) + buffer.readu16(data, st.offset + 28) + 10 + buffer.writeu8(data, p, bit32.bxor(buffer.readu8(data, p), 0xFF)) + local z2 = Zip.open(data) + local out, err = z2:read("stored.bin") + t:check(out == nil and err.code == Err.CHECKSUM, "stored CRC mismatch: " .. tostring(err)) + t:check(z2:read("stored.bin", false) ~= nil, "verify = false") + local e = table.clone(z:find("readme.txt")) + e.flags = 1 + local _, ee = z:read(e) + t:check(ee and ee.code == Err.UNSUPPORTED, "encrypted refused") + e.flags, e.method = 0, 12 + local _, merr = z:read(e) + t:check(merr and merr.code == Err.UNSUPPORTED and string.find(merr.message, "method 12", 1, true), "bzip2 refused: " .. tostring(merr)) + local _, oe = Zip.open(5 :: any) + t:check(oe and oe.code == Err.ARG, "a non-buffer argument") +end + +-- the writer +do + local rand = T.rng(5) + local w = Zip.writer() + local files = {} + local text = string.rep("the quick brown fox jumps over the lazy dog ", 2000) + local noise = buffer.create(5000) + for i = 0, 4999 do + buffer.writeu8(noise, i, rand(2147483648) // 8388608) + end + local function put(name: string, data: any, opts: any?) + t:check(w:add(name, data, opts), "add " .. name) + table.insert(files, { name, if type(data) == "string" then data elseif data then buffer.tostring(data) else "" }) + end + put("text.txt", text, { level = 9, mtime = 1589722662 }) + put("stored.txt", text, { method = "store" }) + put("noise.bin", noise) -- deflate is not smaller: stored + put("empty.txt", "") + put("dir/", nil) + put("dir/\u{fc}nicode.txt", "h\u{e9}llo", { comment = "a file comment" }) + put("level0.txt", text, { level = 0 }) + local out, err = w:finish({ comment = "archive comment" }) + t:check(out, "finish: " .. tostring(err)) + local z = Zip.open(out :: buffer) + t:check(z, "our archive opens") + local list = z:list() + t:eq(#list, #files, "entry count") + for i, f in files do + t:eq(list[i].name, f[1], "name " .. i) + t:eq(z:readString(list[i]), f[2], "content " .. f[1]) + end + t:eq(list[1].method, 8, "deflated") + t:check(list[1].compressedSize < #text // 10, "compressed") + t:eq(list[2].method, 0, "stored") + t:eq(list[3].method, 0, "incompressible data is stored") + t:check(list[5].isDir, "directory entry") + t:check(list[6].utf8 and not list[1].utf8, "UTF-8 flag only for non-ASCII names") + t:eq(list[6].comment, "a file comment", "entry comment") + t:eq(list[1].mtime, 1589722662, "mtime round trip") + local md = list[1].modified + t:check(md.year == 2020 and md.month == 5 and md.day == 17 and md.hour == 13 and md.min == 37 and md.sec == 42, "dos time written") + t:check(list[2].modified.year == 1980 and list[2].modified.month == 1 and list[2].modified.day == 1, "default time 1980-01-01") + t:eq(z.comment, "archive comment", "archive comment written") + t:check(not z.zip64, "small archive is not ZIP64") + -- forced ZIP64 + local w64 = Zip.writer() + w64:add("a.txt", text) + w64:add("b.txt", "bee", { method = "store" }) + local z64 = Zip.open(w64:finish({ zip64 = true }) :: buffer) + t:check(z64 and z64.zip64 and z64:readString("a.txt") == text and z64:readString("b.txt") == "bee", "forced ZIP64 round trip") + -- over 65535 entries: the ZIP64 end record + local wm = Zip.writer() + for i = 0, 65999 do + wm:add(string.format("d/%05d.txt", i), tostring(i), { method = "store" }) + end + local zm = Zip.open(wm:finish() :: buffer) + t:check(zm and zm.zip64 and #zm:list() == 66000 and zm:readString("d/65999.txt") == "65999", "66000 entries") + -- dates + for _, s in { 315532800, 946684799, 1700000000, 4354819198 } do + local tm, dt = Zip.dosTime(s) + t:eq(Zip.unixTime(tm, dt), s - s % 2, "dos time of " .. s) + end + t:check(select(2, Zip.dosTime(0)) == 0x21, "before 1980 clamps") + -- bad arguments + t:check(not w:add("", "x"), "empty name") + t:check(not w:add("x", 5 :: any), "bad data") + t:check(not w:add("x", "y", { method = "lzma" } :: any), "bad method") +end + +-- the Archive (archive/zip) +do + t:eq(ZipF.name, "zip", "name") + t:eq(ZipF.category, "archive", "category") + local a, err = ZipF.decode(Bytes.reader(buffer.fromstring(byName.basic.data))) + t:check(a and a.kind == "archive" and a.format == "zip", "decode: " .. tostring(err)) + local list = a:list() + t:eq(#list, byName.basic.count, "list") + t:check(list[1].name == "readme.txt" and list[1].method == "deflate" and not list[1].dir and list[1].mtime == 1589722662, "entry fields") + t:check(list[4].dir, "dir entry") + local rd = a:read("readme.txt") + t:check(rd and Crc32.of(rd :: buffer) == byName.basic.entries[1][3], "read") + t:check(a:read("MAIN.bmp") ~= nil, "read by the lookup rules") + -- edit: replace, add, remove, then write; unchanged entries are copied raw + a:add("readme.txt", "replaced") + a:add("new/one.txt", string.rep("x", 1000), { level = 9 }) + t:check(a:remove("Skin/stored.bin") and not a:remove("nope"), "remove") + local out = a:write() :: buffer + local b = ZipF.decode(Bytes.reader(out)) :: any + t:check(b, "rewritten archive opens") + t:eq(buffer.tostring(b:read("readme.txt")), "replaced", "replaced entry") + t:eq(buffer.tostring(b:read("new/one.txt")), string.rep("x", 1000), "added entry") + t:check(b:read("Skin/stored.bin") == nil, "removed entry") + t:check(b:read("Skin/Main.BMP") and Crc32.of(b:read("Skin/Main.BMP")) == byName.basic.entries[2][3], "copied entry") + local names = {} + for _, e in b:list() do + table.insert(names, e.name) + end + t:eq(table.concat(names, ","), "readme.txt,Skin/Main.BMP,Skin/,Skin/sub/deep.txt,empty.txt,__MACOSX/Skin/._Main.BMP,Sk\u{ef}n/\u{fc}nicode.txt,new/one.txt", "order kept") + -- create, encode of a table, encode of another Archive + local c = ZipF.create() + c:add("hello.txt", "hi") + local cz = ZipF.decode(Bytes.reader(ZipF.encode(c) :: buffer)) :: any + t:eq(buffer.tostring(cz:read("hello.txt")), "hi", "create + encode") + local tz = ZipF.decode(Bytes.reader(ZipF.encode({ ["b.txt"] = "bee", ["a.txt"] = buffer.fromstring("ay") }) :: buffer)) :: any + t:check(tz:list()[1].name == "a.txt" and buffer.tostring(tz:read("b.txt")) == "bee", "encode a { name = data } table") + local _, ee = ZipF.encode(5 :: any) + t:check(ee and ee.code == Err.ARG, "encode a number") + -- comments survive a rewrite + local cm = ZipF.decode(Bytes.reader(buffer.fromstring(byName.comment.data))) :: any + t:eq(string.sub(Zip.open(cm:write()).comment, 1, 14), "a comment with", "comment kept on write") + -- the api + local la = F.archive.load(byName.basic.data) + t:check(la and la.kind == "archive" and #la:list() == byName.basic.count, "F.archive.load") + t:eq(F.detect(byName.basic.data), "zip", "F.detect") + local saved = F.save(la, nil, { format = "zip" }) + t:check(saved and #Zip.open(saved):list() == byName.basic.count, "F.save zip") + local saved2 = F.save(la) + t:check(saved2 ~= nil, "F.save without a format uses the source format") +end + +-- corrupt archives never throw +local samples = {} +for _, a in Fx.archives do + if a.data then + table.insert(samples, a.data) + end +end +t:fuzz("open + read every entry", function(b: buffer) + local z = Zip.open(b) + if z then + for _, e in z:list() do + z:read(e) + end + end + return z +end, samples, { mutations = 40 }) +t:fuzz("archive decode + write", function(b: buffer) + local a = ZipF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 10, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/zip.py b/tools/fixtures/zip.py new file mode 100644 index 0000000..3a66642 --- /dev/null +++ b/tools/fixtures/zip.py @@ -0,0 +1,161 @@ +# ZIP fixtures (tools/fixtures.py): containers/Zip + archive/zip. Ported from zip-luau tools/fixtures.py. +# tests/gen/zip_cases.luau generated archives with Python zipfile's view of every entry ({ name, size, crc, method }): +# stored and deflate entries, an archive comment holding a fake end record, data descriptors, +# force_zip64, a hand-built all-ZIP64 archive, 66000 entries (ZIP64 end record), a prefix +# stub, a wrong local extra length, unicode names, empty; plus every .wsz skin in $SKINS_DIR +# when it is set (the Webamp demo skins; not redistributable, so not committed). Archives +# over 1 MB are stored zlib-compressed (dataZ) +import io, os, random, struct, sys, zipfile, zlib + +SKINS = os.environ.get("SKINS_DIR", "") +TEXT = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % i for i in range(3000)) + + +class Unseekable(io.RawIOBase): + def __init__(self): + self.buf = bytearray() + def writable(self): + return True + def write(self, b): + self.buf += b + return len(b) + +def mk(files, comment=b"", stream=False, force64=False): + out = Unseekable() if stream else io.BytesIO() + with zipfile.ZipFile(out, "w") as z: + for name, data, method in files: + zi = zipfile.ZipInfo(name, (2020, 5, 17, 13, 37, 42)) + zi.compress_type = method + if force64: + with z.open(zi, "w", force_zip64=True) as f: + f.write(data) + else: + z.writestr(zi, data) + z.comment = comment + return bytes(out.buf if stream else out.getvalue()) + +def zip64_by_hand(files): + # every size / offset field is 0xFFFFFFFF with the values in ZIP64 extras, plus the ZIP64 end record + locator + local, cd = bytearray(), bytearray() + for name, data in files: + n = name.encode() + c = zlib.compressobj(9, zlib.DEFLATED, -15) + comp = c.compress(data) + c.flush() + crc = zlib.crc32(data) + off = len(local) + lx = struct.pack(" the archive zipfile reads for the expected listing (when zipfile cannot read the real one) + def add(label, data, ref=None): + archives.append((label, data)) + if ref is not None: + REF[label] = ref + + add("basic", mk(basic)) + # zipfile itself takes the fake end record in this comment (it searches for the last signature) + add("comment", mk(basic[:3], comment=b"a comment with a fake end record PK\x05\x06" + b"\0" * 18 + b" and more" * 100), mk(basic[:3])) + add("descriptors", mk(basic[:6], stream=True)) + add("force_zip64", mk(basic[:6], force64=True)) + add("zip64_by_hand", zip64_by_hand([("a.txt", TEXT), ("b/c.bin", rng.randbytes(4000)), ("z.txt", b"")])) + add("prefixed", b"MZ" + b"\x90" * 3000 + mk(basic[:3])) + add("empty", mk([])) + w = bytearray(mk([("x.txt", TEXT, D), ("y.txt", b"why" * 1000, S)])) + struct.pack_into(" 1000000: + c["dataZ"] = zlib.compress(data, 9) # big archives (66000 entries): zlib, inflated by the test + else: + c["data"] = data + out[key].append(c) + ctx.emit("zip_cases", out)