Zip archives

Zip archives: the zip mod

mods/zip.luma reads and writes .zip archives: the ones zip and unzip, Windows Explorer, macOS and Python’s zipfile make and open. It is written in Luma, on deflate, crypto.crc32 and folders. Copy it next to your program and import it:

import "zip"

zip.pack(folder("site"), file("site.zip"))
zip.unpack(file("site.zip"), folder("restore"))
print(zip.names(file("site.zip")))
FunctionWhat it does
zip.pack(from, to)writes a folder’s files and folders, all the way down, to an archive (the folder’s contents are at its top)
zip.unpack(from, to)writes an archive’s files and folders into a folder, made if it isn’t there; a file that is there is replaced
zip.unpack(from, to, max)the same, writing at most max bytes (4 GB if not given)
zip.names(from)the paths in an archive, as a [str] (a folder’s end in /)
zip.make(files)an archive in memory, a [byte], from a {str: [byte]} of names and contents
zip.read(data)the files of an archive in memory, as a {str: [byte]}, e.g. one that came from a web request
files: {str: [byte]} = {"report.csv": convert("day,sales\n1,100\n")}
file("report.zip").write(zip.make(files))

What is kept

  • Each file is compressed with DEFLATE, or stored as it is when that isn’t smaller (and when it is under 100 bytes). Its CRC-32 is checked when it comes out.
  • Times are kept to the second, and permission bits too: an unpacked script still runs.
  • Names are UTF-8 (ü.txt, 日本.txt), and folders, empty ones too, are in the archive.
  • Archives larger than 4 GB or with more than 65535 entries are ZIP64, which every current tool reads.
  • An archive is written beside its path and takes it when it is whole, so a program that stops on the way never leaves half an archive.

Safety

Archives come from anywhere, so unpack checks what it writes:

  • A name that would land outside the folder (../evil.txt, /etc/passwd, C:/x) is refused: error zip.UNSAFE. Nothing is written beside the folder.
  • Links in an archive are left out (Luma doesn’t make links).
  • An archive that would write more than max bytes is refused before anything is written: error zip.TOO_BIG. A “zip bomb” of a few kilobytes can hold terabytes.
  • A damaged archive (a CRC-32 that doesn’t match, a size that is wrong) is refused: error zip.BROKEN.

Errors

CodeWhen
zip.BROKEN (100)not a zip archive, a damaged one, an encrypted entry, or a compression method other than stored and deflated (bzip2, LZMA, Zstandard)
zip.UNSAFE (101)a name that would land outside the folder
zip.TOO_BIG (102)more than max bytes

A folder or file that isn’t there raises the usual error 8, and anything else a file operation does, error 9.

Not available yet

  • Encrypted archives (ZipCrypto, AES), and compression methods other than DEFLATE.
  • Adding to an archive that is there, or taking one file out without reading the archive’s directory again.
  • Files larger than memory: each file is compressed or unpacked in memory, one at a time.