--!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/compress/Deflate) instead of injected. The writer is new: stored / deflated entries (codecs/compress/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("@rosetta/core/Err") local Types = require("@rosetta/Types") local Bytes = require("@rosetta/core/Bytes") local Crc32 = require("@rosetta/core/Crc32") local Deflate = require("@rosetta/codecs/compress/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 = table.create(math.min(count, 65536)) :: { any } 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 civil = Types.Date.civilFromDays 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