C library and SDK

include/peel.h and libpeel_ffi: how to link them, who frees what, how errors, passwords, cancellation and sessions work, and complete examples in C, Swift, Python, Go and Node.

Peel 1.4.0 · Snack Studio · Updated

The C ABI is how the Mac app itself calls the engine, and how anything that can load a C library can too. It is one header, include/peel.h, and one library, built as both libpeel_ffi.a and libpeel_ffi.dylib. There are 37 functions. Most take paths and return a JSON string; a few return bytes, and the rest manage cancel tokens and sessions.

Build and link

TerminalShell
git clone git@github.com:SnackStudio/peel.git && cd peel
cargo build --release -p peel-ffi
# target/release/libpeel_ffi.a   target/release/libpeel_ffi.dylib   include/peel.h

The rules

Strings and bytes: who frees what

You receiveFree it with
A char * from any function (JSON, UTF-8, NUL-terminated)peel_string_free(s)
An unsigned char * from peel_read_member* or peel_session_read_memberpeel_bytes_free(ptr, len)
A PeelSession *peel_session_close(s)
A PeelCancelToken *peel_cancel_token_free(t), after the call it was passed to has returned

Never call free() on these: they come from Rust’s allocator, not yours. Strings you pass in are borrowed for the call only: UTF-8, NUL-terminated.

Errors

A function that returns a string returns either its result or an error object, so check for "error" before using it:

Error objectJSON
{"error": "wrong_password", "detail": "…engine text, for logs…"}

kind is one of damaged, wrong_password, password_required, not_enough_space (adds needed and available), unsupported, permission_denied, decompression_bomb, too_large (adds size and max for one member), cancelled, io, not_found, invalid_name, unsafe_entry, already_exists, other, or panic. Show people your own words for the kind; detail is for logs. Functions that return bytes return NULL on failure; the session variants also fill an error JSON out-parameter.

Panic safety

No call unwinds into C. The library runs inside Quick Look, Spotlight and an XPC service, where a Rust panic crossing the boundary would take the host down. Every export catches a panic and returns {"error": "panic", "detail": …}, which means that archive could not be read. Calls that return no string fall back to 0, NULL or nothing. Keep Rust’s default panic = "unwind" if you build the library yourself.

Passwords

Use the *_with_password functions. They take the password as UTF-8, NUL-terminated (NULL or "" for none), copy it once, wipe their copy before returning, and never read the environment. Wipe your own copy too. The older peel_extract, peel_extract_to, peel_extract_member, peel_extract_entry and peel_read_member still read PEEL_PASSWORD for existing callers. Any process of the same user can read the environment, so do not set it.

Cancellation

A PeelCancelToken stops one call and only that call. Create it, pass it to a *_with_token or session function, call peel_cancel_token_cancel from any thread, and free it once the call has returned. The cancelled call returns {"error": "cancelled"} and leaves no partial file. A NULL token never cancels, and a call given a token ignores the process-wide flag.

The process-wide flag (peel_cancel, peel_cancel_clear, peel_cancel_requested) stops whatever is running that has no token of its own. peel_extract_entry does not clear it, so call peel_cancel_clear() first if you use it.

Sessions

A PeelSession is an archive opened once for many member reads. A ZIP keeps its directory in memory, so each read skips the open and the scan. Sessions can be shared between threads; reads on one session run one at a time. If the file changes after the session was opened, reads fail with an io error rather than answering from a stale index; open a new one. peel_session_status returns {"path", "format", "state"} with state open, invalidated or closed.

The functions

GroupFunctions
Extractpeel_extract (takes a PeelPolicy struct), peel_extract_to, peel_extract_with_password
Listpeel_list, peel_list_limited, peel_list_limited_with_token, peel_list_limited_with_password
One member, to diskpeel_extract_member, peel_extract_entry, peel_extract_entry_with_token, peel_extract_entry_with_password
One member, to memorypeel_read_member, peel_read_member_with_password, peel_bytes_free; peel_read_member_fd returns an open descriptor to an unlinked file instead, for handing to another process
Sessionspeel_session_open, peel_session_status, peel_session_read_member, peel_session_read_member_range, peel_session_close
Understandpeel_probe, peel_inspect, peel_assess, peel_formats
Recoverpeel_find_originals, peel_unlock, peel_unlock_known, peel_salvage, peel_recover_plan
Cancelpeel_cancel, peel_cancel_clear, peel_cancel_requested, peel_cancel_token_new, peel_cancel_token_cancel, peel_cancel_token_is_cancelled, peel_cancel_token_free
Memorypeel_string_free, peel_bytes_free

Extract policy

peel_extract takes a PeelPolicy by value; peel_extract_to and peel_extract_with_password take the same three fields as arguments, which is easier from languages that cannot build a C struct.

peel.hC
typedef struct PeelPolicy {
    const char *destination; /* nullable: beside the archive */
    uint32_t collision;      /* 0=error 1=overwrite 2=rename 3=skip */
    uint32_t enclosing;      /* 0=when_needed 1=always 2=never */
} PeelPolicy;

The result is the same JSON the CLI prints for extract -j: format, destination, extracted, skipped, sources.

Reading one member

Recovery

peel_find_originals(archive, roots) and peel_unlock(archive, roots, dest) take the folders to search as one string. peel_unlock_known also accepts explicit originals: newline-separated ENTRY<tab>FILE pairs, matched on contents, and needs at least one of roots or known to be non-empty. peel_salvage(archive, dest) writes whatever is readable from a damaged archive into dest and reports each file as recovered, partial or unrecoverable.

C

List an archive, then open it once and read a member with a cancel token. This is the complete program.

demo.cC
#include <stdio.h>
#include "peel.h"

int main(int argc, char **argv) {
    if (argc < 3) { fprintf(stderr, "usage: demo ARCHIVE MEMBER\n"); return 2; }

    char *json = peel_list(argv[1]);        /* entries, or {"error": ...} */
    if (!json) return 1;
    puts(json);
    peel_string_free(json);

    char *err = NULL;
    PeelSession *s = peel_session_open(argv[1], NULL, &err);
    if (!s) { fprintf(stderr, "%s\n", err); peel_string_free(err); return 1; }

    PeelCancelToken *tok = peel_cancel_token_new();   /* cancel from another thread if needed */
    size_t len = 0;
    unsigned char *buf = peel_session_read_member(s, argv[2], 64u << 20, tok, &len, &err);
    if (buf) {
        fwrite(buf, 1, len, stdout);
        peel_bytes_free(buf, len);
    } else {
        fprintf(stderr, "%s\n", err);
        peel_string_free(err);
    }
    peel_cancel_token_free(tok);
    peel_session_close(s);
    return buf ? 0 : 1;
}
TerminalShell
cc demo.c -I include -L target/release -lpeel_ffi -Wl,-rpath,$PWD/target/release -o demo
./demo demo.zip src/a.txt

Swift

Swift can import the header through a module map, or you can declare the few functions you need with @_silgen_name, which needs no header at all:

main.swiftSwift
import Foundation

@_silgen_name("peel_list") func peel_list(_ path: UnsafePointer<CChar>) -> UnsafeMutablePointer<CChar>?
@_silgen_name("peel_string_free") func peel_string_free(_ s: UnsafeMutablePointer<CChar>?)

func listJSON(_ path: String) -> String? {
    guard let raw = peel_list(path) else { return nil }
    defer { peel_string_free(raw) }
    return String(cString: raw)
}

print(listJSON(CommandLine.arguments[1]) ?? "no result")
TerminalShell
swiftc main.swift -L target/release -lpeel_ffi -Xlinker -rpath -Xlinker $PWD/target/release -o list
./list demo.zip

Decode the JSON with JSONDecoder into your own Decodable types, and check for an error key first.

Python

With ctypes, declare the return type as c_void_p so you keep the raw pointer. A c_char_p return would copy the string and lose the pointer you must free.

peel.pyPython
import ctypes, json, sys

lib = ctypes.CDLL("./libpeel_ffi.dylib")
lib.peel_inspect.argtypes = [ctypes.c_char_p]
lib.peel_inspect.restype = ctypes.c_void_p
lib.peel_string_free.argtypes = [ctypes.c_void_p]
lib.peel_string_free.restype = None

def call_json(fn, *args):
    ptr = fn(*args)
    try:
        return json.loads(ctypes.string_at(ptr).decode("utf-8"))
    finally:
        lib.peel_string_free(ptr)

summary = call_json(lib.peel_inspect, sys.argv[1].encode())
if "error" in summary:
    sys.exit(f"{summary['error']}: {summary.get('detail')}")
print(summary["format"], len(summary["entries"]), "entries")
TerminalShell
python3 peel.py demo.zip      # zip 3 entries

Go

With cgo, put peel.h and the library beside your module, and free the C string you pass in as well as the one you get back.

main.goGo
package main

/*
#cgo CFLAGS: -I${SRCDIR}/include
#cgo LDFLAGS: -L${SRCDIR} -lpeel_ffi -Wl,-rpath,${SRCDIR}
#include <stdlib.h>
#include "peel.h"
*/
import "C"

import (
    "fmt"
    "os"
    "unsafe"
)

func main() {
    path := C.CString(os.Args[1])
    defer C.free(unsafe.Pointer(path))

    out := C.peel_inspect(path)
    defer C.peel_string_free(out)
    fmt.Println(C.GoString(out))
}
TerminalShell
go mod init demo && go build -o inspect . && ./inspect demo.zip

Node

Node has no built-in FFI. koffi loads the library without a build step (npm install koffi). If you prefer N-API, write a small addon that includes peel.h and follows the same rules: free every string with peel_string_free.

peel.jsJavaScript
const koffi = require("koffi");

const lib = koffi.load("./libpeel_ffi.dylib");
// Declare the return as `void *` so we keep the pointer and can free it.
const peel_inspect = lib.func("void *peel_inspect(const char *path)");
const peel_string_free = lib.func("void peel_string_free(void *s)");

function inspect(path) {
  const ptr = peel_inspect(path);
  try {
    return JSON.parse(koffi.decode(ptr, "char", -1));
  } finally {
    peel_string_free(ptr);
  }
}

const summary = inspect(process.argv[2]);
console.log(summary.format, summary.entries.length, "entries");
TerminalShell
node peel.js demo.zip      # zip 3 entries

Calls are synchronous. For a long extract, run them on a worker thread so the event loop stays free, and use a cancel token.