--!strict -- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their -- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS -- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7, -- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read. -- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower -- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header -- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu -- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc), -- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or -- at the first header found in the first 64 KB). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Crc16 = require("@formats/core/Crc16") local Lzh = require("@formats/codecs/compress/Lzh") local Archive = require("@formats/containers/Archive") -- ------------------------------------------------------------------------------------------------ contract local Lha = { name = "lha", category = "archive", extensions = { "lzh", "lha", "lzs" }, mime = { "application/x-lzh-compressed" }, deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" }, caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } }, } export type DecodeOptions = { maxBytes: number?, -- refuse an entry larger than this (default 2^30) maxEntries: number?, -- default 65536 } export type EncodeOptions = {} -- ------------------------------------------------------------------------------------------------ constants local METHODS: { [string]: boolean } = { ["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true, ["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true, ["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true, } -- ------------------------------------------------------------------------------------------------ sniff local function isHeader(s: string): boolean if #s < 22 then return false end local m = string.sub(s, 3, 7) local level = string.byte(s, 21) return METHODS[m] == true and level <= 3 end function Lha.sniff(r: Bytes.Reader): number if isHeader(r:peek(22)) then return 0.95 end return 0 end -- ------------------------------------------------------------------------------------------------ decode -- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them) local function path(s: string): string s = string.gsub(s, "[\\\255]", "/") local parts = {} for part in string.gmatch(s, "[^/]+") do if part ~= "." and part ~= ".." then table.insert(parts, part) end end return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "") end type Header = { method: string, packed: number, size: number, mtime: number?, level: number, name: string, dir: string?, crc: number?, mode: number?, uid: number?, gid: number?, uname: string?, gname: string?, attr: number?, comment: string?, os: string?, dataAt: number, } -- the extended headers from offset p (size field width w), until a zero size; returns the end offset local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?) local size = first local guard = 0 while size ~= 0 do guard += 1 if guard > 4096 or size < w + 1 or p + size > limit then return nil, "bad extended header" end local e = r:sub(p, size) local kind = e:u8() local body = size - 1 - w if kind == 0x01 then h.name = e:string(body) elseif kind == 0x02 then h.dir = e:string(body) elseif kind == 0x3F or kind == 0x71 then h.comment = e:string(body) elseif kind == 0x40 and body >= 2 then h.attr = e:u16le() elseif kind == 0x50 and body >= 2 then h.mode = e:u16le() elseif kind == 0x51 and body >= 4 then h.gid, h.uid = e:u16le(), e:u16le() elseif kind == 0x52 then h.gname = e:string(body) elseif kind == 0x53 then h.uname = e:string(body) elseif kind == 0x54 and body >= 4 then h.mtime = e:u32le() elseif kind == 0x42 and body >= 16 then h.packed, h.size = e:u64le(), e:u64le() end e:seek(size - w) local nextSize = if w == 2 then e:u16le() else e:u32le() if e.err then return nil, "truncated extended header" end p += size size = nextSize end return p, nil end local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386", [0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt", [0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" } -- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker local function header(r: Bytes.Reader, p: number): (Header?, string?) local limit = r:size() if p >= limit or r:sub(p, 1):u8() == 0 then return nil, nil end if p + 22 > limit then return nil, "truncated header" end local s = r:sub(p, 26) local b0 = s:u8() s:u8() local method = s:string(5) local packed, size, stamp = s:u32le(), s:u32le(), s:u32le() s:u8() local level = s:u8() if not METHODS[method] then return nil, "bad method " .. method end local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 } if level == 0 or level == 1 then local hsize = b0 + 2 if p + hsize > limit or hsize < 24 then return nil, "truncated header" end local hr = r:sub(p + 21, hsize - 21) local nlen = hr:u8() h.name = hr:string(nlen) h.crc = hr:u16le() h.mtime = Archive.fromDos(stamp) if level == 0 then -- an optional Unix extension: 'U', mtime, mode, uid, gid if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then h.os = if hr:u8() == 0x55 then "unix" else "os68k" h.mtime = hr:u32le() h.mode = hr:u16le() h.uid, h.gid = hr:u16le(), hr:u16le() end h.dataAt = p + hsize else h.os = OS[hr:u8()] local first = r:sub(p + hsize - 2, 2):u16le() local e, err = extended(r, p + hsize, 2, first, h, limit) if not e then return nil, err end h.packed = packed - (e - (p + hsize)) h.dataAt = e end if hr.err then return nil, "truncated header" end elseif level == 2 then local total = r:sub(p, 2):u16le() local hr = r:sub(p + 21, 5) h.crc = hr:u16le() local osByte = hr:u8() h.os = OS[osByte] if osByte == 0x4B then total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates) end local first = hr:u16le() h.mtime = stamp local e, err = extended(r, p + 26, 2, first, h, limit) if not e or hr.err then return nil, err or "truncated header" end h.dataAt = p + total if total < 26 or h.dataAt > limit then return nil, "bad level 2 header size" end elseif level == 3 then local hr = r:sub(p + 21, 11) h.crc = hr:u16le() h.os = OS[hr:u8()] local total = hr:u32le() local first = hr:u32le() h.mtime = stamp local e, err = extended(r, p + 32, 4, first, h, limit) if not e or hr.err then return nil, err or "truncated header" end h.dataAt = p + total if total < 32 or h.dataAt > limit then return nil, "bad level 3 header size" end else return nil, "unsupported: header level " .. level end return h, nil end local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" } local function encoder(a: any, o: any?): (buffer?, Err.Err?) return Lha.encode(a, o) end function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local o: DecodeOptions = opts or {} local maxBytes = o.maxBytes or 2 ^ 30 local maxEntries = o.maxEntries or 65536 local p = 0 -- a self-extracting stub: find the first header if not isHeader(r:peek(22)) then local head = r:peek(65536) local at = nil for k = 1, #head - 22 do if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then at = k - 1 break end end if not at then return nil, Err.new(Err.CORRUPT, "no LHA header") end p = at end local a = Archive.new("lha", encoder) local count = 0 local levels = {} while true do local h, err = header(r, p) if err then return nil, Err.from(err, r.base + p) end if not h then break end count += 1 if count > maxEntries then return nil, Err.new(Err.LIMIT, "more than maxEntries entries") end levels[h.level] = true if h.packed < 0 or h.dataAt + h.packed > r:size() then return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt) end -- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do local os = h.os if os == nil or os == "msdos" or os == "atari" or os == "os2" then if not string.find(h.name .. (h.dir or ""), "%l") then h.name = string.lower(h.name) h.dir = if h.dir then string.lower(h.dir) else nil end end -- the full path (a Unix symlink "name|target" may be split across the directory and file name headers) local name = path(h.name) if h.dir and h.dir ~= "" then local d = path(h.dir) if string.sub(d, -1) ~= "/" then d ..= "/" end name = d .. name end local link: string? = nil local bar = string.find(name, "|", 1, true) if bar then name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1) end local isDir = h.method == "lhd" if isDir and link == nil and string.sub(name, -1) ~= "/" then name ..= "/" end local e: any = { name = name, size = if isDir or link then 0 else h.size, compressedSize = h.packed, method = h.method, mtime = h.mtime, dir = isDir and link == nil, mode = h.mode, uid = h.uid, gid = h.gid, uname = h.uname, gname = h.gname, attr = h.attr, comment = h.comment, os = h.os, level = h.level, crc = h.crc, } if link then e.link = link e.type = "symlink" elseif not isDir and h.size > 0 then if h.size > maxBytes then return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") end local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc local buf, base = r.buf, r.base e.load = function(): (buffer?, Err.Err?) local out: buffer?, derr: string? if method == "lh0" or method == "lz4" then if packed < size then return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size") end out = buffer.create(size) buffer.copy(out :: buffer, 0, buf, base + at, size) elseif LZH_METHOD[method] then out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method]) else return nil, Err.new(Err.UNSUPPORTED, "method " .. method) end if not out then return nil, Err.from(derr) end if crc and Crc16.arc(out, 0, size) ~= crc then return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch") end return out, nil end end Archive.put(a, e) p = h.dataAt + h.packed end a.meta.source = { format = "lha", levels = levels } return a, nil end -- ------------------------------------------------------------------------------------------------ encode function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local items = Archive.entries(value) if not items then return nil, Err.new(Err.ARG, "expected an Archive") end local out = Bytes.writer() for _, it in items do local e: any = it.entry local data = buffer.create(0) if not e.dir then local b, err = it.read() if not b then return nil, err end data = b end local full = string.gsub(e.name, "/+$", "") local dirPart, base = string.match(full, "^(.*/)([^/]*)$") if not dirPart then dirPart, base = "", full end if e.dir then dirPart, base = full .. "/", "" end local h = Bytes.writer() h:u16le(0) -- total size, patched h:string(if e.dir then "-lhd-" else "-lh0-") h:u32le(buffer.len(data)) h:u32le(buffer.len(data)) h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0) h:u8(0x20) h:u8(2) h:u16le(Crc16.arc(data, 0, buffer.len(data))) h:u8(0x55) -- 'U'nix -- extended headers: [type][body][size of the next one]; the first size ends the base header local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } } if dirPart ~= "" then table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) }) end if type(e.mode) == "number" then local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000) table.insert(exts, { 0x50, string.char(m % 256, m // 256) }) end h:u16le(#exts[1][2] + 3) for i, x in exts do h:u8(x[1]) h:string(x[2]) h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0) end local hb = h:finish() local total = buffer.len(hb) if total > 65535 then return nil, Err.new(Err.ARG, "header too long for " .. e.name) end buffer.writeu16(hb, 0, total) -- the header CRC covers the whole header with its own field zero local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27 buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total)) out:bytes(hb) out:bytes(data) end out:u8(0) return out:finish(), nil end -- ------------------------------------------------------------------------------------------------ extras -- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data) function Lha.new(): any local a = Archive.new("lha", encoder) a.meta.source = { format = "lha" } return a end return Lha