Guides
Embed in Swift
Link libpeel_ffi, wrap the C calls in one small Swift file, and list, read and extract archives in-process with typed errors and cancellation.
Peel’s Mac app calls Rind this way. The engine runs inside your
process, so there is no child process to start and no output to parse.
Every call takes paths, returns a JSON string, and is synchronous. If
you would rather not link a library, run the peel command
from Swift and read its JSON instead (see Scripts and CI).
libpeel_ffi and include/peel.h
come from a checkout of the Peel repository. The released library is not
published as a package. Peel.app carries its own copy at
Contents/Frameworks/libpeel_ffi.dylib, for the app’s use.
Link the library
From a checkout, build it. This is the same command the C library page uses:
cargo build --release -p peel-ffi
# target/release/libpeel_ffi.a target/release/libpeel_ffi.dylib include/peel.hinclude/ holds only peel.h. To
import it from Swift, add a module map beside it:
module CPeel {
header "peel.h"
export *
}Then compile with the include folder on the import path. Dynamic:
swiftc -parse-as-library Rind.swift Demo.swift -I include \
-L target/release -lpeel_ffi -Xlinker -rpath -Xlinker $PWD/target/release -o demoStatic:
swiftc -parse-as-library Rind.swift Demo.swift -I include \
target/release/libpeel_ffi.a -lz -lbz2 -llzma -lc++ -liconv -o demoBoth lines built and ran the examples below. The dylib records its
build path as its install name, so to ship it beside your program run
install_name_tool -id @rpath/libpeel_ffi.dylib libpeel_ffi.dylib
and link with -Wl,-rpath,@executable_path. In an Xcode
project you can instead put #import "peel.h" in a bridging
header; the module map above was the only route tested here.
Who frees what
The rules are the C library’s. In Swift they become three habits.
| You receive | Free it with |
|---|---|
char * from any function |
peel_string_free |
unsigned char * from a member read |
peel_bytes_free(ptr, len) |
PeelSession * |
peel_session_close |
PeelCancelToken * |
peel_cancel_token_free, after the call has
returned |
A file descriptor from peel_read_member_fd |
close, or let a FileHandle do it |
Never use free(). The memory comes from Rust’s
allocator. Put the free in a defer the moment you hold the
pointer, copy the bytes into a String or Data,
and let the pointer go. Strings you pass in are borrowed for the call
only, which is what withCString gives you.
Errors and decoding
A string-returning call returns either its result or
{"error": "<kind>", "detail": "…"}. The kinds are the
same on every surface; see Errors.
Model them as an enum, and let anything unknown fall back to
other:
import CPeel
import Foundation
/// The error kinds Rind reports. Unknown kinds map to `.other`.
enum RindErrorKind: String {
case damaged, wrongPassword = "wrong_password", passwordRequired = "password_required"
case notEnoughSpace = "not_enough_space", unsupported
case permissionDenied = "permission_denied", decompressionBomb = "decompression_bomb"
case tooLarge = "too_large", cancelled, io, notFound = "not_found"
case invalidName = "invalid_name", unsafeEntry = "unsafe_entry"
case alreadyExists = "already_exists", other, panic
}
struct RindError: Error {
let kind: RindErrorKind
let detail: String // engine text: log it, never show it
}
private struct ErrorBody: Decodable {
let error: String
let detail: String?
}
struct Entry: Decodable {
let name: String
let size: UInt64
let isDir: Bool
enum CodingKeys: String, CodingKey { case name, size, isDir = "is_dir" }
}
struct Listing: Decodable {
let entries: [Entry]
let maxEntries: UInt32
let truncated: Bool
enum CodingKeys: String, CodingKey { case entries, truncated, maxEntries = "max_entries" }
}
struct ExtractResult: Decodable {
let format: String
let destination: String
let extracted: [String]
let skipped: [String]
}peel_list returns a bare array.
peel_list_limited and its variants return an object with
entries, max_entries, truncated
and path, so Listing above matches the second.
peel_extract_with_password returns format,
destination, extracted, skipped
and sources; the type above keeps four of them.
not_enough_space adds needed and
available, and too_large adds
size and max (for one member). Decode them as
optional fields if you want to show them. Show people your own sentence
for each kind. detail is the engine’s text: it can hold
paths and member names, so log it privately and keep it out of the
interface.
The helpers that take a string, check for an error and free it:
/// Takes ownership of a string the engine returned: decode it, then free it.
private func take<T: Decodable>(_ type: T.Type, _ raw: UnsafeMutablePointer<CChar>?) throws -> T {
guard let raw else { throw RindError(kind: .other, detail: "no result") }
defer { peel_string_free(raw) }
let data = Data(bytes: raw, count: strlen(raw))
if let body = try? JSONDecoder().decode(ErrorBody.self, from: data) {
throw RindError(kind: RindErrorKind(rawValue: body.error) ?? .other, detail: body.detail ?? "")
}
return try JSONDecoder().decode(T.self, from: data)
}
/// The error JSON from an out-parameter, freed, as a Swift error.
private func takeError(_ raw: UnsafeMutablePointer<CChar>?) -> RindError {
guard let raw else { return RindError(kind: .other, detail: "no error text") }
defer { peel_string_free(raw) }
let body = try? JSONDecoder().decode(ErrorBody.self, from: Data(bytes: raw, count: strlen(raw)))
return RindError(kind: RindErrorKind(rawValue: body?.error ?? "") ?? .other, detail: body?.detail ?? "")
}
/// `body` with a C string for `s`, or with NULL for nil.
private func withOptionalCString<R>(_ s: String?, _ body: (UnsafePointer<CChar>?) throws -> R) rethrows -> R {
guard let s else { return try body(nil) }
return try s.withCString(body)
}takeError does the same for the error out-parameter that
session and descriptor calls fill. A panic inside the engine never
unwinds into your process. It comes back as the panic kind,
which means that archive could not be read.
Passwords
Use the *_with_password functions. They take the
password as UTF-8, copy it once, wipe their copy before returning, and
never read the environment. Pass nil for none. The older
calls (peel_extract, peel_extract_to,
peel_read_member and others) still read
PEEL_PASSWORD; do not set it, because any process of the
same user can read your environment.
A Swift String cannot be wiped, so keep the password’s
lifetime short: fetch it when you call, pass it, drop it. The wrapper
below takes password: String? on every call. A wrong
password and a missing one are different kinds, so you can ask again
only when it is wrong.
Cancel with a Task
A PeelCancelToken stops one call and only that call.
Call peel_cancel_token_cancel from any thread; the call
returns cancelled and leaves no partial file. The engine
call blocks, so run it on a dispatch queue and let Task cancellation
flip the token:
/// One cancel token for one call. Freed when the last reference goes,
/// which is after the call has returned because the call closure holds it.
final class CancelToken: @unchecked Sendable {
fileprivate let raw: OpaquePointer = peel_cancel_token_new()
func cancel() { peel_cancel_token_cancel(raw) }
deinit { peel_cancel_token_free(raw) }
}
/// Run a blocking engine call off the caller's thread; cancelling the Task
/// cancels the token, which stops the call.
func cancellable<T: Sendable>(_ work: @escaping @Sendable (CancelToken) throws -> T) async throws -> T {
let token = CancelToken()
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { cont in
DispatchQueue.global(qos: .userInitiated).async {
cont.resume(with: Result { try work(token) })
}
}
} onCancel: {
token.cancel()
}
}The token is a class so that its deinit frees it. Both
the work closure and the onCancel closure hold a reference,
so it outlives the call. Each call gets its own token; never share one
between two calls.
The process-wide flag (peel_cancel,
peel_cancel_clear) stops anything that has no token of its
own, so avoid it in a library. If you call
peel_extract_entry, which does not clear the flag, call
peel_cancel_clear() first.
List and extract
enum Rind {
static func list(_ path: String, maxEntries: UInt32 = 10_000, password: String? = nil) async throws -> Listing {
try await cancellable { token in
try path.withCString { p in
try withOptionalCString(password) { pw in
try take(Listing.self, peel_list_limited_with_password(p, maxEntries, token.raw, pw))
}
}
}
}
static func extract(_ path: String, to destination: String, password: String? = nil) throws -> ExtractResult {
try path.withCString { p in
try destination.withCString { d in
try withOptionalCString(password) { pw in
// collision 2 = rename, enclosing 0 = when_needed
try take(ExtractResult.self, peel_extract_with_password(p, d, 2, 0, pw))
}
}
}
}
}collision 2 renames, and enclosing 0 adds
an enclosing folder only when the archive needs one. The other values
are 0=error 1=overwrite 2=rename 3=skip and
0=when_needed 1=always 2=never. peel_extract
takes the same three fields as a PeelPolicy struct, which
Swift can build once the header is imported. Extraction applies Rind’s safety rules: an entry
that climbs out of the destination is refused before anything is
written.
Read one member
To read several members of one archive, open it once. A ZIP keeps its
directory in memory, so each read skips the open and the scan. If the
file changes after the session opened, reads fail with an
io error instead of answering from a stale index; open a
new session.
/// An archive opened once for many reads.
final class RindSession: @unchecked Sendable {
fileprivate let raw: OpaquePointer
init(_ path: String, password: String? = nil) throws {
var err: UnsafeMutablePointer<CChar>?
let s = path.withCString { p in withOptionalCString(password) { pw in peel_session_open(p, pw, &err) } }
guard let s else { throw takeError(err) }
raw = s
}
deinit { peel_session_close(raw) }
/// One member in memory. `maxBytes` of 0 means no cap.
func read(_ member: String, maxBytes: UInt64, token: CancelToken? = nil) throws -> Data {
var len = 0
var err: UnsafeMutablePointer<CChar>?
let buf = member.withCString { m in
withExtendedLifetime(token) {
peel_session_read_member(raw, m, maxBytes, token?.raw, &len, &err)
}
}
guard let buf else { throw takeError(err) }
defer { peel_bytes_free(buf, len) }
return Data(bytes: buf, count: len) // copies; an empty member gives an empty Data
}
}maxBytes caps the member size accepted; 0 means no cap,
and a larger member is too_large. A symlink is not read
(unsupported). Names containing .. or a
leading / are refused. An empty member gives a non-NULL
pointer and a length of 0, which becomes empty Data.
For a window of a member, peel_session_read_member_range
returns bytes [offset, offset + length). The size comes
back when the format records it before the data and is
UInt64.max otherwise. A compressed member is decoded from
its start, so a deep offset costs the read up to it. Memory is bounded
by length, which must be 1 to 1 GiB.
extension RindSession {
/// Bytes [offset, offset + length) of one member, and the member's size
/// when the format records it before the data.
func read(_ member: String, offset: UInt64, length: UInt64) throws -> (data: Data, totalSize: UInt64?) {
var len = 0
var total: UInt64 = 0
var err: UnsafeMutablePointer<CChar>?
let buf = member.withCString { m in
peel_session_read_member_range(raw, m, offset, length, nil, &len, &total, &err)
}
guard let buf else { throw takeError(err) }
defer { peel_bytes_free(buf, len) }
return (Data(bytes: buf, count: len), total == UInt64.max ? nil : total)
}
}To a file descriptor
peel_read_member_fd decrypts or inflates one member into
an unnamed file and returns an open descriptor at byte 0, close-on-exec.
No path ever names it, so no other process can open it, but you can hand
it to one. It reads one archive by path; it does not use a session.
/// One member as an open descriptor on an unlinked file. The handle closes it.
func readMemberFD(_ path: String, member: String, maxBytes: UInt64, password: String? = nil) throws -> FileHandle {
var err: UnsafeMutablePointer<CChar>?
let fd = path.withCString { p in
member.withCString { m in
withOptionalCString(password) { pw in peel_read_member_fd(p, m, maxBytes, nil, pw, &err) }
}
}
guard fd >= 0 else { throw takeError(err) }
return FileHandle(fileDescriptor: fd, closeOnDealloc: true)
}FileHandle(fileDescriptor:closeOnDealloc:) takes
ownership. To write the member somewhere, read the handle in chunks
(read(upToCount:)) into a file you created; the descriptor
is not a path, so you cannot move it.
Threading
- Calls are synchronous and block the calling thread. Never call them on the main thread.
- A session can be shared between threads. Reads on one session run one at a time, so a second reader waits. Open two sessions for two parallel readers.
- A cancel token can be cancelled from any thread, and only the call it was passed to notices.
- The process-wide cancel flag is shared by the whole process. Per-call tokens avoid it.
Run it
This is the program that exercised everything above. It runs in a
folder holding the demo files demo.zip,
locked.zip, hostile.zip and
photos.7z.
import Foundation
@main struct Demo {
static func main() async {
do {
let listing = try await Rind.list("demo.zip")
for e in listing.entries where !e.isDir { print(e.name, e.size) }
let session = try RindSession("demo.zip")
let data = try session.read("project/src/main.rs", maxBytes: 1 << 20)
print(String(decoding: data, as: UTF8.self), terminator: "")
let part = try session.read("project/src/main.rs", offset: 3, length: 4)
print(String(decoding: part.data, as: UTF8.self), part.totalSize as Any)
let handle = try readMemberFD("demo.zip", member: "project/README.md", maxBytes: 0)
print((try handle.readToEnd() ?? Data()).count, "bytes through the descriptor")
do { _ = try session.read("nope.txt", maxBytes: 0) }
catch let e as RindError { print("kind:", e.kind) }
do { _ = try Rind.extract("locked.zip", to: "out", password: "wrong") }
catch let e as RindError { print("kind:", e.kind) }
do { _ = try Rind.extract("hostile.zip", to: "out") }
catch let e as RindError { print("kind:", e.kind) }
let task = Task {
while !Task.isCancelled { await Task.yield() } // wait until we are cancelled
return try await Rind.list("photos.7z")
}
task.cancel()
do { _ = try await task.value }
catch let e as RindError { print("kind:", e.kind) }
} catch {
print("failed:", error)
}
}
}project/README.md 47
project/docs/chapter-1.md 5411
project/docs/chapter-2.md 5411
project/docs/chapter-3.md 5411
project/docs/chapter-4.md 5411
project/docs/chapter-5.md 5411
project/docs/chapter-6.md 5411
project/src/main.rs 37
fn main() {
println!("hello");
}
main Optional(37)
47 bytes through the descriptor
kind: notFound
kind: wrongPassword
kind: unsafeEntry
kind: cancelledThe cancelled task never calls the engine until it has been cancelled, so the output is the same on every run. A real caller cancels from a button or a timeout, and the call stops within one read buffer.
How Peel does it
Peel’s own code is the reference for what survives contact with a shipping app.
- Loading.
app/PeelFfi/PeelFfi.swiftopenslibpeel_ffi.dylibwithdlopenand looks up each function withdlsym, so a build that carries an older library still runs and reports a missing function as unavailable. That is also why it callspeel_extract_to, which takes the policy as plain arguments, instead of passing a struct. A module map does the same job for you, andapp/PeelFfi/module.modulemapexists for that, but its header is an older copy ofpeel.hand the app does not import it. - Where the library lives.
app/project.ymlcopies the dylib into the app’sFrameworksfolder, and the extensions carry their own copy in theirResources. The Spotlight importer linkslibpeel_ffi.astatically, becausemdworkercannot reliably load the app’s dylib. - Errors.
takeJSONin that file checks forerror, logs thedetailwith private privacy, and throws only the kind.swift/PeelKit/Sources/PeelKit/EngineErrors.swiftis the enum, with an unknown code falling back toother. - Cancellation.
app/ComicCover/ComicCoverReader.swiftruns the read on a queue, waits on a semaphore with a deadline, and callstoken.cancel()when the deadline passes.app/PeelQLPreview/ArchivePreviewBuilder.swiftdoes the same for Quick Look previews. - Descriptors over XPC.
app/PeelArchiveXPC/PeelArchiveXPCService.swiftanswersreadMemberFDwith aFileHandle(fileDescriptor:closeOnDealloc: true), which XPC sends to the caller; the protocol is inPeelArchiveXPCProtocol.swift.app/Peel/DecryptedCopy.swiftcopies that handle into a private folder (mode 0700) when another app needs a real path, then removes it. - Sessions. The app’s Swift code does not use sessions today. They are in the header, tested above, and are the right tool for a reader that opens one archive and pulls many members.
- Passwords for child processes. Where the app runs
the
peelcommand instead,swift/PeelKit/Sources/PeelKit/EnginePassword.swiftpasses the password on standard input with--password-stdin, never in arguments or the environment.
Next: the full function list is on the C library page, the error kinds on Errors, and the Rust crate on the Rust library page.
void peel_bytes_free(unsigned char *ptr, size_t len) Free a buffer returned by peel_read_member or a session read.void peel_cancel_token_cancel(const PeelCancelToken *token) Cancel the one call this token was passed to. Safe from any thread.void peel_cancel_token_free(PeelCancelToken *token) Free a cancel token once its call has returned.PeelCancelToken *peel_cancel_token_new(void) Create a cancel token for one call.char *peel_extract_with_password(const char *archive_path, const char *destination, uint32_t collision, uint32_t enclosing, const char *password) Extract a whole archive with the password as an argument. Never reads the environment; wipes its copy of the password.char *peel_list_limited_with_password(const char *archive_path, uint32_t max_entries, const PeelCancelToken *token, const char *password) peel_list_limited for an encrypted archive, with the password as an argument.int peel_read_member_fd(const char *archive_path, const char *member, uint64_t max_bytes, const PeelCancelToken *token, const char *password, char **out_error) Read one member into an unlinked temporary file and return it as an open descriptor, for handing to another process.void peel_session_close(PeelSession *session) Close and free a session; NULL is ignored.PeelSession *peel_session_open(const char *archive_path, const char *password, char **error_json) Open an archive once and keep its index, for many reads. NULL with an error JSON on failure.unsigned char *peel_session_read_member(const PeelSession *session, const char *member, uint64_t max_bytes, const PeelCancelToken *token, size_t *out_len, char **error_json) Read one member through an open session into a heap buffer.unsigned char *peel_session_read_member_range(const PeelSession *session, const char *member, uint64_t offset, uint64_t length, const PeelCancelToken *token, size_t *out_len, uint64_t *out_total, char **error_json) Read a byte range of one member through an open session.void peel_string_free(char *s) Free a JSON string returned by any peel_* call.