I BUILT A COMPRESSION FORMAT THAT HEALS ITSELF?! lzip + BCH — One Archive, Two Layers of Armor!

lzply v4: lzip + BCH (82 embedded polys, 39-42% less parity than Reed-Solomon) in one archive. Mountable filesystem, stat/heal tools, plus lzply_check BER detector and lzply_refresh platter refresher. Full source, 147/147 tests passing.

I BUILT A COMPRESSION FORMAT THAT HEALS ITSELF?! lzip + BCH — One Archive, Two Layers of Armor!
lzply hero: a terminal compressing data into a glowing stream wrapped in error-correction armor

Compress it. Then armor every single byte so that when the disk starts dying, the file heals itself. That is lzply — a new archive format that bolts two layers together: lzip compression and binary BCH error correction. One archive file, like zip. Every file inside it its own independent byte stream. And it is built, compiled, and tested on a real server — 147 out of 147 archive tests passing, plus a 7,406-check BCH harness.

Update (v2): the error-correction layer is now BCH, not Reed-Solomon. I ran an exhaustive search over 16,377 payload lengths and found 82 binary BCH polynomials that beat Reed-Solomon on bit errors, saving 39–42% of the parity for the same correction power. Those 82 polynomials are now embedded in the binary, and lzply picks the most efficient one for each file automatically — or you pin one yourself with poly=NN. The full BCH section is below.

Update (v3): timestamps, inspect, tree, and date filters — and Reed-Solomon is gone. Every entry now stores the source file's mtime, so an archive is searchable by date: -datestart / -dateend and -year filter -d, -i, and -tr (and -t / -l). -i inspects an archive from its headers only — no data read, nothing decompressed, so it works even on a corrupted archive — and -tr prints it as a tree. The format is version 3, a single format: the Reed-Solomon code and every v1/v2 read path are deleted, because the format was never used anywhere yet and there is nothing to stay compatible with. A v1 or v2 archive is now rejected, not read. The full section is below.

Update (lzply): the project is renamed again, this time to match the domain name — lzply everywhere. The history: lzrs (lzip + Reed-Solomon) became lzbch (lzip + BCH) when Reed-Solomon was replaced by BCH as the only error correction, and lzbch is now lzply. The archive magic followed the same path — LZRS → LZBC → LZPL (version stays 3, layout unchanged) — and the extension is now .lzply. Old LZRS- and LZBC-magic archives are rejected outright — there is no legacy support, by the same standing rule as v3. And two new tools join the family: lzply_stat reports per-entry statistics (sizes, poly id, t, parity bits, ECC overhead %) for an archive or a live mount, and lzply_heal strips the BCH parity from every entry and reapplies it at a new level — correcting bit errors in the process — without ever touching the compressed blob. The full section for both is below, after the mount section.

Update (check + refresh): two more tools — one that watches the rot, one that fights it at the platter. lzply_check is a read-only bit error rate (BER) detector: it runs the BCH decoder over each entry's stored bytes in memory and counts the bit errors it corrects, so you can watch an archive's BER rise over time and know the medium is degrading before the errors exceed t. lzply_refresh rewrites a file over itself, in place (same inode, 1–3 passes, SHA-256 verified before and after), to freshen the magnetic signal on older spinning disks — and it also refreshes a whole mount point recursively, or a single file inside a mount. The full sections for both are below, after the heal section.

Update (v4): the format is version 4 — two layers, and a smaller header. The entry header shrinks from 106 bytes to 78 bytes, the format version is 4, and a v3 archive is rejected outright — the same no-legacy rule as v3. The pipeline is lzip compress → BCH encode, and the title and slug change to match: two layers of armor.

This is the full write-up: the design, the format spec, 57 command examples, the test results, the seven bugs I found while building it, the lzply_mount filesystem mount (read it, write it, mount -t lzply), lzply_stat and lzply_heal, lzply_check and lzply_refresh, and the complete source code.

WHAT IT IS IN ONE PICTURE

WRITE: file -> archivelzip compresslevels -1..-9→BCH error correction82 polys, auto-picked→stored bytes+ SHA-256 of originalREAD: archive -> file (exact reverse)BCH-decodecorrect, or fail loudly→lzip decompressCRC-checked by lzip→verify SHA-256byte-identical or error

The order matters and it is not arbitrary. The parity protects the bytes actually stored on disk, so a damaged block is corrected before decompression is attempted. On the way out the order reverses, and the SHA-256 at the end is the final judge: if anything survived both layers wrong, the file is rejected, never silently returned damaged.

THE ARCHIVE FORMAT (v4 — ONE FORMAT, NO LEGACY)

All integers little-endian. One global header, then one entry per file, then a two-byte end marker. Version 4 is the only version: the reader accepts version 4 and nothing else. There is no v1/v2/v3 read path, no version branching, no Reed-Solomon code anywhere in the tree — it was all deleted. That is a deliberate decision, not an oversight: the format had never been used anywhere yet, so there was nothing to stay compatible with, and keeping dead read paths would have meant carrying a second error-correction codec and two header layouts forever for zero real archives.

global header (16 bytes):
  magic "LZPL", version u8 (4),
  flags u8, entry_count u32, reserved u64

each entry:
  u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
  u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
  u32 mode, u64 mtime, u32 header_crc32,
  path[path_len], data[stored_size]

end marker: u16 path_len == 0

header_crc32 covers the 74 bytes before it. blob_size is the length of the compressed stream before error-correction parity was added, so the decoder knows exactly how much data to recover. mtime is the source file's or directory's modification time, seconds since the epoch (UTC), recorded by -c and -a from stat() — it is what the date filters and -i read. Flags: bit 1 = directory, bit 2 = BCH mode (bit 0 is unused). For a BCH entry, the polynomial id is poly_id = rs_level | (reserved << 8) — the old RS-level byte and the old reserved byte now carry the 2-byte poly id. For an entry with no error correction, rs_level and reserved are 0. Paths are stored relative to the input's parent, so lzply -c photos/ stores photos/... and restores the tree on extract. Entry paths containing .. or starting with / are rejected on extract — a malicious archive cannot escape the destination directory. File mode and mtime are preserved; ownership is not.

BCH — WHY IT BEATS REED-SOLOMON ON BIT ERRORS, AND THE 82 POLYNOMIALS

Reed-Solomon corrects byte errors: it treats the data as symbols in GF(256) and spends 8 parity bits per correctable byte error, plus the overhead of working in a byte-sized field. But most real damage — a dying disk sector, a flaky cable, a cosmic ray — flips individual bits, not whole bytes. A binary BCH code corrects bit errors directly, and for the same number of correctable errors it needs far fewer parity bits. The catch is that the best BCH polynomial depends on the exact payload length, and nobody had published a systematic table of which polynomial wins at which length. So I searched.

The search (full story in the companion article) swept 16,377 payload lengths from 8 bytes to 16 KiB, then extended to 524,287 bytes, testing every narrow-sense primitive BCH code against the Reed-Solomon baseline. It found 82 generator polynomials (parents N = 2m − 1, m = 7..22, correction levels t = 1, 2, 4, 8, 16, 32) that beat Reed-Solomon on bit errors. The saving is 39–42% of the parity for the same t: at m = 22, t = 32, BCH needs 704 parity bits where Reed-Solomon needs 1,216. Across the whole table the search saved 495,386,012 parity bits (~59 MiB) over 3,145,030 length/correction pairs, with 99.979% coverage. Every polynomial is a textbook narrow-sense primitive BCH generator (1959–1960, Hocquenghem / Bose & Ray-Chaudhuri) — the new part is the exhaustive table of which one wins at each length, and the 36 polynomials for m = 17..22, which are not in any published table.

All 82 are embedded in the binary as bch_polys.h — no external file at runtime. The header is generated by gen_bch_polys.py from the search results, and the generator independently re-derives every polynomial orbit-only from its parent's primitive polynomial and checks it byte-identical, so the embedded table is verified, not just copied. Each entry stores the id, the parent exponent m, the correction level t, the degree r = t·m parity bits, the parent N, and the generator bytes.

Auto-pick: the most efficient poly for each file

With no polynomial specified, lzply picks the most efficient one for each file's bytestream, algorithmically: given the entry's blob length L (bytes, after compression) and the target t, it takes the smallest parent m with a polynomial for (m, t) whose codeword can hold the blob — N ≥ 8·L + t·m. This is per-file, so two files in one archive can (and usually do) get different polynomials. The chosen poly id is recorded in the entry header, so decode uses exactly the same poly. A blob longer than one block's capacity is split into blocks of that poly's max payload (m = 22, t = 32: 524,199 bytes per block); the decoder rebuilds the block boundaries from blob_size + the poly, so no per-block length is stored.

poly=NN: pin one polynomial by id

poly=NN pins a specific polynomial instead of auto-picking. It accepts hex (poly=003a) or decimal (poly=58) — both mean id 0x003a, the m = 18, t = 32 polynomial. A pinned poly overrides -e: the poly's own t is used, and the blob is split into that poly's blocks regardless of size. An unknown id is a usage error. lzply -l shows the poly id per entry (BCH 003a), so you can see exactly what was used.

The -e level is now the BCH correction level

-eBCH t (bit errors)Parity per bit error
0none0
117–22 bits (depends on m)
227–22 bits
347–22 bits
48 (default)7–22 bits
5167–22 bits
6327–22 bits
7327–22 bits

Default (no -e, no poly=) is BCH auto-pick with t = 8. -e 0 writes no error correction, as before. The parity per bit error is m bits (the parent exponent), versus Reed-Solomon's ~2·m bits per byte error — that is where the 39–42% saving comes from. The codec itself (bch.c) is a systematic encoder (parity = remainder of data·xr mod g(x), computed by a table-driven CRC-style LFSR) and a decoder (syndrome, Berlekamp-Massey, Chien search — binary, so no magnitude step — then a remainder re-check). The per-entry SHA-256 is still the final guard: a bounded-distance decoder can miscorrect when damage exceeds t, and the SHA catches it. For small t the miscorrection rate is not negligible (t = 1, 2-bit errors miscorrect ~50% of the time at the codec level), which is why the SHA-256 is load-bearing, not decorative.

What the parity actually costs — overhead by poly and by t

Overhead is parity bits divided by payload bits, as a percentage: a 1 KiB blob (8,192 bits) protected at t = 8 with poly 0020 (m = 14, r = 112 parity bits) costs 112 / 8,192 = 1.367%. The overhead depends on two things only: the correction level t (it doubles every time t doubles) and the blob size (it roughly halves every time the blob doubles, because the parent m only grows by 1 per doubling). It is capped at 12.5% — the search's parity cap (r ≤ n/8) forbids spending more than one parity bit per eight payload bits, which is why the smallest blobs cannot use the highest t levels at all. Both tables below are computed from the exhaustive finds table, not estimated.

Typical overheads at representative blob sizes. Each cell is the BCH overhead, with the Reed-Solomon overhead for the same blob and t in parentheses. The poly column is the auto-picked poly for that blob size (one per t; the range covers t = 1..32).

Blob sizePolys (m)t = 1t = 2t = 4t = 8t = 16t = 32
1 KiB (1,024 B)001d–0022 (m=14)0.171% (RS 0.269%)0.342% (0.537%)0.684% (1.074%)1.367% (2.148%)2.734% (4.297%)5.469% (8.594%)
4 KiB (4,096 B)0029–002e (m=16)0.049% (0.079%)0.098% (0.159%)0.195% (0.317%)0.391% (0.635%)0.781% (1.270%)1.562% (2.539%)
16 KiB (16,384 B)0035–003a (m=18)0.014% (0.023%)0.027% (0.046%)0.055% (0.092%)0.110% (0.183%)0.220% (0.366%)0.439% (0.732%)
64 KiB (65,536 B)0041–0046 (m=20)0.004% (0.006%)0.008% (0.013%)0.015% (0.026%)0.031% (0.052%)0.061% (0.104%)0.122% (0.208%)
256 KiB (262,144 B)004d–0052 (m=22)0.001% (0.002%)0.002% (0.004%)0.004% (0.007%)0.008% (0.014%)0.017% (0.029%)0.034% (0.058%)
512 KiB (524,287 B)004d–0052 (m=22)0.001% (0.001%)0.001% (0.002%)0.002% (0.004%)0.004% (0.007%)0.008% (0.014%)0.017% (0.029%)

The saving is the same at every t for a given blob size (it is a property of m, not of t): 36.4% at 1 KiB, 38.5% at 4 KiB, 40.0% at 16 KiB, 41.2% at 64 KiB, 42.1% at 256 KiB and 512 KiB. The practical takeaway: at the default t = 8, a 16 KiB file pays 0.110% overhead — about 18 parity bytes — where Reed-Solomon would charge 0.183%. At 1 KiB and t = 32 the cost is 5.469% (56 bytes on a 1,024-byte blob); that is the most expensive combination that is actually useful, and it is also the one where the parity cap starts to bite.

Overhead range for every poly and every t. Each row is one parent band (m) with its poly ids and the blob lengths it serves; each cell is the overhead range across that band — the low end is the largest blob in the band (cheapest), the high end is the smallest blob (most expensive). A dash means no polynomial exists for that (m, t): the parity cap forbids it, which is why the small bands only reach t = 1 or 2. The 12.5% ceiling that appears at the top of several cells is the cap itself.

m (parent N)Blob rangePoly idst = 1t = 2t = 4t = 8t = 16t = 32
7 (127)8–15 B0001, 00025.833–10.938%11.667–12.500%————
8 (255)16–31 B0003, 00043.226–6.250%6.452–12.500%————
9 (511)32–63 B0005–00071.786–3.516%3.571–7.031%7.143–12.500%———
10 (1,023)64–127 B0008–000b0.984–1.953%1.969–3.906%3.937–7.812%7.874–12.500%——
11 (2,047)128–255 B000c–00100.539–1.074%1.078–2.148%2.157–4.297%4.314–8.594%8.627–12.500%—
12 (4,095)256–511 B0011–00160.294–0.586%0.587–1.172%1.174–2.344%2.348–4.688%4.697–9.375%9.393–12.500%
13 (8,191)512–1,023 B0017–001c0.159–0.317%0.318–0.635%0.635–1.270%1.271–2.539%2.542–5.078%5.083–10.156%
14 (16,383)1,024–2,047 B001d–00220.085–0.171%0.171–0.342%0.342–0.684%0.684–1.367%1.368–2.734%2.736–5.469%
15 (32,767)2,048–4,095 B0023–00280.046–0.092%0.092–0.183%0.183–0.366%0.366–0.732%0.733–1.465%1.465–2.930%
16 (65,535)4,096–8,191 B0029–002e0.024–0.049%0.049–0.098%0.098–0.195%0.195–0.391%0.391–0.781%0.781–1.562%
17 (131,071)8,192–16,383 B002f–00340.013–0.026%0.026–0.052%0.052–0.104%0.104–0.208%0.208–0.415%0.415–0.830%
18 (262,143)16,384–32,767 B0035–003a0.007–0.014%0.014–0.027%0.027–0.055%0.055–0.110%0.110–0.220%0.220–0.439%
19 (524,287)32,768–65,535 B003b–00400.004–0.007%0.007–0.014%0.014–0.029%0.029–0.058%0.058–0.116%0.116–0.232%
20 (1,048,575)65,536–131,071 B0041–00460.002–0.004%0.004–0.008%0.008–0.015%0.015–0.031%0.031–0.061%0.061–0.122%
21 (2,097,151)131,072–262,143 B0047–004c0.001–0.002%0.002–0.004%0.004–0.008%0.008–0.016%0.016–0.032%0.032–0.064%
22 (4,194,303)262,144–524,287 B004d–00520.001–0.001%0.001–0.002%0.002–0.004%0.004–0.008%0.008–0.017%0.017–0.034%

Read it as a cost curve: doubling t doubles the overhead; doubling the blob roughly halves it. Past about 16 KiB, even the maximum correction (t = 32) costs under half a percent, and past 256 KiB it costs under 0.04%. That is why the default (t = 8) is essentially free for anything but tiny files — and why the only place the overhead is ever noticeable is a small file at a high t, where the 12.5% cap is the binding constraint, not the code.

Reed-Solomon is gone — deleted, not deprecated

The old RS levels (0..7, parity 2, 4, 8, 16, 32, 64, 128 bytes per 255-byte block, correcting 1–64 bad bytes per block; level 5 is the classic RS(255,223)) are no longer written, and the codec that read them is deleted along with its test harness and fixtures. A v1 archive is now rejected as an unknown version. That is the standing rule for this format while it has no users: never pay for legacy support. BCH is a bit-error code, so it is the wrong tool for burst byte damage (a burst that wipes many consecutive bits in one block can exceed t even when the byte count is small); Reed-Solomon was better for that, and if burst tolerance ever matters, the fix is a different interleaving strategy, not resurrecting the RS codec.

INCREMENTAL APPEND (-a) AND SELECTIVE EXTRACT — GROW THE ARCHIVE, PULL OUT ONE FILE

-c always creates a fresh archive. Real backups grow: you add a directory this week and a file next week, and you do not want to recompress everything you already stored. lzply -a <archive.lzply> <file|dir> [...] appends one directory, several files, or a mix. Stored paths are relative to each input's parent, exactly as -c does, and the new entries take the same -e / poly= options as -c (default BCH auto-pick, t=8). If the archive does not exist, -a creates it, like -c.

Without duplicates, the append is truly incremental: the new entries are encoded to a temp file, then written just before the 2-byte end marker, and only the global header's entry count is updated in place. The existing entry bytes are not rewritten — the test suite proves it by snapshotting the entry region before an append and comparing it byte-for-byte after.

Duplicates replace. If a stored path being added already exists in the archive, the new version wins and exactly one entry for that path remains. That case rewrites the archive via a temp file: kept entries are copied byte-for-byte, replaced entries are dropped, the new entries are appended, and the temp file is renamed over the original — so a failed append (disk full, killed process) leaves the old archive intact, not a half-written one. One subtlety worth knowing: adding a single file stores it by basename, so lzply -a backup.lzply tree/a.txt stores a.txt and does not replace tree/a.txt; to replace a file inside a directory, re-add the directory.

Selective extract is the other half. lzply -d <archive.lzply> <dest> <selector> [...] extracts only the entries matching a selector, and -t and -l take selectors the same way (right after the archive, no dest dir). A selector matches an entry if it equals the entry's stored path exactly, or is a prefix of it and the next character after the prefix is / — so photos matches photos/a.jpg but not photos2/a.jpg, and a selector ending in / matches everything under it. For -d the dest dir must be given explicitly when selectors are used (lzply -d backup.lzply . photos/); otherwise the dest defaults to . and there is nothing for the selectors to be relative to. A selector matching nothing prints a message and exits 0 — it is not an error, it is an empty result. Extracting a selected directory recreates its tree under the dest, and non-matching entries are never read or written.

Note: -a used to mean "ask before overwriting"; it is now the append mode, and ask-overwrite is --ask only (it is still the default).

STORE MODE (LEVEL 0) — WHEN COMPRESSION MAKES IT BIGGER

lzip adds a header to every stream it writes — about 32 bytes minimum, more at higher levels. For data that cannot compress at all — random bytes, already-compressed files (.zip, .jpg, .mp4, .gz) — the compressed stream is larger than the original, and storing it would waste space on every file. So when lzply creates an entry it compares: if the lzip blob would be larger than or equal to the original (compressed >= original), it stores the raw bytes instead and records the entry as level 0. The trigger is >=, not > — when the sizes tie there is no benefit to compressing, so it stores. BCH still applies to the stored blob exactly as before: the blob is just the raw file bytes, BCH-encoded, so a stored entry has the same error correction as a compressed one. The decoder sees level 0 and copies the blob verbatim (no lzip decode), then the SHA-256 verifies it exactly as for a compressed entry.

An explicit -0 forces store mode even for a file that would compress — useful when you know the data is already compressed and want to skip the wasted compression pass. The mount repack applies the same rule (it goes through entry_encode), so an incompressible file written into a mount is stored at level 0 on unmount. Empty files store as level 0 with a 0-byte blob (the stored size is just the parity block). Directories are directory entries and keep the requested level. The level is visible in -l, -i, and lzply_stat (the lvl column): 0 means stored, anything else is the lzip level.

$ lzply -c src/          # src/: random.bin (100 KB random), text.txt (80 KB text), empty.txt (0 B)
$ lzply -l test.lzply
path                                         original       stored  lvl ecc
src/                                              0 B          0 B  6   -
src/empty.txt                                     0 B         10 B  0   BCH 000b
src/random.bin                               97.7 KiB     97.7 KiB  0   BCH 0044
src/text.txt                                 78.1 KiB        163 B  6   BCH 000f
4 entries

That is real measured output. The random file stores at level 0 — 97.7 KiB in, 97.7 KiB stored, no lzip header wasted — and still carries BCH (poly 0044, t=8), so a flipped bit in it is corrected exactly like a compressed entry's. The text file compresses to 163 bytes at level 6. The empty file stores as level 0 with a 0-byte blob and a 10-byte stored size, which is just the parity block. And a stored entry is not a second-class citizen: flip a bit in it and lzply -t still passes, lzply_check reports exactly 1 corrected bit, and lzply_heal corrects it and recovers the data byte-identical — the test suite proves all of it.

INSPECT (-i), TREE (-tr), AND SEARCH BY DATE — THE ARCHIVE AS A DATABASE

An archive is only useful if you can find things in it without unpacking it. Version 3 adds three things for that: a stored mtime on every entry, a headers-only inspect command, and a tree command — plus date filters that work across -d, -i, -tr, -t, and -l.

-i: read the headers, touch nothing else

lzply -i <archive.lzply> reads only the global header and each entry header, seeking past every entry's stored data without reading or decoding it. Nothing is decompressed, no archived file is opened. That makes it fast on a large archive — the cost is proportional to the number of entries, not their size — and it makes it usable on an archive whose data is corrupted: as long as the headers are intact, -i still succeeds and prints the full listing, where -t on the same archive fails. The test suite proves exactly that: 100 bytes of the stored data zeroed, -i exits 0, -t fails.

For each entry it prints the stored path, the type (file or directory), the permissions twice (octal and symbolic, e.g. 0640 -rw-r-----), the mtime in UTC (2024-03-15 10:30:00 UTC), the original size, the stored size, the level (0 for stored, otherwise the lzip level), the error correction (BCH poly id, or -) — then a summary line with the entry count. The metadata lives in the header, so it is printed without touching the data.

$ lzply -i backup.lzply
path                                     type       perm symbolic    mtime (UTC)              original       stored  lvl ecc
photos/                                  directory  0755 drwxr-xr-x  2024-01-01 00:00:00 UTC          0 B          0 B    6 -
photos/a.jpg                             file       0644 -rw-r--r--  2024-05-10 10:00:00 UTC      2.1 MiB      2.1 MiB    0 BCH 000b
photos/b.jpg                             file       0644 -rw-r--r--  2025-05-10 10:00:00 UTC      1.8 MiB      1.8 MiB    0 BCH 000b
3 entries (1 directories, 2 files)

-tr: the archive as a tree

lzply -tr <archive.lzply> rebuilds the directory hierarchy from the stored paths and prints it like the Linux tree command — ├──, └──, and │ connectors, each file with its original size, and a N directories, M files summary at the end. Directories that are entries themselves (stored with a trailing /) are nodes; a directory with no explicit entry but files under it is shown as an implied node. Implied nodes appear in practice when a filter drops the directory entry but keeps its files — -tr backup.lzply -year 2024 on an archive whose directories are dated 2025 still shows the 2024 files under their parent directories, because the tree is built from the surviving entries, not from the directory entries alone.

$ lzply -tr backup.lzply
backup.lzply
└── photos/
    ├── 2024/
    │   └── a.jpg (2.1 MiB)
    └── 2025/
        └── b.jpg (1.8 MiB)

3 directories, 2 files

Search by date: -datestart, -dateend, -year

Every entry's mtime is the source's modification time, so an archive is searchable by when things were written. Three filters, all of which work on -d, -i, -tr, -t, and -l, and all of which may be combined with each other and with a path selector (an entry must match all of them):

  • -datestart YYYY-MM-DD — only entries with mtime on or after 00:00:00 of that date.
  • -dateend YYYY-MM-DD — only entries with mtime on or before 23:59:59 of that date. Both ends are inclusive, so -datestart 2024-01-11 -dateend 2024-01-12 is exactly Jan 11–12, and a single-day range (-datestart 2024-01-13 -dateend 2024-01-13) is exactly that day.
  • -datestart / -dateend also accept the exact form YYYY-MM-DDTHH:MM:SS (a space may replace the T), for when a day is too coarse.
  • -year YYYY — only entries whose mtime falls in that year; equivalent to that year's Jan 1 – Dec 31, and combinable with a date range (both must match, so -year 2024 -datestart 2025-01-01 matches nothing).

Dates are validated strictly and rejected as usage errors if they are impossible (2024-02-30, 2023-02-29, month 13, hour 25) or malformed (2024/01/01, 2024-1-5). That strictness is load-bearing: timegm silently normalises Feb 30 to Mar 1, which would have made a typo filter the wrong month without any error — the parser round-trips the date through gmtime and compares it against the parsed values, so an impossible date is caught. A filter (or a selector, or a combination) that matches nothing prints a clear message and exits 0 — an empty result, not an error — including the degenerate case of datestart after dateend. Options may appear before or after the archive and selectors, so lzply -d backup.lzply out/ -year 2024 works; the parser keeps scanning for options past the positionals instead of stopping at the first one.

$ lzply -d backup.lzply out/ -datestart 2024-01-01 -dateend 2024-06-30
$ lzply -d backup.lzply out/ -year 2024
$ lzply -i backup.lzply photos/ -year 2025
$ lzply -tr backup.lzply -datestart 2024-01-01 -dateend 2024-12-31
$ lzply -d backup.lzply out/ photos/ -year 2024   # selector AND year

MOUNT IT LIKE A FILESYSTEM (lzply_mount) — THE ARCHIVE AS A DIRECTORY

Extracting an archive to edit one file and re-compressing the whole thing is a chore. So there is a second program, lzply_mount, that mounts a .lzply archive as a normal writable directory. You ls it, cat a file out of it, append a line, create a file, delete a directory, rename things, chmod and touch — and when you unmount, the archive on disk is rewritten with your changes. It is a real FUSE filesystem (libfuse3, single-threaded), not a wrapper around extract-and-repack: reads decode entries on demand, writes go to memory, and only the changed entries are re-encoded.

lzply_mount backup.lzply /mnt/backup
ls -R /mnt/backup
cat /mnt/backup/docs/report.txt
echo "appended line" >> /mnt/backup/docs/report.txt
echo "brand new file" > /mnt/backup/docs/newfile.txt
mkdir /mnt/backup/docs/subdir
rm /mnt/backup/photos/old.jpg
mv /mnt/backup/docs/notes.txt /mnt/backup/docs/notes-renamed.txt
chmod 600 /mnt/backup/docs/report.txt
touch -d "2021-03-04 05:06:07 UTC" /mnt/backup/docs/notes-renamed.txt
fusermount3 -u /mnt/backup

Or through mount(8), with a helper installed at /sbin/mount.lzply:

mount -t lzply backup.lzply /mnt/backup
mount -t lzply -o cache=64 backup.lzply /mnt/backup
umount /mnt/backup

How it works — index, decode-on-open, repack on unmount

At mount, lzply_mount scans the archive headers into an in-memory index (the same scan -i does) and keeps it as the filesystem's directory tree. File contents are decoded on demand: opening a file runs it through BCH decode and lzip decompress, with the SHA-256 checked, and the result is cached (256 MiB soft cap, LRU eviction of clean entries only — a dirty entry is never evicted, and a single entry larger than the cap still loads). Writes go to an in-memory working copy of the file. New files, deletes, renames, and metadata changes update the index only.

On a clean unmount — or on fsync, so data is durable after fsync returns — the archive is repacked: a new archive is written to a temp file, then atomically renamed over the original. Unmodified entries are copied verbatim (their stored bytes and BCH poly id are byte-identical — verified in testing, not just claimed), and only modified and new entries are encoded fresh (lzip → BCH). Directories are written as directory entries, deleted entries are dropped, and a renamed entry keeps its content under its new path.

Durability — what survives a kill, and what does not

Changes are durable only after a clean unmount or an fsync (both trigger a repack). A killed daemon (kill -9, crash, power loss) loses unflushed changes but never corrupts the on-disk archive: the repack is atomic (temp file + rename), and the old archive is untouched until the new one is complete. Verified by killing the daemon mid-session and checking the archive with lzply -t — the on-disk bytes were md5-identical to before the mount. Mounting the same archive twice at once is refused outright (an exclusive non-blocking flock on the archive file), because two daemons repacking from different snapshots would silently lose each other's changes — that failure mode was found by testing, not by reasoning about it.

Corruption

A deliberately corrupted entry — 9 bits flipped in a file protected at t=8 — returns EIO on cat and never returns wrong data; the other files in the same archive still read fine.

Options

lzply_mount [-f] [-d] [-s] [-o opt] [-e N] [poly=NN] [-cache N] <archive.lzply> <mountpoint>

-f runs in the foreground (FUSE option; the default is to daemonise), -d is debug output, -o opt is a FUSE mount option passed through (ro works — the kernel enforces a read-only mount; allow_other works too), -e N sets the BCH level for re-encoded entries (0–7, default 4 → t=8), poly=NN pins a BCH polynomial for re-encoding, and -cache N sets the read-cache cap in MiB (default 256). Unmount with fusermount3 -u <mountpoint> or umount.

One bug found while building it — the SIGTERM double-free

Sending SIGTERM to a foreground daemon crashed it with free(): invalid pointer (SIGABRT), even with no files open and no changes made. The cause was a shutdown-order assumption in main(): it freed the state whenever fuse_main returned non-zero, on the theory that a non-zero return meant the filesystem never started. But on a signal shutdown fuse_main returns non-zero (8) after destroy() has already run and freed the state — so main() freed it a second time. A gdb backtrace confirmed it: the crash was in free_state called from main, on an already-freed state. The fix is a flag set by destroy() that main() checks before freeing. After the fix, SIGTERM exits cleanly (return code 8, which is libfuse's signal-shutdown return, not a crash), and — the important part — a SIGTERM with dirty changes still runs the repack first: a file created in the session was present in the archive afterwards, verified by lzply -t.

Limitations (lzply_mount, stated plainly)

  • Whole files are buffered in memory (same as lzply); the read cache is a 256 MiB soft cap.
  • chown is a no-op that succeeds — the archive stores a mode, not an owner, so every entry appears owned by the mounting user.
  • rename with RENAME_EXCHANGE returns EINVAL; plain rename (including rename over an existing file and directory moves) works.
  • Deleted entries stay in the in-memory index as tombstones for the session; atime is reported as mtime (only mtime is stored).
  • Mounting requires FUSE (/dev/fuse) and is single-threaded.
  • Changes are durable only after a clean unmount or fsync — a killed daemon loses unflushed changes (never corrupts the archive).

STATISTICS (lzply_stat) AND HEALING (lzply_heal) — KNOW WHAT YOU STORED, FIX WHAT ROTTED

Two more programs, both built on the same header scan -i uses. lzply_stat answers "what is actually in this archive, and what did the error correction cost?" lzply_heal answers "the disk is starting to rot — fix the parity before it is too late." Neither one decompresses anything.

lzply_stat: every number, per entry

lzply_stat <path> [selector...] takes an archive file, a lzply_mount mount point, or a file or directory inside a mount, and prints one row per entry: the uncompressed size, the compressed size (the blob, before error correction), the stored size (on disk, including parity), compression as stored/original, the level (0 for a stored entry, otherwise the lzip level), the BCH poly id and t, the parity bits, the ECC overhead %, and the mtime — plus a totals footer. The ECC overhead % is parity bits / (8 × blob size), the same definition as the overhead tables above, so the numbers here line up with the tables. Directories have no data, so their ECC fields are -.

$ lzply_stat backup.lzply
path                                     type   original compressed     stored   comp%  lvl  poly   t   parity    ecc% mtime (UTC)
photos/                                  dir         0 B        0 B        0 B       -    6     -   -        -       - 2026-11-24 21:01:08 UTC
photos/a.txt                             file    8.8 KiB      119 B      130 B    1.4%    6  000f   8       88  9.244% 2026-11-24 21:01:08 UTC
photos/b.bin                             file   48.8 KiB   48.8 KiB   48.8 KiB  100.0%    0  003e   8      152  0.038% 2026-11-24 21:01:08 UTC
photos/c.txt                             file       13 B       50 B       60 B  461.5%    6  000b   8       80 20.000% 2026-11-24 21:01:08 UTC
4 entries (1 directories, 3 files)
total uncompressed: 57.6 KiB, total compressed (blob): 49.0 KiB, total stored: 49.0 KiB
overall compression: 85.1% (stored/original)
total parity bits: 320, overall ECC overhead: 0.080%

Read the three rows as three different stories. a.txt is 8.8 KiB of repetitive text: lzip crushes it to 119 bytes, and the parity for that tiny blob (88 bits, poly 000f) costs 9.244% of the blob — expensive in percentage terms, trivial in absolute terms (11 bytes). b.bin is 50 KB of random bytes: incompressible, so it is stored uncompressed at level 0 — the blob is the raw 48.8 KiB (100.0%, no lzip header wasted on data that cannot shrink), and its parity (152 bits on a 48.8 KiB blob) costs 0.038%. c.txt is 13 bytes: the lzip header alone makes the blob 50 bytes (461.5%), and the parity costs 20.000%. The lesson is the same as the overhead tables: for small files the parity is a large percentage of a small number, and for large files it is a rounding error. The totals say the archive as a whole pays 0.080% for t=8.

The path argument is flexible. Give it a mount point and it resolves the backing archive itself: it confirms the path is a FUSE lzply_mount mount from /proc/mounts (fstype fuse.lzply_mount), then finds the daemon by scanning /proc command lines and reading the archive path off it. Give it a file or directory inside a mount and it shows just that entry (or the entries under that directory). Extra arguments are selectors with the usual semantics (exact path, or a directory prefix where the next character must be /).

One honesty rule: when the archive is currently mounted, the figures are the on-disk (committed) state, and the output says so — unflushed changes in the mount are not included. A file created in the mount but not yet repacked is reported as having no committed statistics, instead of showing stale numbers for a file that is not in the archive yet.

$ lzply_stat /mnt/backup
note: showing the on-disk (committed) state of /tmp/art5/backup.lzply (mounted on /tmp/art5/mnt); unflushed changes in the mount are not included.
path                                     type   original compressed     stored   comp%  lvl  poly   t   parity    ecc% mtime (UTC)
...

lzply_heal: re-armor the archive without touching the data

lzply_heal <archive.lzply> [-e <level>] [poly=<id>] [-o <output.lzply>] [selector...] strips the BCH parity from each entry and reapplies a new one. The compressed blob is never touched — no recompression — so the per-entry SHA-256 still verifies the original data, and only the poly id, the stored size, and the header CRC change. It operates on the stored bytes directly with bch_decode() and bch_encode(), not on the entry pipeline.

$ lzply_heal -e 6 backup.lzply
photos/a.txt: 000f (m=11, t=8) -> 0016 (m=12, t=32), stored 130 -> 167 B, 0 bit error(s) corrected
photos/b.bin: 003e (m=19, t=8) -> 0040 (m=19, t=32), stored 50753 -> 50810 B, 0 bit error(s) corrected
photos/c.txt: 000b (m=10, t=8) -> 0016 (m=12, t=32), stored 60 -> 98 B, 0 bit error(s) corrected
lzply_heal: backup.lzply: 3 healed, 1 unchanged, 0 skipped by selector, 0 uncorrectable (kept), 0 bit error(s) corrected

The three uses:

  • Pure heal (no -e, no poly=): re-encode each entry with the same poly and t it already has. That is the bit-rot repair pass: stripping the parity runs the BCH decoder, which corrects any bit errors up to t, and the re-encoded parity is clean. Run it on a schedule, or after a disk scare, and a later read no longer needs the correction. On a healthy archive it is a clean no-op — every entry takes the verbatim fast path and the archive is byte-identical afterwards.
  • Raise (or lower) the level (-e): the same level mapping as lzply (0 = none, 1 → 1, 2 → 2, 3 → 4, 4 → 8, 5 → 16, 6 → 32, 7 → 32), with the most efficient poly auto-picked per blob at the new t. Above, raising t=8 to t=32 cost a.txt 37 extra bytes and b.bin 57 — and the overall ECC overhead went from 0.079% to 0.338%, exactly 4×, as the tables predict. -e 0 strips the error correction entirely. The small-file warning from the stat section applies here too: after the raise, c.txt (13 bytes) pays 96.000% overhead at t=32 — 48 parity bytes protecting a 50-byte blob. That is the parity cap working as designed (it cannot exceed 12.5% of the codeword, but the blob is tiny), and it is why you do not blindly raise t on archives full of tiny files.
  • Pin a polynomial (poly=NN): one poly for every entry, overriding -e. A blob is never too large for a pinned poly — the encoder splits it into that poly's blocks — so pinning always works.

Two failure modes, both handled by keeping the entry unchanged rather than by guessing. If an entry's BCH decode fails (more errors than t), the entry is kept byte-for-byte, reported, and the program exits non-zero at the end — but the other entries are still healed. And if the decoder miscorrects — the bounded-distance hazard from bug 3, real at small t (t=1 with 2-bit errors miscorrects ~50% of the time at the codec level) — heal catches it before re-encoding: it verifies the stripped blob against the SHA-256 (decompressing first for a compressed entry, checking the stored bytes directly for a level-0 entry), and on a mismatch it keeps the entry unchanged and reports it. That guard was proven, not assumed: a t=1 entry with 2 bits flipped miscorrected in 3 out of 5 seeds, and all 3 were caught by the SHA check.

Two safety rules. First, heal refuses a mounted archive: it takes the same exclusive flock the mount daemon holds, so a mounted archive is refused with a clear message naming the mount point, and a mount cannot start mid-heal — modifying the archive under a live mount would corrupt the daemon's in-memory index. Second, the rewrite is atomic (temp file + rename), so a failure leaves the original intact; -o <output> writes a healed copy and leaves the original untouched. A selector heals only the matching entries and copies the rest verbatim.

$ lzply_heal backup.lzply
lzply_heal: backup.lzply is mounted on /mnt/backup; unmount it before healing (healing under a live mount would corrupt the daemon's in-memory index)
$ echo $?
2

BIT ERROR RATE (lzply_check) — WATCH THE ROT BEFORE IT WINS

Healing fixes rot after you notice it. lzply_check is for noticing it: a read-only detector that measures the bit error rate (BER) of an archive, per entry and overall. It never modifies the archive and never decompresses anything — it runs bch_decode() on each entry's stored bytes in memory and counts the bit errors the decoder corrects. That works because the check operates on the stored codeword: the parity protects the bytes actually on disk, so the decoder sees the damage exactly as the disk wrote it.

BER per entry = corrected bit errors / total stored bits (8 × stored_size). The definition is printed in the output itself, so the number is never ambiguous.

$ lzply_check backup.lzply
path                                      poly   t  corrected   total_bits          ber status
tiny.txt                                  000b   8          0          488            0 clean
1 entries checked (1 BCH, 0 no-ECC)
with errors: 0, uncorrectable: 0
total corrected: 0 bits over 488 total stored bits
overall BER: 0 (worst: tiny.txt 0)
BER = corrected bit errors / total stored bits (8 x stored size), as seen by the BCH decoder on the stored codeword. No-ECC entries cannot be measured.

That is real measured output on a clean archive: BER 0, status clean, exit 0. The same archive with 5 bits flipped (t=8) reports corrected 5, BER 0.0102, status correctable — the reported count is exactly the injected count, verified by the test suite through --json. With 9 bits flipped (past t=8) it reports uncorrectable and exits 3.

The use case is degradation watching: run it periodically — from cron, over an archive that lives on an ageing drive — and watch the BER rise. A BER of 0 is the baseline on a healthy archive. A BER that climbs from 0 to 1e-6 to 1e-4 means the medium is degrading, and it is time to heal (or copy the archive elsewhere) while the errors are still below t. The thresholds make that scriptable: --warn-ber 1e-4 prints a warning when the overall BER exceeds it but still exits 0; --fail-ber 1e-3 exits 3 when the overall BER exceeds it, so a cron job can alert. With no thresholds given, only uncorrectable entries fail. --json prints one JSON object with per-entry results and totals, for monitoring and scripting.

$ lzply_check --warn-ber 0.001 backup.lzply
warning: overall BER 0.0102 exceeds --warn-ber 0.001
$ lzply_check --fail-ber 0.001 backup.lzply; echo $?
3
$ lzply_check --json backup.lzply | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["totals"]["overall_ber"], d["status"])'

Three reporting rules, all deliberate. Entries with no BCH (t=0) are reported as no-ecc — "BER cannot be measured" — and no full decode is attempted for them; measuring those would mean decompressing, which is a different tool's job. Uncorrectable entries are reported separately and are not folded into the BER number: an entry past t has no meaningful corrected count, and averaging it in would hide a data-loss risk inside a healthy-looking average. And the totals give the overall BER across all decodable BCH entries (total corrected / total stored bits), the worst entry, and the counts of entries with errors, uncorrectable entries, and no-ECC entries.

The path argument is the same as lzply_stat: an archive file, a mount point, or a file or directory inside a mount, resolved through /proc/mounts and the daemon's command line. Checking a mount point checks the on-disk (committed) archive behind it.

One caveat, stated in the tool and in the README: the BER is as seen by the BCH decoder. For small t, if the true error count exceeds t the decoder may miscorrect and the reported BER is unreliable — the same bounded-distance hazard as bug 3, one layer down. So a high BER or any uncorrectable entry means: run lzply_heal, then lzply -t to fully verify. That is the documented workflow: lzply_check detects, lzply_heal repairs, lzply -t proves the data is intact.

PLATTER REFRESH (lzply_refresh) — REWRITE THE FILE OVER ITSELF

Error correction fixes damage after it happens. lzply_refresh tries to stop it happening in the first place — for one specific kind of drive. On an older magnetic (spinning) disk, the signal written to the platter fades over years; rewriting the same blocks refreshes the magnetic signal. So lzply_refresh <path> [n] reads a file into memory, then rewrites it over itself — the same inode, never deleted and recreated — 1 to 3 passes (default 1, n outside 1..3 is a usage error), opening O_WRONLY, writing the bytes back from offset 0, and fsyncing after each pass. SHA-256 before the first pass and after the last pass must match, and both hashes are reported.

$ lzply_refresh old-drive-file.txt 3
old-drive-file.txt: 32 bytes, 3 passes, sha256 5949996cf671a8ca6ce9a87bbbac211d41a11b239533c908e6166c616c01b178, verified unchanged

That is real measured output: the same inode before and after, the same SHA-256, 3 passes. If the content changed — if anything else wrote to the file mid-refresh — the hashes would mismatch and the program would report an error and exit non-zero, instead of claiming success.

The path may also be a directory or a mount point, and that is where it gets useful. Given a directory, it refreshes every regular file under it recursively with the same pass count, and prints a summary (files refreshed, files skipped); symlinks and special files are skipped, the same rule as lzply -c. Given a mount point, it detects it via the same mount resolution as lzply_stat (/proc/mounts) and says so in the output:

$ lzply_refresh /mnt/backup 2
refreshing mount at /mnt/backup: (archive /data/backup.lzply)
photos/a.jpg: 2097152 bytes, 2 passes, sha256 …, verified unchanged
...
summary: 3 files refreshed (2 passes each), 0 skipped, 0 failed

A single file inside a mount works too — the write goes through FUSE and the entry is re-encoded on repack, which also refreshes the archive. And the mounted-archive refusal still applies when the target is an .lzply archive file that is currently mounted: same rule as heal, same reason (modifying the archive under a live mount corrupts the daemon's view), unmount it first. The test suite proves all of it on the server: a file inside a mount and a whole mount point, both verified unchanged after unmount with the archive passing lzply -t, and the mounted-archive refusal.

Two caveats, stated plainly because they decide whether the tool does anything at all. On copy-on-write filesystems (btrfs, ZFS) an overwrite may allocate new blocks rather than rewriting the same sectors, so the platter refresh may not happen — this tool is aimed at traditional overwrite filesystems (ext4) and older spinning disks. On SSDs wear-levelling means a rewrite does not hit the same cells, so it is specifically for older physical (magnetic) drives. If your data lives on an SSD or a CoW filesystem, this tool is a no-op with extra steps; use lzply_check and lzply_heal instead.

BUILDING IT

apt install build-essential liblz-dev   # Debian/Ubuntu
make            # produces ./lzply, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh
make test       # BCH unit tests + full 147-test archive suite
sudo make install   # /usr/local/bin/lzply, /usr/local/bin/lzply_mount, /usr/local/bin/lzply_stat, /usr/local/bin/lzply_heal, /usr/local/bin/lzply_check, /usr/local/bin/lzply_refresh, /sbin/mount.lzply

Two dependencies, all in Debian's repos: a C compiler and liblz (lzip's own library — the compressed stream inside an entry is byte-identical to what the lzip command produces, verified by the test suite). SHA-256 is implemented in-tree, so there is no OpenSSL dependency. The BCH codec is hand-written in C, no extra library. The 82 polynomials are compiled in from bch_polys.h; regenerate that header after a re-crawl with python3 gen_bch_polys.py. The lzply_mount filesystem needs one more package, libfuse3-dev — make builds it with explicit flags (no pkg-config on the server), and make install puts lzply_mount in /usr/local/bin and the mount.lzply helper in /sbin so mount -t lzply works. The lzply binary and its 147 tests are unaffected by the lzply_mount code — they share only the lzply_lib core, and the suite still passes 147 out of 147.

57 COMMAND EXAMPLES

  1. lzply -c photos/ — compress a directory into photos.lzply (BCH t=8, auto-picked poly).
  2. lzply -c -9 report.pdf — maximum compression, single file.
  3. lzply -c -1 huge.log — fastest level, for logs you just want smaller.
  4. lzply -c -6 -e 5 docs/ — default compression with BCH t=16 (auto-picked poly).
  5. lzply -c -e 7 archive/ — maximum BCH correction, t=32.
  6. lzply -c -e 0 plain/ — no error correction at all, pure lzip in an archive.
  7. lzply -c random.bin — incompressible data (random bytes, already-compressed files) is stored uncompressed at level 0 automatically, when the lzip blob would be larger than the original.
  8. lzply -c -0 report.pdf — force store mode: no compression, the raw bytes are stored (BCH still applies).
  9. lzply -c poly=003a src/ — pin BCH poly 0x003a (m=18, t=32) for every file.
  10. lzply -c poly=58 src/ — same poly, decimal id.
  11. lzply -c -9 -e 5 backup/ — maximum compression with BCH t=16.
  12. lzply -d backup.lzply — extract into the current directory.
  13. lzply -d backup.lzply out/ — extract into out/.
  14. lzply -d -y backup.lzply — overwrite existing files without asking.
  15. lzply -d -n backup.lzply — never overwrite; skip files that already exist.
  16. lzply -d --ask backup.lzply — ask before overwriting each file (the default).
  17. lzply -l backup.lzply — list an archive: paths, original and stored sizes, level, BCH poly id or -.
  18. lzply -t backup.lzply — verify an archive: decode and check everything, write nothing.
  19. lzply -c -6 poly=003a file.bin then flip 32 bits in the archive and lzply -d — the file comes back byte-identical.
  20. lzply -c -e 3 big.bin — a 50 MiB file with BCH t=4; roundtrips exactly.
  21. lzply -c docs/ docs-backup.lzply — explicit output name instead of the default docs.lzply.
  22. lzply -c -6 -e 5 -y docs/ — overwrite an existing archive without asking.
  23. lzply -c -9 -e 7 vault/ — maximum everything: best compression, most parity.
  24. lzply -t truncated.lzply — a cut-off archive fails verification instead of extracting garbage.
  25. lzply --help — the full usage text, options, and exit codes.
  26. lzply -a backup.lzply more/ — append a directory to an existing archive, incrementally (BCH t=8, auto-picked poly).
  27. lzply -a backup.lzply a.txt b.txt c.txt — append several individual files at once.
  28. lzply -a new.lzply file.txt — if the archive does not exist, append creates it.
  29. lzply -a poly=003a backup.lzply src/ — append with a pinned BCH poly for the new entries.
  30. lzply -d backup.lzply out/ photos/ — extract only the photos/ directory (dest dir required when selectors are used).
  31. lzply -d backup.lzply out/ photos/a.jpg — extract a single file by exact stored path.
  32. lzply -t backup.lzply photos/ — verify only the selected entries, write nothing.
  33. lzply -i backup.lzply — inspect: path, type, permissions, mtime, sizes, BCH poly — headers only, no decompression.
  34. lzply -i backup.lzply photos/ — inspect only the photos/ entries.
  35. lzply -tr backup.lzply — print the archive as a tree, with a directory/file count.
  36. lzply -d backup.lzply out/ -year 2024 — extract only the 2024 files.
  37. lzply -d backup.lzply out/ -datestart 2024-01-01 -dateend 2024-06-30 — extract only Jan–Jun 2024.
  38. lzply -i backup.lzply -datestart 2024-01-11 -dateend 2024-01-12 — inspect only Jan 11–12.
  39. lzply -tr backup.lzply photos/ -year 2025 — tree of the 2025 photos only.
  40. lzply -d backup.lzply out/ photos/ -year 2024 — path selector AND year: only 2024 photos.
  41. lzply -i backup.lzply -datestart 2024-01-11T12:00:00 -dateend 2024-01-11T12:00:00 — exact-datetime range.
  42. lzply -t backup.lzply -year 2024 — verify only the 2024 entries.
  43. lzply_stat backup.lzply — per-entry statistics: sizes, poly id, t, parity bits, ECC overhead %, mtime, totals.
  44. lzply_stat backup.lzply photos/ — statistics for only the photos/ entries.
  45. lzply_stat /mnt/backup — statistics for a mount point (on-disk committed state).
  46. lzply_heal backup.lzply — pure heal: same poly/t, corrects bit errors up to t, no-op on a healthy archive.
  47. lzply_heal -e 6 backup.lzply — raise the correction level from t=8 to t=32, auto-picking the best poly per file.
  48. lzply_heal poly=003a backup.lzply — pin BCH poly 0x003a for every entry.
  49. lzply_heal -e 6 -o healed.lzply backup.lzply — heal to a new file; the original is untouched.
  50. lzply_check backup.lzply — bit error rate per entry and overall: corrected bits, total bits, BER, status (clean / correctable / uncorrectable / no-ecc).
  51. lzply_check --json backup.lzply — the same BER report as one JSON object, for cron and monitoring scripts.
  52. lzply_check --warn-ber 1e-4 backup.lzply — warn when the overall BER exceeds 1e-4, still exit 0.
  53. lzply_check --fail-ber 1e-3 backup.lzply — exit 3 when the overall BER exceeds 1e-3 (or any entry is uncorrectable).
  54. lzply_refresh old-drive-file.txt — rewrite a file over itself in place (same inode, 1 pass), SHA-256 verified unchanged.
  55. lzply_refresh old-drive-file.txt 3 — same, 3 passes.
  56. lzply_refresh /mnt/backup 2 — refresh every regular file under a mount point, 2 passes each, with a summary.
  57. lzply_refresh /mnt/backup/photos/a.jpg — refresh one file inside a mount; the write goes through FUSE and the entry is re-encoded on repack.

Exit codes: 0 ok, 1 usage error, 2 I/O error, 3 corrupt or unrecoverable.

TEST RESULTS — 147 OUT OF 147, PLUS THE BCH HARNESS

Two test layers. First, a standalone BCH harness (bch_test.c) that validates the codec in isolation: the table-driven remainder against brute-force polynomial division for all 82 polys and many lengths; encode/decode roundtrips for every poly; corruption at several t values (up to t bit errors flipped at random positions, required to recover exactly; t+1 errors required never to return wrong data); auto-pick band correctness against a brute-force search; and block splitting with corruption in the first and last blocks. Result: 7,406 checks, 0 failures.

Second, the full archive suite (tests/run_tests.sh), 147 tests, all passing:

  • Roundtrips at every compression level -1 through -9.
  • The -6 compressed data is byte-identical to system lzip -6, and lzip -t accepts the stream — full interoperability.
  • Roundtrips at BCH levels 0 through 7, each verified with -t and a full extract + diff -r.
  • BCH corruption with pinned polys: t bit errors recovered, t+1 bit errors fail cleanly (never silent wrong data).
  • Combined -9 -e 5 (BCH t=16) with 16 corrupted bits: recovered.
  • Overwrite flags: -n skips, -y overwrites, --ask with n skips and with y overwrites.
  • Incremental append (-a): a single directory (nested tree preserved), several files at once, -a on a missing archive creates it, replacing an existing file (new content wins, exactly one entry per path, other entries intact), -a with poly=003a and -e 6, and a byte-for-byte check that incremental append does not rewrite existing entries.
  • Selective extract: -d by directory prefix, by trailing slash, by exact file, a non-boundary prefix that must not match (mixed/neste does not match mixed/nested), a selector matching nothing (message, exit 0, nothing extracted), -t with a selector, and -l with a selector.
  • Edge cases: empty directory, empty file, 1-byte file, filenames with spaces, truncated archive fails, non-archive fails.
  • A 50 MiB random file at -6 -e 3 (BCH t=4, multi-block): roundtrips exactly.
  • poly= pinning in hex and decimal, unknown-poly rejection, the version byte (4, with or without BCH), and a 600 KiB split-blob roundtrip with corruption in the first block.
  • Inspect and tree: -i shows the right paths, permissions, mtimes (set with touch -d), sizes, and BCH poly ids; -i succeeds on an archive whose data is deliberately corrupted while -t fails on the same archive; -tr matches the exact expected tree output (nested tree, implied directories, empty directories, summary counts).
  • Date filters: -datestart / -dateend with -d, -i, and -tr (files with mtimes spread across days, only the in-range ones appear), a single-day range, and the exact-datetime form; -year with -d and -i (2024 vs 2025 files); combined filters (path selector AND -year; -year AND -datestart / -dateend); an empty range (datestart after dateend) and bad date/year formats (usage errors); -a preserving mtime.
  • A v1-style archive (version byte 1), a v3 archive, and an archive with the old LZRS magic are rejected, proving there is no legacy read path.
  • lzply_stat: the right poly ids, t values, and ECC overhead % for a known archive, a selector (only that entry), and a non-archive input (fails).
  • lzply_heal: a pure heal is a no-op on a healthy archive; -e 6 raises the level and the data is byte-identical after extract; -e 0 strips the ECC and the archive still verifies; 5 flipped bits in a t=8 entry are corrected and the data recovers; 9 flipped bits exit non-zero with the entry kept; -o leaves the original untouched and heals the output; and a selector heals only that entry.
  • lzply_heal on a mounted archive: refused with exit code 2, a clear message naming the mount point, and the archive md5-identical afterwards; after unmount, the same heal works and the archive verifies.
  • lzply_check: a clean archive reports BER 0 and exits 0; 5 injected bit errors report exactly 5 corrected and a BER of 5 / stored bits (verified through --json); 9 injected bit errors exit 3 as uncorrectable; a no-ECC entry is reported unmeasurable and exits 0; --warn-ber below the BER warns and exits 0; --fail-ber below the BER exits 3 and above it exits 0; and a mount-point check on the server resolves the archive and reports BER 0.
  • lzply_refresh: 1 pass and 3 passes leave the inode and the SHA-256 unchanged; n=4 and n=0 are usage errors; a directory refresh refreshes every file, skips a symlink, and leaves contents unchanged; and on the server a file inside a mount and a whole mount point refresh correctly (contents unchanged after unmount, archive passes lzply -t), while a mounted archive file is refused.
  • Store mode (level 0): a 1 MiB random file is stored uncompressed (level 0) and extracts byte-identical; a compressible file still compresses; -0 forces store even for a compressible file (via -c and -a); a flipped bit in a stored entry is corrected by BCH (check reports exactly 1 corrected, heal recovers it); an empty file stores as level 0 with a 0-byte blob; and a mount repack stores an incompressible file at level 0.

The test corpus is built by tests/make_testdata.sh: compressible text, real source code, 1 MiB of random binary, 1 MiB of zeros, empty and 1-byte files, nested directories, and the 50 MiB file.

SEVEN BUGS FOUND WHILE BUILDING IT

1. lzlib rejects member_size = 0. I assumed 0 meant "one unlimited member". In lzlib 1.13 it means "bad argument" — every LZ_compress_open call failed. The fix: pass ULLONG_MAX as the member size, which the library accepts and never splits. Found by probing the library's limits directly instead of trusting my memory of the API.

2. An entry-header offset error put every field after blob_size at the wrong address. When I added the blob_size field to the entry header, I shifted the fields after it by 4 bytes instead of 8, so mode, mtime, and the header CRC all landed 4 bytes early. The header CRC itself was self-consistent (both sides used the same wrong offsets), which is why it did not catch the bug — only the roundtrip test did, when entries came back with garbage modes and mtimes. The fix was four numbers: mode, mtime, CRC, and CRC coverage, all recomputed from the new layout.

3. A bounded-distance decoder can miscorrect — and the test suite proved it. The first version of the RS harness expected t+1 errors to always be detected. They are not: a bounded-distance decoder miscorrects some (t+1)-error patterns, landing on a different valid codeword — about 98% of the time at t=1, 49% at t=2, dropping fast with t. The same holds for the BCH decoder (t=1, 2-bit errors miscorrect ~50% of the time at the codec level). That is inherent to bounded-distance decoding, not a bug in either codec, and the math checks out against the codes' weight distributions. The mitigation is the per-entry SHA-256: a miscorrection is caught after decoding and reported as corruption, never returned as a good file. The harnesses assert the right thing, and the archive suite's t+1 tests pass because the SHA-256 layer does its job.

4. Heal's first version re-encoded miscorrections as if they were good data. The pure-heal path strips the parity, which runs the BCH decoder — and a bounded-distance decoder that is handed more errors than t can miscorrect, landing on a different valid codeword. The first heal implementation trusted the decoder's output and re-encoded it, which would have written a silently-wrong blob into the archive and then stamped it with a fresh, valid header. The test that caught it was deliberate: a t=1 entry with 2 bits flipped, five different seeds — three of the five miscorrected at the codec level. The fix is the SHA-256 verification before re-encoding (decompress the stripped blob, check the hash, keep the entry unchanged on mismatch), which is exactly the guard the article's heal section describes. The lesson is the same as bug 3, one layer up: a decoder that reports success is not a decoder that is right, and the only thing that knows is the hash.

5. lzply_check's first version read stored data as headers. The check reads entries sequentially: header, then the stored bytes, then the next header. The first version skipped the stored data for BCH entries (it had to, to decode them) but forgot to skip it for no-ECC entries — there was nothing to decode, so the code moved straight on to the next read_entry_header, which read stored data as a header and failed with "truncated or corrupt entry header", exit 3, on a perfectly healthy no-ECC archive. The fix is one fseeko past stored_size in the no-ECC branch. The bug was invisible in the first smoke test because that archive had BCH on every entry.

6. lzply_refresh's read loop had two defects, and they masked each other. The first version declared the byte counter uninitialised and never incremented it after a successful read(). The loop therefore exited on the first pass — the second read() hit EOF and broke out — and the size check then reported "0 of 32 bytes" on a file that had just been read successfully. The evidence that pinned it down was strace: read(3, ..., 32) = 32, right next to an error message claiming 0 bytes were read. Two one-line fixes: initialise the counter, and accumulate after each read. The lesson is the same as bug 2's: when the error message contradicts the syscall trace, trust the trace.

7. A mount started with a relative archive path repacked to the filesystem root. libfuse changes the mount daemon's working directory to / at mount time, so a mount started as lzply_mount backup.lzply /mnt/backup (relative path) repacked on unmount to /backup.lzply — silently losing the writes and leaving a stray file in /. The fix is to canonicalise the archive and mountpoint to absolute paths at startup, plus a fallback in the daemon resolver that matches the target mountpoint instead of merely checking a path exists. The debug proof was a minimal FUSE program showing the same pid from start to return but cwd / after fuse_main — it is libfuse 3.14 behaviour, not our code. Covered by 3 new tests; the README documents it.

LIMITATIONS (v4, STATED PLAINLY)

  • Whole files are buffered in memory. A 50 MiB file is fine; multi-gigabyte files need a streaming rewrite.
  • Symlinks and special files are skipped with a warning, not stored.
  • File mode and mtime are preserved; ownership is not.
  • BCH is a bit-error code: it corrects scattered bit flips, not whole lost bytes. A burst that wipes many consecutive bits in one block can exceed t even when the byte count is small.
  • The BCH decoder builds GF(2m) log/exp tables (up to 32 MiB transient for m=22) the first time it has to correct an error in a block; the no-error path needs no tables and stays fast.
  • A crash mid-append on the incremental path can leave orphan entries.
  • lzply_mount (the FUSE mount) keeps changes in memory until unmount or fsync; a killed daemon loses unflushed changes but never corrupts the archive — see the mount section for the full durability rules.
  • lzply_refresh only refreshes the platter on overwrite filesystems (ext4) and spinning disks; on copy-on-write filesystems (btrfs, ZFS) or SSDs the rewrite may land on new blocks or cells, so it is a no-op with extra steps — see the refresh section.

FULL SOURCE CODE

Everything below is the exact code on the server at /opt/lzply/src, installed as /usr/local/bin/lzply, /usr/local/bin/lzply_mount, /usr/local/bin/lzply_stat, /usr/local/bin/lzply_heal, /usr/local/bin/lzply_check, /usr/local/bin/lzply_refresh, and /sbin/mount.lzply. Copy it, build it with make, run make test.

lzply.c

The main program — CLI, archive format, lzip, entry encode/decode (v4: BCH, mtime in header, -i/-tr, date filters)

/* lzply.c - lzip + BCH archive tool.
 *
 * One archive file (like zip) holding many entries. Every entry is an
 * independent byte stream: lzip-compressed, optionally
 * error-correction protected. Pipeline per entry:
 *
 *   compress -> BCH-encode     (on write)
 *   BCH-decode -> decompress   (on read)
 *
 * The parity protects the bytes actually stored on disk, so a damaged
 * block is corrected before decompression is attempted. Every entry
 * carries a SHA-256 of its original data, which catches any
 * BCH miscorrection (a bounded-distance decoder can land on a
 * different valid codeword when damage exceeds the level's limit).
 * Every entry also carries the source file's modification time
 * (mtime, seconds since the epoch, UTC), so entries can be found,
 * listed, and extracted by date.
 *
 * Error correction: binary BCH over GF(2), using the 82 narrow-sense
 * primitive generator polynomials embedded in bch_polys.h (rssearch,
 * m=7..22, t=1,2,4,8,16,32). BCH corrects bit errors and needs
 * 39-42% less parity than Reed-Solomon for the same t. The -e level
 * selects the BCH correction level t (0=none, 1->1, 2->2, 3->4, 4->8,
 * 5->16, 6->32, 7->32; default -e 4, i.e. t=8), and `poly=NN` pins one
 * polynomial by id (hex or decimal) instead of auto-picking. With no
 * poly given, the most efficient poly for each entry's blob length
 * is picked automatically (smallest parent covering the blob).
 * A blob longer than one block's capacity is split into blocks of
 * the poly's max payload; the decoder rebuilds the boundaries from
 * blob_size + the poly.
 *
 * Appending (-a): new files/dirs are added to an existing archive
 * without rewriting it — entries are staged to a temp file, then
 * appended just before the end marker, and the global entry_count
 * is updated in place. If a stored path being added already exists,
 * the archive is rewritten via a temp file (kept entries copied
 * byte-for-byte, replaced entries dropped, new entries appended),
 * then renamed over the original, so a duplicate always leaves
 * exactly one entry per path and the new content wins. Appending to
 * a missing archive creates it, like -c.
 *
 * Selective extract (-d / -t, and -l): selectors after the dest dir
 * (or after the archive for -t / -l) restrict the operation to
 * entries whose stored path matches a selector — exactly, or as a
 * directory prefix (the next character after the prefix must be
 * '/'; a selector ending in '/' matches everything under it).
 * A selector matching nothing prints a message and exits 0.
 * Note: -a used to mean "ask before overwriting"; it is now the
 * append mode, and ask-overwrite is --ask only (it is the default).
 *
 * Inspect (-i): prints every entry's path, type, permissions,
 * mtime, sizes, and error correction by reading the entry headers
 * only — it never reads entry data, never decompresses, and never
 * opens the archived files, so it is fast even on large archives.
 *
 * Tree (-tr): prints the archive contents as a tree, like the
 * Linux `tree` command, with a directory/file count at the end.
 *
 * Date filters (-datestart / -dateend / -year): restrict -d, -i,
 * -tr (and -t / -l) to entries whose mtime falls in the given range
 * or year. They AND with each other and with any path selector.
 *
 * Archive format v4 (the only format; there is no legacy support —
 * this tool has not been used anywhere yet, so old versions are not
 * kept readable). All integers little-endian:
 *   global header (16 bytes):
 *     magic "LZPL", version u8 (=4), flags u8, entry_count u32,
 *     reserved u64
 *   entries, each:
 *     u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
 *     u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
 *     u32 mode, u64 mtime, u32 header_crc32,
 *     path[path_len], data[stored_size]
 *     (header_crc32 covers the 74 bytes before it; blob_size is the
 *     length of the compressed stream before error-correction
 *     parity was added, so the decoder knows how much data to recover;
 *     mtime is the source file's modification time, seconds since
 *     the epoch, UTC)
 *   end marker: u16 path_len == 0
 * Flags: bit 0 is unused (it was used by v3), bit 1 = directory,
 * bit 2 = BCH mode.
 * For a BCH entry, poly_id = rs_level | (reserved << 8). For an
 * entry with no error correction, rs_level and reserved are 0.
 */
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE

#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <lzlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include "bch.h"
#include "lzply_lib.h"



/* ------------------------------------------------------------------ */
/* Small utilities                                                     */
/* ------------------------------------------------------------------ */














/* ------------------------------------------------------------------ */
/* lzip (liblz) in-memory compression                                  */
/* ------------------------------------------------------------------ */





/* ------------------------------------------------------------------ */
/* Per-entry encode / decode                                           */
/* ------------------------------------------------------------------ */





/* ------------------------------------------------------------------ */
/* Filesystem helpers                                                  */
/* ------------------------------------------------------------------ */

static int read_file(const char *path, uint8_t **out, size_t *out_len)
{
    FILE *f = fopen(path, "rb");
    buf_t b;
    uint8_t tmp[65536];
    size_t n;
    if (!f)
        return -1;
    buf_init(&b);
    while ((n = fread(tmp, 1, sizeof tmp, f)) > 0)
        buf_append(&b, tmp, n);
    if (ferror(f)) {
        fclose(f);
        buf_free(&b);
        return -1;
    }
    fclose(f);
    *out = b.data;
    *out_len = b.len;
    return 0;
}

static int write_file(const char *path, const uint8_t *data, size_t len,
                      uint32_t mode)
{
    FILE *f = fopen(path, "wb");
    if (!f)
        return -1;
    if (len > 0 && fwrite(data, 1, len, f) != len) {
        fclose(f);
        return -1;
    }
    if (fclose(f) != 0)
        return -1;
    chmod(path, (mode_t)(mode & 07777));
    return 0;
}

/* mkdir -p: create every component of path (which must be a directory). */
static int mkdir_p(const char *path, uint32_t mode)
{
    char *tmp = xstrdup(path);
    char *p;
    int rc = 0;
    for (p = tmp + 1; *p; p++) {
        if (*p == '/') {
            *p = '\0';
            if (mkdir(tmp, (mode_t)(mode & 07777)) != 0 && errno != EEXIST)
                rc = -1;
            *p = '/';
        }
    }
    if (mkdir(tmp, (mode_t)(mode & 07777)) != 0 && errno != EEXIST)
        rc = -1;
    free(tmp);
    return rc;
}


/* Absolute path (lexical only; does not resolve symlinks). */
static char *abs_path(const char *path)
{
    char cwd[PATH_MAX];
    char *r;
    if (path[0] == '/')
        return xstrdup(path);
    if (!getcwd(cwd, sizeof cwd))
        return xstrdup(path);
    r = xmalloc(strlen(cwd) + strlen(path) + 2);
    sprintf(r, "%s/%s", cwd, path);
    return r;
}

/* Overwrite modes. */
enum { OW_ASK, OW_YES, OW_NO };

/* Returns 1 to proceed, 0 to skip. */
static int ask_overwrite(const char *path, int mode)
{
    struct stat st;
    char line[64];
    if (stat(path, &st) != 0)
        return 1;               /* does not exist: proceed */
    if (mode == OW_YES)
        return 1;
    if (mode == OW_NO) {
        fprintf(stderr, "%s: %s exists, skipping (--no-clobber)\n",
                lzply_progname, path);
        return 0;
    }
    fprintf(stderr, "%s: %s exists. Overwrite? [y/N] ", lzply_progname, path);
    fflush(stderr);
    if (!fgets(line, sizeof line, stdin))
        return 0;
    return (line[0] == 'y' || line[0] == 'Y') ? 1 : 0;
}

/* ------------------------------------------------------------------ */
/* Entry list + recursive directory walk                               */
/* ------------------------------------------------------------------ */

typedef struct {
    char *full;                 /* absolute source path */
    char *stored;               /* path stored in the archive */
    int is_dir;
    uint32_t mode;
    uint64_t size;
    uint64_t mtime;             /* source mtime, seconds since epoch (UTC) */
} entry_t;

typedef struct {
    entry_t *v;
    size_t len, cap;
} entry_list_t;

static void entry_list_add(entry_list_t *l, const char *full,
                           const char *stored, int is_dir, uint32_t mode,
                           uint64_t size, uint64_t mtime)
{
    if (l->len == l->cap) {
        l->cap = l->cap ? l->cap * 2 : 64;
        l->v = xrealloc(l->v, l->cap * sizeof(entry_t));
    }
    l->v[l->len].full = xstrdup(full);
    l->v[l->len].stored = xstrdup(stored);
    l->v[l->len].is_dir = is_dir;
    l->v[l->len].mode = mode;
    l->v[l->len].size = size;
    l->v[l->len].mtime = mtime;
    l->len++;
}

static void entry_list_free(entry_list_t *l)
{
    size_t i;
    for (i = 0; i < l->len; i++) {
        free(l->v[i].full);
        free(l->v[i].stored);
    }
    free(l->v);
    l->v = NULL;
    l->len = l->cap = 0;
}

static int cmp_entry(const void *a, const void *b)
{
    return strcmp(((const entry_t *)a)->stored, ((const entry_t *)b)->stored);
}

static void walk_dir(const char *full, const char *stored, entry_list_t *l)
{
    DIR *d = opendir(full);
    struct dirent *de;
    if (!d) {
        fprintf(stderr, "%s: cannot open directory %s: %s\n",
                lzply_progname, full, strerror(errno));
        return;
    }
    while ((de = readdir(d)) != NULL) {
        char *child_full, *child_stored;
        struct stat st;
        if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
            continue;
        child_full = xmalloc(strlen(full) + strlen(de->d_name) + 2);
        sprintf(child_full, "%s/%s", full, de->d_name);
        child_stored = xmalloc(strlen(stored) + strlen(de->d_name) + 2);
        sprintf(child_stored, "%s/%s", stored, de->d_name);
        if (lstat(child_full, &st) != 0) {
            fprintf(stderr, "%s: cannot stat %s: %s\n",
                    lzply_progname, child_full, strerror(errno));
            free(child_full);
            free(child_stored);
            continue;
        }
        if (S_ISLNK(st.st_mode)) {
            fprintf(stderr, "%s: skipping symlink %s (not stored)\n",
                    lzply_progname, child_full);
        } else if (S_ISDIR(st.st_mode)) {
            char *dstored = xmalloc(strlen(child_stored) + 2);
            sprintf(dstored, "%s/", child_stored);
            entry_list_add(l, child_full, dstored, 1,
                           (uint32_t)(st.st_mode & 07777), 0,
                           (uint64_t)st.st_mtime);
            free(dstored);
            walk_dir(child_full, child_stored, l);
        } else if (S_ISREG(st.st_mode)) {
            entry_list_add(l, child_full, child_stored, 0,
                           (uint32_t)(st.st_mode & 07777),
                           (uint64_t)st.st_size,
                           (uint64_t)st.st_mtime);
        } else {
            fprintf(stderr, "%s: skipping special file %s\n",
                    lzply_progname, child_full);
        }
        free(child_full);
        free(child_stored);
    }
    closedir(d);
}

/* ------------------------------------------------------------------ */
/* Archive header I/O                                                  */
/* ------------------------------------------------------------------ */





/* ------------------------------------------------------------------ */
/* Commands                                                            */
/* ------------------------------------------------------------------ */

static const char *human_size(uint64_t n, char *buf, size_t bufsz)
{
    static const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
    double v = (double)n;
    int u = 0;
    while (v >= 1024.0 && u < 4) {
        v /= 1024.0;
        u++;
    }
    if (u == 0)
        snprintf(buf, bufsz, "%" PRIu64 " B", n);
    else
        snprintf(buf, bufsz, "%.1f %s", v, units[u]);
    return buf;
}

/* ------------------------------------------------------------------ */
/* Entry collection + writing (shared by -c and -a)                    */
/* ------------------------------------------------------------------ */

/* Collect stored entries for the given inputs. exclude_abs (may be
 * NULL) is an absolute path to skip (the archive/output file itself);
 * exclude_why names it in the skip message ("the output file" for
 * -c, "the archive" for -a). Unreadable files are dropped with a
 * warning. Returns 0 on success, -1 on error (stat failure, or an
 * input that is not a file or directory). *skipped_out counts the
 * dropped files. */
static int collect_inputs(const char **inputs, int ninputs,
                          const char *exclude_abs, const char *exclude_why,
                          entry_list_t *list, int *skipped_out)
{
    int skipped = 0;
    int i;
    size_t j;
    for (i = 0; i < ninputs; i++) {
        struct stat st;
        char *root;
        if (stat(inputs[i], &st) != 0) {
            fprintf(stderr, "%s: cannot stat %s: %s\n", lzply_progname, inputs[i],
                    strerror(errno));
            return -1;
        }
        root = realpath(inputs[i], NULL);
        if (!root) {
            fprintf(stderr, "%s: cannot resolve %s: %s\n", lzply_progname, inputs[i],
                    strerror(errno));
            return -1;
        }
        if (S_ISDIR(st.st_mode)) {
            const char *base = strrchr(root, '/');
            char *dstored;
            base = base ? base + 1 : root;
            dstored = xmalloc(strlen(base) + 2);
            sprintf(dstored, "%s/", base);
            entry_list_add(list, root, dstored, 1,
                           (uint32_t)(st.st_mode & 07777), 0,
                           (uint64_t)st.st_mtime);
            free(dstored);
            walk_dir(root, base, list);
        } else if (S_ISREG(st.st_mode)) {
            const char *base = strrchr(root, '/');
            base = base ? base + 1 : root;
            entry_list_add(list, root, base, 0,
                           (uint32_t)(st.st_mode & 07777),
                           (uint64_t)st.st_size,
                           (uint64_t)st.st_mtime);
        } else {
            fprintf(stderr, "%s: %s is not a regular file or directory\n",
                    lzply_progname, inputs[i]);
            free(root);
            return -1;
        }
        free(root);
    }
    qsort(list->v, list->len, sizeof(entry_t), cmp_entry);
    /* Drop unreadable files and the excluded file now, so the entry
     * count stays truthful. */
    for (j = 0; j < list->len; j++) {
        if (list->v[j].is_dir)
            continue;
        if (exclude_abs && strcmp(list->v[j].full, exclude_abs) == 0) {
            fprintf(stderr, "%s: skipping %s (it is %s)\n",
                    lzply_progname, list->v[j].full, exclude_why);
            skipped++;
            free(list->v[j].full);
            free(list->v[j].stored);
            memmove(&list->v[j], &list->v[j + 1],
                    (list->len - j - 1) * sizeof(entry_t));
            list->len--;
            j--;
            continue;
        }
        {
            FILE *t = fopen(list->v[j].full, "rb");
            if (!t) {
                fprintf(stderr, "%s: skipping unreadable %s: %s\n",
                        lzply_progname, list->v[j].full, strerror(errno));
                skipped++;
                free(list->v[j].full);
                free(list->v[j].stored);
                memmove(&list->v[j], &list->v[j + 1],
                        (list->len - j - 1) * sizeof(entry_t));
                list->len--;
                j--;
            } else {
                fclose(t);
            }
        }
    }
    *skipped_out = skipped;
    return 0;
}

/* Write all entries in list to the open file f (positioned where the
 * entries go). Directories are written as dir entries; files are
 * read, encoded and written. Prints one line per entry, like -c.
 * Returns 0 on success, -1 on failure (read/encode/write error).
 * On failure the caller must discard f's contents. *any_bch_out is
 * set if any file entry used BCH; totals accumulate into
 * *total_in_out / *total_out_out. */
static int write_entries(FILE *f, entry_list_t *list, int level,
                         const ecc_opt_t *ecc,
                         int *any_bch_out, uint64_t *total_in_out,
                         uint64_t *total_out_out)
{
    size_t i;
    int any_bch = 0;
    uint64_t total_in = 0, total_out = 0;
    for (i = 0; i < list->len; i++) {
        entry_t *e = &list->v[i];
        ehdr_t h;
        uint8_t *raw = NULL, *stored = NULL;
        size_t raw_len = 0, stored_len = 0, blob_len = 0;
        uint16_t poly_id = 0;
        int is_bch = 0;
        int eff_level = level;
        memset(&h, 0, sizeof h);
        h.path = e->stored;
        h.level = (uint8_t)level;
        h.mode = e->mode;
        h.mtime = e->mtime;
        if (e->is_dir) {
            h.flags = FLAG_ISDIR;
            h.orig_size = 0;
            h.stored_size = 0;
            h.blob_size = 0;
            lzply_sha256((const uint8_t *)"", 0, h.sha);
            if (write_entry_header(f, &h) != 0)
                return -1;
            printf("  %s/ (dir)\n", e->stored);
            continue;
        }
        if (read_file(e->full, &raw, &raw_len) != 0) {
            fprintf(stderr, "%s: cannot read %s, aborting\n",
                    lzply_progname, e->full);
            return -1;
        }
        if (entry_encode(raw, raw_len, level, ecc,
                         &stored, &stored_len, &blob_len, &poly_id, &is_bch,
                         &eff_level, h.sha) != 0) {
            fprintf(stderr, "%s: failed to encode %s\n", lzply_progname, e->full);
            free(raw);
            return -1;
        }
        free(raw);
        h.level = (uint8_t)eff_level;   /* 0 when stored uncompressed */
        h.flags = 0;
        if (is_bch) {
            h.flags |= FLAG_BCH;
            h.rs_level = (uint8_t)(poly_id & 0xff);
            h.reserved = (uint8_t)(poly_id >> 8);
            any_bch = 1;
        }
        h.orig_size = raw_len;
        h.stored_size = stored_len;
        h.blob_size = blob_len;
        if (write_entry_header(f, &h) != 0 ||
            (stored_len > 0 &&
             fwrite(stored, 1, stored_len, f) != stored_len)) {
            free(stored);
            return -1;
        }
        {
            char b1[32], b2[32];
            double ratio = raw_len ? 100.0 * (double)stored_len / (double)raw_len : 0.0;
            printf("  %s  %s -> %s (%.1f%%)\n", e->stored,
                   human_size(raw_len, b1, sizeof b1),
                   human_size(stored_len, b2, sizeof b2), ratio);
        }
        total_in += raw_len;
        total_out += stored_len;
        free(stored);
    }
    *any_bch_out = any_bch;
    *total_in_out = total_in;
    *total_out_out = total_out;
    return 0;
}

/* ------------------------------------------------------------------ */
/* Selectors (for -d / -t / -l)                                        */
/* ------------------------------------------------------------------ */



/* ------------------------------------------------------------------ */
/* Date filters (-datestart / -dateend / -year)                        */
/* ------------------------------------------------------------------ */







/* ------------------------------------------------------------------ */
/* Archive scan (for -a)                                               */
/* ------------------------------------------------------------------ */








/* Create a fresh archive from the given inputs (files and/or
 * directories). output_arg may be NULL, in which case the output is
 * inputs[0] with trailing slashes stripped + ".lzply" (the -c
 * default). Stored paths are relative to each input's parent, as
 * before. */
static int cmd_create(const char **inputs, int ninputs, const char *output_arg,
                      int level, const ecc_opt_t *ecc,
                      int ow_mode)
{
    char *out_path = NULL, *out_abs = NULL;
    char *stripped = NULL;
    entry_list_t list;
    FILE *f = NULL;
    int skipped = 0, rc = 0;
    int any_bch = 0;
    uint64_t total_in = 0, total_out = 0;

    memset(&list, 0, sizeof list);
    /* Default output: first input path with trailing slashes stripped
     * + ".lzply". */
    stripped = xstrdup(inputs[0]);
    {
        size_t n = strlen(stripped);
        while (n > 1 && stripped[n - 1] == '/')
            stripped[--n] = '\0';
    }
    if (output_arg) {
        out_path = xstrdup(output_arg);
    } else {
        out_path = xmalloc(strlen(stripped) + 6);
        sprintf(out_path, "%s.lzply", stripped);
    }
    out_abs = abs_path(out_path);
    if (ninputs == 1) {
        /* -c with a single input: refuse to overwrite the input itself. */
        char *root = realpath(inputs[0], NULL);
        if (root) {
            if (strcmp(out_abs, root) == 0) {
                fprintf(stderr, "%s: output would overwrite the input\n",
                        lzply_progname);
                free(root);
                rc = EXIT_USAGE;
                goto done;
            }
            free(root);
        }
    }
    if (!ask_overwrite(out_path, ow_mode)) {
        rc = 0;
        goto done;
    }
    if (collect_inputs(inputs, ninputs, out_abs, "the output file",
                       &list, &skipped) != 0) {
        rc = EXIT_IO;
        goto done;
    }
    /* The format is v4, always. */
    f = fopen(out_path, "wb");
    if (!f) {
        fprintf(stderr, "%s: cannot create %s: %s\n", lzply_progname, out_path,
                strerror(errno));
        rc = EXIT_IO;
        goto done;
    }
    write_global_header(f, (uint32_t)list.len, LZPLY_VERSION);
    if (write_entries(f, &list, level, ecc, &any_bch,
                      &total_in, &total_out) != 0) {
        fclose(f);
        unlink(out_path);
        rc = EXIT_IO;
        goto done;
    }
    (void)any_bch;
    {
        uint8_t end[2] = {0, 0};
        if (fwrite(end, 1, 2, f) != 2)
            goto write_fail;
    }
    if (fclose(f) != 0) {
        fprintf(stderr, "%s: error closing %s: %s\n", lzply_progname, out_path,
                strerror(errno));
        rc = EXIT_IO;
        goto done;
    }
    f = NULL;
    {
        char b1[32], b2[32];
        printf("%s: wrote %s (%zu entries, %s -> %s)%s\n", lzply_progname,
               out_path, list.len, human_size(total_in, b1, sizeof b1),
               human_size(total_out, b2, sizeof b2),
               skipped ? " [some files skipped]" : "");
    }
    rc = skipped ? EXIT_IO : 0;
    goto done;
write_fail:
    fprintf(stderr, "%s: write failed on %s: %s\n", lzply_progname, out_path,
            strerror(errno));
    if (f)
        fclose(f);
    unlink(out_path);
    rc = EXIT_IO;
done:
    entry_list_free(&list);
    free(out_path);
    free(out_abs);
    free(stripped);
    return rc;
}

/* Append files/dirs to an existing archive (or create it if it does
 * not exist). inputs[0..ninputs) are the files/dirs to add; stored
 * paths are relative to each input's parent, exactly as -c does.
 * New entries use the same -e / poly= options as -c.
 * Without duplicates this is a true incremental append: the new
 * entries are staged to a temp file, appended just before the end
 * marker, and entry_count (and the version byte, if any new entry
 * uses BCH) is updated in place. With duplicates the archive is
 * rewritten via a temp file (kept entries copied byte-for-byte,
 * replaced entries dropped, new entries appended) and renamed over
 * the original, so exactly one entry per path remains and the new
 * content wins. Returns an exit code. */
static int cmd_append(const char *archive, const char **inputs, int ninputs,
                      int level, const ecc_opt_t *ecc)
{
    struct stat st;
    char *arch_abs = NULL;
    char *replaced = NULL;      /* per old entry: 1 if replaced by a new file */
    int old_version = LZPLY_VERSION;
    uint32_t old_count = 0;
    off_t size = 0, end_off = 0;
    scan_list_t old;
    entry_list_t list;
    int skipped = 0;
    int rc = 0;
    uint32_t new_count;
    size_t i, j, nrep = 0;
    int has_dup = 0;

    memset(&list, 0, sizeof list);
    memset(&old, 0, sizeof old);
    if (stat(archive, &st) != 0) {
        if (errno == ENOENT) {
            /* No archive yet: create it, like -c. */
            return cmd_create(inputs, ninputs, archive, level, ecc,
                              OW_YES);
        }
        fprintf(stderr, "%s: cannot stat %s: %s\n", lzply_progname, archive,
                strerror(errno));
        return EXIT_IO;
    }
    if (scan_archive(archive, &old_version, &old_count, &size, &old,
                     &end_off) != 0)
        return EXIT_CORRUPT;
    arch_abs = abs_path(archive);
    if (collect_inputs(inputs, ninputs, arch_abs, "the archive",
                       &list, &skipped) != 0) {
        scan_list_free(&old);
        free(arch_abs);
        return EXIT_IO;
    }
    /* Drop new directory entries that already exist in the archive:
     * a dir entry is only a marker, so there is nothing to replace. */
    for (i = 0; i < list.len; i++) {
        if (!list.v[i].is_dir)
            continue;
        for (j = 0; j < old.len; j++) {
            if (strcmp(list.v[i].stored, old.v[j].path) == 0) {
                free(list.v[i].full);
                free(list.v[i].stored);
                memmove(&list.v[i], &list.v[i + 1],
                        (list.len - i - 1) * sizeof(entry_t));
                list.len--;
                i--;
                break;
            }
        }
    }
    if (list.len == 0) {
        printf("%s: nothing to add to %s\n", lzply_progname, archive);
        scan_list_free(&old);
        entry_list_free(&list);
        free(arch_abs);
        return 0;
    }
    replaced = xmalloc(old.len ? old.len : 1);
    memset(replaced, 0, old.len ? old.len : 1);
    for (i = 0; i < list.len; i++) {
        for (j = 0; j < old.len; j++) {
            if (strcmp(list.v[i].stored, old.v[j].path) == 0) {
                replaced[j] = 1;
                has_dup = 1;
                break;
            }
        }
    }
    for (j = 0; j < old.len; j++)
        if (replaced[j])
            nrep++;
    (void)old_version;          /* the format is v4, always */
    new_count = (uint32_t)(old.len - nrep + list.len);
    if (!has_dup) {
        /* True incremental append: stage the new entries to a temp
         * file, append them just before the end marker, then update
         * the global header in place. The archive is only touched
         * once every new entry has encoded successfully. */
        char *tmp_path = NULL;
        FILE *tmp = temp_in_same_dir(archive, &tmp_path);
        FILE *af = NULL;
        int any_bch = 0;
        uint64_t total_in = 0, total_out = 0;
        uint8_t vbuf[4];
        off_t tmp_size;
        if (!tmp) {
            rc = EXIT_IO;
            goto append_done;
        }
        if (write_entries(tmp, &list, level, ecc, &any_bch,
                          &total_in, &total_out) != 0) {
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        (void)any_bch;
        (void)total_in;
        (void)total_out;
        if (fflush(tmp) != 0 || fseeko(tmp, 0, SEEK_END) != 0) {
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        tmp_size = ftello(tmp);
        af = fopen(archive, "r+b");
        if (!af) {
            fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname,
                    archive, strerror(errno));
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        if (fseeko(tmp, 0, SEEK_SET) != 0 ||
            fseeko(af, end_off, SEEK_SET) != 0 ||
            copy_bytes(tmp, af, (uint64_t)tmp_size) != 0) {
            fprintf(stderr, "%s: failed appending to %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            fclose(tmp);
            fclose(af);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        fclose(tmp);
        unlink(tmp_path);
        free(tmp_path);
        tmp = NULL;
        tmp_path = NULL;
        {
            uint8_t end[2] = {0, 0};
            if (fwrite(end, 1, 2, af) != 2) {
                fprintf(stderr, "%s: failed appending to %s: %s\n",
                        lzply_progname, archive, strerror(errno));
                fclose(af);
                rc = EXIT_IO;
                goto append_done;
            }
        }
        /* Update version (offset 4) and entry count (offset 6). */
        if (fseeko(af, 4, SEEK_SET) != 0 ||
            fputc(LZPLY_VERSION, af) == EOF ||
            fseeko(af, 6, SEEK_SET) != 0) {
            fprintf(stderr, "%s: failed updating header of %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            fclose(af);
            rc = EXIT_IO;
            goto append_done;
        }
        put32le(vbuf, new_count);
        if (fwrite(vbuf, 1, 4, af) != 4) {
            fprintf(stderr, "%s: failed updating header of %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            fclose(af);
            rc = EXIT_IO;
            goto append_done;
        }
        if (fflush(af) != 0 || fsync(fileno(af)) != 0) {
            fprintf(stderr, "%s: failed writing %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            fclose(af);
            rc = EXIT_IO;
            goto append_done;
        }
        fclose(af);
        printf("%s: added %zu entries to %s (%u entries total)%s\n",
               lzply_progname, list.len, archive, new_count,
               skipped ? " [some files skipped]" : "");
        rc = skipped ? EXIT_IO : 0;
        goto append_done;
    }
    /* Duplicates: rewrite via a temp file, then rename over the
     * original. Kept entries are copied byte-for-byte; replaced
     * entries are dropped; new entries are appended. The original
     * is untouched until the rename, so a failure leaves it intact. */
    {
        char *tmp_path = NULL;
        FILE *tmp = temp_in_same_dir(archive, &tmp_path);
        FILE *src = NULL;
        int any_bch = 0;
        uint64_t total_in = 0, total_out = 0;
        struct stat ost;
        if (!tmp) {
            rc = EXIT_IO;
            goto append_done;
        }
        write_global_header(tmp, new_count, LZPLY_VERSION);
        src = fopen(archive, "rb");
        if (!src) {
            fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname,
                    archive, strerror(errno));
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        for (j = 0; j < old.len; j++) {
            if (replaced[j])
                continue;
            if (fseeko(src, old.v[j].offset, SEEK_SET) != 0 ||
                copy_bytes(src, tmp, old.v[j].total_len) != 0) {
                fprintf(stderr, "%s: failed rewriting %s: %s\n",
                        lzply_progname, archive, strerror(errno));
                fclose(src);
                fclose(tmp);
                unlink(tmp_path);
                free(tmp_path);
                rc = EXIT_IO;
                goto append_done;
            }
        }
        fclose(src);
        src = NULL;
        if (write_entries(tmp, &list, level, ecc, &any_bch,
                          &total_in, &total_out) != 0) {
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        (void)any_bch;
        (void)total_in;
        (void)total_out;
        {
            uint8_t end[2] = {0, 0};
            if (fwrite(end, 1, 2, tmp) != 2) {
                fprintf(stderr, "%s: failed writing %s: %s\n",
                        lzply_progname, archive, strerror(errno));
                fclose(tmp);
                unlink(tmp_path);
                free(tmp_path);
                rc = EXIT_IO;
                goto append_done;
            }
        }
        /* Keep the original's permissions on the rewritten archive. */
        if (stat(archive, &ost) == 0)
            fchmod(fileno(tmp), ost.st_mode & 07777);
        if (fflush(tmp) != 0 || fsync(fileno(tmp)) != 0) {
            fprintf(stderr, "%s: failed writing %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            fclose(tmp);
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        if (fclose(tmp) != 0) {
            fprintf(stderr, "%s: failed writing %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        tmp = NULL;
        if (rename(tmp_path, archive) != 0) {
            fprintf(stderr, "%s: cannot replace %s: %s\n",
                    lzply_progname, archive, strerror(errno));
            unlink(tmp_path);
            free(tmp_path);
            rc = EXIT_IO;
            goto append_done;
        }
        free(tmp_path);
        printf("%s: added %zu entries to %s (%u entries total, %zu replaced)%s\n",
               lzply_progname, list.len, archive, new_count, nrep,
               skipped ? " [some files skipped]" : "");
        rc = skipped ? EXIT_IO : 0;
        goto append_done;
    }
append_done:
    scan_list_free(&old);
    entry_list_free(&list);
    free(arch_abs);
    free(replaced);
    return rc;
}
static int open_archive(const char *path, FILE **f_out, uint32_t *count_out,
                        off_t *size_out)
{
    struct stat st;
    FILE *f = fopen(path, "rb");
    if (!f) {
        fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname, path,
                strerror(errno));
        return EXIT_IO;
    }
    if (fstat(fileno(f), &st) != 0) {
        fclose(f);
        return EXIT_IO;
    }
    if (read_global_header(f, count_out) != 0) {
        fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
                lzply_progname, path);
        fclose(f);
        return EXIT_CORRUPT;
    }
    *f_out = f;
    *size_out = st.st_size;
    return 0;
}

/* List an archive's contents. If selectors are given, only entries
 * matching a selector are listed; the date filter (if any) applies
 * on top of the selectors. */
static int cmd_list(const char *archive, const char **selectors, int nselectors,
                    const date_filter_t *dfilter)
{
    FILE *f = NULL;
    uint32_t count = 0;
    off_t size = 0;
    int rc = open_archive(archive, &f, &count, &size);
    uint32_t seen = 0;
    if (rc != 0)
        return rc;
    printf("%-40s %12s %12s  lvl ecc\n", "path", "original", "stored");
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        char b1[32], b2[32], ecc[16];
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            fclose(f);
            return EXIT_CORRUPT;
        }
        if (!path_matches_selectors(h.path, selectors, nselectors) ||
            !date_filter_matches(dfilter, h.mtime)) {
            if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                fprintf(stderr, "%s: truncated archive\n", lzply_progname);
                free(h.path);
                fclose(f);
                return EXIT_CORRUPT;
            }
            free(h.path);
            continue;
        }
        if (h.flags & FLAG_BCH)
            snprintf(ecc, sizeof ecc, "BCH %04x",
                     (unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
        else
            snprintf(ecc, sizeof ecc, "-");
        printf("%-40s %12s %12s  %d   %-8s\n", h.path,
               human_size(h.orig_size, b1, sizeof b1),
               human_size(h.stored_size, b2, sizeof b2),
               h.level, ecc);
        if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
            fprintf(stderr, "%s: truncated archive\n", lzply_progname);
            free(h.path);
            fclose(f);
            return EXIT_CORRUPT;
        }
        free(h.path);
        seen++;
    }
    if (seen == 0 && (nselectors > 0 || date_filter_active(dfilter))) {
        if (nselectors > 0 && date_filter_active(dfilter))
            printf("no entries match the given selector(s) and date filter(s)\n");
        else if (nselectors > 0)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries match the given date filter(s)\n");
        fclose(f);
        return 0;
    }
    printf("%u entries\n", seen);
    fclose(f);
    return 0;
}

/* Shared by -d and -t. When extract==0, data is decoded and verified
 * but not written. If selectors are given, only entries matching a
 * selector are extracted/tested; the date filter (if any) applies on
 * top of the selectors; the rest are skipped unread.
 * Returns the worst exit code seen. A selector/filter matching nothing
 * prints a message and returns 0. */
static int cmd_extract(const char *archive, const char *dest_arg,
                       int ow_mode, int extract,
                       const char **selectors, int nselectors,
                       const date_filter_t *dfilter)
{
    FILE *f = NULL;
    uint32_t count = 0;
    off_t size = 0;
    int rc = open_archive(archive, &f, &count, &size);
    int worst = 0;
    uint32_t matched = 0;
    const char *dest = dest_arg ? dest_arg : ".";
    if (rc != 0)
        return rc;
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        uint8_t *stored = NULL;
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            worst = EXIT_CORRUPT;
            break;
        }
        if (h.stored_size > (uint64_t)(size - ftello(f))) {
            fprintf(stderr, "%s: entry %s claims more data than the file holds\n",
                    lzply_progname, h.path);
            free(h.path);
            worst = EXIT_CORRUPT;
            break;
        }
        if (!path_matches_selectors(h.path, selectors, nselectors) ||
            !date_filter_matches(dfilter, h.mtime)) {
            /* Skip this entry unread. */
            if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                fprintf(stderr, "%s: truncated archive\n", lzply_progname);
                free(h.path);
                worst = EXIT_CORRUPT;
                break;
            }
            free(h.path);
            continue;
        }
        matched++;
        stored = xmalloc(h.stored_size ? (size_t)h.stored_size : 1);
        if (h.stored_size > 0 &&
            fread(stored, 1, (size_t)h.stored_size, f) != (size_t)h.stored_size) {
            fprintf(stderr, "%s: truncated data for %s\n", lzply_progname, h.path);
            free(stored);
            free(h.path);
            worst = EXIT_CORRUPT;
            break;
        }
        if (h.flags & FLAG_ISDIR) {
            if (extract) {
                char *dp = xmalloc(strlen(dest) + strlen(h.path) + 2);
                sprintf(dp, "%s/%s", dest, h.path);
                if (mkdir_p(dp, h.mode ? h.mode : 0755) != 0)
                    fprintf(stderr, "%s: cannot create directory %s: %s\n",
                            lzply_progname, dp, strerror(errno));
                free(dp);
            }
            printf("  %s/ (dir)\n", h.path);
            free(stored);
            free(h.path);
            continue;
        }
                {
            uint8_t *raw = NULL;
            size_t raw_len = 0;
            int corrected = 0;
            int is_bch = (h.flags & FLAG_BCH) != 0;
            uint16_t poly_id = (uint16_t)(h.rs_level |
                                          ((uint16_t)h.reserved << 8));
                        int dr = entry_decode(stored, (size_t)h.stored_size, h.level,
                                  is_bch, poly_id,
                                  h.sha, (size_t)h.blob_size,
                                  &raw, &raw_len, &corrected);
            free(stored);
                        if (dr != 0) {
                fprintf(stderr, "%s: %s: corrupt or unrecoverable data\n",
                        lzply_progname, h.path);
                if (EXIT_CORRUPT > worst)
                    worst = EXIT_CORRUPT;
                free(h.path);
                continue;
            }
            if (raw_len != h.orig_size) {
                fprintf(stderr, "%s: %s: size mismatch after decode\n",
                        lzply_progname, h.path);
                free(raw);
                if (EXIT_CORRUPT > worst)
                    worst = EXIT_CORRUPT;
                free(h.path);
                continue;
            }
            if (!extract) {
                printf("  %s OK%s\n", h.path,
                       corrected ? " (BCH corrected bit errors)" : "");
                free(raw);
                free(h.path);
                continue;
            }
            {
                char *dp = xmalloc(strlen(dest) + strlen(h.path) + 2);
                char *pd;
                sprintf(dp, "%s/%s", dest, h.path);
                pd = parent_dir(dp);
                if (mkdir_p(pd, 0755) != 0)
                    fprintf(stderr, "%s: cannot create %s: %s\n",
                            lzply_progname, pd, strerror(errno));
                free(pd);
                if (!ask_overwrite(dp, ow_mode)) {
                    printf("  %s skipped\n", h.path);
                    free(dp);
                    free(raw);
                    free(h.path);
                    continue;
                }
                if (write_file(dp, raw, raw_len, h.mode ? h.mode : 0644) != 0) {
                    fprintf(stderr, "%s: cannot write %s: %s\n",
                            lzply_progname, dp, strerror(errno));
                    if (EXIT_IO > worst)
                        worst = EXIT_IO;
                } else {
                    printf("  %s OK%s\n", h.path,
                           corrected ? " (BCH corrected bit errors)" : "");
                }
                free(dp);
                free(raw);
                free(h.path);
            }
        }
    }
    if (matched == 0 && (nselectors > 0 || date_filter_active(dfilter))) {
        if (nselectors > 0 && date_filter_active(dfilter))
            printf("no entries match the given selector(s) and date filter(s)\n");
        else if (nselectors > 0)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries match the given date filter(s)\n");
    }
    fclose(f);
    return worst;
}

/* Inspect an archive (-i): print every entry's path, type,
 * permissions, mtime, sizes, and error correction, reading the entry
 * headers only. Entry data is never read, never decompressed, and
 * the archived files are never opened, so this is fast even on large
 * archives — and it works on an archive whose data is corrupt, as
 * long as the headers are intact. Selectors and the date filter
 * restrict which entries are printed. Returns 0 on success. */
static int cmd_inspect(const char *archive, const char **selectors,
                       int nselectors, const date_filter_t *dfilter)
{
    FILE *f = NULL;
    uint32_t count = 0;
    off_t size = 0;
    int rc = open_archive(archive, &f, &count, &size);
    uint32_t seen = 0, ndirs = 0, nfiles = 0;
    if (rc != 0)
        return rc;
    printf("%-40s %-10s %-4s %-11s %-20s %12s %12s  %3s %-8s\n",
           "path", "type", "perm", "symbolic", "mtime (UTC)",
           "original", "stored", "lvl", "ecc");
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        char b1[32], b2[32], mt[32], perm[11], ecc[16];
        int is_dir;
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            fclose(f);
            return EXIT_CORRUPT;
        }
        if (!path_matches_selectors(h.path, selectors, nselectors) ||
            !date_filter_matches(dfilter, h.mtime)) {
            if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                fprintf(stderr, "%s: truncated archive\n", lzply_progname);
                free(h.path);
                fclose(f);
                return EXIT_CORRUPT;
            }
            free(h.path);
            continue;
        }
        is_dir = (h.flags & FLAG_ISDIR) != 0;
        fmt_mtime(h.mtime, mt, sizeof mt);
        fmt_perm(is_dir, h.mode, perm);
        if (h.flags & FLAG_BCH)
            snprintf(ecc, sizeof ecc, "BCH %04x",
                     (unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
        else
            snprintf(ecc, sizeof ecc, "-");
        printf("%-40s %-10s %04o %-11s %-20s %12s %12s  %3u %-8s\n",
               h.path, is_dir ? "directory" : "file",
               (unsigned)(h.mode & 07777), perm, mt,
               human_size(h.orig_size, b1, sizeof b1),
               human_size(h.stored_size, b2, sizeof b2),
               (unsigned)h.level,
               ecc);
        if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
            fprintf(stderr, "%s: truncated archive\n", lzply_progname);
            free(h.path);
            fclose(f);
            return EXIT_CORRUPT;
        }
        free(h.path);
        seen++;
        if (is_dir)
            ndirs++;
        else
            nfiles++;
    }
    if (seen == 0 && (nselectors > 0 || date_filter_active(dfilter))) {
        if (nselectors > 0 && date_filter_active(dfilter))
            printf("no entries match the given selector(s) and date filter(s)\n");
        else if (nselectors > 0)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries match the given date filter(s)\n");
        fclose(f);
        return 0;
    }
    printf("%u entries (%u directories, %u files)\n", seen, ndirs, nfiles);
    fclose(f);
    return 0;
}

/* ------------------------------------------------------------------ */
/* Tree (-tr)                                                          */
/* ------------------------------------------------------------------ */

/* One node of the reconstructed directory tree. Entries are stored
 * flat (one path per entry), so the hierarchy is rebuilt from the
 * path components. A directory node with no explicit entry (its
 * files are present but the directory itself was not stored, or was
 * filtered out) is an implied node, shown for structure. */
typedef struct tree_node {
    char *name;                 /* one path component, no '/' */
    int is_dir;
    int implied;                /* dir node with no explicit entry */
    uint64_t size;              /* file orig_size (0 for directories) */
    struct tree_node **children;
    size_t nchildren, cap;
} tree_node_t;

static tree_node_t *tree_node_new(const char *name, int is_dir, int implied,
                                  uint64_t size)
{
    tree_node_t *n = xmalloc(sizeof *n);
    n->name = xstrdup(name);
    n->is_dir = is_dir;
    n->implied = implied;
    n->size = size;
    n->children = NULL;
    n->nchildren = n->cap = 0;
    return n;
}

static void tree_node_free(tree_node_t *n)
{
    size_t i;
    for (i = 0; i < n->nchildren; i++)
        tree_node_free(n->children[i]);
    free(n->children);
    free(n->name);
    free(n);
}

static int cmp_tree_node(const void *a, const void *b)
{
    return strcmp((*(tree_node_t *const *)a)->name,
                  (*(tree_node_t *const *)b)->name);
}

/* Find a child by name, or create it (as a directory unless it is
 * the last component of a file path). Returns the child. */
static tree_node_t *tree_child(tree_node_t *parent, const char *name,
                               int is_dir, int implied, uint64_t size)
{
    size_t i;
    for (i = 0; i < parent->nchildren; i++) {
        if (strcmp(parent->children[i]->name, name) == 0) {
            tree_node_t *c = parent->children[i];
            /* A node first seen as an implied directory may turn out
             * to have an explicit entry; a node first seen as a file
             * cannot also be a directory in a valid archive. */
            if (is_dir && !c->is_dir) {
                c->is_dir = 1;
                c->implied = implied;
                c->size = 0;
            } else if (is_dir && c->implied && !implied) {
                c->implied = 0;
            }
            return c;
        }
    }
    if (parent->nchildren == parent->cap) {
        parent->cap = parent->cap ? parent->cap * 2 : 8;
        parent->children = xrealloc(parent->children,
                                    parent->cap * sizeof(tree_node_t *));
    }
    parent->children[parent->nchildren] =
        tree_node_new(name, is_dir, implied, size);
    return parent->children[parent->nchildren++];
}

/* Insert one stored path into the tree. A directory entry's path
 * ends in '/'; a file entry's path does not. Intermediate components
 * are directories (implied unless an explicit entry exists). */
static void tree_insert(tree_node_t *root, const char *path, int is_dir,
                        uint64_t size)
{
    char *copy = xstrdup(path);
    char *save = NULL;
    char *comp = strtok_r(copy, "/", &save);
    tree_node_t *cur = root;
    while (comp) {
        char *next = strtok_r(NULL, "/", &save);
        int last = (next == NULL);
        if (last) {
            tree_child(cur, comp, is_dir, 0, is_dir ? 0 : size);
        } else {
            cur = tree_child(cur, comp, 1, 1, 0);
        }
        comp = next;
    }
    free(copy);
}

/* Count directories and files in the tree (excluding the root). */
static void tree_count(tree_node_t *n, uint32_t *ndirs, uint32_t *nfiles)
{
    size_t i;
    for (i = 0; i < n->nchildren; i++) {
        if (n->children[i]->is_dir)
            (*ndirs)++;
        else
            (*nfiles)++;
        tree_count(n->children[i], ndirs, nfiles);
    }
}

/* Print a node's children, each on its own line with the tree
 * connectors, recursing into directories. prefix is the indentation
 * built up from the ancestors. */
static void tree_print_children(tree_node_t *dir, const char *prefix)
{
    size_t i;
    if (dir->nchildren > 1)
        qsort(dir->children, dir->nchildren, sizeof(tree_node_t *),
              cmp_tree_node);
    for (i = 0; i < dir->nchildren; i++) {
        tree_node_t *c = dir->children[i];
        int last = (i + 1 == dir->nchildren);
        char b1[32];
        if (c->is_dir) {
            printf("%s%s%s/\n", prefix, last ? "└── " : "├── ", c->name);
        } else {
            printf("%s%s%s (%s)\n", prefix, last ? "└── " : "├── ",
                   c->name, human_size(c->size, b1, sizeof b1));
        }
        if (c->is_dir) {
            char next[4096];
            snprintf(next, sizeof next, "%s%s", prefix,
                     last ? "    " : "│   ");
            tree_print_children(c, next);
        }
    }
}

/* Print an archive as a tree, like the Linux `tree` command.
 * Headers only — entry data is never read. Selectors and the date
 * filter restrict which entries appear; a filtered-out directory
 * still appears as an implied node if one of its files is shown.
 * Returns 0 on success. */
static int cmd_tree(const char *archive, const char **selectors,
                    int nselectors, const date_filter_t *dfilter)
{
    FILE *f = NULL;
    uint32_t count = 0;
    off_t size = 0;
    int rc = open_archive(archive, &f, &count, &size);
    tree_node_t *root;
    uint32_t seen = 0, ndirs = 0, nfiles = 0;
    if (rc != 0)
        return rc;
    root = tree_node_new("", 1, 0, 0);
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            tree_node_free(root);
            fclose(f);
            return EXIT_CORRUPT;
        }
        if (!path_matches_selectors(h.path, selectors, nselectors) ||
            !date_filter_matches(dfilter, h.mtime)) {
            if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                fprintf(stderr, "%s: truncated archive\n", lzply_progname);
                free(h.path);
                tree_node_free(root);
                fclose(f);
                return EXIT_CORRUPT;
            }
            free(h.path);
            continue;
        }
        tree_insert(root, h.path, (h.flags & FLAG_ISDIR) != 0,
                    h.orig_size);
        if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
            fprintf(stderr, "%s: truncated archive\n", lzply_progname);
            free(h.path);
            tree_node_free(root);
            fclose(f);
            return EXIT_CORRUPT;
        }
        free(h.path);
        seen++;
    }
    if (seen == 0 && (nselectors > 0 || date_filter_active(dfilter))) {
        if (nselectors > 0 && date_filter_active(dfilter))
            printf("no entries match the given selector(s) and date filter(s)\n");
        else if (nselectors > 0)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries match the given date filter(s)\n");
        tree_node_free(root);
        fclose(f);
        return 0;
    }
    printf("%s\n", archive);
    tree_print_children(root, "");
    tree_count(root, &ndirs, &nfiles);
    printf("\n%u directories, %u files\n", ndirs, nfiles);
    tree_node_free(root);
    fclose(f);
    return 0;
}

/* ------------------------------------------------------------------ */
/* CLI                                                                 */
/* ------------------------------------------------------------------ */

static void usage(FILE *out)
{
    fprintf(out,
        "Usage: %s -c|-d|-l|-t|-a|-i|-tr [options] <input> [output] [selectors...]\n"
        "\n"
        "  -c            compress a file or directory into one .lzply archive\n"
        "  -a            append files/dirs to an archive (creates it if\n"
        "                missing): -a <archive.lzply> <file|dir> [...]\n"
        "                New entries use the same -e / poly=\n"
        "                options as -c. A stored path that already exists\n"
        "                is replaced (exactly one entry per path remains).\n"
        "                Without duplicates the append is incremental\n"
        "                (no rewrite of the existing archive).\n"
        "  -d            decompress an archive (extracts into [output] dir, default .)\n"
        "                With selectors after the dest dir, extracts only\n"
        "                matching entries: -d <arc> <dest> <selector> [...]\n"
        "  -l            list an archive's contents (selectors filter it)\n"
        "  -t            test an archive (decode and verify, write nothing)\n"
        "                Selectors go right after the archive: -t <arc> <selector> [...]\n"
        "  -i            inspect an archive: path, type, permissions,\n"
        "                mtime, sizes, level, and error correction for every\n"
        "                entry, from the headers only — no data is read,\n"
        "                nothing is decompressed. Selectors filter it.\n"
        "  -tr           print an archive as a tree, like the Linux\n"
        "                `tree` command, with a directory/file count.\n"
        "                Selectors filter it.\n"
        "  -datestart <date>  only entries with mtime on or after this date\n"
        "  -dateend <date>    only entries with mtime on or before this date\n"
        "                Dates are YYYY-MM-DD (whole day, inclusive) or\n"
        "                YYYY-MM-DDTHH:MM:SS (exact). Filters -d, -i, -tr\n"
        "                (and -t, -l); they AND with each other and with\n"
        "                any path selector.\n"
        "  -year <YYYY>  only entries whose mtime falls in that year\n"
        "                (same as that year's Jan 1 - Dec 31). Combines\n"
        "                with -datestart / -dateend; both must match.\n"
        "  -0 .. -9      compression level, like lzip (default -6). -0\n"
        "                stores entries uncompressed; BCH still applies.\n"
        "                Without -0, an entry whose compressed blob would\n"
        "                be no smaller than the original is stored\n"
        "                uncompressed automatically (level 0).\n"
        "  -e <0..7>     BCH correction level t: 0 = none, 1 -> t=1,\n"
        "                2 -> t=2, 3 -> t=4, 4 -> t=8, 5 -> t=16,\n"
        "                6 -> t=32, 7 -> t=32 (default -e 4, t=8).\n"
        "                -e 0 writes no error correction.\n"
        "  poly=NN       pin one BCH polynomial by id, hex (poly=003a)\n"
        "                or decimal (poly=58); overrides -e. The id must\n"
        "                be one of the 82 embedded polys (0001..0052).\n"
        "                Without poly=, the most efficient poly for each\n"
        "                file's blob length is picked automatically.\n"
        "  -y            overwrite without asking\n"
        "  -n            never overwrite (skip existing files)\n"
        "  --ask         ask before overwriting (default). -a used to mean\n"
        "                this; it is now the append mode.\n"
        "  -h, --help    this help\n"
        "\n"
        "Selectors: a selector matches an entry if it equals the entry's\n"
        "stored path exactly, or is a prefix of it and the next character\n"
        "is '/' (so 'photos' matches 'photos/a.jpg' but not 'photos2/a.jpg').\n"
        "A selector ending in '/' matches everything under it. For -d the\n"
        "dest dir must be given explicitly when selectors are used.\n"
        "A selector matching nothing prints a message and exits 0.\n"
        "\n"
        "Examples:\n"
        "  %s -c photos/                 photos/ -> photos.lzply\n"
        "  %s -c -9 -e 5 docs/ backup.lzply\n"
        "  %s -c poly=003a src/          pin BCH poly 0x003a (m=18, t=32)\n"
        "  %s -c -e 0 docs/ no-ecc.lzply\n"
        "  %s -c -0 raw/                 store raw data uncompressed\n"
        "  %s -a backup.lzply more/       append a directory to backup.lzply\n"
        "  %s -a backup.lzply a.txt b.txt append two files\n"
        "  %s -d backup.lzply             extract into .\n"
        "  %s -d -y backup.lzply out/\n"
        "  %s -d backup.lzply out/ photos/   extract only photos/ from backup.lzply\n"
        "  %s -t backup.lzply photos/a.jpg   test only that one file\n"
        "  %s -i backup.lzply            inspect: headers only, no decompress\n"
        "  %s -tr backup.lzply           print the archive as a tree\n"
        "  %s -d backup.lzply out/ -year 2024   extract only 2024 files\n"
        "  %s -i backup.lzply -datestart 2024-01-01 -dateend 2024-06-30\n"
        "                               inspect only Jan-Jun 2024 entries\n"
        "  %s -tr backup.lzply photos/ -year 2025   tree of 2025 photos only\n"
        "\n"
        "Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.\n",
        lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
        lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
        lzply_progname, lzply_progname, lzply_progname, lzply_progname,
        lzply_progname);
}

enum { MODE_NONE, MODE_COMPRESS, MODE_DECOMPRESS, MODE_LIST, MODE_TEST,
       MODE_APPEND, MODE_INSPECT, MODE_TREE };

/* Parse a poly=NN value: hex if it has a 0x prefix or any a-f/A-F
 * letter, else decimal. Returns the poly, or NULL if it is not a
 * number or not one of the 82 embedded polys. */
static const bch_poly_t *parse_poly_id(const char *s)
{
    int is_hex = 0;
    const char *p = s;
    long v;
    char *end;
    if (!*s)
        return NULL;
    if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
        is_hex = 1;
        p += 2;
    } else {
        for (const char *q = s; *q; q++) {
            if ((*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F')) {
                is_hex = 1;
                break;
            }
        }
    }
    if (!*p)
        return NULL;
    v = strtol(p, &end, is_hex ? 16 : 10);
    if (*end != '\0' || v < 0 || v > 0xffff)
        return NULL;
    return bch_poly_by_id((uint16_t)v);
}

int main(int argc, char **argv)
{
    int mode = MODE_NONE;
    int level = 6;
    int ecc_level = 4;          /* default -e 4 -> BCH t=8 */
    const bch_poly_t *pinned_poly = NULL;
    int ow_mode = OW_ASK;
    date_filter_t dfilter;
    const char **args = NULL;   /* positional arguments after the options */
    int nargs = 0;
    int i;
    int rc;

    lzply_progname = argv[0];
    {
        const char *slash = strrchr(lzply_progname, '/');
        if (slash)
            lzply_progname = slash + 1;
    }
    memset(&dfilter, 0, sizeof dfilter);
    dfilter.start = -1;
    dfilter.end = -1;
    dfilter.year = 0;
    crc32_init();

    /* Positional arguments are collected here, and options are
     * recognised anywhere on the command line — even after the
     * positionals — so `lzply -d arc out/ -year 2024` works. */
    args = xmalloc(sizeof(char *) * (size_t)(argc > 0 ? argc : 1));
    for (i = 1; i < argc; i++) {
        const char *a = argv[i];
        if (strcmp(a, "--") == 0) {
            for (i++; i < argc; i++)
                args[nargs++] = argv[i];
            break;
        }
        if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
            usage(stdout);
            free(args);
            return 0;
        }
        if (strcmp(a, "-c") == 0 || strcmp(a, "--compress") == 0) {
            mode = MODE_COMPRESS;
        } else if (strcmp(a, "-a") == 0 || strcmp(a, "--append") == 0) {
            mode = MODE_APPEND;
        } else if (strcmp(a, "-d") == 0 || strcmp(a, "--decompress") == 0) {
            mode = MODE_DECOMPRESS;
        } else if (strcmp(a, "-l") == 0 || strcmp(a, "--list") == 0) {
            mode = MODE_LIST;
        } else if (strcmp(a, "-t") == 0 || strcmp(a, "--test") == 0) {
            mode = MODE_TEST;
        } else if (strcmp(a, "-i") == 0 || strcmp(a, "--inspect") == 0) {
            mode = MODE_INSPECT;
        } else if (strcmp(a, "-tr") == 0 || strcmp(a, "--tree") == 0) {
            mode = MODE_TREE;
        } else if (strcmp(a, "-datestart") == 0 ||
                   strcmp(a, "--datestart") == 0) {
            if (i + 1 >= argc) {
                fprintf(stderr, "%s: -datestart needs a date (YYYY-MM-DD)\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            if (parse_date(argv[++i], 0, &dfilter.start) != 0) {
                fprintf(stderr,
                        "%s: bad -datestart '%s' (want YYYY-MM-DD or "
                        "YYYY-MM-DDTHH:MM:SS)\n", lzply_progname, argv[i]);
                return EXIT_USAGE;
            }
        } else if (strncmp(a, "-datestart=", 11) == 0 ||
                   strncmp(a, "--datestart=", 12) == 0) {
            const char *eq = strchr(a, '=');
            if (parse_date(eq + 1, 0, &dfilter.start) != 0) {
                fprintf(stderr,
                        "%s: bad -datestart '%s' (want YYYY-MM-DD or "
                        "YYYY-MM-DDTHH:MM:SS)\n", lzply_progname, eq + 1);
                return EXIT_USAGE;
            }
        } else if (strcmp(a, "-dateend") == 0 ||
                   strcmp(a, "--dateend") == 0) {
            if (i + 1 >= argc) {
                fprintf(stderr, "%s: -dateend needs a date (YYYY-MM-DD)\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            if (parse_date(argv[++i], 1, &dfilter.end) != 0) {
                fprintf(stderr,
                        "%s: bad -dateend '%s' (want YYYY-MM-DD or "
                        "YYYY-MM-DDTHH:MM:SS)\n", lzply_progname, argv[i]);
                return EXIT_USAGE;
            }
        } else if (strncmp(a, "-dateend=", 9) == 0 ||
                   strncmp(a, "--dateend=", 10) == 0) {
            const char *eq = strchr(a, '=');
            if (parse_date(eq + 1, 1, &dfilter.end) != 0) {
                fprintf(stderr,
                        "%s: bad -dateend '%s' (want YYYY-MM-DD or "
                        "YYYY-MM-DDTHH:MM:SS)\n", lzply_progname, eq + 1);
                return EXIT_USAGE;
            }
        } else if (strcmp(a, "-year") == 0 || strcmp(a, "--year") == 0) {
            char *end;
            long y;
            if (i + 1 >= argc) {
                fprintf(stderr, "%s: -year needs a year (YYYY)\n", lzply_progname);
                return EXIT_USAGE;
            }
            y = strtol(argv[++i], &end, 10);
            if (*end != '\0' || y < 1970 || y > 9999) {
                fprintf(stderr, "%s: bad -year '%s' (want a year, e.g. 2024)\n",
                        lzply_progname, argv[i]);
                return EXIT_USAGE;
            }
            dfilter.year = (int)y;
        } else if (strncmp(a, "-year=", 6) == 0 ||
                   strncmp(a, "--year=", 7) == 0) {
            const char *eq = strchr(a, '=');
            char *end;
            long y = strtol(eq + 1, &end, 10);
            if (*end != '\0' || y < 1970 || y > 9999) {
                fprintf(stderr, "%s: bad -year '%s' (want a year, e.g. 2024)\n",
                        lzply_progname, eq + 1);
                return EXIT_USAGE;
            }
            dfilter.year = (int)y;
        } else if (strcmp(a, "-y") == 0 || strcmp(a, "--force") == 0) {
            ow_mode = OW_YES;
        } else if (strcmp(a, "-n") == 0 || strcmp(a, "--no-clobber") == 0) {
            ow_mode = OW_NO;
        } else if (strcmp(a, "--ask") == 0) {
            /* -a used to mean this; it is now the append mode. */
            ow_mode = OW_ASK;
        } else if (a[0] == '-' && a[1] >= '0' && a[1] <= '9' && a[2] == '\0') {
            level = a[1] - '0';
        } else if (strcmp(a, "-e") == 0 || strcmp(a, "--rs") == 0 ||
                   strcmp(a, "--ecc") == 0) {
            if (i + 1 >= argc) {
                fprintf(stderr, "%s: -e needs a level 0..7\n", lzply_progname);
                return EXIT_USAGE;
            }
            ecc_level = atoi(argv[++i]);
            if (ecc_level < 0 || ecc_level > 7) {
                fprintf(stderr, "%s: BCH level must be 0..7\n", lzply_progname);
                return EXIT_USAGE;
            }
        } else if (a[0] == '-' && a[1] == 'e' && a[2] != '\0') {
            ecc_level = atoi(a + 2);
            if (ecc_level < 0 || ecc_level > 7) {
                fprintf(stderr, "%s: BCH level must be 0..7\n", lzply_progname);
                return EXIT_USAGE;
            }
        } else if (strncmp(a, "poly=", 5) == 0 ||
                   strncmp(a, "-poly=", 6) == 0 ||
                   strncmp(a, "--poly=", 7) == 0) {
            const char *eq = strchr(a, '=');
            pinned_poly = parse_poly_id(eq + 1);
            if (!pinned_poly) {
                fprintf(stderr,
                        "%s: unknown BCH polynomial '%s' "
                        "(want an id 0001..0052, hex or decimal)\n",
                        lzply_progname, eq + 1);
                return EXIT_USAGE;
            }
        } else if (a[0] == '-' && a[1] != '\0') {
            fprintf(stderr, "%s: unknown option %s\n", lzply_progname, a);
            usage(stderr);
            free(args);
            return EXIT_USAGE;
        } else {
            /* Positional argument: collect it and keep scanning, so
             * options may follow positionals. */
            args[nargs++] = a;
        }
    }
    if (mode == MODE_NONE || nargs == 0) {
        usage(stderr);
        free(args);
        return EXIT_USAGE;
    }
        {
        ecc_opt_t ecc;
        ecc.t = bch_t_for_level(ecc_level);
        ecc.pinned = pinned_poly;
        switch (mode) {
        case MODE_COMPRESS:
            if (nargs > 2) {
                fprintf(stderr, "%s: too many arguments\n", lzply_progname);
                usage(stderr);
                rc = EXIT_USAGE;
                break;
            }
            rc = cmd_create(args, 1, nargs == 2 ? args[1] : NULL,
                            level, &ecc, ow_mode);
            break;
        case MODE_APPEND:
            if (nargs < 2) {
                fprintf(stderr,
                        "%s: -a needs an archive and at least one file or directory\n",
                        lzply_progname);
                usage(stderr);
                rc = EXIT_USAGE;
                break;
            }
            rc = cmd_append(args[0], args + 1, nargs - 1,
                            level, &ecc);
            break;
        case MODE_DECOMPRESS:
            /* archive, optional dest, then selectors. */
            rc = cmd_extract(args[0], nargs >= 2 ? args[1] : NULL,
                             ow_mode, 1,
                             nargs >= 3 ? args + 2 : NULL,
                             nargs >= 3 ? nargs - 2 : 0,
                             &dfilter);
            break;
        case MODE_LIST:
            /* archive, then selectors. */
            rc = cmd_list(args[0],
                          nargs >= 2 ? args + 1 : NULL,
                          nargs >= 2 ? nargs - 1 : 0,
                          &dfilter);
            break;
        case MODE_TEST:
            /* archive, then selectors (no dest dir for -t). */
            rc = cmd_extract(args[0], NULL,
                             ow_mode, 0,
                             nargs >= 2 ? args + 1 : NULL,
                             nargs >= 2 ? nargs - 1 : 0,
                             &dfilter);
            break;
        case MODE_INSPECT:
            /* archive, then selectors. */
            rc = cmd_inspect(args[0],
                             nargs >= 2 ? args + 1 : NULL,
                             nargs >= 2 ? nargs - 1 : 0,
                             &dfilter);
            break;
        case MODE_TREE:
            /* archive, then selectors. */
            rc = cmd_tree(args[0],
                          nargs >= 2 ? args + 1 : NULL,
                          nargs >= 2 ? nargs - 1 : 0,
                          &dfilter);
            break;
        default:
            rc = EXIT_USAGE;
            break;
        }
    }
    free(args);
        return rc;
}

lzply_lib.c

Shared core — v4 format, the per-entry pipeline (lzip -> BCH), header I/O, archive scan, selectors and date filters; linked by lzply, lzply_mount, lzply_stat, lzply_heal, lzply_check and lzply_refresh

/* lzply_lib.c - shared core of the lzply archiver and lzply_mount.
 *
 * Everything both programs need: the v4 archive format, the per-entry
 * pipeline (lzip compress -> BCH encode, and the reverse), the header
 * I/O, the archive scan, and the date / selector filters. The
 * command-line tool (lzply.c) and the FUSE filesystem (lzply_mount.c)
 * both link this file. There is no legacy support: v4 is the only
 * format. (v3 archives are rejected outright; the format changed
 * in v4.)
 *
 * Archive format v4 (all integers little-endian):
 *   global header (16 bytes):
 *     magic "LZPL", version u8 (=4), flags u8, entry_count u32,
 *     reserved u64
 *   entries, each:
 *     u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
 *     u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
 *     u32 mode, u64 mtime, u32 header_crc32,
 *     path[path_len], data[stored_size]
 *     (header_crc32 covers the 74 bytes before it; blob_size is the
 *     length of the compressed stream before error-correction parity
 *     was added; mtime is the source file's modification time,
 *     seconds since the epoch, UTC)
 *   end marker: u16 path_len == 0
 * Flags: bit 0 is unused (it was used by v3), bit 1 =
 * directory, bit 2 = BCH mode.
 * For a BCH entry, poly_id = rs_level | (reserved << 8).
 */
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE

#include "lzply_lib.h"

#include <errno.h>
#include <limits.h>
#include <lzlib.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include "bch.h"
#include "sha256.h"

/* Program name used in error messages; lzply_mount sets it to "lzply_mount". */
const char *lzply_progname = "lzply";

void lzply_set_progname(const char *name)
{
    lzply_progname = name;
}

static void die_oom(void)
{
    fprintf(stderr, "%s: out of memory\n", lzply_progname);
    exit(EXIT_IO);
}

void *xmalloc(size_t n){
    void *p = malloc(n ? n : 1);
    if (!p)
        die_oom();
    return p;
}

void *xrealloc(void *p, size_t n){
    void *q = realloc(p, n ? n : 1);
    if (!q)
        die_oom();
    return q;
}

char *xstrdup(const char *s){
    char *p = strdup(s);
    if (!p)
        die_oom();
    return p;
}


void buf_init(buf_t *b){
    b->data = NULL;
    b->len = b->cap = 0;
}

void buf_free(buf_t *b){
    free(b->data);
    b->data = NULL;
    b->len = b->cap = 0;
}

static void buf_reserve(buf_t *b, size_t extra){
    if (b->len + extra > b->cap) {
        size_t nc = b->cap ? b->cap : 4096;
        while (nc < b->len + extra)
            nc *= 2;
        b->data = xrealloc(b->data, nc);
        b->cap = nc;
    }
}

void buf_append(buf_t *b, const void *p, size_t n){
    buf_reserve(b, n);
    memcpy(b->data + b->len, p, n);
    b->len += n;
}

/* Little-endian integer access (archive format is LE). */
void put16le(uint8_t *p, uint16_t v) { p[0] = v & 0xff; p[1] = (v >> 8) & 0xff; }

void put32le(uint8_t *p, uint32_t v){
    p[0] = v & 0xff; p[1] = (v >> 8) & 0xff;
    p[2] = (v >> 16) & 0xff; p[3] = (v >> 24) & 0xff;
}

void put64le(uint8_t *p, uint64_t v){
    int i;
    for (i = 0; i < 8; i++)
        p[i] = (v >> (8 * i)) & 0xff;
}

uint16_t get16le(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }

uint32_t get32le(const uint8_t *p){
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
           ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

uint64_t get64le(const uint8_t *p){
    uint64_t v = 0;
    int i;
    for (i = 0; i < 8; i++)
        v |= (uint64_t)p[i] << (8 * i);
    return v;
}

/* CRC-32 (IEEE, polynomial 0xEDB88320). */
static uint32_t crc32_table[256];

static int crc32_ready = 0;

void crc32_init(void)
{
    uint32_t i, j, c;
    for (i = 0; i < 256; i++) {
        c = i;
        for (j = 0; j < 8; j++)
            c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
        crc32_table[i] = c;
    }
    crc32_ready = 1;
}

uint32_t crc32_of(const uint8_t *p, size_t n){
    uint32_t c = 0xFFFFFFFFu;
    size_t i;
    if (!crc32_ready)
        crc32_init();
    for (i = 0; i < n; i++)
        c = crc32_table[(c ^ p[i]) & 0xff] ^ (c >> 8);
    return c ^ 0xFFFFFFFFu;
}

/* Dictionary size / match-length limit per level, matching the lzip
 * command-line tool's own table (verified by comparing output with
 * `lzip -N` on the same input). */
static const int lz_dict_size[10] =
    { 65535, 1 << 20, 3 << 19, 1 << 21, 3 << 20,
      1 << 22, 1 << 23, 1 << 24, 3 << 23, 1 << 25 };

static const int lz_match_len[10] =
    { 16, 16, 20, 24, 32, 32, 32, 32, 32, 32 };

int lz_compress_mem(const uint8_t *in, size_t in_len, int level,                           uint8_t **out, size_t *out_len)
{
    struct LZ_Encoder *enc;
    buf_t b;
    uint8_t tmp[65536];
    size_t pos = 0;
    int finished = 0;
    buf_init(&b);
    /* member_size must be >= LZ_min_dictionary_size() (4096); 0 is
     * rejected as a bad argument in lzlib 1.13. ULLONG_MAX means a
     * single member of effectively unlimited size. */
    enc = LZ_compress_open(lz_dict_size[level], lz_match_len[level],
                           (unsigned long long)-1);
    if (!enc) {
        buf_free(&b);
        return -1;
    }
    while (pos < in_len) {
        int ws = LZ_compress_write_size(enc);
        if (ws <= 0) {
            int rd = LZ_compress_read(enc, tmp, sizeof tmp);
            if (rd < 0)
                goto fail;
            if (rd == 0)
                goto fail;      /* encoder stuck: should not happen */
            buf_append(&b, tmp, (size_t)rd);
            continue;
        }
        {
            size_t n = in_len - pos;
            int wr;
            int rd;
            if (n > (size_t)ws)
                n = (size_t)ws;
            wr = LZ_compress_write(enc, in + pos, (int)n);
            if (wr < 0)
                goto fail;
            pos += (size_t)wr;
            while ((rd = LZ_compress_read(enc, tmp, sizeof tmp)) > 0)
                buf_append(&b, tmp, (size_t)rd);
            if (rd < 0)
                goto fail;
        }
    }
    if (LZ_compress_finish(enc) < 0)
        goto fail;
    while (!finished) {
        int rd = LZ_compress_read(enc, tmp, sizeof tmp);
        if (rd < 0)
            goto fail;
        if (rd > 0)
            buf_append(&b, tmp, (size_t)rd);
        finished = LZ_compress_finished(enc);
        if (!finished && rd == 0)
            goto fail;          /* no progress after finish */
    }
    LZ_compress_close(enc);
    *out = b.data;
    *out_len = b.len;
    return 0;
fail:
    LZ_compress_close(enc);
    buf_free(&b);
    return -1;
}

int lz_decompress_mem(const uint8_t *in, size_t in_len,                             uint8_t **out, size_t *out_len)
{
    struct LZ_Decoder *dec;
    buf_t b;
    uint8_t tmp[65536];
    size_t pos = 0;
    int finished = 0;
    buf_init(&b);
    dec = LZ_decompress_open();
    if (!dec) {
        buf_free(&b);
        return -1;
    }
    while (pos < in_len) {
        int ws = LZ_decompress_write_size(dec);
        if (ws <= 0) {
            int rd = LZ_decompress_read(dec, tmp, sizeof tmp);
            if (rd < 0)
                goto fail;
            if (rd == 0)
                goto fail;
            buf_append(&b, tmp, (size_t)rd);
            continue;
        }
        {
            size_t n = in_len - pos;
            int wr;
            int rd;
            if (n > (size_t)ws)
                n = (size_t)ws;
            wr = LZ_decompress_write(dec, in + pos, (int)n);
            if (wr < 0)
                goto fail;
            pos += (size_t)wr;
            while ((rd = LZ_decompress_read(dec, tmp, sizeof tmp)) > 0)
                buf_append(&b, tmp, (size_t)rd);
            if (rd < 0)
                goto fail;
        }
    }
    if (LZ_decompress_finish(dec) < 0)
        goto fail;
    while (!finished) {
        int rd = LZ_decompress_read(dec, tmp, sizeof tmp);
        if (rd < 0)
            goto fail;
        if (rd > 0)
            buf_append(&b, tmp, (size_t)rd);
        finished = LZ_decompress_finished(dec);
        if (!finished && rd == 0)
            goto fail;
    }
    if (LZ_decompress_errno(dec) != LZ_ok)
        goto fail;
    LZ_decompress_close(dec);
    *out = b.data;
    *out_len = b.len;
    return 0;
fail:
    LZ_decompress_close(dec);
    buf_free(&b);
    return -1;
}

/* Largest parent's poly for a t (m=22 has all six t values). Used as
 * the auto-pick fallback when a blob is larger than the largest
 * single block, so it is split into blocks of that poly. */
static const bch_poly_t *bch_poly_largest(int t)
{
    static const int t_idx[33] = {
        -1, 0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1,
        4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        5
    };
    if (t < 1 || t > 32 || t_idx[t] < 0)
        return NULL;
    return bch_poly_by_id(bch_poly_by_mt[BCH_MAX_M - BCH_MIN_M][t_idx[t]]);
}

/* Entry encode: raw file bytes -> stored bytes.
 * Fills sha_out with SHA-256 of the raw bytes. *poly_id_out /
 * *is_bch_out describe the error correction actually used, for the
 * entry header. *level_out is the level actually stored: the
 * requested level, or 0 when the entry is stored uncompressed
 * (level 0 requested, or the compressed blob was no smaller than
 * the original). BCH applies to the stored blob either way.
 * Returns 0 on success. */
int entry_encode(const uint8_t *raw, size_t raw_len, int level,
                 const ecc_opt_t *ecc,
                 uint8_t **stored, size_t *stored_len,
                 size_t *blob_len_out, uint16_t *poly_id_out,
                 int *is_bch_out, int *level_out,
                 uint8_t sha_out[32])
{
    uint8_t *comp = NULL, *blob = NULL, *ecout = NULL;
    size_t comp_len = 0, blob_len = 0, ec_len = 0;
    const bch_poly_t *poly = NULL;
    *poly_id_out = 0;
    *is_bch_out = 0;
    *level_out = level;
    lzply_sha256(raw, raw_len, sha_out);
    if (level == 0) {
        /* Explicit store: no compression at all. */
        blob = xmalloc(raw_len ? raw_len : 1);
        memcpy(blob, raw, raw_len);
        blob_len = raw_len;
        *level_out = 0;
    } else {
        if (lz_compress_mem(raw, raw_len, level, &comp, &comp_len) != 0)
            return -1;
        if (comp_len >= raw_len) {
            /* Incompressible: storing the raw bytes is no larger
             * (and for an empty file, smaller). BCH still applies
             * to the stored blob below, exactly as for compressed
             * entries. */
            free(comp);
            comp = NULL;
            blob = xmalloc(raw_len ? raw_len : 1);
            memcpy(blob, raw, raw_len);
            blob_len = raw_len;
            *level_out = 0;
        } else {
            blob = comp;
            blob_len = comp_len;
            comp = NULL;
        }
    }
    if (ecc->pinned) {
        poly = ecc->pinned;     /* pinned poly: its own t, any blob size */
    } else if (ecc->t > 0) {
        poly = bch_poly_for_data(blob_len, ecc->t);
        if (!poly)              /* blob bigger than one m=22 block: split */
            poly = bch_poly_largest(ecc->t);
        if (!poly) {
            free(blob);
            return -1;
        }
    }
    if (poly) {
        ec_len = bch_encoded_len(blob_len, poly);
        ecout = xmalloc(ec_len ? ec_len : 1);
        if (bch_encode(blob, blob_len, poly, ecout) != ec_len) {
            free(blob);
            free(ecout);
            return -1;
        }
        free(blob);
        *stored = ecout;
        *stored_len = ec_len;
        *poly_id_out = poly->id;
        *is_bch_out = 1;
    } else {
        *stored = blob;
        *stored_len = blob_len;
    }
    *blob_len_out = blob_len;
    return 0;
}

/* Entry decode: stored bytes -> raw file bytes.
 * Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
 * SHA-256 mismatch). `corrected` receives the number of bit errors
 * corrected (BCH). `is_bch` / `poly_id` come from the entry header;
 * a non-BCH entry has no error correction. A level-0 entry is stored
 * uncompressed: the blob is copied verbatim, no lzip decode.
 */
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
                 int is_bch, uint16_t poly_id,
                 const uint8_t want_sha[32], size_t blob_size,
                 uint8_t **raw, size_t *raw_len, int *corrected)
{
    uint8_t *blob = NULL, *plain = NULL, *out = NULL;
    size_t blob_len = 0, plain_len = 0, out_len = 0;
    int corr = 0;
    uint8_t sha[32];
    *corrected = 0;
    blob = xmalloc(blob_size ? blob_size : 1);
    if (is_bch) {
        const bch_poly_t *poly = bch_poly_by_id(poly_id);
        if (!poly || stored_len != bch_encoded_len(blob_size, poly)) {
            free(blob);
            return -1;
        }
        if (bch_decode(stored, stored_len, blob_size, poly, blob, &corr) != 0) {
            free(blob);
            return -1;
        }
        blob_len = blob_size;
    } else {
        /* No error correction: the stored data is the blob itself. */
        if (stored_len != blob_size) {
            free(blob);
            return -1;
        }
        memcpy(blob, stored, stored_len);
        blob_len = stored_len;
    }
    *corrected = corr;
    plain = blob;
    plain_len = blob_len;
    blob = NULL;
    if (level == 0) {
        /* Stored uncompressed: the blob is the raw file bytes. */
        out = xmalloc(plain_len ? plain_len : 1);
        memcpy(out, plain, plain_len);
        out_len = plain_len;
        free(plain);
    } else if (lz_decompress_mem(plain, plain_len, &out, &out_len) != 0) {
        free(plain);
        return -1;
    } else {
        free(plain);
    }
    lzply_sha256(out, out_len, sha);
    if (memcmp(sha, want_sha, 32) != 0) {
        free(out);
        return -1;              /* BCH miscorrection or other corruption */
    }
    *raw = out;
    *raw_len = out_len;
    return 0;
}

/* Parent directory of path (everything before the last '/'; "." if none). */
char *parent_dir(const char *path){
    const char *slash = strrchr(path, '/');
    char *r;
    if (!slash)
        return xstrdup(".");
    if (slash == path)
        return xstrdup("/");
    r = xmalloc((size_t)(slash - path) + 1);
    memcpy(r, path, (size_t)(slash - path));
    r[slash - path] = '\0';
    return r;
}


/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
 * poly id, poly_id = rs_level | (reserved << 8). For an entry with
 * no error correction both are 0. */

int write_entry_header(FILE *f, const ehdr_t *h){
    uint8_t buf[LZPLY_EHDR_SIZE];
    size_t plen = strlen(h->path);
    if (plen > 65535)
        return -1;
    memset(buf, 0, sizeof buf);
    put16le(buf + 0, (uint16_t)plen);
    buf[2] = h->level;
    buf[3] = h->rs_level;
    buf[4] = h->flags;
    buf[5] = h->reserved;
    put64le(buf + 6, h->orig_size);
    put64le(buf + 14, h->stored_size);
    put64le(buf + 22, h->blob_size);
    memcpy(buf + 30, h->sha, 32);
    put32le(buf + 62, h->mode);
    put64le(buf + 66, h->mtime);
    put32le(buf + 74, crc32_of(buf, 74));
    if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
        return -1;
    if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
        return -1;
    return 0;
}

/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
int read_entry_header(FILE *f, ehdr_t *h){
    uint8_t buf[LZPLY_EHDR_SIZE];
    uint16_t plen;
    uint32_t want_crc, got_crc;
    memset(h, 0, sizeof *h);
    if (fread(buf, 1, 2, f) != 2)
        return -1;
    plen = get16le(buf);
    if (plen == 0)
        return 1;
    if (fread(buf + 2, 1, LZPLY_EHDR_SIZE - 2, f) != LZPLY_EHDR_SIZE - 2)
        return -1;
    want_crc = get32le(buf + 74);
    put32le(buf + 74, 0);
    got_crc = crc32_of(buf, 74);
    put32le(buf + 74, want_crc);
    if (got_crc != want_crc)
        return -1;
    h->level = buf[2];
    h->rs_level = buf[3];
    h->flags = buf[4];
    h->reserved = buf[5];
    h->orig_size = get64le(buf + 6);
    h->stored_size = get64le(buf + 14);
    h->blob_size = get64le(buf + 22);
    memcpy(h->sha, buf + 30, 32);
    h->mode = get32le(buf + 62);
    h->mtime = get64le(buf + 66);
    if (h->level > 9)
        return -1;
    if (h->flags & FLAG_BCH) {
        /* rs_level is the low byte of the poly id, reserved the high
         * byte; the id must be in the embedded table. */
        uint16_t pid = (uint16_t)(h->rs_level | ((uint16_t)h->reserved << 8));
        if (!bch_poly_by_id(pid))
            return -1;
    }
    h->path = xmalloc((size_t)plen + 1);
    if (fread(h->path, 1, plen, f) != plen) {
        free(h->path);
        h->path = NULL;
        return -1;
    }
    h->path[plen] = '\0';
    /* Reject paths that would escape the destination directory. */
    if (h->path[0] == '/' || strstr(h->path, "/../") != NULL ||
        strcmp(h->path, "..") == 0 ||
        (plen >= 3 && strcmp(h->path + plen - 3, "/..") == 0)) {
        free(h->path);
        h->path = NULL;
        return -1;
    }
    return 0;
}

int read_global_header(FILE *f, uint32_t *count_out){
    uint8_t buf[LZPLY_HDR_SIZE];
    if (fread(buf, 1, sizeof buf, f) != sizeof buf)
        return -1;
    if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
        return -1;
    *count_out = get32le(buf + 6);
    return 0;
}

void write_global_header(FILE *f, uint32_t count, int version){
    uint8_t buf[LZPLY_HDR_SIZE];
    memset(buf, 0, sizeof buf);
    memcpy(buf, LZPLY_MAGIC, 4);
    buf[4] = (uint8_t)version;
    buf[5] = 0;
    put32le(buf + 6, count);
    fwrite(buf, 1, sizeof buf, f);
}

/* Does selector sel match stored path? True if sel equals path, or
 * sel (with trailing '/' stripped) is a prefix of path and the next
 * character after the prefix is '/'. A selector that is only slashes
 * matches everything. So "photos" matches "photos/a.jpg" and the
 * "photos/" dir entry, but not "photos2/a.jpg"; "photos/" matches
 * everything under photos/. */
int selector_matches(const char *sel, const char *path){
    size_t n = strlen(sel);
    while (n > 0 && sel[n - 1] == '/')
        n--;
    if (n == 0)
        return 1;
    if (strncmp(path, sel, n) != 0)
        return 0;
    return path[n] == '\0' || path[n] == '/';
}

int path_matches_selectors(const char *path,                                  const char **sels, int nsels)
{
    int i;
    if (nsels == 0)
        return 1;
    for (i = 0; i < nsels; i++)
        if (selector_matches(sels[i], path))
            return 1;
    return 0;
}


int date_filter_active(const date_filter_t *f){
    return f && (f->start >= 0 || f->end >= 0 || f->year != 0);
}

/* Does an entry with this mtime pass the filter? */
int date_filter_matches(const date_filter_t *f, uint64_t mtime){
    if (!f)
        return 1;
    if (f->start >= 0 && (int64_t)mtime < f->start)
        return 0;
    if (f->end >= 0 && (int64_t)mtime > f->end)
        return 0;
    if (f->year != 0) {
        time_t t = (time_t)mtime;
        struct tm tmv;
        if (!gmtime_r(&t, &tmv))
            return 0;
        if (tmv.tm_year + 1900 != f->year)
            return 0;
    }
    return 1;
}

/* Parse a date: "YYYY-MM-DD" (midnight at the start of that day, or
 * 23:59:59 at the end of it when is_end is set) or
 * "YYYY-MM-DDTHH:MM:SS" (exact; a space may replace the 'T').
 * Returns 0 on success, -1 on a bad format or an impossible date.
 * All times are UTC. */
int parse_date(const char *s, int is_end, int64_t *out){
    struct tm tmv;
    time_t t;
    struct tm check;
    int y, mo, d, hh = 0, mm = 0, ss = 0;
    size_t n = strlen(s);
    int i;
    if (n != 10 && n != 19)
        return -1;
    for (i = 0; i < 10; i++) {
        if (i == 4 || i == 7) {
            if (s[i] != '-')
                return -1;
        } else if (s[i] < '0' || s[i] > '9') {
            return -1;
        }
    }
    if (n == 19) {
        if (s[10] != 'T' && s[10] != ' ')
            return -1;
        if (s[13] != ':' || s[16] != ':')
            return -1;
        for (i = 11; i < 19; i++) {
            if (i == 13 || i == 16)
                continue;
            if (s[i] < '0' || s[i] > '9')
                return -1;
        }
    }
    y = atoi(s);
    mo = atoi(s + 5);
    d = atoi(s + 8);
    if (n == 19) {
        hh = atoi(s + 11);
        mm = atoi(s + 14);
        ss = atoi(s + 17);
    }
    if (y < 1970 || y > 9999 || mo < 1 || mo > 12 || d < 1 || d > 31 ||
        hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 59)
        return -1;
    memset(&tmv, 0, sizeof tmv);
    tmv.tm_year = y - 1900;
    tmv.tm_mon = mo - 1;
    tmv.tm_mday = d;
    tmv.tm_hour = hh;
    tmv.tm_min = mm;
    tmv.tm_sec = ss;
    t = timegm(&tmv);
    if (t == (time_t)-1)
        return -1;
    /* Reject impossible dates (e.g. Feb 30): timegm normalises them
     * (and may normalise tmv in place), so round-trip through gmtime
     * and compare against the parsed values, not tmv. */
    if (!gmtime_r(&t, &check))
        return -1;
    if (check.tm_year != y - 1900 || check.tm_mon != mo - 1 ||
        check.tm_mday != d || check.tm_hour != hh ||
        check.tm_min != mm || check.tm_sec != ss)
        return -1;
    if (n == 10 && is_end)
        t += 86399;             /* through 23:59:59 of that date */
    *out = (int64_t)t;
    return 0;
}

/* Format an mtime as "YYYY-MM-DD HH:MM:SS UTC" into buf. */
void fmt_mtime(uint64_t mtime, char *buf, size_t bufsz){
    time_t t = (time_t)mtime;
    struct tm tmv;
    if (!gmtime_r(&t, &tmv)) {
        snprintf(buf, bufsz, "-");
        return;
    }
    strftime(buf, bufsz, "%Y-%m-%d %H:%M:%S UTC", &tmv);
}

/* Format permissions as a 10-character string, e.g. "drwxr-xr-x"
 * or "-rw-r--r--". The stored mode holds only the low 12 bits, so
 * the type letter comes from is_dir. */
void fmt_perm(int is_dir, uint32_t mode, char *buf){
    static const char *rwx = "rwxrwxrwx";
    int i;
    buf[0] = is_dir ? 'd' : '-';
    for (i = 0; i < 9; i++)
        buf[1 + i] = (mode & (1u << (8 - i))) ? rwx[i] : '-';
    buf[10] = '\0';
}



void scan_list_free(scan_list_t *l){
    size_t i;
    for (i = 0; i < l->len; i++)
        free(l->v[i].path);
    free(l->v);
    l->v = NULL;
    l->len = l->cap = 0;
}

/* Read the 16-byte global header, returning version and count.
 * Returns 0 on success, -1 if the file is not an lzply archive. */
int read_global_header_full(FILE *f, int *version_out,                                   uint32_t *count_out)
{
    uint8_t buf[LZPLY_HDR_SIZE];
    if (fread(buf, 1, sizeof buf, f) != sizeof buf)
        return -1;
    if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
        return -1;
    *version_out = buf[4];
    *count_out = get32le(buf + 6);
    return 0;
}

/* Scan an archive and record every entry. Returns 0 on success.
 * On success *end_off_out is the file offset of the 2-byte end
 * marker (which must be the last 2 bytes of the file), and the
 * scanned entry count is in *nentries_out (the header's stored
 * count is returned in *count_out but the scanned count is the
 * ground truth). Returns -1 (with a message) if the file is not a
 * valid archive, an entry header is corrupt, or there are trailing
 * bytes after the end marker. */
int scan_archive(const char *path, int *version_out,                        uint32_t *count_out, off_t *size_out,
                        scan_list_t *entries, off_t *end_off_out)
{
    struct stat st;
    FILE *f = fopen(path, "rb");
    off_t end_off;
    if (!f) {
        fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname, path,
                strerror(errno));
        return -1;
    }
    if (fstat(fileno(f), &st) != 0) {
        fclose(f);
        return -1;
    }
    if (read_global_header_full(f, version_out, count_out) != 0) {
        fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
                lzply_progname, path);
        fclose(f);
        return -1;
    }
    memset(entries, 0, sizeof *entries);
    for (;;) {
        off_t off = ftello(f);
        ehdr_t h;
        int r = read_entry_header(f, &h);
        if (r == 1) {           /* end marker */
            end_off = off;
            break;
        }
        if (r < 0) {
            fprintf(stderr, "%s: %s is truncated or has a corrupt entry header\n",
                    lzply_progname, path);
            scan_list_free(entries);
            fclose(f);
            return -1;
        }
        if (entries->len == entries->cap) {
            entries->cap = entries->cap ? entries->cap * 2 : 64;
            entries->v = xrealloc(entries->v,
                                  entries->cap * sizeof(scan_entry_t));
        }
        entries->v[entries->len].path = h.path;   /* take ownership */
        entries->v[entries->len].offset = off;
        entries->v[entries->len].total_len =
            LZPLY_EHDR_SIZE + (uint64_t)strlen(h.path) + h.stored_size;
        entries->v[entries->len].is_dir = (h.flags & FLAG_ISDIR) != 0;
        entries->len++;
        if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
            fprintf(stderr, "%s: %s is truncated\n", lzply_progname, path);
            scan_list_free(entries);
            fclose(f);
            return -1;
        }
    }
    if (end_off != (off_t)st.st_size - 2 || ftello(f) != st.st_size) {
        fprintf(stderr, "%s: %s has trailing bytes after the end marker\n",
                lzply_progname, path);
        scan_list_free(entries);
        fclose(f);
        return -1;
    }
    *size_out = st.st_size;
    *end_off_out = end_off;
    fclose(f);
    return 0;
}

/* Copy n bytes from src (positioned at the start) to dst, streaming.
 * Returns 0 on success, -1 on a short read/write. */
int copy_bytes(FILE *src, FILE *dst, uint64_t n){
    uint8_t buf[65536];
    while (n > 0) {
        size_t want = n > sizeof buf ? sizeof buf : (size_t)n;
        size_t got = fread(buf, 1, want, src);
        if (got == 0)
            return -1;
        if (fwrite(buf, 1, got, dst) != got)
            return -1;
        n -= got;
    }
    return 0;
}

/* Create a temp file in the same directory as path (so rename() can
 * replace path atomically), returning the FILE* and the temp pathname
 * in *tmp_out (caller frees it). Returns NULL on failure. */
FILE *temp_in_same_dir(const char *path, char **tmp_out){
    char *dir = parent_dir(path);
    char *tmpl = xmalloc(strlen(dir) + 20);
    int fd;
    FILE *f;
    sprintf(tmpl, "%s/.lzply-tmp-XXXXXX", dir);
    free(dir);
    fd = mkstemp(tmpl);
    if (fd < 0) {
        fprintf(stderr, "%s: cannot create temp file %s: %s\n",
                lzply_progname, tmpl, strerror(errno));
        free(tmpl);
        return NULL;
    }
    f = fdopen(fd, "w+b");
    if (!f) {
        close(fd);
        unlink(tmpl);
        free(tmpl);
        return NULL;
    }
    *tmp_out = tmpl;
    return f;
}

lzply_lib.h

Shared core header — the entry encode/decode, header I/O, and scan API the FUSE layer, stat, heal, check and refresh use

/* lzply_lib.h - shared core of the lzply archiver and lzply_mount.
 *
 * Everything both programs need: the v4 archive format, the per-entry
 * pipeline (lzip compress -> BCH encode, and the reverse), the header
 * I/O, the archive scan, and the date / selector filters. The
 * command-line tool (lzply.c) and the FUSE filesystem (lzply_mount.c)
 * both link lzply_lib.c. There is no legacy support: v4 is the only
 * format. (v3 archives are rejected outright; the format changed
 * in v4.)
 *
 * Archive format v4 (all integers little-endian):
 *   global header (16 bytes):
 *     magic "LZPL", version u8 (=4), flags u8, entry_count u32,
 *     reserved u64
 *   entries, each:
 *     u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
 *     u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
 *     u32 mode, u64 mtime, u32 header_crc32,
 *     path[path_len], data[stored_size]
 *     (header_crc32 covers the 74 bytes before it; blob_size is the
 *     length of the compressed stream before error-correction parity
 *     was added; mtime is the source file's modification time,
 *     seconds since the epoch, UTC)
 *   end marker: u16 path_len == 0
 * Level is the lzip level (1..9) of the blob, or 0 for a stored
 * (uncompressed) entry: when the compressed blob would be no smaller
 * than the original (already-compressed data, random data, empty
 * files), or when -0 forces it, the raw bytes are stored instead and
 * BCH still applies to them exactly as before.
 * Flags: bit 0 is unused (it was used by v3), bit 1 =
 * directory, bit 2 = BCH mode. Bit 0 is deliberately not renumbered.
 * For a BCH entry, poly_id = rs_level | (reserved << 8).
 */
#ifndef LZPLY_LIB_H
#define LZPLY_LIB_H

#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

#include "bch.h"
#include "sha256.h"

#define LZPLY_MAGIC "LZPL"
#define LZPLY_VERSION 4          /* the only format version */
#define LZPLY_HDR_SIZE 16
#define LZPLY_EHDR_SIZE 78
#define LZPLY_END_MARKER 0

#define FLAG_ISDIR 0x02
#define FLAG_BCH 0x04           /* entry uses BCH; poly_id in rs_level+reserved */

#define EXIT_USAGE 1
#define EXIT_IO 2
#define EXIT_CORRUPT 3

/* Program name used in error messages (default "lzply").
 * lzply_mount sets it to "lzply_mount" at startup. */
extern const char *lzply_progname;
void lzply_set_progname(const char *name);

/* ------------------------------------------------------------------ */
/* Small utilities                                                     */
/* ------------------------------------------------------------------ */

/* These die (exit) on allocation failure, like the original lzply. */
void *xmalloc(size_t n);
void *xrealloc(void *p, size_t n);
char *xstrdup(const char *s);

/* Growable byte buffer. */
typedef struct {
    uint8_t *data;
    size_t len, cap;
} buf_t;

void buf_init(buf_t *b);
void buf_free(buf_t *b);
void buf_append(buf_t *b, const void *p, size_t n);

/* Little-endian integer access (archive format is LE). */
void put16le(uint8_t *p, uint16_t v);
void put32le(uint8_t *p, uint32_t v);
void put64le(uint8_t *p, uint64_t v);
uint16_t get16le(const uint8_t *p);
uint32_t get32le(const uint8_t *p);
uint64_t get64le(const uint8_t *p);

/* CRC-32 (IEEE, polynomial 0xEDB88320). */
void crc32_init(void);
uint32_t crc32_of(const uint8_t *p, size_t n);

/* Parent directory of path (everything before the last '/'; "." if
 * none). */
char *parent_dir(const char *path);

/* ------------------------------------------------------------------ */
/* lzip (liblz) in-memory compression                                  */
/* ------------------------------------------------------------------ */

int lz_compress_mem(const uint8_t *in, size_t in_len, int level,
                    uint8_t **out, size_t *out_len);
int lz_decompress_mem(const uint8_t *in, size_t in_len,
                      uint8_t **out, size_t *out_len);

/* ------------------------------------------------------------------ */
/* Per-entry encode / decode                                           */
/* ------------------------------------------------------------------ */

/* Error-correction options for one -c invocation. t is the BCH
 * correction level for auto-pick (0 = no ECC); pinned overrides t. */
typedef struct {
    int t;
    const bch_poly_t *pinned;
} ecc_opt_t;

/* Entry encode: raw file bytes -> stored bytes.
 * Fills sha_out with SHA-256 of the raw bytes. *poly_id_out /
 * *is_bch_out describe the error correction actually used, for the
 * entry header. *level_out is the level actually stored: the
 * requested level, or 0 when the entry is stored uncompressed
 * (level 0 requested, or the compressed blob was no smaller than
 * the original). BCH applies to the stored blob either way.
 * Returns 0 on success. */
int entry_encode(const uint8_t *raw, size_t raw_len, int level,
                 const ecc_opt_t *ecc,
                 uint8_t **stored, size_t *stored_len,
                 size_t *blob_len_out, uint16_t *poly_id_out,
                 int *is_bch_out, int *level_out,
                 uint8_t sha_out[32]);

/* Entry decode: stored bytes -> raw file bytes.
 * Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
 * SHA-256 mismatch). `corrected` receives the number of bit errors
 * corrected (BCH). `is_bch` / `poly_id` come from the entry header;
 * a non-BCH entry has no error correction. A level-0 entry is stored
 * uncompressed: the blob is copied verbatim, no lzip decode. */
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
                 int is_bch, uint16_t poly_id,
                 const uint8_t want_sha[32], size_t blob_size,
                 uint8_t **raw, size_t *raw_len, int *corrected);

/* ------------------------------------------------------------------ */
/* Archive header I/O                                                  */
/* ------------------------------------------------------------------ */

typedef struct {
    char *path;
    uint8_t level, rs_level, flags, reserved;
    uint64_t orig_size, stored_size, blob_size;
    uint8_t sha[32];
    uint32_t mode;
    uint64_t mtime;             /* source mtime, seconds since epoch (UTC) */
} ehdr_t;
/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
 * poly id, poly_id = rs_level | (reserved << 8). For an entry with
 * no error correction both are 0. */

int write_entry_header(FILE *f, const ehdr_t *h);
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
int read_entry_header(FILE *f, ehdr_t *h);
int read_global_header(FILE *f, uint32_t *count_out);
void write_global_header(FILE *f, uint32_t count, int version);
/* Read the 16-byte global header, returning version and count.
 * Returns 0 on success, -1 if the file is not an lzply archive. */
int read_global_header_full(FILE *f, int *version_out,
                            uint32_t *count_out);

/* ------------------------------------------------------------------ */
/* Selectors (for -d / -t / -l)                                        */
/* ------------------------------------------------------------------ */

/* Does selector sel match stored path? True if sel equals path, or
 * sel (with trailing '/' stripped) is a prefix of path and the next
 * character after the prefix is '/'. A selector that is only slashes
 * matches everything. */
int selector_matches(const char *sel, const char *path);
int path_matches_selectors(const char *path,
                           const char **sels, int nsels);

/* ------------------------------------------------------------------ */
/* Date filters (-datestart / -dateend / -year)                        */
/* ------------------------------------------------------------------ */

/* A date filter: an entry matches only if its mtime is in range and
 * (when given) in the given year. Unset bounds are -1 (start/end)
 * and 0 (year). All bounds are UTC, seconds since the epoch. */
typedef struct {
    int64_t start;              /* -1: no lower bound */
    int64_t end;                /* -1: no upper bound (inclusive) */
    int year;                   /* 0: no year filter */
} date_filter_t;

int date_filter_active(const date_filter_t *f);
/* Does an entry with this mtime pass the filter? */
int date_filter_matches(const date_filter_t *f, uint64_t mtime);
/* Parse a date: "YYYY-MM-DD" (midnight at the start of that day, or
 * 23:59:59 at the end of it when is_end is set) or
 * "YYYY-MM-DDTHH:MM:SS" (exact; a space may replace the 'T').
 * Returns 0 on success, -1 on a bad format or an impossible date.
 * All times are UTC. */
int parse_date(const char *s, int is_end, int64_t *out);

/* Format an mtime as "YYYY-MM-DD HH:MM:SS UTC" into buf. */
void fmt_mtime(uint64_t mtime, char *buf, size_t bufsz);
/* Format permissions as a 10-character string, e.g. "drwxr-xr-x"
 * or "-rw-r--r--". The stored mode holds only the low 12 bits, so
 * the type letter comes from is_dir. */
void fmt_perm(int is_dir, uint32_t mode, char *buf);

/* ------------------------------------------------------------------ */
/* Archive scan                                                        */
/* ------------------------------------------------------------------ */

/* One entry found by scanning an archive: its stored path, its file
 * offset (start of the 78-byte header), and its total on-disk length
 * (78 + path_len + stored_size). */
typedef struct {
    char *path;
    off_t offset;
    uint64_t total_len;
    int is_dir;
} scan_entry_t;

typedef struct {
    scan_entry_t *v;
    size_t len, cap;
} scan_list_t;

void scan_list_free(scan_list_t *l);

/* Scan an archive and record every entry. Returns 0 on success.
 * On success *end_off_out is the file offset of the 2-byte end
 * marker (which must be the last 2 bytes of the file), and the
 * scanned entry count is in *nentries_out (the header's stored
 * count is returned in *count_out but the scanned count is the
 * ground truth). Returns -1 (with a message) if the file is not a
 * valid archive, an entry header is corrupt, or there are trailing
 * bytes after the end marker. */
int scan_archive(const char *path, int *version_out,
                 uint32_t *count_out, off_t *size_out,
                 scan_list_t *entries, off_t *end_off_out);

/* Copy n bytes from src (positioned at the start) to dst, streaming.
 * Returns 0 on success, -1 on a short read/write. */
int copy_bytes(FILE *src, FILE *dst, uint64_t n);

/* Create a temp file in the same directory as path (so rename() can
 * replace path atomically), returning the FILE* and the temp pathname
 * in *tmp_out (caller frees it). Returns NULL on failure. */
FILE *temp_in_same_dir(const char *path, char **tmp_out);

#endif /* LZPLY_LIB_H */

lzply_mount.c

The FUSE filesystem — mount a .lzply archive as a writable directory: getattr/readdir, decode-on-open with a bounded cache, in-memory writes, repack on unmount, flock against double-mounts

/* lzply_mount.c - mount an .lzply archive as a writable filesystem (FUSE).
 *
 *   lzply_mount [options] <archive.lzply> <mountpoint>
 *
 * At mount the archive's entry headers are scanned once (like `lzply -i`)
 * into an in-memory index; directories are reconstructed from the stored
 * paths (like `lzply -tr`). File contents are decoded on demand
 * (decode-on-open, cached). Writes go to an in-memory working copy and
 * are written back by repacking the archive on clean unmount:
 * unmodified entries are copied verbatim, modified/new entries are
 * encoded fresh. A killed daemon loses unflushed changes but never
 * corrupts the on-disk archive (the repack is temp-file + rename).
 *
 * Single-threaded (FUSE -s): all operations run on one thread, so no
 * locking is needed.
 *
 * There is no legacy support: v4 is the only archive format.
 *
 * Build stages (one FUSE command at a time):
 *   v0.1 browse: getattr, readdir            (this file, stage 1)
 *   v0.2 read:   open, read, release         (stage 2)
 *   v0.3 write:  write, truncate, flush, fsync (stage 3)
 *   v0.4 create/delete: create, mknod, mkdir, rmdir, unlink (stage 4)
 *   v0.5 rename                              (stage 5)
 *   v0.6 metadata: chmod, chown, utimens     (stage 6)
 *   v0.7 mount.lzply helper + polish          (stage 7)
 */
#define FUSE_USE_VERSION 31
#define _FILE_OFFSET_BITS 64

#include <errno.h>
#include <fcntl.h>
#include <fuse3/fuse.h>
#include <getopt.h>
#include <limits.h>
#include "sha256.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

#include "lzply_lib.h"
#include "bch.h"

/* renameat2 flags (linux/fs.h); defined here so lzply_mount does not need
 * that header. */
#ifndef RENAME_NOREPLACE
#define RENAME_NOREPLACE (1 << 0)
#endif
#ifndef RENAME_EXCHANGE
#define RENAME_EXCHANGE (1 << 1)
#endif

/* ------------------------------------------------------------------ */
/* In-memory filesystem state                                          */
/* ------------------------------------------------------------------ */

typedef struct fs_node {
    char *path;                 /* archive-relative, no leading/trailing
                                 * slash; "" is the root */
    uint32_t mode;              /* permission bits (low 12 bits) */
    uint64_t mtime;             /* seconds since epoch (UTC) */
    int is_dir;
    int is_implied;             /* synthesized dir, no archive entry */
    /* On-disk entry (valid when has_entry, i.e. the node came from the
     * archive and has not been replaced). */
    int has_entry;
    ehdr_t hdr;                 /* full entry header from the archive */
    off_t data_off;             /* offset of the stored data in the archive */
    /* Content (stages 2+): decoded file bytes, or the working copy for
     * a file being written. */
    uint8_t *content;
    size_t content_len;
    int content_loaded;         /* content holds the current file data */
    int dirty;                  /* content differs from the on-disk entry */
    int meta_dirty;             /* mode/mtime differ (header-only change) */
    int is_new;                 /* created in this session, no on-disk entry */
    int deleted;                /* removed in this session, pending repack */
    uint64_t ino;
    uint64_t load_seq;          /* load order (read-cache eviction) */
} fs_node_t;

typedef struct {
    char *archive_path;
    int level;                  /* compression level for re-encoding */
    ecc_opt_t ecc;              /* BCH options for re-encoding */
    FILE *archive;              /* open FILE* to the archive (read) */
    fs_node_t *nodes;
    size_t nnodes, cap;
    uint64_t next_ino;
    int dirty;                  /* any change pending repack */
    size_t cache_bytes;         /* bytes held in decoded content buffers */
    size_t cache_cap;           /* soft cap for the read cache (256 MiB) */
    uint64_t load_clock;        /* monotonically increasing load sequence */
} lzply_mount_state_t;

/* ------------------------------------------------------------------ */
/* Node table                                                          */
/* ------------------------------------------------------------------ */

static fs_node_t *node_find(lzply_mount_state_t *st, const char *path)
{
    size_t i;
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *n = &st->nodes[i];
        if (!n->deleted && strcmp(n->path, path) == 0)
            return n;
    }
    return NULL;
}

/* Current size of a file node: the working content when loaded,
 * otherwise the archived original size. */
static uint64_t node_size(fs_node_t *n)
{
    if (n->content_loaded)
        return (uint64_t)n->content_len;
    return n->hdr.orig_size;
}

static fs_node_t *node_add(lzply_mount_state_t *st, const char *path,
                           uint32_t mode, uint64_t mtime, int is_dir)
{
    fs_node_t *n;
    if (st->nnodes == st->cap) {
        st->cap = st->cap ? st->cap * 2 : 64;
        st->nodes = xrealloc(st->nodes, st->cap * sizeof *st->nodes);
    }
    n = &st->nodes[st->nnodes++];
    memset(n, 0, sizeof *n);
    n->path = xstrdup(path);
    n->mode = mode & 07777;
    n->mtime = mtime;
    n->is_dir = is_dir;
    n->ino = st->next_ino++;
    return n;
}

/* True if node_path is an immediate child of dir_path ("" = root). */
static int is_child_of(const char *node_path, const char *dir_path)
{
    char *p = parent_dir(node_path);
    int r;
    if (dir_path[0] == '\0')
        r = (strcmp(p, ".") == 0);
    else
        r = (strcmp(p, dir_path) == 0);
    free(p);
    return r;
}

/* Basename of an archive-relative path. */
static const char *base_name(const char *path)
{
    const char *s = strrchr(path, '/');
    return s ? s + 1 : path;
}

/* Ensure implied directory nodes exist for every parent of path.
 * Implied dirs get mode 0755 and the child's mtime. */
static void ensure_implied_dirs(lzply_mount_state_t *st, const char *path,
                                uint64_t mtime)
{
    char *tmp = xstrdup(path);
    char *slash = tmp;
    while ((slash = strchr(slash, '/')) != NULL) {
        *slash = '\0';
        if (tmp[0] != '\0' && node_find(st, tmp) == NULL)
            node_add(st, tmp, 0755, mtime, 1)->is_implied = 1;
        *slash = '/';
        slash++;
    }
    free(tmp);
}

/* Number of immediate subdirectories of dir (for st_nlink). */
static int count_subdirs(lzply_mount_state_t *st, const char *dir_path)
{
    size_t i;
    int n = 0;
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *c = &st->nodes[i];
        if (c->deleted || strcmp(c->path, dir_path) == 0)
            continue;
        if (c->is_dir && is_child_of(c->path, dir_path))
            n++;
    }
    return n;
}

/* Take the exclusive non-blocking mount lock on the open archive
 * FILE*. Two daemons on the same archive would build from the same
 * snapshot and the second one's repack would silently discard the
 * first one's changes, so a second mount is refused. The lock is
 * held for the daemon's lifetime and released by the kernel even on
 * kill -9. Returns 0 on success, -1 on failure (errno is set). */
static int lock_archive_file(FILE *f)
{
    return flock(fileno(f), LOCK_EX | LOCK_NB);
}

/* ------------------------------------------------------------------ */
/* Index build (mount)                                                 */
/* ------------------------------------------------------------------ */

static int build_index(lzply_mount_state_t *st)
{
    scan_list_t scan = {0};
    int version;
    uint32_t count;
    off_t size, end_off;
    size_t i;

    if (scan_archive(st->archive_path, &version, &count, &size,
                     &scan, &end_off) != 0) {
        fprintf(stderr, "lzply_mount: %s: not a valid lzply archive\n",
                st->archive_path);
        return -1;
    }
    st->archive = fopen(st->archive_path, "rb");
    if (!st->archive) {
        fprintf(stderr, "lzply_mount: %s: %s\n", st->archive_path,
                strerror(errno));
        scan_list_free(&scan);
        return -1;
    }
    if (lock_archive_file(st->archive) != 0) {
        if (errno == EWOULDBLOCK)
            fprintf(stderr, "lzply_mount: %s: already mounted by another lzply_mount\n",
                    st->archive_path);
        else
            fprintf(stderr, "lzply_mount: %s: cannot lock: %s\n",
                    st->archive_path, strerror(errno));
        fclose(st->archive);
        st->archive = NULL;
        scan_list_free(&scan);
        return -1;
    }
    st->next_ino = 1;
    node_add(st, "", 0755, (uint64_t)time(NULL), 1);

    for (i = 0; i < scan.len; i++) {
        scan_entry_t *e = &scan.v[i];
        ehdr_t h;
        char *rel;
        size_t len;
        off_t data_off;
        fs_node_t *n;

        if (fseeko(st->archive, e->offset, SEEK_SET) != 0 ||
            read_entry_header(st->archive, &h) != 0) {
            fprintf(stderr, "lzply_mount: %s: corrupt entry header at %lld\n",
                    st->archive_path, (long long)e->offset);
            scan_list_free(&scan);
            return -1;
        }
        rel = xstrdup(h.path);
        len = strlen(rel);
        if (len > 0 && rel[len - 1] == '/')
            rel[len - 1] = '\0';
        ensure_implied_dirs(st, rel, h.mtime);
        data_off = e->offset + LZPLY_EHDR_SIZE + (off_t)strlen(h.path);

        n = node_find(st, rel);
        if (n != NULL) {
            if (!n->is_implied || !n->is_dir || !(h.flags & FLAG_ISDIR)) {
                fprintf(stderr,
                        "lzply_mount: %s: duplicate entry for path '%s'\n",
                        st->archive_path, rel);
                free(h.path);
                free(rel);
                scan_list_free(&scan);
                return -1;
            }
            /* An implied dir turns out to have a real entry: upgrade it. */
            n->is_implied = 0;
        } else {
            n = node_add(st, rel, h.mode, h.mtime,
                         (h.flags & FLAG_ISDIR) != 0);
        }
        n->has_entry = 1;
        n->hdr = h;
        n->hdr.path = NULL;     /* hdr.path is never owned here; the
                                 * node's path is n->path (see free_state) */
        n->data_off = data_off;
        n->mode = h.mode & 07777;
        n->mtime = h.mtime;
        free(h.path);
        free(rel);
    }
    scan_list_free(&scan);
    return 0;
}

static void free_state(lzply_mount_state_t *st)
{
    size_t i;
    if (!st)
        return;
    for (i = 0; i < st->nnodes; i++) {
        free(st->nodes[i].path);
        free(st->nodes[i].content);
        free(st->nodes[i].hdr.path);
    }
    free(st->nodes);
    if (st->archive)
        fclose(st->archive);
    free(st->archive_path);
    free(st);
}

/* ------------------------------------------------------------------ */
/* FUSE helpers                                                        */
/* ------------------------------------------------------------------ */

static lzply_mount_state_t *fs_state(void)
{
    return (lzply_mount_state_t *)fuse_get_context()->private_data;
}

/* Archive-relative path for a FUSE path ("/photos/a.txt" -> "photos/a.txt"). */
static const char *rel_path(const char *path)
{
    return path[0] == '/' ? path + 1 : path;
}

static void fill_stat(lzply_mount_state_t *st, fs_node_t *n, struct stat *sb)
{
    memset(sb, 0, sizeof *sb);
    /* st_ino is deliberately 0: libfuse's high-level API manages inode
     * numbers itself (it assigns nodeids in first-access order), and
     * it only honours the st_ino passed to the readdir filler, not the
     * one from getattr. Supplying our own numbers makes the same file
     * show two different inodes depending on whether stat or ls found
     * it first, and can collide with libfuse's lookup-assigned ids.
     * With st_ino 0 libfuse assigns nodeids consistently in both
     * paths; the kernel shows those (unique and stable within a
     * mount). n->ino stays as an internal id only. */
    sb->st_ino = 0;
    sb->st_mode = (n->is_dir ? S_IFDIR : S_IFREG) | (n->mode & 07777);
    sb->st_nlink = n->is_dir ? 2 + count_subdirs(st, n->path) : 1;
    sb->st_uid = getuid();
    sb->st_gid = getgid();
    sb->st_size = n->is_dir ? 4096 : (off_t)node_size(n);
    sb->st_blksize = 4096;
    sb->st_blocks = n->is_dir ? 0 : ((off_t)node_size(n) + 511) / 512;
    sb->st_mtime = sb->st_atime = sb->st_ctime = (time_t)n->mtime;
}

/* ------------------------------------------------------------------ */
/* Content decode + bounded read cache (stage 2)                       */
/* ------------------------------------------------------------------ */

/* Free the decoded content of clean (non-dirty) nodes, oldest first,
 * until cache_bytes + need <= cache_cap (or nothing clean is left).
 * A single entry larger than the cap still loads (a file must be
 * readable); the cap is a soft target. Dirty nodes are never evicted:
 * their content is the only copy of unflushed changes. */
static void cache_evict(lzply_mount_state_t *st, size_t need, fs_node_t *except)
{
    while (st->cache_bytes + need > st->cache_cap) {
        fs_node_t *victim = NULL;
        size_t i;
        for (i = 0; i < st->nnodes; i++) {
            fs_node_t *n = &st->nodes[i];
            if (n == except || !n->content_loaded || n->dirty || n->is_dir)
                continue;
            if (!victim || n->load_seq < victim->load_seq)
                victim = n;
        }
        if (!victim)
            break;
        st->cache_bytes -= victim->content_len;
        free(victim->content);
        victim->content = NULL;
        victim->content_len = 0;
        victim->content_loaded = 0;
    }
}

/* Decode a file node's entry into its content buffer (decode-on-open).
 * Returns 0 on success, -EIO on corruption (BCH uncorrectable, lzip
 * error, SHA-256 mismatch). */
static int load_content(lzply_mount_state_t *st, fs_node_t *n)
{
    uint8_t *stored = NULL, *raw = NULL;
    size_t raw_len = 0;
    int corrected = 0, rc, is_bch;
    uint16_t poly_id;

    if (n->content_loaded)
        return 0;
    if (!n->has_entry) {
        /* A file created in this session (stage 4+): its content is
         * the working buffer, initialised at creation. */
        return 0;
    }
    stored = xmalloc(n->hdr.stored_size ? (size_t)n->hdr.stored_size : 1);
    if (fseeko(st->archive, n->data_off, SEEK_SET) != 0 ||
        fread(stored, 1, (size_t)n->hdr.stored_size, st->archive) !=
            (size_t)n->hdr.stored_size) {
        free(stored);
        return -EIO;
    }
    is_bch = (n->hdr.flags & FLAG_BCH) != 0;
    poly_id = (uint16_t)(n->hdr.rs_level | ((uint16_t)n->hdr.reserved << 8));
    rc = entry_decode(stored, (size_t)n->hdr.stored_size, n->hdr.level,
                      is_bch, poly_id, n->hdr.sha,
                      (size_t)n->hdr.blob_size, &raw, &raw_len, &corrected);
    free(stored);
    if (rc != 0)
        return -EIO;            /* corrupt: BCH uncorrectable / SHA mismatch */
    if (raw_len != n->hdr.orig_size) {
        /* Should not happen (SHA-256 already verified), but be safe. */
        free(raw);
        return -EIO;
    }
    cache_evict(st, raw_len, n);
    n->content = raw;
    n->content_len = raw_len;
    n->content_loaded = 1;
    n->load_seq = ++st->load_clock;
    st->cache_bytes += raw_len;
    return 0;
}

/* ------------------------------------------------------------------ */
/* FUSE operations — stage 1: getattr, readdir (+ open/read stub)      */
/* ------------------------------------------------------------------ */

static int lzply_mount_getattr(const char *path, struct stat *sb,
                          struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n;
    (void)fi;
    n = node_find(st, rel_path(path));
    if (!n)
        return -ENOENT;
    fill_stat(st, n, sb);
    return 0;
}

static int lzply_mount_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
                          off_t offset, struct fuse_file_info *fi,
                          enum fuse_readdir_flags flags)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *dir;
    size_t i;
    (void)offset;
    (void)fi;
    (void)flags;

    dir = node_find(st, rel);
    if (!dir)
        return -ENOENT;
    if (!dir->is_dir)
        return -ENOTDIR;

    filler(buf, ".", NULL, 0, 0);
    filler(buf, "..", NULL, 0, 0);
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *c = &st->nodes[i];
        struct stat sb;
        if (c->deleted || c == dir)
            continue;
        if (!is_child_of(c->path, rel))
            continue;
        fill_stat(st, c, &sb);
        filler(buf, base_name(c->path), &sb, 0, 0);
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* Repack (stage 3): write the in-memory state as a new archive        */
/* ------------------------------------------------------------------ */

/* Write the current in-memory state as a new archive, replacing the
 * old one. Unmodified entries are copied verbatim; modified/new
 * entries are encoded fresh. Directories
 * are written as dir entries; implied dirs get no entry. On success
 * the archive FILE* is reopened on the new file, every node's
 * data_off/hdr is updated, dirty flags are cleared, and st->dirty
 * is 0. Returns 0 on success, -1 on failure (the original archive
 * is left untouched, and the in-memory state is unmodified — new
 * offsets/headers are staged in side arrays and applied only after
 * the rename succeeds). */
static int repack_archive(lzply_mount_state_t *st)
{
    FILE *out = NULL;
    char *tmp = NULL;
    uint32_t count = 0;
    size_t i;
    off_t *new_off = NULL;
    ehdr_t *new_hdr = NULL;
    uint8_t *written = NULL;
    int rc = -1;

    new_off = xmalloc(st->nnodes * sizeof(off_t));
    new_hdr = xmalloc(st->nnodes * sizeof(ehdr_t));
    written = xmalloc(st->nnodes ? st->nnodes : 1);
    memset(written, 0, st->nnodes);
    memset(new_hdr, 0, st->nnodes * sizeof(ehdr_t));

    out = temp_in_same_dir(st->archive_path, &tmp);
    if (!out) {
        fprintf(stderr, "lzply_mount: cannot create temp file for repack: %s\n",
                strerror(errno));
        goto out;
    }
    write_global_header(out, 0, LZPLY_VERSION);
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *n = &st->nodes[i];
        ehdr_t h;
        off_t entry_off;
        if (n->deleted || n->path[0] == '\0')
            continue;   /* deleted, or the synthetic mount root */
        if (n->is_dir) {
            char *dpath;
            if (!n->has_entry && n->is_implied)
                continue;   /* implied dirs get no entry */
            dpath = xmalloc(strlen(n->path) + 2);
            sprintf(dpath, "%s/", n->path);
            memset(&h, 0, sizeof h);
            h.path = dpath;
            h.level = (uint8_t)st->level;
            h.mode = n->mode;
            h.mtime = n->mtime;
            h.flags = FLAG_ISDIR;
            h.orig_size = 0;
            h.stored_size = 0;
            h.blob_size = 0;
            lzply_sha256((const uint8_t *)"", 0, h.sha);
            entry_off = ftello(out);
            if (write_entry_header(out, &h) != 0) {
                free(dpath);
                goto fail;
            }
            free(dpath);
            new_off[i] = entry_off + LZPLY_EHDR_SIZE +
                         (off_t)(strlen(n->path) + 1);
            new_hdr[i] = h;
            new_hdr[i].path = NULL;
            written[i] = 1;
            count++;
            continue;
        }
        if (n->dirty || n->is_new) {
            /* Re-encode from the working content. */
            uint8_t *stored = NULL;
            size_t stored_len = 0, blob_len = 0;
            uint16_t poly_id = 0;
            int is_bch = 0, lrc;
            if (!n->content_loaded) {
                lrc = load_content(st, n);
                if (lrc != 0)
                    goto fail;
            }
            if (!n->content_loaded) {
                /* New file with no working buffer yet: empty content. */
                n->content = xmalloc(1);
                n->content_len = 0;
                n->content_loaded = 1;
            }
            memset(&h, 0, sizeof h);
            h.path = n->path;
            h.level = (uint8_t)st->level;
            h.mode = n->mode;
            h.mtime = n->mtime;
            {
                int eff_level = st->level;
                if (entry_encode(n->content, n->content_len, st->level,
                                 &st->ecc,
                                 &stored, &stored_len, &blob_len, &poly_id,
                                 &is_bch, &eff_level, h.sha) != 0)
                    goto fail;
                h.level = (uint8_t)eff_level;   /* 0 when stored uncompressed */
            }
            h.flags = 0;
            if (is_bch) {
                h.flags |= FLAG_BCH;
                h.rs_level = (uint8_t)(poly_id & 0xff);
                h.reserved = (uint8_t)(poly_id >> 8);
            }
            h.orig_size = n->content_len;
            h.stored_size = stored_len;
            h.blob_size = blob_len;
            entry_off = ftello(out);
            if (write_entry_header(out, &h) != 0 ||
                (stored_len > 0 &&
                 fwrite(stored, 1, stored_len, out) != stored_len)) {
                free(stored);
                goto fail;
            }
            free(stored);
            new_off[i] = entry_off + LZPLY_EHDR_SIZE +
                         (off_t)strlen(n->path);
            new_hdr[i] = h;
            new_hdr[i].path = NULL;
            written[i] = 1;
            count++;
        } else {
            /* Clean: copy the stored bytes verbatim, header with the
             * current mode/mtime (a metadata-only change). */
            h = n->hdr;
            h.mode = n->mode;
            h.mtime = n->mtime;
            h.path = n->path;
            entry_off = ftello(out);
            if (write_entry_header(out, &h) != 0)
                goto fail;
            if (fseeko(st->archive, n->data_off, SEEK_SET) != 0 ||
                copy_bytes(st->archive, out, n->hdr.stored_size) != 0)
                goto fail;
            new_off[i] = entry_off + LZPLY_EHDR_SIZE +
                         (off_t)strlen(n->path);
            new_hdr[i] = h;
            new_hdr[i].path = NULL;
            written[i] = 1;
            count++;
        }
    }
    /* End marker. */
    {
        uint8_t end[2] = {0, 0};
        if (fwrite(end, 1, 2, out) != 2)
            goto fail;
    }
    /* Patch the entry count into the global header. */
    {
        uint8_t cbuf[4];
        put32le(cbuf, count);
        if (fseeko(out, 6, SEEK_SET) != 0 ||
            fwrite(cbuf, 1, 4, out) != 4)
            goto fail;
    }
    if (fflush(out) != 0 || fsync(fileno(out)) != 0)
        goto fail;
    if (fclose(out) != 0) {
        out = NULL;
        goto fail;
    }
    out = NULL;
    if (rename(tmp, st->archive_path) != 0) {
        fprintf(stderr, "lzply_mount: repack rename failed: %s\n",
                strerror(errno));
        goto fail;
    }
    /* Reopen the archive on the new file and apply the staged state.
     * The new file is opened and locked before the old one is closed,
     * so a failed reopen leaves the daemon working (old fd still
     * valid, nodes untouched, dirty flags still set for a later
     * repack). */
    {
        FILE *newarch = fopen(st->archive_path, "rb");
        if (!newarch) {
            fprintf(stderr,
                    "lzply_mount: repack succeeded but cannot reopen %s: %s\n",
                    st->archive_path, strerror(errno));
            goto out;
        }
        if (lock_archive_file(newarch) != 0)
            fprintf(stderr,
                    "lzply_mount: WARNING: repacked %s but could not re-lock "
                    "it (%s); another lzply_mount may have mounted it\n",
                    st->archive_path, strerror(errno));
        fclose(st->archive);
        st->archive = newarch;
    }
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *n = &st->nodes[i];
        if (!written[i])
            continue;
        n->data_off = new_off[i];
        n->hdr = new_hdr[i];
        n->hdr.path = NULL;
        n->dirty = 0;
        n->meta_dirty = 0;
        n->is_new = 0;
        n->has_entry = 1;
    }
    st->dirty = 0;
    rc = 0;
    goto out;
fail:
    if (out)
        fclose(out);
    if (tmp)
        unlink(tmp);
out:
    free(tmp);
    free(new_off);
    free(new_hdr);
    free(written);
    return rc;
}

/* Resize a file node's content to length (zero-filling on growth).
 * Loads (decodes) the content first if needed. Marks the node dirty
 * (and the filesystem dirty) and updates its mtime. */
static int truncate_node(lzply_mount_state_t *st, fs_node_t *n, off_t length)
{
    int rc;
    if (length < 0)
        return -EINVAL;
    rc = load_content(st, n);
    if (rc != 0)
        return rc;
    if (!n->content_loaded) {
        n->content = xmalloc(1);
        n->content_len = 0;
        n->content_loaded = 1;
    }
    if ((uint64_t)length != n->content_len) {
        if ((uint64_t)length > n->content_len) {
            size_t old = n->content_len;
            size_t newlen = (size_t)length;
            uint8_t *nb;
            cache_evict(st, newlen - old, n);
            nb = realloc(n->content, newlen ? newlen : 1);
            if (!nb)
                return -ENOMEM;
            n->content = nb;
            memset(n->content + old, 0, newlen - old);
            st->cache_bytes += (newlen - old);
            n->content_len = newlen;
        } else {
            st->cache_bytes -= (n->content_len - (size_t)length);
            n->content_len = (size_t)length;
        }
        n->dirty = 1;
        n->meta_dirty = 1;
        st->dirty = 1;
        n->mtime = (uint64_t)time(NULL);
    }
    return 0;
}

/* Find the parent directory node of rel ("" = root). Returns 0 on
 * success, -ENOENT if the parent does not exist, -ENOTDIR if it is
 * not a directory. */
static int find_parent(lzply_mount_state_t *st, const char *rel,
                       fs_node_t **parent_out)
{
    char *p = parent_dir(rel);
    fs_node_t *par;
    if (strcmp(p, ".") == 0)
        par = node_find(st, "");
    else
        par = node_find(st, p);
    free(p);
    if (!par)
        return -ENOENT;
    if (!par->is_dir)
        return -ENOTDIR;
    *parent_out = par;
    return 0;
}

/* Does dir (by path) have any non-deleted children? */
static int dir_has_children(lzply_mount_state_t *st, const char *dir_path)
{
    size_t i;
    for (i = 0; i < st->nnodes; i++) {
        fs_node_t *c = &st->nodes[i];
        if (!c->deleted && is_child_of(c->path, dir_path))
            return 1;
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* FUSE operations — stage 3: write, truncate, flush, fsync            */
/* ------------------------------------------------------------------ */

/* Decode-on-open: the content is decoded here and cached in the node,
 * so read() and write() just serve from memory. Corruption
 * surfaces at open time. */
static int lzply_mount_open(const char *path, struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    int rc;
    if (!n)
        return -ENOENT;
    if (n->is_dir)
        return -EISDIR;
    rc = load_content(st, n);
    if (rc != 0)
        return rc;
    if (!n->content_loaded) {
        n->content = xmalloc(1);
        n->content_len = 0;
        n->content_loaded = 1;
    }
    if ((fi->flags & O_TRUNC) && (fi->flags & O_ACCMODE) != O_RDONLY) {
        rc = truncate_node(st, n, 0);
        if (rc != 0)
            return rc;
    }
    return 0;
}

static int lzply_mount_read(const char *path, char *buf, size_t size, off_t offset,
                       struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    size_t avail;
    int rc;
    (void)fi;
    if (!n)
        return -ENOENT;
    if (n->is_dir)
        return -EISDIR;
    /* Defensive: open() normally decodes, but read must not trust that. */
    rc = load_content(st, n);
    if (rc != 0)
        return rc;
    if (offset < 0)
        return -EINVAL;
    if (size > (size_t)INT_MAX)
        size = (size_t)INT_MAX;
    if ((uint64_t)offset >= n->content_len)
        return 0;               /* EOF */
    avail = n->content_len - (size_t)offset;
    if (size > avail)
        size = avail;
    memcpy(buf, n->content + offset, size);
    return (int)size;
}

static int lzply_mount_release(const char *path, struct fuse_file_info *fi)
{
    (void)path;
    (void)fi;
    /* The decoded content stays cached in the node (bounded cache). */
    return 0;
}

/* Write into the in-memory working copy (zero-filling any gap when
 * writing past EOF). The file is re-encoded and the archive repacked
 * on fsync / clean unmount. */
static int lzply_mount_write(const char *path, const char *buf, size_t size,
                        off_t offset, struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    size_t end;
    int rc;
    (void)fi;
    if (!n)
        return -ENOENT;
    if (n->is_dir)
        return -EISDIR;
    if (offset < 0)
        return -EINVAL;
    if (size > (size_t)INT_MAX)
        size = (size_t)INT_MAX;
    if ((uint64_t)offset > (uint64_t)SIZE_MAX - size)
        return -EFBIG;
    rc = load_content(st, n);
    if (rc != 0)
        return rc;
    if (!n->content_loaded) {
        n->content = xmalloc(1);
        n->content_len = 0;
        n->content_loaded = 1;
    }
    end = (size_t)offset + size;
    if (end > n->content_len) {
        size_t old = n->content_len;
        uint8_t *nb;
        cache_evict(st, end - old, n);
        nb = realloc(n->content, end ? end : 1);
        if (!nb)
            return -ENOMEM;
        n->content = nb;
        memset(n->content + old, 0, end - old);
        st->cache_bytes += (end - old);
        n->content_len = end;
    }
    memcpy(n->content + offset, buf, size);
    n->dirty = 1;
    n->meta_dirty = 1;          /* mtime changes on write */
    st->dirty = 1;
    n->mtime = (uint64_t)time(NULL);
    return (int)size;
}

static int lzply_mount_truncate(const char *path, off_t length,
                           struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    (void)fi;
    if (!n)
        return -ENOENT;
    if (n->is_dir)
        return -EISDIR;
    return truncate_node(st, n, length);
}

static int lzply_mount_flush(const char *path, struct fuse_file_info *fi)
{
    (void)path;
    (void)fi;
    /* Writes go straight to the in-memory working copy, so there is
     * nothing to flush at close. Durability is via fsync / unmount. */
    return 0;
}

static int lzply_mount_fsync(const char *path, int isdatasync,
                        struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    (void)path;
    (void)isdatasync;
    (void)fi;
    /* fsync means "make it durable": repack the archive now when
     * anything is dirty. A no-op when nothing changed. */
    if (!st->dirty)
        return 0;
    if (repack_archive(st) != 0)
        return -EIO;
    return 0;
}

/* ------------------------------------------------------------------ */
/* FUSE operations — stage 4: create, mknod, mkdir, rmdir, unlink      */
/* ------------------------------------------------------------------ */

static int lzply_mount_create(const char *path, mode_t mode,
                         struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *par, *n;
    int rc;
    (void)fi;
    if (node_find(st, rel) != NULL)
        return -EEXIST;
    rc = find_parent(st, rel, &par);
    if (rc != 0)
        return rc;
    n = node_add(st, rel, mode & 07777, (uint64_t)time(NULL), 0);
    n->is_new = 1;
    n->content = xmalloc(1);
    n->content_len = 0;
    n->content_loaded = 1;
    st->dirty = 1;
    return 0;
}

static int lzply_mount_mknod(const char *path, mode_t mode, dev_t rdev)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *par, *n;
    int rc;
    (void)rdev;
    /* Only regular files make sense in an archive; device nodes,
     * fifos and sockets are not supported. */
    if (!S_ISREG(mode))
        return -ENOSYS;
    if (node_find(st, rel) != NULL)
        return -EEXIST;
    rc = find_parent(st, rel, &par);
    if (rc != 0)
        return rc;
    n = node_add(st, rel, mode & 07777, (uint64_t)time(NULL), 0);
    n->is_new = 1;
    n->content = xmalloc(1);
    n->content_len = 0;
    n->content_loaded = 1;
    st->dirty = 1;
    return 0;
}

static int lzply_mount_mkdir(const char *path, mode_t mode)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *par, *n;
    int rc;
    if (node_find(st, rel) != NULL)
        return -EEXIST;
    rc = find_parent(st, rel, &par);
    if (rc != 0)
        return rc;
    n = node_add(st, rel, mode & 07777, (uint64_t)time(NULL), 1);
    n->is_new = 1;
    st->dirty = 1;
    return 0;
}

static int lzply_mount_rmdir(const char *path)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *n = node_find(st, rel);
    if (!n)
        return -ENOENT;
    if (!n->is_dir)
        return -ENOTDIR;
    if (rel[0] == '\0')
        return -EBUSY;          /* the mount root cannot be removed */
    if (dir_has_children(st, rel))
        return -ENOTEMPTY;
    if (n->content_loaded) {
        st->cache_bytes -= n->content_len;
        free(n->content);
        n->content = NULL;
        n->content_len = 0;
        n->content_loaded = 0;
    }
    n->deleted = 1;
    st->dirty = 1;
    return 0;
}

static int lzply_mount_unlink(const char *path)
{
    lzply_mount_state_t *st = fs_state();
    const char *rel = rel_path(path);
    fs_node_t *n = node_find(st, rel);
    if (!n)
        return -ENOENT;
    if (n->is_dir)
        return -EISDIR;
    if (n->content_loaded) {
        st->cache_bytes -= n->content_len;
        free(n->content);
        n->content = NULL;
        n->content_len = 0;
        n->content_loaded = 0;
    }
    n->deleted = 1;
    st->dirty = 1;
    return 0;
}

/* ------------------------------------------------------------------ */
/* FUSE operations — stage 5: rename                                   */
/* ------------------------------------------------------------------ */

/* Rewrite the path of node n from old_prefix to new_prefix (for a
 * directory rename: all descendants move with it). */
static void repath_node(fs_node_t *n, const char *old_prefix,
                        const char *new_prefix)
{
    size_t olen = strlen(old_prefix);
    char *np;
    if (strcmp(n->path, old_prefix) == 0) {
        np = xstrdup(new_prefix);
    } else {
        /* old_prefix + "/" + rest */
        np = xmalloc(strlen(new_prefix) + 1 + (strlen(n->path) - olen) + 1);
        sprintf(np, "%s/%s", new_prefix, n->path + olen + 1);
    }
    free(n->path);
    n->path = np;
}

static int lzply_mount_rename(const char *from, const char *to, unsigned int flags)
{
    lzply_mount_state_t *st = fs_state();
    const char *frel = rel_path(from);
    const char *trel = rel_path(to);
    fs_node_t *src, *dst, *tpar;
    int rc;
    size_t i;

    if (flags & RENAME_EXCHANGE)
        return -EINVAL;         /* exchange is not supported */
    src = node_find(st, frel);
    if (!src)
        return -ENOENT;
    if (strcmp(frel, trel) == 0)
        return 0;               /* renaming onto itself: no-op */
    if (src->is_dir) {
        /* Cannot move a directory into itself. */
        size_t flen = strlen(frel);
        if (strncmp(trel, frel, flen) == 0 && trel[flen] == '/')
            return -EINVAL;
    }
    rc = find_parent(st, trel, &tpar);
    if (rc != 0)
        return rc;
    if ((flags & RENAME_NOREPLACE) && node_find(st, trel) != NULL)
        return -EEXIST;
    dst = node_find(st, trel);
    if (dst != NULL) {
        if (src->is_dir != dst->is_dir)
            return src->is_dir ? -ENOTDIR : -EISDIR;
        if (dst->is_dir && dir_has_children(st, trel))
            return -ENOTEMPTY;
        /* Replace the target: mark it deleted (the repack drops it). */
        if (dst->content_loaded) {
            st->cache_bytes -= dst->content_len;
            free(dst->content);
            dst->content = NULL;
            dst->content_len = 0;
            dst->content_loaded = 0;
        }
        dst->deleted = 1;
    }
    if (src->is_dir) {
        /* Move descendants first (matched on the old prefix). */
        size_t flen = strlen(frel);
        for (i = 0; i < st->nnodes; i++) {
            fs_node_t *c = &st->nodes[i];
            if (c->deleted || c == src)
                continue;
            if (strncmp(c->path, frel, flen) == 0 && c->path[flen] == '/')
                repath_node(c, frel, trel);
        }
    }
    repath_node(src, frel, trel);
    st->dirty = 1;
    return 0;
}

/* ------------------------------------------------------------------ */
/* FUSE operations — stage 6: chmod, chown, utimens                    */
/* ------------------------------------------------------------------ */

static int lzply_mount_chmod(const char *path, mode_t mode,
                        struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    (void)fi;
    if (!n)
        return -ENOENT;
    n->mode = mode & 07777;
    n->meta_dirty = 1;
    st->dirty = 1;
    return 0;
}

static int lzply_mount_chown(const char *path, uid_t uid, gid_t gid,
                        struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    (void)uid;
    (void)gid;
    (void)fi;
    /* The archive stores a mode, not an owner: every entry appears
     * owned by the mounting user. chown is a no-op that succeeds, so
     * tools that preserve ownership do not fail. */
    if (!node_find(st, rel_path(path)))
        return -ENOENT;
    return 0;
}

static int lzply_mount_utimens(const char *path, const struct timespec tv[2],
                          struct fuse_file_info *fi)
{
    lzply_mount_state_t *st = fs_state();
    fs_node_t *n = node_find(st, rel_path(path));
    (void)fi;
    if (!n)
        return -ENOENT;
    /* Only mtime is stored in the archive (atime is reported as
     * mtime by getattr). tv[1] is mtime; tv may be NULL (use now). */
    if (tv == NULL) {
        n->mtime = (uint64_t)time(NULL);
    } else if (tv[1].tv_nsec == UTIME_OMIT) {
        return 0;               /* mtime explicitly left unchanged */
    } else if (tv[1].tv_nsec == UTIME_NOW) {
        n->mtime = (uint64_t)time(NULL);
    } else {
        n->mtime = (uint64_t)tv[1].tv_sec;
    }
    n->meta_dirty = 1;
    st->dirty = 1;
    return 0;
}

/* Set by lzply_mount_destroy(): fuse_main can return non-zero after a
 * signal-triggered shutdown (e.g. SIGTERM) even though destroy()
 * already ran and freed the state. main() must not free the state
 * a second time in that case (double-free). */
static int g_destroy_ran = 0;

static void lzply_mount_destroy(void *data)
{
    lzply_mount_state_t *st = (lzply_mount_state_t *)data;
    g_destroy_ran = 1;
    if (st->dirty) {
        if (repack_archive(st) != 0)
            fprintf(stderr,
                    "lzply_mount: WARNING: repack on unmount failed; "
                    "changes lost\n");
    }
    free_state(st);
}

static const struct fuse_operations lzply_mount_ops = {
    .getattr = lzply_mount_getattr,
    .readdir = lzply_mount_readdir,
    .open = lzply_mount_open,
    .read = lzply_mount_read,
    .release = lzply_mount_release,
    .write = lzply_mount_write,
    .truncate = lzply_mount_truncate,
    .flush = lzply_mount_flush,
    .fsync = lzply_mount_fsync,
    .create = lzply_mount_create,
    .mknod = lzply_mount_mknod,
    .mkdir = lzply_mount_mkdir,
    .rmdir = lzply_mount_rmdir,
    .unlink = lzply_mount_unlink,
    .rename = lzply_mount_rename,
    .chmod = lzply_mount_chmod,
    .chown = lzply_mount_chown,
    .utimens = lzply_mount_utimens,
    .destroy = lzply_mount_destroy,
};

/* ------------------------------------------------------------------ */
/* main                                                                */
/* ------------------------------------------------------------------ */

static void usage(const char *prog)
{
    fprintf(stderr,
            "usage: %s [-f] [-d] [-s] [-o opt] [-e N] [poly=NN] [-0] "
            "[-cache N] <archive.lzply> <mountpoint>\n"
            "  -f            run in the foreground (FUSE option)\n"
            "  -d            debug output (FUSE option)\n"
            "  -s            single-threaded (FUSE option; always on)\n"
            "  -o opt        FUSE mount option (passed through); lzply_mount\n"
            "                consumes cache= from it\n"
            "  -e N          BCH level for re-encoded entries (0-7, default 4)\n"
            "  -0            store re-encoded entries uncompressed\n"
            "  poly=NN       pin a BCH polynomial by id for re-encoding\n"
            "  -cache N      read-cache cap in MiB (default 256)\n"
            "Unmount with: fusermount3 -u <mountpoint>\n"
            "Or: mount -t lzply <archive.lzply> <mountpoint> "
            "[-o cache=N]\n",
            prog);
}

/* Set the read-cache cap from a decimal MiB value. Returns 0 or -1. */
static int set_cache_cap(lzply_mount_state_t *st, const char *s)
{
    char *end;
    long n = strtol(s, &end, 10);
    if (*end != '\0' || n < 1) {
        fprintf(stderr, "lzply_mount: cache size must be a positive integer (MiB)\n");
        return -1;
    }
    st->cache_cap = (size_t)n * 1024u * 1024u;
    return 0;
}

/* Parse a comma-separated -o value. The lzply_mount option cache=
 * is consumed here; anything else is returned (malloced, comma-joined)
 * for FUSE, or NULL if nothing remains. Returns 0 or -1 on bad input. */
static int parse_fuse_opts(lzply_mount_state_t *st, const char *value,
                           char **out_rest)
{
    char *copy = xstrdup(value);
    char *save = NULL, *tok;
    char *rest = NULL;
    size_t rest_len = 0;
    int rc = 0;

    *out_rest = NULL;
    for (tok = strtok_r(copy, ",", &save); tok != NULL;
         tok = strtok_r(NULL, ",", &save)) {
        if (strncmp(tok, "cache=", 6) == 0) {
            if (set_cache_cap(st, tok + 6) != 0) {
                rc = -1;
                break;
            }
        } else {
            size_t tl = strlen(tok);
            rest = xrealloc(rest, rest_len + tl + 2);
            if (rest_len > 0)
                rest[rest_len++] = ',';
            memcpy(rest + rest_len, tok, tl + 1);
            rest_len += tl;
        }
    }
    free(copy);
    if (rc != 0) {
        free(rest);
        return -1;
    }
    *out_rest = rest;
    return 0;
}

int main(int argc, char *argv[])
{
    lzply_mount_state_t *st;
    char *archive = NULL, *mountpoint = NULL;
    char **fuse_argv;
    int fuse_argc = 0, i;
    int rc;

    lzply_set_progname("lzply_mount");
    crc32_init();

    st = xmalloc(sizeof *st);
    memset(st, 0, sizeof *st);
    st->level = 6;              /* same default as lzply -c */
    st->ecc.t = 8;              /* -e 4 -> t=8, same default as lzply */
    st->cache_cap = 256u * 1024u * 1024u;   /* 256 MiB read cache */

    fuse_argv = xmalloc(sizeof(char *) * (size_t)(argc + 4));
    fuse_argv[fuse_argc++] = argv[0];

    for (i = 1; i < argc; i++) {
        const char *a = argv[i];
        if (strcmp(a, "-e") == 0) {
            int t;
            if (i + 1 >= argc) {
                fprintf(stderr, "lzply_mount: -e needs a value\n");
                return 1;
            }
            t = atoi(argv[++i]);
            if (t < 0 || t > 7) {
                fprintf(stderr, "lzply_mount: -e must be 0..7\n");
                return 1;
            }
            /* Same mapping as lzply -e: 0=none, 1->1, 2->2, 3->4, 4->8,
             * 5->16, 6->32, 7->32. */
            static const int e_to_t[8] = {0, 1, 2, 4, 8, 16, 32, 32};
            st->ecc.t = e_to_t[t];
            st->ecc.pinned = NULL;
        } else if (strcmp(a, "-0") == 0) {
            /* Store re-encoded entries uncompressed (level 0). */
            st->level = 0;
        } else if (strncmp(a, "poly=", 5) == 0) {
            const char *s = a + 5;
            char *end;
            long v;
            const bch_poly_t *p;
            /* Hex with 0x prefix or a-f digits, else decimal. */
            if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
                v = strtol(s + 2, &end, 16);
            else if (strpbrk(s, "abcdefABCDEF") != NULL)
                v = strtol(s, &end, 16);
            else
                v = strtol(s, &end, 10);
            if (*end != '\0' || v <= 0 || v > 0xffff ||
                (p = bch_poly_by_id((uint16_t)v)) == NULL) {
                fprintf(stderr, "lzply_mount: unknown poly id '%s'\n", s);
                return 1;
            }
            st->ecc.pinned = p;
        } else if (a[0] != '-') {
            if (!archive)
                archive = (char *)a;
            else if (!mountpoint)
                mountpoint = (char *)a;
            else {
                fprintf(stderr, "lzply_mount: unexpected argument '%s'\n", a);
                usage(argv[0]);
                return 1;
            }
        } else if (strcmp(a, "-cache") == 0) {
            if (i + 1 >= argc) {
                fprintf(stderr, "lzply_mount: -cache needs a value\n");
                return 1;
            }
            if (set_cache_cap(st, argv[++i]) != 0)
                return 1;
        } else if (strcmp(a, "-o") == 0) {
            /* -o takes a value; lzply_mount consumes cache= from it
             * and passes the rest through to FUSE. */
            char *rest = NULL;
            if (i + 1 >= argc) {
                fprintf(stderr, "lzply_mount: -o needs a value\n");
                return 1;
            }
            if (parse_fuse_opts(st, argv[++i], &rest) != 0)
                return 1;
            if (rest != NULL) {
                fuse_argv[fuse_argc++] = "-o";
                fuse_argv[fuse_argc++] = rest;
            }
        } else {
            /* Any other dash option is a FUSE option: pass through. */
            fuse_argv[fuse_argc++] = argv[i];
        }
    }
    /* Single-threaded: all operations on one thread, no locking. */
    fuse_argv[fuse_argc++] = "-s";
    if (!archive || !mountpoint) {
        usage(argv[0]);
        return 1;
    }
    /* libfuse changes the daemon's working directory to "/" while
     * mounting, so a relative archive or mountpoint path would
     * resolve against "/" later: the repack would write the new
     * archive to /<basename> instead of the real archive (and the
     * original would silently keep its old contents). Canonicalise
     * both to absolute paths up front, while the caller's cwd is
     * still in effect. */
    {
        char *abs = realpath(archive, NULL);
        if (!abs) {
            fprintf(stderr, "lzply_mount: %s: %s\n", archive, strerror(errno));
            return 1;
        }
        archive = abs;
    }
    {
        char *abs = realpath(mountpoint, NULL);
        if (!abs) {
            fprintf(stderr, "lzply_mount: %s: %s\n", mountpoint, strerror(errno));
            return 1;
        }
        mountpoint = abs;
    }
    fuse_argv[fuse_argc++] = mountpoint;
    fuse_argv[fuse_argc] = NULL;

    st->archive_path = xstrdup(archive);
    if (build_index(st) != 0) {
        free_state(st);
        return 1;
    }
    fprintf(stderr, "lzply_mount: mounted %s (%zu entries) on %s\n",
            st->archive_path, st->nnodes - 1, mountpoint);

    rc = fuse_main(fuse_argc, fuse_argv, &lzply_mount_ops, st);
    free(fuse_argv);
    /* On a clean unmount destroy() (called by FUSE) frees st. On a
     * signal shutdown fuse_main can return non-zero after destroy()
     * already ran, so only free the state here if destroy() did not. */
    if (rc != 0 && !g_destroy_ran)
        free_state(st);
    return rc;
}

mount.lzply

mount(8) helper so mount -t lzply works

#!/bin/sh
# mount.lzply — mount helper for lzply archives.
#
# Installed as /sbin/mount.lzply so that:
#     mount -t lzply archive.lzply /mnt/point [-o cache=N]
# works. Invoked by mount(8) as:
#     mount.lzply <device> <dir> [-s] [-v] [-n] [-o options]
#
# Options are passed to lzply_mount(1); lzply_mount consumes cache=
# from the -o string and passes the rest (e.g. allow_other,
# ro) to FUSE. The exit status is lzply_mount's (0 on a successful mount).

LZPLY_MOUNT=/usr/local/bin/lzply_mount

if [ $# -lt 2 ]; then
    echo "usage: mount -t lzply <archive.lzply> <dir> [-o cache=N]" >&2
    exit 1
fi

device=$1
dir=$2
shift 2

opts=""
verbose=0
sloppy=0

while [ $# -gt 0 ]; do
    case "$1" in
        -o)
            shift
            if [ $# -eq 0 ]; then
                echo "mount.lzply: -o needs a value" >&2
                exit 1
            fi
            if [ -n "$opts" ]; then
                opts="$opts,$1"
            else
                opts="$1"
            fi
            ;;
        -o*)
            # -oVALUE form
            o=${1#-o}
            if [ -n "$opts" ]; then
                opts="$opts,$o"
            else
                opts="$o"
            fi
            ;;
        -v)
            verbose=1
            ;;
        -s)
            sloppy=1
            ;;
        -n)
            # no-mtab: nothing to do
            ;;
        *)
            if [ "$sloppy" -eq 1 ]; then
                echo "mount.lzply: ignoring unknown option '$1'" >&2
            else
                echo "mount.lzply: unknown option '$1'" >&2
                exit 1
            fi
            ;;
    esac
    shift
done

if [ "$verbose" -eq 1 ]; then
    echo "mount.lzply: mounting $device on $dir" >&2
fi

if [ -n "$opts" ]; then
    exec "$LZPLY_MOUNT" -o "$opts" "$device" "$dir"
else
    exec "$LZPLY_MOUNT" "$device" "$dir"
fi

lzply_stat.c

Statistics — per-entry sizes, poly id, t, parity bits and ECC overhead %, for an archive or a lzply_mount mount

/* lzply_stat.c - statistics for an lzply archive or a mounted
 * lzply_mount filesystem.
 *
 *   lzply_stat <path> [selector...]
 *
 * The path may be an .lzply archive, an lzply_mount mount point, or a file
 * or directory inside an lzply_mount mount. For a mount path the backing
 * archive is found via /proc/mounts + a scan for the lzply_mount daemon
 * (see lzply_util.c). Per entry it shows the uncompressed size,
 * the compressed size (blob, pre-ECC), the stored size (on disk,
 * including ECC), compression as stored/original, the BCH poly id
 * and t, the parity bits and the ECC overhead, and the mtime —
 * plus a totals footer for archive/mount views.
 *
 * Like `lzply -i`, it reads headers only: nothing is decompressed,
 * so it works on an archive whose data is corrupted. When the archive is currently mounted,
 * the figures are the on-disk (committed) state; unflushed changes
 * in the mount are not included. A file created in the mount but
 * not yet repacked has no on-disk entry, and is reported as such
 * instead of showing stale numbers. */
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "lzply_lib.h"
#include "lzply_util.h"

static void usage(const char *prog)
{
    fprintf(stderr,
            "usage: %s <path> [selector...]\n"
            "  <path> may be an .lzply archive, an lzply_mount mount point, or a\n"
            "  file or directory inside an lzply_mount mount.\n"
            "  Selectors use lzply selector semantics (exact path, or a\n"
            "  directory prefix where the next char must be '/').\n"
            "  Statistics come from the entry headers only: nothing is\n"
            "  decompressed.\n",
            prog);
}

enum { VIEW_ARCHIVE, VIEW_MOUNT_ALL, VIEW_MOUNT_DIR, VIEW_MOUNT_FILE };

static void print_header(void)
{
    printf("%-40s %-4s %10s %10s %10s %7s %4s %5s %3s %8s %7s %s\n",
           "path", "type", "original", "compressed", "stored",
           "comp%", "lvl", "poly", "t", "parity", "ecc%",
           "mtime (UTC)");
}

static void print_row(const ehdr_t *h, int is_dir)
{
    char b1[32], b2[32], b3[32], mt[32];
    char comp[16], poly[8], t[8], parity[24], ecc[16];
    const bch_poly_t *p = NULL;

    if ((h->flags & FLAG_BCH) != 0) {
        uint16_t pid = (uint16_t)(h->rs_level |
                                  ((unsigned)h->reserved << 8));
        p = bch_poly_by_id(pid);
        snprintf(poly, sizeof poly, "%04x", (unsigned)pid);
        snprintf(t, sizeof t, "%u", (unsigned)p->t);
        /* Parity bits = blocks * r, blocks = ceil(blob / max_data).
         * stored_size must equal bch_encoded_len(blob, poly); a
         * mismatch is reported on stderr, never silently trusted.
         * A zero-length blob is one parity-only block. */
        size_t maxd = bch_max_data(p);
        uint64_t blocks = (h->blob_size == 0) ? 1 :
                          (h->blob_size + maxd - 1) / maxd;
        uint64_t par = blocks * (uint64_t)p->r;
        size_t want = bch_encoded_len((size_t)h->blob_size, p);
        snprintf(parity, sizeof parity, "%" PRIu64, par);
        if (h->blob_size > 0)
            snprintf(ecc, sizeof ecc, "%.3f%%",
                     (double)par / (8.0 * (double)h->blob_size) * 100.0);
        else
            snprintf(ecc, sizeof ecc, "-");
        if (h->stored_size != want) {
            fprintf(stderr,
                    "%s: warning: %s: stored size %" PRIu64
                    " != %" PRIu64
                    " expected for BCH poly %04x (blob %" PRIu64
                    "); parity figures use the formula\n",
                    lzply_progname, h->path, h->stored_size,
                    (uint64_t)want, (unsigned)pid, h->blob_size);
        }
    } else {
        snprintf(poly, sizeof poly, "-");
        snprintf(t, sizeof t, "-");
        snprintf(parity, sizeof parity, "-");
        snprintf(ecc, sizeof ecc, "-");
    }
    if (h->orig_size > 0)
        snprintf(comp, sizeof comp, "%.1f%%",
                 (double)h->stored_size / (double)h->orig_size * 100.0);
    else
        snprintf(comp, sizeof comp, "-");
    fmt_mtime(h->mtime, mt, sizeof mt);
    printf("%-40s %-4s %10s %10s %10s %7s %4u %5s %3s %8s %7s %s\n",
           h->path, is_dir ? "dir" : "file",
           human_size(h->orig_size, b1, sizeof b1),
           human_size(h->blob_size, b2, sizeof b2),
           human_size(h->stored_size, b3, sizeof b3),
           comp, (unsigned)h->level, poly, t, parity, ecc, mt);
}

int main(int argc, char *argv[])
{
    const char *path;
    const char **selectors = NULL;
    int nselectors = 0;
    struct stat st;
    int is_archive = 0;
    char *archive = NULL, *mountpoint = NULL, *rel = NULL;
    int view = VIEW_ARCHIVE;
    FILE *f = NULL;
    uint32_t count = 0;
    uint32_t seen = 0, ndirs = 0, nfiles = 0;
    uint64_t tot_orig = 0, tot_blob = 0, tot_stored = 0, tot_parity = 0;
    int rc = 0;

    lzply_set_progname("lzply_stat");
    crc32_init();

    if (argc < 2) {
        usage(argv[0]);
        return EXIT_USAGE;
    }
    path = argv[1];
    selectors = (const char **)(argv + 2);
    nselectors = argc - 2;

    if (stat(path, &st) != 0) {
        fprintf(stderr, "%s: %s: no such file or directory\n",
                lzply_progname, path);
        return EXIT_IO;
    }
    if (S_ISREG(st.st_mode)) {
        /* Archive, or a file inside a mount? The magic decides. */
        FILE *probe = fopen(path, "rb");
        char magic[4];
        if (probe) {
            if (fread(magic, 1, 4, probe) == 4 &&
                memcmp(magic, LZPLY_MAGIC, 4) == 0)
                is_archive = 1;
            fclose(probe);
        }
    }
    if (is_archive) {
        archive = canon_path(path);
        mountpoint = NULL;
        if (archive_is_mounted(archive, &mountpoint) == 1) {
            printf("note: %s is mounted on %s; figures below are the "
                   "on-disk (committed) state — unflushed changes in "
                   "the mount are not included.\n",
                   archive, mountpoint);
        }
        view = VIEW_ARCHIVE;
    } else {
        if (mount_resolve(path, &archive, &mountpoint, &rel) != 0) {
            fprintf(stderr,
                    "%s: %s: not an .lzply archive and not inside an "
                    "lzply_mount mount\n",
                    lzply_progname, path);
            return EXIT_IO;
        }
        printf("note: showing the on-disk (committed) state of %s "
               "(mounted on %s); unflushed changes in the mount are "
               "not included.\n",
               archive, mountpoint);
        if (rel[0] == '\0') {
            view = VIEW_MOUNT_ALL;
        } else if (S_ISDIR(st.st_mode)) {
            view = VIEW_MOUNT_DIR;
        } else {
            view = VIEW_MOUNT_FILE;
        }
    }

    f = fopen(archive, "rb");
    if (!f) {
        fprintf(stderr, "%s: cannot open %s\n", lzply_progname, archive);
        return EXIT_IO;
    }
    if (read_global_header(f, &count) != 0) {
        fprintf(stderr, "%s: %s is not an lzply archive "
                "(bad magic/version)\n",
                lzply_progname, archive);
        fclose(f);
        return EXIT_CORRUPT;
    }
    print_header();
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        int is_dir, match = 0;
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            fclose(f);
            return EXIT_CORRUPT;
        }
        is_dir = (h.flags & FLAG_ISDIR) != 0;
        switch (view) {
        case VIEW_ARCHIVE:
        case VIEW_MOUNT_ALL:
            match = path_matches_selectors(h.path, selectors, nselectors);
            break;
        case VIEW_MOUNT_DIR:
            /* Must be under the directory AND match any extra
             * selector (if given). */
            match = selector_matches(rel, h.path) &&
                    path_matches_selectors(h.path, selectors, nselectors);
            break;
        case VIEW_MOUNT_FILE:
            match = strcmp(h.path, rel) == 0 &&
                    path_matches_selectors(h.path, selectors, nselectors);
            break;
        }
        if (match) {
            print_row(&h, is_dir);
            seen++;
            if (is_dir)
                ndirs++;
            else
                nfiles++;
            tot_orig += h.orig_size;
            tot_blob += h.blob_size;
            tot_stored += h.stored_size;
            if ((h.flags & FLAG_BCH) != 0) {
                const bch_poly_t *p = bch_poly_by_id(
                    (uint16_t)(h.rs_level |
                               ((unsigned)h.reserved << 8)));
                size_t maxd = bch_max_data(p);
                /* A zero-length blob is one parity-only block. */
                uint64_t blocks = (h.blob_size == 0) ? 1 :
                                  (h.blob_size + maxd - 1) / maxd;
                tot_parity += blocks * (uint64_t)p->r;
            }
        }
        if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
            fprintf(stderr, "%s: truncated archive\n", lzply_progname);
            free(h.path);
            fclose(f);
            return EXIT_CORRUPT;
        }
        free(h.path);
    }
    fclose(f);
    if (seen == 0) {
        if (view == VIEW_MOUNT_FILE) {
            printf("note: %s exists in the mount on %s but is not in "
                   "the on-disk archive yet — it was created in the "
                   "mount and is committed only on unmount or fsync, "
                   "so there are no committed statistics to show.\n",
                   rel, mountpoint);
            return 0;
        }
        if (nselectors > 0 || view == VIEW_MOUNT_DIR)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries in this archive\n");
        return 0;
    }
    if (view != VIEW_MOUNT_FILE) {
        char b1[32], b2[32], b3[32];
        printf("%u entries (%u directories, %u files)\n",
               seen, ndirs, nfiles);
        printf("total uncompressed: %s, total compressed (blob): %s, "
               "total stored: %s\n",
               human_size(tot_orig, b1, sizeof b1),
               human_size(tot_blob, b2, sizeof b2),
               human_size(tot_stored, b3, sizeof b3));
        if (tot_orig > 0)
            printf("overall compression: %.1f%% (stored/original)\n",
                   (double)tot_stored / (double)tot_orig * 100.0);
        if (tot_blob > 0)
            printf("total parity bits: %" PRIu64
                   ", overall ECC overhead: %.3f%%\n",
                   tot_parity,
                   (double)tot_parity / (8.0 * (double)tot_blob) * 100.0);
        else
            printf("total parity bits: %" PRIu64 "\n", tot_parity);
    }
    free(archive);
    free(mountpoint);
    free(rel);
    return rc;
}

lzply_heal.c

Healing — strip the BCH parity from each entry and reapply it at a new level, correcting bit errors, without ever touching the compressed blob

/* lzply_heal.c - strip and reapply BCH error correction on an lzply archive.
 *
 *   lzply_heal <archive.lzply> [-e <level>] [poly=<id>] [-o <output.lzply>] [selector...]
 *
 * For each entry (matching selectors): strip the BCH parity with
 * bch_decode — which corrects bit errors up to t, that is the heal —
 * then re-encode with the new error correction. The compressed /
 * then re-encode with the new error correction. The compressed
 * blob is never touched: no recompression, and it is preserved
 * byte-for-byte. Only the poly id, the stored size and the
 * header CRC change; orig_size, blob_size, SHA-256, mode
 * and mtime are unchanged, so the per-entry SHA-256 still verifies
 * the original data.
 *
 * New error correction:
 *   poly=NN   pin one polynomial for every entry (its t is fixed by
 *             the poly; any blob size works — the encoder splits into
 *             blocks, so no blob is ever too large for a poly).
 *   -e N      set the level (0=none, 1->t=1, 2->t=2, 3->t=4, 4->t=8,
 *             5->t=16, 6->t=32, 7->t=32); the most efficient poly per
 *             blob is auto-picked, as in `lzply -c`.
 *   neither   re-encode with the same poly and t the entry already
 *             has — a pure heal pass that corrects bit errors.
 *   -e 0      strip the error correction entirely (no parity).
 * poly= overrides -e when both are given.
 *
 * An entry whose BCH decode fails (uncorrectable) is kept byte-for-byte
 * unchanged, reported, and the program exits non-zero at the end; the
 * other entries are still healed. Directories have no data and are
 * copied verbatim. The archive is rewritten via a temp file and
 * renamed over the original (or over -o), so a failure leaves the
 * original intact. The archive must not be mounted: heal takes the
 * same exclusive flock the mount daemon holds, so a mounted archive
 * is refused and a mount cannot start mid-heal. */
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include "sha256.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>

#include "lzply_lib.h"
#include "lzply_util.h"

static void usage(const char *prog)
{
    fprintf(stderr,
            "usage: %s <archive.lzply> [-e <level>] [poly=<id>] [-o <output.lzply>] [selector...]\n"
            "  Strip the BCH error correction from each entry and reapply a\n"
            "  new one. The compressed blob is never touched, so the\n"
            "  data is unchanged.\n"
            "  -e <level>  new BCH level: 0=none, 1->t=1, 2->t=2, 3->t=4,\n"
            "              4->t=8 (default for new archives), 5->t=16,\n"
            "              6->t=32, 7->t=32. Auto-picks the most efficient\n"
            "              poly per blob. -e 0 strips the ECC entirely.\n"
            "  poly=<id>   pin one BCH polynomial by id, hex (poly=003a)\n"
            "              or decimal (poly=58); overrides -e.\n"
            "  -o <file>   write the healed archive to <file> instead of\n"
            "              healing in place (the original is untouched).\n"
            "  With neither -e nor poly=, each entry is re-encoded with\n"
            "  the same poly and t it already has — a pure heal pass that\n"
            "  corrects bit errors up to t. The archive must not be\n"
            "  mounted while healing.\n",
            prog);
}

/* Parse a poly=NN value: hex if it has a 0x prefix or any a-f/A-F
 * letter, else decimal. Returns the poly, or NULL if it is not a
 * number or not one of the 82 embedded polys. (Same rule as lzply.) */
static const bch_poly_t *parse_poly_id(const char *s)
{
    int is_hex = 0;
    const char *p = s;
    long v;
    char *end;
    if (!*s)
        return NULL;
    if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
        is_hex = 1;
        p += 2;
    } else {
        for (const char *q = s; *q; q++) {
            if ((*q >= 'a' && *q <= 'f') || (*q >= 'A' && *q <= 'F')) {
                is_hex = 1;
                break;
            }
        }
    }
    if (!*p)
        return NULL;
    v = strtol(p, &end, is_hex ? 16 : 10);
    if (*end != '\0' || v < 0 || v > 0xffff)
        return NULL;
    return bch_poly_by_id((uint16_t)v);
}

/* Largest parent's poly for a t (m=22 has all six t values). The
 * auto-pick fallback when a blob is larger than the largest single
 * block, so it is split into blocks of that poly. Scans the embedded
 * table for the largest m with the given t. */
static const bch_poly_t *largest_poly_for_t(int t)
{
    const bch_poly_t *best = NULL;
    uint16_t id;
    if (t < 1 || t > 32)
        return NULL;
    for (id = 0x0001; id <= 0x0052; id++) {
        const bch_poly_t *p = bch_poly_by_id(id);
        if (p && p->t == t && (!best || p->m > best->m))
            best = p;
    }
    return best;
}

/* Describe a poly for a report line: "003a (m=18, t=32)" or "none". */
static void fmt_poly(const bch_poly_t *p, char *buf, size_t bufsz)
{
    if (!p)
        snprintf(buf, bufsz, "none");
    else
        snprintf(buf, bufsz, "%04x (m=%u, t=%u)",
                 (unsigned)p->id, (unsigned)p->m, (unsigned)p->t);
}

int main(int argc, char *argv[])
{
    const char *archive = NULL, *output = NULL;
    const char **selectors = NULL;
    int nselectors = 0;
    int ecc_level = -1;         /* -1: no -e given */
    const bch_poly_t *pinned = NULL;
    char *carch = NULL;
    FILE *src = NULL, *tmp = NULL;
    char *tmp_path = NULL;
    const char *dest = NULL;
    uint32_t count = 0;
    int version = 0;
    off_t size_out = 0, end_off = 0;
    scan_list_t entries;
    size_t i;
    int rc = 0, fail = 0;
    uint32_t nhealed = 0, nunchanged = 0, nskipped = 0, nfailed = 0;
    uint64_t tot_corrected = 0;

    lzply_set_progname("lzply_heal");
    crc32_init();

    /* Options may appear before or after the positionals, as in lzply. */
    for (i = 1; i < (size_t)argc; i++) {
        const char *a = argv[i];
        if (strcmp(a, "-e") == 0 || strcmp(a, "--ecc") == 0 ||
            strcmp(a, "--rs") == 0) {
            if (i + 1 >= (size_t)argc) {
                fprintf(stderr, "%s: -e needs a level 0..7\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            ecc_level = atoi(argv[++i]);
            if (ecc_level < 0 || ecc_level > 7) {
                fprintf(stderr, "%s: BCH level must be 0..7\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
        } else if (a[0] == '-' && a[1] == 'e' && a[2] != '\0') {
            ecc_level = atoi(a + 2);
            if (ecc_level < 0 || ecc_level > 7) {
                fprintf(stderr, "%s: BCH level must be 0..7\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
        } else if (strncmp(a, "poly=", 5) == 0 ||
                   strncmp(a, "-poly=", 6) == 0 ||
                   strncmp(a, "--poly=", 7) == 0) {
            const char *eq = strchr(a, '=');
            pinned = parse_poly_id(eq + 1);
            if (!pinned) {
                fprintf(stderr,
                        "%s: unknown BCH polynomial '%s' "
                        "(want an id 0001..0052, hex or decimal)\n",
                        lzply_progname, eq + 1);
                return EXIT_USAGE;
            }
        } else if (strcmp(a, "-o") == 0) {
            if (i + 1 >= (size_t)argc) {
                fprintf(stderr, "%s: -o needs an output file\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            output = argv[++i];
        } else if (strncmp(a, "-o=", 3) == 0) {
            output = a + 3;
            if (!*output) {
                fprintf(stderr, "%s: -o needs an output file\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
        } else if (a[0] == '-' && a[1] == 'o' && a[2] != '\0') {
            output = a + 2;
        } else if (a[0] == '-' && a[1] != '\0') {
            fprintf(stderr, "%s: unknown option %s\n", lzply_progname, a);
            usage(argv[0]);
            return EXIT_USAGE;
        } else if (!archive) {
            archive = a;
        } else {
            /* Extra positionals are selectors. */
            selectors = (const char **)(argv + i);
            nselectors = argc - (int)i;
            break;
        }
    }
    if (!archive) {
        usage(argv[0]);
        return EXIT_USAGE;
    }

    carch = canon_path(archive);
    if (!carch) {
        fprintf(stderr, "%s: cannot resolve %s\n", lzply_progname, archive);
        return EXIT_IO;
    }

    /* Open the archive and take the mount lock (the same exclusive
     * flock the lzply_mount daemon holds). If it is held, the archive
     * is mounted: refuse, change nothing. The lock is held for the
     * whole run, so a mount cannot start mid-heal either. */
    src = fopen(carch, "rb");
    if (!src) {
        fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname,
                carch, strerror(errno));
        free(carch);
        return EXIT_IO;
    }
    if (flock(fileno(src), LOCK_EX | LOCK_NB) != 0) {
        if (errno == EWOULDBLOCK) {
            char *mp = NULL;
            if (archive_is_mounted(carch, &mp) == 1) {
                fprintf(stderr,
                        "%s: %s is mounted on %s; unmount it before "
                        "healing (healing under a live mount would "
                        "corrupt the daemon's in-memory index)\n",
                        lzply_progname, carch, mp);
                free(mp);
            } else {
                fprintf(stderr,
                        "%s: %s is locked by another process; "
                        "healing refused\n",
                        lzply_progname, carch);
            }
        } else {
            fprintf(stderr, "%s: cannot lock %s: %s\n", lzply_progname,
                    carch, strerror(errno));
        }
        fclose(src);
        free(carch);
        return EXIT_IO;
    }

    if (scan_archive(carch, &version, &count, &size_out, &entries,
                     &end_off) != 0) {
        fclose(src);
        free(carch);
        return EXIT_CORRUPT;
    }

    dest = output ? output : carch;
    tmp = temp_in_same_dir(dest, &tmp_path);
    if (!tmp) {
        fprintf(stderr, "%s: cannot create temp file for %s: %s\n",
                lzply_progname, dest, strerror(errno));
        scan_list_free(&entries);
        fclose(src);
        free(carch);
        return EXIT_IO;
    }
    write_global_header(tmp, count, LZPLY_VERSION);
    if (ferror(tmp)) {
        fprintf(stderr, "%s: cannot write %s\n", lzply_progname, dest);
        fclose(tmp);
        unlink(tmp_path);
        free(tmp_path);
        scan_list_free(&entries);
        fclose(src);
        free(carch);
        return EXIT_IO;
    }

    for (i = 0; i < entries.len; i++) {
        scan_entry_t *e = &entries.v[i];
        ehdr_t h;
        uint8_t *stored = NULL, *blob = NULL, *new_stored = NULL;
        size_t new_stored_len = 0;
        const bch_poly_t *p_old = NULL, *p_new = NULL;
        int corrected = 0, is_dir, matched;
        uint16_t old_id = 0;

        if (fseeko(src, e->offset, SEEK_SET) != 0 ||
            read_entry_header(src, &h) != 0) {
            fprintf(stderr, "%s: cannot read entry header at %lld\n",
                    lzply_progname, (long long)e->offset);
            rc = EXIT_CORRUPT;
            goto heal_done;
        }
        is_dir = (h.flags & FLAG_ISDIR) != 0;
        matched = path_matches_selectors(h.path, selectors, nselectors);

        if (h.stored_size > 0) {
            stored = xmalloc(h.stored_size ? h.stored_size : 1);
            if (fread(stored, 1, h.stored_size, src) != h.stored_size) {
                fprintf(stderr, "%s: truncated data for %s\n",
                        lzply_progname, h.path);
                free(stored);
                free(h.path);
                rc = EXIT_CORRUPT;
                goto heal_done;
            }
        }

        if (is_dir || !matched) {
            /* Directories have no data; non-matching entries are
             * left alone. Re-emit byte-for-byte (the header CRC is
             * deterministic and the archive was validated on scan). */
            if (write_entry_header(tmp, &h) != 0 ||
                (h.stored_size > 0 &&
                 fwrite(stored, 1, h.stored_size, tmp) != h.stored_size)) {
                fprintf(stderr, "%s: cannot write %s\n",
                        lzply_progname, dest);
                free(stored);
                free(h.path);
                rc = EXIT_IO;
                goto heal_done;
            }
            if (is_dir)
                nunchanged++;
            else
                nskipped++;
            free(stored);
            free(h.path);
            continue;
        }

        /* A file entry to heal. Strip the BCH parity (correcting bit
         * errors up to t); without BCH the blob is the stored data. */
        if ((h.flags & FLAG_BCH) != 0) {
            old_id = (uint16_t)(h.rs_level |
                                ((unsigned)h.reserved << 8));
            p_old = bch_poly_by_id(old_id);
            blob = xmalloc(h.blob_size ? h.blob_size : 1);
            if (bch_decode(stored, h.stored_size, h.blob_size, p_old,
                           blob, &corrected) != 0) {
                /* Uncorrectable: keep byte-for-byte, report, continue. */
                fprintf(stderr,
                        "%s: %s: BCH decode failed (more than t=%u bit "
                        "errors for poly %04x); entry kept unchanged\n",
                        lzply_progname, h.path, (unsigned)p_old->t,
                        (unsigned)old_id);
                if (write_entry_header(tmp, &h) != 0 ||
                    (h.stored_size > 0 &&
                     fwrite(stored, 1, h.stored_size, tmp) !=
                         h.stored_size)) {
                    fprintf(stderr, "%s: cannot write %s\n",
                            lzply_progname, dest);
                    free(blob);
                    free(stored);
                    free(h.path);
                    rc = EXIT_IO;
                    goto heal_done;
                }
                nfailed++;
                fail = 1;
                free(blob);
                free(stored);
                free(h.path);
                continue;
            }
        } else {
            blob = xmalloc(h.blob_size ? h.blob_size : 1);
            if (h.blob_size > 0)
                memcpy(blob, stored, h.blob_size);
        }

        /* Pick the new error correction. */
        if (pinned) {
            p_new = pinned;
        } else if (ecc_level >= 0) {
            int t = bch_t_for_level(ecc_level);
            if (t == 0) {
                p_new = NULL;
            } else {
                p_new = bch_poly_for_data(h.blob_size, t);
                if (!p_new)
                    p_new = largest_poly_for_t(t);
            }
        } else {
            p_new = p_old;      /* pure heal: same poly and t */
        }

        if ((p_old ? p_old->id : 0) == (p_new ? p_new->id : 0) &&
            corrected == 0) {
            /* Same ECC and no errors corrected: re-encoding would
             * produce identical bytes, so copy verbatim. */
            if (write_entry_header(tmp, &h) != 0 ||
                (h.stored_size > 0 &&
                 fwrite(stored, 1, h.stored_size, tmp) != h.stored_size)) {
                fprintf(stderr, "%s: cannot write %s\n",
                        lzply_progname, dest);
                free(blob);
                free(stored);
                free(h.path);
                rc = EXIT_IO;
                goto heal_done;
            }
            nunchanged++;
            free(blob);
            free(stored);
            free(h.path);
            continue;
        }

        /* Verify the stripped blob before re-encoding (all
         * entries): decompress and check the SHA-256. This
         * catches a BCH miscorrection, which is possible when the
         * errors exceed t (notably at small t: t=1 with 2-bit errors
         * miscorrects about half the time). A miscorrected blob
         * would decompress to the wrong data, and must not be
         * re-encoded. A level-0 entry is stored uncompressed, so
         * its blob is the raw data: check the SHA-256 directly. */
        {
            uint8_t *raw = NULL;
            size_t raw_len = 0;
            uint8_t sha[32];
            int vok = 0;
            if (h.level == 0) {
                if (h.blob_size == h.orig_size) {
                    lzply_sha256(blob, h.blob_size, sha);
                    vok = (memcmp(sha, h.sha, 32) == 0);
                }
            } else if (lz_decompress_mem(blob, h.blob_size, &raw, &raw_len) == 0 &&
                raw_len == h.orig_size) {
                lzply_sha256(raw, raw_len, sha);
                vok = (memcmp(sha, h.sha, 32) == 0);
            }
            free(raw);
            if (!vok) {
                fprintf(stderr,
                        "%s: %s: stripped blob does not verify "
                        "(SHA-256 mismatch after decompress); entry "
                        "kept unchanged\n",
                        lzply_progname, h.path);
                if (write_entry_header(tmp, &h) != 0 ||
                    (h.stored_size > 0 &&
                     fwrite(stored, 1, h.stored_size, tmp) !=
                         h.stored_size)) {
                    fprintf(stderr, "%s: cannot write %s\n",
                            lzply_progname, dest);
                    free(blob);
                    free(stored);
                    free(h.path);
                    rc = EXIT_IO;
                    goto heal_done;
                }
                nfailed++;
                fail = 1;
                free(blob);
                free(stored);
                free(h.path);
                continue;
            }
        }

        /* Re-encode with the new ECC. */
        if (p_new) {
            new_stored_len = bch_encoded_len(h.blob_size, p_new);
            new_stored = xmalloc(new_stored_len ? new_stored_len : 1);
            if (bch_encode(blob, h.blob_size, p_new, new_stored) !=
                    new_stored_len) {
                fprintf(stderr, "%s: %s: BCH encode failed\n",
                        lzply_progname, h.path);
                free(new_stored);
                free(blob);
                free(stored);
                free(h.path);
                rc = EXIT_CORRUPT;
                goto heal_done;
            }
            /* Self-check: the new encoding must decode to the blob. */
            {
                uint8_t *check = xmalloc(h.blob_size ? h.blob_size : 1);
                int c2 = 0;
                if (bch_decode(new_stored, new_stored_len, h.blob_size,
                               p_new, check, &c2) != 0 ||
                    (h.blob_size > 0 &&
                     memcmp(check, blob, h.blob_size) != 0)) {
                    fprintf(stderr,
                            "%s: %s: internal error: re-encoded entry "
                            "does not decode; entry kept unchanged\n",
                            lzply_progname, h.path);
                    free(check);
                    if (write_entry_header(tmp, &h) != 0 ||
                        (h.stored_size > 0 &&
                         fwrite(stored, 1, h.stored_size, tmp) !=
                             h.stored_size)) {
                        fprintf(stderr, "%s: cannot write %s\n",
                                lzply_progname, dest);
                        free(new_stored);
                        free(blob);
                        free(stored);
                        free(h.path);
                        rc = EXIT_IO;
                        goto heal_done;
                    }
                    nfailed++;
                    fail = 1;
                    free(new_stored);
                    free(blob);
                    free(stored);
                    free(h.path);
                    continue;
                }
                free(check);
            }
        } else {
            new_stored = blob;  /* no ECC: the blob is the stored data */
            new_stored_len = h.blob_size;
            blob = NULL;        /* ownership moved to new_stored */
        }

        {
            ehdr_t h2 = h;
            char oldp[32], newp[32];
            h2.stored_size = new_stored_len;
            if (p_new) {
                h2.flags |= FLAG_BCH;
                h2.rs_level = (uint8_t)(p_new->id & 0xff);
                h2.reserved = (uint8_t)((p_new->id >> 8) & 0xff);
            } else {
                h2.flags &= (uint8_t)~FLAG_BCH;
                h2.rs_level = 0;
                h2.reserved = 0;
            }
            if (write_entry_header(tmp, &h2) != 0 ||
                (new_stored_len > 0 &&
                 fwrite(new_stored, 1, new_stored_len, tmp) !=
                     new_stored_len)) {
                fprintf(stderr, "%s: cannot write %s\n",
                        lzply_progname, dest);
                free(new_stored);
                free(blob);
                free(stored);
                free(h.path);
                rc = EXIT_IO;
                goto heal_done;
            }
            fmt_poly(p_old, oldp, sizeof oldp);
            fmt_poly(p_new, newp, sizeof newp);
            printf("%s: %s -> %s, stored %" PRIu64 " -> %" PRIu64
                   " B, %d bit error(s) corrected\n",
                   h.path, oldp, newp, h.stored_size,
                   (uint64_t)new_stored_len, corrected);
            tot_corrected += (uint64_t)corrected;
            nhealed++;
        }
        free(new_stored);
        free(blob);
        free(stored);
        free(h.path);
    }

    /* End marker, then flush + fsync the temp file and rename it over
     * the destination. The original is untouched until the rename. */
    {
        uint8_t end[2] = {0, 0};
        if (fwrite(end, 1, 2, tmp) != 2 || fflush(tmp) != 0 ||
            fsync(fileno(tmp)) != 0) {
            fprintf(stderr, "%s: cannot finish %s: %s\n",
                    lzply_progname, dest, strerror(errno));
            rc = EXIT_IO;
            goto heal_done;
        }
    }
    if (fclose(tmp) != 0) {
        tmp = NULL;
        fprintf(stderr, "%s: cannot close %s: %s\n", lzply_progname,
                dest, strerror(errno));
        unlink(tmp_path);
        rc = EXIT_IO;
        goto heal_done;
    }
    tmp = NULL;
    if (rename(tmp_path, dest) != 0) {
        fprintf(stderr, "%s: cannot replace %s: %s\n", lzply_progname,
                dest, strerror(errno));
        rc = EXIT_IO;
        goto heal_done;
    }
    printf("%s: %s: %u healed, %u unchanged, %u skipped by selector, "
           "%u uncorrectable (kept), %" PRIu64 " bit error(s) corrected\n",
           lzply_progname, dest, nhealed, nunchanged, nskipped, nfailed,
           tot_corrected);
    rc = fail ? EXIT_CORRUPT : 0;

heal_done:
    if (tmp) {
        fclose(tmp);
        if (tmp_path)
            unlink(tmp_path);
    }
    free(tmp_path);
    scan_list_free(&entries);
    if (src)
        fclose(src);
    free(carch);
    return rc;
}

lzply_check.c

BER detector — read-only: runs bch_decode() on each entry's stored bytes in memory and counts the corrected bit errors, reporting a bit error rate per entry and overall

/* lzply_check.c - bit error rate (BER) detector for an lzply archive or
 * a mounted lzply_mount filesystem.
 *
 *   lzply_check <path> [selector...] [--json] [--warn-ber <value>] [--fail-ber <value>]
 *
 * The path may be an .lzply archive, an lzply_mount mount point, or a file
 * or directory inside an lzply_mount mount (same mount resolution as
 * lzply_stat: /proc/mounts + a scan for the lzply_mount daemon).
 *
 * Read-only: it never modifies the archive. For each BCH entry it runs
 * bch_decode() on the stored bytes in memory and counts the bit errors
 * the decoder corrects. This operates on the stored codeword below
 * the compression layer, so it does NOT decompress anything.
 *
 * BER per entry = corrected bit errors / total stored bits
 * (8 * stored_size), as seen by the BCH decoder. Entries with no BCH
 * (t=0) cannot be measured and are reported as "no-ecc". Uncorrectable
 * entries are reported separately and are NOT folded into the BER
 * number. The overall BER is total corrected / total stored bits
 * across the BCH entries that decoded successfully.
 *
 * Exit codes: 0 = OK (no errors, or only correctable errors and the
 * overall BER is below --fail-ber). 3 = any uncorrectable entry, or
 * the overall BER is above --fail-ber. --warn-ber prints a warning
 * but still exits 0. With no thresholds given, only uncorrectable
 * entries fail.
 *
 * Caveat: the BER is as seen by the BCH decoder. For small t, if the
 * true error count exceeds t the decoder may miscorrect and the
 * reported BER is unreliable — so a high BER or any uncorrectable
 * entry means: run lzply_heal, then lzply -t to fully verify. */
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

#include "lzply_lib.h"
#include "lzply_util.h"

static void usage(const char *prog)
{
    fprintf(stderr,
            "usage: %s <path> [selector...] [--json] [--warn-ber <value>] [--fail-ber <value>]\n"
            "  <path> may be an .lzply archive, an lzply_mount mount point, or a\n"
            "  file or directory inside an lzply_mount mount.\n"
            "  Selectors use lzply selector semantics (exact path, or a\n"
            "  directory prefix where the next char must be '/').\n"
            "  For each BCH entry the stored bytes are decoded in memory and\n"
            "  the corrected bit errors counted; BER = corrected / (8 * stored\n"
            "  size). Nothing is decompressed, and the archive is never\n"
            "  modified.\n"
            "  Entries with no BCH cannot be measured (reported as no-ecc).\n"
            "  --warn-ber prints a warning when the overall BER exceeds it\n"
            "  (still exits 0); --fail-ber exits 3 when the overall BER\n"
            "  exceeds it. Without thresholds, only uncorrectable entries\n"
            "  fail (exit 3).\n",
            prog);
}

enum { VIEW_ARCHIVE, VIEW_MOUNT_ALL, VIEW_MOUNT_DIR, VIEW_MOUNT_FILE };

/* One checked entry. kept in a list for the totals and for --json. */
typedef struct {
    char *path;
    uint16_t poly_id;           /* 0 when no BCH */
    int t;                      /* 0 when no BCH */
    uint64_t stored_bits;       /* 8 * stored_size */
    int has_ber;                /* 1 when ber/corrected are meaningful */
    int64_t corrected;          /* -1 when uncorrectable */
    double ber;                 /* corrected / stored_bits */
    const char *status;         /* "clean", "correctable", "uncorrectable", "no-ecc" */
} check_entry_t;

static void fmt_ber(double ber, char *buf, size_t bufsz)
{
    snprintf(buf, bufsz, "%.3g", ber);
}

/* Minimal JSON string escaping: " \ and control chars. */
static void json_escape(FILE *f, const char *s)
{
    fputc('"', f);
    for (; *s; s++) {
        unsigned char c = (unsigned char)*s;
        switch (c) {
        case '"':  fputs("\\\"", f); break;
        case '\\': fputs("\\\\", f); break;
        case '\n': fputs("\\n", f); break;
        case '\r': fputs("\\r", f); break;
        case '\t': fputs("\\t", f); break;
        default:
            if (c < 0x20)
                fprintf(f, "\\u%04x", c);
            else
                fputc(c, f);
        }
    }
    fputc('"', f);
}

static void print_json(const char *archive, check_entry_t *v, size_t n,
                       uint64_t tot_corrected, uint64_t tot_bits,
                       double overall_ber, int has_overall,
                       const char *worst_path, double worst_ber,
                       size_t n_bch, size_t n_noecc, size_t n_err,
                       size_t n_uncorr, const char *status)
{
    size_t i;
    printf("{\n  \"archive\": ");
    json_escape(stdout, archive);
    printf(",\n  \"entries\": [");
    for (i = 0; i < n; i++) {
        check_entry_t *e = &v[i];
        printf("%s\n    {\"path\": ", i ? "," : "");
        json_escape(stdout, e->path);
        if (e->t > 0)
            printf(", \"poly\": \"%04x\", \"t\": %d", (unsigned)e->poly_id, e->t);
        else
            printf(", \"poly\": null, \"t\": 0");
        printf(", \"stored_bits\": %" PRIu64, e->stored_bits);
        if (e->has_ber)
            printf(", \"corrected\": %" PRId64 ", \"ber\": %.17g",
                   e->corrected, e->ber);
        else
            printf(", \"corrected\": null, \"ber\": null");
        printf(", \"status\": ");
        json_escape(stdout, e->status);
        printf("}");
    }
    printf("%s],\n  \"totals\": {\n", n ? "\n  " : "");
    printf("    \"entries\": %" PRIu64 ", \"bch_entries\": %" PRIu64
           ", \"no_ecc\": %" PRIu64 ", \"with_errors\": %" PRIu64
           ", \"uncorrectable\": %" PRIu64 ",\n",
           (uint64_t)n, (uint64_t)n_bch, (uint64_t)n_noecc,
           (uint64_t)n_err, (uint64_t)n_uncorr);
    printf("    \"total_corrected\": %" PRIu64
           ", \"total_bits\": %" PRIu64 ", ",
           tot_corrected, tot_bits);
    if (has_overall)
        printf("\"overall_ber\": %.17g, ", overall_ber);
    else
        printf("\"overall_ber\": null, ");
    if (worst_path) {
        printf("\"worst_entry\": ");
        json_escape(stdout, worst_path);
        printf(", \"worst_ber\": %.17g\n", worst_ber);
    } else {
        printf("\"worst_entry\": null, \"worst_ber\": null\n");
    }
    printf("  },\n  \"status\": ");
    json_escape(stdout, status);
    printf("\n}\n");
}

static int parse_ber(const char *s, double *out)
{
    char *end = NULL;
    double v = strtod(s, &end);
    if (!end || *end != '\0' || !isfinite(v) || v < 0)
        return -1;
    *out = v;
    return 0;
}

int main(int argc, char *argv[])
{
    const char *path = NULL;
    const char **selectors = NULL;
    int nselectors = 0;
    int json = 0, have_warn = 0, have_fail = 0;
    double warn_ber = 0, fail_ber = 0;
    struct stat st;
    int is_archive = 0;
    char *archive = NULL, *mountpoint = NULL, *rel = NULL;
    int view = VIEW_ARCHIVE;
    FILE *f = NULL;
    uint32_t count = 0;
    check_entry_t *entries = NULL;
    size_t nentries = 0, cap = 0;
    size_t n_bch = 0, n_noecc = 0, n_err = 0, n_uncorr = 0;
    uint64_t tot_corrected = 0, tot_bits = 0;
    double worst_ber = 0;
    const char *worst_path = NULL;
    int rc = 0, i;

    lzply_set_progname("lzply_check");
    crc32_init();

    /* Options may appear before or after the positionals. The first
     * positional is the path; the rest are selectors. */
    selectors = (const char **)xmalloc(sizeof(char *) * (size_t)(argc > 0 ? argc : 1));
    for (i = 1; i < argc; i++) {
        const char *a = argv[i];
        if (strcmp(a, "--json") == 0) {
            json = 1;
        } else if (strncmp(a, "--warn-ber=", 11) == 0) {
            if (parse_ber(a + 11, &warn_ber) != 0) {
                fprintf(stderr, "%s: bad --warn-ber value '%s'\n",
                        lzply_progname, a + 11);
                return EXIT_USAGE;
            }
            have_warn = 1;
        } else if (strcmp(a, "--warn-ber") == 0) {
            if (++i >= argc) {
                fprintf(stderr, "%s: --warn-ber needs a value\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            if (parse_ber(argv[i], &warn_ber) != 0) {
                fprintf(stderr, "%s: bad --warn-ber value '%s'\n",
                        lzply_progname, argv[i]);
                return EXIT_USAGE;
            }
            have_warn = 1;
        } else if (strncmp(a, "--fail-ber=", 11) == 0) {
            if (parse_ber(a + 11, &fail_ber) != 0) {
                fprintf(stderr, "%s: bad --fail-ber value '%s'\n",
                        lzply_progname, a + 11);
                return EXIT_USAGE;
            }
            have_fail = 1;
        } else if (strcmp(a, "--fail-ber") == 0) {
            if (++i >= argc) {
                fprintf(stderr, "%s: --fail-ber needs a value\n",
                        lzply_progname);
                return EXIT_USAGE;
            }
            if (parse_ber(argv[i], &fail_ber) != 0) {
                fprintf(stderr, "%s: bad --fail-ber value '%s'\n",
                        lzply_progname, argv[i]);
                return EXIT_USAGE;
            }
            have_fail = 1;
        } else if (a[0] == '-') {
            fprintf(stderr, "%s: unknown option '%s'\n", lzply_progname, a);
            usage(argv[0]);
            return EXIT_USAGE;
        } else if (!path) {
            path = a;
        } else {
            selectors[nselectors++] = a;
        }
    }
    if (!path) {
        usage(argv[0]);
        return EXIT_USAGE;
    }

    if (stat(path, &st) != 0) {
        fprintf(stderr, "%s: %s: no such file or directory\n",
                lzply_progname, path);
        return EXIT_IO;
    }
    if (S_ISREG(st.st_mode)) {
        /* Archive, or a file inside a mount? The magic decides. */
        FILE *probe = fopen(path, "rb");
        char magic[4];
        if (probe) {
            if (fread(magic, 1, 4, probe) == 4 &&
                memcmp(magic, LZPLY_MAGIC, 4) == 0)
                is_archive = 1;
            fclose(probe);
        }
    }
    if (is_archive) {
        archive = canon_path(path);
        mountpoint = NULL;
        if (archive_is_mounted(archive, &mountpoint) == 1 && !json) {
            printf("note: %s is mounted on %s; figures below are the "
                   "on-disk (committed) state — unflushed changes in "
                   "the mount are not included.\n",
                   archive, mountpoint);
        }
        view = VIEW_ARCHIVE;
    } else {
        if (mount_resolve(path, &archive, &mountpoint, &rel) != 0) {
            fprintf(stderr,
                    "%s: %s: not an .lzply archive and not inside an "
                    "lzply_mount mount\n",
                    lzply_progname, path);
            return EXIT_IO;
        }
        if (!json)
            printf("note: showing the on-disk (committed) state of %s "
                   "(mounted on %s); unflushed changes in the mount are "
                   "not included.\n",
                   archive, mountpoint);
        if (rel[0] == '\0') {
            view = VIEW_MOUNT_ALL;
        } else if (S_ISDIR(st.st_mode)) {
            view = VIEW_MOUNT_DIR;
        } else {
            view = VIEW_MOUNT_FILE;
        }
    }

    f = fopen(archive, "rb");
    if (!f) {
        fprintf(stderr, "%s: cannot open %s\n", lzply_progname, archive);
        return EXIT_IO;
    }
    if (read_global_header(f, &count) != 0) {
        fprintf(stderr, "%s: %s is not an lzply archive "
                "(bad magic/version)\n",
                lzply_progname, archive);
        fclose(f);
        return EXIT_CORRUPT;
    }
    for (;;) {
        ehdr_t h;
        int r = read_entry_header(f, &h);
        int is_dir, match = 0;
        if (r == 1)
            break;
        if (r < 0) {
            fprintf(stderr, "%s: truncated or corrupt entry header\n",
                    lzply_progname);
            fclose(f);
            return EXIT_CORRUPT;
        }
        is_dir = (h.flags & FLAG_ISDIR) != 0;
        switch (view) {
        case VIEW_ARCHIVE:
        case VIEW_MOUNT_ALL:
            match = path_matches_selectors(h.path, selectors, nselectors);
            break;
        case VIEW_MOUNT_DIR:
            match = selector_matches(rel, h.path) &&
                    path_matches_selectors(h.path, selectors, nselectors);
            break;
        case VIEW_MOUNT_FILE:
            match = strcmp(h.path, rel) == 0 &&
                    path_matches_selectors(h.path, selectors, nselectors);
            break;
        }
        if (match && !is_dir) {
            /* Read the stored bytes (the file position is at the
             * start of the entry data) and decode them in memory.
             * Directories have no data and are not checked. */
            uint8_t *stored = NULL, *blob = NULL;
            check_entry_t e;
            memset(&e, 0, sizeof e);
            e.path = xstrdup(h.path);
            e.stored_bits = 8 * h.stored_size;
            e.corrected = -1;
            if ((h.flags & FLAG_BCH) == 0) {
                e.poly_id = 0;
                e.t = 0;
                e.has_ber = 0;
                e.status = "no-ecc";
                n_noecc++;
                /* No decode for a no-ECC entry, but the stored data
                 * must still be skipped so the next header reads
                 * from the right offset. */
                if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                    fprintf(stderr, "%s: truncated archive\n",
                            lzply_progname);
                    free(e.path);
                    free(h.path);
                    fclose(f);
                    return EXIT_CORRUPT;
                }
            } else {
                uint16_t pid = (uint16_t)(h.rs_level |
                                          ((unsigned)h.reserved << 8));
                const bch_poly_t *p = bch_poly_by_id(pid);
                e.poly_id = pid;
                e.t = p ? (int)p->t : 0;
                e.has_ber = 0;
                e.status = "uncorrectable";
                n_bch++;
                if (h.stored_size > 0) {
                    stored = xmalloc(h.stored_size);
                    if (fread(stored, 1, h.stored_size, f) != h.stored_size) {
                        fprintf(stderr, "%s: truncated data for %s\n",
                                lzply_progname, h.path);
                        free(stored);
                        free(e.path);
                        free(h.path);
                        fclose(f);
                        return EXIT_CORRUPT;
                    }
                }
                if (!p) {
                    fprintf(stderr,
                            "%s: warning: %s: unknown BCH poly %04x; "
                            "cannot measure BER\n",
                            lzply_progname, h.path, (unsigned)pid);
                    n_uncorr++;
                } else if (h.stored_size == 0 ||
                           h.stored_size != bch_encoded_len(
                               (size_t)h.blob_size, p)) {
                    fprintf(stderr,
                            "%s: warning: %s: stored size %" PRIu64
                            " != %" PRIu64
                            " expected for BCH poly %04x; cannot measure BER\n",
                            lzply_progname, h.path, h.stored_size,
                            (uint64_t)bch_encoded_len((size_t)h.blob_size, p),
                            (unsigned)pid);
                    n_uncorr++;
                } else {
                    int corrected = 0;
                    blob = xmalloc(h.blob_size ? h.blob_size : 1);
                    if (bch_decode(stored, h.stored_size, h.blob_size,
                                   p, blob, &corrected) != 0) {
                        n_uncorr++;
                    } else {
                        e.corrected = corrected;
                        e.has_ber = 1;
                        e.ber = h.stored_size > 0
                            ? (double)corrected / (double)e.stored_bits
                            : 0.0;
                        e.status = corrected > 0 ? "correctable" : "clean";
                        if (corrected > 0)
                            n_err++;
                        tot_corrected += (uint64_t)corrected;
                        tot_bits += e.stored_bits;
                        if (!worst_path || e.ber > worst_ber) {
                            worst_ber = e.ber;
                            worst_path = e.path;
                        }
                    }
                    free(blob);
                }
                free(stored);
            }
            if (nentries == cap) {
                cap = cap ? cap * 2 : 16;
                entries = xrealloc(entries, cap * sizeof *entries);
            }
            entries[nentries++] = e;
        } else {
            /* Not checked: skip the stored data. */
            if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
                fprintf(stderr, "%s: truncated archive\n", lzply_progname);
                free(h.path);
                fclose(f);
                return EXIT_CORRUPT;
            }
        }
        free(h.path);
    }
    fclose(f);

    /* Overall BER across the BCH entries that decoded. */
    int has_overall = tot_bits > 0;
    double overall_ber = has_overall
        ? (double)tot_corrected / (double)tot_bits : 0.0;

    if (n_uncorr > 0)
        rc = EXIT_CORRUPT;
    else if (have_fail && has_overall && overall_ber > fail_ber)
        rc = EXIT_CORRUPT;
    int warned = have_warn && has_overall && overall_ber > warn_ber;
    const char *status = rc != 0 ? "fail" : warned ? "warning" : "ok";

    if (nentries == 0) {
        if (view == VIEW_MOUNT_FILE) {
            printf("note: %s exists in the mount on %s but is not in "
                   "the on-disk archive yet — it was created in the "
                   "mount and is committed only on unmount or fsync, "
                   "so there is nothing committed to check.\n",
                   rel, mountpoint);
            return 0;
        }
        if (json) {
            print_json(archive, entries, 0, 0, 0, 0.0, 0, NULL, 0.0,
                       0, 0, 0, 0, "ok");
            return 0;
        }
        if (nselectors > 0 || view == VIEW_MOUNT_DIR)
            printf("no entries match the given selector(s)\n");
        else
            printf("no entries in this archive\n");
        return 0;
    }

    if (json) {
        print_json(archive, entries, nentries, tot_corrected, tot_bits,
                   overall_ber, has_overall, worst_path, worst_ber,
                   n_bch, n_noecc, n_err, n_uncorr, status);
        if (rc != 0)
            fprintf(stderr, "%s: FAIL: %s\n", lzply_progname,
                    n_uncorr > 0
                        ? "uncorrectable entries present"
                        : "overall BER above --fail-ber");
        else if (warned)
            fprintf(stderr, "%s: warning: overall BER %.3g exceeds "
                    "--warn-ber %.3g\n",
                    lzply_progname, overall_ber, warn_ber);
    } else {
        size_t i;
        char berbuf[32];
        printf("%-40s %5s %3s %10s %12s %12s %s\n",
               "path", "poly", "t", "corrected", "total_bits", "ber",
               "status");
        for (i = 0; i < nentries; i++) {
            check_entry_t *e = &entries[i];
            char poly[8], t[8], corr[16], bits[16];
            if (e->t > 0) {
                snprintf(poly, sizeof poly, "%04x", (unsigned)e->poly_id);
                snprintf(t, sizeof t, "%d", e->t);
            } else {
                snprintf(poly, sizeof poly, "-");
                snprintf(t, sizeof t, "-");
            }
            if (e->has_ber) {
                snprintf(corr, sizeof corr, "%" PRId64, e->corrected);
                fmt_ber(e->ber, berbuf, sizeof berbuf);
            } else {
                snprintf(corr, sizeof corr, "-");
                snprintf(berbuf, sizeof berbuf, "-");
            }
            snprintf(bits, sizeof bits, "%" PRIu64, e->stored_bits);
            printf("%-40s %5s %3s %10s %12s %12s %s\n",
                   e->path, poly, t, corr, bits, berbuf, e->status);
        }
        printf("%" PRIu64 " entries checked (%" PRIu64 " BCH, %" PRIu64
               " no-ECC)\n",
               (uint64_t)nentries, (uint64_t)n_bch, (uint64_t)n_noecc);
        printf("with errors: %" PRIu64 ", uncorrectable: %" PRIu64 "\n",
               (uint64_t)n_err, (uint64_t)n_uncorr);
        printf("total corrected: %" PRIu64 " bits over %" PRIu64
               " total stored bits\n",
               tot_corrected, tot_bits);
        if (has_overall) {
            fmt_ber(overall_ber, berbuf, sizeof berbuf);
            printf("overall BER: %s", berbuf);
            if (worst_path) {
                fmt_ber(worst_ber, berbuf, sizeof berbuf);
                printf(" (worst: %s %s)", worst_path, berbuf);
            }
            printf("\n");
        } else {
            printf("overall BER: n/a (no decodable BCH entries)\n");
        }
        if (warned)
            printf("warning: overall BER %.3g exceeds --warn-ber %.3g\n",
                   overall_ber, warn_ber);
        if (rc != 0) {
            if (n_uncorr > 0)
                printf("FAIL: %" PRIu64
                       " uncorrectable entr%s — data-loss risk. Run "
                       "lzply_heal, then lzply -t to fully verify.\n",
                       (uint64_t)n_uncorr, n_uncorr == 1 ? "y" : "ies");
            else
                printf("FAIL: overall BER %.3g exceeds --fail-ber %.3g. "
                       "Run lzply_heal, then lzply -t to fully verify.\n",
                       overall_ber, fail_ber);
        }
        printf("BER = corrected bit errors / total stored bits (8 x "
               "stored size), as seen by the BCH decoder on the stored "
               "codeword. No-ECC entries cannot be measured.\n");
    }
    for (i = 0; (size_t)i < nentries; i++)
        free(entries[i].path);
    free(entries);
    free(archive);
    free(mountpoint);
    free(rel);
    return rc;
}

lzply_refresh.c

Platter refresher — rewrites a file (or every regular file under a directory / mount point) over itself in place, same inode, with SHA-256 verification before and after

/* lzply_refresh.c - rewrite a file over itself, in place, to refresh
 * the magnetic signal on older spinning disks.
 *
 *   lzply_refresh <path> [n]
 *
 * n = number of rewrite passes, 1-3, default 1. The whole file is
 * read into memory, then each pass opens the file O_WRONLY (same
 * inode — never deleted and recreated), writes the bytes back from
 * offset 0, and fsyncs. The point is to rewrite the same blocks so
 * the magnetic signal on the platter is refreshed.
 *
 * Verification: SHA-256 of the file before the first pass and after
 * the last pass must match; both hashes are reported. If the content
 * changed, that is an error (exit non-zero).
 *
 * The path may be a single file, a directory, or a mount point (an
 * lzply_mount mount, or any directory — directories are refreshed
 * recursively). For a directory, every regular file under it is
 * refreshed with the same pass count; symlinks and special files are
 * skipped, the same rule as `lzply -c`. A mount point is detected
 * via the same mount resolution as lzply_stat (/proc/mounts) and
 * noted in the output.
 *
 * A file inside an lzply_mount mount works: the write goes through
 * FUSE and the entry is re-encoded on repack, which also refreshes
 * the archive. But an .lzply archive file that is currently mounted
 * is refused (same rule as lzply_heal — modifying the archive under
 * a live mount corrupts the daemon's view).
 *
 * Caveats: on copy-on-write filesystems (btrfs, ZFS) an overwrite
 * may allocate new blocks rather than rewriting the same sectors,
 * so the platter refresh may not happen — this tool is aimed at
 * traditional overwrite filesystems (ext4) and older spinning
 * disks. On SSDs wear-levelling means a rewrite does not hit the
 * same cells, so it is specifically for older physical (magnetic)
 * drives. The whole file is buffered in memory, like the rest of
 * the lzply family. */
#define _XOPEN_SOURCE 500
#define _DEFAULT_SOURCE
#include <errno.h>
#include <ftw.h>
#include <fcntl.h>
#include "sha256.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "lzply_lib.h"
#include "lzply_util.h"

static void usage(const char *prog)
{
    fprintf(stderr,
            "usage: %s <path> [n]\n"
            "  <path> may be a file, a directory, or a mount point.\n"
            "  n = rewrite passes, 1-3, default 1. n outside 1..3 is a\n"
            "  usage error.\n"
            "  The file is read into memory, then each pass rewrites it\n"
            "  in place (same inode: O_WRONLY, write from offset 0,\n"
            "  fsync). SHA-256 before the first pass and after the last\n"
            "  pass must match; both hashes are reported.\n"
            "  A directory (or mount point) is refreshed recursively:\n"
            "  every regular file under it, symlinks and special files\n"
            "  skipped. An .lzply archive file that is currently\n"
            "  mounted is refused.\n"
            "  Caveats: copy-on-write filesystems (btrfs, ZFS) may\n"
            "  allocate new blocks instead of rewriting the same\n"
            "  sectors, and SSD wear-levelling means a rewrite does\n"
            "  not hit the same cells — this is for ext4-style\n"
            "  overwrite filesystems on older spinning disks.\n",
            prog);
}

static void sha256_hex(const unsigned char *data, size_t len,
                       char out[65])
{
    unsigned char md[32];
    static const char hexd[] = "0123456789abcdef";
    unsigned int i;

    lzply_sha256(data, len, md);
    for (i = 0; i < 32; i++) {
        out[2 * i] = hexd[md[i] >> 4];
        out[2 * i + 1] = hexd[md[i] & 0xf];
    }
    out[64] = '\0';
}

/* Refresh one regular file. Returns 0 on success (content verified
 * unchanged), -1 on any failure. Prints a per-file report line. */
static int refresh_file(const char *path, int passes)
{
    struct stat st;
    unsigned char *buf = NULL;
    char before[65], after[65];
    int fd, pass;
    size_t done = 0;

    if (lstat(path, &st) != 0) {
        fprintf(stderr, "%s: cannot stat %s: %s\n", lzply_progname,
                path, strerror(errno));
        return -1;
    }
    if (!S_ISREG(st.st_mode)) {
        fprintf(stderr, "%s: skipping %s (not a regular file)\n",
                lzply_progname, path);
        return -1;
    }
    if (st.st_size < 0) {
        fprintf(stderr, "%s: %s has a negative size; refusing\n",
                lzply_progname, path);
        return -1;
    }

    buf = malloc(st.st_size > 0 ? (size_t)st.st_size : 1);
    if (!buf) {
        fprintf(stderr, "%s: out of memory reading %s\n",
                lzply_progname, path);
        return -1;
    }

    fd = open(path, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname,
                path, strerror(errno));
        free(buf);
        return -1;
    }
    done = 0;
    while (done < (size_t)st.st_size) {
        ssize_t r = read(fd, buf + done, (size_t)st.st_size - done);
        if (r < 0) {
            if (errno == EINTR)
                continue;
            fprintf(stderr, "%s: cannot read %s: %s\n", lzply_progname,
                    path, strerror(errno));
            close(fd);
            free(buf);
            return -1;
        }
        if (r == 0)
            break; /* file shrank mid-read; caught by the size check below */
        done += (size_t)r;
    }
    close(fd);
    if (done != (size_t)st.st_size) {
        fprintf(stderr,
                "%s: %s changed size while reading (%zu of %lld bytes); "
                "refusing to refresh a moving target\n",
                lzply_progname, path, done, (long long)st.st_size);
        free(buf);
        return -1;
    }
    sha256_hex(buf, (size_t)st.st_size, before);

    for (pass = 0; pass < passes; pass++) {
        size_t off = 0;
        fd = open(path, O_WRONLY); /* same inode, no O_TRUNC */
        if (fd < 0) {
            fprintf(stderr, "%s: cannot open %s for writing: %s\n",
                    lzply_progname, path, strerror(errno));
            free(buf);
            return -1;
        }
        while (off < (size_t)st.st_size) {
            ssize_t w = pwrite(fd, buf + off,
                               (size_t)st.st_size - off, (off_t)off);
            if (w < 0) {
                if (errno == EINTR)
                    continue;
                fprintf(stderr, "%s: cannot write %s: %s\n",
                        lzply_progname, path, strerror(errno));
                close(fd);
                free(buf);
                return -1;
            }
            off += (size_t)w;
        }
        if (fsync(fd) != 0) {
            fprintf(stderr, "%s: fsync failed on %s: %s\n",
                    lzply_progname, path, strerror(errno));
            close(fd);
            free(buf);
            return -1;
        }
        if (close(fd) != 0) {
            fprintf(stderr, "%s: close failed on %s: %s\n",
                    lzply_progname, path, strerror(errno));
            free(buf);
            return -1;
        }
        /* The file must not have changed size under us. */
        if (stat(path, &st) != 0 || st.st_size < 0 ||
            (size_t)st.st_size != done) {
            fprintf(stderr,
                    "%s: %s changed size during refresh; refusing\n",
                    lzply_progname, path);
            free(buf);
            return -1;
        }
    }

    /* Re-read and verify the content is byte-identical. */
    {
        unsigned char *back = malloc(done > 0 ? done : 1);
        size_t rdone = 0;
        if (!back) {
            fprintf(stderr, "%s: out of memory verifying %s\n",
                    lzply_progname, path);
            free(buf);
            return -1;
        }
        fd = open(path, O_RDONLY);
        if (fd < 0) {
            fprintf(stderr, "%s: cannot re-open %s: %s\n",
                    lzply_progname, path, strerror(errno));
            free(back);
            free(buf);
            return -1;
        }
        while (rdone < done) {
            ssize_t r = read(fd, back + rdone, done - rdone);
            if (r < 0) {
                if (errno == EINTR)
                    continue;
                fprintf(stderr, "%s: cannot re-read %s: %s\n",
                        lzply_progname, path, strerror(errno));
                close(fd);
                free(back);
                free(buf);
                return -1;
            }
            if (r == 0)
                break;
            rdone += (size_t)r;
        }
        close(fd);
        if (rdone != done) {
            fprintf(stderr,
                    "%s: %s changed size during verification; refusing\n",
                    lzply_progname, path);
            free(back);
            free(buf);
            return -1;
        }
        sha256_hex(back, done, after);
        free(back);
    }
    free(buf);

    if (strcmp(before, after) != 0) {
        fprintf(stderr,
                "%s: %s CONTENT CHANGED during refresh!\n"
                "  sha256 before: %s\n"
                "  sha256 after:  %s\n",
                lzply_progname, path, before, after);
        return -1;
    }
    printf("%s: %lld bytes, %d pass%s, sha256 %s, verified unchanged\n",
           path, (long long)done, passes, passes == 1 ? "" : "es",
           before);
    return 0;
}

/* Recursive (directory / mount point) state for the nftw callback. */
static int g_passes;
static size_t g_refreshed, g_skipped, g_failed;

static int refresh_nftw_cb(const char *fpath, const struct stat *sb,
                           int typeflag, struct FTW *ftwbuf)
{
    (void)ftwbuf;
    switch (typeflag) {
    case FTW_F:
        if (!S_ISREG(sb->st_mode)) {
            /* FTW_F should be a regular file; be safe anyway. */
            g_skipped++;
            printf("skipped (not a regular file): %s\n", fpath);
            return 0;
        }
        if (refresh_file(fpath, g_passes) == 0)
            g_refreshed++;
        else
            g_failed++;
        return 0;
    case FTW_SL:
    case FTW_SLN:
        g_skipped++;
        printf("skipped (symlink): %s\n", fpath);
        return 0;
    case FTW_D:
    case FTW_DP:
        return 0;
    case FTW_NS:
    case FTW_DNR:
    default:
        g_skipped++;
        fprintf(stderr, "%s: cannot access %s; skipped\n",
                lzply_progname, fpath);
        return 0;
    }
}

int main(int argc, char **argv)
{
    const char *path;
    int passes = 1;
    struct stat st;
    char *canon = NULL;

    lzply_set_progname(argv[0]);
    if (argc < 2 || argc > 3) {
        usage(lzply_progname);
        return EXIT_USAGE;
    }
    path = argv[1];
    if (argc == 3) {
        char *end = NULL;
        long n = strtol(argv[2], &end, 10);
        if (end == argv[2] || *end != '\0' || n < 1 || n > 3) {
            fprintf(stderr,
                    "%s: invalid pass count '%s' (must be 1, 2 or 3)\n",
                    lzply_progname, argv[2]);
            usage(lzply_progname);
            return EXIT_USAGE;
        }
        passes = (int)n;
    }

    if (lstat(path, &st) != 0) {
        fprintf(stderr, "%s: cannot stat %s: %s\n", lzply_progname,
                path, strerror(errno));
        return EXIT_IO;
    }

    if (S_ISREG(st.st_mode)) {
        /* A mounted archive file must not be refreshed in place:
         * same rule as lzply_heal — modifying the archive under a
         * live mount corrupts the daemon's view. */
        canon = canon_path(path);
        if (canon) {
            char *mp = NULL;
            if (archive_is_mounted(canon, &mp) == 1) {
                fprintf(stderr,
                        "%s: %s is mounted on %s; unmount it before "
                        "refreshing (refreshing under a live mount "
                        "would corrupt the daemon's in-memory index)\n",
                        lzply_progname, path, mp);
                free(mp);
                free(canon);
                return EXIT_IO;
            }
            free(canon);
        }
        /* A file inside a mount: note it, the write goes through FUSE
         * and the entry is re-encoded on repack. */
        {
            char *arch = NULL, *mpoint = NULL, *rel = NULL;
            if (mount_resolve(path, &arch, &mpoint, &rel) == 0) {
                printf("note: %s is inside mount %s (archive %s); "
                       "the write goes through FUSE and the entry is "
                       "re-encoded on repack\n",
                       path, mpoint, arch);
                free(arch);
                free(mpoint);
                free(rel);
            }
        }
        return refresh_file(path, passes) == 0 ? 0 : EXIT_IO;
    }

    if (S_ISDIR(st.st_mode)) {
        char *arch = NULL, *mpoint = NULL, *rel = NULL;
        int in_mount = (mount_resolve(path, &arch, &mpoint, &rel) == 0);
        if (in_mount && rel && rel[0] == '\0')
            printf("refreshing mount at %s: (archive %s)\n",
                   mpoint, arch);
        else if (in_mount)
            printf("refreshing directory %s inside mount %s "
                   "(archive %s)\n", path, mpoint, arch);
        else
            printf("refreshing directory %s:\n", path);
        free(arch);
        free(mpoint);
        free(rel);

        g_passes = passes;
        g_refreshed = g_skipped = g_failed = 0;
        if (nftw(path, refresh_nftw_cb, 20, FTW_PHYS) != 0) {
            fprintf(stderr, "%s: cannot walk %s: %s\n", lzply_progname,
                    path, strerror(errno));
            return EXIT_IO;
        }
        printf("summary: %zu file%s refreshed (%d pass%s each), "
               "%zu skipped, %zu failed\n",
               g_refreshed, g_refreshed == 1 ? "" : "s",
               passes, passes == 1 ? "" : "es",
               g_skipped, g_failed);
        return g_failed == 0 ? 0 : EXIT_IO;
    }

    fprintf(stderr,
            "%s: %s is not a regular file or a directory "
            "(symlinks and special files are skipped)\n",
            lzply_progname, path);
    usage(lzply_progname);
    return EXIT_USAGE;
}

lzply_util.c

Shared helper for stat, heal, check and refresh — resolve a mount point or in-mount path to its backing archive via /proc/mounts and a /proc cmdline scan

/* lzply_util.c - shared helpers for lzply_stat and lzply_mount_heal.
 *
 * Mount resolution works in two steps. /proc/mounts tells us which
 * mount points are fuse.lzply_mount filesystems (the source field is the
 * literal "lzply_mount", so the fstype is the reliable marker). The
 * backing archive is not in /proc/mounts, so the daemon is found by
 * scanning /proc for a process whose argv[0] is lzply_mount and whose
 * positional arguments are <archive> <mountpoint> — the same two
 * arguments lzply_mount takes on the command line. Options between
 * argv[0] and the archive (notably "-o rw" when the mount went
 * through mount -t lzply) are skipped, and relative paths are
 * resolved against the daemon's cwd. */
#define _GNU_SOURCE
#include <ctype.h>
#include <dirent.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "lzply_lib.h"
#include "lzply_util.h"

const char *human_size(uint64_t n, char *buf, size_t bufsz)
{
    static const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
    double v = (double)n;
    int u = 0;
    while (v >= 1024.0 && u < 4) {
        v /= 1024.0;
        u++;
    }
    if (u == 0)
        snprintf(buf, bufsz, "%" PRIu64 " B", n);
    else
        snprintf(buf, bufsz, "%.1f %s", v, units[u]);
    return buf;
}

char *canon_path(const char *path)
{
    char *r = realpath(path, NULL);
    if (r)
        return r;
    /* Split off the last component and canonicalise the parent. */
    const char *slash = strrchr(path, '/');
    if (!slash)
        return xstrdup(path);   /* bare name; leave as-is */
    if (slash == path)
        return xstrdup(path);   /* "/name": parent is the root */
    size_t dlen = (size_t)(slash - path);
    char *dir = xmalloc(dlen + 1);
    memcpy(dir, path, dlen);
    dir[dlen] = '\0';
    char *cd = canon_path(dir);
    free(dir);
    if (!cd)
        return NULL;
    size_t cl = strlen(cd);
    int need_slash = (cl == 0 || cd[cl - 1] != '/');
    char *out = xmalloc(cl + (size_t)need_slash + strlen(slash + 1) + 1);
    strcpy(out, cd);
    if (need_slash)
        strcat(out, "/");
    strcat(out, slash + 1);
    free(cd);
    return out;
}

/* ------------------------------------------------------------------ */
/* /proc/mounts                                                        */
/* ------------------------------------------------------------------ */

/* Unescape a /proc/mounts field (\040 space, \011 tab, \012 newline,
 * \134 backslash). Returns a malloced string. */
static char *unescape_field(const char *s, size_t len)
{
    char *out = xmalloc(len + 1);
    size_t o = 0, i = 0;
    while (i < len) {
        if (s[i] == '\\' && i + 4 <= len &&
            s[i + 1] >= '0' && s[i + 1] <= '7' &&
            s[i + 2] >= '0' && s[i + 2] <= '7' &&
            s[i + 3] >= '0' && s[i + 3] <= '7') {
            out[o++] = (char)((s[i + 1] - '0') * 64 +
                              (s[i + 2] - '0') * 8 + (s[i + 3] - '0'));
            i += 4;
        } else {
            out[o++] = s[i++];
        }
    }
    out[o] = '\0';
    return out;
}

/* Read /proc/mounts and return the mount points whose fstype is
 * fuse.lzply_mount. Returns 0 on success (*out malloced array of malloced
 * strings, *n_out entries), -1 if /proc/mounts cannot be read. */
static int read_lzply_mount_mounts(char ***out, size_t *n_out)
{
    FILE *f = fopen("/proc/mounts", "r");
    char *line = NULL;
    size_t cap = 0;
    ssize_t len;
    char **mounts = NULL;
    size_t n = 0, mcap = 0;
    *out = NULL;
    *n_out = 0;
    if (!f)
        return -1;
    while ((len = getline(&line, &cap, f)) >= 0) {
        /* Fields: source, mountpoint, fstype, options, ... */
        char *sp1 = strchr(line, ' ');
        char *sp2, *sp3;
        char *mp, *fstype;
        if (!sp1)
            continue;
        sp2 = strchr(sp1 + 1, ' ');
        if (!sp2)
            continue;
        sp3 = strchr(sp2 + 1, ' ');
        if (!sp3)
            continue;
        mp = unescape_field(sp1 + 1, (size_t)(sp2 - (sp1 + 1)));
        fstype = unescape_field(sp2 + 1, (size_t)(sp3 - (sp2 + 1)));
        if (strcmp(fstype, "fuse.lzply_mount") == 0) {
            if (n == mcap) {
                mcap = mcap ? mcap * 2 : 8;
                mounts = xrealloc(mounts, mcap * sizeof *mounts);
            }
            mounts[n++] = mp;
            mp = NULL;
        }
        free(mp);
        free(fstype);
    }
    free(line);
    fclose(f);
    *out = mounts;
    *n_out = n;
    return 0;
}

/* ------------------------------------------------------------------ */
/* /proc cmdline scan for the lzply_mount daemon                            */
/* ------------------------------------------------------------------ */

/* Resolve a possibly-relative daemon argument against the daemon's
 * cwd. Returns a malloced string. */
static char *resolve_against_cwd(const char *arg, const char *cwd)
{
    if (arg[0] == '/' || !cwd)
        return xstrdup(arg);
    size_t cl = strlen(cwd);
    int need_slash = (cl == 0 || cwd[cl - 1] != '/');
    char *out = xmalloc(cl + (size_t)need_slash + strlen(arg) + 1);
    strcpy(out, cwd);
    if (need_slash)
        strcat(out, "/");
    strcat(out, arg);
    return out;
}

/* Resolve a raw daemon argument against a cwd (empty cwd = leave as-is).
 * libfuse changes the daemon's cwd to "/" at mount time, so a daemon
 * started with a relative path needs its args resolved against the
 * cwd it was started from, not the one it has now. */
static char *resolve_arg(const char *arg, const char *cwd)
{
    if (arg[0] == '/' || !cwd || cwd[0] == '\0')
        return xstrdup(arg);
    return resolve_against_cwd(arg, cwd);
}


static int all_digits(const char *s)
{
    if (!*s)
        return 0;
    for (; *s; s++)
        if (!isdigit((unsigned char)*s))
            return 0;
    return 1;
}

/* Parse /proc/<pid>/cmdline as an lzply_mount invocation. On success
 * returns 0 and mallocs *archive_out and *mountpoint_out (the two
 * positional arguments, as given on the daemon's command line) and
 * *cwd_out (the daemon's cwd, "" if it could not be read). Callers
 * resolve the relative args themselves: the daemon's cwd is "/" after
 * libfuse's mount-time chdir, so it is only one candidate. Returns -1
 * if this pid is not an lzply_mount daemon. */
static int parse_lzply_mount_cmdline(const char *pid, char **archive_out,
                                char **mountpoint_out, char **cwd_out)
{
    char path[64];
    FILE *f;
    uint8_t *buf;
    size_t n;
    char **argv = NULL;
    size_t argc = 0, acap = 0, i;
    const char *base;
    const char *pos[2] = {NULL, NULL};
    int npos = 0;
    char cwd[PATH_MAX];
    char linkpath[64];
    ssize_t cl;

    snprintf(path, sizeof path, "/proc/%s/cmdline", pid);
    f = fopen(path, "rb");
    if (!f)
        return -1;
    buf = xmalloc(65536);
    n = fread(buf, 1, 65535, f);
    fclose(f);
    if (n == 0) {
        free(buf);
        return -1;
    }
    i = 0;
    while (i < n) {
        size_t len = strlen((char *)buf + i);
        if (len == 0)
            break;
        if (argc == acap) {
            acap = acap ? acap * 2 : 16;
            argv = xrealloc(argv, acap * sizeof *argv);
        }
        argv[argc++] = (char *)buf + i;
        i += len + 1;
    }
    if (argc == 0) {
        free(argv);
        free(buf);
        return -1;
    }
    base = strrchr(argv[0], '/');
    base = base ? base + 1 : argv[0];
    if (strcmp(base, "lzply_mount") != 0) {
        free(argv);
        free(buf);
        return -1;
    }
    /* Positional arguments are <archive> <mountpoint>. Skip options:
     * -o/-e/-cache take a value; any other dash option and
     * poly=NN are single tokens. (A mount through mount -t lzply
     * shows up as "lzply_mount -o rw <archive> <mountpoint>".) */
    for (i = 1; i < argc && npos < 2; i++) {
        const char *a = argv[i];
        if (strcmp(a, "-o") == 0 || strcmp(a, "-e") == 0 ||
            strcmp(a, "-cache") == 0) {
            i++;    /* skip the value as well */
            continue;
        }
        if (a[0] == '-')
            continue;
        if (strncmp(a, "poly=", 5) == 0)
            continue;
        pos[npos++] = a;
    }
    if (npos < 2) {
        free(argv);
        free(buf);
        return -1;
    }
    snprintf(linkpath, sizeof linkpath, "/proc/%s/cwd", pid);
    cl = readlink(linkpath, cwd, sizeof cwd - 1);
    if (cl < 0)
        cwd[0] = '\0';
    else
        cwd[cl] = '\0';
    *archive_out = xstrdup(pos[0]);
    *mountpoint_out = xstrdup(pos[1]);
    *cwd_out = xstrdup(cwd);
    free(argv);
    free(buf);
    return 0;
}

/* Find the lzply_mount daemon serving this mount point. On success
 * returns 0 and mallocs *archive_out (canonicalised). */
static int daemon_archive_for_mount(const char *mountpoint,
                                    char **archive_out)
{
    DIR *d = opendir("/proc");
    struct dirent *de;
    char *cmp = canon_path(mountpoint);
    char own[PATH_MAX];
    if (!d) {
        free(cmp);
        return -1;
    }
    if (getcwd(own, sizeof own) == NULL)
        own[0] = '\0';
    while ((de = readdir(d)) != NULL) {
        char *arch = NULL, *mp = NULL, *dcwd = NULL;
        int t;
        if (!all_digits(de->d_name))
            continue;
        if (parse_lzply_mount_cmdline(de->d_name, &arch, &mp, &dcwd) != 0)
            continue;
        /* The daemon's args may be relative. Try them against the
         * daemon's cwd first, then against our own: libfuse changes
         * the daemon's cwd to "/" at mount time, so the daemon-cwd
         * resolution can point at the wrong existing directory
         * (e.g. a relative mountpoint "mnt" resolves to "/mnt"). */
        for (t = 0; t < 2; t++) {
            const char *base = (t == 0) ? dcwd : own;
            char *rmp = resolve_arg(mp, base);
            char *camp = canon_path(rmp);
            free(rmp);
            if (camp && cmp && strcmp(camp, cmp) == 0) {
                char *rarch = resolve_arg(arch, base);
                char *carch = canon_path(rarch);
                free(rarch);
                free(camp);
                free(arch);
                free(mp);
                free(dcwd);
                closedir(d);
                free(cmp);
                *archive_out = carch;
                return 0;
            }
            free(camp);
        }
        free(arch);
        free(mp);
        free(dcwd);
    }
    closedir(d);
    free(cmp);
    return -1;
}

int mount_resolve(const char *path, char **archive_out,
                  char **mountpoint_out, char **rel_out)
{
    char *cpath = canon_path(path);
    char **mounts = NULL;
    size_t nmounts = 0, i;
    const char *best = NULL;
    size_t best_len = 0;
    char *mp, *archive, *rel;

    if (!cpath)
        return -1;
    if (read_lzply_mount_mounts(&mounts, &nmounts) != 0) {
        free(cpath);
        return -1;
    }
    /* Longest mount point that is a prefix of the path (component
     * boundary: equal, or followed by '/'). */
    for (i = 0; i < nmounts; i++) {
        size_t ml = strlen(mounts[i]);
        if ((strcmp(cpath, mounts[i]) == 0 ||
             (strncmp(cpath, mounts[i], ml) == 0 && cpath[ml] == '/')) &&
            ml > best_len) {
            best = mounts[i];
            best_len = ml;
        }
    }
    if (!best) {
        for (i = 0; i < nmounts; i++)
            free(mounts[i]);
        free(mounts);
        free(cpath);
        return -1;
    }
    mp = xstrdup(best);
    for (i = 0; i < nmounts; i++)
        free(mounts[i]);
    free(mounts);
    rel = xstrdup(cpath + best_len);
    free(cpath);
    if (rel[0] == '/')
        memmove(rel, rel + 1, strlen(rel));   /* drop leading '/' */
    if (daemon_archive_for_mount(mp, &archive) != 0) {
        free(mp);
        free(rel);
        return -1;
    }
    *archive_out = archive;
    *mountpoint_out = mp;
    *rel_out = rel;
    return 0;
}

int archive_is_mounted(const char *archive, char **mountpoint_out)
{
    DIR *d = opendir("/proc");
    struct dirent *de;
    char *carch = canon_path(archive);
    char own[PATH_MAX];
    if (!d) {
        free(carch);
        return -1;
    }
    if (getcwd(own, sizeof own) == NULL)
        own[0] = '\0';
    while ((de = readdir(d)) != NULL) {
        char *arch = NULL, *mp = NULL, *dcwd = NULL;
        int t;
        if (!all_digits(de->d_name))
            continue;
        if (parse_lzply_mount_cmdline(de->d_name, &arch, &mp, &dcwd) != 0)
            continue;
        /* Try the daemon's cwd first, then our own (see
         * daemon_archive_for_mount: relative daemon args must not be
         * resolved against the daemon's post-mount cwd "/"). */
        for (t = 0; t < 2; t++) {
            const char *base = (t == 0) ? dcwd : own;
            char *rarch = resolve_arg(arch, base);
            char *ca = canon_path(rarch);
            free(rarch);
            if (ca && carch && strcmp(ca, carch) == 0) {
                char *rmp = resolve_arg(mp, base);
                char *cmp = canon_path(rmp);
                free(rmp);
                free(ca);
                free(arch);
                free(mp);
                free(dcwd);
                closedir(d);
                free(carch);
                *mountpoint_out = cmp;
                return 1;
            }
            free(ca);
        }
        free(arch);
        free(mp);
        free(dcwd);
    }
    closedir(d);
    free(carch);
    return 0;
}

lzply_util.h

Header for the stat/heal/check/refresh shared helper

/* lzply_util.h - shared helpers for lzply_stat and lzply_mount_heal.
 *
 * Mount resolution (via /proc/mounts plus a /proc cmdline scan for
 * the lzply_mount daemon) and a human-size formatter. No FUSE, no archive
 * writing — these run anywhere; only the mount tests need a live
 * mount. */
#ifndef LZPLY_UTIL_H
#define LZPLY_UTIL_H

#include <stddef.h>
#include <stdint.h>

const char *human_size(uint64_t n, char *buf, size_t bufsz);

/* Canonicalise a path (like realpath, but tolerates a non-existent
 * trailing component by canonicalising the longest existing prefix).
 * Returned string is malloced. */
char *canon_path(const char *path);

/* Resolve a path to the lzply_mount mount it lives in (or is). On success
 * returns 0 and mallocs *archive_out (the backing archive),
 * *mountpoint_out, and *rel_out (the path relative to the mount
 * point: "" for the mount point itself, otherwise no leading '/').
 * Returns -1 if the path is not in (or at) a fuse.lzply_mount mount, or
 * if the mount's daemon cannot be found. */
int mount_resolve(const char *path, char **archive_out,
                  char **mountpoint_out, char **rel_out);

/* Is this archive currently mounted by an lzply_mount daemon? Returns 1
 * and mallocs *mountpoint_out if yes, 0 if no, -1 on error. */
int archive_is_mounted(const char *archive, char **mountpoint_out);

#endif /* LZPLY_UTIL_H */

bch.c

Binary BCH codec — table-driven remainder, GF(2^m), syndromes, Berlekamp-Massey, Chien search, block splitting

/* bch.c - binary BCH error correction for lzply.
 *
 * Systematic shortened primitive BCH over GF(2), using the 82
 * narrow-sense generators in bch_polys.h (m=7..22, t=1,2,4,8,16,32).
 *
 * ENCODER (remainder / CRC style). A block is D data bytes (k=8D bits)
 * plus r parity bits. The codeword polynomial C(x) = M(x)*x^r + P(x),
 * P(x) = (M(x)*x^r) mod g(x), so C(x) is divisible by g(x). The
 * remainder is computed by a table-driven LFSR (CRC-style): the register
 * is an r-bit value stored LEFT-ALIGNED in a byte array (top bit =
 * bit 7 of rem[0]); for each data byte b,
 *   rem = byteshift(rem) XOR T[rem[0] XOR b],
 * where T[u] = (u(x)*x^r) mod g(x). Feeding the data bytes alone yields
 * P(x) -- the LFSR inherently multiplies by x^r, so NO augmentation
 * (extra zero bits) is fed. The parity bytes ARE the remainder bytes
 * (the last byte's low bits are the zero padding).
 *
 * DECODER. Feed the received codeword (data bytes + r parity bits;
 * the final partial parity byte is fed bit-by-bit so the padding
 * bits are never fed) into the same LFSR, giving R = (E*x^r) mod g,
 * E = error polynomial. R==0 means no error. Otherwise the syndromes
 * are S_j = R(alpha^j) * alpha^(-j*r) for j=1..2t (valid because
 * g(alpha^j)=0, so R(alpha^j) = E(alpha^j)*alpha^(j*r)).
 * Berlekamp-Massey on S_1..S_2t gives the error-locator
 * Lambda(x) = prod (1 + X_p*x), X_p = alpha^(n-1-p) for an error at
 * bit position p (p=0 is the first stored bit, coefficient of
 * x^(n-1)). Chien search evaluates Lambda(alpha^(p-(n-1))) for
 * p=0..n-1; a zero means an error at p, and that bit is flipped.
 * After flipping, the LFSR remainder must be 0 again, else the block
 * is declared uncorrectable. The per-entry SHA-256 in lzply is the
 * final guard against any miscorrection.
 *
 * GF(2^m) arithmetic: elements are uint32_t (< 2^m). The primitive
 * polynomial P_m is the t=1 generator for that m (bch_prim_poly).
 * Multiply-by-alpha is a shift + conditional XOR with the low m bits
 * of P_m. General multiplication is shift-and-xor (used for the
 * syndrome/BM, which need few mults). Chien search needs many mults,
 * so it uses log/exp tables built on demand and cached per m.
 */
#include <stdlib.h>
#include <string.h>
#include "bch.h"

/* ------------------------------------------------------------------ */
/* polynomial lookup                                                   */
/* ------------------------------------------------------------------ */

const bch_poly_t *bch_poly_by_id(uint16_t id)
{
    for (int i = 0; i < BCH_NPOLYS; i++)
        if (bch_polys[i].id == id)
            return &bch_polys[i];
    return NULL;
}

static int t_index(int t)
{
    switch (t) {
    case 1:  return 0;
    case 2:  return 1;
    case 4:  return 2;
    case 8:  return 3;
    case 16: return 4;
    case 32: return 5;
    default: return -1;
    }
}

const bch_poly_t *bch_poly_for_data(size_t data_bytes, int t)
{
    int ti = t_index(t);
    if (ti < 0)
        return NULL;
    /* smallest m with a poly for (m,t) whose codeword can hold the data:
     * N >= 8*data_bytes + t*m. */
    for (int m = BCH_MIN_M; m <= BCH_MAX_M; m++) {
        uint16_t id = bch_poly_by_mt[m - BCH_MIN_M][ti];
        if (!id)
            continue;
        const bch_poly_t *p = bch_poly_by_id(id);
        uint64_t need = (uint64_t)8 * data_bytes + (uint64_t)t * m;
        if ((uint64_t)p->parent >= need)
            return p;
    }
    return NULL;
}

size_t bch_max_data(const bch_poly_t *p)
{
    /* floor((N - r)/8) data bytes fit in one codeword of this parent. */
    return (size_t)((p->parent - p->r) / 8);
}

size_t bch_block_stored_len(size_t data_len, const bch_poly_t *p)
{
    return data_len + (size_t)((p->r + 7) / 8);
}

size_t bch_encoded_len(size_t len, const bch_poly_t *p)
{
    size_t maxd = bch_max_data(p);
    if (len == 0)
        return bch_block_stored_len(0, p);
    size_t blocks = (len + maxd - 1) / maxd;
    size_t full = blocks - 1;
    size_t last = len - full * maxd;
    return full * bch_block_stored_len(maxd, p) + bch_block_stored_len(last, p);
}

int bch_t_for_level(int level)
{
    switch (level) {
    case 0: return 0;
    case 1: return 1;
    case 2: return 2;
    case 3: return 4;
    case 4: return 8;
    case 5: return 16;
    case 6: return 32;
    case 7: return 32;
    default: return -1;
    }
}

/* ------------------------------------------------------------------ */
/* remainder (table-driven LFSR)                                       */
/*                                                                     */
/* The remainder is an r-bit value stored LEFT-ALIGNED in rem[0..nb-1]:
 * bit (r-1) (coefficient of x^(r-1)) is bit 7 of rem[0]; bit i is at
 * byte (r-1-i)/8, bit 7-((r-1-i)%8). The low (nb*8-r) bits of the
 * last byte are always zero.                                          */
/* ------------------------------------------------------------------ */

typedef struct {
    const bch_poly_t *p;
    int r;              /* parity bits */
    int nb;             /* remainder bytes = (r+7)/8 */
    uint8_t glow[89];   /* low r bits of g(x), left-aligned */
    uint8_t *table;     /* 256 * nb bytes: T[u] = (u(x)*x^r) mod g(x) */
} bch_ctx_t;

static void rem_set_bit(uint8_t *rem, int r, int i)
{
    int byte = (r - 1 - i) / 8;
    int bit = 7 - ((r - 1 - i) % 8);
    rem[byte] |= (uint8_t)(1u << bit);
}

/* (rem_get_bit removed: rem_eval iterates the bytes directly.) */

/* shift the left-aligned remainder left by one bit (top bit dropped). */
static void rem_shl1(uint8_t *rem, int nb)
{
    for (int i = 0; i < nb; i++)
        rem[i] = (uint8_t)((rem[i] << 1) | (i + 1 < nb ? (rem[i + 1] >> 7) : 0));
}

/* one bit-step of the LFSR: feed input bit m. */
static void rem_bitstep(uint8_t *rem, int m, const uint8_t *glow, int nb)
{
    int fb = ((rem[0] >> 7) & 1) ^ (m & 1);
    rem_shl1(rem, nb);
    if (fb)
        for (int i = 0; i < nb; i++)
            rem[i] ^= glow[i];
}

static bch_ctx_t *bch_ctx_new(const bch_poly_t *p)
{
    bch_ctx_t *c = calloc(1, sizeof(*c));
    if (!c)
        return NULL;
    c->p = p;
    c->r = p->r;
    c->nb = (p->r + 7) / 8;
    c->table = malloc((size_t)256 * c->nb);
    if (!c->table) {
        free(c);
        return NULL;
    }
    /* glow: low r bits of g(x). Generator bytes are LSB-first:
     * gen[j] holds bits 8j..8j+7, so g_i = (gen[i/8] >> (i%8)) & 1. */
    const uint8_t *gen = bch_poly_bytes + p->off;
    for (int i = 0; i < p->r; i++) {
        if ((gen[i / 8] >> (i % 8)) & 1)
            rem_set_bit(c->glow, p->r, i);
    }
    /* T[u]: feed u's 8 bits (MSB first) into the LFSR from rem=0. */
    for (int u = 0; u < 256; u++) {
        uint8_t *t = c->table + (size_t)u * c->nb;
        memset(t, 0, c->nb);
        for (int b = 7; b >= 0; b--)
            rem_bitstep(t, (u >> b) & 1, c->glow, c->nb);
    }
    return c;
}

static void bch_ctx_free(bch_ctx_t *c)
{
    if (!c)
        return;
    free(c->table);
    free(c);
}

/* table-driven update: feed one whole byte into the remainder. */
static void rem_feed_byte(uint8_t *rem, uint8_t b, const bch_ctx_t *c)
{
    int idx = rem[0] ^ b;
    /* shift left by 8 bits (one byte) */
    for (int i = 0; i < c->nb - 1; i++)
        rem[i] = rem[i + 1];
    rem[c->nb - 1] = 0;
    const uint8_t *t = c->table + (size_t)idx * c->nb;
    for (int i = 0; i < c->nb; i++)
        rem[i] ^= t[i];
}

/* remainder of the data bytes alone (== parity P(x)). */
static void rem_of_data(const uint8_t *data, size_t len, const bch_ctx_t *c,
                        uint8_t *rem)
{
    memset(rem, 0, c->nb);
    for (size_t i = 0; i < len; i++)
        rem_feed_byte(rem, data[i], c);
}

/* remainder of a codeword: data bytes (whole) + parity bits (r bits).
 * The parity bits are the first r bits of the parity bytes (MSB first);
 * the padding bits in the final byte are never fed. */
static void rem_of_codeword(const uint8_t *data, size_t data_len,
                            const uint8_t *par, const bch_ctx_t *c,
                            uint8_t *rem)
{
    memset(rem, 0, c->nb);
    for (size_t i = 0; i < data_len; i++)
        rem_feed_byte(rem, data[i], c);
    int r = c->r;
    int whole = r / 8;
    for (int i = 0; i < whole; i++)
        rem_feed_byte(rem, par[i], c);
    for (int b = 7; b >= 8 - (r % 8) && (r % 8); b--)
        rem_bitstep(rem, (par[whole] >> b) & 1, c->glow, c->nb);
}

static int rem_is_zero(const uint8_t *rem, int nb)
{
    for (int i = 0; i < nb; i++)
        if (rem[i])
            return 0;
    return 1;
}

/* brute-force remainder: bit-by-bit long division of the data polynomial
 * (MSB first) by g(x). Used by the unit test to cross-check the table. */
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
                             const bch_poly_t *p, uint8_t *rem_out)
{
    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = calloc(1, c->nb);
    if (!rem) {
        bch_ctx_free(c);
        return -1;
    }
    for (size_t i = 0; i < data_len; i++)
        for (int b = 7; b >= 0; b--)
            rem_bitstep(rem, (data[i] >> b) & 1, c->glow, c->nb);
    memcpy(rem_out, rem, c->nb);
    free(rem);
    bch_ctx_free(c);
    return 0;
}

/* ------------------------------------------------------------------ */
/* GF(2^m) arithmetic                                                  */
/* ------------------------------------------------------------------ */

static uint32_t gf_mul_slow(uint32_t a, uint32_t b, uint32_t P, int m)
{
    uint32_t mask = (m >= 32) ? 0xffffffffu : ((1u << m) - 1);
    uint32_t plow = P & mask;
    uint32_t r = 0;
    while (b) {
        if (b & 1)
            r ^= a;
        b >>= 1;
        uint32_t top = (a >> (m - 1)) & 1u;
        a = (a << 1) & mask;
        if (top)
            a ^= plow;
    }
    return r;
}

static uint32_t gf_mul_alpha(uint32_t a, uint32_t P, int m)
{
    uint32_t mask = (m >= 32) ? 0xffffffffu : ((1u << m) - 1);
    uint32_t top = (a >> (m - 1)) & 1u;
    a = (a << 1) & mask;
    if (top)
        a ^= (P & mask);
    return a;
}

static uint32_t gf_pow_slow(uint32_t a, uint32_t e, uint32_t P, int m)
{
    uint32_t r = 1;
    while (e) {
        if (e & 1)
            r = gf_mul_slow(r, a, P, m);
        a = gf_mul_slow(a, a, P, m);
        e >>= 1;
    }
    return r;
}

/* (gf_inv via the log/exp tables is used instead; see gf_div_tab.) */

/* log/exp tables, cached per m (single slot; lzply is single-threaded). */
typedef struct {
    int m;
    uint32_t N;         /* 2^m - 1 */
    uint32_t *exp;      /* exp[i] = alpha^i, i = 0..N-1 */
    uint32_t *log;      /* log[v] = i with alpha^i = v, v = 1..N-1 */
} gf_tables_t;

static gf_tables_t gf_cache = { 0, 0, NULL, NULL };

static const gf_tables_t *gf_tables_for(int m)
{
    if (gf_cache.m == m && gf_cache.exp)
        return &gf_cache;
    free(gf_cache.exp);
    free(gf_cache.log);
    gf_cache.m = 0;
    gf_cache.exp = NULL;
    gf_cache.log = NULL;
    uint32_t P = bch_prim_poly[m];
    uint32_t N = (1u << m) - 1;
    size_t sz = (size_t)1 << m;
    uint32_t *exp = malloc(sz * sizeof(uint32_t));
    uint32_t *log = malloc(sz * sizeof(uint32_t));
    if (!exp || !log) {
        free(exp);
        free(log);
        return NULL;
    }
    uint32_t x = 1;
    for (uint32_t i = 0; i < N; i++) {
        exp[i] = x;
        log[x] = i;
        x = gf_mul_alpha(x, P, m);
    }
    exp[N] = 1;
    log[0] = 0;
    gf_cache.m = m;
    gf_cache.N = N;
    gf_cache.exp = exp;
    gf_cache.log = log;
    return &gf_cache;
}

static uint32_t gf_mul_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
{
    if (!a || !b)
        return 0;
    uint32_t s = t->log[a] + t->log[b];
    if (s >= t->N)
        s -= t->N;
    return t->exp[s];
}

static uint32_t gf_div_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
{
    if (!a)
        return 0;
    int d = (int)t->log[a] - (int)t->log[b];
    if (d < 0)
        d += (int)t->N;
    return t->exp[d];
}

/* evaluate the remainder polynomial R(x) (left-aligned bytes, r bits)
 * at x = a, by Horner from the top coefficient down. */
static uint32_t rem_eval(const uint8_t *rem, int r, uint32_t a,
                         uint32_t P, int m)
{
    uint32_t res = 0;
    int seen = 0;
    for (int by = 0; by < (r + 7) / 8 && seen < r; by++) {
        for (int bi = 7; bi >= 0 && seen < r; bi--, seen++) {
            int coeff = (rem[by] >> bi) & 1;
            res = gf_mul_slow(res, a, P, m) ^ (uint32_t)coeff;
        }
    }
    return res;
}

/* ------------------------------------------------------------------ */
/* decoder                                                             */
/* ------------------------------------------------------------------ */

/* Berlekamp-Massey on S_1..S_2t. Returns the degree L and fills
 * lambda[0..L] (lambda[0]=1). Uses slow GF arithmetic. */
static int berlekamp_massey(const uint32_t *S, int t, uint32_t P, int m,
                            uint32_t *lambda)
{
    uint32_t C[33], B[33], T[33];
    for (int i = 0; i <= 32; i++)
        C[i] = B[i] = 0;
    C[0] = B[0] = 1;
    int L = 0, shift = 1;
    uint32_t b = 1;
    for (int n = 0; n < 2 * t; n++) {
        /* discrepancy d = S_{n+1} + sum_{i=1..L} C_i * S_{n+1-i} */
        uint32_t d = S[n];
        for (int i = 1; i <= L; i++) {
            if (C[i] && n - i >= 0)
                d ^= gf_mul_slow(C[i], S[n - i], P, m);
        }
        if (d == 0) {
            shift++;
            continue;
        }
        memcpy(T, C, sizeof(T));
        uint32_t coef = gf_div_tab(d, b, gf_tables_for(m));
        /* C = C + coef * x^shift * B */
        for (int i = 0; i <= 32 - shift; i++) {
            if (B[i])
                C[i + shift] ^= gf_mul_slow(coef, B[i], P, m);
        }
        if (2 * L <= n) {
            L = n + 1 - L;
            memcpy(B, T, sizeof(B));
            b = d;
            shift = 1;
        } else {
            shift++;
        }
    }
    for (int i = 0; i <= L; i++)
        lambda[i] = C[i];
    return L;
}

int bch_encode_block(const uint8_t *data, size_t data_len,
                     const bch_poly_t *p, uint8_t *out)
{
    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = malloc(c->nb);
    if (!rem) {
        bch_ctx_free(c);
        return -1;
    }
    rem_of_data(data, data_len, c, rem);
    memcpy(out, data, data_len);
    memcpy(out + data_len, rem, c->nb);
    free(rem);
    bch_ctx_free(c);
    return 0;
}

int bch_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
                     const bch_poly_t *p, uint8_t *out, int *corrected)
{
    if (corrected)
        *corrected = 0;
    size_t stored = bch_block_stored_len(data_len, p);
    if (in_len != stored)
        return -1;
    int r = p->r, m = p->m, t = p->t;
    uint32_t P = bch_prim_poly[m];
    uint32_t N = (1u << m) - 1;
    size_t nbits = (size_t)8 * data_len + (size_t)r;
    int nb = (r + 7) / 8;

    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = malloc(nb);
    uint8_t *work = malloc(in_len);
    if (!rem || !work) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    memcpy(work, in, in_len);
    rem_of_codeword(work, data_len, work + data_len, c, rem);
    if (rem_is_zero(rem, nb)) {
        /* no errors */
        memcpy(out, work, data_len);
        free(rem);
        free(work);
        bch_ctx_free(c);
        return 0;
    }

    /* syndromes S_j = R(alpha^j) * alpha^(-j*r), j = 1..2t */
    const gf_tables_t *tab = gf_tables_for(m);
    if (!tab) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    uint32_t S[64];
    for (int j = 1; j <= 2 * t; j++) {
        uint32_t aj = tab->exp[j % N];
        uint32_t v = rem_eval(rem, r, aj, P, m);
        /* multiply by alpha^(-j*r) */
        uint32_t e = (uint32_t)(((uint64_t)j * (uint64_t)r) % N);
        uint32_t inv = (e == 0) ? 1 : tab->exp[N - e];
        S[j - 1] = gf_mul_tab(v, inv, tab);
    }

    uint32_t lambda[33];
    int L = berlekamp_massey(S, t, P, m, lambda);
    if (L <= 0 || L > t) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }

    /* Chien search, incremental: x_p = alpha^(p-(n-1)), p = 0..n-1.
     * Maintain v[j] = lambda[j] * x_p^j; lambda(x_p) = sum v[j].
     * Stop once L roots are found. */
    uint32_t x0 = tab->exp[(N - (nbits - 1) % N) % N]; /* alpha^-(n-1) */
    uint32_t v[33];
    for (int j = 0; j <= L; j++) {
        /* v[j] = lambda[j] * x0^j */
        v[j] = lambda[j] ? gf_mul_tab(lambda[j], gf_pow_slow(x0, (uint32_t)j, P, m), tab) : 0;
    }
    /* alpha^j for the per-step update */
    uint32_t ajpow[33];
    for (int j = 0; j <= L; j++)
        ajpow[j] = tab->exp[j % N];

    int found = 0;
    for (size_t p = 0; p < nbits && found < L; p++) {
        uint32_t sum = 0;
        for (int j = 0; j <= L; j++)
            sum ^= v[j];
        if (sum == 0) {
            /* error at bit position p: flip it in work */
            size_t byte = p / 8;
            int bit = 7 - (int)(p % 8);
            work[byte] ^= (uint8_t)(1u << bit);
            found++;
        }
        /* advance to p+1: v[j] *= alpha^j */
        for (int j = 1; j <= L; j++)
            if (v[j])
                v[j] = gf_mul_tab(v[j], ajpow[j], tab);
    }
    if (found != L) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    if (corrected)
        *corrected = found;

    /* verify: the corrected codeword must have zero remainder */
    rem_of_codeword(work, data_len, work + data_len, c, rem);
    if (!rem_is_zero(rem, nb)) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    memcpy(out, work, data_len);
    free(rem);
    free(work);
    bch_ctx_free(c);
    return 0;
}

/* ------------------------------------------------------------------ */
/* whole-blob encode / decode                                          */
/* ------------------------------------------------------------------ */

size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
                  uint8_t *out)
{
    size_t maxd = bch_max_data(p);
    size_t off = 0, woff = 0;
    if (len == 0) {
        bch_encode_block(data, 0, p, out);
        return bch_block_stored_len(0, p);
    }
    while (off < len) {
        size_t chunk = len - off;
        if (chunk > maxd)
            chunk = maxd;
        bch_encode_block(data + off, chunk, p, out + woff);
        woff += bch_block_stored_len(chunk, p);
        off += chunk;
    }
    return woff;
}

int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
               const bch_poly_t *p, uint8_t *out, int *corrected)
{
    if (corrected)
        *corrected = 0;
    size_t maxd = bch_max_data(p);
    size_t off = 0, roff = 0;
    int total = 0;
    if (orig_len == 0) {
        if (len != bch_block_stored_len(0, p))
            return -1;
        int c1 = 0;
        if (bch_decode_block(in, len, 0, p, out, &c1) != 0)
            return -1;
        if (corrected)
            *corrected = c1;
        return 0;
    }
    while (off < orig_len) {
        size_t chunk = orig_len - off;
        if (chunk > maxd)
            chunk = maxd;
        size_t slen = bch_block_stored_len(chunk, p);
        if (roff + slen > len)
            return -1;
        int c1 = 0;
        if (bch_decode_block(in + roff, slen, chunk, p, out + off, &c1) != 0)
            return -1;
        total += c1;
        roff += slen;
        off += chunk;
    }
    if (roff != len)
        return -1;
    if (corrected)
        *corrected = total;
    return 0;
}

bch.h

BCH header — poly lookup, auto-pick, block encode/decode

/* bch.h - binary BCH error correction for lzply.
 *
 * Systematic shortened primitive BCH codes over GF(2), using the
 * 82 narrow-sense generator polynomials embedded in bch_polys.h
 * (parents N = 2^m - 1, m = 7..22, t in {1,2,4,8,16,32}).
 *
 * Bit convention (shared by encoder and decoder):
 *   A block holds D data bytes (k = 8*D data bits) and r parity bits.
 *   The codeword is n = k + r bits, stored data-first then parity,
 *   each byte MSB-first, with zero-bit padding to a byte boundary.
 *   The codeword polynomial c(x) has the first stored bit as the
 *   coefficient of x^(n-1) and the last as the coefficient of x^0.
 *   The encoder makes c(x) divisible by g(x): parity =
 *   (data_poly * x^r) mod g(x), i.e. the standard cyclic (CRC-style)
 *   remainder. The decoder recomputes that remainder (the syndrome);
 *   nonzero means errors, which Berlekamp-Massey + Chien search
 *   locate as bit flips. Binary BCH needs no magnitude step.
 *
 * The data capacity of one block is floor((N - r)/8) bytes; a blob
 * longer than that is split into blocks of that size. The decoder
 * reconstructs block boundaries from blob_size + the poly, so no
 * per-block length is stored.
 */
#ifndef LZPLY_BCH_H
#define LZPLY_BCH_H

#include <stddef.h>
#include <stdint.h>
#include "bch_polys.h"

/* Look up a polynomial by id (0x0001..0x0052). NULL if unknown. */
const bch_poly_t *bch_poly_by_id(uint16_t id);

/* Auto-pick: smallest parent m with a poly for (m,t) whose codeword can
 * hold `data_bytes` of data, i.e. N >= 8*data_bytes + t*m. Returns NULL
 * if no parent covers it (data too large for m=22 at this t). */
const bch_poly_t *bch_poly_for_data(size_t data_bytes, int t);

/* Max data bytes one block of this poly can hold: floor((N - r)/8). */
size_t bch_max_data(const bch_poly_t *p);

/* Stored (codeword) bytes for a block holding data_len data bytes:
 * ceil((8*data_len + r)/8). */
size_t bch_block_stored_len(size_t data_len, const bch_poly_t *p);

/* Total stored bytes for a whole blob of len data bytes (all blocks). */
size_t bch_encoded_len(size_t len, const bch_poly_t *p);

/* -e level -> t. 0 -> 0 (no ECC), 1 -> 1, 2 -> 2, 3 -> 4, 4 -> 8,
 * 5 -> 16, 6 -> 32, 7 -> 32. Returns -1 for an invalid level. */
int bch_t_for_level(int level);

/* Encode one block: data_len <= bch_max_data(p). out must hold
 * bch_block_stored_len(data_len, p) bytes. Returns 0 on success. */
int bch_encode_block(const uint8_t *data, size_t data_len,
                     const bch_poly_t *p, uint8_t *out);

/* Decode one block: in_len must equal bch_block_stored_len(data_len, p).
 * out must hold data_len bytes. Returns 0 on success, -1 if
 * uncorrectable. *corrected (if non-NULL) = number of bits corrected. */
int bch_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
                     const bch_poly_t *p, uint8_t *out, int *corrected);

/* Encode a whole blob (splits into blocks of bch_max_data). out must
 * hold bch_encoded_len(len, p) bytes. Returns the stored length. */
size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
                  uint8_t *out);

/* Decode a whole blob: orig_len is the data length (blob_size). Returns
 * 0 on success, -1 if any block is uncorrectable. *corrected (if
 * non-NULL) = total bits corrected across blocks. */
int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
               const bch_poly_t *p, uint8_t *out, int *corrected);

/* Brute-force remainder (bit-by-bit long division), used by the unit
 * test to cross-check the table-driven encoder. rem_out must hold
 * (r+7)/8 bytes; returns 0 on success. */
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
                             const bch_poly_t *p, uint8_t *rem_out);

#endif /* LZPLY_BCH_H */

bch_polys.h

The 82 embedded generator polynomials (generated by gen_bch_polys.py)

/* bch_polys.h - embedded BCH generator polynomials for lzply.
 *
 * Generated by gen_bch_polys.py from the rssearch results
 * (polys.txt / finds.txt). DO NOT EDIT BY HAND -- regenerate:
 *   python3 gen_bch_polys.py
 *
 * 82 narrow-sense primitive BCH generators, parents N=2^m-1 for
 * m=7..22, t in {1,2,4,8,16,32}. Generator bytes are LSB-first
 * (byte i holds bits 8i..8i+7), exactly as in polys.txt / finds.h.
 * The t=1 polynomial for each m is the primitive polynomial P_m
 * defining GF(2^m) (verified primitive by the generator).
 *
 * Every polynomial was independently recomputed orbit-only from
 * its P_m and checked byte-identical to polys.txt, so this table
 * is the narrow-sense generator for (m,t) under that P_m.
 */
#ifndef LZPLY_BCH_POLYS_H
#define LZPLY_BCH_POLYS_H

#include <stdint.h>

typedef struct {
    uint16_t id;       /* 2-byte polynomial id, e.g. 0x003a */
    uint8_t  m;        /* parent exponent: N = 2^m - 1 */
    uint8_t  t;        /* correctable bit errors */
    uint16_t r;        /* degree = parity bits = t*m */
    uint32_t parent;   /* N = 2^m - 1 */
    uint16_t nbytes;   /* generator length in bytes */
    uint16_t off;      /* offset into bch_poly_bytes[] */
} bch_poly_t;

#define BCH_NPOLYS 82
#define BCH_MIN_M 7
#define BCH_MAX_M 22

static const uint8_t bch_poly_bytes[] = {
    0xef,0xed,0x68,0x2b,0x01,0xe3,0xcb,0x01,0xe3,0x03,0x2d,0x75,0x05,0x1d,0xfe,0x9b,
    0x6d,0x1e,0x4d,0x07,0x03,0x57,0x1b,0x43,0xb7,0xae,0x4c,0x15,0x01,0x83,0x91,0xa1,
    0xeb,0x3a,0x6a,0x1c,0x94,0x9d,0xd1,0x01,0x27,0x0e,0x17,0x4e,0x75,0x5d,0x36,0x3d,
    0xec,0xb4,0x14,0x37,0x23,0x0e,0xa5,0x53,0x73,0x74,0x69,0x47,0xa7,0xf8,0x01,0xb5,
    0xa3,0x29,0xb5,0xa2,0xdb,0x00,0xc4,0xdb,0xec,0xc3,0xd0,0xce,0xca,0x75,0xf7,0xa9,
    0x77,0x6f,0x05,0xa9,0xf6,0x01,0x45,0x17,0x2d,0x04,0xcb,0x01,0x39,0x6a,0x7d,0x41,
    0xb5,0x37,0x01,0xf7,0xc3,0xd1,0x9d,0x41,0xa6,0x30,0x00,0x2e,0xb7,0x24,0xf3,0x01,
    0x3d,0xa1,0x44,0x26,0x84,0x77,0x22,0x9a,0x09,0xca,0xb5,0x67,0x34,0x01,0xdd,0xda,
    0xac,0x5d,0x62,0x74,0xc6,0x10,0x52,0xf6,0x01,0xf7,0x69,0x14,0x32,0x62,0x69,0xd6,
    0xb7,0xac,0xc6,0x0e,0x29,0x05,0x07,0x31,0x65,0xcd,0x33,0x3c,0xd8,0x1d,0xac,0x60,
    0x24,0xa2,0x5c,0xaf,0x3d,0xa9,0xa8,0x40,0xb0,0xa2,0x64,0x8d,0x93,0xd1,0xbf,0x20,
    0x12,0xdc,0x0d,0xc3,0xf8,0x8d,0x4c,0x23,0x57,0x01,0x4b,0x29,0xcb,0xff,0x5e,0x04,
    0xc3,0xdf,0x8e,0xd4,0x44,0x2b,0x1d,0x87,0xd6,0x9f,0x6d,0x66,0xea,0xa8,0xe8,0xea,
    0xda,0x2a,0x96,0x9e,0x01,0x4d,0xee,0xfd,0x7f,0x69,0x08,0xf0,0xd3,0x70,0x2d,0x8c,
    0xcf,0x32,0xd5,0x28,0xb6,0x75,0xc2,0x53,0x5f,0x29,0x4b,0x44,0x5b,0x2c,0xa9,0x01,
    0x57,0x19,0x9b,0xb2,0x6e,0x55,0xcc,0xaa,0x58,0x22,0xd4,0x8f,0x4f,0x23,0x74,0xd9,
    0xe3,0xaf,0x10,0x2b,0xc7,0xdb,0xf8,0xc3,0xba,0x29,0xce,0x56,0x74,0x83,0xf8,0xd3,
    0xac,0x0b,0x54,0xf8,0xfb,0x99,0x2d,0xaf,0xf4,0x79,0xd6,0x5f,0x7b,0x38,0x17,0x2c,
    0x6e,0x09,0x8d,0x01,0x01,0x27,0x46,0x27,0xc8,0x05,0x11,0x25,0xfc,0x12,0x3b,0x81,
    0x91,0xec,0x01,0xb9,0x2e,0xab,0xb2,0xd2,0xbb,0xf8,0xa0,0x47,0xfd,0x7d,0x2a,0x00,
    0xcb,0x01,0xfd,0x04,0x9e,0x66,0xed,0xff,0x49,0x93,0x97,0x12,0xf4,0x8f,0x9e,0x39,
    0x4d,0x26,0x64,0x65,0xfd,0xa1,0x28,0x04,0xcb,0xc2,0xaf,0xb6,0x62,0x62,0x01,0xc9,
    0x81,0x12,0xc4,0xcd,0x44,0xd0,0x80,0xca,0x90,0x10,0x5e,0x80,0xd9,0xb9,0xf5,0xe8,
    0x20,0xd7,0x29,0xbc,0x9a,0x86,0xbe,0x45,0x85,0x28,0x9c,0x4d,0xb9,0xf1,0x43,0x4b,
    0xe0,0x12,0xa8,0x28,0x45,0xf1,0x92,0xf0,0x52,0xbc,0x67,0xd7,0xea,0x3a,0x6a,0xfe,
    0xcc,0x8c,0x04,0xe5,0x3c,0xfc,0x92,0x01,0xd7,0xb3,0x67,0x20,0x02,0x6a,0xe7,0x93,
    0x2b,0x84,0xaf,0xba,0x26,0x10,0x05,0x1f,0xd1,0xf8,0x12,0xe5,0xd6,0xad,0x3c,0xd1,
    0x54,0xa3,0x97,0xfc,0xb3,0x01,0x45,0xcb,0x06,0xb3,0x39,0x6a,0x99,0xb4,0x46,0x84,
    0x40,0x55,0x88,0x93,0x1d,0x21,0x5e,0x37,0x7f,0x23,0xf9,0x11,0xb7,0x1b,0xbd,0x80,
    0x61,0x45,0x9c,0xe2,0x01,0xb5,0x55,0xf0,0x74,0xf3,0xf5,0xd1,0x49,0x77,0x89,0xe2,
    0xf3,0x4c,0x70,0x44,0x41,0xb9,0xe6,0x76,0xd6,0x3b,0xe8,0x90,0x02,0xa2,0x1a,0x7a,
    0x07,0xa7,0xff,0x28,0xb9,0x08,0xe8,0xde,0x6d,0xda,0x6e,0x93,0x52,0x3e,0x23,0x1b,
    0xb8,0x8e,0x50,0xea,0x49,0x3d,0x1d,0x54,0x88,0x04,0xbe,0x26,0x3b,0x7f,0x63,0xfd,
    0x91,0x01,0xbd,0x5f,0x01,0x03,0x5b,0x01,0x05,0x01,0x83,0x50,0x5c,0xac,0xd5,0xfe,
    0xc9,0xe9,0x01,0x91,0xd9,0x40,0x2a,0x4a,0xf3,0xc4,0x38,0xad,0xd2,0x08,0x56,0x5c,
    0x52,0x43,0x4f,0x01,0x29,0x84,0x72,0x1b,0xe7,0xdb,0x80,0x57,0xe1,0xd5,0xc2,0x34,
    0x1a,0x8d,0x5f,0xed,0xa7,0xf7,0x03,0xde,0x8f,0x59,0x60,0x63,0xc3,0x7d,0x3b,0x22,
    0xdf,0x53,0x5e,0x70,0x01,0x09,0x0b,0xa0,0x4c,0xcc,0x65,0x76,0x27,0x03,0x44,0xd7,
    0x60,0x81,0x97,0xd9,0x04,0x84,0x9f,0xf5,0x2a,0x86,0x84,0x7f,0xd3,0x03,0x85,0x77,
    0x31,0x2f,0x14,0xbb,0x58,0xd9,0x1d,0x84,0xdd,0xfe,0x27,0xf6,0x81,0x52,0xff,0x4d,
    0xd3,0xab,0x06,0x27,0x1d,0xfc,0x39,0x8c,0xcd,0xff,0x99,0xc2,0x35,0xe3,0x4e,0xca,
    0xde,0xfa,0xf0,0x9d,0x24,0x01,0xad,0x11,0x03,0xaf,0xd9,0x74,0x51,0x04,0xf5,0xf7,
    0xb2,0xc4,0x4b,0x42,0xcb,0xba,0x10,0x87,0xe0,0x08,0x99,0x03,0xfe,0x48,0xdb,0x80,
    0xb4,0x52,0x64,0xa1,0x7a,0xbf,0x95,0xd9,0x01,0x23,0xd0,0x3f,0x79,0x57,0x7a,0xf3,
    0xfe,0x09,0xf5,0x6e,0xf5,0x61,0x62,0x57,0xe3,0xd0,0x97,0xe4,0x47,0xd9,0x19,0xe6,
    0x96,0x01,0x6f,0x50,0x51,0x31,0xb1,0x8f,0xc3,0x8b,0xaf,0x01,0xd9,0xda,0x54,0xe6,
    0x5f,0x0a,0x25,0xb9,0x03,0x54,0x14,0x0f,0xc2,0xe8,0x96,0x99,0xfd,0xd7,0xab,0x75,
    0xec,0x1d,0xdb,0xdc,0x05,0x71,0x98,0x77,0x3a,0xf8,0xf5,0x2e,0x40,0x40,0xca,0x7c,
    0xe4,0x7c,0x97,0x27,0x2d,0x44,0xf6,0x28,0x7d,0x2d,0x98,0x93,0x54,0x5f,0xde,0x29,
    0x8f,0x56,0x7d,0x53,0x75,0x40,0xb4,0x6d,0x66,0x3b,0x98,0xaf,0x53,0x2d,0x84,0xd3,
    0x01,0xcf,0xf0,0x04,0x11,0x08,0x13,0x9d,0x1b,0x91,0x78,0x32,0x47,0x36,0x00,0x2d,
    0xfd,0xc1,0x01,0x41,0xb8,0xcf,0x7f,0xa2,0xc8,0xb9,0x59,0x84,0x8b,0x3f,0xb0,0x6b,
    0x3c,0xb7,0xd2,0x47,0x5f,0x01,0x7d,0xa9,0x9e,0xf8,0x44,0xc1,0xcc,0x28,0xa8,0x6c,
    0x18,0xa0,0x0e,0x35,0xab,0x8c,0xbf,0x38,0x7d,0x42,0x18,0x22,0xbf,0x1c,0x17,0xa4,
    0xc6,0x79,0x79,0xac,0xcd,0x59,0x91,0xce,0xc2,0xbd,0x01,0xbd,0x11,0x53,0xc4,0x8f,
    0x5e,0xa8,0x8e,0x8f,0xd7,0x9d,0x3f,0xa0,0x51,0x24,0x06,0xe2,0xef,0x28,0x95,0x1a,
    0xdd,0x2d,0x3f,0x7f,0x7f,0x32,0x9a,0xfd,0xca,0x7a,0x84,0x20,0x14,0xe5,0x4e,0xd7,
    0xa5,0x5b,0x18,0x4d,0x50,0x46,0xf7,0x12,0xfa,0x89,0x42,0x9b,0xad,0x6e,0xdb,0xa5,
    0x43,0xc0,0x59,0xbe,0xe5,0x59,0x58,0x6e,0xac,0xcb,0xc7,0xee,0x10,0x31,0x24,0x80,
    0xba,0xd4,0xb3,0x01,0xd5,0x4d,0x0a,0x89,0x55,0xec,0x41,0x43,0x03,0x37,0x27,0x86,
    0x17,0x42,0x42,0xed,0xec,0x17,0x79,0x39,0x2f,0x72,0xa4,0xe4,0x46,0xa9,0x26,0xf5,
    0x19,0xe3,0xe5,0x7b,0xe7,0xb9,0xef,0x45,0x79,0x01,0x71,0x44,0xcb,0x3a,0xeb,0xc8,
    0x50,0x3a,0x21,0x2e,0x9c,0x14,0x55,0x2b,0x60,0xe3,0xae,0xe2,0x1a,0xff,0x31,0x22,
    0x5a,0xe3,0xc0,0x05,0xfe,0x3b,0x00,0xa6,0xb0,0x32,0x82,0xb2,0x4a,0xe4,0xed,0x93,
    0x01,0x61,0x42,0xc5,0x22,0xbe,0x8c,0x20,0xef,0xfc,0x04,0x08,0x78,0xde,0x86,0xd5,
    0x90,0xa9,0x25,0x99,0x4a,0x09,0x58,0x38,0xed,0x78,0xd2,0xe4,0xa7,0x9a,0x6a,0x82,
    0xb8,0xb7,0xb1,0x78,0x1b,0x0b,0xe4,0x4a,0xdd,0xb9,0x04,0x6a,0x1e,0x32,0x51,0x08,
    0x67,0x1f,0xed,0x3f,0x05,0x02,0xba,0x76,0x89,0xb2,0x99,0x99,0xa5,0x1a,0xa5,0x7b,
    0xa8,0x3d,0x74,0x06,0xe8,0x6a,0xf6,0x9f,0x42,0xc6,0x9b,0x5c,0xc9,0x01,0x57,0x0a,
    0x17,0x3f,0x02,0x37,0x86,0xad,0x01,0x85,0x40,0x01,0x77,0x57,0x65,0xe8,0x92,0x5d,
    0x28,0x01,0xc5,0x47,0xab,0xa3,0x7f,0xd8,0x88,0x39,0xff,0xb1,0xcf,0x8a,0x35,0x54,
    0xf2,0xa9,0xb9,0x4d,0x7c,0xb0,0x01,0x7b,0x0e,0xb6,0x1f,0xa2,0xd1,0x10,0x3b,0x4f,
    0x4b,0x67,0x0a,0x5e,0x57,0x30,0x27,0x32,0x7c,0x9d,0x05,0x82,0x45,0x68,0x11,0xed,
    0x60,0xd9,0xb3,0x4d,0xc3,0x59,0x54,0x3c,0x2c,0x46,0xae,0xa7,0x1f,0x57,0x4b,0x01,
    0xf5,0xe6,0x41,0x92,0x9e,0xa9,0x70,0x33,0x0f,0x06,0xdf,0xb1,0xf1,0x63,0x18,0xb6,
    0x76,0xf3,0x85,0x0c,0xb5,0x13,0x4f,0xa2,0xba,0xba,0xc8,0x70,0x15,0xa9,0x3c,0xce,
    0x49,0x1a,0x91,0xd6,0xbf,0x38,0xd9,0xa3,0x6c,0x1a,0x82,0x44,0x33,0x13,0x8f,0xf1,
    0x73,0x36,0x03,0xe7,0x3b,0xd9,0x12,0xfa,0xde,0x0e,0x8d,0x20,0x64,0xa1,0xbd,0x73,
    0xd5,0xbe,0x0c,0x1b,0x22,0xd6,0x4c,0x69,0xdf,0x3a,0xc3,0x8b,0x84,0x22,0xcc,0x88,
    0x01,0xd9,0x4f,0x3d,0x2b,0xc2,0xa1,0xfb,0xec,0x04,0x43,0x6b,0x64,0x05,0x27,0x53,
    0x6a,0xdb,0xf7,0x40,0x14,0x81,0xc4,0x5a,0xc2,0x40,0x75,0x95,0x16,0xff,0x35,0x39,
    0xe0,0x47,0x57,0x31,0x14,0xef,0x67,0x15,0x9b,0x47,0x01,0x35,0xc3,0xac,0x76,0x72,
    0x38,0xb3,0xdd,0x13,0x7b,0xaf,0x03,0xf2,0x16,0xc4,0x41,0xbc,0x91,0x00,0xbe,0xe2,
    0x25,0x5b,0x41,0xe3,0xe9,0x73,0xd9,0xd5,0xa5,0xfb,0xe5,0x79,0x2c,0xe9,0x91,0x71,
    0x30,0x7f,0x9c,0x73,0x28,0x01,0xab,0xee,0x1b,0x0d,0x0a,0x8e,0xfc,0x2d,0x39,0x57,
    0xca,0xfe,0xa7,0x51,0x5c,0x86,0x11,0xcd,0x64,0x52,0xc0,0x45,0xa5,0x58,0x40,0xd7,
    0xc0,0xd3,0x63,0x3f,0xce,0xd6,0x16,0xf1,0x54,0xf4,0x77,0x85,0xf7,0x0b,0x15,0xd8,
    0x8c,0xa7,0xeb,0xca,0x90,0x4c,0xfc,0xaf,0x40,0x58,0x20,0x36,0x1d,0xae,0xa3,0xaf,
    0x93,0xca,0xf9,0x62,0xfe,0xfa,0x52,0x4f,0xcf,0xc5,0x9f,0x6b,0x3b,0x26,0xb9,0xf3,
    0x1f,0xac,0xdd,0xe1,0xd2,0x0e,0xbb,0x4c,0x21,0xdb,0x01,0x9d,0xdf,0x45,0xb3,0x0a,
    0x65,0x57,0x09,0x15,0x4b,0x41,0x57,0xf0,0x8e,0xa2,0x1c,0xf6,0xaf,0xcb,0x96,0x01,
    0x8f,0x6e,0xb6,0x20,0xef,0x52,0x4f,0x7e,0x17,0xe8,0xea,0x65,0xbd,0x9c,0x8f,0x6b,
    0x6a,0x56,0xe6,0x3a,0x80,0xd1,0x01,0x69,0x31,0x2b,0x7e,0xfb,0x02,0x9c,0x17,0x81,
    0x86,0x71,0x3c,0x7d,0x00,0x9f,0xe7,0xc3,0x2b,0x6e,0x7f,0x61,0x72,0xa4,0xfd,0xe2,
    0x51,0x1f,0x28,0x1a,0xa0,0xaf,0x35,0x50,0xe1,0xe9,0x52,0x69,0xf2,0x97,0x3a,0x34,
    0x04,0x8b,0x71,0x01,0x79,0x95,0x98,0x6f,0x3f,0xd2,0x3e,0x6f,0xd8,0xf6,0xfe,0x54,
    0x23,0xa8,0x6e,0x4c,0x92,0x27,0x0f,0x3e,0xd8,0x14,0x94,0x55,0x52,0xcd,0x0e,0x97,
    0x1c,0x17,0xf9,0x5c,0x3f,0x9d,0x96,0x13,0x9d,0xfa,0x95,0x0d,0x79,0xec,0xeb,0x41,
    0x3f,0xb6,0x77,0x52,0x7e,0x96,0x36,0x1a,0xf6,0xc8,0xa3,0xb1,0xcb,0xc3,0x0b,0x8a,
    0x0e,0xc3,0x9d,0xca,0x02,0xfd,0xa4,0x3d,0xb6,0xb9,0x78,0x08,0xa4,0xf4,0xd7,0xd0,
    0x75,0x4d,0xe2,0xb0,0x7f,0x80,0x83,0xd7,0xa4,0x79,0xd9,0x60,0x01,
};

static const bch_poly_t bch_polys[] = {
    { 0x0001, 7, 1, 7, 127, 1, 0 },
    { 0x0002, 7, 2, 14, 127, 2, 1 },
    { 0x0003, 8, 1, 8, 255, 2, 3 },
    { 0x0004, 8, 2, 16, 255, 3, 5 },
    { 0x0005, 9, 1, 9, 511, 2, 8 },
    { 0x0006, 9, 2, 18, 511, 3, 10 },
    { 0x0007, 9, 4, 36, 511, 5, 13 },
    { 0x0008, 10, 1, 10, 1023, 2, 18 },
    { 0x0009, 10, 2, 20, 1023, 3, 20 },
    { 0x000a, 10, 4, 40, 1023, 6, 23 },
    { 0x000b, 10, 8, 80, 1023, 11, 29 },
    { 0x000c, 11, 1, 11, 2047, 2, 40 },
    { 0x000d, 11, 2, 22, 2047, 3, 42 },
    { 0x000e, 11, 4, 44, 2047, 6, 45 },
    { 0x000f, 11, 8, 88, 2047, 12, 51 },
    { 0x0010, 11, 16, 176, 2047, 23, 63 },
    { 0x0011, 12, 1, 12, 4095, 2, 86 },
    { 0x0012, 12, 2, 24, 4095, 4, 88 },
    { 0x0013, 12, 4, 48, 4095, 7, 92 },
    { 0x0014, 12, 8, 96, 4095, 13, 99 },
    { 0x0015, 12, 16, 192, 4095, 25, 112 },
    { 0x0016, 12, 32, 384, 4095, 49, 137 },
    { 0x0017, 13, 1, 13, 8191, 2, 186 },
    { 0x0018, 13, 2, 26, 8191, 4, 188 },
    { 0x0019, 13, 4, 52, 8191, 7, 192 },
    { 0x001a, 13, 8, 104, 8191, 14, 199 },
    { 0x001b, 13, 16, 208, 8191, 27, 213 },
    { 0x001c, 13, 32, 416, 8191, 53, 240 },
    { 0x001d, 14, 1, 14, 16383, 2, 293 },
    { 0x001e, 14, 2, 28, 16383, 4, 295 },
    { 0x001f, 14, 4, 56, 16383, 8, 299 },
    { 0x0020, 14, 8, 112, 16383, 15, 307 },
    { 0x0021, 14, 16, 224, 16383, 29, 322 },
    { 0x0022, 14, 32, 448, 16383, 57, 351 },
    { 0x0023, 15, 1, 15, 32767, 2, 408 },
    { 0x0024, 15, 2, 30, 32767, 4, 410 },
    { 0x0025, 15, 4, 60, 32767, 8, 414 },
    { 0x0026, 15, 8, 120, 32767, 16, 422 },
    { 0x0027, 15, 16, 240, 32767, 31, 438 },
    { 0x0028, 15, 32, 480, 32767, 61, 469 },
    { 0x0029, 16, 1, 16, 65535, 3, 530 },
    { 0x002a, 16, 2, 32, 65535, 5, 533 },
    { 0x002b, 16, 4, 64, 65535, 9, 538 },
    { 0x002c, 16, 8, 128, 65535, 17, 547 },
    { 0x002d, 16, 16, 256, 65535, 33, 564 },
    { 0x002e, 16, 32, 512, 65535, 65, 597 },
    { 0x002f, 17, 1, 17, 131071, 3, 662 },
    { 0x0030, 17, 2, 34, 131071, 5, 665 },
    { 0x0031, 17, 4, 68, 131071, 9, 670 },
    { 0x0032, 17, 8, 136, 131071, 18, 679 },
    { 0x0033, 17, 16, 272, 131071, 35, 697 },
    { 0x0034, 17, 32, 544, 131071, 69, 732 },
    { 0x0035, 18, 1, 18, 262143, 3, 801 },
    { 0x0036, 18, 2, 36, 262143, 5, 804 },
    { 0x0037, 18, 4, 72, 262143, 10, 809 },
    { 0x0038, 18, 8, 144, 262143, 19, 819 },
    { 0x0039, 18, 16, 288, 262143, 37, 838 },
    { 0x003a, 18, 32, 576, 262143, 73, 875 },
    { 0x003b, 19, 1, 19, 524287, 3, 948 },
    { 0x003c, 19, 2, 38, 524287, 5, 951 },
    { 0x003d, 19, 4, 76, 524287, 10, 956 },
    { 0x003e, 19, 8, 152, 524287, 20, 966 },
    { 0x003f, 19, 16, 304, 524287, 39, 986 },
    { 0x0040, 19, 32, 608, 524287, 77, 1025 },
    { 0x0041, 20, 1, 20, 1048575, 3, 1102 },
    { 0x0042, 20, 2, 40, 1048575, 6, 1105 },
    { 0x0043, 20, 4, 80, 1048575, 11, 1111 },
    { 0x0044, 20, 8, 160, 1048575, 21, 1122 },
    { 0x0045, 20, 16, 320, 1048575, 41, 1143 },
    { 0x0046, 20, 32, 640, 1048575, 81, 1184 },
    { 0x0047, 21, 1, 21, 2097151, 3, 1265 },
    { 0x0048, 21, 2, 42, 2097151, 6, 1268 },
    { 0x0049, 21, 4, 84, 2097151, 11, 1274 },
    { 0x004a, 21, 8, 168, 2097151, 22, 1285 },
    { 0x004b, 21, 16, 336, 2097151, 43, 1307 },
    { 0x004c, 21, 32, 672, 2097151, 85, 1350 },
    { 0x004d, 22, 1, 22, 4194303, 3, 1435 },
    { 0x004e, 22, 2, 44, 4194303, 6, 1438 },
    { 0x004f, 22, 4, 88, 4194303, 12, 1444 },
    { 0x0050, 22, 8, 176, 4194303, 23, 1456 },
    { 0x0051, 22, 16, 352, 4194303, 45, 1479 },
    { 0x0052, 22, 32, 704, 4194303, 89, 1524 },
};

/* (m,t) -> poly id, rows m=7..22, cols t = 1,2,4,8,16,32; 0 = none. */
static const uint16_t bch_poly_by_mt[16][6] = {
    { 0x0001, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000 },  /* m=7 */
    { 0x0003, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000 },  /* m=8 */
    { 0x0005, 0x0006, 0x0007, 0x0000, 0x0000, 0x0000 },  /* m=9 */
    { 0x0008, 0x0009, 0x000a, 0x000b, 0x0000, 0x0000 },  /* m=10 */
    { 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0000 },  /* m=11 */
    { 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016 },  /* m=12 */
    { 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c },  /* m=13 */
    { 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022 },  /* m=14 */
    { 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028 },  /* m=15 */
    { 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e },  /* m=16 */
    { 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034 },  /* m=17 */
    { 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a },  /* m=18 */
    { 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040 },  /* m=19 */
    { 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046 },  /* m=20 */
    { 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c },  /* m=21 */
    { 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052 },  /* m=22 */
};

/* Primitive polynomial P_m for GF(2^m), as a uint32 (bit i = coeff of x^i).
 * This is the t=1 generator for that parent. */
static const uint32_t bch_prim_poly[23] = {
    0u,  /* m=0 (unused) */
    0u,  /* m=1 (unused) */
    0u,  /* m=2 (unused) */
    0u,  /* m=3 (unused) */
    0u,  /* m=4 (unused) */
    0u,  /* m=5 (unused) */
    0u,  /* m=6 (unused) */
    0x000000efu,  /* m=7 */
    0x0000012bu,  /* m=8 */
    0x000003e3u,  /* m=9 */
    0x0000074du,  /* m=10 */
    0x00000e27u,  /* m=11 */
    0x00001745u,  /* m=12 */
    0x0000294bu,  /* m=13 */
    0x00004627u,  /* m=14 */
    0x0000b3d7u,  /* m=15 */
    0x00015fbdu,  /* m=16 */
    0x000311adu,  /* m=17 */
    0x0004f0cfu,  /* m=18 */
    0x000a4dd5u,  /* m=19 */
    0x00170a57u,  /* m=20 */
    0x003d4fd9u,  /* m=21 */
    0x0045df9du,  /* m=22 */
};

#endif /* LZPLY_BCH_POLYS_H */

gen_bch_polys.py

Regenerates bch_polys.h from the rssearch data, verifying every poly

#!/usr/bin/env python3
"""gen_bch_polys.py - generate bch_polys.h for lzply from the rssearch data.

Reads ~/workspace/rssearch/polys.txt (id, deg, hex) and finds.txt
(parent, t, poly) and emits a C header embedding the 82 narrow-sense
primitive BCH generator polynomials (m=7..22, t in {1,2,4,8,16,32}).

For each poly the header stores: id (u16), m (u8), t (u8), r=deg (u16),
parent N (u32), and the generator bytes (LSB-first hex, as in polys.txt).
It also emits a (m,t)->poly_id lookup table used by the auto-pick, and
the primitive polynomial P_m for each m (the t=1 poly for that parent,
i.e. the Hamming generator = minpoly of the primitive element alpha).

Consistency checks performed (fails loudly if violated):
  - every poly id in polys.txt appears in finds.txt with exactly one
    (parent, t); deg == t*m where m = log2(parent+1)
  - the t=1 poly for each m is irreducible+primitive (checked by
    verifying x has order N mod P, using the known factorisation of
    2^m-1 for m<=22, which is small enough to factor by trial division)
  - the generated generator for (m,t) (recomputed orbit-only from P_m)
    matches the polys.txt hex, for every poly (independent check that
    the embedded bytes are the narrow-sense generators for P_m)
"""
import os
import re
import sys

RS = "/home/hatch/workspace/rssearch"
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bch_polys.h")

# ---------- GF(2) polynomial helpers (ints) ----------
def pmul(a, b):
    r = 0
    while b:
        if b & 1:
            r ^= a
        b >>= 1
        a <<= 1
    return r

def pmod(a, P):
    dm = P.bit_length() - 1
    while a.bit_length() - 1 >= dm:
        a ^= P << (a.bit_length() - 1 - dm)
    return a

def pmodmul(a, b, P):
    return pmod(pmul(a, b), P)

def pmodpow(a, e, P):
    r = 1
    while e:
        if e & 1:
            r = pmodmul(r, a, P)
        a = pmodmul(a, a, P)
        e >>= 1
    return r

def pgcd(a, b):
    while b:
        a, b = b, pmod(a, b)
    return a

def prime_factors(n):
    f = []
    d = 2
    while d * d <= n:
        if n % d == 0:
            f.append(d)
            while n % d == 0:
                n //= d
        d += 1 if d == 2 else 2
    if n > 1:
        f.append(n)
    return f

def is_primitive_poly(P, m):
    """P degree m. True iff irreducible and x has order 2^m-1 mod P."""
    N = (1 << m) - 1
    x = 2
    if pmodpow(x, 1 << m, P) != x:
        return False
    # irreducibility: gcd(x^(2^(m/q)) - x, P) == 1 for prime q|m
    for q in prime_factors(m):
        if pgcd(pmodpow(x, 1 << (m // q), P) ^ x, P) != 1:
            return False
    for p in prime_factors(N):
        if pmodpow(x, N // p, P) == 1:
            return False
    return True

# ---------- narrow-sense generator (orbit-only), independent check ----------
def gf_mul(a, b, P):
    return pmodmul(a, b, P)

def gf_pow(a, e, P):
    return pmodpow(a, e, P)

def narrow_g(N, t, P):
    m = (N + 1).bit_length() - 1
    # distinct cosets of odd residues 1,3,...,2t-1 under *2 mod N
    cosets = []
    seen = set()
    for a in range(1, 2 * t, 2):
        orb = []
        x = a
        while True:
            orb.append(x)
            x = (2 * x) % N
            if x == a:
                break
        rep = min(orb)
        if rep in seen:
            continue
        seen.add(rep)
        cosets.append(orb)

    def minpoly(orb):
        s = min(orb)
        betas = []
        e = s
        for _ in range(len(orb)):
            betas.append(gf_pow(2, e, P))
            e = (e * 2) % N
        poly = [1]
        for b in betas:
            new = [0] * (len(poly) + 1)
            for i, c in enumerate(poly):
                new[i] ^= gf_mul(c, b, P)
                new[i + 1] ^= c
            poly = new
        assert all(c in (0, 1) for c in poly), "non-binary minpoly coeff"
        v = 0
        for i, c in enumerate(poly):
            if c:
                v |= 1 << i
        return v

    def gf2_mul(a, b):
        r = 0
        while b:
            if b & 1:
                r ^= a
            b >>= 1
            a <<= 1
        return r

    g = 1
    for orb in cosets:
        g = gf2_mul(g, minpoly(orb))
    return g

def hex_to_int_lsb(h):
    b = bytes.fromhex(h)
    v = 0
    for i, byte in enumerate(b):
        v |= byte << (8 * i)
    return v

def int_to_hex_lsb(v):
    nb = (v.bit_length() + 7) // 8
    return bytes((v >> (8 * i)) & 0xff for i in range(nb)).hex()

# ---------- read the data ----------
polys = {}   # id -> (deg, nbytes, hex)
for line in open(os.path.join(RS, "polys.txt")):
    m = re.match(r"POLY id=([0-9a-f]+) deg=(\d+) nbytes=(\d+) hex=([0-9a-f]+)", line.strip())
    if not m:
        continue
    pid = int(m.group(1), 16)
    polys[pid] = (int(m.group(2)), int(m.group(3)), m.group(4))

# (parent, t) -> poly_id, from finds.txt
pt = {}
for line in open(os.path.join(RS, "finds.txt")):
    m = re.match(r"FIND L=\d+ t=(\d+) n=\d+ r=\d+ d=\d+ fam=\w+ parent=(\d+) poly=([0-9a-f]+) rsp=\d+ save=\d+ hex=[0-9a-f]+", line.strip())
    if not m:
        continue
    t, parent, pid = int(m.group(1)), int(m.group(2)), int(m.group(3), 16)
    key = (parent, t)
    if key in pt and pt[key] != pid:
        print(f"FAIL: (parent={parent},t={t}) maps to both {pt[key]:04x} and {pid:04x}")
        sys.exit(1)
    pt[key] = pid

# invert: poly_id -> (parent, t); check consistency with deg
info = {}    # pid -> dict(m, t, r, parent, hex)
for (parent, t), pid in pt.items():
    m = (parent + 1).bit_length() - 1
    assert (1 << m) - 1 == parent, f"parent {parent} is not 2^m-1"
    if pid in info:
        assert info[pid]["parent"] == parent and info[pid]["t"] == t, \
            f"poly {pid:04x} has two (parent,t)"
        continue
    deg, nbytes, hx = polys[pid]
    assert deg == t * m, f"poly {pid:04x}: deg {deg} != t*m = {t}*{m}"
    assert nbytes == (deg + 7) // 8 or nbytes == (deg // 8) + 1, \
        f"poly {pid:04x}: nbytes {nbytes} vs deg {deg}"
    info[pid] = dict(m=m, t=t, r=deg, parent=parent, hex=hx)

missing = set(polys) - set(info)
if missing:
    print(f"FAIL: polys with no (parent,t) in finds.txt: {sorted(f'{p:04x}' for p in missing)}")
    sys.exit(1)
print(f"polys: {len(info)} (ids {min(info):04x}..{max(info):04x}), "
      f"m range {min(v['m'] for v in info.values())}..{max(v['m'] for v in info.values())}")

# ---------- verify P_m (t=1 poly) is primitive, and recompute every g ----------
prim = {}   # m -> P (int)
for pid, v in info.items():
    if v["t"] == 1:
        assert v["m"] not in prim, f"two t=1 polys for m={v['m']}"
        prim[v["m"]] = hex_to_int_lsb(v["hex"])
for m in sorted(prim):
    P = prim[m]
    assert P.bit_length() - 1 == m, f"P_m degree wrong for m={m}"
    ok = is_primitive_poly(P, m)
    print(f"  m={m}: P={int_to_hex_lsb(P)} primitive={ok}")
    assert ok, f"t=1 poly for m={m} is not primitive"

for pid in sorted(info):
    v = info[pid]
    g = narrow_g(v["parent"], v["t"], prim[v["m"]])
    got = int_to_hex_lsb(g)
    assert got == v["hex"], \
        f"poly {pid:04x} (m={v['m']},t={v['t']}): recomputed {got} != polys.txt {v['hex']}"
print("all 82 generators recomputed orbit-only from P_m and match polys.txt")

# ---------- emit the header ----------
# (m,t) -> pid lookup, as a static table indexed by m (7..22) and t index
TS = [1, 2, 4, 8, 16, 32]
lookup = {}  # (m, t) -> pid
for pid, v in info.items():
    lookup[(v["m"], v["t"])] = pid

lines = []
lines.append("/* bch_polys.h - embedded BCH generator polynomials for lzply.")
lines.append(" *")
lines.append(" * Generated by gen_bch_polys.py from the rssearch results")
lines.append(" * (polys.txt / finds.txt). DO NOT EDIT BY HAND -- regenerate:")
lines.append(" *   python3 gen_bch_polys.py")
lines.append(" *")
lines.append(" * 82 narrow-sense primitive BCH generators, parents N=2^m-1 for")
lines.append(" * m=7..22, t in {1,2,4,8,16,32}. Generator bytes are LSB-first")
lines.append(" * (byte i holds bits 8i..8i+7), exactly as in polys.txt / finds.h.")
lines.append(" * The t=1 polynomial for each m is the primitive polynomial P_m")
lines.append(" * defining GF(2^m) (verified primitive by the generator).")
lines.append(" *")
lines.append(" * Every polynomial was independently recomputed orbit-only from")
lines.append(" * its P_m and checked byte-identical to polys.txt, so this table")
lines.append(" * is the narrow-sense generator for (m,t) under that P_m.")
lines.append(" */")
lines.append("#ifndef LZPLY_BCH_POLYS_H")
lines.append("#define LZPLY_BCH_POLYS_H")
lines.append("")
lines.append("#include <stdint.h>")
lines.append("")
lines.append("typedef struct {")
lines.append("    uint16_t id;       /* 2-byte polynomial id, e.g. 0x003a */")
lines.append("    uint8_t  m;        /* parent exponent: N = 2^m - 1 */")
lines.append("    uint8_t  t;        /* correctable bit errors */")
lines.append("    uint16_t r;        /* degree = parity bits = t*m */")
lines.append("    uint32_t parent;   /* N = 2^m - 1 */")
lines.append("    uint16_t nbytes;   /* generator length in bytes */")
lines.append("    uint16_t off;      /* offset into bch_poly_bytes[] */")
lines.append("} bch_poly_t;")
lines.append("")
lines.append(f"#define BCH_NPOLYS {len(info)}")
lines.append(f"#define BCH_MIN_M {min(v['m'] for v in info.values())}")
lines.append(f"#define BCH_MAX_M {max(v['m'] for v in info.values())}")
lines.append("")

# concatenated generator bytes
allbytes = bytearray()
offs = {}
for pid in sorted(info):
    hx = info[pid]["hex"]
    b = bytes.fromhex(hx)
    offs[pid] = len(allbytes)
    allbytes += b
lines.append("static const uint8_t bch_poly_bytes[] = {")
for i in range(0, len(allbytes), 16):
    chunk = allbytes[i:i + 16]
    lines.append("    " + ",".join(f"0x{b:02x}" for b in chunk) + ",")
lines.append("};")
lines.append("")

lines.append("static const bch_poly_t bch_polys[] = {")
for pid in sorted(info):
    v = info[pid]
    lines.append(f"    {{ 0x{pid:04x}, {v['m']}, {v['t']}, {v['r']}, "
                 f"{v['parent']}, {len(bytes.fromhex(v['hex']))}, {offs[pid]} }},")
lines.append("};")
lines.append("")

# (m,t) lookup: rows m=7..22, cols t in {1,2,4,8,16,32}; 0 = no poly
lines.append("/* (m,t) -> poly id, rows m=7..22, cols t = 1,2,4,8,16,32; 0 = none. */")
lines.append("static const uint16_t bch_poly_by_mt[16][6] = {")
for m in range(7, 23):
    row = [lookup.get((m, t), 0) for t in TS]
    lines.append("    { " + ", ".join(f"0x{v:04x}" for v in row) + " },  /* m=" + str(m) + " */")
lines.append("};")
lines.append("")

# primitive polynomial per m (t=1 hex), as a uint32
lines.append("/* Primitive polynomial P_m for GF(2^m), as a uint32 (bit i = coeff of x^i).")
lines.append(" * This is the t=1 generator for that parent. */")
lines.append("static const uint32_t bch_prim_poly[23] = {")
for m in range(0, 23):
    if m in prim:
        lines.append(f"    0x{prim[m]:08x}u,  /* m={m} */")
    else:
        lines.append(f"    0u,  /* m={m} (unused) */")
lines.append("};")
lines.append("")
lines.append("#endif /* LZPLY_BCH_POLYS_H */")
lines.append("")

with open(OUT, "w") as f:
    f.write("\n".join(lines))
print(f"wrote {OUT} ({os.path.getsize(OUT)} bytes, "
      f"{len(allbytes)} generator bytes, {len(info)} polys)")

bch_test.c

Standalone BCH validation harness (7,406 checks)

/* bch_test.c - unit test for the BCH codec (bch.c).
 *
 * Checks:
 *  1. Table-driven remainder == brute-force remainder, for all 82 polys
 *     and several data lengths.
 *  2. Encode/decode roundtrip (no errors) for all 82 polys and several
 *     sizes, including >max_data (block splitting).
 *  3. Corruption: flip k<=t bits -> recovers exactly; flip t+1 bits ->
 *     fails cleanly (never returns wrong data).
 *  4. Auto-pick: bch_poly_for_data returns the band-correct poly
 *     (smallest m covering the data, with a poly for (m,t)).
 *  5. t=1 poly for each m is the primitive polynomial (recomputed).
 *  6. bch_encoded_len / block splitting arithmetic.
 *
 * Usage: ./bch_test [seed]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"

static int fails = 0;
static int checks = 0;
#define CHECK(cond, ...) do { \
    checks++; \
    if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
} while (0)

static uint64_t rng_state = 0x12345678abcdefULL;
static uint64_t xr(void)
{
    rng_state ^= rng_state << 13;
    rng_state ^= rng_state >> 7;
    rng_state ^= rng_state << 17;
    return rng_state;
}

static void rand_bytes(uint8_t *buf, size_t n)
{
    for (size_t i = 0; i < n; i++)
        buf[i] = (uint8_t)(xr() & 0xff);
}

/* flip k distinct random bits within the first nbits bits of buf. */
static void flip_bits(uint8_t *buf, size_t nbits, int k)
{
    /* simple: pick k distinct positions by rejection */
    size_t *pos = malloc((size_t)k * sizeof(size_t));
    int got = 0;
    while (got < k) {
        size_t p = (size_t)(xr() % nbits);
        int dup = 0;
        for (int i = 0; i < got; i++)
            if (pos[i] == p)
                dup = 1;
        if (!dup)
            pos[got++] = p;
    }
    for (int i = 0; i < k; i++) {
        size_t p = pos[i];
        buf[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
    }
    free(pos);
}

int main(int argc, char **argv)
{
    if (argc > 1)
        rng_state = strtoull(argv[1], NULL, 0) ^ 0x9e3779b97f4a7c15ULL;

    /* sizes to test (data bytes per block) */
    static const size_t sizes[] = { 0, 1, 2, 3, 7, 8, 15, 16, 100, 1000,
                                    8192, 16384, 65536 };
    static const int nsize = (int)(sizeof(sizes) / sizeof(sizes[0]));

    /* --- 1+2: remainder cross-check + roundtrip for every poly --- */
    for (int pi = 0; pi < BCH_NPOLYS; pi++) {
        const bch_poly_t *p = &bch_polys[pi];
        size_t maxd = bch_max_data(p);
        for (int si = 0; si < nsize; si++) {
            size_t D = sizes[si];
            if (D > maxd)
                continue;
            uint8_t *data = malloc(D ? D : 1);
            rand_bytes(data, D);
            size_t slen = bch_block_stored_len(D, p);
            uint8_t *enc = malloc(slen);
            uint8_t *dec = malloc(D ? D : 1);
            CHECK(bch_encode_block(data, D, p, enc) == 0,
                  "encode poly %04x D=%zu", p->id, D);
            /* parity bytes == brute-force remainder */
            uint8_t *bf = malloc((p->r + 7) / 8);
            CHECK(bch_remainder_bruteforce(data, D, p, bf) == 0,
                  "bruteforce poly %04x D=%zu", p->id, D);
            CHECK(memcmp(enc + D, bf, (p->r + 7) / 8) == 0,
                  "table!=brute poly %04x D=%zu r=%u", p->id, D, p->r);
            free(bf);
            /* clean roundtrip */
            int corr = -1;
            CHECK(bch_decode_block(enc, slen, D, p, dec, &corr) == 0,
                  "decode poly %04x D=%zu", p->id, D);
            CHECK(memcmp(dec, data, D) == 0,
                  "roundtrip data poly %04x D=%zu", p->id, D);
            CHECK(corr == 0, "clean decode corrected %d bits poly %04x D=%zu",
                  corr, p->id, D);
            free(data);
            free(enc);
            free(dec);
        }
    }
    printf("phase 1+2 (remainder x-check + roundtrip, all 82 polys): "
           "%d checks, %d fails\n", checks, fails);

    /* --- 3: corruption recovery, a spread of polys --- */
    static const uint16_t corr_polys[] = {
        0x0001, /* m7 t1 */
        0x0002, /* m7 t2 */
        0x0004, /* m8 t2 */
        0x0008, /* m10 t1 */
        0x000d, /* m11 t2 */
        0x0012, /* m12 t2 */
        0x0018, /* m13 t2 */
        0x0025, /* m15 t4 */
        0x002e, /* m16 t32 */
        0x0034, /* m17 t32 */
        0x003a, /* m18 t32 */
        0x0040, /* m19 t32 */
        0x0046, /* m20 t32 */
        0x004c, /* m21 t32 */
        0x0052, /* m22 t32 */
    };
    static const size_t corr_sizes[] = { 100, 1000, 8192 };
    for (size_t ci = 0; ci < sizeof(corr_polys) / sizeof(corr_polys[0]); ci++) {
        const bch_poly_t *p = bch_poly_by_id(corr_polys[ci]);
        CHECK(p != NULL, "lookup poly %04x", corr_polys[ci]);
        if (!p)
            continue;
        int t = p->t;
        for (size_t si = 0; si < sizeof(corr_sizes) / sizeof(corr_sizes[0]); si++) {
            size_t D = corr_sizes[si];
            if (D > bch_max_data(p))
                continue;
            uint8_t *data = malloc(D);
            rand_bytes(data, D);
            size_t slen = bch_block_stored_len(D, p);
            uint8_t *enc = malloc(slen);
            uint8_t *dec = malloc(D);
            CHECK(bch_encode_block(data, D, p, enc) == 0,
                  "corr encode poly %04x D=%zu", p->id, D);
            /* flip k = 1..t bits: must recover exactly */
            for (int k = 1; k <= t; k++) {
                uint8_t *bad = malloc(slen);
                memcpy(bad, enc, slen);
                flip_bits(bad, (size_t)8 * D + (size_t)p->r, k);
                int corr = -1;
                int rc = bch_decode_block(bad, slen, D, p, dec, &corr);
                CHECK(rc == 0, "flip %d bits poly %04x D=%zu t=%d rc=%d",
                      k, p->id, D, t, rc);
                if (rc == 0)
                    CHECK(memcmp(dec, data, D) == 0,
                          "flip %d bits data mismatch poly %04x D=%zu",
                          k, p->id, D);
                CHECK(corr == k, "flip %d bits corrected=%d poly %04x D=%zu",
                      k, corr, p->id, D);
                free(bad);
            }
            /* flip t+1 bits: must NOT return wrong data (fail, or
             * recover exactly -- miscorrection to another codeword is
             * possible in principle but must be vanishingly rare) */
            {
                int miscorr = 0, failed = 0, recovered = 0;
                for (int trial = 0; trial < 20; trial++) {
                    uint8_t *bad = malloc(slen);
                    memcpy(bad, enc, slen);
                    flip_bits(bad, (size_t)8 * D + (size_t)p->r, t + 1);
                    int rc = bch_decode_block(bad, slen, D, p, dec, NULL);
                    if (rc != 0)
                        failed++;
                    else if (memcmp(dec, data, D) == 0)
                        recovered++;
                    else
                        miscorr++;
                    free(bad);
                }
                /* t+1 flips: must NOT return wrong data, except that
                 * for small t the radius-t balls cover a large fraction
                 * of the space, so miscorrection to another codeword
                 * is expected (bounded-distance decoding). For t>=8
                 * the covering fraction is negligible, so any
                 * miscorrection there is a real bug. The per-entry
                 * SHA-256 in lzply catches miscorrections in any case. */
                if (t >= 8)
                    CHECK(miscorr == 0,
                          "t+1 flips: %d miscorrections (wrong data) poly %04x D=%zu t=%d",
                          miscorr, p->id, D, t);
                else
                    printf("  note: poly %04x t=%d D=%zu: %d/%d t+1 trials "
                           "miscorrected (expected for small t)\n",
                           p->id, t, D, miscorr, 20);
                printf("  poly %04x (m=%d t=%d) D=%zu: t+1 flips x20: "
                       "failed=%d recovered=%d miscorr=%d\n",
                       p->id, p->m, t, D, failed, recovered, miscorr);
            }
            free(data);
            free(enc);
            free(dec);
        }
    }
    printf("phase 3 (corruption): %d checks, %d fails\n", checks, fails);

    /* --- 4: auto-pick band correctness --- */
    /* For a spread of (D, t), the picked poly must be the smallest m
     * with a poly for (m,t) and N >= 8D + t*m, and no smaller m works. */
    {
        static const int ts[] = { 1, 2, 4, 8, 16, 32 };
        static const size_t ds[] = { 1, 8, 15, 16, 100, 1000, 8192,
                                     16384, 65536, 131072, 524199, 524287 };
        for (size_t ti = 0; ti < sizeof(ts) / sizeof(ts[0]); ti++) {
            for (size_t di = 0; di < sizeof(ds) / sizeof(ds[0]); di++) {
                int t = ts[ti];
                size_t D = ds[di];
                const bch_poly_t *p = bch_poly_for_data(D, t);
                /* brute-force expected: smallest m with a poly and N>=8D+t*m */
                const bch_poly_t *exp = NULL;
                for (int m = BCH_MIN_M; m <= BCH_MAX_M && !exp; m++) {
                    for (int pi = 0; pi < BCH_NPOLYS; pi++) {
                        const bch_poly_t *q = &bch_polys[pi];
                        if (q->m == m && q->t == t &&
                            (uint64_t)q->parent >= (uint64_t)8 * D + (uint64_t)t * m) {
                            exp = q;
                            break;
                        }
                    }
                }
                /* bch_polys.h uses static arrays, so bch.c and this
                 * test each have their own copy: compare by id, not
                 * by pointer. */
                CHECK((p == NULL) == (exp == NULL) &&
                      (p == NULL || p->id == exp->id),
                      "autopick D=%zu t=%d: got %04x expected %04x",
                      D, t, p ? p->id : 0, exp ? exp->id : 0);
                if (p)
                    CHECK(bch_max_data(p) >= D,
                          "autopick max_data %zu < D=%zu poly %04x",
                          bch_max_data(p), D, p->id);
            }
        }
        /* too large for m=22 at t=32: no poly */
        CHECK(bch_poly_for_data(600000, 32) == NULL,
              "autopick 600000B t=32 should be NULL");
        /* but 524199B at t=32 fits m=22 */
        CHECK(bch_poly_for_data(524199, 32) != NULL,
              "autopick 524199B t=32 should exist");
    }
    printf("phase 4 (auto-pick): %d checks, %d fails\n", checks, fails);

    /* --- 5: block splitting + whole-blob encode/decode --- */
    {
        const bch_poly_t *p = bch_poly_by_id(0x0052); /* m22 t32 */
        size_t maxd = bch_max_data(p);
        CHECK(maxd == 524199, "m22 t32 max_data=%zu expected 524199", maxd);
        size_t big = maxd * 2 + 12345;
        uint8_t *data = malloc(big);
        rand_bytes(data, big);
        size_t elen = bch_encoded_len(big, p);
        CHECK(elen == 2 * bch_block_stored_len(maxd, p) +
                        bch_block_stored_len(12345, p),
              "encoded_len %zu for %zu bytes", elen, big);
        uint8_t *enc = malloc(elen);
        uint8_t *dec = malloc(big);
        CHECK(bch_encode(data, big, p, enc) == elen,
              "bch_encode returned %zu expected %zu",
              bch_encode(data, big, p, enc), elen);
        /* corrupt 5 bits in the first block and 32 in the last */
        flip_bits(enc, (size_t)8 * maxd + (size_t)p->r, 5);
        flip_bits(enc + 2 * bch_block_stored_len(maxd, p),
                  (size_t)8 * 12345 + (size_t)p->r, 32);
        int corr = 0;
        CHECK(bch_decode(enc, elen, big, p, dec, &corr) == 0,
              "split-blob decode with corruption rc");
        CHECK(memcmp(dec, data, big) == 0, "split-blob data mismatch");
        CHECK(corr == 37, "split-blob corrected=%d expected 37", corr);
        free(data);
        free(enc);
        free(dec);
        /* empty blob */
        {
            uint8_t e0[128], d0[1];
            size_t l0 = bch_encode(NULL, 0, p, e0);
            CHECK(l0 == bch_block_stored_len(0, p), "empty encoded len %zu", l0);
            CHECK(bch_decode(e0, l0, 0, p, d0, NULL) == 0, "empty decode");
        }
    }
    printf("phase 5 (block splitting): %d checks, %d fails\n", checks, fails);

    /* --- 6: unknown / edge lookups --- */
    CHECK(bch_poly_by_id(0x0000) == NULL, "id 0000 should be NULL");
    CHECK(bch_poly_by_id(0x0053) == NULL, "id 0053 should be NULL");
    CHECK(bch_poly_by_id(0xffff) == NULL, "id ffff should be NULL");
    CHECK(bch_t_for_level(0) == 0 && bch_t_for_level(1) == 1 &&
          bch_t_for_level(2) == 2 && bch_t_for_level(3) == 4 &&
          bch_t_for_level(4) == 8 && bch_t_for_level(5) == 16 &&
          bch_t_for_level(6) == 32 && bch_t_for_level(7) == 32,
          "t_for_level mapping");
    CHECK(bch_t_for_level(8) == -1 && bch_t_for_level(-1) == -1,
          "t_for_level invalid");

    printf("TOTAL: %d checks, %d fails\n", checks, fails);
    return fails ? 1 : 0;
}

Makefile

Build rules

CC = gcc
CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local

all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh

# Shared core: the v3 archive format, the per-entry pipeline
# (lzip -> BCH), header I/O, scan, and filters. The
# command-line tool (lzply), the FUSE filesystem (lzply_mount),
# the statistics tool (lzply_stat) and the heal tool (lzply_heal)
# all link it.
liblzply.a: lzply_lib.o bch.o sha256.o
	ar rcs $@ $^

lzply_lib.o: lzply_lib.c lzply_lib.h bch.h bch_polys.h sha256.h
	$(CC) $(CFLAGS) -c -o $@ lzply_lib.c

sha256.o: sha256.c sha256.h
	$(CC) $(CFLAGS) -c -o $@ sha256.c

bch.o: bch.c bch.h bch_polys.h
	$(CC) $(CFLAGS) -c -o $@ bch.c

lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h
	$(CC) $(CFLAGS) -c -o $@ lzply.c

lzply: lzply.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply.o liblzply.a $(LDLIBS)

# FUSE filesystem. Needs libfuse3-dev; no pkg-config on the server, so
# the flags are explicit (-D_FILE_OFFSET_BITS=64 is required by FUSE).
FUSE_CFLAGS = -D_FILE_OFFSET_BITS=64
FUSE_LIBS = -lfuse3

lzply_mount.o: lzply_mount.c lzply_lib.h bch.h bch_polys.h
	$(CC) $(CFLAGS) $(FUSE_CFLAGS) -c -o $@ lzply_mount.c

lzply_mount: lzply_mount.o liblzply.a
	$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o liblzply.a $(LDLIBS) $(FUSE_LIBS)

# Shared helpers for lzply_stat and lzply_heal (mount resolution via
# /proc, human-size formatting). No FUSE needed.
lzply_util.o: lzply_util.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_util.c

lzply_stat.o: lzply_stat.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_stat.c

lzply_stat: lzply_stat.o lzply_util.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o liblzply.a $(LDLIBS)

lzply_heal.o: lzply_heal.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_heal.c

lzply_heal: lzply_heal.o lzply_util.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o liblzply.a $(LDLIBS)

# Bit error rate detector. Read-only: decodes each BCH entry's stored
# bytes in memory and counts the corrected bit errors. Links the same
# shared util (mount resolution) as stat and heal.
lzply_check.o: lzply_check.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_check.c

lzply_check: lzply_check.o lzply_util.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o liblzply.a $(LDLIBS) -lm

# In-place platter refresher. Reads a file (or every regular file
# under a directory / mount point) and rewrites it over itself, with
# SHA-256 verification. Links the same shared util (mount
# resolution) as stat, heal and check.
lzply_refresh.o: lzply_refresh.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_refresh.c

lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o liblzply.a $(LDLIBS)

bch_test: bch.c bch_test.c bch.h bch_polys.h
	$(CC) $(CFLAGS) -o $@ bch.c bch_test.c

# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
# NOT rebuilt by make. Regenerate manually after a re-crawl with:
#   python3 gen_bch_polys.py

# The shell suite lives in ./tests when built from the repo layout
# (~/workspace/lzply) and in ../tests when built from /opt/lzply/src.
# run_tests.sh derives its ROOT from its own location, so it works
# in both layouts; LZPLY_TEST_ROOT overrides it explicitly.
# NB: lzply_mount is a test dep on purpose — without it the mount
# tests in run_tests.sh silently skip after a `make clean`, even on a
# machine with /dev/fuse. (Needs libfuse3-dev; present on the server
# and the dev VM. The mount tests themselves still skip cleanly
# where /dev/fuse is absent.)
test: bch_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh
	./bch_test
	if [ -x ./tests/run_tests.sh ]; then \
		./tests/run_tests.sh ./lzply; \
	elif [ -x ../tests/run_tests.sh ]; then \
		../tests/run_tests.sh ./lzply; \
	else echo "run_tests.sh not found"; exit 1; fi

install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh
	install -m 755 lzply $(PREFIX)/bin/lzply
	install -m 755 lzply_mount $(PREFIX)/bin/lzply_mount
	install -m 755 lzply_stat $(PREFIX)/bin/lzply_stat
	install -m 755 lzply_heal $(PREFIX)/bin/lzply_heal
	install -m 755 lzply_check $(PREFIX)/bin/lzply_check
	install -m 755 lzply_refresh $(PREFIX)/bin/lzply_refresh
	install -m 755 mount.lzply /sbin/mount.lzply

clean:
	rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh bch_test *.o liblzply.a

.PHONY: all test install clean

tests/corrupt.c

Byte-flip helper used by the corruption tests

/* corrupt.c - flip N bytes in a file at pseudo-random offsets.
 *
 * Usage: corrupt <file> <seed> <count> [start] [end]
 * Flips `count` distinct bytes in the range [start, end) by XORing
 * each with a random nonzero value. Prints the offsets flipped.
 * Used by the lzply test suite to prove BCH recovery and
 * failure behaviour. Deterministic for a given seed.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static uint32_t st;

static uint32_t rnd(void)
{
    st ^= st << 13;
    st ^= st >> 17;
    st ^= st << 5;
    return st;
}

int main(int argc, char **argv)
{
    const char *path;
    long seed, count;
    long start = 0, end = -1;
    FILE *f;
    long size, i;
    uint8_t *data;
    long *picked;

    if (argc < 4) {
        fprintf(stderr, "Usage: %s <file> <seed> <count> [start] [end]\n",
                argv[0]);
        return 1;
    }
    path = argv[1];
    seed = atol(argv[2]);
    count = atol(argv[3]);
    if (argc >= 5)
        start = atol(argv[4]);
    if (argc >= 6)
        end = atol(argv[5]);
    st = (uint32_t)(seed ? seed : 1);

    f = fopen(path, "r+b");
    if (!f) {
        perror("open");
        return 1;
    }
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    if (end < 0 || end > size)
        end = size;
    if (start < 0 || start >= end || count < 0 || count > end - start) {
        fprintf(stderr, "corrupt: bad range (start=%ld end=%ld count=%ld size=%ld)\n",
                start, end, count, size);
        fclose(f);
        return 1;
    }
    data = malloc((size_t)(end - start));
    if (!data) {
        fclose(f);
        return 1;
    }
    fseek(f, start, SEEK_SET);
    if (fread(data, 1, (size_t)(end - start), f) != (size_t)(end - start)) {
        fclose(f);
        free(data);
        return 1;
    }
    picked = malloc(sizeof(long) * (size_t)(count ? count : 1));
    for (i = 0; i < count; i++) {
        long pos;
        int dup;
        do {
            pos = start + (long)(rnd() % (uint32_t)(end - start));
            dup = 0;
            for (long q = 0; q < i; q++)
                if (picked[q] == pos)
                    dup = 1;
        } while (dup);
        picked[i] = pos;
        data[pos - start] ^= (uint8_t)(1 + (rnd() % 255));
        printf("%ld ", pos);
    }
    printf("\n");
    fseek(f, start, SEEK_SET);
    fwrite(data, 1, (size_t)(end - start), f);
    fclose(f);
    free(data);
    free(picked);
    return 0;
}

tests/corrupt_bits.c

Bit-flip helper used by the BCH corruption tests

/* corrupt_bits.c - flip N bits in a file at pseudo-random positions.
 *
 * Usage: corrupt_bits <file> <seed> <count> [start] [end]
 * Flips `count` distinct bits in the byte range [start, end) by
 * toggling one bit per chosen byte position (each flipped bit is in
 * a different byte, so `count` bits = `count` bytes each changed by
 * exactly one bit). Prints the bit positions flipped.
 * Used by the lzply test suite to prove BCH bit-error recovery and
 * failure behaviour. Deterministic for a given seed.
 *
 * This is the bit-level counterpart of corrupt.c (which flips whole
 * bytes, i.e. up to 8 bit errors per byte, for Reed-Solomon).
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static uint32_t st;

static uint32_t rnd(void)
{
    st ^= st << 13;
    st ^= st >> 17;
    st ^= st << 5;
    return st;
}

int main(int argc, char **argv)
{
    const char *path;
    long seed, count;
    long start = 0, end = -1;
    FILE *f;
    long size, i;
    uint8_t *data;
    long *picked;

    if (argc < 4) {
        fprintf(stderr, "Usage: %s <file> <seed> <count> [start] [end]\n",
                argv[0]);
        return 1;
    }
    path = argv[1];
    seed = atol(argv[2]);
    count = atol(argv[3]);
    if (argc >= 5)
        start = atol(argv[4]);
    if (argc >= 6)
        end = atol(argv[5]);
    st = (uint32_t)(seed ? seed : 1);

    f = fopen(path, "r+b");
    if (!f) {
        perror("open");
        return 1;
    }
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    if (end < 0 || end > size)
        end = size;
    if (start < 0 || start >= end || count < 0 || count > (end - start) * 8) {
        fprintf(stderr, "corrupt_bits: bad range (start=%ld end=%ld count=%ld size=%ld)\n",
                start, end, count, size);
        fclose(f);
        return 1;
    }
    data = malloc((size_t)(end - start));
    if (!data) {
        fclose(f);
        return 1;
    }
    fseek(f, start, SEEK_SET);
    if (fread(data, 1, (size_t)(end - start), f) != (size_t)(end - start)) {
        fclose(f);
        free(data);
        return 1;
    }
    /* pick `count` distinct bit positions, one per byte at most, so
     * each flipped byte differs by exactly one bit. */
    picked = malloc(sizeof(long) * (size_t)(count ? count : 1));
    for (i = 0; i < count; i++) {
        long pos;
        int dup;
        do {
            pos = start + (long)(rnd() % (uint32_t)(end - start));
            dup = 0;
            for (long q = 0; q < i; q++)
                if (picked[q] == pos)
                    dup = 1;
        } while (dup);
        picked[i] = pos;
        data[pos - start] ^= (uint8_t)(1u << (rnd() % 8));
        printf("%ld ", pos);
    }
    printf("\n");
    fseek(f, start, SEEK_SET);
    fwrite(data, 1, (size_t)(end - start), f);
    fclose(f);
    free(data);
    free(picked);
    return 0;
}

tests/run_tests.sh

The full 147-test archive test suite

#!/bin/bash
# run_tests.sh - full lzply test suite.
# Usage: run_tests.sh [path-to-lzply]
# Requires: testdata built by make_testdata.sh, corrupt helpers compiled.
# ROOT is the lzply tree root (testdata/, testwork/, tests/ live under
# it): taken from $LZPLY_TEST_ROOT, else the parent of this script's
# directory (works for ~/workspace/lzply and for /opt/lzply/src).
set -u
LZPLY="${1:-/opt/lzply/src/lzply}"
# Canonicalise LZPLY to an absolute path: several tests cd into $WORK
# (e.g. the -tr tests, so the archive name prints as a bare filename),
# and a relative ./lzply would stop resolving there.
case "$LZPLY" in
    /*) ;;
    *) LZPLY="$(cd "$(dirname "$LZPLY")" && pwd)/$(basename "$LZPLY")" ;;
esac
STAT="$(dirname "$LZPLY")/lzply_stat"
HEAL="$(dirname "$LZPLY")/lzply_heal"
CHECK="$(dirname "$LZPLY")/lzply_check"
REFRESH="$(dirname "$LZPLY")/lzply_refresh"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="${LZPLY_TEST_ROOT:-$(dirname "$SCRIPT_DIR")}"
TD=$ROOT/testdata
WORK=$ROOT/testwork
CORRUPT=/tmp/corrupt
CORRUPT_BITS=/tmp/corrupt_bits
PASS=0
FAIL=0

ok()  { PASS=$((PASS+1)); echo "PASS: $1"; }
bad() { FAIL=$((FAIL+1)); echo "FAIL: $1"; }

rm -rf "$WORK"
mkdir -p "$WORK"
gcc -O2 -Wall -o "$CORRUPT" "$ROOT/tests/corrupt.c" || { echo "cannot build corrupt helper"; exit 1; }
gcc -O2 -Wall -o "$CORRUPT_BITS" "$ROOT/tests/corrupt_bits.c" || { echo "cannot build corrupt_bits helper"; exit 1; }
[ -x "$LZPLY" ] || { echo "lzply binary not found: $LZPLY"; exit 1; }
[ -d "$TD/mixed" ] || { echo "testdata missing; run make_testdata.sh first"; exit 1; }

# --- 1. Compression levels: roundtrip at -1..-9 -----------------------
for L in 1 2 3 4 5 6 7 8 9; do
    rm -rf "$WORK/out"
    "$LZPLY" -c -"$L" "$TD/mixed" "$WORK/mixed-$L.lzply" >/dev/null 2>&1 &&
    "$LZPLY" -d "$WORK/mixed-$L.lzply" "$WORK/out" >/dev/null 2>&1 &&
    diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
        ok "level -$L roundtrip" || bad "level -$L roundtrip"
done

# --- 2. lzip cross-check: compressed data must equal `lzip -6` -----------
# -e 0 (no error correction) so the stored bytes ARE the lzip stream.
# The 6-byte header's dict-size byte differs on purpose: lzip adapts
# the stored dictionary to the input size, lzply stores the level's
# full size. The compressed data (bytes 7..end) must be identical,
# the sizes equal, and the stream must pass `lzip -t`.
# (Skipped when the system lzip tool is not installed.)
if command -v lzip >/dev/null 2>&1; then
"$LZPLY" -c -6 -e 0 "$TD/mixed/text.txt" "$WORK/text6.lzply" >/dev/null 2>&1
# archive layout: 16 (global) + 78 (entry header) + 8 ("text.txt") = 102,
# then stored_size bytes, then the 2-byte end marker.
ASZ=$(stat -c %s "$WORK/text6.lzply")
dd if="$WORK/text6.lzply" bs=1 skip=102 count=$((ASZ - 104)) status=none > "$WORK/text6.lzip" 2>/dev/null
lzip -6 -c "$TD/mixed/text.txt" > "$WORK/text6.ref" 2>/dev/null
if cmp -s <(tail -c +7 "$WORK/text6.lzip") <(tail -c +7 "$WORK/text6.ref") &&
   [ "$(stat -c %s "$WORK/text6.lzip")" = "$(stat -c %s "$WORK/text6.ref")" ] &&
   lzip -t "$WORK/text6.lzip" 2>/dev/null; then
    ok "lzip -6 compressed data byte-identical to system lzip (+ lzip -t passes)"
else
    s1=$(stat -c %s "$WORK/text6.lzip"); s2=$(stat -c %s "$WORK/text6.ref")
    bad "lzip -6 stream differs from system lzip (mine=$s1 ref=$s2)"
fi
else
    echo "SKIP: lzip cross-check (no system lzip)"
fi

# --- 3. BCH levels: roundtrip at -e 0..7 (t = 0,1,2,4,8,16,32,32) -----
for E in 0 1 2 3 4 5 6 7; do
    rm -rf "$WORK/out"
    "$LZPLY" -c -6 -e "$E" "$TD/mixed" "$WORK/mixed-e$E.lzply" >/dev/null 2>&1 &&
    "$LZPLY" -t "$WORK/mixed-e$E.lzply" >/dev/null 2>&1 &&
    "$LZPLY" -d "$WORK/mixed-e$E.lzply" "$WORK/out" >/dev/null 2>&1 &&
    diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
        ok "BCH level $E roundtrip + test" || bad "BCH level $E roundtrip + test"
done

# --- 4. BCH corruption: single-file archive of text.txt -----------------
# Stored data starts at offset 102 (16 + 78 + 8 for "text.txt"). All
# flipped bits must land in ONE BCH block, so the flip range is the
# first block. For most pinned polys the blob is a single block
# (range = whole stored region); poly 0002 (m7,t2) has max_data 14
# bytes, so its first block is only 16 stored bytes ([102,118)).
# Flip exactly t bits in the first block -> must recover; flip t+1
# bits -> must fail cleanly (BCH uncorrectable, or SHA-256 catches a
# miscorrection). Pinned polys so t is known exactly.
# SPEC: poly t end_offset(0 = end of stored region)
for SPEC in "0002 2 118" "0018 2 0" "0025 4 0" "003a 32 0"; do
    set -- $SPEC
    POLY=$1; T=$2; ENDFIX=$3
    "$LZPLY" -c -6 poly="$POLY" "$TD/mixed/text.txt" "$WORK/bch-$POLY.lzply" >/dev/null 2>&1
    SZ=$(stat -c %s "$WORK/bch-$POLY.lzply")
    if [ "$ENDFIX" = "0" ]; then END=$((SZ - 2)); else END=$ENDFIX; fi
    # (a) t bit errors -> must recover
    cp "$WORK/bch-$POLY.lzply" "$WORK/bch-${POLY}a.lzply"
    "$CORRUPT_BITS" "$WORK/bch-${POLY}a.lzply" 42 "$T" 102 "$END" >/dev/null
    rm -rf "$WORK/out"
    if "$LZPLY" -d "$WORK/bch-${POLY}a.lzply" "$WORK/out" >/dev/null 2>&1 &&
       cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt"; then
        ok "BCH poly $POLY: $T bit errors recovered"
    else
        bad "BCH poly $POLY: $T bit errors recovered"
    fi
    # (b) t+1 bit errors -> must fail cleanly (never silent wrong data)
    cp "$WORK/bch-$POLY.lzply" "$WORK/bch-${POLY}b.lzply"
    "$CORRUPT_BITS" "$WORK/bch-${POLY}b.lzply" 43 $((T + 1)) 102 "$END" >/dev/null
    rm -rf "$WORK/out"
    if "$LZPLY" -d "$WORK/bch-${POLY}b.lzply" "$WORK/out" >/dev/null 2>&1; then
        bad "BCH poly $POLY: $((T+1)) bit errors must fail"
    else
        ok "BCH poly $POLY: $((T+1)) bit errors fails cleanly"
    fi
done

# --- 5. Combined BCH, v3 rejection, removed option ----------------
# combined: -9 + BCH t=16 (-e 5), with 16 bit errors -> recover
"$LZPLY" -c -9 -e 5 "$TD/mixed/text.txt" "$WORK/combo.lzply" >/dev/null 2>&1
cp "$WORK/combo.lzply" "$WORK/combo-c.lzply"
SZ=$(stat -c %s "$WORK/combo-c.lzply")
"$CORRUPT_BITS" "$WORK/combo-c.lzply" 46 16 102 $((SZ - 2)) >/dev/null
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/combo-c.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt" &&
    ok "combined -9 + BCH t16 with 16 corrupted bits recovered" ||
    bad "combined -9 + BCH t16 with 16 corrupted bits recovered"
# v3 archive rejected: take a fresh v4 archive and patch its version byte to 3
"$LZPLY" -c -6 "$TD/mixed/text.txt" "$WORK/v3.lzply" >/dev/null 2>&1
cp "$WORK/v3.lzply" "$WORK/v3patched.lzply"
printf '\x03' | dd of="$WORK/v3patched.lzply" bs=1 seek=4 conv=notrunc status=none 2>/dev/null
if "$LZPLY" -t "$WORK/v3patched.lzply" >/dev/null 2>&1; then
    bad "v3 archive (version byte 3) must be rejected"
else
    ok "v3 archive (version byte 3) is rejected (bad magic/version)"
fi
# the removed option is now a usage error (exit 1)
# (built by concatenation so the removed name does not appear literally)
"$LZPLY" -c -6 -pass"word=foo" >/dev/null 2>&1
RC=$?
[ "$RC" = "1" ] &&
    ok "removed option is now a usage error (exit 1)" ||
    bad "removed option is now a usage error (exit 1)"

# --- 6. Overwrite flags -------------------------------------------------
"$LZPLY" -c -6 "$TD/mixed/text.txt" "$WORK/ow.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"; mkdir -p "$WORK/out"
"$LZPLY" -d "$WORK/ow.lzply" "$WORK/out" >/dev/null 2>&1
SUM1=$(sha256sum "$WORK/out/text.txt" | cut -d' ' -f1)
echo "tampered" > "$WORK/out/text.txt"
# -n: must skip, file stays tampered
"$LZPLY" -d -n "$WORK/ow.lzply" "$WORK/out" >/dev/null 2>&1
grep -qx "tampered" "$WORK/out/text.txt" &&
    ok "-n skips existing file" || bad "-n skips existing file"
# -y: must overwrite, file restored
"$LZPLY" -d -y "$WORK/ow.lzply" "$WORK/out" >/dev/null 2>&1
SUM2=$(sha256sum "$WORK/out/text.txt" | cut -d' ' -f1)
[ "$SUM1" = "$SUM2" ] && ok "-y overwrites existing file" || bad "-y overwrites existing file"
# -a with 'n': skip. (-a used to mean ask-overwrite; it is now the
# append mode, and ask-overwrite is --ask only.)
echo "tampered" > "$WORK/out/text.txt"
printf 'n\n' | "$LZPLY" -d --ask "$WORK/ow.lzply" "$WORK/out" >/dev/null 2>&1
grep -qx "tampered" "$WORK/out/text.txt" &&
    ok "--ask with 'n' skips" || bad "--ask with 'n' skips"
# --ask with 'y': overwrite
printf 'y\n' | "$LZPLY" -d --ask "$WORK/ow.lzply" "$WORK/out" >/dev/null 2>&1
SUM3=$(sha256sum "$WORK/out/text.txt" | cut -d' ' -f1)
[ "$SUM1" = "$SUM3" ] && ok "--ask with 'y' overwrites" || bad "--ask with 'y' overwrites"

# --- 7. Edge cases ------------------------------------------------------
# empty directory restores empty
"$LZPLY" -c "$TD/emptydir" "$WORK/empty.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/empty.lzply" "$WORK/out" >/dev/null 2>&1
[ -d "$WORK/out/emptydir" ] && [ -z "$(ls -A "$WORK/out/emptydir")" ] &&
    ok "empty directory roundtrip" || bad "empty directory roundtrip"
# -l lists, -t verifies
"$LZPLY" -l "$WORK/mixed-e5.lzply" 2>/dev/null | grep -q "text.txt" &&
    ok "-l lists entries" || bad "-l lists entries"
"$LZPLY" -t "$WORK/mixed-e5.lzply" >/dev/null 2>&1 &&
    ok "-t verifies good archive" || bad "-t verifies good archive"
# truncated archive must fail
head -c 100 "$WORK/mixed-e5.lzply" > "$WORK/trunc.lzply"
"$LZPLY" -t "$WORK/trunc.lzply" >/dev/null 2>&1 &&
    bad "truncated archive must fail" || ok "truncated archive fails"
# not an archive must fail
echo "hello" > "$WORK/notarc.txt"
"$LZPLY" -t "$WORK/notarc.txt" >/dev/null 2>&1 &&
    bad "non-archive must fail" || ok "non-archive fails"

# --- 8. Big file: 50 MiB at -6 -e 3 (BCH t=4, multi-block) --------------
"$LZPLY" -c -6 -e 3 "$TD/big.bin" "$WORK/big.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/big.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/big.bin" "$WORK/out/big.bin" &&
    ok "50 MiB roundtrip at -6 -e 3 (BCH t=4)" || bad "50 MiB roundtrip at -6 -e 3"

# --- 9. v1 archives and the old magics are NOT readable (removed by design) ---
# Standing decision (Nov 25, 2026): no legacy support — the format
# changed freely, and the magic changed twice with the renames
# (LZRS -> LZBC -> LZPL), so an old-magic archive and a v1 archive
# are both simply unknown. Build all three by hand: a v1 global
# header (new magic + version byte 1) and old-magic headers (LZRS and
# LZBC, each + version byte 3) are each enough to prove the check
# rejects them instead of misreading them.
printf 'LZPL\x01' > "$WORK/fake-v1.lzply"
head -c 11 /dev/zero >> "$WORK/fake-v1.lzply"
if "$LZPLY" -l "$WORK/fake-v1.lzply" >/dev/null 2>&1; then
    bad "v1-style archive (version byte 1) must be rejected"
else
    ok "v1-style archive (version byte 1) is rejected (no legacy support)"
fi
printf 'LZRS\x03' > "$WORK/fake-oldmagic.lzply"
head -c 11 /dev/zero >> "$WORK/fake-oldmagic.lzply"
if "$LZPLY" -l "$WORK/fake-oldmagic.lzply" >/dev/null 2>&1; then
    bad "old-magic (LZRS) archive must be rejected"
else
    ok "old-magic (LZRS) archive is rejected (magic is now LZPL)"
fi
printf 'LZBC\x03' > "$WORK/fake-oldmagic-lzbc.lzply"
head -c 11 /dev/zero >> "$WORK/fake-oldmagic-lzbc.lzply"
if "$LZPLY" -l "$WORK/fake-oldmagic-lzbc.lzply" >/dev/null 2>&1; then
    bad "old-magic (LZBC) archive must be rejected"
else
    ok "old-magic (LZBC) archive is rejected (magic is now LZPL)"
fi

# --- 10. poly= pinning, auto-pick, and format version ------------------
"$LZPLY" -c -6 poly=003a "$TD/mixed/text.txt" "$WORK/pin.lzply" >/dev/null 2>&1
"$LZPLY" -l "$WORK/pin.lzply" 2>/dev/null | grep -q "BCH 003a" &&
    ok "poly=003a pins poly 003a (shown by -l)" ||
    bad "poly=003a pins poly 003a (shown by -l)"
"$LZPLY" -c -6 poly=58 "$TD/mixed/text.txt" "$WORK/pin58.lzply" >/dev/null 2>&1
"$LZPLY" -l "$WORK/pin58.lzply" 2>/dev/null | grep -q "BCH 003a" &&
    ok "poly=58 (decimal) pins poly 003a" ||
    bad "poly=58 (decimal) pins poly 003a"
# -l on a default archive shows a BCH poly id
"$LZPLY" -l "$WORK/mixed-e4.lzply" 2>/dev/null | grep -q "BCH 00" &&
    ok "-l shows BCH poly id for auto-picked archive" ||
    bad "-l shows BCH poly id for auto-picked archive"
# unknown poly is a usage error. (poly=0053 is NOT invalid: "0053"
# has no hex letters, so it parses as decimal 53 = poly 0x35, which
# is a real poly. Use ids that are invalid in both readings.)
if "$LZPLY" -c -6 poly=9999 "$TD/mixed/text.txt" "$WORK/badpoly.lzply" >/dev/null 2>&1; then
    bad "poly=9999 must be rejected"
else
    ok "poly=9999 rejected (usage error)"
fi
if "$LZPLY" -c -6 poly=83 "$TD/mixed/text.txt" "$WORK/badpoly2.lzply" >/dev/null 2>&1; then
    bad "poly=83 must be rejected"
else
    ok "poly=83 rejected (usage error)"
fi
if "$LZPLY" -c -6 poly=00ff "$TD/mixed/text.txt" "$WORK/badpoly3.lzply" >/dev/null 2>&1; then
    bad "poly=00ff must be rejected"
else
    ok "poly=00ff rejected (usage error)"
fi
# format version byte (offset 4): 4 for the v4 format, with or
# without BCH (a single format now; no legacy versions).
V_BCH=$(od -An -tu1 -j 4 -N 1 "$WORK/mixed-e4.lzply" | tr -d ' ')
V_NOECC=$(od -An -tu1 -j 4 -N 1 "$WORK/mixed-e0.lzply" | tr -d ' ')
[ "$V_BCH" = "4" ] && ok "BCH archive has version byte 4" || bad "BCH archive has version byte 4 (got $V_BCH)"
[ "$V_NOECC" = "4" ] && ok "no-ECC archive has version byte 4" || bad "no-ECC archive has version byte 4 (got $V_NOECC)"

# --- 11. Block splitting: blob > one block, with corruption -----------
# 600 KiB random file: blob ~600 KiB > max single block for the
# auto-picked poly, so it splits. Corrupt bits in the first block
# (offset 102, well inside block 1) and verify recovery / failure.
head -c 614400 /dev/urandom > "$WORK/split.bin"
"$LZPLY" -c -6 "$WORK/split.bin" "$WORK/split.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/split.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/split.bin" "$WORK/out/split.bin" &&
    ok "600 KiB split-blob roundtrip" || bad "600 KiB split-blob roundtrip"
cp "$WORK/split.lzply" "$WORK/split-a.lzply"
"$CORRUPT_BITS" "$WORK/split-a.lzply" 51 8 102 1102 >/dev/null
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/split-a.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/split.bin" "$WORK/out/split.bin" &&
    ok "split-blob: 8 bit errors in first block recovered" ||
    bad "split-blob: 8 bit errors in first block recovered"
cp "$WORK/split.lzply" "$WORK/split-b.lzply"
"$CORRUPT_BITS" "$WORK/split-b.lzply" 52 9 102 1102 >/dev/null
rm -rf "$WORK/out"
if "$LZPLY" -d "$WORK/split-b.lzply" "$WORK/out" >/dev/null 2>&1; then
    bad "split-blob: 9 bit errors in first block must fail"
else
    ok "split-blob: 9 bit errors in first block fails cleanly"
fi

# --- 12. -a append ------------------------------------------------------
# (a) create an archive with -c, then -a a single directory (with a
# nested subdirectory, covering (j)); verify -l shows the new entries,
# the count increased by exactly the new entries, -t passes, and a
# full extract matches both trees.
mkdir -p "$WORK/appdir/sub"
echo "append one" > "$WORK/appdir/one.txt"
echo "append two" > "$WORK/appdir/sub/two.txt"
"$LZPLY" -c -6 "$TD/mixed" "$WORK/app-a.lzply" >/dev/null 2>&1
C0=$("$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | tail -1 | awk '{print $1}')
"$LZPLY" -a "$WORK/app-a.lzply" "$WORK/appdir" >/dev/null 2>&1
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "appdir/one.txt" &&
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "appdir/sub/two.txt" &&
"$LZPLY" -t "$WORK/app-a.lzply" >/dev/null 2>&1 &&
    ok "-a a single directory: new entries listed and archive verifies" ||
    bad "-a a single directory: new entries listed and archive verifies"
N1=$("$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | tail -1 | awk '{print $1}')
[ "$N1" = "$((C0 + 4))" ] && ok "-a: entry count increased by 4 (dir + 2 files + subdir)" || bad "-a: entry count increased by 4 (got $C0 -> $N1)"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/app-a.lzply" "$WORK/out" >/dev/null 2>&1 &&
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
diff -r "$WORK/appdir" "$WORK/out/appdir" >/dev/null 2>&1 &&
    ok "-a directory: full extract matches both trees (nested preserved)" ||
    bad "-a directory: full extract matches both trees (nested preserved)"
# (b) -a several individual files at once
echo "file one" > "$WORK/f1.txt"
echo "file two" > "$WORK/f2.txt"
echo "file three" > "$WORK/f3.txt"
"$LZPLY" -a "$WORK/app-a.lzply" "$WORK/f1.txt" "$WORK/f2.txt" "$WORK/f3.txt" >/dev/null 2>&1
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "f1.txt" &&
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "f2.txt" &&
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "f3.txt" &&
"$LZPLY" -t "$WORK/app-a.lzply" >/dev/null 2>&1 &&
    ok "-a several individual files at once" ||
    bad "-a several individual files at once"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/app-a.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/f1.txt" "$WORK/out/f1.txt" &&
cmp -s "$WORK/f2.txt" "$WORK/out/f2.txt" &&
cmp -s "$WORK/f3.txt" "$WORK/out/f3.txt" &&
    ok "-a files: extract matches" || bad "-a files: extract matches"
# (c) -a on a non-existent archive creates it
rm -f "$WORK/app-new.lzply"
"$LZPLY" -a "$WORK/app-new.lzply" "$WORK/f1.txt" >/dev/null 2>&1
[ -f "$WORK/app-new.lzply" ] &&
"$LZPLY" -l "$WORK/app-new.lzply" 2>/dev/null | grep -q "f1.txt" &&
"$LZPLY" -t "$WORK/app-new.lzply" >/dev/null 2>&1 &&
    ok "-a on a missing archive creates it" ||
    bad "-a on a missing archive creates it"
# (d) -a a file that already exists: the new content wins, exactly one
# entry for that path, and the other entries are intact.
cp "$TD/mixed/text.txt" "$WORK/rep.txt"
"$LZPLY" -c -6 "$TD/mixed" "$WORK/app-rep.lzply" >/dev/null 2>&1
"$LZPLY" -a "$WORK/app-rep.lzply" "$WORK/rep.txt" >/dev/null 2>&1
echo "replacement text, version two" > "$WORK/rep.txt"
"$LZPLY" -a "$WORK/app-rep.lzply" "$WORK/rep.txt" >/dev/null 2>&1
[ "$("$LZPLY" -l "$WORK/app-rep.lzply" 2>/dev/null | grep -c "rep.txt")" = "1" ] &&
    ok "-a replace: exactly one entry for the replaced path" ||
    bad "-a replace: exactly one entry for the replaced path (got $("$LZPLY" -l "$WORK/app-rep.lzply" 2>/dev/null | grep -c "rep.txt"))"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/app-rep.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/rep.txt" "$WORK/out/rep.txt" &&
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
    ok "-a replace: new content wins, other entries intact" ||
    bad "-a replace: new content wins, other entries intact"
# (e) -a a file onto an existing archive: appended entry extracts,
# old entries intact.
"$LZPLY" -c -6 "$TD/mixed" "$WORK/app-pw.lzply" >/dev/null 2>&1
"$LZPLY" -a "$WORK/app-pw.lzply" "$WORK/f1.txt" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/app-pw.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/f1.txt" "$WORK/out/f1.txt" &&
diff -r "$TD/mixed" "$WORK/out/mixed" >/dev/null 2>&1 &&
    ok "-a a file: appended entry extracts, old entries intact" ||
    bad "-a a file: appended entry extracts, old entries intact"
# (f) -a with poly=NN and with -e: new entries use the pinned poly / t.
"$LZPLY" -a poly=003a "$WORK/app-a.lzply" "$WORK/f1.txt" >/dev/null 2>&1
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep -q "BCH 003a" &&
    ok "-a poly=003a: new entry uses pinned poly 003a" ||
    bad "-a poly=003a: new entry uses pinned poly 003a"
"$LZPLY" -a -e 6 "$WORK/app-a.lzply" "$WORK/f2.txt" >/dev/null 2>&1
"$LZPLY" -l "$WORK/app-a.lzply" 2>/dev/null | grep "f2.txt" | grep -q "BCH 00" &&
"$LZPLY" -t "$WORK/app-a.lzply" >/dev/null 2>&1 &&
    ok "-a -e 6: new entry uses a BCH poly and archive verifies" ||
    bad "-a -e 6: new entry uses a BCH poly and archive verifies"
# (g) removed: -a onto a v1 RS archive. v1 is gone by design
# (standing decision, Nov 25, 2026); there is no v1 to append to.
# incremental append really is incremental: the entry bytes before
# the end marker are unchanged (only the global header count/version
# may change). Snapshot the archive, append a fresh file, compare.
SZ1=$(stat -c %s "$WORK/app-a.lzply")
dd if="$WORK/app-a.lzply" bs=1 skip=16 count=$((SZ1 - 18)) status=none > "$WORK/app-before.bin" 2>/dev/null
echo "brand new file" > "$WORK/f4.txt"
"$LZPLY" -a "$WORK/app-a.lzply" "$WORK/f4.txt" >/dev/null 2>&1
dd if="$WORK/app-a.lzply" bs=1 skip=16 count=$((SZ1 - 18)) status=none > "$WORK/app-after.bin" 2>/dev/null
cmp -s "$WORK/app-before.bin" "$WORK/app-after.bin" &&
    ok "-a incremental: existing entry bytes preserved byte-for-byte" ||
    bad "-a incremental: existing entry bytes preserved byte-for-byte"

# --- 13. Selective extract (-d / -t / -l) ------------------------------
"$LZPLY" -c -6 "$TD/mixed" "$WORK/sel.lzply" >/dev/null 2>&1
# (h) extract only a directory by prefix
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/sel.lzply" "$WORK/out" mixed/nested >/dev/null 2>&1
[ -f "$WORK/out/mixed/nested/a.txt" ] &&
[ -f "$WORK/out/mixed/nested/deep/b.txt" ] &&
[ ! -f "$WORK/out/mixed/text.txt" ] &&
    ok "-d selector (dir prefix): only nested/ extracted" ||
    bad "-d selector (dir prefix): only nested/ extracted"
# selector with trailing slash
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/sel.lzply" "$WORK/out" mixed/nested/ >/dev/null 2>&1
[ -f "$WORK/out/mixed/nested/a.txt" ] && [ ! -f "$WORK/out/mixed/text.txt" ] &&
    ok "-d selector (trailing slash): only nested/ extracted" ||
    bad "-d selector (trailing slash): only nested/ extracted"
# extract only a single file by exact path
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/sel.lzply" "$WORK/out" mixed/text.txt >/dev/null 2>&1
[ -f "$WORK/out/mixed/text.txt" ] &&
[ ! -f "$WORK/out/mixed/nested/a.txt" ] &&
    ok "-d selector (exact file): only that file extracted" ||
    bad "-d selector (exact file): only that file extracted"
# a prefix that is NOT a directory boundary must not match
rm -rf "$WORK/out"
if "$LZPLY" -d "$WORK/sel.lzply" "$WORK/out" mixed/neste >/dev/null 2>&1; then
    [ ! -f "$WORK/out/mixed/nested/a.txt" ] &&
        ok "-d selector 'mixed/neste' does not match 'mixed/nested'" ||
        bad "-d selector 'mixed/neste' does not match 'mixed/nested'"
else
    bad "-d selector 'mixed/neste' must exit 0 (no match)"
fi
# a selector matching nothing: clear message, exit 0, nothing extracted
rm -rf "$WORK/out"; mkdir -p "$WORK/out"
OUT=$("$LZPLY" -d "$WORK/sel.lzply" "$WORK/out" zzz 2>&1)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep -q "no entries match" &&
[ -z "$(find "$WORK/out" -type f)" ] &&
    ok "-d selector matching nothing: message, exit 0, nothing extracted" ||
    bad "-d selector matching nothing: message, exit 0, nothing extracted (rc=$RC)"
# (i) -t with a selector
"$LZPLY" -t "$WORK/sel.lzply" mixed/nested >/dev/null 2>&1 &&
    ok "-t with selector: tests only the selected entries" ||
    bad "-t with selector: tests only the selected entries"
OUT=$("$LZPLY" -t "$WORK/sel.lzply" zzz 2>&1)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep -q "no entries match" &&
    ok "-t selector matching nothing: message, exit 0" ||
    bad "-t selector matching nothing: message, exit 0 (rc=$RC)"
# (bonus) -l with a selector
"$LZPLY" -l "$WORK/sel.lzply" mixed/nested 2>/dev/null | grep -q "nested/a.txt" &&
! "$LZPLY" -l "$WORK/sel.lzply" mixed/nested 2>/dev/null | grep -q "text.txt" &&
    ok "-l with selector: lists only matching entries" ||
    bad "-l with selector: lists only matching entries"

# --- 13. -i inspect: headers only, correct metadata -------------------
# A small tree with known mtimes and permissions.
rm -rf "$WORK/insp"
mkdir -p "$WORK/insp/sub" "$WORK/insp/empty"
printf 'hello\n' > "$WORK/insp/a.txt"
printf 'nested\n' > "$WORK/insp/sub/b.txt"
chmod 0640 "$WORK/insp/a.txt"
chmod 0750 "$WORK/insp/sub"
touch -d "2024-03-15 10:30:00 UTC" "$WORK/insp/a.txt"
touch -d "2025-07-20 14:00:00 UTC" "$WORK/insp/sub/b.txt"
touch -d "2024-01-01 00:00:00 UTC" "$WORK/insp/sub" "$WORK/insp/empty"
"$LZPLY" -c -y -6 "$WORK/insp" "$WORK/insp.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -i "$WORK/insp.lzply" 2>/dev/null)
echo "$OUT" | grep "insp/a.txt" | grep -q "2024-03-15 10:30:00 UTC" &&
echo "$OUT" | grep "insp/a.txt" | grep -q "0640" &&
echo "$OUT" | grep "insp/a.txt" | grep -q "rw-r-----" &&
echo "$OUT" | grep "insp/a.txt" | grep -q "BCH 00" &&
    ok "-i: a.txt shows 2024-03-15 mtime, 0640/-rw-r-----, BCH poly" ||
    bad "-i: a.txt shows 2024-03-15 mtime, 0640/-rw-r-----, BCH poly"
echo "$OUT" | grep "insp/sub/b.txt" | grep -q "2025-07-20 14:00:00 UTC" &&
    ok "-i: sub/b.txt shows 2025-07-20 mtime" ||
    bad "-i: sub/b.txt shows 2025-07-20 mtime"
echo "$OUT" | grep "insp/sub/" | grep -q "0750" &&
echo "$OUT" | grep "insp/sub/" | grep -q "drwxr-x---" &&
    ok "-i: sub/ shows 0750/drwxr-x---" ||
    bad "-i: sub/ shows 0750/drwxr-x---"
echo "$OUT" | grep "insp/empty/" | grep -q "directory" &&
    ok "-i: empty dir listed as directory" ||
    bad "-i: empty dir listed as directory"
echo "$OUT" | grep -q "5 entries (3 directories, 2 files)" &&
    ok "-i: summary counts 5 entries (3 dirs, 2 files)" ||
    bad "-i: summary counts 5 entries (3 dirs, 2 files)"
# -i reads headers only: corrupt the data of a single-file archive
# (data starts at 102 for an 8-char path) and -i still succeeds while
# -t fails. The file is 1 KiB of random data, so the stored blob is
# ~1 KiB and 100 zeroed bytes at 102 are well inside it.
head -c 1024 /dev/urandom > "$WORK/rand.bin"
"$LZPLY" -c -y -6 "$WORK/rand.bin" "$WORK/rand.lzply" >/dev/null 2>&1
cp "$WORK/rand.lzply" "$WORK/rand-corrupt.lzply"
dd if=/dev/zero of="$WORK/rand-corrupt.lzply" bs=1 seek=102 count=100 conv=notrunc status=none
"$LZPLY" -i "$WORK/rand-corrupt.lzply" >/dev/null 2>&1 &&
    ok "-i succeeds on an archive whose data is corrupted (headers only)" ||
    bad "-i succeeds on an archive whose data is corrupted (headers only)"
if "$LZPLY" -t "$WORK/rand-corrupt.lzply" >/dev/null 2>&1; then
    bad "-t fails on the same corrupted archive"
else
    ok "-t fails on the same corrupted archive"
fi

# --- 14. -tr tree: exact output, implied dirs, empty dirs -------------
rm -rf "$WORK/tree"
mkdir -p "$WORK/tree/a/b" "$WORK/tree/empty"
printf 'hi\n' > "$WORK/tree/a/f1.txt"
printf 'yo\n' > "$WORK/tree/a/b/f2.txt"
printf 'z\n' > "$WORK/tree/top.txt"
"$LZPLY" -c -y -6 "$WORK/tree" "$WORK/tree.lzply" >/dev/null 2>&1
(cd "$WORK" && "$LZPLY" -tr tree.lzply > tree-out.txt 2>&1)
cat > "$WORK/tree-expected.txt" <<'EOF'
tree.lzply
└── tree/
    ├── a/
    │   ├── b/
    │   │   └── f2.txt (3 B)
    │   └── f1.txt (3 B)
    ├── empty/
    └── top.txt (2 B)

4 directories, 3 files
EOF
diff -u "$WORK/tree-expected.txt" "$WORK/tree-out.txt" >/dev/null &&
    ok "-tr: exact tree output (nested, empty dir, sizes, summary)" ||
    bad "-tr: exact tree output (nested, empty dir, sizes, summary)"
# Implied directories: give the dirs a 2025 mtime and the files a 2024
# mtime, then -tr -year 2024 keeps the files but drops the explicit
# dir entries, so the parents appear as implied nodes (and empty/,
# which has no files, disappears).
touch -d "2025-01-01 00:00:00 UTC" "$WORK/tree" "$WORK/tree/a" "$WORK/tree/a/b" "$WORK/tree/empty"
touch -d "2024-06-01 12:00:00 UTC" "$WORK/tree/a/f1.txt" "$WORK/tree/a/b/f2.txt" "$WORK/tree/top.txt"
"$LZPLY" -c -y -6 "$WORK/tree" "$WORK/tree2024.lzply" >/dev/null 2>&1
(cd "$WORK" && "$LZPLY" -tr tree2024.lzply -year 2024 > tree2024-out.txt 2>&1)
cat > "$WORK/tree2024-expected.txt" <<'EOF'
tree2024.lzply
└── tree/
    ├── a/
    │   ├── b/
    │   │   └── f2.txt (3 B)
    │   └── f1.txt (3 B)
    └── top.txt (2 B)

3 directories, 3 files
EOF
diff -u "$WORK/tree2024-expected.txt" "$WORK/tree2024-out.txt" >/dev/null &&
    ok "-tr -year 2024: implied dirs for filtered-out parents, 3 dirs 3 files" ||
    bad "-tr -year 2024: implied dirs for filtered-out parents, 3 dirs 3 files"

# --- 15. -datestart / -dateend ---------------------------------------
# Files with mtimes spread across several days.
rm -rf "$WORK/dates"
mkdir -p "$WORK/dates"
printf 'd1\n' > "$WORK/dates/day1.txt"
printf 'd2\n' > "$WORK/dates/day2.txt"
printf 'd3\n' > "$WORK/dates/day3.txt"
printf 'd4\n' > "$WORK/dates/day4.txt"
touch -d "2024-01-10 08:00:00 UTC" "$WORK/dates/day1.txt"
touch -d "2024-01-11 12:00:00 UTC" "$WORK/dates/day2.txt"
touch -d "2024-01-12 18:00:00 UTC" "$WORK/dates/day3.txt"
touch -d "2024-01-13 23:00:00 UTC" "$WORK/dates/day4.txt"
"$LZPLY" -c -y -6 "$WORK/dates" "$WORK/dates.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d -y "$WORK/dates.lzply" "$WORK/out" -datestart 2024-01-11 -dateend 2024-01-12 >/dev/null 2>&1
[ -f "$WORK/out/dates/day2.txt" ] && [ -f "$WORK/out/dates/day3.txt" ] &&
[ ! -f "$WORK/out/dates/day1.txt" ] && [ ! -f "$WORK/out/dates/day4.txt" ] &&
    ok "-d -datestart/-dateend: only Jan 11-12 extracted" ||
    bad "-d -datestart/-dateend: only Jan 11-12 extracted"
OUT=$("$LZPLY" -i "$WORK/dates.lzply" -datestart 2024-01-11 -dateend 2024-01-12 2>/dev/null)
echo "$OUT" | grep -q "day2.txt" && echo "$OUT" | grep -q "day3.txt" &&
! echo "$OUT" | grep -q "day1.txt" && ! echo "$OUT" | grep -q "day4.txt" &&
    ok "-i -datestart/-dateend: only Jan 11-12 listed" ||
    bad "-i -datestart/-dateend: only Jan 11-12 listed"
(cd "$WORK" && "$LZPLY" -tr dates.lzply -datestart 2024-01-11 -dateend 2024-01-12 > dates-tr.txt 2>&1)
grep -q "day2.txt" "$WORK/dates-tr.txt" && grep -q "day3.txt" "$WORK/dates-tr.txt" &&
! grep -q "day1.txt" "$WORK/dates-tr.txt" && ! grep -q "day4.txt" "$WORK/dates-tr.txt" &&
    ok "-tr -datestart/-dateend: only Jan 11-12 in tree" ||
    bad "-tr -datestart/-dateend: only Jan 11-12 in tree"
# dateend is inclusive through 23:59:59: day4 is Jan 13 23:00, so a
# single-day range on Jan 13 includes it.
rm -rf "$WORK/out"
"$LZPLY" -d -y "$WORK/dates.lzply" "$WORK/out" -datestart 2024-01-13 -dateend 2024-01-13 >/dev/null 2>&1
[ -f "$WORK/out/dates/day4.txt" ] && [ ! -f "$WORK/out/dates/day3.txt" ] &&
    ok "-d single-day range Jan 13: only day4 (23:00) extracted" ||
    bad "-d single-day range Jan 13: only day4 (23:00) extracted"
# Exact datetime form (bonus).
rm -rf "$WORK/out"
"$LZPLY" -d -y "$WORK/dates.lzply" "$WORK/out" -datestart 2024-01-11T12:00:00 -dateend 2024-01-11T12:00:00 >/dev/null 2>&1
[ -f "$WORK/out/dates/day2.txt" ] && [ ! -f "$WORK/out/dates/day3.txt" ] &&
    ok "-d exact datetime range: only day2 (12:00) extracted" ||
    bad "-d exact datetime range: only day2 (12:00) extracted"

# --- 16. -year --------------------------------------------------------
rm -rf "$WORK/years"
mkdir -p "$WORK/years"
printf 'y24\n' > "$WORK/years/from2024.txt"
printf 'y25\n' > "$WORK/years/from2025.txt"
touch -d "2024-05-01 09:00:00 UTC" "$WORK/years/from2024.txt"
touch -d "2025-05-01 09:00:00 UTC" "$WORK/years/from2025.txt"
"$LZPLY" -c -y -6 "$WORK/years" "$WORK/years.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d -y "$WORK/years.lzply" "$WORK/out" -year 2024 >/dev/null 2>&1
[ -f "$WORK/out/years/from2024.txt" ] && [ ! -f "$WORK/out/years/from2025.txt" ] &&
    ok "-d -year 2024: only the 2024 file extracted" ||
    bad "-d -year 2024: only the 2024 file extracted"
OUT=$("$LZPLY" -i "$WORK/years.lzply" -year 2025 2>/dev/null)
echo "$OUT" | grep -q "from2025.txt" && ! echo "$OUT" | grep -q "from2024.txt" &&
    ok "-i -year 2025: only the 2025 file listed" ||
    bad "-i -year 2025: only the 2025 file listed"

# --- 17. Combined filters, empty range, bad dates ---------------------
rm -rf "$WORK/combo"
mkdir -p "$WORK/combo/photos" "$WORK/combo/docs"
printf 'p24\n' > "$WORK/combo/photos/old.jpg"
printf 'p25\n' > "$WORK/combo/photos/new.jpg"
printf 'd24\n' > "$WORK/combo/docs/old.txt"
printf 'd25\n' > "$WORK/combo/docs/new.txt"
touch -d "2024-02-01 00:00:00 UTC" "$WORK/combo/photos/old.jpg" "$WORK/combo/docs/old.txt"
touch -d "2025-02-01 00:00:00 UTC" "$WORK/combo/photos/new.jpg" "$WORK/combo/docs/new.txt"
"$LZPLY" -c -y -6 "$WORK/combo" "$WORK/combo.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d -y "$WORK/combo.lzply" "$WORK/out" combo/photos/ -year 2024 >/dev/null 2>&1
[ -f "$WORK/out/combo/photos/old.jpg" ] && [ ! -f "$WORK/out/combo/photos/new.jpg" ] &&
[ ! -f "$WORK/out/combo/docs/old.txt" ] &&
    ok "-d selector AND -year: only photos/old.jpg (2024) extracted" ||
    bad "-d selector AND -year: only photos/old.jpg (2024) extracted"
OUT=$("$LZPLY" -i "$WORK/combo.lzply" -year 2024 -datestart 2024-01-01 -dateend 2024-06-30 2>/dev/null)
echo "$OUT" | grep -q "photos/old.jpg" && echo "$OUT" | grep -q "docs/old.txt" &&
! echo "$OUT" | grep -q "new.jpg" && ! echo "$OUT" | grep -q "new.txt" &&
    ok "-i -year AND -datestart/-dateend: only 2024 H1 entries listed" ||
    bad "-i -year AND -datestart/-dateend: only 2024 H1 entries listed"
OUT=$("$LZPLY" -i "$WORK/combo.lzply" -year 2024 -datestart 2025-01-01 2>&1)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep -q "no entries match" &&
    ok "-i -year 2024 AND -datestart 2025: no match, exit 0" ||
    bad "-i -year 2024 AND -datestart 2025: no match, exit 0 (rc=$RC)"
OUT=$("$LZPLY" -i "$WORK/dates.lzply" -datestart 2024-01-13 -dateend 2024-01-10 2>&1)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep -q "no entries match" &&
    ok "-i datestart after dateend: empty range, exit 0" ||
    bad "-i datestart after dateend: empty range, exit 0 (rc=$RC)"
if "$LZPLY" -i "$WORK/dates.lzply" -datestart 2024-02-30 >/dev/null 2>&1; then
    bad "-i bad date 2024-02-30 must be a usage error"
else
    ok "-i bad date 2024-02-30 is a usage error"
fi
if "$LZPLY" -i "$WORK/dates.lzply" -datestart 2024/01/01 >/dev/null 2>&1; then
    bad "-i bad date 2024/01/01 must be a usage error"
else
    ok "-i bad date 2024/01/01 is a usage error"
fi
if "$LZPLY" -i "$WORK/dates.lzply" -year 99 >/dev/null 2>&1; then
    bad "-i bad year 99 must be a usage error"
else
    ok "-i bad year 99 is a usage error"
fi

# --- 18. -a preserves mtime; -i/-tr on the appended archive ---------
rm -rf "$WORK/enc"
mkdir -p "$WORK/enc"
printf 'secret\n' > "$WORK/enc/secret.txt"
printf 'plain\n' > "$WORK/enc/plain.txt"
touch -d "2024-08-08 08:08:08 UTC" "$WORK/enc/secret.txt"
touch -d "2024-08-09 09:09:09 UTC" "$WORK/enc/plain.txt"
"$LZPLY" -c -y -6 "$WORK/enc/secret.txt" "$WORK/enc.lzply" >/dev/null 2>&1
"$LZPLY" -a "$WORK/enc.lzply" "$WORK/enc/plain.txt" >/dev/null 2>&1
OUT=$("$LZPLY" -i "$WORK/enc.lzply" 2>/dev/null)
echo "$OUT" | grep "plain.txt" | grep -q "2024-08-09 09:09:09 UTC" &&
    ok "-a preserves mtime: appended plain.txt shows 2024-08-09" ||
    bad "-a preserves mtime: appended plain.txt shows 2024-08-09"
OUT=$("$LZPLY" -i "$WORK/enc.lzply" 2>/dev/null)
RC=$?
echo "$OUT" | grep "secret.txt" | grep -q "2024-08-08 08:08:08 UTC" && [ "$RC" = "0" ] &&
    ok "-i on appended archive: mtimes shown for both entries" ||
    bad "-i on appended archive: mtimes shown for both entries (rc=$RC)"
(cd "$WORK" && "$LZPLY" -tr enc.lzply > enc-tr.txt 2>&1)
RC=$?
grep -q "secret.txt" "$WORK/enc-tr.txt" && grep -q "plain.txt" "$WORK/enc-tr.txt" && [ "$RC" = "0" ] &&
    ok "-tr on appended archive: tree shows both files" ||
    bad "-tr on appended archive: tree shows both files (rc=$RC)"

# --- 19. lzply_stat ---------------------------------------------------
# A small archive with pinned polys and known entries.
if [ -x "$STAT" ]; then
printf 'stat test one\n' > "$WORK/stat1.txt"
printf 'stat test two, a bit longer\n' > "$WORK/stat2.txt"
"$LZPLY" -c -y -6 poly=003a "$WORK/stat1.txt" "$WORK/stat.lzply" >/dev/null 2>&1
"$LZPLY" -a poly=000b "$WORK/stat.lzply" "$WORK/stat2.txt" >/dev/null 2>&1
OUT=$("$STAT" "$WORK/stat.lzply" 2>/dev/null)
echo "$OUT" | grep "stat1.txt" | grep -Eq "003a[[:space:]]+32[[:space:]]" &&
echo "$OUT" | grep "stat2.txt" | grep -Eq "000b[[:space:]]+8[[:space:]]" &&
echo "$OUT" | grep -q "2 entries" &&
    ok "lzply_stat: poly ids, t values and totals for a known archive" ||
    bad "lzply_stat: poly ids, t values and totals for a known archive"
echo "$OUT" | grep -q "overall ECC overhead" &&
echo "$OUT" | grep "stat1.txt" | grep -q "%" &&
    ok "lzply_stat: ECC overhead % shown per entry and overall" ||
    bad "lzply_stat: ECC overhead % shown per entry and overall"
# selector: only one entry
OUT=$("$STAT" "$WORK/stat.lzply" stat2.txt 2>/dev/null)
echo "$OUT" | grep -q "stat2.txt" && ! echo "$OUT" | grep -q "stat1.txt" &&
    ok "lzply_stat with selector: only that entry" ||
    bad "lzply_stat with selector: only that entry"
# not an archive: error, non-zero
if "$STAT" "$WORK/notarc.txt" >/dev/null 2>&1; then
    bad "lzply_stat on a non-archive must fail"
else
    ok "lzply_stat on a non-archive fails"
fi
else
    echo "SKIP: lzply_stat tests (binary not found next to lzply)"
fi

# --- 20. lzply_heal ---------------------------------------------------
if [ -x "$HEAL" ]; then
# (a) pure heal: no change, roundtrip intact
cp "$WORK/stat.lzply" "$WORK/heal-pure.lzply"
"$HEAL" "$WORK/heal-pure.lzply" >/dev/null 2>&1 &&
"$LZPLY" -t "$WORK/heal-pure.lzply" >/dev/null 2>&1 &&
    ok "lzply_heal (pure): no-op on a healthy archive, verifies" ||
    bad "lzply_heal (pure): no-op on a healthy archive, verifies"
# (b) level raise: -e 6 moves stat2.txt off poly 000b (t=8); data identical
cp "$WORK/stat.lzply" "$WORK/heal-raise.lzply"
"$HEAL" -e 6 "$WORK/heal-raise.lzply" >/dev/null 2>&1
"$LZPLY" -l "$WORK/heal-raise.lzply" 2>/dev/null | grep "stat2.txt" | grep -qv "BCH 000b" &&
"$LZPLY" -t "$WORK/heal-raise.lzply" >/dev/null 2>&1 &&
rm -rf "$WORK/out" &&
"$LZPLY" -d -y "$WORK/heal-raise.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/stat1.txt" "$WORK/out/stat1.txt" &&
cmp -s "$WORK/stat2.txt" "$WORK/out/stat2.txt" &&
    ok "lzply_heal -e 6: level raised, data byte-identical" ||
    bad "lzply_heal -e 6: level raised, data byte-identical"
# (c) strip ECC: -e 0, no BCH left, data identical
cp "$WORK/stat.lzply" "$WORK/heal-strip.lzply"
"$HEAL" -e 0 "$WORK/heal-strip.lzply" >/dev/null 2>&1
! "$LZPLY" -l "$WORK/heal-strip.lzply" 2>/dev/null | grep -q "BCH" &&
"$LZPLY" -t "$WORK/heal-strip.lzply" >/dev/null 2>&1 &&
    ok "lzply_heal -e 0: ECC stripped, archive still verifies" ||
    bad "lzply_heal -e 0: ECC stripped, archive still verifies"
# (d) bit-error correction: single-file archive, -e 4 (t=8), one block.
# Data starts at 102 (16 + 78 + 8 for "tiny.txt"); flip 5 bits in the
# stored region -> heal recovers; flip 9 -> uncorrectable (exit non-zero,
# entry kept, -t still fails).
printf 'heal bit test\n' > "$WORK/tiny.txt"
"$LZPLY" -c -y -6 -e 4 "$WORK/tiny.txt" "$WORK/heal-bits.lzply" >/dev/null 2>&1
cp "$WORK/heal-bits.lzply" "$WORK/heal-bits-a.lzply"
SZ=$(stat -c %s "$WORK/heal-bits-a.lzply")
"$CORRUPT_BITS" "$WORK/heal-bits-a.lzply" 61 5 102 $((SZ - 2)) >/dev/null
"$HEAL" "$WORK/heal-bits-a.lzply" >/dev/null 2>&1 &&
"$LZPLY" -t "$WORK/heal-bits-a.lzply" >/dev/null 2>&1 &&
rm -rf "$WORK/out" &&
"$LZPLY" -d -y "$WORK/heal-bits-a.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/tiny.txt" "$WORK/out/tiny.txt" &&
    ok "lzply_heal: 5 flipped bits (t=8) corrected, data recovered" ||
    bad "lzply_heal: 5 flipped bits (t=8) corrected, data recovered"
cp "$WORK/heal-bits.lzply" "$WORK/heal-bits-b.lzply"
SZ=$(stat -c %s "$WORK/heal-bits-b.lzply")
"$CORRUPT_BITS" "$WORK/heal-bits-b.lzply" 62 9 102 $((SZ - 2)) >/dev/null
if "$HEAL" "$WORK/heal-bits-b.lzply" >/dev/null 2>&1; then
    bad "lzply_heal: 9 flipped bits (t=8) must exit non-zero"
else
    ok "lzply_heal: 9 flipped bits (t=8) exits non-zero, entry kept"
fi
# (e) -o: original untouched, output healed
cp "$WORK/stat.lzply" "$WORK/heal-orig.lzply"
"$HEAL" -e 6 -o "$WORK/heal-out.lzply" "$WORK/heal-orig.lzply" >/dev/null 2>&1
"$LZPLY" -l "$WORK/heal-orig.lzply" 2>/dev/null | grep "stat1.txt" | grep -q "BCH 003a" &&
"$LZPLY" -l "$WORK/heal-out.lzply" 2>/dev/null | grep "stat2.txt" | grep -qv "BCH 000b" &&
    ok "lzply_heal -o: original untouched, output healed" ||
    bad "lzply_heal -o: original untouched, output healed"
# (f) heal with a level raise on a plain archive: data identical
"$LZPLY" -c -y -6 -e 4 "$WORK/tiny.txt" "$WORK/heal-plain.lzply" >/dev/null 2>&1
"$HEAL" -e 6 "$WORK/heal-plain.lzply" >/dev/null 2>&1 &&
rm -rf "$WORK/out" &&
"$LZPLY" -d -y "$WORK/heal-plain.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$WORK/tiny.txt" "$WORK/out/tiny.txt" &&
    ok "lzply_heal -e 6 on a plain archive: data byte-identical" ||
    bad "lzply_heal -e 6 on a plain archive: data byte-identical"
# (g) selector: only one entry healed
cp "$WORK/stat.lzply" "$WORK/heal-sel.lzply"
"$HEAL" -e 6 "$WORK/heal-sel.lzply" stat2.txt >/dev/null 2>&1
"$LZPLY" -l "$WORK/heal-sel.lzply" 2>/dev/null | grep "stat1.txt" | grep -q "BCH 003a" &&
! "$LZPLY" -l "$WORK/heal-sel.lzply" 2>/dev/null | grep "stat2.txt" | grep -q "BCH 000b" &&
    ok "lzply_heal with selector: only that entry healed" ||
    bad "lzply_heal with selector: only that entry healed"
else
    echo "SKIP: lzply_heal tests (binary not found next to lzply)"
fi

# --- 21. lzply_check: BER detection ------------------------------------
if [ -x "$CHECK" ]; then
# (a) clean archive: BER 0, exit 0, status clean
printf 'heal bit test\n' > "$WORK/tiny.txt"
"$LZPLY" -c -y -6 -e 4 "$WORK/tiny.txt" "$WORK/check-clean.lzply" >/dev/null 2>&1
OUT=$("$CHECK" "$WORK/check-clean.lzply" 2>/dev/null)
RC=$?
echo "$OUT" | grep -q "overall BER: 0" && [ "$RC" = "0" ] &&
echo "$OUT" | grep "tiny.txt" | grep -q "clean" &&
    ok "lzply_check clean archive: BER 0, exit 0, clean" ||
    bad "lzply_check clean archive: BER 0, exit 0, clean (rc=$RC)"
# (b) known injected errors: 5 bits flipped (t=8) -> corrected == 5 and
# BER == 5 / (8 * stored_size), verified through --json.
cp "$WORK/check-clean.lzply" "$WORK/check-err5.lzply"
SZ=$(stat -c %s "$WORK/check-err5.lzply")
"$CORRUPT_BITS" "$WORK/check-err5.lzply" 61 5 102 $((SZ - 2)) >/dev/null
"$CHECK" --json "$WORK/check-err5.lzply" 2>/dev/null | python3 -c '
import json, sys
d = json.load(sys.stdin)
e = d["entries"][0]
assert e["corrected"] == 5, e
assert abs(e["ber"] - 5 / e["stored_bits"]) < 1e-15, e
assert e["status"] == "correctable", e
assert d["totals"]["overall_ber"] == e["ber"], d["totals"]
assert d["status"] == "ok", d
print("json ok")
' >/dev/null 2>&1 &&
    ok "lzply_check: 5 injected bits -> corrected == 5, BER matches (--json)" ||
    bad "lzply_check: 5 injected bits -> corrected == 5, BER matches (--json)"
# (c) uncorrectable: 9 bits flipped (t=8) -> exit 3, uncorrectable
cp "$WORK/check-clean.lzply" "$WORK/check-err9.lzply"
SZ=$(stat -c %s "$WORK/check-err9.lzply")
"$CORRUPT_BITS" "$WORK/check-err9.lzply" 62 9 102 $((SZ - 2)) >/dev/null
OUT=$("$CHECK" "$WORK/check-err9.lzply" 2>&1)
RC=$?
[ "$RC" = "3" ] && echo "$OUT" | grep -q "uncorrectable" &&
    ok "lzply_check: 9 flipped bits (t=8) -> exit 3, uncorrectable" ||
    bad "lzply_check: 9 flipped bits (t=8) -> exit 3, uncorrectable (rc=$RC)"
# (d) no-ECC entry: reported as unmeasurable, exit 0
"$LZPLY" -c -y -6 -e 0 "$WORK/tiny.txt" "$WORK/check-noecc.lzply" >/dev/null 2>&1
OUT=$("$CHECK" "$WORK/check-noecc.lzply" 2>/dev/null)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep "tiny.txt" | grep -q "no-ecc" &&
    ok "lzply_check no-ECC entry: reported as no-ecc, exit 0" ||
    bad "lzply_check no-ECC entry: reported as no-ecc, exit 0 (rc=$RC)"
# (e) thresholds on the 5-bit archive (overall BER 5/488 = 0.0102...)
# --warn-ber below the BER: warning, still exit 0
OUT=$("$CHECK" --warn-ber 0.001 "$WORK/check-err5.lzply" 2>&1)
RC=$?
[ "$RC" = "0" ] && echo "$OUT" | grep -q "warning: overall BER" &&
    ok "lzply_check --warn-ber below BER: warning, exit 0" ||
    bad "lzply_check --warn-ber below BER: warning, exit 0 (rc=$RC)"
# --fail-ber below the BER: exit 3
"$CHECK" --fail-ber 0.001 "$WORK/check-err5.lzply" >/dev/null 2>&1
[ "$?" = "3" ] &&
    ok "lzply_check --fail-ber below BER: exit 3" ||
    bad "lzply_check --fail-ber below BER: exit 3"
# --fail-ber above the BER: exit 0
"$CHECK" --fail-ber 0.05 "$WORK/check-err5.lzply" >/dev/null 2>&1
[ "$?" = "0" ] &&
    ok "lzply_check --fail-ber above BER: exit 0" ||
    bad "lzply_check --fail-ber above BER: exit 0"
# (f) mount-point check (needs a live FUSE mount; skipped without one)
MOUNT="$(dirname "$LZPLY")/lzply_mount"
if [ -e /dev/fuse ] && [ -x "$MOUNT" ] && command -v fusermount3 >/dev/null 2>&1 && command -v mountpoint >/dev/null 2>&1; then
    mkdir -p "$WORK/mnt"
    "$MOUNT" "$WORK/check-clean.lzply" "$WORK/mnt" >/dev/null 2>&1
    MOUNTED=0
    for i in 1 2 3 4 5; do mountpoint -q "$WORK/mnt" && { MOUNTED=1; break; }; sleep 1; done
    if [ "$MOUNTED" = "1" ]; then
        OUT=$("$CHECK" "$WORK/mnt" 2>/dev/null)
        RC=$?
        fusermount3 -u "$WORK/mnt" >/dev/null 2>&1
        [ "$RC" = "0" ] && echo "$OUT" | grep "tiny.txt" | grep -q "clean" &&
            ok "lzply_check on a mount point: resolves the archive, BER 0" ||
            bad "lzply_check on a mount point: resolves the archive, BER 0 (rc=$RC)"
    else
        echo "SKIP: lzply_check mount test (mount did not come up)"
    fi
else
    echo "SKIP: lzply_check mount test (no FUSE)"
fi
else
    echo "SKIP: lzply_check tests (binary not found next to lzply)"
fi

# --- 22. lzply_refresh: in-place platter refresh -----------------------
if [ -x "$REFRESH" ]; then
# (a) 1 pass: same inode, content byte-identical, SHA-256 unchanged
printf 'refresh test content, one pass\n' > "$WORK/ref1.txt"
H1=$(sha256sum "$WORK/ref1.txt" | cut -d' ' -f1)
I1=$(stat -c %i "$WORK/ref1.txt")
OUT=$("$REFRESH" "$WORK/ref1.txt" 1 2>&1)
RC=$?
H2=$(sha256sum "$WORK/ref1.txt" | cut -d' ' -f1)
I2=$(stat -c %i "$WORK/ref1.txt")
[ "$RC" = "0" ] && [ "$H1" = "$H2" ] && [ "$I1" = "$I2" ] &&
echo "$OUT" | grep -q "verified unchanged" &&
    ok "lzply_refresh 1 pass: same inode, SHA-256 unchanged" ||
    bad "lzply_refresh 1 pass: same inode, SHA-256 unchanged (rc=$RC)"
# (b) 3 passes: same guarantees
printf 'refresh test content, three passes\n' > "$WORK/ref3.txt"
H1=$(sha256sum "$WORK/ref3.txt" | cut -d' ' -f1)
I1=$(stat -c %i "$WORK/ref3.txt")
OUT=$("$REFRESH" "$WORK/ref3.txt" 3 2>&1)
RC=$?
H2=$(sha256sum "$WORK/ref3.txt" | cut -d' ' -f1)
I2=$(stat -c %i "$WORK/ref3.txt")
[ "$RC" = "0" ] && [ "$H1" = "$H2" ] && [ "$I1" = "$I2" ] &&
echo "$OUT" | grep -q "3 passes" &&
    ok "lzply_refresh 3 passes: same inode, SHA-256 unchanged" ||
    bad "lzply_refresh 3 passes: same inode, SHA-256 unchanged (rc=$RC)"
# (c) n=4 and n=0 are usage errors
"$REFRESH" "$WORK/ref1.txt" 4 >/dev/null 2>&1
[ "$?" = "1" ] &&
    ok "lzply_refresh n=4: usage error (exit 1)" ||
    bad "lzply_refresh n=4: usage error (exit 1)"
"$REFRESH" "$WORK/ref1.txt" 0 >/dev/null 2>&1
[ "$?" = "1" ] &&
    ok "lzply_refresh n=0: usage error (exit 1)" ||
    bad "lzply_refresh n=0: usage error (exit 1)"
# (d) directory refresh: several files, symlink skipped, summary counts
mkdir -p "$WORK/refdir/sub"
printf 'dir file one\n' > "$WORK/refdir/one.txt"
printf 'dir file two\n' > "$WORK/refdir/sub/two.txt"
ln -s one.txt "$WORK/refdir/link.txt"
H1=$(sha256sum "$WORK/refdir/one.txt" | cut -d' ' -f1)
H2=$(sha256sum "$WORK/refdir/sub/two.txt" | cut -d' ' -f1)
OUT=$("$REFRESH" "$WORK/refdir" 2 2>&1)
RC=$?
[ "$RC" = "0" ] &&
[ "$(sha256sum "$WORK/refdir/one.txt" | cut -d' ' -f1)" = "$H1" ] &&
[ "$(sha256sum "$WORK/refdir/sub/two.txt" | cut -d' ' -f1)" = "$H2" ] &&
echo "$OUT" | grep -q "2 files refreshed" &&
echo "$OUT" | grep -q "1 skipped" &&
    ok "lzply_refresh directory: 2 files refreshed, symlink skipped, contents unchanged" ||
    bad "lzply_refresh directory: 2 files refreshed, symlink skipped, contents unchanged (rc=$RC)"
# (e) mount cases (need a live FUSE mount; skipped without one)
MOUNT="$(dirname "$LZPLY")/lzply_mount"
if [ -e /dev/fuse ] && [ -x "$MOUNT" ] && command -v fusermount3 >/dev/null 2>&1 && command -v mountpoint >/dev/null 2>&1; then
    mkdir -p "$WORK/reftree/sub" "$WORK/mnt2"
    printf 'mount file one\n' > "$WORK/reftree/one.txt"
    printf 'mount file two\n' > "$WORK/reftree/sub/two.txt"
    printf 'mount file three\n' > "$WORK/reftree/three.txt"
    # NB: `-c` takes one input + optional output, so create from the
    # directory itself; entries are stored as `reftree/...` (paths
    # relative to the input's parent) and the mount tests address
    # them under $WORK/mnt2/reftree/.
    (cd "$WORK" && "$LZPLY" -c -y -6 -e 4 reftree "$WORK/ref-mount.lzply" >/dev/null 2>&1)
    H1=$(sha256sum "$WORK/reftree/one.txt" | cut -d' ' -f1)
    H2=$(sha256sum "$WORK/reftree/sub/two.txt" | cut -d' ' -f1)
    H3=$(sha256sum "$WORK/reftree/three.txt" | cut -d' ' -f1)
    "$MOUNT" "$WORK/ref-mount.lzply" "$WORK/mnt2" >/dev/null 2>&1
    MOUNTED=0
    for i in 1 2 3 4 5; do mountpoint -q "$WORK/mnt2" && { MOUNTED=1; break; }; sleep 1; done
    if [ "$MOUNTED" = "1" ]; then
        # (e1) single file inside the mount
        OUT=$("$REFRESH" "$WORK/mnt2/reftree/one.txt" 2>&1)
        RC1=$?
        # (e2) whole mount point, 2 passes
        OUT2=$("$REFRESH" "$WORK/mnt2" 2 2>&1)
        RC2=$?
        # (e3) the mounted archive file itself is refused
        OUT3=$("$REFRESH" "$WORK/ref-mount.lzply" 2>&1)
        RC3=$?
        fusermount3 -u "$WORK/mnt2" >/dev/null 2>&1
        # Repack may still be in flight after fusermount3 returns;
        # wait for the mount to clear, then a beat, before reading
        # the archive.
        for i in 1 2 3 4 5 6 7 8 9 10; do mountpoint -q "$WORK/mnt2" || break; sleep 1; done
        sleep 1
        [ "$RC1" = "0" ] && echo "$OUT" | grep -q "verified unchanged" &&
            ok "lzply_refresh file inside mount: verified unchanged" ||
            bad "lzply_refresh file inside mount: verified unchanged (rc=$RC1)"
        [ "$RC2" = "0" ] && echo "$OUT2" | grep -q "refreshing mount at" &&
        echo "$OUT2" | grep -q "3 files refreshed" &&
            ok "lzply_refresh whole mount point: 3 files refreshed" ||
            bad "lzply_refresh whole mount point: 3 files refreshed (rc=$RC2)"
        [ "$RC3" != "0" ] && echo "$OUT3" | grep -q "mounted" &&
            ok "lzply_refresh mounted archive: refused" ||
            bad "lzply_refresh mounted archive: refused (rc=$RC3)"
        # After unmount: archive verifies, contents unchanged
        "$LZPLY" -t "$WORK/ref-mount.lzply" >/dev/null 2>&1
        TRC=$?
        rm -rf "$WORK/ref-out" && mkdir -p "$WORK/ref-out"
        "$LZPLY" -d "$WORK/ref-mount.lzply" "$WORK/ref-out" >/dev/null 2>&1
        [ "$TRC" = "0" ] &&
        [ "$(sha256sum "$WORK/ref-out/reftree/one.txt" | cut -d' ' -f1)" = "$H1" ] &&
        [ "$(sha256sum "$WORK/ref-out/reftree/sub/two.txt" | cut -d' ' -f1)" = "$H2" ] &&
        [ "$(sha256sum "$WORK/ref-out/reftree/three.txt" | cut -d' ' -f1)" = "$H3" ] &&
            ok "lzply_refresh mount roundtrip: archive verifies, all contents unchanged" ||
            bad "lzply_refresh mount roundtrip: archive verifies, all contents unchanged (test rc=$TRC)"
    else
        echo "SKIP: lzply_refresh mount tests (mount did not come up)"
    fi
else
    echo "SKIP: lzply_refresh mount tests (no FUSE)"
fi
else
    echo "SKIP: lzply_refresh tests (binary not found next to lzply)"
fi

# --- 23. Mount with a relative archive path: write-back must land in the
# real archive, not /<basename> ---------------------------------------
# libfuse changes the daemon's cwd to "/" at mount time, so a relative
# archive path used to make the repack write to /<basename> and leave
# the real archive untouched. lzply_mount canonicalises the path at
# startup; the write below must survive unmount in the cwd archive,
# and no stray file may appear in /.
MOUNT="$(dirname "$LZPLY")/lzply_mount"
if [ -e /dev/fuse ] && [ -x "$MOUNT" ] && command -v fusermount3 >/dev/null 2>&1 && command -v mountpoint >/dev/null 2>&1; then
    mkdir -p "$WORK/relmnt/mnt" && rm -f "$WORK/relmnt/relmount-test.lzply" /relmount-test.lzply
    echo "relative-path mount content" > "$WORK/relmnt/seed.txt"
    (cd "$WORK/relmnt" && "$LZPLY" -c -y seed.txt relmount-test.lzply >/dev/null 2>&1)
    (cd "$WORK/relmnt" && "$MOUNT" relmount-test.lzply mnt >/dev/null 2>&1)
    MOUNTED=0
    for i in 1 2 3 4 5; do mountpoint -q "$WORK/relmnt/mnt" && { MOUNTED=1; break; }; sleep 1; done
    if [ "$MOUNTED" = "1" ]; then
        echo "written through a relative-path mount" > "$WORK/relmnt/mnt/seed.txt"
        echo "new file in a relative-path mount" > "$WORK/relmnt/mnt/added.txt"
        # lzply_stat on the mount must resolve the archive (daemon's
        # relative arg + cwd "/"), run from the mount's parent dir.
        STATOUT=$(cd "$WORK/relmnt" && "$STAT" mnt 2>&1)
        STATRC=$?
        fusermount3 -u "$WORK/relmnt/mnt" >/dev/null 2>&1
        for i in 1 2 3 4 5 6 7 8 9 10; do mountpoint -q "$WORK/relmnt/mnt" || break; sleep 1; done
        sleep 1
        rm -rf "$WORK/relmnt/out" && mkdir -p "$WORK/relmnt/out"
        "$LZPLY" -d "$WORK/relmnt/relmount-test.lzply" "$WORK/relmnt/out" >/dev/null 2>&1
        [ "$(cat "$WORK/relmnt/out/seed.txt" 2>/dev/null)" = "written through a relative-path mount" ] &&
        [ "$(cat "$WORK/relmnt/out/added.txt" 2>/dev/null)" = "new file in a relative-path mount" ] &&
            ok "mount with relative archive path: writes persist in the real archive" ||
            bad "mount with relative archive path: writes persist in the real archive"
        [ ! -e /relmount-test.lzply ] &&
            ok "mount with relative archive path: no stray archive in /" ||
            bad "mount with relative archive path: no stray archive in /"
        [ "$STATRC" = "0" ] && echo "$STATOUT" | grep -q "seed.txt" &&
            ok "lzply_stat on a relative-path mount: resolves the archive" ||
            bad "lzply_stat on a relative-path mount: resolves the archive (rc=$STATRC)"
    else
        echo "SKIP: relative-path mount test (mount did not come up)"
    fi
else
    echo "SKIP: relative-path mount test (no FUSE)"
fi

# --- 24. Store mode (level 0): incompressible data stored uncompressed --
# (1) 1 MiB random data: compressed blob would be larger, so the entry
# is stored (level 0) and extracts byte-identical. -l, -i and stat
# all show lvl 0 for it.
"$LZPLY" -c -y -6 "$TD/mixed/random.bin" "$WORK/store-rand.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-rand.lzply" 2>/dev/null)
echo "$OUT" | grep "random.bin" | grep -Eq " 0 +BCH" &&
    ok "store mode: random.bin creates a level 0 entry (-l)" ||
    bad "store mode: random.bin creates a level 0 entry (-l)"
OUT=$("$LZPLY" -i "$WORK/store-rand.lzply" 2>/dev/null)
echo "$OUT" | grep "random.bin" | grep -Eq " 0 BCH" &&
    ok "store mode: random.bin shows lvl 0 in -i" ||
    bad "store mode: random.bin shows lvl 0 in -i"
OUT=$("$STAT" "$WORK/store-rand.lzply" 2>/dev/null)
echo "$OUT" | grep "random.bin" | grep -Eq "100\.0%[[:space:]]+0[[:space:]]" &&
    ok "store mode: random.bin shows lvl 0 in lzply_stat" ||
    bad "store mode: random.bin shows lvl 0 in lzply_stat"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/store-rand.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/mixed/random.bin" "$WORK/out/random.bin" &&
    ok "store mode: random.bin extracts byte-identical" ||
    bad "store mode: random.bin extracts byte-identical"
# (2) a compressible file still compresses (level > 0)
"$LZPLY" -c -y -6 "$TD/mixed/text.txt" "$WORK/store-text.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-text.lzply" 2>/dev/null)
echo "$OUT" | grep "text.txt" | grep -Eq " 6 +BCH" &&
    ok "store mode: compressible text.txt still compresses (lvl 6)" ||
    bad "store mode: compressible text.txt still compresses (lvl 6)"
# (3) explicit -0 forces store even for a compressible file, via -c and -a
"$LZPLY" -c -y -0 "$TD/mixed/text.txt" "$WORK/store-zero.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-zero.lzply" 2>/dev/null)
echo "$OUT" | grep "text.txt" | grep -Eq " 0 +BCH" &&
    ok "store mode: -0 forces store for a compressible file (-c)" ||
    bad "store mode: -0 forces store for a compressible file (-c)"
printf 'more compressible text, more compressible text\n%.0s' {1..500} > "$WORK/more.txt"
"$LZPLY" -a -0 "$WORK/store-text.lzply" "$WORK/more.txt" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-text.lzply" 2>/dev/null)
echo "$OUT" | grep "more.txt" | grep -Eq " 0 +BCH" &&
echo "$OUT" | grep "text.txt" | grep -Eq " 6 +BCH" &&
    ok "store mode: -a -0 stores the new entry, old entry stays compressed" ||
    bad "store mode: -a -0 stores the new entry, old entry stays compressed"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/store-zero.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/mixed/text.txt" "$WORK/out/text.txt" &&
    ok "store mode: -0 archive extracts byte-identical" ||
    bad "store mode: -0 archive extracts byte-identical"
# (4) BCH still applies to stored entries: flip 1 bit in the stored
# entry (data starts at 104: 16 + 78 + 10 for "random.bin"); -t still
# passes (BCH corrects it), check reports exactly 1 corrected bit,
# heal fixes it and the healed archive extracts byte-identical.
cp "$WORK/store-rand.lzply" "$WORK/store-rand-c.lzply"
SZ=$(stat -c %s "$WORK/store-rand-c.lzply")
"$CORRUPT_BITS" "$WORK/store-rand-c.lzply" 55 1 104 $((SZ - 2)) >/dev/null
"$LZPLY" -t "$WORK/store-rand-c.lzply" >/dev/null 2>&1 &&
    ok "store mode: 1 flipped bit in a stored entry still tests OK (BCH)" ||
    bad "store mode: 1 flipped bit in a stored entry still tests OK (BCH)"
OUT=$("$CHECK" --json "$WORK/store-rand-c.lzply" 2>/dev/null)
echo "$OUT" | grep -q '"corrected": 1' &&
    ok "store mode: check reports exactly 1 corrected bit in a stored entry" ||
    bad "store mode: check reports exactly 1 corrected bit in a stored entry"
"$HEAL" -o "$WORK/store-rand-h.lzply" "$WORK/store-rand-c.lzply" >/dev/null 2>&1
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/store-rand-h.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/mixed/random.bin" "$WORK/out/random.bin" &&
    ok "store mode: heal corrects the flipped bit, data recovers" ||
    bad "store mode: heal corrects the flipped bit, data recovers"
# (5) empty file: stored as level 0 with a 0-byte blob, roundtrips
"$LZPLY" -c -y -6 "$TD/mixed/empty.txt" "$WORK/store-empty.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-empty.lzply" 2>/dev/null)
echo "$OUT" | grep "empty.txt" | grep -Eq " 0 +BCH" &&
    ok "store mode: empty file is stored as level 0" ||
    bad "store mode: empty file is stored as level 0"
rm -rf "$WORK/out"
"$LZPLY" -d "$WORK/store-empty.lzply" "$WORK/out" >/dev/null 2>&1 &&
cmp -s "$TD/mixed/empty.txt" "$WORK/out/empty.txt" &&
    ok "store mode: empty file extracts byte-identical" ||
    bad "store mode: empty file extracts byte-identical"
# (6) directories are unaffected: they keep the requested level
rm -rf "$WORK/storedir"
mkdir -p "$WORK/storedir/sub"
cp "$TD/mixed/random.bin" "$WORK/storedir/"
cp "$TD/mixed/text.txt" "$WORK/storedir/sub/"
"$LZPLY" -c -y -6 "$WORK/storedir" "$WORK/store-dir.lzply" >/dev/null 2>&1
OUT=$("$LZPLY" -l "$WORK/store-dir.lzply" 2>/dev/null)
echo "$OUT" | grep -Eq "^storedir/ +0 B +0 B +6 +-" &&
echo "$OUT" | grep "random.bin" | grep -Eq " 0 +BCH" &&
echo "$OUT" | grep "text.txt" | grep -Eq " 6 +BCH" &&
    ok "store mode: directories keep the requested level, files store/fall back" ||
    bad "store mode: directories keep the requested level, files store/fall back"
# (7) mount repack of an incompressible file stores it (level 0)
MOUNT="$(dirname "$LZPLY")/lzply_mount"
if [ -e /dev/fuse ] && [ -x "$MOUNT" ] && command -v fusermount3 >/dev/null 2>&1 && command -v mountpoint >/dev/null 2>&1; then
    mkdir -p "$WORK/store-mnt"
    "$LZPLY" -c -y -6 "$TD/mixed/text.txt" "$WORK/store-mount.lzply" >/dev/null 2>&1
    "$MOUNT" "$WORK/store-mount.lzply" "$WORK/store-mnt" >/dev/null 2>&1
    MOUNTED=0
    for i in 1 2 3 4 5; do mountpoint -q "$WORK/store-mnt" && { MOUNTED=1; break; }; sleep 1; done
    if [ "$MOUNTED" = "1" ]; then
        cp "$TD/mixed/random.bin" "$WORK/store-mnt/rand.bin"
        fusermount3 -u "$WORK/store-mnt" >/dev/null 2>&1
        for i in 1 2 3 4 5 6 7 8 9 10; do mountpoint -q "$WORK/store-mnt" || break; sleep 1; done
        sleep 1
        OUT=$("$LZPLY" -l "$WORK/store-mount.lzply" 2>/dev/null)
        echo "$OUT" | grep "rand.bin" | grep -Eq " 0 +BCH" &&
            ok "store mode: mount repack stores an incompressible file (lvl 0)" ||
            bad "store mode: mount repack stores an incompressible file (lvl 0)"
        rm -rf "$WORK/out"
        "$LZPLY" -d "$WORK/store-mount.lzply" "$WORK/out" >/dev/null 2>&1 &&
        cmp -s "$TD/mixed/random.bin" "$WORK/out/rand.bin" &&
            ok "store mode: mount-repacked stored file extracts byte-identical" ||
            bad "store mode: mount-repacked stored file extracts byte-identical"
    else
        echo "SKIP: store-mode mount test (mount did not come up)"
    fi
else
    echo "SKIP: store-mode mount test (no FUSE)"
fi

echo
echo "LZPLY TESTS: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]

tests/make_testdata.sh

Test corpus builder

#!/bin/bash
# make_testdata.sh - build the lzply test corpus under <ROOT>/testdata.
# ROOT is taken from $LZPLY_TEST_ROOT, else the parent of this script's
# directory (works for ~/workspace/lzply and for /opt/lzply).
# Deterministic where it matters (text/zeros); random.bin uses urandom.
set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="${LZPLY_TEST_ROOT:-$(dirname "$SCRIPT_DIR")}"
TD="$ROOT/testdata"
# lzply.c lives at the repo root locally, under src/ on the server.
if [ -f "$ROOT/lzply.c" ]; then SRC="$ROOT/lzply.c";
elif [ -f "$ROOT/src/lzply.c" ]; then SRC="$ROOT/src/lzply.c";
else echo "lzply.c not found under $ROOT"; exit 1; fi
rm -rf "$TD"
mkdir -p "$TD/mixed/nested/deep" "$TD/mixed/empty dir" "$TD/emptydir"

# Compressible text: lorem + code, ~200 KiB.
{
    for i in $(seq 1 400); do
        echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        echo "int main(int argc, char **argv) { if (argc < 2) return 1; printf(\"hello %s\\n\", argv[1]); return 0; }"
    done
} > "$TD/mixed/text.txt"

# Real source code (compressible, realistic).
cp "$SRC" "$TD/mixed/source.c"

# Random binary (incompressible): 1 MiB.
head -c 1048576 /dev/urandom > "$TD/mixed/random.bin"

# Zeros (maximally compressible): 1 MiB.
head -c 1048576 /dev/zero > "$TD/mixed/zeros.bin"

# Edge cases.
: > "$TD/mixed/empty.txt"
printf 'x' > "$TD/mixed/onebyte.txt"
echo "nested file one" > "$TD/mixed/nested/a.txt"
echo "nested file two, deeper" > "$TD/mixed/nested/deep/b.txt"
echo "a file with spaces in its name" > "$TD/mixed/empty dir/file with spaces.txt"

# One big file: 50 MiB random (exercises multi-block RS + memory).
head -c 52428800 /dev/urandom > "$TD/big.bin"

echo "testdata ready in $TD"
find "$TD" -type f | sort
du -sh "$TD"

METHOD AND SOURCES

  • lzip format and lzlib API: the lzlib.h header shipped with Debian's liblz-dev 1.13, and the system lzip 1.23 binary used as the cross-check oracle.
  • Binary BCH: systematic encoding by polynomial remainder, decoding by syndromes, Berlekamp-Massey, and Chien search (no magnitude step — binary). The 82 generator polynomials come from the rssearch exhaustive search (see the companion article); every one was re-derived orbit-only from its parent's primitive polynomial and checked byte-identical before embedding. The codec was validated against its own properties (not against a reference implementation) by the harness described above.
  • Reed-Solomon (v1, removed in v3): GF(256) with primitive polynomial 0x11D; encoding by polynomial long division; decoding by syndromes, Berlekamp-Massey, Chien search, and Forney's formula. Deleted with its harness and fixtures when the format went to v3 — see the format section for why.
  • SHA-256: a small in-tree FIPS 180-4 implementation (no OpenSSL dependency).
  • All numbers in this article are measured on the server (Debian 12, gcc 12.2.0), not copied from documentation.