ws-arch2: archive/yenc (yEnc 1.3 read incl. multi-part in one text, write; CRC checks)

This commit is contained in:
4DBug committed 2026-10-31 14:00:46 -05:00
1 parent 8cdb65367a
commit fe44292f58
6 files changed
+387

No files matched your search

+1
View File
@@ -56,6 +56,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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` |
| archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
| data | cbor | .cbor | yes | yes | binary: true, ordered: true, tags: true | `tests/data/cbor.luau` |
+12
View File
@@ -626,6 +626,18 @@ local list: { Entry } = {
return require("@formats/archive/xz")
end,
},
{
name = "yenc",
category = "archive",
path = "archive/yenc",
extensions = { "yenc", "ync" },
mime = { "application/x-yenc" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" },
caps = { decode = true, encode = true, multipart = true },
load = function()
return require("@formats/archive/yenc")
end,
},
{
name = "zip",
category = "archive",
+276
View File
@@ -0,0 +1,276 @@
--!strict
-- archive/yenc: yEnc-encoded binaries (yEnc 1.3: =ybegin / =ypart / =yend, byte + 42 with "=" escapes) as an Archive:
-- every =ybegin block is a file; the parts of a multi-part file found in the same text are joined at their =ypart
-- begin offsets. The part CRC (pcrc32) and, once all parts are there, the file CRC (crc32) and size are verified
-- (Err.CHECKSUM / Err.CORRUPT); missing parts leave a short file with meta.incomplete listing it. One file makes a
-- single-stream archive (meta.stream). Written from the yEnc 1.3 draft (Jürgen Helbing); writing produces one
-- single-part block per file with 128-character lines, escaping NUL, LF, CR, "=" and a leading / trailing TAB, space
-- or ".", as uuenview / yencode do. Not supported: joining parts spread over several files (concatenate them first).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Yenc = {
name = "yenc",
category = "archive",
extensions = { "yenc", "ync" },
mime = { "application/x-yenc" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "containers/Archive" },
caps = { decode = true, encode = true, multipart = true },
}
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
export type EncodeOptions = {
line: number?, -- characters per line (default 128)
name: string?, -- the name of a buffer / string value (default "data")
}
-- ------------------------------------------------------------------------------------------------ sniff
function Yenc.sniff(r: Bytes.Reader): number
local head = r:peek(4096)
if string.match(head, "^=ybegin ") then
return 0.95
end
return if string.find(head, "\n=ybegin [^\n]*name=") then 0.6 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- key=value fields of a keyword line; name= runs to the end of the line
local function fields(line: string): { [string]: string }
local f: { [string]: string } = {}
local s, name = string.match(line, "^(.-)name=(.*)$")
if s then
f.name = string.gsub(name :: string, "%s+$", "")
line = s
end
for k, v in string.gmatch(line, "(%w+)=(%S+)") do
f[k] = v
end
return f
end
-- decode the data lines [i, j) of src into out at o; returns the new o (stops at the end of out)
local function decodeData(src: buffer, i: number, j: number, out: buffer, o: number): number
local lim = buffer.len(out)
local esc = false
for p = i, j - 1 do
local c = buffer.readu8(src, p)
if c == 13 or c == 10 then
continue
end
if c == 61 and not esc then
esc = true
continue
end
if esc then
c -= 64
esc = false
end
if o < lim then
buffer.writeu8(out, o, (c - 42) % 256)
end
o += 1
end
return o
end
-- count the decoded bytes of the data lines [i, j)
local function countData(src: buffer, i: number, j: number): number
local n, esc = 0, false
for p = i, j - 1 do
local c = buffer.readu8(src, p)
if c ~= 13 and c ~= 10 then
if c == 61 and not esc then
esc = true
else
esc = false
n += 1
end
end
end
return n
end
type Part = { first: number, last: number, from: number, to: number, pcrc: number?, part: number? }
type File = { name: string, size: number, crc: number?, parts: { Part }, total: number? }
local function hex(s: string?): number?
return if s and string.match(s, "^%x+$") and #s <= 8 then tonumber(s, 16) else nil
end
local function parse(b: buffer, base: number, limit: number): ({ File }?, string?)
local files: { File } = {}
local byName: { [string]: File } = {}
local p = base
local cur: File? = nil
local part: Part? = nil
while p < limit do
local nl = p
while nl < limit and buffer.readu8(b, nl) ~= 10 do
nl += 1
end
local isKey = nl - p >= 2 and buffer.readu8(b, p) == 61 and buffer.readu8(b, p + 1) == 121 -- "=y"
if isKey then
local line = string.gsub(buffer.readstring(b, p, nl - p), "\r$", "")
local kw = string.match(line, "^=y(%a+)")
local f = fields(line)
if kw == "begin" then
local name = f.name
local size = tonumber(f.size or "")
if not name or name == "" or not size or size < 0 then
return nil, "=ybegin without name or size"
end
local 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)
end
cur = file
part = { first = 0, last = size, from = nl + 1, to = nl + 1, part = tonumber(f.part or "") }
elseif kw == "part" and part then
local first, last = tonumber(f.begin or ""), tonumber(f["end"] or "")
if not first or not last or first < 1 or last < first - 1 then
return nil, "bad =ypart range"
end
part.first, part.last = first - 1, last
part.from, part.to = nl + 1, nl + 1
elseif kw == "end" and part and cur then
part.pcrc = hex(f.pcrc32)
if f.crc32 then
cur.crc = hex(f.crc32)
end
local size = tonumber(f.size or "")
if size and size ~= part.last - part.first then
return nil, "=yend size " .. size .. " does not match the part (" .. (part.last - part.first) .. ")"
end
table.insert(cur.parts, part)
part = nil
end
elseif part then
part.to = nl + 1
end
p = nl + 1
end
if part then
return nil, "truncated: no =yend"
end
if #files == 0 then
return nil, "no =ybegin line"
end
return files, nil
end
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
return Yenc.encode(a, o)
end
function Yenc.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxBytes = o.maxBytes or 2 ^ 30
local b = r.buf
local files, perr = parse(b, r.base, math.min(r.limit, buffer.len(b)))
if not files then
return nil, Err.from(perr)
end
local a = Archive.new("yenc", encoder)
local incomplete = {}
for _, f in files do
if f.size > maxBytes then
return nil, Err.new(Err.LIMIT, f.name .. ": size over maxBytes")
end
local out = buffer.create(f.size)
local covered = 0
for _, pt in f.parts do
local n = countData(b, pt.from, pt.to)
if n ~= pt.last - pt.first or pt.last > f.size then
return nil, Err.new(Err.CORRUPT, f.name .. ": part data is " .. n .. " bytes, the header says " .. (pt.last - pt.first))
end
local tmp = buffer.create(n)
decodeData(b, pt.from, pt.to, tmp, 0)
if pt.pcrc and Crc32.of(tmp) ~= pt.pcrc then
return nil, Err.new(Err.CHECKSUM, f.name .. ": part CRC mismatch")
end
buffer.copy(out, pt.first, tmp, 0, n)
covered += n
end
local whole = covered == f.size
if whole and f.crc and Crc32.of(out) ~= f.crc then
return nil, Err.new(Err.CHECKSUM, f.name .. ": CRC mismatch")
end
if not whole then
table.insert(incomplete, f.name)
end
Archive.put(a, { name = f.name, size = f.size, dir = false, method = "yenc", data = out, complete = whole })
end
a.meta.stream = #files == 1
a.meta.incomplete = if #incomplete > 0 then incomplete else nil
a.meta.source = { format = "yenc" }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Yenc.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local lineLen = o.line or 128
if type(lineLen) ~= "number" or lineLen < 2 or lineLen > 997 then
return nil, Err.new(Err.ARG, "line must be 2..997")
end
local files, err = Archive.files(value, o.name)
if not files then
return nil, err
end
if #files == 0 then
return nil, Err.new(Err.ARG, "nothing to encode")
end
local w = Bytes.writer()
for _, f in files do
if string.find(f.name, "[\r\n]") then
return nil, Err.new(Err.ARG, "file names may not contain line breaks")
end
local data = f.data
local n = buffer.len(data)
w:string(string.format("=ybegin line=%d size=%d name=%s\r\n", lineLen, n, f.name))
local col = 0
for i = 0, n - 1 do
local c = (buffer.readu8(data, i) + 42) % 256
local critical = c == 0 or c == 10 or c == 13 or c == 61
if not critical and (c == 9 or c == 32) and (col == 0 or col >= lineLen - 1 or i == n - 1) then
critical = true
elseif not critical and c == 46 and col == 0 then
critical = true
end
if critical then
w:u8(61)
w:u8((c + 64) % 256)
col += 2
else
w:u8(c)
col += 1
end
if col >= lineLen and i < n - 1 then
w:string("\r\n")
col = 0
end
end
if n > 0 then
w:string("\r\n")
end
w:string(string.format("=yend size=%d crc32=%08x\r\n", n, Crc32.of(data)))
end
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty yEnc Archive: a:add(name, data); a:write({ line })
function Yenc.new(): any
local a = Archive.new("yenc", encoder)
a.meta.source = { format = "yenc" }
return a
end
return Yenc
+53
View File
@@ -0,0 +1,53 @@
-- archive/yenc tests: single-part files by uuenview -y (including every byte value and the critical characters), a
-- multi-part posting in order and reversed, two files in one text; part / file CRC and size checks; an incomplete
-- posting; our output decodes with uudeview (fixture step) and round-trips; errors; the fuzz pass.
-- Fixtures: tools/fixtures/yenc.py.
local T = require("@tests/T")
local F = require("@formats")
local Yenc = require("@formats/archive/yenc")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local E = require("@tests/archive/_entries")
local Fx = require("@tests/gen/yenc")
local t = T.suite("yenc")
t:eq(Yenc.name, "yenc", "name")
local samples = {}
for _, c in Fx.cases do
local a, err = Yenc.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
if a then
E.check(t, a, c.entries, c.name)
t:eq(a.meta.incomplete, nil, c.name .. ": complete")
end
t:eq(F.detect(c.data), "yenc", c.name .. ": detect")
if #c.data < 20000 then
table.insert(samples, c.data)
end
end
t:check(Fx.ours.ok, "our output decodes with uudeview")
E.roundTrip(t, Yenc, nil, "round trip")
E.roundTrip(t, Yenc, { line = 7 }, "round trip, 7-character lines")
-- only the first part of a posting: a short file flagged incomplete
local p = Yenc.decode(Bytes.reader(buffer.fromstring(Fx.partial))) :: any
t:check(p and p.meta.incomplete and p.meta.incomplete[1] == "big.bin" and p:list()[1].complete == false, "incomplete posting")
-- errors
local good = buffer.tostring(Yenc.encode("hello", { name = "h" }) :: buffer)
local function code(s: string): string?
local _, e = Yenc.decode(Bytes.reader(buffer.fromstring(s)))
return e and e.code
end
t:eq(code((string.gsub(good, "crc32=%x+", "crc32=00000000"))), Err.CHECKSUM, "bad crc32")
t:eq(code((string.gsub(good, "=yend size=5", "=yend size=6"))), Err.CORRUPT, "size mismatch")
t:eq(code((string.gsub(good, "=yend[^\n]*\n", ""))), Err.TRUNCATED, "no =yend")
t:eq(code("nothing\n"), Err.CORRUPT, "no =ybegin")
t:eq(code("=ybegin line=128 size=99999999999 name=x\n=yend size=99999999999\n"), Err.LIMIT, "huge size")
t:eq((select(2, Yenc.encode("x", { line = 1 })) :: any).code, Err.ARG, "bad line length")
t:fuzz("decode", function(b: buffer)
return Yenc.decode(Bytes.reader(b))
end, samples)
t:done()
+1
View File
@@ -31,6 +31,7 @@ def tool(pkgs, argv, cwd=None, input=None, check=True):
def ours(ctx, fmt, opts=""):
"""our writer's output for the standard file set (bytes)"""
script = os.path.join(ctx.root, "tools", "fixtures", "_arch2_ours.luau")
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [script, "-a", fmt, opts]
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
+44
View File
@@ -0,0 +1,44 @@
# yEnc fixtures (tools/fixtures.py): single-part files by uudeview's `uuenview -y`, a multi-part posting (uuenview -y
# -200 split into parts, concatenated into one text, parts in reverse order too), a text with two files; our writer's
# output (tools/fixtures/_arch2_ours.luau) decoded by `uudeview`.
# tests/gen/yenc.luau { cases = { { name, data, entries = { { name, size, crc } } } }, ours = { ok } }
import importlib.util, os, shutil, 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/yenc"]
PKG = ["uudeview"]
def generate(ctx):
tmp = A.tmpdir()
try:
big = ("big.bin", ctx.rng(9).randbytes(90000))
files = A.FILES + [big, ("crit.bin", bytes(range(256)) * 3 + b"\x00\r\n=\t . " * 50)]
A.tree(files, tmp)
ent = {n: {"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in files}
cases, texts = [], {}
for n, _ in files:
texts[n] = A.tool(PKG, ["uuenview", "-y", n], cwd=tmp)
cases.append({"name": "uuenview -y " + n, "data": texts[n], "entries": [ent[n]]})
A.tool(PKG, ["uuenview", "-y", "-200", "-od", tmp, "big.bin"], cwd=tmp)
parts = sorted(f for f in os.listdir(tmp) if f.startswith("big.") and f[4:].isdigit())
assert len(parts) >= 2, parts
bodies = [open(os.path.join(tmp, p), "rb").read() for p in parts]
cases.append({"name": "multipart (%d parts)" % len(parts), "data": b"".join(bodies), "entries": [ent["big.bin"]]})
cases.append({"name": "multipart reversed", "data": b"\n".join(reversed(bodies)), "entries": [ent["big.bin"]]})
cases.append({"name": "two files", "data": b"header text\n" + texts["hello.txt"] + b"\nbetween\n" + texts["crit.bin"], "entries": [ent["hello.txt"], ent["crit.bin"]]})
d = A.tmpdir()
try:
p = os.path.join(d, "ours.txt")
open(p, "wb").write(A.ours(ctx, "yenc"))
A.tool(PKG, ["uudeview", "-i", "-p", d + "/", p], cwd=d)
got = A.read_tree(d)
ok = all(got.get(n) == zlib.crc32(b) for n, b in A.FILES if b)
finally:
shutil.rmtree(d)
ctx.emit("yenc", {"cases": cases, "ours": {"ok": ok}, "partial": bodies[0]})
finally:
shutil.rmtree(tmp)