Skip to main content
coreydaley.dev

Inside ArchiveKit: no format registry, just the compiler

Rename a RAR to .zip and Purrchiver still opens it as a RAR. Rename a ZIP to .br and Purrchiver’s archive engine takes the name at its word.

Both come from the same piece of code, in ArchiveKit, the Swift package that does all of Purrchiver’s archive work. The app around it is SwiftUI, sheets and menus. ArchiveKit is the part that knows what a RAR5 header looks like, how 7-Zip derives an AES key, and which engine should handle the file you just dropped on the window.

This is a tour of how it’s put together, and of one asymmetry in it: adding a format you can create is checked by the compiler, and adding a format you can open isn’t.

Some of the code shown here is from the next release, marked where it matters.

Several engines, one Swift API

ArchiveKit is mostly a Swift layer over C and C++ libraries that do the real work:

EngineUsed for
libarchiveReads most formats, including unencrypted RAR. Writes ZIP, 7z, the tar family, the single-stream compressors, ISO and cpio
UnRAREncrypted RAR, and RAR5 archives libarchive refuses New in 1.1
Apple Archive.aar, and encrypted .aea
Brotli.br and .tar.br
ArchiveKit’s own SwiftStuffIt .sit and .sea, and the Mac wrappers BinHex, MacBinary and AppleSingle New in 1.1

The app never talks to any of them directly. It asks for an Archive and iterates its entries, or creates an ArchiveWriter with a format. Which engine is underneath is ArchiveKit’s business.

Some formats live one level up, in their own packages: disk images, age and .crypto encrypted files, and PAR2 recovery data. The app routes those before ArchiveKit ever sees them.

Why it carries its own C libraries

ArchiveKit compiles in its own copies of libarchive, UnRAR, xz, zstd, LZ4, Brotli and part of the LZMA SDK, even though macOS ships some of these. The main reasons:

  • xz: macOS has a liblzma, but no public headers for it. App Review rejected Purrchiver 1.0 under Guideline 2.5.1 for linking it.
  • zstd: macOS doesn’t include it, and without a compiled-in copy libarchive falls back to running a zstd program.
  • The LZMA SDK: libarchive’s 7z writer compresses on one thread, which made .7z about eight times slower than 7-Zip. The SDK’s multithreaded encoder closed that gap.
  • Brotli: Apple’s Compression framework has Brotli, but no quality setting.
  • libarchive and UnRAR: there’s no Apple equivalent for RAR or 7z at all.

Carrying libraries means carrying patches. Purrchiver’s libarchive adds 7z encryption, and in the next release New in 1.1 a Deflate64 decoder, Apple’s pbzx stream format and block-level salvage of damaged archives: about 1,500 lines of its own C in all. Fixes to libarchive itself go upstream.

Opening a file: signatures first, mostly

To open a file, ArchiveKit reads its first eight bytes. Rar! followed by \x1A\x07 is RAR whatever the file is called, which is why the renamed RAR still opens. Detection then walks a fixed list: encrypted Apple Archive and Apple Archive, 7z, RAR, the compressors (gzip, bzip2, xz, zstd, lzip, LZ4, .Z), then StuffIt, Windows executables and a few others.

Partway down, there’s a block of formats with no signature at the start, like .lzma and .br, which can only be matched by extension. Everything checked after that block, including ZIP’s PK, tar’s ustar at byte 257 and an ISO’s CD001 at 0x8001, loses to a matching name. That’s the renamed ZIP. The order of that list is load-bearing, and nothing but the order enforces it.

Multi-part sets get their own pass: .part1.rar, .r00, .7z.001, .zip.001, .z01, and byte-split tar files like .tar.gz.001 are recognized as one archive.

Then ArchiveKit picks the engine, and for RAR the deciding question isn’t the format but whether there’s a password (trimmed):

if let pass = passphrase {
    let sniff = sniffRARArchive(url)
    if sniff.isRAR {
        guard pass.isAllASCII else { throw ArchiveError.unicodePasswordNotSupported }
        try Self.verifyIdentityUnchanged(url: url, snapshot: sniff.identity)
        // A later part of a set is read from its first.
        let reader = try UnrarReader(url: VolumeSet.parts(of: url).first ?? url,
                                     passphrase: pass)
        return .unrar(reader)
    }
}
// …
try openLibarchive()

libarchive can’t decrypt RAR, so a password sends the file to UnRAR. Without one, RAR stays on libarchive, which a comment there says is faster and the more battle-tested path. In the next release New in 1.1, UnRAR also opens an encrypted set from its first part whichever part you picked, and takes over when libarchive refuses a RAR5 archive with a dictionary over 64 MB.

Around that choice:

  • The file is checked again before it’s parsed. That’s the verifyIdentityUnchanged line. ArchiveKit notes the file’s identity when it starts and confirms it’s the same file before an engine opens it, so a file swapped out in between isn’t read.
  • Formats it can’t read still get an answer. StuffIt X, ACE, lzop and a few others are detected so the app can say what the file is and what to use instead, rather than “unknown format”.
  • ArchiveKit doesn’t run outside programs New in 1.1. libarchive will decompress lrzip, lzop and grzip by running those tools. Those filters are now switched off.

Writing: a format plus a filter

libarchive splits an archive into two pieces: a format (how entries are laid out) and a filter (how the byte stream is compressed). A .tar.gz is the tar format through the gzip filter. A plain .gz is the “raw” format, a single stream with no entry headers, through the same filter.

So ArchiveWriter is mostly one switch (trimmed):

case .tarGz:
    archive_write_set_format_pax_restricted(h)
    archive_write_add_filter_gzip(h)
    // …
case .gzip:
    archive_write_set_format_raw(h)
    archive_write_add_filter_gzip(h)
    // …

Options are strings libarchive parses, like 7zip:encryption=aes256+header or xz:threads=N. The formats libarchive doesn’t write go to the other engines: Apple Archive through Apple’s framework, Brotli through the vendored library.

7z encryption is Purrchiver’s own addition to libarchive, about 300 lines of C on Apple’s CommonCrypto, and I’ve written up how that patch works, including why it caps how hard a hostile archive can make the key derivation work. Two things it does from the app’s side: setting a password on a new 7z always encrypts the headers too, so file names are hidden as well as contents, and passwords are ASCII-only for now.

The compiler is the registry

There’s no format registry: no single table that the UI, the file types and the free/paid split all read from. There are three enums:

  • ArchiveKind, the 45 kinds of file the reader recognizes, some only so it can explain why it won’t open them;
  • ArchiveFormat, what the writer can produce;
  • CompressFormatID, what you can pick in the Create sheet.

CompressFormatID is the app’s one source of truth for create formats. It replaced three copies of the list that had drifted apart in three different screens. Its properties are switch statements with no default:, and the code says why:

/// `switch self` with no `default:` so a new case fails to compile
/// until the author assigns it a tier.
public var isFreeToCreate: Bool {

Add a case and the build fails until you’ve decided whether it’s free or paid, which encryption it allows, whether it has a compression level, and which ArchiveFormat it maps to. ArchiveWriter’s switch over ArchiveFormat has no default: either. From the Create sheet down to the libarchive calls, a half-added create format doesn’t build.

Then tests check that the decisions add up:

  • free and paid formats must split the full list exactly, with no overlap;
  • the encryption options are swept across every format;
  • the stored names must match an exact list, because they’re saved in your presets, and renaming one would quietly break them;
  • every format offered in Shortcuts must map to a writer configuration;
  • a vendored library with no license entry in the About screen fails a test.

It still isn’t a one-line change. Adding CBZ as a create format New in 1.1 touched 15 files, though about a third of those were CBZ’s own page ordering and conversion. And a few create properties still have a default:, so those are decisions the compiler won’t ask for.

The read side is where it’s weakest. Detection is that ordered chain of checks, and the switch that hands a detected file to an engine ends in default: break. A new readable format can be detected and never routed, or routed and shadowed by an extension check above it, and everything builds. The app’s declared file types are hand-kept lists too, tested only against themselves.

Engines that can’t share

Two engines can’t run twice at once in one process. UnRAR keeps global state, including a password cache, so a second session throws rather than waiting. Apple Archive calls made concurrently fail intermittently with an unhelpful error. Both sit behind locks, and the app queues work for them, putting a drag-out you’re waiting on ahead of a batch job. The test suites run serially for the same reason.

How it’s tested

ArchiveKit has more than 600 tests and about 900 fixture files, and the app adds an interop suite that has real tools (7zz, tar, unzip, ditto, Apple’s aa) open Purrchiver’s archives and the other way round. Two parts of ArchiveKit’s suite stand out:

  • A damaged corpus: real malformed files collected from other projects' test suites (Apache Commons Compress, Go, libarchive, py7zr, yauzl). The bar is that nothing crashes, nothing hangs, and nothing is written outside the destination.
  • Read-only checks: every recovery path is wrapped in a test that the source file’s bytes, size and modification date are unchanged afterwards, including when it fails or is cancelled. Purrchiver never changes a damaged archive, and this is what holds it to that.

There’s no fuzzing. The closest thing is the corpus, some of which other projects’ fuzzers found. There’s more on the whole setup in how Purrchiver is tested.

If you’ve built something that reads many formats, how do you stop a new one from being half-added: a registry, exhaustive switches, or tests?

Related posts