cas#
content-addressed backup repositories: chunking, packs, signed encrypted snapshots, GC -- crate root lib/cas/lib.rs
cas -- a content-addressed, deduplicating, encrypted chunk store (BackupCraft's repository
format "bcrepo-1")
Repo::create(path, &CreateOptions) / Repo::open(path, Unlock::{Master, Passphrase,
Recovery}) a repository in a folder (store::Folder)
Repo::create_in(store, ..) / open_in(store, ..) in any Store (store.rs: objects by kind
and name, the way S3, SFTP or WebDAV keep them);
one holder at a time (Store::lock)
repo.writer() -> Writer put(kind, bytes) / put_stream(reader) -> chunk ids,
finish() (packs and indexes are durable);
finish_unsaved() -> (stats, Unsaved): the same, and
gc stays out until unsaved.save_snapshot(..) -- the
way of a backup where a gc can run beside it;
.codec(c, level): this writer's compression
(the repository's own is the default)
repo.read_chunk(id) / read_tree(id) repo.save_snapshot / load_snapshot / snapshot_ids /
delete_snapshot (refused while immutable)
repo.check(read_data, progress) snapshots, signatures, references, every blob
repo.gc(progress) mark & sweep, repack sparse packs
repo.add_passphrase / set_recovery / set_immutable_days / trust_signer
Signers: snapshots are saved and loaded only with trusted keys -- CreateOptions::signer and
the keys given to trust_signer (save_snapshot: UntrustedSigner, load_snapshot: Corrupt).
The list sits in repo.json under the MAC of the repository key, so it keeps out other keys
and mistakes, not someone who holds the repository key (who could call trust_signer). A
repo.json without a MAC (taken away) does not open (Corrupt).
Objects: the config "repo" (repo.json), packs, their indexes, snapshots; a Folder keeps them
as repo.json data/<xx>/<pack>.pack index/<pack>.idx snapshots/<id>.snap LOCK
Keys: one random repository key, wrapped in repo.json for the server's master key, for
passphrases (Argon2id) and for the recovery kit (sealed box); per purpose keys are
derived from it with BLAKE3 derive_key (chunk ids, data, index, snapshots, gear).
Chunks: id = BLAKE3-keyed(id key, plain) -> identical data is stored once, the ids reveal
nothing without the key. Commit order of a backup: packs -> indexes -> snapshot,
each put atomic and durable (Store's rule; Folder: synced, renamed, the folder
synced); a crash leaves at most unreferenced packs, which gc removes. A listing
that fails stops gc (it is no empty repository). Until its snapshot is there a
backup's chunks are such packs too: gc waits for open writers and for an Unsaved,
and a snapshot saved the plain way after a gc took chunks of it is refused
(save_snapshot).
cas crate root#
FORMAT: &str = "bcrepo-1"
type ChunkId = [u8; 32]
KIND_DATA: u8 = 0
KIND_TREE: u8 = 1
enum CasErrorIo(String)Corrupt(String)-- damaged or forged dataLocked-- none of the unlock methods fitsInUse-- another process uses the repositoryNotARepositoryNotEmptyImmutable(i64)-- a snapshot that may not be deleted yetNotFound(String)CancelledTooLargeUntrustedSigner-- save_snapshot with a key the repository does not trust (CreateOptions::signer and the keys of trust_signer are trusted)
type CasResult<T> = Result<T, CasError>fn hex_id(id: &ChunkId) -> Stringfn parse_id(s: &str) -> Option<ChunkId>struct Keysthe per-purpose keys of a repositoryid: [u8; 32]data: [u8; 32]index: [u8; 32]snapshot: [u8; 32]gear: [u8; 32]
impl Keys
fn chunk_id(&self, data: &[u8]) -> ChunkIdenum Unlock<'a>how to open a repositoryMaster(&'a [u8; 32])-- the server's repository wrap keyPassphrase(&'a str)Recovery(&'a [u8; 32])-- the recovery kit's X25519 secret
struct CreateOptionsid: Stringchunk_avg: usize-- average chunk size (a power of two; 1 MiB)compression: Codecmaster: [u8; 32]-- the server's wrap keyrecovery: Option<[u8; 32]>signer: [u8; 32]-- the public key whose snapshots this repository trusts (the only one that may save snapshots until trust_signer adds another)immutable_days: u32
struct WriteStatsstatistics of a writerchunks: u64raw: u64new_chunks: u64new_raw: u64new_stored: u64-- bytes added to pack files
struct CheckReportsnapshots: u64bad_snapshots: Vec<String>chunks_referenced: u64missing: u64damaged: u64packs: u64orphan_packs: u64-- packs without an index (left by an interrupted write)bytes_read: u64
impl CheckReport
fn ok(&self) -> boolstruct GcReportpacks_deleted: u64packs_repacked: u64bytes_freed: u64chunks_removed: u64
type Progress<'a> = &'a mut dyn FnMut(u64, u64) -> boolprogress: (done, total) -> false to cancelstruct Repo
impl Repo
fn create(path: &str, o: &CreateOptions) -> CasResult<Repo>create a repository in an empty (or new) folderfn create_in(store: impl Store + 'static, o: &CreateOptions) -> CasResult<Repo>create a repository in a store that holds nothing yet (NotEmpty)fn open(path: &str, unlock: Unlock) -> CasResult<Repo>open the repository in a folderfn open_in(store: impl Store + 'static, unlock: Unlock) -> CasResult<Repo>open the repository in a storefn path(&self) -> &strwhere the repository is: its folder (Repo::open), else the store's locationfn store(&self) -> &dyn Storethe store the repository lives infn id(&self) -> Stringfn immutable_days(&self) -> u32fn chunker(&self) -> &Chunkerfn keys(&self) -> &Keysfn chunk_count(&self) -> usizechunks in the indexfn has_chunk(&self, id: &ChunkId) -> boolfn stored_bytes(&self) -> u64bytes of all pack files (0 when the store cannot list them)fn add_passphrase(&self, pass: &str, label: &str, repo_key_from: Unlock) -> CasResult<()>let a passphrase open the repository (Argon2id, 64 MiB)fn has_passphrase(&self, label: &str) -> boolwhether a passphrase with this label opens the repositoryfn set_recovery(&self, pk: &[u8; 32], repo_key_from: Unlock) -> CasResult<()>seal the repository key for a (new) recovery kitfn set_immutable_days(&self, days: u32) -> CasResult<()>raise the immutability (never lowers it)fn trust_signer(&self, pk: &[u8; 32]) -> CasResult<()>trust snapshots signed by another key too (a restored server with a new key): only trusted keys may save snapshots, and load_snapshot refuses the others. The list is protected by the repository key: whoever opens the repository can call this, so the check keeps out other keys and mistakes, not a holder of the repository key.fn writer(&self) -> Writer<'_>a writer for new chunks (backups run several at once; gc waits for them)fn read_chunk(&self, id: &ChunkId) -> CasResult<Vec<u8>>the plain content of a chunkfn read_tree(&self, id: &ChunkId) -> CasResult<Tree>fn save_snapshot(&self, snap: &Snapshot, signer: &ed25519::Keypair) -> CasResult<()>store a snapshot (after its writer finished); signed bysigner, a key the repository trusts (CreateOptions::signer or one given to trust_signer), else UntrustedSigner.Between the writer's finish and this call the new chunks belong to no snapshot, and a gc of another thread -- one that waited for the writer runs at that very moment -- removes them. Where a gc can run beside the backup, finish the writer with
finish_unsavedand save through theUnsavedit returns: gc waits for it. This call cannot keep a gc out afterwards; it refuses the snapshot instead (NotFound) when chunks of it are gone -- looked up once a gc of this process has removed anything. It waits for a running gc: not to be called while the same thread holds a Writer or an Unsaved.fn snapshot_ids(&self) -> Vec<String>the ids of the snapshots, sorted (none when the store cannot list them)fn load_snapshot(&self, id: &str) -> CasResult<Snapshot>a snapshot, checked (signature by a trusted key, authentic encryption)fn delete_snapshot(&self, id: &str, now: i64) -> CasResult<()>delete a snapshot (its chunks go with the next gc) -- refused while it is immutablefn referenced(&self, snap: &Snapshot, out: &mut BTreeSet<ChunkId>) -> CasResult<()>every chunk a snapshot references (trees and data)fn check(&self, read_data: bool, progress: Progress) -> CasResult<CheckReport>check the repository: every snapshot opens and verifies, every referenced chunk is indexed; withread_dataevery blob is read, decrypted and compared with its idfn gc(&self, progress: Progress) -> CasResult<GcReport>remove what no snapshot references: empty packs are deleted, sparse packs (less than 60 % in use) are rewritten with their live blobs. Waits for open writers and for what finish_unsaved left of them. Lost index files are rebuilt from the packs' trailers first (repair_index). Refused (Corrupt), nothing removed, while a snapshot does not open, or while a chunk it references is not in the index and a pack without an index (and without a readable trailer) is left: the chunk may be in that packfn repair_index(&self) -> CasResult<u64>rebuild missing index files from the packs' trailersfn peek_id(path: &str) -> CasResult<String>the id of a repository folder without opening itfn peek_id_in(store: &dyn Store) -> CasResult<String>the id of the repository in a store without opening itstruct Writer<'a>writes new chunks into packsstats: WriteStats
impl<'a> Writer<'a>
fn codec(mut self, codec: Codec, level: i32) -> Selfcompress this writer's data chunks withcodec(level: zstd's level); trees stay LZ4fn put(&mut self, kind: u8, data: &[u8]) -> CasResult<ChunkId>store a chunk (once) -> its idfn put_stream(&mut self, read: &mut dyn FnMut(&mut [u8]) -> Result<usize, String>, cancel: &dyn Fn() -> bool) -> CasResult<(Vec<ChunkId>, u64)>chunk a stream and store it -> (chunk ids, size);readfills the buffer, Ok(0) = endfn put_tree(&mut self, t: &Tree) -> CasResult<ChunkId>fn finish(mut self) -> CasResult<WriteStats>write the last pack; every chunk put so far is durable afterwards. gc may run from here on, and it removes chunks no snapshot holds: a backup whose snapshot follows usesfinish_unsavedwhere a gc of another thread is possible (Repo::save_snapshot)fn finish_unsaved(mut self) -> CasResult<(WriteStats, Unsaved<'a>)>finish, and gc stays out until the snapshot of these chunks is saved through the returnedUnsaved(or that is dropped: a backup given up)struct Unsaved<'a>what a writer finished withfinish_unsavedleaves: its chunks -- new ones and those it found stored already -- before a snapshot holds them. gc waits while this lives, so the thread that holds it starts no gc, check or further writer before it is saved or dropped.
impl Unsaved<'_>
fn save_snapshot(self, snap: &Snapshot, signer: &ed25519::Keypair) -> CasResult<()>store the snapshot of these chunks (signed bysigner, a trusted key, else UntrustedSigner); gc may run again afterwards
cas/chunker.rs#
Source: lib/cas/chunker.rs
chunker -- content-defined chunking (FastCDC with normalized chunking, level 2)
Boundaries depend on the content only, so an insertion early in a file moves one boundary
and leaves the later chunks (and their deduplication) intact. The gear table is derived
from the repository key: chunk sizes do not reveal known files to someone who sees the
repository without its key.
struct Chunkermin: usizeavg: usizemax: usize
impl Chunker
fn new(gear_key: &[u8; 32], avg: usize) -> Chunkeravg must be a power of two; min = avg / 4, max = avg * 4fn cut(&self, data: &[u8], last: bool) -> Option<usize>the length of the first chunk ofdata(last: no more data follows)fn split(&self, data: &[u8]) -> Vec<usize>split a whole buffer into chunk lengths
cas/pack.rs#
Source: lib/cas/pack.rs
pack -- blobs, pack files and their indexes
blob kind:u8 codec:u8 | nonce:24 | XChaCha20-Poly1305(data key, nonce,
aad = chunk id ‖ kind ‖ codec, payload) payload: plain, an LZ4 block or a
zstd frame (the codec byte says which)
pack "BCK1" | blobs ... | sealed index (as below) | len:u32 | "BCKI"
(the trailer repeats the index: a lost index file can be rebuilt from the pack)
index "BCI1" | nonce:24 | XChaCha20-Poly1305(index key, aad = pack id, JSON
[[id hex, offset, length, kind, raw length], ...])
Pack files are written to a temporary name, synced, renamed; then their index. A crash
leaves at most a pack without an index (garbage that check reports and gc removes).
PACK_MAGIC: &[u8; 4] = b"BCK1"
PACK_TRAILER: &[u8; 4] = b"BCKI"
INDEX_MAGIC: &[u8; 4] = b"BCI1"
/// a pack is closed when it reaches this size
PACK_TARGET: usize = 32 << 20
BLOB_OVERHEAD: usize = 2 + 24 + 16
type PackId = [u8; 16]struct Locwhere a chunk livespack: PackIdoff: u32len: u32kind: u8raw: u32-- the plain length
fn seal_blob(keys: &Keys, id: &ChunkId, kind: u8, data: &[u8], codec: Codec, level: i32) -> Vec<u8>seal one chunk into a blob (compressed withcodecwhen that saves something;level: zstd's level)fn open_blob(keys: &Keys, id: &ChunkId, blob: &[u8], raw_len: usize) -> Result<Vec<u8>, CasError>open a blob: the plain chunk (checked against its id)fn seal_index(keys: &Keys, pack: &PackId, entries: &[(ChunkId, Loc)]) -> Vec<u8>an index (entries of one pack) as sealed bytesfn open_index(keys: &Keys, pack: &PackId, b: &[u8]) -> Result<Vec<(ChunkId, Loc)>, CasError>the entries of a sealed indexfn trailer_index(keys: &Keys, pack: &PackId, b: &[u8]) -> Result<Vec<(ChunkId, Loc)>, CasError>the index stored in a pack's trailerstruct PackBufa pack being filledid: PackIddata: Vec<u8>entries: Vec<(ChunkId, Loc)>
impl PackBuf
fn new() -> PackBuffn push(&mut self, id: ChunkId, kind: u8, raw: usize, blob: &[u8]) -> Locfn fits(&self, blob_len: usize, raw: usize) -> boolwhether a blob ofblob_lenbytes (rawunpacked) still has u32 offsets and lengthsfn is_empty(&self) -> boolfn finish(&mut self, keys: &Keys) -> Vec<u8>the complete pack file (with its trailer)fn pack_hex(p: &PackId) -> Stringfn parse_pack(s: &str) -> Option<PackId>
cas/snapshot.rs#
Source: lib/cas/snapshot.rs
snapshot -- what a restore point holds: a tree of nodes per backed-up root, stored as
chunks (an unchanged directory produces the same tree chunk and is stored once), and the
snapshot record that names the roots, signed with Ed25519 and encrypted
snapshot file "BCN1" | nonce:24 | XChaCha20-Poly1305(snapshot key, aad = snapshot id,
signature:64 ‖ signer public key:32 ‖ JSON of the Snapshot)
SNAP_MAGIC: &[u8; 4] = b"BCN1"
enum NodeKindFileDirSymlinkOther
impl NodeKind
fn as_str(&self) -> &'static strfn parse(s: &str) -> NodeKindstruct Nodeone entry of a directory (or a root)name: Stringkind: NodeKindsize: u64mtime_ns: i64atime_ns: i64ctime_ns: i64mode: u32uid: u32gid: u32attrs: u32ino: u64dev: u64link: String-- symbolic links: the target as stored in the linkchunks: Vec<ChunkId>-- files: the content chunks in ordertree: Option<ChunkId>-- directories: the tree chunk of their entrieserror: String-- a message when the entry could not be read completely (locked file, permission)count: u64-- directories: the files below (withsize= their bytes); 0 in older snapshots
impl Node
fn to_json(&self) -> Valuefn from_json(v: &Value) -> Option<Node>struct Treethe entries of a directory, sorted by namenodes: Vec<Node>
impl Tree
fn encode(&self) -> Vec<u8>fn decode(b: &[u8]) -> Option<Tree>fn find(&self, name: &str) -> Option<&Node>struct SnapStatstotals of a snapshotfiles: u64dirs: u64bytes: u64-- the plain size of all filesnew_bytes: u64-- stored bytes added by this snapshot (after dedupe, compression, encryption)new_chunks: u64new_raw: u64-- plain bytes of the new chunkserrors: u64-- files that could not be read (completely)
struct Snapshota restore pointid: Stringcreated: i64job_id: Stringjob_name: Stringhost: Stringroots: Vec<Node>-- one node per backed-up source; its name is the full source pathparent: Stringfull: boolstats: SnapStatsimmutable_until: i64-- not deletable before this time (seconds)meta: Value-- the caller's extra data (session id, ...)
impl Snapshot
fn to_json(&self) -> Valuefn from_json(v: &Value) -> Option<Snapshot>fn seal(key: &[u8; 32], signer: &crypto::ed25519::Keypair, snap: &Snapshot) -> Result<Vec<u8>, CasError>seal a snapshot (signed bysigner)fn open(key: &[u8; 32], id: &str, b: &[u8]) -> Result<(Snapshot, [u8; 32]), CasError>open a snapshot file: the snapshot and its signer (the signature is checked; whether the signer is trusted is the caller's decision)
cas/store.rs#
Source: lib/cas/store.rs
store -- where a repository keeps its objects: the Store trait and Folder, a folder of the
file system (plat::fs, so also a vfs mount such as mem://)
Store init, lock, get, get_range, put, delete, list, location: objects by
kind and name, the way S3, SFTP or WebDAV keep them
Kind Config ("repo"), Pack, Index, Snapshot
Folder::new(path) repo.json data/<xx>/<pack>.pack index/<pack>.idx
snapshots/<id>.snap LOCK
What the repository asks of a store (Repo::create_in / open_in):
- put is atomic and durable: once it returns Ok, get and list see the whole object, also
after a crash, and a put that failed leaves the old object or none (the commit order of a
backup -- packs, indexes, snapshot -- rests on it)
- a delete that returned Ok stays done; deleting what is not there is Ok
- get and list see every put that returned before them (read after write)
- lock keeps a second holder out, also one of another process or host, until the guard
is dropped
Nothing that comes back from a store is trusted: packs, indexes and snapshots are sealed and
repo.json carries a MAC, so a store that changes, swaps or replays objects is found out (a
rollback to older objects of the same repository is not); names and sizes of a listing are
checked before use. A store sees the names, the sizes and when objects come and go: pack
and index names are random, snapshot names are the ids given to save_snapshot.
enum Kindwhat an object of a repository isConfig-- the repository's settings and wrapped keys; the repository uses one, named "repo"Pack-- a pack of sealed chunks (written once, read in ranges, deleted by gc)Index-- the sealed index of the pack of the same nameSnapshot-- a sealed and signed snapshot, named by its id
type StoreLock = Box<dyn Any + Send + Sync>what [Store::lock] hands out: the repository is held until it is droppedtrait Store: Send + SyncWhere a repository keeps its objects. A name is not empty and has none of '/', '\\', '.', ':' (pack and index names are hex, snapshot names the ids given to save_snapshot). The rules a store keeps are those in the header of this module: put atomic and durable, read after write, a lock that keeps every other holder out.fn location(&self) -> Stringwhere it is, for messages and Repo::path ("D:/Backups/repo", "s3://bucket/prefix")fn init(&self) -> CasResult<()>make the place of a new repository: NotEmpty when it already holds anythingfn lock(&self) -> CasResult<StoreLock>hold the repository (InUse while another holder has it)fn get(&self, kind: Kind, name: &str) -> CasResult<Option<Vec<u8>>>the whole object; Ok(None) when there is nonefn get_range(&self, kind: Kind, name: &str, off: u64, len: usize) -> CasResult<Vec<u8>>lenbytes fromoffon, fewer only where the object ends (NotFound when there is none). The default reads the whole object: a store with ranged reads does betterfn put(&self, kind: Kind, name: &str, data: &[u8]) -> CasResult<()>store an object (replacing one of the same name), atomic and durablefn delete(&self, kind: Kind, name: &str) -> CasResult<()>remove an object; one that is not there is finefn list(&self, kind: Kind) -> CasResult<Vec<(String, u64)>>the names and sizes of the objects of a kind, in any order
fn name_ok(name: &str) -> boolwhether a store may be asked for this name (Store's rule)struct FolderA repository in a folder of the file system: repo.json, data/<xx>/<pack>.pack (the first two hex digits), index/<pack>.idx, snapshots/<id>.snap and LOCK (plat::FileLock: one holder at a time on this machine). Files and folders are the owner's only (write_file_private, mkdir_private); a write goes to a temporary sibling that is synced and renamed into place. The path can be a vfs name too (mem://, a mount). Listings and removals go through open folders (plat::fs::Dir): the repository's folder is taken as it is, a folder below it that is a link (data, a pack folder, index, snapshots) is refused, so gc never removes another repository's packs through it.
impl Folder
fn new(path: &str) -> Folderfn path(&self) -> &str