detached 49c9a08

#1 feat(export): export WoW Forever client data to SQLite

state
merged · 557ac9c · merge commit
branch
feat/export → main
opened
bnema ·
updated

Export the game data of a local World of Warcraft: Forever client into SQLite.

What it does

  • forever-db export: reads the local CASC storage (indexes, archives, BLTE incl. Salsa20, encoding, root), decodes every WDC5 DB2 table the client ships (1161 tables on build 1.60.1.71037) and applies the hotfixes from DBCache.bin. Writes wowf-<version>.sqlite + current.sqlite symlink with _meta, _tables, _columns, _hotfixes.
  • forever-db status: up to date / stale (build_changed, hotfixes_changed, schema_changed, defs_changed) / never exported.
  • forever-db defs show|update: table definitions and keys ship embedded (81 KB snapshot derived from WoWDBDefs, CC BY-SA 4.0); export never uses the network; defs update is the only network command.
  • forever-db debug cat <fdid>.

Checks

  • gofmt, go vet, go test -race ./....
  • Real install, network blocked: 1161 ok, 0 failed, hotfixes applied, ~5.5 s; real-data tests (golden values, hotfix narrowing cross-check, client keys) pass.
  • Wrap-up review (2 reviewers) + targeted re-review: all findings fixed.

Licence: AGPL-3.0-or-later; NOTICE credits DBCD and TACTSharp (MIT).

CommitSubjectAuthorDateSignatureStatus
49c9a08docs(readme): describe the merge base and attributionbrice GPG Verified
79b4f0cfix(cli): compute the defs merge base only when mergingbrice GPG Verified
8062be4fix(sources): prune only stale cache entries and reject duplicate tablesbrice GPG Verified
3804085fix(export): hash definitions independently of compressionbrice GPG Verified
187750bfix(defs): keep base hashes for layoutless tables and report corruption accuratelybrice GPG Verified
8936a07refactor(defs): drop the sources dependency from generationbrice GPG Verified
5ffb595feat(defs): show data attributionbrice GPG Verified
3f76b01test(defs): replace placeholder writer with embedded snapshot checksbrice GPG Verified
83998d5fix(defs): harden snapshot decoding and generationbrice GPG Verified
f8a395adocs: clarify usage, licence and attributionbrice GPG Verified
ecbcae1refactor: share atomic file writes and tidy cachesbrice GPG Verified
4d91d06fix(export): mark exports stale when definitions changebrice GPG Verified
5783d16docs(readme): document embedded definitionsbrice GPG Verified
182dc3ffeat(defs): embed the WoW Forever definitions snapshotbrice GPG Verified
00dd2e3feat(cli): add defs update and defs showbrice GPG Verified
8a1d2affeat(export): read definitions from the embedded snapshotbrice GPG Verified
145d5e0feat(defs): generate snapshots from an installbrice GPG Verified
7e6a852feat(defs): add embedded definitions snapshot formatbrice GPG Verified
c5a4992fix(sources): fetch WoWDBDefs without the GitHub APIbrice GPG Verified
01b1bf4test(hotfix): cross-check narrow fields against hotfix payloadsbrice GPG Verified
79553eedocs(readme): describe crafts without a recipe item accuratelybrice GPG Verified
ec1cb39test(wdc5): cover relation-by-id, skipped strings and fuzz fixturesbrice GPG Verified
e13752cfix(cli): lock exports and honor second interruptbrice GPG Verified
2cd5cfcfix(export): isolate per-table write failuresbrice GPG Verified
7c62503fix(export): skip zero client keysbrice GPG Verified
823472fperf(wdc5): allocate row values once per rowbrice GPG Verified
3046b3ffix(export): open sqlite via file URI and sync before publishbrice GPG Verified
bb3b698fix(wdc5): prevent size overflow and narrow signed fieldsbrice GPG Verified
9504d0adocs(readme): fix recipe item query to use ItemEffect learn triggersbrice GPG Verified
d6e002bfeat(cli): add export command and integration testbrice GPG Verified
0912875docs(readme): document usage, schema and limitsbrice GPG Verified
975bc00feat(status): report export freshnessbrice GPG Verified
5d5fed9feat(export): orchestrate the full exportbrice GPG Verified
0af9ddefeat(export): write tables and metadata to SQLitebrice GPG Verified
e0e2f71feat(export): decode tables and load client keysbrice GPG Verified
62c1f61feat(schema): define SQLite export schemabrice GPG Verified
c392a82feat(hotfix): decode and apply hotfix rowsbrice GPG Verified
75cb6c0fix(sources): allow hyphens in manifest table namesbrice GPG Verified
1a3a0a1fix(sources): validate downloads and honor cancellationbrice GPG Verified
c25cba3feat(hotfix): parse DBCache.binbrice GPG Verified
e6c64f8fix(dbd): validate field sizesbrice GPG Verified
a9c6634test(wdc5): decode every real Forever tablebrice GPG Verified
2b2d834fix(casc): bound archive reads and document resolve orderbrice GPG Verified
30552b6feat(wdc5): decode sparse WDC5 recordsbrice GPG Verified
c5a5cdcfeat(wdc5): decode dense WDC5 recordsbrice GPG Verified
8ec3d12feat(wdc5): parse WDC5 headers and sectionsbrice GPG Verified
421c0a5feat(sources): load WoWDBDefs manifestbrice GPG Verified
3fc2448feat(sources): fetch and cache WoWDBDefs and TACTKeysbrice GPG Verified
a45d089feat(dbd): parse WoWDBDefs definitionsbrice GPG Verified
4c32150fix(blte): bound sizes from untrusted BLTE headersbrice GPG Verified
eda9386fix(install): validate build key and localebrice GPG Verified
4200426feat(casc): open local storage and add debug catbrice GPG Verified
6e6f971feat(casc): resolve FileDataIDs from TSFM rootbrice GPG Verified
8da64cffeat(casc): parse encoding filebrice GPG Verified
59a9abefeat(casc): read local CASC indexes and data archivesbrice GPG Verified
88186f8feat(blte): decode BLTE with zlib and Salsa20 blocksbrice GPG Verified
e29e459feat(tactkeys): add TACT key ringbrice GPG Verified
902eb44feat(salsa20): add Salsa20 with 128-bit keysbrice GPG Verified
f78dcd6feat(install): detect WoW Forever install and build configbrice GPG Verified
ce16a9efeat(db2): add shared table contractbrice GPG Verified
5110b82feat(cli): add root command and path resolutionbrice GPG Verified

Checks 0

no checks

84 files · +12301 -2
no checks
A Makefile +26 -0
@@ -0,0 +1,26 @@
1+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
2+COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
3+LDFLAGS := -ldflags "-s -w -X github.com/bnema/forever-db/cmd.version=$(VERSION) -X github.com/bnema/forever-db/cmd.commit=$(COMMIT)"
4+
5+.PHONY: build install fmt vet test tidy clean
6+
7+build: fmt vet
8+ go build $(LDFLAGS) -buildmode=pie -trimpath -o build/forever-db .
9+
10+install:
11+ go install $(LDFLAGS) .
12+
13+fmt:
14+ go fmt ./...
15+
16+vet:
17+ go vet ./...
18+
19+test:
20+ go test ./...
21+
22+tidy:
23+ go mod tidy
24+
25+clean:
26+ rm -rf build/
@@ -0,0 +1,26 @@
1+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
2+COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
3+LDFLAGS := -ldflags "-s -w -X github.com/bnema/forever-db/cmd.version=$(VERSION) -X github.com/bnema/forever-db/cmd.commit=$(COMMIT)"
4+
5+.PHONY: build install fmt vet test tidy clean
6+
7+build: fmt vet
8+ go build $(LDFLAGS) -buildmode=pie -trimpath -o build/forever-db .
9+
10+install:
11+ go install $(LDFLAGS) .
12+
13+fmt:
14+ go fmt ./...
15+
16+vet:
17+ go vet ./...
18+
19+test:
20+ go test ./...
21+
22+tidy:
23+ go mod tidy
24+
25+clean:
26+ rm -rf build/
A NOTICE +67 -0
@@ -0,0 +1,67 @@
1+forever-db
2+Copyright (C) 2026 bnema
3+SPDX-License-Identifier: AGPL-3.0-or-later
4+
5+This project uses the following projects as format references and port
6+sources for the CASC, BLTE, Salsa20 and WDC5/hotfix readers.
7+
8+------------------------------------------------------------------------
9+DBCD — https://github.com/wowdev/DBCD
10+------------------------------------------------------------------------
11+
12+MIT License
13+
14+Copyright (c) 2020 wowdev
15+
16+Permission is hereby granted, free of charge, to any person obtaining a copy
17+of this software and associated documentation files (the "Software"), to deal
18+in the Software without restriction, including without limitation the rights
19+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20+copies of the Software, and to permit persons to whom the Software is
21+furnished to do so, subject to the following conditions:
22+
23+The above copyright notice and this permission notice shall be included in all
24+copies or substantial portions of the Software.
25+
26+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32+SOFTWARE.
33+
34+------------------------------------------------------------------------
35+TACTSharp — https://github.com/wowdev/TACTSharp
36+------------------------------------------------------------------------
37+
38+MIT License
39+
40+Copyright (c) 2024 Martin Benjamins
41+
42+Permission is hereby granted, free of charge, to any person obtaining a copy
43+of this software and associated documentation files (the "Software"), to deal
44+in the Software without restriction, including without limitation the rights
45+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46+copies of the Software, and to permit persons to whom the Software is
47+furnished to do so, subject to the following conditions:
48+
49+The above copyright notice and this permission notice shall be included in all
50+copies or substantial portions of the Software.
51+
52+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58+SOFTWARE.
59+
60+------------------------------------------------------------------------
61+Data
62+------------------------------------------------------------------------
63+
64+The embedded definitions snapshot (internal/defs/data/forever.json.gz) is
65+derived from WoWDBDefs (https://github.com/wowdev/WoWDBDefs) by the
66+WoWDBDefs contributors, CC BY-SA 4.0, and TACTKeys
67+(https://github.com/wowdev/TACTKeys). See internal/defs/data/README.md.
@@ -0,0 +1,67 @@
1+forever-db
2+Copyright (C) 2026 bnema
3+SPDX-License-Identifier: AGPL-3.0-or-later
4+
5+This project uses the following projects as format references and port
6+sources for the CASC, BLTE, Salsa20 and WDC5/hotfix readers.
7+
8+------------------------------------------------------------------------
9+DBCD — https://github.com/wowdev/DBCD
10+------------------------------------------------------------------------
11+
12+MIT License
13+
14+Copyright (c) 2020 wowdev
15+
16+Permission is hereby granted, free of charge, to any person obtaining a copy
17+of this software and associated documentation files (the "Software"), to deal
18+in the Software without restriction, including without limitation the rights
19+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20+copies of the Software, and to permit persons to whom the Software is
21+furnished to do so, subject to the following conditions:
22+
23+The above copyright notice and this permission notice shall be included in all
24+copies or substantial portions of the Software.
25+
26+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32+SOFTWARE.
33+
34+------------------------------------------------------------------------
35+TACTSharp — https://github.com/wowdev/TACTSharp
36+------------------------------------------------------------------------
37+
38+MIT License
39+
40+Copyright (c) 2024 Martin Benjamins
41+
42+Permission is hereby granted, free of charge, to any person obtaining a copy
43+of this software and associated documentation files (the "Software"), to deal
44+in the Software without restriction, including without limitation the rights
45+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46+copies of the Software, and to permit persons to whom the Software is
47+furnished to do so, subject to the following conditions:
48+
49+The above copyright notice and this permission notice shall be included in all
50+copies or substantial portions of the Software.
51+
52+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58+SOFTWARE.
59+
60+------------------------------------------------------------------------
61+Data
62+------------------------------------------------------------------------
63+
64+The embedded definitions snapshot (internal/defs/data/forever.json.gz) is
65+derived from WoWDBDefs (https://github.com/wowdev/WoWDBDefs) by the
66+WoWDBDefs contributors, CC BY-SA 4.0, and TACTKeys
67+(https://github.com/wowdev/TACTKeys). See internal/defs/data/README.md.
M README.md +111 -2
@@ -1,5 +1,114 @@
11 # forever-db
22
3-Exports the game data of a local World of Warcraft: Forever client (DB2 tables and hotfixes) into a SQLite database.
3+forever-db exports the game data of a local World of Warcraft: Forever client into a SQLite database: every DB2 table the client ships, with the hotfixes cached in `DBCache.bin` applied on top. It only reads the game files and never modifies them. Only the Forever product (`wowf`) is supported.
44
5-Table definitions come from [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0) and encryption keys from [TACTKeys](https://github.com/wowdev/TACTKeys). Both are downloaded at runtime into a local cache and are not redistributed with this project.
5+## Install
6+
7+```sh
8+go install github.com/bnema/forever-db@latest
9+```
10+
11+Or from a checkout:
12+
13+```sh
14+make build # produces build/forever-db
15+```
16+
17+## Usage
18+
19+```sh
20+forever-db export --dir "<WoW dir>"
21+forever-db status --dir "<WoW dir>" [--json]
22+forever-db defs show [--json]
23+forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
24+```
25+
26+`--dir` is the folder that contains `.build.info`, for example in a Wine prefix:
27+`~/.wine/drive_c/Program Files (x86)/World of Warcraft`.
28+
29+| Flag / env | Meaning |
30+|---|---|
31+| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export`, `status` and `defs update`) |
32+| `--out`, `FOREVER_DB_DATA_DIR` | Output directory, default `$XDG_DATA_HOME/forever-db` (`~/.local/share/forever-db`) |
33+| `--force` | Export even when the database is already up to date |
34+| `-v`, `--verbose` | Debug logging |
35+
36+A flag always wins over its environment variable.
37+
38+Each export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it.
39+
40+### Definitions
41+
42+`export` never uses the network. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.
43+
44+After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. `defs update` is the only command that uses the network.
45+
46+`forever-db defs show` prints which snapshot is in use (`embedded` or `local`), its builds, WoWDBDefs commit, generation time, table, layout and key counts, and an attribution line for the data sources (`attribution` object with `--json`).
47+
48+Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export) or `never exported`; run `export` again when it is stale.
49+
50+Exit codes: 0 success (including per-table failures, listed in the summary and `_tables`), 1 fatal error. Use `status --json` (`state`) and `_tables.status` in scripts.
51+
52+## Database layout
53+
54+- **One table per DB2 table**, named like the DB2 table (`SpellReagents`, `ItemSparse`, …). Columns follow the WoWDBDefs definition; arrays become `Name_0`, `Name_1`, … The record ID is the `INTEGER PRIMARY KEY`.
55+- **`_meta`**: key/value pairs: schema version, tool version, build version and key, locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.
56+- **`_tables`**: one row per table: `status` (`ok`, `absent`, `no_definition`, `failed`), error message, base row count, hotfix counts (upserts, deletes, reverts, errors), skipped rows and sections.
57+- **`_columns`**: one row per SQL column: type (`int`, `uint`, `float`, `string`), bit size, array index, and `ref_table` / `ref_column` for columns that reference another table. Use these to find joins.
58+- **`_hotfixes`**: every hotfix entry of a known table with the action taken (`upsert`, `delete`, `revert`, `ignored`, `error`).
59+
60+Integers are stored as SQLite `INTEGER`. Unsigned 64-bit values keep their bit pattern as a signed int64, so values above 2^63 read back as negative numbers.
61+
62+## Example queries
63+
64+Cooking (SkillLine 185) recipes that use a given reagent item (`?1` = item ID):
65+
66+```sql
67+SELECT DISTINCT s."Spell" AS craft_spell, i."Display_lang" AS reagent
68+FROM "SpellReagents" r
69+JOIN "SkillLineAbility" s ON s."Spell" = r."SpellID"
70+JOIN "ItemSparse" i ON i."ID" = ?1
71+WHERE s."SkillLine" = 185
72+ AND ?1 IN (r."Reagent_0", r."Reagent_1", r."Reagent_2", r."Reagent_3",
73+ r."Reagent_4", r."Reagent_5", r."Reagent_6", r."Reagent_7");
74+```
75+
76+The recipe item that teaches a craft spell (`?` = craft spell ID). A recipe item has an `ItemEffect` with `TriggerType = 6` (learn spell) whose `SpellID` is the craft spell; `ItemXItemEffect` links that effect to the item. An empty result means no item teaches that craft:
77+
78+```sql
79+SELECT x."ItemID", i."Display_lang" AS recipe
80+FROM "ItemEffect" ie
81+JOIN "ItemXItemEffect" x ON x."ItemEffectID" = ie."ID"
82+JOIN "ItemSparse" i ON i."ID" = x."ItemID"
83+WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
84+```
85+
86+## Limits
87+
88+- Client data only. Vendors, prices, drop rates, NPC spawns and most quest details live on the server and are not included.
89+- A few encrypted sections use keys that are not public. Their rows are skipped and counted in `_tables.skipped_rows`.
90+
91+## Tests
92+
93+`go test ./...` runs the unit tests on synthetic fixtures. Tests against real data are skipped unless these variables are set:
94+
95+| Variable | Points to |
96+|---|---|
97+| `FOREVER_DB_TEST_WOW_DIR` | A WoW Forever install (folder with `.build.info`) |
98+| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `internal/defs/data/forever.json.gz` |
99+| `FOREVER_DB_TEST_DBD_DIR` | A WoWDBDefs `definitions/` folder |
100+| `FOREVER_DB_TEST_MANIFEST` | A WoWDBDefs `manifest.json` |
101+| `FOREVER_DB_TEST_TACTKEYS` | A TACTKeys `WoW.txt` file |
102+| `FOREVER_DB_TEST_TABLES` | Optional comma-separated table names to limit the WDC5 sweep |
103+| `FOREVER_DB_TEST_GOLDEN` | Optional JSON file of expected sample rows for the WDC5 sweep |
104+
105+## Data sources and licences
106+
107+- Table definitions: [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0).
108+- Encryption keys: [TACTKeys](https://github.com/wowdev/TACTKeys).
109+
110+The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `internal/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.
111+
112+Copyright (C) 2026 bnema. SPDX-License-Identifier: AGPL-3.0-or-later. The project code is licensed under the GNU Affero General Public License v3.0 or later (see `LICENSE`).
113+
114+forever-db is an unofficial tool and is not affiliated with or endorsed by Blizzard Entertainment.
@@ -1,5 +1,114 @@
1 # forever-db1 # forever-db
2 2
3-Exports the game data of a local World of Warcraft: Forever client (DB2 tables and hotfixes) into a SQLite database.3+forever-db exports the game data of a local World of Warcraft: Forever client into a SQLite database: every DB2 table the client ships, with the hotfixes cached in `DBCache.bin` applied on top. It only reads the game files and never modifies them. Only the Forever product (`wowf`) is supported.
4 4
5-Table definitions come from [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0) and encryption keys from [TACTKeys](https://github.com/wowdev/TACTKeys). Both are downloaded at runtime into a local cache and are not redistributed with this project.5+## Install
6+
7+```sh
8+go install github.com/bnema/forever-db@latest
9+```
10+
11+Or from a checkout:
12+
13+```sh
14+make build # produces build/forever-db
15+```
16+
17+## Usage
18+
19+```sh
20+forever-db export --dir "<WoW dir>"
21+forever-db status --dir "<WoW dir>" [--json]
22+forever-db defs show [--json]
23+forever-db defs update --dir "<WoW dir>" [--fresh] [--output FILE] [--offline]
24+```
25+
26+`--dir` is the folder that contains `.build.info`, for example in a Wine prefix:
27+`~/.wine/drive_c/Program Files (x86)/World of Warcraft`.
28+
29+| Flag / env | Meaning |
30+|---|---|
31+| `--dir`, `FOREVER_DB_WOW_DIR` | Game directory (required by `export`, `status` and `defs update`) |
32+| `--out`, `FOREVER_DB_DATA_DIR` | Output directory, default `$XDG_DATA_HOME/forever-db` (`~/.local/share/forever-db`) |
33+| `--force` | Export even when the database is already up to date |
34+| `-v`, `--verbose` | Debug logging |
35+
36+A flag always wins over its environment variable.
37+
38+Each export writes `wowf-<version>.sqlite` and points the `current.sqlite` symlink at it.
39+
40+### Definitions
41+
42+`export` never uses the network. The table definitions and encryption keys for the Forever client ship inside the binary as a small snapshot.
43+
44+After a game patch, `export` may report tables without a definition (status `no_definition`) and suggests `forever-db defs update`. That command downloads WoWDBDefs and TACTKeys (cached and revalidated in `$XDG_CACHE_HOME/forever-db`), reads the installed client, and writes `<data dir>/defs.json.gz`, which overrides the embedded snapshot. By default the new definitions are merged with the current ones: the snapshot in use (`<data dir>/defs.json.gz`, else the embedded one), or, with `--output FILE` (written there instead), that file if it exists, else the embedded snapshot. `--fresh` starts from scratch, `--offline` uses the download cache only. `defs update` is the only command that uses the network.
45+
46+`forever-db defs show` prints which snapshot is in use (`embedded` or `local`), its builds, WoWDBDefs commit, generation time, table, layout and key counts, and an attribution line for the data sources (`attribution` object with `--json`).
47+
48+Hotfixes change after a patch or a game session. `forever-db status` reports `up to date`, `stale` (with the reasons: `build_changed`, `hotfixes_changed`, `schema_changed`, `defs_changed` when the definitions snapshot in use differs from the one of the export) or `never exported`; run `export` again when it is stale.
49+
50+Exit codes: 0 success (including per-table failures, listed in the summary and `_tables`), 1 fatal error. Use `status --json` (`state`) and `_tables.status` in scripts.
51+
52+## Database layout
53+
54+- **One table per DB2 table**, named like the DB2 table (`SpellReagents`, `ItemSparse`, …). Columns follow the WoWDBDefs definition; arrays become `Name_0`, `Name_1`, … The record ID is the `INTEGER PRIMARY KEY`.
55+- **`_meta`**: key/value pairs: schema version, tool version, build version and key, locale, export time, DBCache hash and status (`applied`, `missing`, `invalid`, `build_mismatch`), definitions snapshot origin (`embedded` or `local`), its WoWDBDefs commit, generation time and SHA-256, table counts.
56+- **`_tables`**: one row per table: `status` (`ok`, `absent`, `no_definition`, `failed`), error message, base row count, hotfix counts (upserts, deletes, reverts, errors), skipped rows and sections.
57+- **`_columns`**: one row per SQL column: type (`int`, `uint`, `float`, `string`), bit size, array index, and `ref_table` / `ref_column` for columns that reference another table. Use these to find joins.
58+- **`_hotfixes`**: every hotfix entry of a known table with the action taken (`upsert`, `delete`, `revert`, `ignored`, `error`).
59+
60+Integers are stored as SQLite `INTEGER`. Unsigned 64-bit values keep their bit pattern as a signed int64, so values above 2^63 read back as negative numbers.
61+
62+## Example queries
63+
64+Cooking (SkillLine 185) recipes that use a given reagent item (`?1` = item ID):
65+
66+```sql
67+SELECT DISTINCT s."Spell" AS craft_spell, i."Display_lang" AS reagent
68+FROM "SpellReagents" r
69+JOIN "SkillLineAbility" s ON s."Spell" = r."SpellID"
70+JOIN "ItemSparse" i ON i."ID" = ?1
71+WHERE s."SkillLine" = 185
72+ AND ?1 IN (r."Reagent_0", r."Reagent_1", r."Reagent_2", r."Reagent_3",
73+ r."Reagent_4", r."Reagent_5", r."Reagent_6", r."Reagent_7");
74+```
75+
76+The recipe item that teaches a craft spell (`?` = craft spell ID). A recipe item has an `ItemEffect` with `TriggerType = 6` (learn spell) whose `SpellID` is the craft spell; `ItemXItemEffect` links that effect to the item. An empty result means no item teaches that craft:
77+
78+```sql
79+SELECT x."ItemID", i."Display_lang" AS recipe
80+FROM "ItemEffect" ie
81+JOIN "ItemXItemEffect" x ON x."ItemEffectID" = ie."ID"
82+JOIN "ItemSparse" i ON i."ID" = x."ItemID"
83+WHERE ie."TriggerType" = 6 AND ie."SpellID" = ?;
84+```
85+
86+## Limits
87+
88+- Client data only. Vendors, prices, drop rates, NPC spawns and most quest details live on the server and are not included.
89+- A few encrypted sections use keys that are not public. Their rows are skipped and counted in `_tables.skipped_rows`.
90+
91+## Tests
92+
93+`go test ./...` runs the unit tests on synthetic fixtures. Tests against real data are skipped unless these variables are set:
94+
95+| Variable | Points to |
96+|---|---|
97+| `FOREVER_DB_TEST_WOW_DIR` | A WoW Forever install (folder with `.build.info`) |
98+| `FOREVER_DB_TEST_DEFS` | A definitions snapshot (`defs.json.gz`), e.g. `internal/defs/data/forever.json.gz` |
99+| `FOREVER_DB_TEST_DBD_DIR` | A WoWDBDefs `definitions/` folder |
100+| `FOREVER_DB_TEST_MANIFEST` | A WoWDBDefs `manifest.json` |
101+| `FOREVER_DB_TEST_TACTKEYS` | A TACTKeys `WoW.txt` file |
102+| `FOREVER_DB_TEST_TABLES` | Optional comma-separated table names to limit the WDC5 sweep |
103+| `FOREVER_DB_TEST_GOLDEN` | Optional JSON file of expected sample rows for the WDC5 sweep |
104+
105+## Data sources and licences
106+
107+- Table definitions: [WoWDBDefs](https://github.com/wowdev/WoWDBDefs) (CC BY-SA 4.0).
108+- Encryption keys: [TACTKeys](https://github.com/wowdev/TACTKeys).
109+
110+The definitions snapshot (embedded, or written by `defs update`) is derived from these projects and is licensed under CC BY-SA 4.0; see `internal/defs/data/README.md`. The CASC, BLTE and WDC5 readers follow DBCD and TACTSharp (MIT); see `NOTICE`.
111+
112+Copyright (C) 2026 bnema. SPDX-License-Identifier: AGPL-3.0-or-later. The project code is licensed under the GNU Affero General Public License v3.0 or later (see `LICENSE`).
113+
114+forever-db is an unofficial tool and is not affiliated with or endorsed by Blizzard Entertainment.
A cmd/debug.go +91 -0
@@ -0,0 +1,91 @@
1+package cmd
2+
3+import (
4+ "fmt"
5+ "log/slog"
6+ "os"
7+ "strconv"
8+
9+ "github.com/spf13/cobra"
10+
11+ "github.com/bnema/forever-db/internal/casc"
12+ "github.com/bnema/forever-db/internal/defs"
13+ "github.com/bnema/forever-db/internal/install"
14+ "github.com/bnema/forever-db/internal/tactkeys"
15+)
16+
17+var debugCmd = &cobra.Command{
18+ Use: "debug",
19+ Short: "Low-level inspection tools",
20+ Hidden: true,
21+}
22+
23+var catOut string
24+
25+var catCmd = &cobra.Command{
26+ Use: "cat <fdid>",
27+ Short: "Write the decoded content of a FileDataID",
28+ Args: cobra.ExactArgs(1),
29+ RunE: func(cmd *cobra.Command, args []string) error {
30+ fdid, err := strconv.ParseUint(args[0], 10, 32)
31+ if err != nil {
32+ return fmt.Errorf("invalid FileDataID %q: %w", args[0], err)
33+ }
34+ dir, err := resolveDir(dirFlag, os.Getenv)
35+ if err != nil {
36+ return err
37+ }
38+ inst, err := install.Detect(dir)
39+ if err != nil {
40+ return err
41+ }
42+ st, err := casc.Open(inst, debugRing())
43+ if err != nil {
44+ return err
45+ }
46+ defer st.Close()
47+ data, stats, err := st.ReadFDID(uint32(fdid))
48+ if err != nil {
49+ return err
50+ }
51+ for name, n := range stats.MissingKeys {
52+ slog.Warn("missing TACT key, blocks zero-filled", "key", fmt.Sprintf("%016X", name), "blocks", n)
53+ }
54+ if catOut != "" {
55+ return os.WriteFile(catOut, data, 0o644)
56+ }
57+ _, err = cmd.OutOrStdout().Write(data)
58+ return err
59+ },
60+}
61+
62+// debugRing returns the key ring of the effective definitions snapshot
63+// (no network). Unlike export, it does not add the client keys from
64+// TactKey/TactKeyLookup and hotfixes: debug cat reads single files and stays
65+// fast; blocks under client-only keys are zero-filled and logged.
66+func debugRing() *tactkeys.Ring {
67+ ring, err := snapshotRing()
68+ if err != nil {
69+ slog.Warn("definitions snapshot unavailable, using an empty key ring", "err", err)
70+ return tactkeys.New()
71+ }
72+ return ring
73+}
74+
75+func snapshotRing() (*tactkeys.Ring, error) {
76+ out, err := resolveOut(outFlag, os.Getenv)
77+ if err != nil {
78+ return nil, err
79+ }
80+ snap, _, err := defs.Effective(out)
81+ if err != nil {
82+ return nil, err
83+ }
84+ return snap.Ring(), nil
85+}
86+
87+func init() {
88+ catCmd.Flags().StringVarP(&catOut, "output", "o", "", "write to file instead of stdout")
89+ debugCmd.AddCommand(catCmd)
90+ rootCmd.AddCommand(debugCmd)
91+}
@@ -0,0 +1,91 @@
1+package cmd
2+
3+import (
4+ "fmt"
5+ "log/slog"
6+ "os"
7+ "strconv"
8+
9+ "github.com/spf13/cobra"
10+
11+ "github.com/bnema/forever-db/internal/casc"
12+ "github.com/bnema/forever-db/internal/defs"
13+ "github.com/bnema/forever-db/internal/install"
14+ "github.com/bnema/forever-db/internal/tactkeys"
15+)
16+
17+var debugCmd = &cobra.Command{
18+ Use: "debug",
19+ Short: "Low-level inspection tools",
20+ Hidden: true,
21+}
22+
23+var catOut string
24+
25+var catCmd = &cobra.Command{
26+ Use: "cat <fdid>",
27+ Short: "Write the decoded content of a FileDataID",
28+ Args: cobra.ExactArgs(1),
29+ RunE: func(cmd *cobra.Command, args []string) error {
30+ fdid, err := strconv.ParseUint(args[0], 10, 32)
31+ if err != nil {
32+ return fmt.Errorf("invalid FileDataID %q: %w", args[0], err)
33+ }
34+ dir, err := resolveDir(dirFlag, os.Getenv)
35+ if err != nil {
36+ return err
37+ }
38+ inst, err := install.Detect(dir)
39+ if err != nil {
40+ return err
41+ }
42+ st, err := casc.Open(inst, debugRing())
43+ if err != nil {
44+ return err
45+ }
46+ defer st.Close()
47+ data, stats, err := st.ReadFDID(uint32(fdid))
48+ if err != nil {
49+ return err
50+ }
51+ for name, n := range stats.MissingKeys {
52+ slog.Warn("missing TACT key, blocks zero-filled", "key", fmt.Sprintf("%016X", name), "blocks", n)
53+ }
54+ if catOut != "" {
55+ return os.WriteFile(catOut, data, 0o644)
56+ }
57+ _, err = cmd.OutOrStdout().Write(data)
58+ return err
59+ },
60+}
61+
62+// debugRing returns the key ring of the effective definitions snapshot
63+// (no network). Unlike export, it does not add the client keys from
64+// TactKey/TactKeyLookup and hotfixes: debug cat reads single files and stays
65+// fast; blocks under client-only keys are zero-filled and logged.
66+func debugRing() *tactkeys.Ring {
67+ ring, err := snapshotRing()
68+ if err != nil {
69+ slog.Warn("definitions snapshot unavailable, using an empty key ring", "err", err)
70+ return tactkeys.New()
71+ }
72+ return ring
73+}
74+
75+func snapshotRing() (*tactkeys.Ring, error) {
76+ out, err := resolveOut(outFlag, os.Getenv)
77+ if err != nil {
78+ return nil, err
79+ }
80+ snap, _, err := defs.Effective(out)
81+ if err != nil {
82+ return nil, err
83+ }
84+ return snap.Ring(), nil
85+}
86+
87+func init() {
88+ catCmd.Flags().StringVarP(&catOut, "output", "o", "", "write to file instead of stdout")
89+ debugCmd.AddCommand(catCmd)
90+ rootCmd.AddCommand(debugCmd)
91+}
A cmd/defs.go +247 -0
@@ -0,0 +1,247 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "encoding/json"
6+ "errors"
7+ "fmt"
8+ "io"
9+ "io/fs"
10+ "log/slog"
11+ "net/http"
12+ "os"
13+ "os/signal"
14+ "path/filepath"
15+ "strconv"
16+ "syscall"
17+
18+ "github.com/spf13/cobra"
19+
20+ "github.com/bnema/forever-db/internal/defs"
21+ "github.com/bnema/forever-db/internal/fsutil"
22+ "github.com/bnema/forever-db/internal/install"
23+ "github.com/bnema/forever-db/internal/sources"
24+ "github.com/bnema/forever-db/internal/tactkeys"
25+)
26+
27+// Test hooks for defs update.
28+var (
29+ defsURLs = sources.DefaultURLs()
30+ defsClient *http.Client
31+)
32+
33+var (
34+ defsFresh bool
35+ defsOutput string
36+ defsOffline bool
37+ defsJSON bool
38+)
39+
40+var defsCmd = &cobra.Command{
41+ Use: "defs",
42+ Short: "Manage the table definitions snapshot",
43+}
44+
45+var defsUpdateCmd = &cobra.Command{
46+ Use: "update",
47+ Short: "Rebuild the definitions snapshot from WoWDBDefs and TACTKeys (uses the network)",
48+ Args: cobra.NoArgs,
49+ RunE: func(cmd *cobra.Command, args []string) error {
50+ dir, err := resolveDir(dirFlag, os.Getenv)
51+ if err != nil {
52+ return err
53+ }
54+ out, err := resolveOut(outFlag, os.Getenv)
55+ if err != nil {
56+ return err
57+ }
58+ cache, err := cacheDir(os.Getenv)
59+ if err != nil {
60+ return err
61+ }
62+ inst, err := install.Detect(dir)
63+ if err != nil {
64+ return err
65+ }
66+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
67+ defer stop()
68+ src, err := sources.Fetch(ctx, cache, defsOffline, defsClient, defsURLs, "forever-db/"+version)
69+ if err != nil {
70+ return err
71+ }
72+ manifest, _, err := sources.LoadManifest(src.DBDDir)
73+ if err != nil {
74+ return err
75+ }
76+ kf, err := os.Open(src.TACTKeysPath)
77+ if err != nil {
78+ return err
79+ }
80+ ring, _, err := tactkeys.Parse(kf)
81+ kf.Close()
82+ if err != nil {
83+ return err
84+ }
85+ fresh, stats, err := defs.Generate(ctx, defs.GenerateInput{
86+ Install: inst, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,
87+ Source: defs.Source{WoWDBDefsCommit: src.DBDCommit, TACTKeysSHA256: src.TACTKeysSHA256},
88+ })
89+ if err != nil {
90+ return err
91+ }
92+ if layoutCount(fresh) == 0 {
93+ return errors.New("defs update: no table definitions generated; check --dir")
94+ }
95+ target := defsOutput
96+ if target == "" {
97+ target = filepath.Join(out, defs.LocalFileName)
98+ }
99+ // With --fresh nothing is merged and every layout counts as new.
100+ prev := &defs.Snapshot{}
101+ result := fresh
102+ if !defsFresh {
103+ if defsOutput == "" {
104+ prev, _, err = defs.Effective(out)
105+ } else {
106+ prev, err = mergeBase(target)
107+ }
108+ if err != nil {
109+ return err
110+ }
111+ result = defs.Merge(prev, fresh)
112+ }
113+ if err := writeSnapshotFile(target, result); err != nil {
114+ return err
115+ }
116+ w := cmd.OutOrStdout()
117+ fmt.Fprintf(w, "wrote %s\n", target)
118+ fmt.Fprintf(w, "builds: %v\n", result.Builds)
119+ fmt.Fprintf(w, "tables: %d (%d new layouts), %d absent, %d without definition, %d failed\n",
120+ stats.Tables, newLayouts(prev, fresh), stats.Absent, stats.NoDefinition, stats.Failed)
121+ fmt.Fprintf(w, "keys: %d used, %d missing\n", stats.KeysUsed, stats.KeysMissing)
122+ for _, m := range stats.Missing {
123+ fmt.Fprintf(w, " %s\n", m)
124+ }
125+ return nil
126+ },
127+}
128+
129+// layoutCount returns the number of layouts in s.
130+func layoutCount(s *defs.Snapshot) int {
131+ n := 0
132+ for _, t := range s.Tables {
133+ n += len(t.Layouts)
134+ }
135+ return n
136+}
137+
138+// mergeBase returns the snapshot an explicit --output merges with: the
139+// file itself when it exists and decodes, else the embedded snapshot.
140+func mergeBase(path string) (*defs.Snapshot, error) {
141+ f, err := os.Open(path)
142+ switch {
143+ case err == nil:
144+ s, derr := defs.Decode(f)
145+ f.Close()
146+ if derr == nil {
147+ return s, nil
148+ }
149+ slog.Warn("output snapshot invalid, merging with the embedded snapshot", "path", path, "err", derr)
150+ case !errors.Is(err, fs.ErrNotExist):
151+ slog.Warn("output snapshot unreadable, merging with the embedded snapshot", "path", path, "err", err)
152+ }
153+ return defs.Embedded()
154+}
155+
156+// newLayouts counts table layouts of fresh that prev does not have.
157+func newLayouts(prev, fresh *defs.Snapshot) int {
158+ n := 0
159+ for _, t := range fresh.Tables {
160+ for _, l := range t.Layouts {
161+ h, _ := strconv.ParseUint(l.Hash, 16, 32)
162+ if _, ok := prev.Definition(t.Name, uint32(h)); !ok {
163+ n++
164+ }
165+ }
166+ }
167+ return n
168+}
169+
170+// writeSnapshotFile writes s to path atomically.
171+func writeSnapshotFile(path string, s *defs.Snapshot) error {
172+ var buf bytes.Buffer
173+ if err := s.Encode(&buf); err != nil {
174+ return err
175+ }
176+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
177+ return err
178+ }
179+ return fsutil.WriteAtomic(path, buf.Bytes(), 0o644)
180+}
181+
182+// manifestEntries converts WoWDBDefs manifest entries to defs table entries.
183+func manifestEntries(list []sources.ManifestEntry) []defs.TableEntry {
184+ out := make([]defs.TableEntry, len(list))
185+ for i, e := range list {
186+ out[i] = defs.TableEntry{Name: e.TableName, Hash: e.TableHash, FDID: e.FDID}
187+ }
188+ return out
189+}
190+
191+// defsInfo is the defs show report.
192+type defsInfo struct {
193+ Origin string `json:"origin"`
194+ Builds []string `json:"builds"`
195+ WoWDBDefsCommit string `json:"wowdbdefs_commit"`
196+ GeneratedAt string `json:"generated_at"`
197+ Tables int `json:"tables"`
198+ Layouts int `json:"layouts"`
199+ Keys int `json:"keys"`
200+
201+ Attribution defs.AttributionInfo `json:"attribution"`
202+}
203+
204+var defsShowCmd = &cobra.Command{
205+ Use: "show",
206+ Short: "Show the definitions snapshot used by export",
207+ Args: cobra.NoArgs,
208+ RunE: func(cmd *cobra.Command, args []string) error {
209+ out, err := resolveOut(outFlag, os.Getenv)
210+ if err != nil {
211+ return err
212+ }
213+ s, origin, err := defs.Effective(out)
214+ if err != nil {
215+ return err
216+ }
217+ info := defsInfo{Origin: origin, Builds: s.Builds, WoWDBDefsCommit: s.Source.WoWDBDefsCommit,
218+ GeneratedAt: s.GeneratedAt, Tables: len(s.Tables), Keys: len(s.Keys), Attribution: defs.Attribution}
219+ if info.Builds == nil {
220+ info.Builds = []string{}
221+ }
222+ for _, t := range s.Tables {
223+ info.Layouts += len(t.Layouts)
224+ }
225+ return printDefsInfo(cmd.OutOrStdout(), info, defsJSON)
226+ },
227+}
228+
229+func printDefsInfo(w io.Writer, i defsInfo, asJSON bool) error {
230+ if asJSON {
231+ enc := json.NewEncoder(w)
232+ enc.SetIndent("", " ")
233+ return enc.Encode(i)
234+ }
235+ _, err := fmt.Fprintf(w, "origin: %s\nbuilds: %v\nWoWDBDefs commit: %s\ngenerated: %s\ntables: %d, layouts: %d, keys: %d\nattribution: %s\n",
236+ i.Origin, i.Builds, i.WoWDBDefsCommit, i.GeneratedAt, i.Tables, i.Layouts, i.Keys, defs.AttributionText)
237+ return err
238+}
239+
240+func init() {
241+ defsUpdateCmd.Flags().BoolVar(&defsFresh, "fresh", false, "do not merge with the current snapshot")
242+ defsUpdateCmd.Flags().StringVar(&defsOutput, "output", "", "output file (default <data dir>/defs.json.gz)")
243+ defsUpdateCmd.Flags().BoolVar(&defsOffline, "offline", false, "use cached WoWDBDefs and TACTKeys only")
244+ defsShowCmd.Flags().BoolVar(&defsJSON, "json", false, "print as JSON")
245+ defsCmd.AddCommand(defsUpdateCmd, defsShowCmd)
246+ rootCmd.AddCommand(defsCmd)
247+}
@@ -0,0 +1,247 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "encoding/json"
6+ "errors"
7+ "fmt"
8+ "io"
9+ "io/fs"
10+ "log/slog"
11+ "net/http"
12+ "os"
13+ "os/signal"
14+ "path/filepath"
15+ "strconv"
16+ "syscall"
17+
18+ "github.com/spf13/cobra"
19+
20+ "github.com/bnema/forever-db/internal/defs"
21+ "github.com/bnema/forever-db/internal/fsutil"
22+ "github.com/bnema/forever-db/internal/install"
23+ "github.com/bnema/forever-db/internal/sources"
24+ "github.com/bnema/forever-db/internal/tactkeys"
25+)
26+
27+// Test hooks for defs update.
28+var (
29+ defsURLs = sources.DefaultURLs()
30+ defsClient *http.Client
31+)
32+
33+var (
34+ defsFresh bool
35+ defsOutput string
36+ defsOffline bool
37+ defsJSON bool
38+)
39+
40+var defsCmd = &cobra.Command{
41+ Use: "defs",
42+ Short: "Manage the table definitions snapshot",
43+}
44+
45+var defsUpdateCmd = &cobra.Command{
46+ Use: "update",
47+ Short: "Rebuild the definitions snapshot from WoWDBDefs and TACTKeys (uses the network)",
48+ Args: cobra.NoArgs,
49+ RunE: func(cmd *cobra.Command, args []string) error {
50+ dir, err := resolveDir(dirFlag, os.Getenv)
51+ if err != nil {
52+ return err
53+ }
54+ out, err := resolveOut(outFlag, os.Getenv)
55+ if err != nil {
56+ return err
57+ }
58+ cache, err := cacheDir(os.Getenv)
59+ if err != nil {
60+ return err
61+ }
62+ inst, err := install.Detect(dir)
63+ if err != nil {
64+ return err
65+ }
66+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
67+ defer stop()
68+ src, err := sources.Fetch(ctx, cache, defsOffline, defsClient, defsURLs, "forever-db/"+version)
69+ if err != nil {
70+ return err
71+ }
72+ manifest, _, err := sources.LoadManifest(src.DBDDir)
73+ if err != nil {
74+ return err
75+ }
76+ kf, err := os.Open(src.TACTKeysPath)
77+ if err != nil {
78+ return err
79+ }
80+ ring, _, err := tactkeys.Parse(kf)
81+ kf.Close()
82+ if err != nil {
83+ return err
84+ }
85+ fresh, stats, err := defs.Generate(ctx, defs.GenerateInput{
86+ Install: inst, Manifest: manifestEntries(manifest), DBDPath: src.DBDPath, Keys: ring,
87+ Source: defs.Source{WoWDBDefsCommit: src.DBDCommit, TACTKeysSHA256: src.TACTKeysSHA256},
88+ })
89+ if err != nil {
90+ return err
91+ }
92+ if layoutCount(fresh) == 0 {
93+ return errors.New("defs update: no table definitions generated; check --dir")
94+ }
95+ target := defsOutput
96+ if target == "" {
97+ target = filepath.Join(out, defs.LocalFileName)
98+ }
99+ // With --fresh nothing is merged and every layout counts as new.
100+ prev := &defs.Snapshot{}
101+ result := fresh
102+ if !defsFresh {
103+ if defsOutput == "" {
104+ prev, _, err = defs.Effective(out)
105+ } else {
106+ prev, err = mergeBase(target)
107+ }
108+ if err != nil {
109+ return err
110+ }
111+ result = defs.Merge(prev, fresh)
112+ }
113+ if err := writeSnapshotFile(target, result); err != nil {
114+ return err
115+ }
116+ w := cmd.OutOrStdout()
117+ fmt.Fprintf(w, "wrote %s\n", target)
118+ fmt.Fprintf(w, "builds: %v\n", result.Builds)
119+ fmt.Fprintf(w, "tables: %d (%d new layouts), %d absent, %d without definition, %d failed\n",
120+ stats.Tables, newLayouts(prev, fresh), stats.Absent, stats.NoDefinition, stats.Failed)
121+ fmt.Fprintf(w, "keys: %d used, %d missing\n", stats.KeysUsed, stats.KeysMissing)
122+ for _, m := range stats.Missing {
123+ fmt.Fprintf(w, " %s\n", m)
124+ }
125+ return nil
126+ },
127+}
128+
129+// layoutCount returns the number of layouts in s.
130+func layoutCount(s *defs.Snapshot) int {
131+ n := 0
132+ for _, t := range s.Tables {
133+ n += len(t.Layouts)
134+ }
135+ return n
136+}
137+
138+// mergeBase returns the snapshot an explicit --output merges with: the
139+// file itself when it exists and decodes, else the embedded snapshot.
140+func mergeBase(path string) (*defs.Snapshot, error) {
141+ f, err := os.Open(path)
142+ switch {
143+ case err == nil:
144+ s, derr := defs.Decode(f)
145+ f.Close()
146+ if derr == nil {
147+ return s, nil
148+ }
149+ slog.Warn("output snapshot invalid, merging with the embedded snapshot", "path", path, "err", derr)
150+ case !errors.Is(err, fs.ErrNotExist):
151+ slog.Warn("output snapshot unreadable, merging with the embedded snapshot", "path", path, "err", err)
152+ }
153+ return defs.Embedded()
154+}
155+
156+// newLayouts counts table layouts of fresh that prev does not have.
157+func newLayouts(prev, fresh *defs.Snapshot) int {
158+ n := 0
159+ for _, t := range fresh.Tables {
160+ for _, l := range t.Layouts {
161+ h, _ := strconv.ParseUint(l.Hash, 16, 32)
162+ if _, ok := prev.Definition(t.Name, uint32(h)); !ok {
163+ n++
164+ }
165+ }
166+ }
167+ return n
168+}
169+
170+// writeSnapshotFile writes s to path atomically.
171+func writeSnapshotFile(path string, s *defs.Snapshot) error {
172+ var buf bytes.Buffer
173+ if err := s.Encode(&buf); err != nil {
174+ return err
175+ }
176+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
177+ return err
178+ }
179+ return fsutil.WriteAtomic(path, buf.Bytes(), 0o644)
180+}
181+
182+// manifestEntries converts WoWDBDefs manifest entries to defs table entries.
183+func manifestEntries(list []sources.ManifestEntry) []defs.TableEntry {
184+ out := make([]defs.TableEntry, len(list))
185+ for i, e := range list {
186+ out[i] = defs.TableEntry{Name: e.TableName, Hash: e.TableHash, FDID: e.FDID}
187+ }
188+ return out
189+}
190+
191+// defsInfo is the defs show report.
192+type defsInfo struct {
193+ Origin string `json:"origin"`
194+ Builds []string `json:"builds"`
195+ WoWDBDefsCommit string `json:"wowdbdefs_commit"`
196+ GeneratedAt string `json:"generated_at"`
197+ Tables int `json:"tables"`
198+ Layouts int `json:"layouts"`
199+ Keys int `json:"keys"`
200+
201+ Attribution defs.AttributionInfo `json:"attribution"`
202+}
203+
204+var defsShowCmd = &cobra.Command{
205+ Use: "show",
206+ Short: "Show the definitions snapshot used by export",
207+ Args: cobra.NoArgs,
208+ RunE: func(cmd *cobra.Command, args []string) error {
209+ out, err := resolveOut(outFlag, os.Getenv)
210+ if err != nil {
211+ return err
212+ }
213+ s, origin, err := defs.Effective(out)
214+ if err != nil {
215+ return err
216+ }
217+ info := defsInfo{Origin: origin, Builds: s.Builds, WoWDBDefsCommit: s.Source.WoWDBDefsCommit,
218+ GeneratedAt: s.GeneratedAt, Tables: len(s.Tables), Keys: len(s.Keys), Attribution: defs.Attribution}
219+ if info.Builds == nil {
220+ info.Builds = []string{}
221+ }
222+ for _, t := range s.Tables {
223+ info.Layouts += len(t.Layouts)
224+ }
225+ return printDefsInfo(cmd.OutOrStdout(), info, defsJSON)
226+ },
227+}
228+
229+func printDefsInfo(w io.Writer, i defsInfo, asJSON bool) error {
230+ if asJSON {
231+ enc := json.NewEncoder(w)
232+ enc.SetIndent("", " ")
233+ return enc.Encode(i)
234+ }
235+ _, err := fmt.Fprintf(w, "origin: %s\nbuilds: %v\nWoWDBDefs commit: %s\ngenerated: %s\ntables: %d, layouts: %d, keys: %d\nattribution: %s\n",
236+ i.Origin, i.Builds, i.WoWDBDefsCommit, i.GeneratedAt, i.Tables, i.Layouts, i.Keys, defs.AttributionText)
237+ return err
238+}
239+
240+func init() {
241+ defsUpdateCmd.Flags().BoolVar(&defsFresh, "fresh", false, "do not merge with the current snapshot")
242+ defsUpdateCmd.Flags().StringVar(&defsOutput, "output", "", "output file (default <data dir>/defs.json.gz)")
243+ defsUpdateCmd.Flags().BoolVar(&defsOffline, "offline", false, "use cached WoWDBDefs and TACTKeys only")
244+ defsShowCmd.Flags().BoolVar(&defsJSON, "json", false, "print as JSON")
245+ defsCmd.AddCommand(defsUpdateCmd, defsShowCmd)
246+ rootCmd.AddCommand(defsCmd)
247+}
A cmd/defs_test.go +237 -0
@@ -0,0 +1,237 @@
1+package cmd
2+
3+import (
4+ "archive/tar"
5+ "bytes"
6+ "compress/gzip"
7+ "encoding/json"
8+ "net/http"
9+ "net/http/httptest"
10+ "os"
11+ "path/filepath"
12+ "reflect"
13+ "strings"
14+ "testing"
15+
16+ "github.com/bnema/forever-db/internal/defs"
17+ "github.com/bnema/forever-db/internal/sources"
18+ "github.com/bnema/forever-db/internal/testutil"
19+)
20+
21+const defsTestSHA = "0123456789abcdef0123456789abcdef01234567"
22+
23+func le32(v uint32) []byte { return []byte{byte(v), byte(v >> 8), byte(v >> 16), byte(v >> 24)} }
24+
25+func wdc5(hash, layout uint32, ids ...uint32) []byte {
26+ var recs []byte
27+ for _, id := range ids {
28+ recs = append(recs, le32(id)...)
29+ recs = append(recs, le32(id*10)...)
30+ }
31+ return (&testutil.WDC5Builder{RecordSize: 8, TableHash: hash, LayoutHash: layout,
32+ Fields: []testutil.WDC5Field{{SizeBits: 32}, {OffsetBits: 32, SizeBits: 32}},
33+ Sections: []testutil.WDC5Section{{RecordCount: uint32(len(ids)), Records: recs}}}).Build()
34+}
35+
36+func defsTarball(t *testing.T, files map[string]string) []byte {
37+ t.Helper()
38+ var buf bytes.Buffer
39+ gz := gzip.NewWriter(&buf)
40+ tw := tar.NewWriter(gz)
41+ tw.WriteHeader(&tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: "pax_global_header", PAXRecords: map[string]string{"comment": defsTestSHA}})
42+ for name, body := range files {
43+ tw.WriteHeader(&tar.Header{Name: "WoWDBDefs-x/" + name, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg})
44+ tw.Write([]byte(body))
45+ }
46+ tw.Close()
47+ gz.Close()
48+ return buf.Bytes()
49+}
50+
51+// setupDefsUpdate serves WoWDBDefs and TACTKeys from httptest and returns
52+// the install dir and the data dir.
53+func setupDefsUpdate(t *testing.T, layout uint32) (wow, data string) {
54+ t.Helper()
55+ wow = testutil.BuildInstall(t, map[uint32][]byte{100: wdc5(0xA1, layout, 1, 2)})
56+ dbd := "COLUMNS\nint ID\nint V\n\nLAYOUT 00000003, 00000004\n$id$ID<32>\nV<32>\n"
57+ tarData := defsTarball(t, map[string]string{
58+ "manifest.json": `[{"tableName":"Alpha","tableHash":"000000A1","db2FileDataID":100},{"tableName":"Gone","db2FileDataID":555}]`,
59+ "definitions/Alpha.dbd": dbd,
60+ "definitions/Gone.dbd": dbd,
61+ })
62+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
63+ switch r.URL.Path {
64+ case "/tar":
65+ w.Write(tarData)
66+ case "/keys":
67+ w.Write([]byte("1122334455667788 00112233445566778899AABBCCDDEEFF\n"))
68+ default:
69+ http.NotFound(w, r)
70+ }
71+ }))
72+ t.Cleanup(srv.Close)
73+ oldURLs, oldClient := defsURLs, defsClient
74+ defsURLs, defsClient = sources.URLs{DBDTarball: srv.URL + "/tar", TACTKeys: srv.URL + "/keys"}, srv.Client()
75+ t.Cleanup(func() { defsURLs, defsClient = oldURLs, oldClient })
76+ return wow, filepath.Join(t.TempDir(), "data")
77+}
78+
79+func runDefs(t *testing.T, args ...string) (string, error) {
80+ t.Helper()
81+ defer func() { defsFresh, defsOutput, defsOffline, defsJSON = false, "", false, false }()
82+ return runCLI(t, args...)
83+}
84+
85+func readSnapshot(t *testing.T, p string) *defs.Snapshot {
86+ t.Helper()
87+ f, err := os.Open(p)
88+ if err != nil {
89+ t.Fatal(err)
90+ }
91+ defer f.Close()
92+ s, err := defs.Decode(f)
93+ if err != nil {
94+ t.Fatal(err)
95+ }
96+ return s
97+}
98+
99+func TestDefsUpdate(t *testing.T) {
100+ wow, data := setupDefsUpdate(t, 3)
101+ out, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh")
102+ if err != nil {
103+ t.Fatal(err)
104+ }
105+ p := filepath.Join(data, defs.LocalFileName)
106+ if !strings.Contains(out, "wrote "+p) || !strings.Contains(out, "tables: 1 (1 new layouts), 1 absent, 0 without definition, 0 failed") {
107+ t.Fatalf("out = %s", out)
108+ }
109+ s := readSnapshot(t, p)
110+ if len(s.Tables) != 1 || s.Tables[0].Name != "Alpha" || s.Tables[0].Layouts[0].Hash != "00000003" || s.Source.WoWDBDefsCommit != defsTestSHA {
111+ t.Fatalf("snapshot = %+v", s)
112+ }
113+ ents, _ := os.ReadDir(data)
114+ if len(ents) != 1 {
115+ t.Fatalf("leftover files: %v", ents)
116+ }
117+
118+ // The client changes layout: merge keeps the old layout, --fresh does not.
119+ wow2, _ := setupDefsUpdate(t, 4)
120+ out, err = runDefs(t, "defs", "update", "--dir", wow2, "--out", data)
121+ if err != nil {
122+ t.Fatal(err)
123+ }
124+ if !strings.Contains(out, "(1 new layouts)") {
125+ t.Fatalf("out = %s", out)
126+ }
127+ if s := readSnapshot(t, p); len(s.Tables[0].Layouts) != 2 {
128+ t.Fatalf("merged layouts = %+v", s.Tables[0].Layouts)
129+ }
130+ custom := filepath.Join(t.TempDir(), "sub", "x.json.gz")
131+ if _, err := runDefs(t, "defs", "update", "--dir", wow2, "--out", data, "--fresh", "--output", custom); err != nil {
132+ t.Fatal(err)
133+ }
134+ if s := readSnapshot(t, custom); len(s.Tables[0].Layouts) != 1 || s.Tables[0].Layouts[0].Hash != "00000004" {
135+ t.Fatalf("fresh layouts = %+v", s.Tables[0].Layouts)
136+ }
137+}
138+
139+func TestDefsShow(t *testing.T) {
140+ data := t.TempDir()
141+ out, err := runDefs(t, "defs", "show", "--out", data, "--json")
142+ if err != nil {
143+ t.Fatal(err)
144+ }
145+ var m map[string]any
146+ if err := json.Unmarshal([]byte(out), &m); err != nil {
147+ t.Fatalf("%v: %s", err, out)
148+ }
149+ for _, k := range []string{"origin", "builds", "wowdbdefs_commit", "generated_at", "tables", "layouts", "keys"} {
150+ if _, ok := m[k]; !ok {
151+ t.Fatalf("missing %s: %s", k, out)
152+ }
153+ }
154+ if m["origin"] != defs.OriginEmbedded {
155+ t.Fatalf("origin = %v", m["origin"])
156+ }
157+ if !reflect.DeepEqual(m["attribution"], map[string]any{"definitions": "WoWDBDefs contributors",
158+ "license": "CC-BY-SA-4.0", "source": "https://github.com/wowdev/WoWDBDefs"}) {
159+ t.Fatalf("attribution = %v", m["attribution"])
160+ }
161+ if _, ok := m["builds"].([]any); !ok {
162+ t.Fatalf("builds not an array: %s", out)
163+ }
164+
165+ wow, _ := setupDefsUpdate(t, 3)
166+ if _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh"); err != nil {
167+ t.Fatal(err)
168+ }
169+ out, err = runDefs(t, "defs", "show", "--out", data)
170+ if err != nil {
171+ t.Fatal(err)
172+ }
173+ if !strings.Contains(out, "origin: local") || !strings.Contains(out, "tables: 1, layouts: 1, keys: 0") || !strings.Contains(out, defsTestSHA) ||
174+ !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see internal/defs/data/README.md\n") {
175+ t.Fatalf("out = %s", out)
176+ }
177+}
178+
179+func TestDefsUpdateOfflineEmptyCache(t *testing.T) {
180+ wow, data := setupDefsUpdate(t, 3)
181+ _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--offline")
182+ if err == nil || !strings.Contains(err.Error(), "WoWDBDefs") {
183+ t.Fatalf("err = %v", err)
184+ }
185+}
186+
187+func TestDefsUpdateNoDefinitions(t *testing.T) {
188+ wow, data := setupDefsUpdate(t, 9) // layout 9 is not in the .dbd
189+ _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh")
190+ if err == nil || !strings.Contains(err.Error(), "no table definitions generated") {
191+ t.Fatalf("err = %v", err)
192+ }
193+ if _, err := os.Stat(filepath.Join(data, defs.LocalFileName)); !os.IsNotExist(err) {
194+ t.Errorf("snapshot written: %v", err)
195+ }
196+}
197+
198+func TestDefsUpdateOutputMergeBase(t *testing.T) {
199+ wow3, data := setupDefsUpdate(t, 3)
200+ // Local override with layout 3: must not be used as base for --output.
201+ if _, err := runDefs(t, "defs", "update", "--dir", wow3, "--out", data, "--fresh"); err != nil {
202+ t.Fatal(err)
203+ }
204+ wow4, _ := setupDefsUpdate(t, 4)
205+ custom := filepath.Join(t.TempDir(), "x.json.gz")
206+ if _, err := runDefs(t, "defs", "update", "--dir", wow4, "--out", data, "--output", custom); err != nil {
207+ t.Fatal(err)
208+ }
209+ s := readSnapshot(t, custom)
210+ emb, err := defs.Embedded()
211+ if err != nil {
212+ t.Fatal(err)
213+ }
214+ alpha := func(s *defs.Snapshot) []string {
215+ for _, tb := range s.Tables {
216+ if tb.Name == "Alpha" {
217+ var h []string
218+ for _, l := range tb.Layouts {
219+ h = append(h, l.Hash)
220+ }
221+ return h
222+ }
223+ }
224+ return nil
225+ }
226+ if got := alpha(s); len(got) != 1 || got[0] != "00000004" || len(s.Tables) != len(emb.Tables)+1 {
227+ t.Fatalf("merged with embedded: Alpha %v, tables %d (embedded %d)", got, len(s.Tables), len(emb.Tables))
228+ }
229+ // The existing output file is now the base.
230+ wow3b, _ := setupDefsUpdate(t, 3)
231+ if _, err := runDefs(t, "defs", "update", "--dir", wow3b, "--out", data, "--output", custom); err != nil {
232+ t.Fatal(err)
233+ }
234+ if got := alpha(readSnapshot(t, custom)); len(got) != 2 {
235+ t.Fatalf("merged with output file: Alpha %v", got)
236+ }
237+}
@@ -0,0 +1,237 @@
1+package cmd
2+
3+import (
4+ "archive/tar"
5+ "bytes"
6+ "compress/gzip"
7+ "encoding/json"
8+ "net/http"
9+ "net/http/httptest"
10+ "os"
11+ "path/filepath"
12+ "reflect"
13+ "strings"
14+ "testing"
15+
16+ "github.com/bnema/forever-db/internal/defs"
17+ "github.com/bnema/forever-db/internal/sources"
18+ "github.com/bnema/forever-db/internal/testutil"
19+)
20+
21+const defsTestSHA = "0123456789abcdef0123456789abcdef01234567"
22+
23+func le32(v uint32) []byte { return []byte{byte(v), byte(v >> 8), byte(v >> 16), byte(v >> 24)} }
24+
25+func wdc5(hash, layout uint32, ids ...uint32) []byte {
26+ var recs []byte
27+ for _, id := range ids {
28+ recs = append(recs, le32(id)...)
29+ recs = append(recs, le32(id*10)...)
30+ }
31+ return (&testutil.WDC5Builder{RecordSize: 8, TableHash: hash, LayoutHash: layout,
32+ Fields: []testutil.WDC5Field{{SizeBits: 32}, {OffsetBits: 32, SizeBits: 32}},
33+ Sections: []testutil.WDC5Section{{RecordCount: uint32(len(ids)), Records: recs}}}).Build()
34+}
35+
36+func defsTarball(t *testing.T, files map[string]string) []byte {
37+ t.Helper()
38+ var buf bytes.Buffer
39+ gz := gzip.NewWriter(&buf)
40+ tw := tar.NewWriter(gz)
41+ tw.WriteHeader(&tar.Header{Typeflag: tar.TypeXGlobalHeader, Name: "pax_global_header", PAXRecords: map[string]string{"comment": defsTestSHA}})
42+ for name, body := range files {
43+ tw.WriteHeader(&tar.Header{Name: "WoWDBDefs-x/" + name, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg})
44+ tw.Write([]byte(body))
45+ }
46+ tw.Close()
47+ gz.Close()
48+ return buf.Bytes()
49+}
50+
51+// setupDefsUpdate serves WoWDBDefs and TACTKeys from httptest and returns
52+// the install dir and the data dir.
53+func setupDefsUpdate(t *testing.T, layout uint32) (wow, data string) {
54+ t.Helper()
55+ wow = testutil.BuildInstall(t, map[uint32][]byte{100: wdc5(0xA1, layout, 1, 2)})
56+ dbd := "COLUMNS\nint ID\nint V\n\nLAYOUT 00000003, 00000004\n$id$ID<32>\nV<32>\n"
57+ tarData := defsTarball(t, map[string]string{
58+ "manifest.json": `[{"tableName":"Alpha","tableHash":"000000A1","db2FileDataID":100},{"tableName":"Gone","db2FileDataID":555}]`,
59+ "definitions/Alpha.dbd": dbd,
60+ "definitions/Gone.dbd": dbd,
61+ })
62+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
63+ switch r.URL.Path {
64+ case "/tar":
65+ w.Write(tarData)
66+ case "/keys":
67+ w.Write([]byte("1122334455667788 00112233445566778899AABBCCDDEEFF\n"))
68+ default:
69+ http.NotFound(w, r)
70+ }
71+ }))
72+ t.Cleanup(srv.Close)
73+ oldURLs, oldClient := defsURLs, defsClient
74+ defsURLs, defsClient = sources.URLs{DBDTarball: srv.URL + "/tar", TACTKeys: srv.URL + "/keys"}, srv.Client()
75+ t.Cleanup(func() { defsURLs, defsClient = oldURLs, oldClient })
76+ return wow, filepath.Join(t.TempDir(), "data")
77+}
78+
79+func runDefs(t *testing.T, args ...string) (string, error) {
80+ t.Helper()
81+ defer func() { defsFresh, defsOutput, defsOffline, defsJSON = false, "", false, false }()
82+ return runCLI(t, args...)
83+}
84+
85+func readSnapshot(t *testing.T, p string) *defs.Snapshot {
86+ t.Helper()
87+ f, err := os.Open(p)
88+ if err != nil {
89+ t.Fatal(err)
90+ }
91+ defer f.Close()
92+ s, err := defs.Decode(f)
93+ if err != nil {
94+ t.Fatal(err)
95+ }
96+ return s
97+}
98+
99+func TestDefsUpdate(t *testing.T) {
100+ wow, data := setupDefsUpdate(t, 3)
101+ out, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh")
102+ if err != nil {
103+ t.Fatal(err)
104+ }
105+ p := filepath.Join(data, defs.LocalFileName)
106+ if !strings.Contains(out, "wrote "+p) || !strings.Contains(out, "tables: 1 (1 new layouts), 1 absent, 0 without definition, 0 failed") {
107+ t.Fatalf("out = %s", out)
108+ }
109+ s := readSnapshot(t, p)
110+ if len(s.Tables) != 1 || s.Tables[0].Name != "Alpha" || s.Tables[0].Layouts[0].Hash != "00000003" || s.Source.WoWDBDefsCommit != defsTestSHA {
111+ t.Fatalf("snapshot = %+v", s)
112+ }
113+ ents, _ := os.ReadDir(data)
114+ if len(ents) != 1 {
115+ t.Fatalf("leftover files: %v", ents)
116+ }
117+
118+ // The client changes layout: merge keeps the old layout, --fresh does not.
119+ wow2, _ := setupDefsUpdate(t, 4)
120+ out, err = runDefs(t, "defs", "update", "--dir", wow2, "--out", data)
121+ if err != nil {
122+ t.Fatal(err)
123+ }
124+ if !strings.Contains(out, "(1 new layouts)") {
125+ t.Fatalf("out = %s", out)
126+ }
127+ if s := readSnapshot(t, p); len(s.Tables[0].Layouts) != 2 {
128+ t.Fatalf("merged layouts = %+v", s.Tables[0].Layouts)
129+ }
130+ custom := filepath.Join(t.TempDir(), "sub", "x.json.gz")
131+ if _, err := runDefs(t, "defs", "update", "--dir", wow2, "--out", data, "--fresh", "--output", custom); err != nil {
132+ t.Fatal(err)
133+ }
134+ if s := readSnapshot(t, custom); len(s.Tables[0].Layouts) != 1 || s.Tables[0].Layouts[0].Hash != "00000004" {
135+ t.Fatalf("fresh layouts = %+v", s.Tables[0].Layouts)
136+ }
137+}
138+
139+func TestDefsShow(t *testing.T) {
140+ data := t.TempDir()
141+ out, err := runDefs(t, "defs", "show", "--out", data, "--json")
142+ if err != nil {
143+ t.Fatal(err)
144+ }
145+ var m map[string]any
146+ if err := json.Unmarshal([]byte(out), &m); err != nil {
147+ t.Fatalf("%v: %s", err, out)
148+ }
149+ for _, k := range []string{"origin", "builds", "wowdbdefs_commit", "generated_at", "tables", "layouts", "keys"} {
150+ if _, ok := m[k]; !ok {
151+ t.Fatalf("missing %s: %s", k, out)
152+ }
153+ }
154+ if m["origin"] != defs.OriginEmbedded {
155+ t.Fatalf("origin = %v", m["origin"])
156+ }
157+ if !reflect.DeepEqual(m["attribution"], map[string]any{"definitions": "WoWDBDefs contributors",
158+ "license": "CC-BY-SA-4.0", "source": "https://github.com/wowdev/WoWDBDefs"}) {
159+ t.Fatalf("attribution = %v", m["attribution"])
160+ }
161+ if _, ok := m["builds"].([]any); !ok {
162+ t.Fatalf("builds not an array: %s", out)
163+ }
164+
165+ wow, _ := setupDefsUpdate(t, 3)
166+ if _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh"); err != nil {
167+ t.Fatal(err)
168+ }
169+ out, err = runDefs(t, "defs", "show", "--out", data)
170+ if err != nil {
171+ t.Fatal(err)
172+ }
173+ if !strings.Contains(out, "origin: local") || !strings.Contains(out, "tables: 1, layouts: 1, keys: 0") || !strings.Contains(out, defsTestSHA) ||
174+ !strings.HasSuffix(out, "attribution: table definitions from WoWDBDefs contributors (CC BY-SA 4.0, https://github.com/wowdev/WoWDBDefs); see internal/defs/data/README.md\n") {
175+ t.Fatalf("out = %s", out)
176+ }
177+}
178+
179+func TestDefsUpdateOfflineEmptyCache(t *testing.T) {
180+ wow, data := setupDefsUpdate(t, 3)
181+ _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--offline")
182+ if err == nil || !strings.Contains(err.Error(), "WoWDBDefs") {
183+ t.Fatalf("err = %v", err)
184+ }
185+}
186+
187+func TestDefsUpdateNoDefinitions(t *testing.T) {
188+ wow, data := setupDefsUpdate(t, 9) // layout 9 is not in the .dbd
189+ _, err := runDefs(t, "defs", "update", "--dir", wow, "--out", data, "--fresh")
190+ if err == nil || !strings.Contains(err.Error(), "no table definitions generated") {
191+ t.Fatalf("err = %v", err)
192+ }
193+ if _, err := os.Stat(filepath.Join(data, defs.LocalFileName)); !os.IsNotExist(err) {
194+ t.Errorf("snapshot written: %v", err)
195+ }
196+}
197+
198+func TestDefsUpdateOutputMergeBase(t *testing.T) {
199+ wow3, data := setupDefsUpdate(t, 3)
200+ // Local override with layout 3: must not be used as base for --output.
201+ if _, err := runDefs(t, "defs", "update", "--dir", wow3, "--out", data, "--fresh"); err != nil {
202+ t.Fatal(err)
203+ }
204+ wow4, _ := setupDefsUpdate(t, 4)
205+ custom := filepath.Join(t.TempDir(), "x.json.gz")
206+ if _, err := runDefs(t, "defs", "update", "--dir", wow4, "--out", data, "--output", custom); err != nil {
207+ t.Fatal(err)
208+ }
209+ s := readSnapshot(t, custom)
210+ emb, err := defs.Embedded()
211+ if err != nil {
212+ t.Fatal(err)
213+ }
214+ alpha := func(s *defs.Snapshot) []string {
215+ for _, tb := range s.Tables {
216+ if tb.Name == "Alpha" {
217+ var h []string
218+ for _, l := range tb.Layouts {
219+ h = append(h, l.Hash)
220+ }
221+ return h
222+ }
223+ }
224+ return nil
225+ }
226+ if got := alpha(s); len(got) != 1 || got[0] != "00000004" || len(s.Tables) != len(emb.Tables)+1 {
227+ t.Fatalf("merged with embedded: Alpha %v, tables %d (embedded %d)", got, len(s.Tables), len(emb.Tables))
228+ }
229+ // The existing output file is now the base.
230+ wow3b, _ := setupDefsUpdate(t, 3)
231+ if _, err := runDefs(t, "defs", "update", "--dir", wow3b, "--out", data, "--output", custom); err != nil {
232+ t.Fatal(err)
233+ }
234+ if got := alpha(readSnapshot(t, custom)); len(got) != 2 {
235+ t.Fatalf("merged with output file: Alpha %v", got)
236+ }
237+}
A cmd/export.go +96 -0
@@ -0,0 +1,96 @@
1+package cmd
2+
3+import (
4+ "fmt"
5+ "io"
6+ "os"
7+ "os/signal"
8+ "syscall"
9+
10+ "github.com/spf13/cobra"
11+
12+ "github.com/bnema/forever-db/internal/export"
13+ "github.com/bnema/forever-db/internal/install"
14+)
15+
16+var exportForce bool
17+
18+var exportCmd = &cobra.Command{
19+ Use: "export",
20+ Short: "Export every client table to a SQLite database",
21+ Args: cobra.NoArgs,
22+ RunE: func(cmd *cobra.Command, args []string) error {
23+ dir, err := resolveDir(dirFlag, os.Getenv)
24+ if err != nil {
25+ return err
26+ }
27+ out, err := resolveOut(outFlag, os.Getenv)
28+ if err != nil {
29+ return err
30+ }
31+ inst, err := install.Detect(dir)
32+ if err != nil {
33+ return err
34+ }
35+ w := cmd.OutOrStdout()
36+ if !exportForce {
37+ r, err := export.Status(inst, out)
38+ if err != nil {
39+ return err
40+ }
41+ if r.State == export.StateUpToDate {
42+ _, err = fmt.Fprintf(w, "already up to date (%s)\n", inst.Version)
43+ return err
44+ }
45+ }
46+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
47+ defer stop()
48+ // After the first signal, restore default handling so a second one kills.
49+ go func() {
50+ <-ctx.Done()
51+ stop()
52+ }()
53+ sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version})
54+ if err != nil {
55+ return err
56+ }
57+ printSummary(w, sum)
58+ return nil
59+ },
60+}
61+
62+func printSummary(w io.Writer, s *export.Summary) {
63+ fmt.Fprintf(w, "exported %s to %s in %s\n", s.Version, s.OutputPath, s.Duration.Round(1e7))
64+ fmt.Fprintf(w, "tables: %d ok, %d absent, %d no_definition, %d failed\n",
65+ s.Counts[export.StatusOK], s.Counts[export.StatusAbsent], s.Counts[export.StatusNoDefinition], s.Counts[export.StatusFailed])
66+ for _, f := range s.Failed {
67+ fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Err)
68+ }
69+ fmt.Fprintf(w, "hotfixes (%s): %d upserts, %d deletes, %d reverts, %d errors\n",
70+ s.DBCacheStatus, s.Hotfix.Upserts, s.Hotfix.Deletes, s.Hotfix.Reverts, s.Hotfix.Errors)
71+ fmt.Fprintf(w, "encrypted rows skipped: %d (%d missing keys), client keys added: %d\n",
72+ s.SkippedRows, len(s.MissingKeys), s.ClientKeysAdded)
73+ commit := s.DefsCommit
74+ if len(commit) > 12 {
75+ commit = commit[:12]
76+ }
77+ if commit == "" {
78+ commit = "unknown"
79+ }
80+ generated := s.DefsGeneratedAt
81+ if len(generated) >= 10 {
82+ generated = generated[:10]
83+ }
84+ if generated == "" {
85+ generated = "unknown"
86+ }
87+ fmt.Fprintf(w, "definitions: %s (WoWDBDefs %s, generated %s)\n", s.DefsOrigin, commit, generated)
88+ if n := s.Counts[export.StatusNoDefinition]; n > 0 {
89+ fmt.Fprintf(w, "hint: %d tables have no definition — run \"forever-db defs update\"\n", n)
90+ }
91+}
92+
93+func init() {
94+ exportCmd.Flags().BoolVar(&exportForce, "force", false, "export even when the last export is up to date")
95+ rootCmd.AddCommand(exportCmd)
96+}
@@ -0,0 +1,96 @@
1+package cmd
2+
3+import (
4+ "fmt"
5+ "io"
6+ "os"
7+ "os/signal"
8+ "syscall"
9+
10+ "github.com/spf13/cobra"
11+
12+ "github.com/bnema/forever-db/internal/export"
13+ "github.com/bnema/forever-db/internal/install"
14+)
15+
16+var exportForce bool
17+
18+var exportCmd = &cobra.Command{
19+ Use: "export",
20+ Short: "Export every client table to a SQLite database",
21+ Args: cobra.NoArgs,
22+ RunE: func(cmd *cobra.Command, args []string) error {
23+ dir, err := resolveDir(dirFlag, os.Getenv)
24+ if err != nil {
25+ return err
26+ }
27+ out, err := resolveOut(outFlag, os.Getenv)
28+ if err != nil {
29+ return err
30+ }
31+ inst, err := install.Detect(dir)
32+ if err != nil {
33+ return err
34+ }
35+ w := cmd.OutOrStdout()
36+ if !exportForce {
37+ r, err := export.Status(inst, out)
38+ if err != nil {
39+ return err
40+ }
41+ if r.State == export.StateUpToDate {
42+ _, err = fmt.Fprintf(w, "already up to date (%s)\n", inst.Version)
43+ return err
44+ }
45+ }
46+ ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
47+ defer stop()
48+ // After the first signal, restore default handling so a second one kills.
49+ go func() {
50+ <-ctx.Done()
51+ stop()
52+ }()
53+ sum, err := export.Run(ctx, export.Options{Dir: dir, OutDir: out, ToolVersion: version})
54+ if err != nil {
55+ return err
56+ }
57+ printSummary(w, sum)
58+ return nil
59+ },
60+}
61+
62+func printSummary(w io.Writer, s *export.Summary) {
63+ fmt.Fprintf(w, "exported %s to %s in %s\n", s.Version, s.OutputPath, s.Duration.Round(1e7))
64+ fmt.Fprintf(w, "tables: %d ok, %d absent, %d no_definition, %d failed\n",
65+ s.Counts[export.StatusOK], s.Counts[export.StatusAbsent], s.Counts[export.StatusNoDefinition], s.Counts[export.StatusFailed])
66+ for _, f := range s.Failed {
67+ fmt.Fprintf(w, " failed %s: %s\n", f.Name, f.Err)
68+ }
69+ fmt.Fprintf(w, "hotfixes (%s): %d upserts, %d deletes, %d reverts, %d errors\n",
70+ s.DBCacheStatus, s.Hotfix.Upserts, s.Hotfix.Deletes, s.Hotfix.Reverts, s.Hotfix.Errors)
71+ fmt.Fprintf(w, "encrypted rows skipped: %d (%d missing keys), client keys added: %d\n",
72+ s.SkippedRows, len(s.MissingKeys), s.ClientKeysAdded)
73+ commit := s.DefsCommit
74+ if len(commit) > 12 {
75+ commit = commit[:12]
76+ }
77+ if commit == "" {
78+ commit = "unknown"
79+ }
80+ generated := s.DefsGeneratedAt
81+ if len(generated) >= 10 {
82+ generated = generated[:10]
83+ }
84+ if generated == "" {
85+ generated = "unknown"
86+ }
87+ fmt.Fprintf(w, "definitions: %s (WoWDBDefs %s, generated %s)\n", s.DefsOrigin, commit, generated)
88+ if n := s.Counts[export.StatusNoDefinition]; n > 0 {
89+ fmt.Fprintf(w, "hint: %d tables have no definition — run \"forever-db defs update\"\n", n)
90+ }
91+}
92+
93+func init() {
94+ exportCmd.Flags().BoolVar(&exportForce, "force", false, "export even when the last export is up to date")
95+ rootCmd.AddCommand(exportCmd)
96+}
A cmd/export_test.go +78 -0
@@ -0,0 +1,78 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "context"
6+ "path/filepath"
7+ "strings"
8+ "testing"
9+
10+ "github.com/bnema/forever-db/internal/export"
11+ "github.com/bnema/forever-db/internal/testutil"
12+)
13+
14+func runCLI(t *testing.T, args ...string) (string, error) {
15+ t.Helper()
16+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
17+ t.Setenv("HOME", t.TempDir())
18+ t.Setenv("FOREVER_DB_WOW_DIR", "")
19+ t.Setenv("FOREVER_DB_DATA_DIR", "")
20+ t.Setenv("XDG_DATA_HOME", t.TempDir())
21+ var out bytes.Buffer
22+ rootCmd.SetOut(&out)
23+ rootCmd.SetErr(&out)
24+ rootCmd.SetArgs(args)
25+ defer func() {
26+ rootCmd.SetArgs(nil)
27+ dirFlag, outFlag, exportForce = "", "", false
28+ }()
29+ err := rootCmd.ExecuteContext(context.Background())
30+ return out.String(), err
31+}
32+
33+func TestExportNotForever(t *testing.T) {
34+ _, err := runCLI(t, "export", "--dir", t.TempDir(), "--out", filepath.Join(t.TempDir(), "o"))
35+ if err == nil || !strings.Contains(err.Error(), "WoW Forever not found") {
36+ t.Fatalf("err = %v", err)
37+ }
38+}
39+
40+func TestExportMissingDir(t *testing.T) {
41+ _, err := runCLI(t, "export", "--out", filepath.Join(t.TempDir(), "o"))
42+ if err == nil || !strings.Contains(err.Error(), "--dir") || !strings.Contains(err.Error(), "FOREVER_DB_WOW_DIR") {
43+ t.Fatalf("err = %v", err)
44+ }
45+}
46+
47+func TestExportEmbeddedNoNetwork(t *testing.T) {
48+ wow := testutil.BuildInstall(t, map[uint32][]byte{1: []byte("x")})
49+ out, err := runCLI(t, "export", "--dir", wow, "--out", filepath.Join(t.TempDir(), "o"))
50+ if err != nil {
51+ t.Fatal(err)
52+ }
53+ if !strings.Contains(out, "definitions: embedded (WoWDBDefs ") {
54+ t.Fatalf("out = %s", out)
55+ }
56+}
57+
58+func TestOfflineFlagRemoved(t *testing.T) {
59+ if _, err := runCLI(t, "export", "--offline"); err == nil || !strings.Contains(err.Error(), "unknown flag") {
60+ t.Fatalf("err = %v", err)
61+ }
62+}
63+
64+func TestPrintSummaryHint(t *testing.T) {
65+ var b bytes.Buffer
66+ printSummary(&b, &export.Summary{Counts: map[string]int{export.StatusNoDefinition: 3}, DefsOrigin: "local",
67+ DefsCommit: "0123456789abcdef0123", DefsGeneratedAt: "2026-11-20T10:00:00Z"})
68+ out := b.String()
69+ if !strings.Contains(out, "definitions: local (WoWDBDefs 0123456789ab, generated 2026-11-20)\n") ||
70+ strings.Count(out, "hint: 3 tables have no definition — run \"forever-db defs update\"") != 1 {
71+ t.Fatalf("out = %s", out)
72+ }
73+ b.Reset()
74+ printSummary(&b, &export.Summary{Counts: map[string]int{}})
75+ if strings.Contains(b.String(), "hint:") {
76+ t.Fatalf("unexpected hint: %s", b.String())
77+ }
78+}
@@ -0,0 +1,78 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "context"
6+ "path/filepath"
7+ "strings"
8+ "testing"
9+
10+ "github.com/bnema/forever-db/internal/export"
11+ "github.com/bnema/forever-db/internal/testutil"
12+)
13+
14+func runCLI(t *testing.T, args ...string) (string, error) {
15+ t.Helper()
16+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
17+ t.Setenv("HOME", t.TempDir())
18+ t.Setenv("FOREVER_DB_WOW_DIR", "")
19+ t.Setenv("FOREVER_DB_DATA_DIR", "")
20+ t.Setenv("XDG_DATA_HOME", t.TempDir())
21+ var out bytes.Buffer
22+ rootCmd.SetOut(&out)
23+ rootCmd.SetErr(&out)
24+ rootCmd.SetArgs(args)
25+ defer func() {
26+ rootCmd.SetArgs(nil)
27+ dirFlag, outFlag, exportForce = "", "", false
28+ }()
29+ err := rootCmd.ExecuteContext(context.Background())
30+ return out.String(), err
31+}
32+
33+func TestExportNotForever(t *testing.T) {
34+ _, err := runCLI(t, "export", "--dir", t.TempDir(), "--out", filepath.Join(t.TempDir(), "o"))
35+ if err == nil || !strings.Contains(err.Error(), "WoW Forever not found") {
36+ t.Fatalf("err = %v", err)
37+ }
38+}
39+
40+func TestExportMissingDir(t *testing.T) {
41+ _, err := runCLI(t, "export", "--out", filepath.Join(t.TempDir(), "o"))
42+ if err == nil || !strings.Contains(err.Error(), "--dir") || !strings.Contains(err.Error(), "FOREVER_DB_WOW_DIR") {
43+ t.Fatalf("err = %v", err)
44+ }
45+}
46+
47+func TestExportEmbeddedNoNetwork(t *testing.T) {
48+ wow := testutil.BuildInstall(t, map[uint32][]byte{1: []byte("x")})
49+ out, err := runCLI(t, "export", "--dir", wow, "--out", filepath.Join(t.TempDir(), "o"))
50+ if err != nil {
51+ t.Fatal(err)
52+ }
53+ if !strings.Contains(out, "definitions: embedded (WoWDBDefs ") {
54+ t.Fatalf("out = %s", out)
55+ }
56+}
57+
58+func TestOfflineFlagRemoved(t *testing.T) {
59+ if _, err := runCLI(t, "export", "--offline"); err == nil || !strings.Contains(err.Error(), "unknown flag") {
60+ t.Fatalf("err = %v", err)
61+ }
62+}
63+
64+func TestPrintSummaryHint(t *testing.T) {
65+ var b bytes.Buffer
66+ printSummary(&b, &export.Summary{Counts: map[string]int{export.StatusNoDefinition: 3}, DefsOrigin: "local",
67+ DefsCommit: "0123456789abcdef0123", DefsGeneratedAt: "2026-11-20T10:00:00Z"})
68+ out := b.String()
69+ if !strings.Contains(out, "definitions: local (WoWDBDefs 0123456789ab, generated 2026-11-20)\n") ||
70+ strings.Count(out, "hint: 3 tables have no definition — run \"forever-db defs update\"") != 1 {
71+ t.Fatalf("out = %s", out)
72+ }
73+ b.Reset()
74+ printSummary(&b, &export.Summary{Counts: map[string]int{}})
75+ if strings.Contains(b.String(), "hint:") {
76+ t.Fatalf("unexpected hint: %s", b.String())
77+ }
78+}
A cmd/paths.go +54 -0
@@ -0,0 +1,54 @@
1+package cmd
2+
3+import (
4+ "errors"
5+ "path/filepath"
6+)
7+
8+const appName = "forever-db"
9+
10+var errHomeNotSet = errors.New("$HOME is not defined")
11+
12+var errDirNotSet = errors.New("WoW directory not set: use --dir or FOREVER_DB_WOW_DIR")
13+
14+// resolveDir returns the WoW install directory: flag > FOREVER_DB_WOW_DIR.
15+func resolveDir(flag string, getenv func(string) string) (string, error) {
16+ if flag != "" {
17+ return flag, nil
18+ }
19+ if v := getenv("FOREVER_DB_WOW_DIR"); v != "" {
20+ return v, nil
21+ }
22+ return "", errDirNotSet
23+}
24+
25+// resolveOut returns the output directory:
26+// flag > FOREVER_DB_DATA_DIR > $XDG_DATA_HOME/forever-db > $HOME/.local/share/forever-db.
27+func resolveOut(flag string, getenv func(string) string) (string, error) {
28+ if flag != "" {
29+ return flag, nil
30+ }
31+ if v := getenv("FOREVER_DB_DATA_DIR"); v != "" {
32+ return v, nil
33+ }
34+ if v := getenv("XDG_DATA_HOME"); v != "" {
35+ return filepath.Join(v, appName), nil
36+ }
37+ home := getenv("HOME")
38+ if home == "" {
39+ return "", errHomeNotSet
40+ }
41+ return filepath.Join(home, ".local", "share", appName), nil
42+}
43+
44+// cacheDir returns $XDG_CACHE_HOME/forever-db > $HOME/.cache/forever-db.
45+func cacheDir(getenv func(string) string) (string, error) {
46+ if v := getenv("XDG_CACHE_HOME"); v != "" {
47+ return filepath.Join(v, appName), nil
48+ }
49+ home := getenv("HOME")
50+ if home == "" {
51+ return "", errHomeNotSet
52+ }
53+ return filepath.Join(home, ".cache", appName), nil
54+}
@@ -0,0 +1,54 @@
1+package cmd
2+
3+import (
4+ "errors"
5+ "path/filepath"
6+)
7+
8+const appName = "forever-db"
9+
10+var errHomeNotSet = errors.New("$HOME is not defined")
11+
12+var errDirNotSet = errors.New("WoW directory not set: use --dir or FOREVER_DB_WOW_DIR")
13+
14+// resolveDir returns the WoW install directory: flag > FOREVER_DB_WOW_DIR.
15+func resolveDir(flag string, getenv func(string) string) (string, error) {
16+ if flag != "" {
17+ return flag, nil
18+ }
19+ if v := getenv("FOREVER_DB_WOW_DIR"); v != "" {
20+ return v, nil
21+ }
22+ return "", errDirNotSet
23+}
24+
25+// resolveOut returns the output directory:
26+// flag > FOREVER_DB_DATA_DIR > $XDG_DATA_HOME/forever-db > $HOME/.local/share/forever-db.
27+func resolveOut(flag string, getenv func(string) string) (string, error) {
28+ if flag != "" {
29+ return flag, nil
30+ }
31+ if v := getenv("FOREVER_DB_DATA_DIR"); v != "" {
32+ return v, nil
33+ }
34+ if v := getenv("XDG_DATA_HOME"); v != "" {
35+ return filepath.Join(v, appName), nil
36+ }
37+ home := getenv("HOME")
38+ if home == "" {
39+ return "", errHomeNotSet
40+ }
41+ return filepath.Join(home, ".local", "share", appName), nil
42+}
43+
44+// cacheDir returns $XDG_CACHE_HOME/forever-db > $HOME/.cache/forever-db.
45+func cacheDir(getenv func(string) string) (string, error) {
46+ if v := getenv("XDG_CACHE_HOME"); v != "" {
47+ return filepath.Join(v, appName), nil
48+ }
49+ home := getenv("HOME")
50+ if home == "" {
51+ return "", errHomeNotSet
52+ }
53+ return filepath.Join(home, ".cache", appName), nil
54+}
A cmd/paths_test.go +77 -0
@@ -0,0 +1,77 @@
1+package cmd
2+
3+import "testing"
4+
5+func envFrom(m map[string]string) func(string) string {
6+ return func(k string) string { return m[k] }
7+}
8+
9+func TestResolveDir(t *testing.T) {
10+ tests := []struct {
11+ name, flag string
12+ env map[string]string
13+ want string
14+ wantErr bool
15+ }{
16+ {"flag wins", "/flag", map[string]string{"FOREVER_DB_WOW_DIR": "/env"}, "/flag", false},
17+ {"env", "", map[string]string{"FOREVER_DB_WOW_DIR": "/env"}, "/env", false},
18+ {"missing", "", nil, "", true},
19+ }
20+ for _, tt := range tests {
21+ t.Run(tt.name, func(t *testing.T) {
22+ got, err := resolveDir(tt.flag, envFrom(tt.env))
23+ if tt.wantErr {
24+ if err == nil || err.Error() != "WoW directory not set: use --dir or FOREVER_DB_WOW_DIR" {
25+ t.Fatalf("err = %v", err)
26+ }
27+ return
28+ }
29+ if err != nil || got != tt.want {
30+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
31+ }
32+ })
33+ }
34+}
35+
36+func TestResolveOut(t *testing.T) {
37+ all := map[string]string{"FOREVER_DB_DATA_DIR": "/data", "XDG_DATA_HOME": "/xdg", "HOME": "/home/u"}
38+ tests := []struct {
39+ name, flag string
40+ env map[string]string
41+ want string
42+ }{
43+ {"flag", "/flag", all, "/flag"},
44+ {"env", "", all, "/data"},
45+ {"xdg", "", map[string]string{"XDG_DATA_HOME": "/xdg", "HOME": "/home/u"}, "/xdg/forever-db"},
46+ {"home", "", map[string]string{"HOME": "/home/u"}, "/home/u/.local/share/forever-db"},
47+ {"no home", "", nil, ""},
48+ }
49+ for _, tt := range tests {
50+ t.Run(tt.name, func(t *testing.T) {
51+ got, err := resolveOut(tt.flag, envFrom(tt.env))
52+ if (err != nil) != (tt.want == "") || got != tt.want {
53+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
54+ }
55+ })
56+ }
57+}
58+
59+func TestCacheDir(t *testing.T) {
60+ tests := []struct {
61+ name string
62+ env map[string]string
63+ want string
64+ }{
65+ {"xdg", map[string]string{"XDG_CACHE_HOME": "/xc", "HOME": "/home/u"}, "/xc/forever-db"},
66+ {"home", map[string]string{"HOME": "/home/u"}, "/home/u/.cache/forever-db"},
67+ {"no home", nil, ""},
68+ }
69+ for _, tt := range tests {
70+ t.Run(tt.name, func(t *testing.T) {
71+ got, err := cacheDir(envFrom(tt.env))
72+ if (err != nil) != (tt.want == "") || got != tt.want {
73+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
74+ }
75+ })
76+ }
77+}
@@ -0,0 +1,77 @@
1+package cmd
2+
3+import "testing"
4+
5+func envFrom(m map[string]string) func(string) string {
6+ return func(k string) string { return m[k] }
7+}
8+
9+func TestResolveDir(t *testing.T) {
10+ tests := []struct {
11+ name, flag string
12+ env map[string]string
13+ want string
14+ wantErr bool
15+ }{
16+ {"flag wins", "/flag", map[string]string{"FOREVER_DB_WOW_DIR": "/env"}, "/flag", false},
17+ {"env", "", map[string]string{"FOREVER_DB_WOW_DIR": "/env"}, "/env", false},
18+ {"missing", "", nil, "", true},
19+ }
20+ for _, tt := range tests {
21+ t.Run(tt.name, func(t *testing.T) {
22+ got, err := resolveDir(tt.flag, envFrom(tt.env))
23+ if tt.wantErr {
24+ if err == nil || err.Error() != "WoW directory not set: use --dir or FOREVER_DB_WOW_DIR" {
25+ t.Fatalf("err = %v", err)
26+ }
27+ return
28+ }
29+ if err != nil || got != tt.want {
30+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
31+ }
32+ })
33+ }
34+}
35+
36+func TestResolveOut(t *testing.T) {
37+ all := map[string]string{"FOREVER_DB_DATA_DIR": "/data", "XDG_DATA_HOME": "/xdg", "HOME": "/home/u"}
38+ tests := []struct {
39+ name, flag string
40+ env map[string]string
41+ want string
42+ }{
43+ {"flag", "/flag", all, "/flag"},
44+ {"env", "", all, "/data"},
45+ {"xdg", "", map[string]string{"XDG_DATA_HOME": "/xdg", "HOME": "/home/u"}, "/xdg/forever-db"},
46+ {"home", "", map[string]string{"HOME": "/home/u"}, "/home/u/.local/share/forever-db"},
47+ {"no home", "", nil, ""},
48+ }
49+ for _, tt := range tests {
50+ t.Run(tt.name, func(t *testing.T) {
51+ got, err := resolveOut(tt.flag, envFrom(tt.env))
52+ if (err != nil) != (tt.want == "") || got != tt.want {
53+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
54+ }
55+ })
56+ }
57+}
58+
59+func TestCacheDir(t *testing.T) {
60+ tests := []struct {
61+ name string
62+ env map[string]string
63+ want string
64+ }{
65+ {"xdg", map[string]string{"XDG_CACHE_HOME": "/xc", "HOME": "/home/u"}, "/xc/forever-db"},
66+ {"home", map[string]string{"HOME": "/home/u"}, "/home/u/.cache/forever-db"},
67+ {"no home", nil, ""},
68+ }
69+ for _, tt := range tests {
70+ t.Run(tt.name, func(t *testing.T) {
71+ got, err := cacheDir(envFrom(tt.env))
72+ if (err != nil) != (tt.want == "") || got != tt.want {
73+ t.Fatalf("got %q, %v; want %q", got, err, tt.want)
74+ }
75+ })
76+ }
77+}
A cmd/root.go +76 -0
@@ -0,0 +1,76 @@
1+package cmd
2+
3+import (
4+ "log/slog"
5+ "os"
6+ "runtime/debug"
7+
8+ "github.com/spf13/cobra"
9+)
10+
11+// Version info set via ldflags at build time.
12+var (
13+ version = "dev"
14+ commit = "unknown"
15+)
16+
17+var (
18+ dirFlag string
19+ outFlag string
20+ verbose bool
21+)
22+
23+var rootCmd = &cobra.Command{
24+ Use: "forever-db",
25+ Short: "Export WoW Forever client data to SQLite",
26+ SilenceUsage: true,
27+ SilenceErrors: false,
28+}
29+
30+// Execute runs the root command and exits with status 1 on error.
31+func Execute() {
32+ if err := rootCmd.Execute(); err != nil {
33+ os.Exit(1)
34+ }
35+}
36+
37+// resolveVersion keeps ldflags values; for a plain "go install" build
38+// (version "dev") it falls back to the module version and VCS revision
39+// recorded in the binary.
40+func resolveVersion(v, c string, read func() (*debug.BuildInfo, bool)) (string, string) {
41+ if v != "dev" {
42+ return v, c
43+ }
44+ info, ok := read()
45+ if !ok {
46+ return v, c
47+ }
48+ if mv := info.Main.Version; mv != "" && mv != "(devel)" {
49+ v = mv
50+ }
51+ for _, s := range info.Settings {
52+ if s.Key == "vcs.revision" && s.Value != "" && c == "unknown" {
53+ c = s.Value
54+ if len(c) > 12 {
55+ c = c[:12]
56+ }
57+ }
58+ }
59+ return v, c
60+}
61+
62+func init() {
63+ version, commit = resolveVersion(version, commit, debug.ReadBuildInfo)
64+ rootCmd.Version = version + " (" + commit + ")"
65+ rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
66+ level := slog.LevelInfo
67+ if verbose {
68+ level = slog.LevelDebug
69+ }
70+ slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
71+ }
72+ pf := rootCmd.PersistentFlags()
73+ pf.StringVar(&dirFlag, "dir", "", "WoW Forever install directory (env FOREVER_DB_WOW_DIR)")
74+ pf.StringVar(&outFlag, "out", "", "output directory (env FOREVER_DB_DATA_DIR)")
75+ pf.BoolVarP(&verbose, "verbose", "v", false, "enable debug logging")
76+}
@@ -0,0 +1,76 @@
1+package cmd
2+
3+import (
4+ "log/slog"
5+ "os"
6+ "runtime/debug"
7+
8+ "github.com/spf13/cobra"
9+)
10+
11+// Version info set via ldflags at build time.
12+var (
13+ version = "dev"
14+ commit = "unknown"
15+)
16+
17+var (
18+ dirFlag string
19+ outFlag string
20+ verbose bool
21+)
22+
23+var rootCmd = &cobra.Command{
24+ Use: "forever-db",
25+ Short: "Export WoW Forever client data to SQLite",
26+ SilenceUsage: true,
27+ SilenceErrors: false,
28+}
29+
30+// Execute runs the root command and exits with status 1 on error.
31+func Execute() {
32+ if err := rootCmd.Execute(); err != nil {
33+ os.Exit(1)
34+ }
35+}
36+
37+// resolveVersion keeps ldflags values; for a plain "go install" build
38+// (version "dev") it falls back to the module version and VCS revision
39+// recorded in the binary.
40+func resolveVersion(v, c string, read func() (*debug.BuildInfo, bool)) (string, string) {
41+ if v != "dev" {
42+ return v, c
43+ }
44+ info, ok := read()
45+ if !ok {
46+ return v, c
47+ }
48+ if mv := info.Main.Version; mv != "" && mv != "(devel)" {
49+ v = mv
50+ }
51+ for _, s := range info.Settings {
52+ if s.Key == "vcs.revision" && s.Value != "" && c == "unknown" {
53+ c = s.Value
54+ if len(c) > 12 {
55+ c = c[:12]
56+ }
57+ }
58+ }
59+ return v, c
60+}
61+
62+func init() {
63+ version, commit = resolveVersion(version, commit, debug.ReadBuildInfo)
64+ rootCmd.Version = version + " (" + commit + ")"
65+ rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
66+ level := slog.LevelInfo
67+ if verbose {
68+ level = slog.LevelDebug
69+ }
70+ slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
71+ }
72+ pf := rootCmd.PersistentFlags()
73+ pf.StringVar(&dirFlag, "dir", "", "WoW Forever install directory (env FOREVER_DB_WOW_DIR)")
74+ pf.StringVar(&outFlag, "out", "", "output directory (env FOREVER_DB_DATA_DIR)")
75+ pf.BoolVarP(&verbose, "verbose", "v", false, "enable debug logging")
76+}
A cmd/root_test.go +32 -0
@@ -0,0 +1,32 @@
1+package cmd
2+
3+import (
4+ "runtime/debug"
5+ "testing"
6+)
7+
8+func TestResolveVersion(t *testing.T) {
9+ info := func(mv string, settings ...debug.BuildSetting) func() (*debug.BuildInfo, bool) {
10+ return func() (*debug.BuildInfo, bool) {
11+ return &debug.BuildInfo{Main: debug.Module{Version: mv}, Settings: settings}, true
12+ }
13+ }
14+ rev := debug.BuildSetting{Key: "vcs.revision", Value: "0123456789abcdef0123"}
15+ tests := []struct {
16+ name, v, c string
17+ read func() (*debug.BuildInfo, bool)
18+ wantV string
19+ wantC string
20+ }{
21+ {"ldflags win", "v0.2.0", "abc", info("v0.1.0", rev), "v0.2.0", "abc"},
22+ {"go install", "dev", "unknown", info("v0.1.0"), "v0.1.0", "unknown"},
23+ {"devel with vcs", "dev", "unknown", info("(devel)", rev), "dev", "0123456789ab"},
24+ {"no info", "dev", "unknown", func() (*debug.BuildInfo, bool) { return nil, false }, "dev", "unknown"},
25+ }
26+ for _, tt := range tests {
27+ v, c := resolveVersion(tt.v, tt.c, tt.read)
28+ if v != tt.wantV || c != tt.wantC {
29+ t.Errorf("%s: got %s %s, want %s %s", tt.name, v, c, tt.wantV, tt.wantC)
30+ }
31+ }
32+}
@@ -0,0 +1,32 @@
1+package cmd
2+
3+import (
4+ "runtime/debug"
5+ "testing"
6+)
7+
8+func TestResolveVersion(t *testing.T) {
9+ info := func(mv string, settings ...debug.BuildSetting) func() (*debug.BuildInfo, bool) {
10+ return func() (*debug.BuildInfo, bool) {
11+ return &debug.BuildInfo{Main: debug.Module{Version: mv}, Settings: settings}, true
12+ }
13+ }
14+ rev := debug.BuildSetting{Key: "vcs.revision", Value: "0123456789abcdef0123"}
15+ tests := []struct {
16+ name, v, c string
17+ read func() (*debug.BuildInfo, bool)
18+ wantV string
19+ wantC string
20+ }{
21+ {"ldflags win", "v0.2.0", "abc", info("v0.1.0", rev), "v0.2.0", "abc"},
22+ {"go install", "dev", "unknown", info("v0.1.0"), "v0.1.0", "unknown"},
23+ {"devel with vcs", "dev", "unknown", info("(devel)", rev), "dev", "0123456789ab"},
24+ {"no info", "dev", "unknown", func() (*debug.BuildInfo, bool) { return nil, false }, "dev", "unknown"},
25+ }
26+ for _, tt := range tests {
27+ v, c := resolveVersion(tt.v, tt.c, tt.read)
28+ if v != tt.wantV || c != tt.wantC {
29+ t.Errorf("%s: got %s %s, want %s %s", tt.name, v, c, tt.wantV, tt.wantC)
30+ }
31+ }
32+}
A cmd/status.go +64 -0
@@ -0,0 +1,64 @@
1+package cmd
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "io"
7+ "os"
8+ "strings"
9+
10+ "github.com/spf13/cobra"
11+
12+ "github.com/bnema/forever-db/internal/export"
13+ "github.com/bnema/forever-db/internal/install"
14+)
15+
16+var statusJSON bool
17+
18+var statusCmd = &cobra.Command{
19+ Use: "status",
20+ Short: "Show whether the last export matches the installed client",
21+ Args: cobra.NoArgs,
22+ RunE: func(cmd *cobra.Command, args []string) error {
23+ dir, err := resolveDir(dirFlag, os.Getenv)
24+ if err != nil {
25+ return err
26+ }
27+ out, err := resolveOut(outFlag, os.Getenv)
28+ if err != nil {
29+ return err
30+ }
31+ inst, err := install.Detect(dir)
32+ if err != nil {
33+ return err
34+ }
35+ r, err := export.Status(inst, out)
36+ if err != nil {
37+ return err
38+ }
39+ return printStatus(cmd.OutOrStdout(), r, statusJSON)
40+ },
41+}
42+
43+func printStatus(w io.Writer, r *export.StatusReport, asJSON bool) error {
44+ if asJSON {
45+ enc := json.NewEncoder(w)
46+ enc.SetIndent("", " ")
47+ return enc.Encode(r)
48+ }
49+ var err error
50+ switch r.State {
51+ case export.StateNeverExported:
52+ _, err = fmt.Fprintln(w, "never exported")
53+ case export.StateUpToDate:
54+ _, err = fmt.Fprintf(w, "up to date (%s)\n", r.InstalledVersion)
55+ default:
56+ _, err = fmt.Fprintf(w, "stale: %s (installed %s, exported %s)\n", strings.Join(r.Reasons, ", "), r.InstalledVersion, r.ExportedVersion)
57+ }
58+ return err
59+}
60+
61+func init() {
62+ statusCmd.Flags().BoolVar(&statusJSON, "json", false, "print the report as JSON")
63+ rootCmd.AddCommand(statusCmd)
64+}
@@ -0,0 +1,64 @@
1+package cmd
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "io"
7+ "os"
8+ "strings"
9+
10+ "github.com/spf13/cobra"
11+
12+ "github.com/bnema/forever-db/internal/export"
13+ "github.com/bnema/forever-db/internal/install"
14+)
15+
16+var statusJSON bool
17+
18+var statusCmd = &cobra.Command{
19+ Use: "status",
20+ Short: "Show whether the last export matches the installed client",
21+ Args: cobra.NoArgs,
22+ RunE: func(cmd *cobra.Command, args []string) error {
23+ dir, err := resolveDir(dirFlag, os.Getenv)
24+ if err != nil {
25+ return err
26+ }
27+ out, err := resolveOut(outFlag, os.Getenv)
28+ if err != nil {
29+ return err
30+ }
31+ inst, err := install.Detect(dir)
32+ if err != nil {
33+ return err
34+ }
35+ r, err := export.Status(inst, out)
36+ if err != nil {
37+ return err
38+ }
39+ return printStatus(cmd.OutOrStdout(), r, statusJSON)
40+ },
41+}
42+
43+func printStatus(w io.Writer, r *export.StatusReport, asJSON bool) error {
44+ if asJSON {
45+ enc := json.NewEncoder(w)
46+ enc.SetIndent("", " ")
47+ return enc.Encode(r)
48+ }
49+ var err error
50+ switch r.State {
51+ case export.StateNeverExported:
52+ _, err = fmt.Fprintln(w, "never exported")
53+ case export.StateUpToDate:
54+ _, err = fmt.Fprintf(w, "up to date (%s)\n", r.InstalledVersion)
55+ default:
56+ _, err = fmt.Fprintf(w, "stale: %s (installed %s, exported %s)\n", strings.Join(r.Reasons, ", "), r.InstalledVersion, r.ExportedVersion)
57+ }
58+ return err
59+}
60+
61+func init() {
62+ statusCmd.Flags().BoolVar(&statusJSON, "json", false, "print the report as JSON")
63+ rootCmd.AddCommand(statusCmd)
64+}
A cmd/status_test.go +32 -0
@@ -0,0 +1,32 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "strings"
6+ "testing"
7+
8+ "github.com/bnema/forever-db/internal/export"
9+)
10+
11+func TestPrintStatus(t *testing.T) {
12+ tests := []struct {
13+ r export.StatusReport
14+ want string
15+ }{
16+ {export.StatusReport{State: export.StateNeverExported}, "never exported\n"},
17+ {export.StatusReport{State: export.StateUpToDate, InstalledVersion: "1.60.1.71037"}, "up to date (1.60.1.71037)\n"},
18+ {export.StatusReport{State: export.StateStale, Reasons: []string{"hotfixes_changed"}, InstalledVersion: "1.60.1.71037", ExportedVersion: "1.60.1.71037"},
19+ "stale: hotfixes_changed (installed 1.60.1.71037, exported 1.60.1.71037)\n"},
20+ }
21+ for _, tt := range tests {
22+ var b bytes.Buffer
23+ if err := printStatus(&b, &tt.r, false); err != nil || b.String() != tt.want {
24+ t.Errorf("got %q, %v", b.String(), err)
25+ }
26+ }
27+ var b bytes.Buffer
28+ printStatus(&b, &export.StatusReport{State: export.StateNeverExported, Reasons: []string{}}, true)
29+ if !strings.Contains(b.String(), `"reasons": []`) {
30+ t.Fatalf("json = %s", b.String())
31+ }
32+}
@@ -0,0 +1,32 @@
1+package cmd
2+
3+import (
4+ "bytes"
5+ "strings"
6+ "testing"
7+
8+ "github.com/bnema/forever-db/internal/export"
9+)
10+
11+func TestPrintStatus(t *testing.T) {
12+ tests := []struct {
13+ r export.StatusReport
14+ want string
15+ }{
16+ {export.StatusReport{State: export.StateNeverExported}, "never exported\n"},
17+ {export.StatusReport{State: export.StateUpToDate, InstalledVersion: "1.60.1.71037"}, "up to date (1.60.1.71037)\n"},
18+ {export.StatusReport{State: export.StateStale, Reasons: []string{"hotfixes_changed"}, InstalledVersion: "1.60.1.71037", ExportedVersion: "1.60.1.71037"},
19+ "stale: hotfixes_changed (installed 1.60.1.71037, exported 1.60.1.71037)\n"},
20+ }
21+ for _, tt := range tests {
22+ var b bytes.Buffer
23+ if err := printStatus(&b, &tt.r, false); err != nil || b.String() != tt.want {
24+ t.Errorf("got %q, %v", b.String(), err)
25+ }
26+ }
27+ var b bytes.Buffer
28+ printStatus(&b, &export.StatusReport{State: export.StateNeverExported, Reasons: []string{}}, true)
29+ if !strings.Contains(b.String(), `"reasons": []`) {
30+ t.Fatalf("json = %s", b.String())
31+ }
32+}
A go.mod +22 -0
@@ -0,0 +1,22 @@
1+module github.com/bnema/forever-db
2+
3+go 1.26.0
4+
5+require (
6+ github.com/spf13/cobra v1.10.2
7+ modernc.org/sqlite v1.62.0
8+)
9+
10+require (
11+ github.com/dustin/go-humanize v1.1.0 // indirect
12+ github.com/google/uuid v1.6.0 // indirect
13+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
14+ github.com/mattn/go-isatty v0.0.24 // indirect
15+ github.com/ncruces/go-strftime v1.1.0 // indirect
16+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
17+ github.com/spf13/pflag v1.0.9 // indirect
18+ golang.org/x/sys v0.49.0 // indirect
19+ modernc.org/libc v1.80.1 // indirect
20+ modernc.org/mathutil v1.7.1 // indirect
21+ modernc.org/memory v1.12.1 // indirect
22+)
@@ -0,0 +1,22 @@
1+module github.com/bnema/forever-db
2+
3+go 1.26.0
4+
5+require (
6+ github.com/spf13/cobra v1.10.2
7+ modernc.org/sqlite v1.62.0
8+)
9+
10+require (
11+ github.com/dustin/go-humanize v1.1.0 // indirect
12+ github.com/google/uuid v1.6.0 // indirect
13+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
14+ github.com/mattn/go-isatty v0.0.24 // indirect
15+ github.com/ncruces/go-strftime v1.1.0 // indirect
16+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
17+ github.com/spf13/pflag v1.0.9 // indirect
18+ golang.org/x/sys v0.49.0 // indirect
19+ modernc.org/libc v1.80.1 // indirect
20+ modernc.org/mathutil v1.7.1 // indirect
21+ modernc.org/memory v1.12.1 // indirect
22+)
A go.sum +60 -0 generated file: collapsed
A internal/blte/blte.go +232 -0
@@ -0,0 +1,232 @@
1+// Package blte decodes BLTE containers (modes N, Z and Salsa20 E).
2+package blte
3+
4+import (
5+ "bytes"
6+ "compress/zlib"
7+ "encoding/binary"
8+ "errors"
9+ "fmt"
10+ "io"
11+ "slices"
12+
13+ "github.com/bnema/forever-db/internal/db2"
14+ "github.com/bnema/forever-db/internal/salsa20"
15+)
16+
17+// Size bounds applied to values read from untrusted BLTE headers.
18+const (
19+ MaxBlockSize = 256 << 20
20+ MaxTotalSize = 1 << 30
21+ maxPrealloc = 64 << 20
22+ tableEntrySize = 24
23+)
24+
25+// Stats reports decode side effects.
26+type Stats struct {
27+ // MissingKeys counts zero-filled encrypted blocks per key name.
28+ MissingKeys map[uint64]int
29+}
30+
31+type block struct {
32+ comp, logical int // logical -1: unknown (headerless)
33+}
34+
35+// Decode decodes a BLTE buffer. keys may be nil.
36+func Decode(buf []byte, keys db2.KeyRing) ([]byte, Stats, error) {
37+ var st Stats
38+ if len(buf) < 8 || string(buf[:4]) != "BLTE" {
39+ return nil, st, fmt.Errorf("blte: bad magic")
40+ }
41+ hsize := int64(binary.BigEndian.Uint32(buf[4:8]))
42+ if hsize == 0 {
43+ return decodeBlocks(buf, 8, []block{{comp: len(buf) - 8, logical: -1}}, keys, nil, &st)
44+ }
45+ if hsize < 12 || hsize > int64(len(buf)) {
46+ return nil, st, fmt.Errorf("blte: invalid header size %d", hsize)
47+ }
48+ if buf[8] != 0x0F {
49+ return nil, st, fmt.Errorf("blte: unsupported table format 0x%02X", buf[8])
50+ }
51+ n := int(buf[9])<<16 | int(buf[10])<<8 | int(buf[11])
52+ if n == 0 {
53+ return nil, st, fmt.Errorf("blte: empty block table")
54+ }
55+ if 12+int64(n)*tableEntrySize > hsize {
56+ return nil, st, fmt.Errorf("blte: block table exceeds header size")
57+ }
58+ total := 0
59+ blocks := make([]block, n)
60+ for i := range blocks {
61+ e := buf[12+i*tableEntrySize:]
62+ comp := binary.BigEndian.Uint32(e[0:])
63+ logical := binary.BigEndian.Uint32(e[4:])
64+ if logical > MaxBlockSize {
65+ return nil, st, fmt.Errorf("blte: block %d: logical size %d exceeds limit", i, logical)
66+ }
67+ total += int(logical)
68+ if total > MaxTotalSize {
69+ return nil, st, fmt.Errorf("blte: total logical size exceeds limit")
70+ }
71+ if int64(comp) > int64(len(buf)) {
72+ return nil, st, fmt.Errorf("blte: block %d: truncated", i)
73+ }
74+ blocks[i] = block{int(comp), int(logical)}
75+ }
76+ out := make([]byte, 0, min(total, maxPrealloc))
77+ return decodeBlocks(buf, int(hsize), blocks, keys, out, &st)
78+}
79+
80+func decodeBlocks(buf []byte, pos int, blocks []block, keys db2.KeyRing, out []byte, st *Stats) ([]byte, Stats, error) {
81+ var zr io.ReadCloser
82+ for i, b := range blocks {
83+ if b.comp < 1 || pos+b.comp > len(buf) {
84+ return nil, *st, fmt.Errorf("blte: block %d: truncated", i)
85+ }
86+ blk := buf[pos : pos+b.comp]
87+ pos += b.comp
88+ before := len(out)
89+ var err error
90+ out, err = decodeBlock(blk, i, b.logical, keys, out, st, &zr)
91+ if err != nil {
92+ return nil, *st, fmt.Errorf("blte: block %d: %w", i, err)
93+ }
94+ if b.logical >= 0 && len(out)-before != b.logical {
95+ return nil, *st, fmt.Errorf("blte: block %d: decoded %d bytes, want %d", i, len(out)-before, b.logical)
96+ }
97+ }
98+ return out, *st, nil
99+}
100+
101+func decodeBlock(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *Stats, zr *io.ReadCloser) ([]byte, error) {
102+ switch blk[0] {
103+ case 'N':
104+ return appendRaw(out, blk[1:])
105+ case 'Z':
106+ return inflate(blk[1:], out, logical, zr)
107+ case 'E':
108+ return decrypt(blk, index, logical, keys, out, st, zr)
109+ }
110+ return nil, fmt.Errorf("unsupported mode %q", blk[0])
111+}
112+
113+func appendRaw(out, data []byte) ([]byte, error) {
114+ if len(out)+len(data) > MaxTotalSize {
115+ return nil, errors.New("output exceeds size limit")
116+ }
117+ return append(out, data...), nil
118+}
119+
120+func newZlib(src []byte, zr *io.ReadCloser) (io.Reader, error) {
121+ if *zr != nil {
122+ if err := (*zr).(zlib.Resetter).Reset(bytes.NewReader(src), nil); err != nil {
123+ return nil, fmt.Errorf("zlib: %w", err)
124+ }
125+ return *zr, nil
126+ }
127+ r, err := zlib.NewReader(bytes.NewReader(src))
128+ if err != nil {
129+ return nil, fmt.Errorf("zlib: %w", err)
130+ }
131+ *zr = r
132+ return r, nil
133+}
134+
135+// inflate appends the zlib stream src to out. With logical >= 0 it decodes
136+// exactly logical bytes and requires the stream to end there.
137+func inflate(src, out []byte, logical int, zr *io.ReadCloser) ([]byte, error) {
138+ r, err := newZlib(src, zr)
139+ if err != nil {
140+ return nil, err
141+ }
142+ start := len(out)
143+ if logical >= 0 {
144+ out = slices.Grow(out, logical)[:start+logical]
145+ if _, err := io.ReadFull(r, out[start:]); err != nil {
146+ return nil, fmt.Errorf("zlib: %w", err)
147+ }
148+ var one [1]byte
149+ for {
150+ n, err := r.Read(one[:])
151+ if n > 0 {
152+ return nil, errors.New("zlib: data exceeds logical size")
153+ }
154+ if err == io.EOF {
155+ return out, nil
156+ }
157+ if err != nil {
158+ return nil, fmt.Errorf("zlib: %w", err)
159+ }
160+ }
161+ }
162+ limit := MaxTotalSize - start
163+ var chunk [32 << 10]byte
164+ for {
165+ n, err := r.Read(chunk[:])
166+ if n > 0 {
167+ if len(out)-start+n > limit {
168+ return nil, errors.New("zlib: output exceeds size limit")
169+ }
170+ out = append(out, chunk[:n]...)
171+ }
172+ if err == io.EOF {
173+ return out, nil
174+ }
175+ if err != nil {
176+ return nil, fmt.Errorf("zlib: %w", err)
177+ }
178+ }
179+}
180+
181+func decrypt(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *Stats, zr *io.ReadCloser) ([]byte, error) {
182+ if len(blk) < 2 || blk[1] != 8 {
183+ return nil, fmt.Errorf("encrypted: bad key name length")
184+ }
185+ if len(blk) < 11 {
186+ return nil, fmt.Errorf("encrypted: truncated")
187+ }
188+ name := binary.LittleEndian.Uint64(blk[2:10])
189+ ivLen := int(blk[10])
190+ if ivLen != 4 && ivLen != 8 {
191+ return nil, fmt.Errorf("encrypted: bad IV length %d", ivLen)
192+ }
193+ if len(blk) < 12+ivLen {
194+ return nil, fmt.Errorf("encrypted: truncated IV")
195+ }
196+ var iv [8]byte
197+ copy(iv[:], blk[11:11+ivLen])
198+ for i := range 4 {
199+ iv[i] ^= byte(index >> (8 * i))
200+ }
201+ if t := blk[11+ivLen]; t != 'S' {
202+ return nil, fmt.Errorf("encrypted: unsupported type %q", t)
203+ }
204+ ct := blk[12+ivLen:]
205+ var key [16]byte
206+ ok := false
207+ if keys != nil {
208+ key, ok = keys.Key(name)
209+ }
210+ if !ok {
211+ if logical < 0 {
212+ return nil, fmt.Errorf("encrypted: missing key %016X in headerless BLTE", name)
213+ }
214+ if st.MissingKeys == nil {
215+ st.MissingKeys = make(map[uint64]int)
216+ }
217+ st.MissingKeys[name]++
218+ return append(out, make([]byte, logical)...), nil
219+ }
220+ if len(ct) == 0 {
221+ return nil, fmt.Errorf("encrypted: empty payload")
222+ }
223+ plain := make([]byte, len(ct))
224+ salsa20.XORKeyStream(plain, ct, &iv, &key)
225+ switch plain[0] {
226+ case 'N':
227+ return appendRaw(out, plain[1:])
228+ case 'Z':
229+ return inflate(plain[1:], out, logical, zr)
230+ }
231+ return nil, fmt.Errorf("encrypted: unsupported inner mode %q", plain[0])
232+}
@@ -0,0 +1,232 @@
1+// Package blte decodes BLTE containers (modes N, Z and Salsa20 E).
2+package blte
3+
4+import (
5+ "bytes"
6+ "compress/zlib"
7+ "encoding/binary"
8+ "errors"
9+ "fmt"
10+ "io"
11+ "slices"
12+
13+ "github.com/bnema/forever-db/internal/db2"
14+ "github.com/bnema/forever-db/internal/salsa20"
15+)
16+
17+// Size bounds applied to values read from untrusted BLTE headers.
18+const (
19+ MaxBlockSize = 256 << 20
20+ MaxTotalSize = 1 << 30
21+ maxPrealloc = 64 << 20
22+ tableEntrySize = 24
23+)
24+
25+// Stats reports decode side effects.
26+type Stats struct {
27+ // MissingKeys counts zero-filled encrypted blocks per key name.
28+ MissingKeys map[uint64]int
29+}
30+
31+type block struct {
32+ comp, logical int // logical -1: unknown (headerless)
33+}
34+
35+// Decode decodes a BLTE buffer. keys may be nil.
36+func Decode(buf []byte, keys db2.KeyRing) ([]byte, Stats, error) {
37+ var st Stats
38+ if len(buf) < 8 || string(buf[:4]) != "BLTE" {
39+ return nil, st, fmt.Errorf("blte: bad magic")
40+ }
41+ hsize := int64(binary.BigEndian.Uint32(buf[4:8]))
42+ if hsize == 0 {
43+ return decodeBlocks(buf, 8, []block{{comp: len(buf) - 8, logical: -1}}, keys, nil, &st)
44+ }
45+ if hsize < 12 || hsize > int64(len(buf)) {
46+ return nil, st, fmt.Errorf("blte: invalid header size %d", hsize)
47+ }
48+ if buf[8] != 0x0F {
49+ return nil, st, fmt.Errorf("blte: unsupported table format 0x%02X", buf[8])
50+ }
51+ n := int(buf[9])<<16 | int(buf[10])<<8 | int(buf[11])
52+ if n == 0 {
53+ return nil, st, fmt.Errorf("blte: empty block table")
54+ }
55+ if 12+int64(n)*tableEntrySize > hsize {
56+ return nil, st, fmt.Errorf("blte: block table exceeds header size")
57+ }
58+ total := 0
59+ blocks := make([]block, n)
60+ for i := range blocks {
61+ e := buf[12+i*tableEntrySize:]
62+ comp := binary.BigEndian.Uint32(e[0:])
63+ logical := binary.BigEndian.Uint32(e[4:])
64+ if logical > MaxBlockSize {
65+ return nil, st, fmt.Errorf("blte: block %d: logical size %d exceeds limit", i, logical)
66+ }
67+ total += int(logical)
68+ if total > MaxTotalSize {
69+ return nil, st, fmt.Errorf("blte: total logical size exceeds limit")
70+ }
71+ if int64(comp) > int64(len(buf)) {
72+ return nil, st, fmt.Errorf("blte: block %d: truncated", i)
73+ }
74+ blocks[i] = block{int(comp), int(logical)}
75+ }
76+ out := make([]byte, 0, min(total, maxPrealloc))
77+ return decodeBlocks(buf, int(hsize), blocks, keys, out, &st)
78+}
79+
80+func decodeBlocks(buf []byte, pos int, blocks []block, keys db2.KeyRing, out []byte, st *Stats) ([]byte, Stats, error) {
81+ var zr io.ReadCloser
82+ for i, b := range blocks {
83+ if b.comp < 1 || pos+b.comp > len(buf) {
84+ return nil, *st, fmt.Errorf("blte: block %d: truncated", i)
85+ }
86+ blk := buf[pos : pos+b.comp]
87+ pos += b.comp
88+ before := len(out)
89+ var err error
90+ out, err = decodeBlock(blk, i, b.logical, keys, out, st, &zr)
91+ if err != nil {
92+ return nil, *st, fmt.Errorf("blte: block %d: %w", i, err)
93+ }
94+ if b.logical >= 0 && len(out)-before != b.logical {
95+ return nil, *st, fmt.Errorf("blte: block %d: decoded %d bytes, want %d", i, len(out)-before, b.logical)
96+ }
97+ }
98+ return out, *st, nil
99+}
100+
101+func decodeBlock(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *Stats, zr *io.ReadCloser) ([]byte, error) {
102+ switch blk[0] {
103+ case 'N':
104+ return appendRaw(out, blk[1:])
105+ case 'Z':
106+ return inflate(blk[1:], out, logical, zr)
107+ case 'E':
108+ return decrypt(blk, index, logical, keys, out, st, zr)
109+ }
110+ return nil, fmt.Errorf("unsupported mode %q", blk[0])
111+}
112+
113+func appendRaw(out, data []byte) ([]byte, error) {
114+ if len(out)+len(data) > MaxTotalSize {
115+ return nil, errors.New("output exceeds size limit")
116+ }
117+ return append(out, data...), nil
118+}
119+
120+func newZlib(src []byte, zr *io.ReadCloser) (io.Reader, error) {
121+ if *zr != nil {
122+ if err := (*zr).(zlib.Resetter).Reset(bytes.NewReader(src), nil); err != nil {
123+ return nil, fmt.Errorf("zlib: %w", err)
124+ }
125+ return *zr, nil
126+ }
127+ r, err := zlib.NewReader(bytes.NewReader(src))
128+ if err != nil {
129+ return nil, fmt.Errorf("zlib: %w", err)
130+ }
131+ *zr = r
132+ return r, nil
133+}
134+
135+// inflate appends the zlib stream src to out. With logical >= 0 it decodes
136+// exactly logical bytes and requires the stream to end there.
137+func inflate(src, out []byte, logical int, zr *io.ReadCloser) ([]byte, error) {
138+ r, err := newZlib(src, zr)
139+ if err != nil {
140+ return nil, err
141+ }
142+ start := len(out)
143+ if logical >= 0 {
144+ out = slices.Grow(out, logical)[:start+logical]
145+ if _, err := io.ReadFull(r, out[start:]); err != nil {
146+ return nil, fmt.Errorf("zlib: %w", err)
147+ }
148+ var one [1]byte
149+ for {
150+ n, err := r.Read(one[:])
151+ if n > 0 {
152+ return nil, errors.New("zlib: data exceeds logical size")
153+ }
154+ if err == io.EOF {
155+ return out, nil
156+ }
157+ if err != nil {
158+ return nil, fmt.Errorf("zlib: %w", err)
159+ }
160+ }
161+ }
162+ limit := MaxTotalSize - start
163+ var chunk [32 << 10]byte
164+ for {
165+ n, err := r.Read(chunk[:])
166+ if n > 0 {
167+ if len(out)-start+n > limit {
168+ return nil, errors.New("zlib: output exceeds size limit")
169+ }
170+ out = append(out, chunk[:n]...)
171+ }
172+ if err == io.EOF {
173+ return out, nil
174+ }
175+ if err != nil {
176+ return nil, fmt.Errorf("zlib: %w", err)
177+ }
178+ }
179+}
180+
181+func decrypt(blk []byte, index, logical int, keys db2.KeyRing, out []byte, st *Stats, zr *io.ReadCloser) ([]byte, error) {
182+ if len(blk) < 2 || blk[1] != 8 {
183+ return nil, fmt.Errorf("encrypted: bad key name length")
184+ }
185+ if len(blk) < 11 {
186+ return nil, fmt.Errorf("encrypted: truncated")
187+ }
188+ name := binary.LittleEndian.Uint64(blk[2:10])
189+ ivLen := int(blk[10])
190+ if ivLen != 4 && ivLen != 8 {
191+ return nil, fmt.Errorf("encrypted: bad IV length %d", ivLen)
192+ }
193+ if len(blk) < 12+ivLen {
194+ return nil, fmt.Errorf("encrypted: truncated IV")
195+ }
196+ var iv [8]byte
197+ copy(iv[:], blk[11:11+ivLen])
198+ for i := range 4 {
199+ iv[i] ^= byte(index >> (8 * i))
200+ }
201+ if t := blk[11+ivLen]; t != 'S' {
202+ return nil, fmt.Errorf("encrypted: unsupported type %q", t)
203+ }
204+ ct := blk[12+ivLen:]
205+ var key [16]byte
206+ ok := false
207+ if keys != nil {
208+ key, ok = keys.Key(name)
209+ }
210+ if !ok {
211+ if logical < 0 {
212+ return nil, fmt.Errorf("encrypted: missing key %016X in headerless BLTE", name)
213+ }
214+ if st.MissingKeys == nil {
215+ st.MissingKeys = make(map[uint64]int)
216+ }
217+ st.MissingKeys[name]++
218+ return append(out, make([]byte, logical)...), nil
219+ }
220+ if len(ct) == 0 {
221+ return nil, fmt.Errorf("encrypted: empty payload")
222+ }
223+ plain := make([]byte, len(ct))
224+ salsa20.XORKeyStream(plain, ct, &iv, &key)
225+ switch plain[0] {
226+ case 'N':
227+ return appendRaw(out, plain[1:])
228+ case 'Z':
229+ return inflate(plain[1:], out, logical, zr)
230+ }
231+ return nil, fmt.Errorf("encrypted: unsupported inner mode %q", plain[0])
232+}
A internal/blte/blte_test.go +183 -0
@@ -0,0 +1,183 @@
1+package blte
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "encoding/hex"
7+ "fmt"
8+ "strings"
9+ "testing"
10+
11+ "github.com/bnema/forever-db/internal/tactkeys"
12+ "github.com/bnema/forever-db/internal/testutil"
13+)
14+
15+func TestHeaderlessN(t *testing.T) {
16+ out, _, err := Decode(testutil.BLTERaw([]byte("hello")), nil)
17+ if err != nil || string(out) != "hello" {
18+ t.Fatalf("got %q, %v", out, err)
19+ }
20+}
21+
22+func TestMultiBlockNZ(t *testing.T) {
23+ z := bytes.Repeat([]byte("abc"), 100)
24+ buf := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("head")}, testutil.BLTEBlock{Mode: 'Z', Data: z})
25+ out, st, err := Decode(buf, nil)
26+ if err != nil || !bytes.Equal(out, append([]byte("head"), z...)) || st.MissingKeys != nil {
27+ t.Fatalf("got %q, %+v, %v", out, st, err)
28+ }
29+}
30+
31+func TestEncryptedKnownKey(t *testing.T) {
32+ key := [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
33+ ring := tactkeys.New()
34+ ring.Add(0xAABBCCDD11223344, key)
35+ buf := testutil.BLTE(
36+ testutil.BLTEBlock{Mode: 'N', Data: []byte("x")},
37+ testutil.BLTEBlock{Mode: 'E', Data: []byte("secret data"), KeyName: 0xAABBCCDD11223344, Key: key, IV: []byte{9, 8, 7, 6}},
38+ )
39+ out, st, err := Decode(buf, ring)
40+ if err != nil || string(out) != "xsecret data" || st.MissingKeys != nil {
41+ t.Fatalf("got %q, %+v, %v", out, st, err)
42+ }
43+}
44+
45+func TestEncryptedMissingKey(t *testing.T) {
46+ buf := testutil.BLTE(
47+ testutil.BLTEBlock{Mode: 'E', Data: []byte("12345"), KeyName: 7},
48+ testutil.BLTEBlock{Mode: 'N', Data: []byte("ok")},
49+ )
50+ out, st, err := Decode(buf, tactkeys.New())
51+ if err != nil || !bytes.Equal(out, []byte("\x00\x00\x00\x00\x00ok")) || st.MissingKeys[7] != 1 {
52+ t.Fatalf("got %q, %+v, %v", out, st, err)
53+ }
54+}
55+
56+func TestErrors(t *testing.T) {
57+ good := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("abcd")})
58+ badFmt := bytes.Clone(good)
59+ badFmt[8] = 0x10
60+ badMode := bytes.Clone(good)
61+ badMode[len(badMode)-5] = 'X'
62+ mismatch := bytes.Clone(good)
63+ binary.BigEndian.PutUint32(mismatch[16:], 9)
64+ tests := map[string]struct {
65+ buf []byte
66+ want string
67+ }{
68+ "table format": {badFmt, "table format"},
69+ "unknown mode": {badMode, "block 0: unsupported mode"},
70+ "truncated": {good[:len(good)-2], "block 0: truncated"},
71+ "size": {mismatch, "block 0: decoded 4 bytes, want 9"},
72+ "magic": {[]byte("XXXX0000"), "bad magic"},
73+ }
74+ for name, tt := range tests {
75+ t.Run(name, func(t *testing.T) {
76+ _, _, err := Decode(tt.buf, nil)
77+ if err == nil || !strings.Contains(err.Error(), tt.want) {
78+ t.Fatalf("err = %v", err)
79+ }
80+ })
81+ }
82+}
83+
84+// TestIndependentVector uses an E block computed outside this code base:
85+// block index 258, key bytes 0..15, key name 0x0123456789ABCDEF, IV a1b2c3d4.
86+func TestIndependentVector(t *testing.T) {
87+ eblk, _ := hex.DecodeString("4508efcdab896745230104a1b2c3d453078d9c78bcba70789d890d3c6bdf")
88+ var blocks [][]byte
89+ var logical []int
90+ for range 258 {
91+ blocks = append(blocks, []byte("Nx"))
92+ logical = append(logical, 1)
93+ }
94+ blocks = append(blocks, eblk)
95+ logical = append(logical, len("hello forever"))
96+ var key [16]byte
97+ for i := range key {
98+ key[i] = byte(i)
99+ }
100+ ring := tactkeys.New()
101+ ring.Add(0x0123456789ABCDEF, key)
102+ out, _, err := Decode(testutil.BLTETable(blocks, logical), ring)
103+ if err != nil {
104+ t.Fatal(err)
105+ }
106+ if got := string(out[258:]); got != "hello forever" || len(out) != 258+13 {
107+ t.Fatalf("got %q", got)
108+ }
109+}
110+
111+func TestEncryptedVariants(t *testing.T) {
112+ key := [16]byte{0xAA, 1, 2}
113+ ring := tactkeys.New()
114+ ring.Add(5, key)
115+ data := bytes.Repeat([]byte("zz"), 500)
116+ buf := testutil.BLTE(
117+ testutil.BLTEBlock{Mode: 'E', Data: []byte("iv8"), KeyName: 5, Key: key, IV: []byte{1, 2, 3, 4, 5, 6, 7, 8}},
118+ testutil.BLTEBlock{Mode: 'E', Data: data, KeyName: 5, Key: key, Inner: 'Z'},
119+ )
120+ out, _, err := Decode(buf, ring)
121+ if err != nil || !bytes.Equal(out, append([]byte("iv8"), data...)) {
122+ t.Fatalf("got %d bytes, %v", len(out), err)
123+ }
124+}
125+
126+func TestMalformed(t *testing.T) {
127+ eHdr := func(b []byte) []byte { return testutil.BLTETable([][]byte{b}, []int{4}) }
128+ typeA := []byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 4, 0, 0, 0, 0, 'A', 1, 2, 3}
129+ bigLogical := testutil.BLTETable([][]byte{[]byte("Nabcd")}, []int{MaxBlockSize + 1})
130+ var many [][]byte
131+ var manyLog []int
132+ for range 5 {
133+ many = append(many, []byte("Na"))
134+ manyLog = append(manyLog, MaxBlockSize)
135+ }
136+ zExtra := testutil.BLTE(testutil.BLTEBlock{Mode: 'Z', Data: []byte("abcdef")})
137+ binary.BigEndian.PutUint32(zExtra[16:], 3)
138+ tests := map[string]struct {
139+ buf []byte
140+ want string
141+ }{
142+ "type A": {eHdr(typeA), "unsupported type 'A'"},
143+ "key len": {eHdr([]byte{'E', 4, 1, 2, 3, 4}), "bad key name length"},
144+ "truncated iv": {eHdr([]byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 8, 1, 2}), "truncated IV"},
145+ "iv len": {eHdr([]byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 5, 1, 2, 3, 4, 5, 'S'}), "bad IV length"},
146+ "zero blocks": {testutil.BLTETable(nil, nil), "empty block table"},
147+ "logical": {bigLogical, "exceeds limit"},
148+ "total": {testutil.BLTETable(many, manyLog), "total logical size exceeds limit"},
149+ "z extra": {zExtra, "exceeds logical size"},
150+ }
151+ for h := 1; h <= 11; h++ {
152+ b := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("abcd")})
153+ binary.BigEndian.PutUint32(b[4:], uint32(h))
154+ tests[fmt.Sprintf("hsize %d", h)] = struct {
155+ buf []byte
156+ want string
157+ }{b, "invalid header size"}
158+ }
159+ for name, tt := range tests {
160+ t.Run(name, func(t *testing.T) {
161+ _, _, err := Decode(tt.buf, tactkeys.New())
162+ if err == nil || !strings.Contains(err.Error(), tt.want) {
163+ t.Fatalf("err = %v", err)
164+ }
165+ })
166+ }
167+}
168+
169+func FuzzDecode(f *testing.F) {
170+ key := [16]byte{1}
171+ f.Add(testutil.BLTERaw([]byte("hello")))
172+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("head")}, testutil.BLTEBlock{Mode: 'Z', Data: []byte("zzzzzz")}))
173+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'E', Data: []byte("enc"), KeyName: 1, Key: key}))
174+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'E', Data: []byte("encz"), KeyName: 2, Key: key, Inner: 'Z'}))
175+ ring := tactkeys.New()
176+ ring.Add(1, key)
177+ f.Fuzz(func(t *testing.T, buf []byte) {
178+ out, _, err := Decode(buf, ring)
179+ if err == nil && len(out) > MaxTotalSize {
180+ t.Fatalf("output %d exceeds limit", len(out))
181+ }
182+ })
183+}
@@ -0,0 +1,183 @@
1+package blte
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "encoding/hex"
7+ "fmt"
8+ "strings"
9+ "testing"
10+
11+ "github.com/bnema/forever-db/internal/tactkeys"
12+ "github.com/bnema/forever-db/internal/testutil"
13+)
14+
15+func TestHeaderlessN(t *testing.T) {
16+ out, _, err := Decode(testutil.BLTERaw([]byte("hello")), nil)
17+ if err != nil || string(out) != "hello" {
18+ t.Fatalf("got %q, %v", out, err)
19+ }
20+}
21+
22+func TestMultiBlockNZ(t *testing.T) {
23+ z := bytes.Repeat([]byte("abc"), 100)
24+ buf := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("head")}, testutil.BLTEBlock{Mode: 'Z', Data: z})
25+ out, st, err := Decode(buf, nil)
26+ if err != nil || !bytes.Equal(out, append([]byte("head"), z...)) || st.MissingKeys != nil {
27+ t.Fatalf("got %q, %+v, %v", out, st, err)
28+ }
29+}
30+
31+func TestEncryptedKnownKey(t *testing.T) {
32+ key := [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
33+ ring := tactkeys.New()
34+ ring.Add(0xAABBCCDD11223344, key)
35+ buf := testutil.BLTE(
36+ testutil.BLTEBlock{Mode: 'N', Data: []byte("x")},
37+ testutil.BLTEBlock{Mode: 'E', Data: []byte("secret data"), KeyName: 0xAABBCCDD11223344, Key: key, IV: []byte{9, 8, 7, 6}},
38+ )
39+ out, st, err := Decode(buf, ring)
40+ if err != nil || string(out) != "xsecret data" || st.MissingKeys != nil {
41+ t.Fatalf("got %q, %+v, %v", out, st, err)
42+ }
43+}
44+
45+func TestEncryptedMissingKey(t *testing.T) {
46+ buf := testutil.BLTE(
47+ testutil.BLTEBlock{Mode: 'E', Data: []byte("12345"), KeyName: 7},
48+ testutil.BLTEBlock{Mode: 'N', Data: []byte("ok")},
49+ )
50+ out, st, err := Decode(buf, tactkeys.New())
51+ if err != nil || !bytes.Equal(out, []byte("\x00\x00\x00\x00\x00ok")) || st.MissingKeys[7] != 1 {
52+ t.Fatalf("got %q, %+v, %v", out, st, err)
53+ }
54+}
55+
56+func TestErrors(t *testing.T) {
57+ good := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("abcd")})
58+ badFmt := bytes.Clone(good)
59+ badFmt[8] = 0x10
60+ badMode := bytes.Clone(good)
61+ badMode[len(badMode)-5] = 'X'
62+ mismatch := bytes.Clone(good)
63+ binary.BigEndian.PutUint32(mismatch[16:], 9)
64+ tests := map[string]struct {
65+ buf []byte
66+ want string
67+ }{
68+ "table format": {badFmt, "table format"},
69+ "unknown mode": {badMode, "block 0: unsupported mode"},
70+ "truncated": {good[:len(good)-2], "block 0: truncated"},
71+ "size": {mismatch, "block 0: decoded 4 bytes, want 9"},
72+ "magic": {[]byte("XXXX0000"), "bad magic"},
73+ }
74+ for name, tt := range tests {
75+ t.Run(name, func(t *testing.T) {
76+ _, _, err := Decode(tt.buf, nil)
77+ if err == nil || !strings.Contains(err.Error(), tt.want) {
78+ t.Fatalf("err = %v", err)
79+ }
80+ })
81+ }
82+}
83+
84+// TestIndependentVector uses an E block computed outside this code base:
85+// block index 258, key bytes 0..15, key name 0x0123456789ABCDEF, IV a1b2c3d4.
86+func TestIndependentVector(t *testing.T) {
87+ eblk, _ := hex.DecodeString("4508efcdab896745230104a1b2c3d453078d9c78bcba70789d890d3c6bdf")
88+ var blocks [][]byte
89+ var logical []int
90+ for range 258 {
91+ blocks = append(blocks, []byte("Nx"))
92+ logical = append(logical, 1)
93+ }
94+ blocks = append(blocks, eblk)
95+ logical = append(logical, len("hello forever"))
96+ var key [16]byte
97+ for i := range key {
98+ key[i] = byte(i)
99+ }
100+ ring := tactkeys.New()
101+ ring.Add(0x0123456789ABCDEF, key)
102+ out, _, err := Decode(testutil.BLTETable(blocks, logical), ring)
103+ if err != nil {
104+ t.Fatal(err)
105+ }
106+ if got := string(out[258:]); got != "hello forever" || len(out) != 258+13 {
107+ t.Fatalf("got %q", got)
108+ }
109+}
110+
111+func TestEncryptedVariants(t *testing.T) {
112+ key := [16]byte{0xAA, 1, 2}
113+ ring := tactkeys.New()
114+ ring.Add(5, key)
115+ data := bytes.Repeat([]byte("zz"), 500)
116+ buf := testutil.BLTE(
117+ testutil.BLTEBlock{Mode: 'E', Data: []byte("iv8"), KeyName: 5, Key: key, IV: []byte{1, 2, 3, 4, 5, 6, 7, 8}},
118+ testutil.BLTEBlock{Mode: 'E', Data: data, KeyName: 5, Key: key, Inner: 'Z'},
119+ )
120+ out, _, err := Decode(buf, ring)
121+ if err != nil || !bytes.Equal(out, append([]byte("iv8"), data...)) {
122+ t.Fatalf("got %d bytes, %v", len(out), err)
123+ }
124+}
125+
126+func TestMalformed(t *testing.T) {
127+ eHdr := func(b []byte) []byte { return testutil.BLTETable([][]byte{b}, []int{4}) }
128+ typeA := []byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 4, 0, 0, 0, 0, 'A', 1, 2, 3}
129+ bigLogical := testutil.BLTETable([][]byte{[]byte("Nabcd")}, []int{MaxBlockSize + 1})
130+ var many [][]byte
131+ var manyLog []int
132+ for range 5 {
133+ many = append(many, []byte("Na"))
134+ manyLog = append(manyLog, MaxBlockSize)
135+ }
136+ zExtra := testutil.BLTE(testutil.BLTEBlock{Mode: 'Z', Data: []byte("abcdef")})
137+ binary.BigEndian.PutUint32(zExtra[16:], 3)
138+ tests := map[string]struct {
139+ buf []byte
140+ want string
141+ }{
142+ "type A": {eHdr(typeA), "unsupported type 'A'"},
143+ "key len": {eHdr([]byte{'E', 4, 1, 2, 3, 4}), "bad key name length"},
144+ "truncated iv": {eHdr([]byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 8, 1, 2}), "truncated IV"},
145+ "iv len": {eHdr([]byte{'E', 8, 1, 2, 3, 4, 5, 6, 7, 8, 5, 1, 2, 3, 4, 5, 'S'}), "bad IV length"},
146+ "zero blocks": {testutil.BLTETable(nil, nil), "empty block table"},
147+ "logical": {bigLogical, "exceeds limit"},
148+ "total": {testutil.BLTETable(many, manyLog), "total logical size exceeds limit"},
149+ "z extra": {zExtra, "exceeds logical size"},
150+ }
151+ for h := 1; h <= 11; h++ {
152+ b := testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("abcd")})
153+ binary.BigEndian.PutUint32(b[4:], uint32(h))
154+ tests[fmt.Sprintf("hsize %d", h)] = struct {
155+ buf []byte
156+ want string
157+ }{b, "invalid header size"}
158+ }
159+ for name, tt := range tests {
160+ t.Run(name, func(t *testing.T) {
161+ _, _, err := Decode(tt.buf, tactkeys.New())
162+ if err == nil || !strings.Contains(err.Error(), tt.want) {
163+ t.Fatalf("err = %v", err)
164+ }
165+ })
166+ }
167+}
168+
169+func FuzzDecode(f *testing.F) {
170+ key := [16]byte{1}
171+ f.Add(testutil.BLTERaw([]byte("hello")))
172+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'N', Data: []byte("head")}, testutil.BLTEBlock{Mode: 'Z', Data: []byte("zzzzzz")}))
173+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'E', Data: []byte("enc"), KeyName: 1, Key: key}))
174+ f.Add(testutil.BLTE(testutil.BLTEBlock{Mode: 'E', Data: []byte("encz"), KeyName: 2, Key: key, Inner: 'Z'}))
175+ ring := tactkeys.New()
176+ ring.Add(1, key)
177+ f.Fuzz(func(t *testing.T, buf []byte) {
178+ out, _, err := Decode(buf, ring)
179+ if err == nil && len(out) > MaxTotalSize {
180+ t.Fatalf("output %d exceeds limit", len(out))
181+ }
182+ })
183+}
A internal/casc/archive.go +104 -0
@@ -0,0 +1,104 @@
1+package casc
2+
3+import (
4+ "errors"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+ "sync"
9+
10+ "github.com/bnema/forever-db/internal/blte"
11+ "github.com/bnema/forever-db/internal/db2"
12+)
13+
14+// ErrNotFound means an encoding key is not in the local indexes.
15+var ErrNotFound = errors.New("casc: key not found in local storage")
16+
17+const archiveHeaderSize = 30
18+
19+// archives reads BLTE payloads from data.NNN files.
20+type archives struct {
21+ dir string
22+ index *indexes
23+
24+ mu sync.Mutex
25+ files map[int]archiveFile
26+ closed bool
27+}
28+
29+type archiveFile struct {
30+ f *os.File
31+ size int64
32+}
33+
34+func newArchives(dataDir string, ix *indexes) *archives {
35+ return &archives{dir: dataDir, index: ix, files: make(map[int]archiveFile)}
36+}
37+
38+func (a *archives) file(n int) (archiveFile, error) {
39+ a.mu.Lock()
40+ defer a.mu.Unlock()
41+ if a.closed {
42+ return archiveFile{}, errors.New("casc: storage closed")
43+ }
44+ if af, ok := a.files[n]; ok {
45+ return af, nil
46+ }
47+ f, err := os.Open(filepath.Join(a.dir, fmt.Sprintf("data.%03d", n)))
48+ if err != nil {
49+ return archiveFile{}, fmt.Errorf("casc: %w", err)
50+ }
51+ fi, err := f.Stat()
52+ if err != nil {
53+ f.Close()
54+ return archiveFile{}, fmt.Errorf("casc: %w", err)
55+ }
56+ af := archiveFile{f: f, size: fi.Size()}
57+ a.files[n] = af
58+ return af, nil
59+}
60+
61+// readEKey reads and BLTE-decodes the file stored under ekey.
62+func (a *archives) readEKey(ekey []byte, keys db2.KeyRing) ([]byte, blte.Stats, error) {
63+ arc, off, size, ok := a.index.lookup(ekey)
64+ if !ok {
65+ return nil, blte.Stats{}, fmt.Errorf("%w: %x", ErrNotFound, ekey)
66+ }
67+ if size < archiveHeaderSize {
68+ return nil, blte.Stats{}, fmt.Errorf("casc: entry %x: size %d too small", ekey, size)
69+ }
70+ af, err := a.file(arc)
71+ if err != nil {
72+ return nil, blte.Stats{}, err
73+ }
74+ if int64(off)+int64(size) > af.size {
75+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d: entry %x at %d+%d exceeds file size %d", arc, ekey, off, size, af.size)
76+ }
77+ buf := make([]byte, size)
78+ if n, err := af.f.ReadAt(buf, int64(off)); n != len(buf) {
79+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d short read at %d (%d of %d bytes): %w", arc, off, n, size, err)
80+ }
81+ for i := range 9 {
82+ if buf[15-i] != ekey[i] {
83+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d at %d: header key mismatch for %x", arc, off, ekey)
84+ }
85+ }
86+ out, st, err := blte.Decode(buf[archiveHeaderSize:], keys)
87+ if err != nil {
88+ return nil, st, fmt.Errorf("casc: %x: %w", ekey, err)
89+ }
90+ return out, st, nil
91+}
92+
93+// Close closes all opened archive files.
94+func (a *archives) Close() error {
95+ a.mu.Lock()
96+ defer a.mu.Unlock()
97+ a.closed = true
98+ var errs []error
99+ for n, af := range a.files {
100+ errs = append(errs, af.f.Close())
101+ delete(a.files, n)
102+ }
103+ return errors.Join(errs...)
104+}
@@ -0,0 +1,104 @@
1+package casc
2+
3+import (
4+ "errors"
5+ "fmt"
6+ "os"
7+ "path/filepath"
8+ "sync"
9+
10+ "github.com/bnema/forever-db/internal/blte"
11+ "github.com/bnema/forever-db/internal/db2"
12+)
13+
14+// ErrNotFound means an encoding key is not in the local indexes.
15+var ErrNotFound = errors.New("casc: key not found in local storage")
16+
17+const archiveHeaderSize = 30
18+
19+// archives reads BLTE payloads from data.NNN files.
20+type archives struct {
21+ dir string
22+ index *indexes
23+
24+ mu sync.Mutex
25+ files map[int]archiveFile
26+ closed bool
27+}
28+
29+type archiveFile struct {
30+ f *os.File
31+ size int64
32+}
33+
34+func newArchives(dataDir string, ix *indexes) *archives {
35+ return &archives{dir: dataDir, index: ix, files: make(map[int]archiveFile)}
36+}
37+
38+func (a *archives) file(n int) (archiveFile, error) {
39+ a.mu.Lock()
40+ defer a.mu.Unlock()
41+ if a.closed {
42+ return archiveFile{}, errors.New("casc: storage closed")
43+ }
44+ if af, ok := a.files[n]; ok {
45+ return af, nil
46+ }
47+ f, err := os.Open(filepath.Join(a.dir, fmt.Sprintf("data.%03d", n)))
48+ if err != nil {
49+ return archiveFile{}, fmt.Errorf("casc: %w", err)
50+ }
51+ fi, err := f.Stat()
52+ if err != nil {
53+ f.Close()
54+ return archiveFile{}, fmt.Errorf("casc: %w", err)
55+ }
56+ af := archiveFile{f: f, size: fi.Size()}
57+ a.files[n] = af
58+ return af, nil
59+}
60+
61+// readEKey reads and BLTE-decodes the file stored under ekey.
62+func (a *archives) readEKey(ekey []byte, keys db2.KeyRing) ([]byte, blte.Stats, error) {
63+ arc, off, size, ok := a.index.lookup(ekey)
64+ if !ok {
65+ return nil, blte.Stats{}, fmt.Errorf("%w: %x", ErrNotFound, ekey)
66+ }
67+ if size < archiveHeaderSize {
68+ return nil, blte.Stats{}, fmt.Errorf("casc: entry %x: size %d too small", ekey, size)
69+ }
70+ af, err := a.file(arc)
71+ if err != nil {
72+ return nil, blte.Stats{}, err
73+ }
74+ if int64(off)+int64(size) > af.size {
75+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d: entry %x at %d+%d exceeds file size %d", arc, ekey, off, size, af.size)
76+ }
77+ buf := make([]byte, size)
78+ if n, err := af.f.ReadAt(buf, int64(off)); n != len(buf) {
79+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d short read at %d (%d of %d bytes): %w", arc, off, n, size, err)
80+ }
81+ for i := range 9 {
82+ if buf[15-i] != ekey[i] {
83+ return nil, blte.Stats{}, fmt.Errorf("casc: data.%03d at %d: header key mismatch for %x", arc, off, ekey)
84+ }
85+ }
86+ out, st, err := blte.Decode(buf[archiveHeaderSize:], keys)
87+ if err != nil {
88+ return nil, st, fmt.Errorf("casc: %x: %w", ekey, err)
89+ }
90+ return out, st, nil
91+}
92+
93+// Close closes all opened archive files.
94+func (a *archives) Close() error {
95+ a.mu.Lock()
96+ defer a.mu.Unlock()
97+ a.closed = true
98+ var errs []error
99+ for n, af := range a.files {
100+ errs = append(errs, af.f.Close())
101+ delete(a.files, n)
102+ }
103+ return errors.Join(errs...)
104+}
A internal/casc/archive_test.go +237 -0
@@ -0,0 +1,237 @@
1+package casc
2+
3+import (
4+ "fmt"
5+ "os"
6+ "path/filepath"
7+ "strings"
8+ "sync"
9+ "testing"
10+
11+ "github.com/bnema/forever-db/internal/testutil"
12+)
13+
14+func ekeyForBucket(t *testing.T, bucket int, seed byte) [16]byte {
15+ t.Helper()
16+ for i := 0; i < 256; i++ {
17+ k := [16]byte{seed, byte(i), 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
18+ if bucketOf(k[:]) == bucket {
19+ return k
20+ }
21+ }
22+ t.Fatal("no key for bucket")
23+ return [16]byte{}
24+}
25+
26+type fixture struct {
27+ dir string
28+ files []testutil.ArchiveFile
29+}
30+
31+func newFixture(t *testing.T) fixture {
32+ t.Helper()
33+ dir := t.TempDir()
34+ var files []testutil.ArchiveFile
35+ for i, b := range []int{1, 1, 7} {
36+ k := ekeyForBucket(t, b, byte(0x10*i+1))
37+ files = append(files, testutil.ArchiveFile{EKey: k, BLTE: testutil.BLTERaw([]byte(fmt.Sprintf("payload-%d", i)))})
38+ }
39+ entries, err := testutil.WriteArchive(dir, 0, files)
40+ if err != nil {
41+ t.Fatal(err)
42+ }
43+ if err := testutil.WriteIDXBuckets(dir, 1, entries); err != nil {
44+ t.Fatal(err)
45+ }
46+ return fixture{dir, files}
47+}
48+
49+func TestBucketOf(t *testing.T) {
50+ // x = 0x01^0x02 = 0x03 → (3&0xF)^(3>>4) = 3; 0xF0 → 0^0xF = 0xF.
51+ if b := bucketOf([]byte{1, 2, 0, 0, 0, 0, 0, 0, 0}); b != 3 {
52+ t.Fatalf("bucket = %d", b)
53+ }
54+ if b := bucketOf([]byte{0xF0, 0, 0, 0, 0, 0, 0, 0, 0}); b != 0xF {
55+ t.Fatalf("bucket = %d", b)
56+ }
57+ if testutil.IDXBucket([]byte{0xAB, 0x12, 0, 0, 0, 0, 0, 0, 0}) != bucketOf([]byte{0xAB, 0x12, 0, 0, 0, 0, 0, 0, 0}) {
58+ t.Fatal("testutil bucket differs")
59+ }
60+}
61+
62+func TestLookup(t *testing.T) {
63+ fx := newFixture(t)
64+ ix, err := openIndexes(fx.dir)
65+ if err != nil {
66+ t.Fatal(err)
67+ }
68+ for i, f := range fx.files {
69+ arc, off, size, ok := ix.lookup(f.EKey[:])
70+ if !ok || arc != 0 || size != uint32(30+len(f.BLTE)) {
71+ t.Fatalf("file %d: %d %d %d %v", i, arc, off, size, ok)
72+ }
73+ }
74+ miss := ekeyForBucket(t, 1, 0xEE)
75+ if _, _, _, ok := ix.lookup(miss[:]); ok {
76+ t.Fatal("unexpected hit")
77+ }
78+}
79+
80+func TestHighestVersion(t *testing.T) {
81+ dir := t.TempDir()
82+ k := ekeyForBucket(t, 2, 0x42)
83+ var key [9]byte
84+ copy(key[:], k[:9])
85+ if _, err := testutil.WriteIDX(dir, 2, 1, []testutil.IDXEntry{{Key: key, Archive: 1, Offset: 10, Size: 40}}); err != nil {
86+ t.Fatal(err)
87+ }
88+ if _, err := testutil.WriteIDX(dir, 2, 0x10, []testutil.IDXEntry{{Key: key, Archive: 3, Offset: 99, Size: 50}}); err != nil {
89+ t.Fatal(err)
90+ }
91+ os.WriteFile(dir+"/0200000099.idx.bak", []byte("x"), 0o644)
92+ ix, err := openIndexes(dir)
93+ if err != nil {
94+ t.Fatal(err)
95+ }
96+ if arc, off, size, ok := ix.lookup(k[:]); !ok || arc != 3 || off != 99 || size != 50 {
97+ t.Fatalf("got %d %d %d %v", arc, off, size, ok)
98+ }
99+}
100+
101+func TestBadSpec(t *testing.T) {
102+ dir := t.TempDir()
103+ p, err := testutil.WriteIDX(dir, 0, 1, nil)
104+ if err != nil {
105+ t.Fatal(err)
106+ }
107+ raw, _ := os.ReadFile(p)
108+ raw[0x0F] = 31
109+ os.WriteFile(p, raw, 0o644)
110+ if _, err := openIndexes(dir); err == nil || !strings.Contains(err.Error(), p) {
111+ t.Fatalf("err = %v", err)
112+ }
113+}
114+
115+func TestReadEKey(t *testing.T) {
116+ fx := newFixture(t)
117+ ix, err := openIndexes(fx.dir)
118+ if err != nil {
119+ t.Fatal(err)
120+ }
121+ a := newArchives(fx.dir, ix)
122+ defer a.Close()
123+ for i, f := range fx.files {
124+ out, _, err := a.readEKey(f.EKey[:], nil)
125+ if err != nil || string(out) != fmt.Sprintf("payload-%d", i) {
126+ t.Fatalf("file %d: %q, %v", i, out, err)
127+ }
128+ }
129+ miss := ekeyForBucket(t, 7, 0xEE)
130+ if _, _, err := a.readEKey(miss[:], nil); err == nil || !strings.Contains(err.Error(), "not found") {
131+ t.Fatalf("err = %v", err)
132+ }
133+}
134+
135+func TestReadEKeyHeaderMismatch(t *testing.T) {
136+ fx := newFixture(t)
137+ path := fx.dir + "/data.000"
138+ raw, _ := os.ReadFile(path)
139+ raw[15] ^= 0xFF // first file's reversed ekey[0]
140+ os.WriteFile(path, raw, 0o644)
141+ ix, err := openIndexes(fx.dir)
142+ if err != nil {
143+ t.Fatal(err)
144+ }
145+ a := newArchives(fx.dir, ix)
146+ defer a.Close()
147+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err == nil || !strings.Contains(err.Error(), "header key mismatch") {
148+ t.Fatalf("err = %v", err)
149+ }
150+}
151+
152+func TestReadEKeyConcurrent(t *testing.T) {
153+ fx := newFixture(t)
154+ ix, err := openIndexes(fx.dir)
155+ if err != nil {
156+ t.Fatal(err)
157+ }
158+ a := newArchives(fx.dir, ix)
159+ defer a.Close()
160+ var wg sync.WaitGroup
161+ errs := make(chan error, 8)
162+ for g := range 8 {
163+ wg.Add(1)
164+ go func() {
165+ defer wg.Done()
166+ for i := range 50 {
167+ f := fx.files[(g+i)%len(fx.files)]
168+ if _, _, err := a.readEKey(f.EKey[:], nil); err != nil {
169+ errs <- err
170+ return
171+ }
172+ }
173+ }()
174+ }
175+ wg.Wait()
176+ close(errs)
177+ for err := range errs {
178+ t.Fatal(err)
179+ }
180+}
181+
182+func TestReadEKeyOversizeEntry(t *testing.T) {
183+ dir := t.TempDir()
184+ k := ekeyForBucket(t, 4, 0x33)
185+ entries, err := testutil.WriteArchive(dir, 0, []testutil.ArchiveFile{{EKey: k, BLTE: testutil.BLTERaw([]byte("abc"))}})
186+ if err != nil {
187+ t.Fatal(err)
188+ }
189+ entries[0].Size = 1 << 29
190+ if err := testutil.WriteIDXBuckets(dir, 1, entries); err != nil {
191+ t.Fatal(err)
192+ }
193+ ix, err := openIndexes(dir)
194+ if err != nil {
195+ t.Fatal(err)
196+ }
197+ a := newArchives(dir, ix)
198+ defer a.Close()
199+ if _, _, err := a.readEKey(k[:], nil); err == nil || !strings.Contains(err.Error(), "exceeds file size") {
200+ t.Fatalf("err = %v", err)
201+ }
202+}
203+
204+func TestReadAfterClose(t *testing.T) {
205+ fx := newFixture(t)
206+ ix, err := openIndexes(fx.dir)
207+ if err != nil {
208+ t.Fatal(err)
209+ }
210+ a := newArchives(fx.dir, ix)
211+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err != nil {
212+ t.Fatal(err)
213+ }
214+ a.Close()
215+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err == nil || !strings.Contains(err.Error(), "closed") {
216+ t.Fatalf("err = %v", err)
217+ }
218+}
219+
220+func FuzzParseIndex(f *testing.F) {
221+ dir := f.TempDir()
222+ k := [9]byte{1, 2, 3}
223+ p, err := testutil.WriteIDX(dir, 3, 1, []testutil.IDXEntry{{Key: k, Archive: 1, Offset: 2, Size: 40}})
224+ if err != nil {
225+ f.Fatal(err)
226+ }
227+ seed, _ := os.ReadFile(p)
228+ f.Add(seed)
229+ f.Fuzz(func(t *testing.T, data []byte) {
230+ path := filepath.Join(t.TempDir(), "x.idx")
231+ os.WriteFile(path, data, 0o644)
232+ raw, err := parseIndex(path)
233+ if err == nil && len(raw)%idxEntrySize != 0 {
234+ t.Fatal("partial entries")
235+ }
236+ })
237+}
@@ -0,0 +1,237 @@
1+package casc
2+
3+import (
4+ "fmt"
5+ "os"
6+ "path/filepath"
7+ "strings"
8+ "sync"
9+ "testing"
10+
11+ "github.com/bnema/forever-db/internal/testutil"
12+)
13+
14+func ekeyForBucket(t *testing.T, bucket int, seed byte) [16]byte {
15+ t.Helper()
16+ for i := 0; i < 256; i++ {
17+ k := [16]byte{seed, byte(i), 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
18+ if bucketOf(k[:]) == bucket {
19+ return k
20+ }
21+ }
22+ t.Fatal("no key for bucket")
23+ return [16]byte{}
24+}
25+
26+type fixture struct {
27+ dir string
28+ files []testutil.ArchiveFile
29+}
30+
31+func newFixture(t *testing.T) fixture {
32+ t.Helper()
33+ dir := t.TempDir()
34+ var files []testutil.ArchiveFile
35+ for i, b := range []int{1, 1, 7} {
36+ k := ekeyForBucket(t, b, byte(0x10*i+1))
37+ files = append(files, testutil.ArchiveFile{EKey: k, BLTE: testutil.BLTERaw([]byte(fmt.Sprintf("payload-%d", i)))})
38+ }
39+ entries, err := testutil.WriteArchive(dir, 0, files)
40+ if err != nil {
41+ t.Fatal(err)
42+ }
43+ if err := testutil.WriteIDXBuckets(dir, 1, entries); err != nil {
44+ t.Fatal(err)
45+ }
46+ return fixture{dir, files}
47+}
48+
49+func TestBucketOf(t *testing.T) {
50+ // x = 0x01^0x02 = 0x03 → (3&0xF)^(3>>4) = 3; 0xF0 → 0^0xF = 0xF.
51+ if b := bucketOf([]byte{1, 2, 0, 0, 0, 0, 0, 0, 0}); b != 3 {
52+ t.Fatalf("bucket = %d", b)
53+ }
54+ if b := bucketOf([]byte{0xF0, 0, 0, 0, 0, 0, 0, 0, 0}); b != 0xF {
55+ t.Fatalf("bucket = %d", b)
56+ }
57+ if testutil.IDXBucket([]byte{0xAB, 0x12, 0, 0, 0, 0, 0, 0, 0}) != bucketOf([]byte{0xAB, 0x12, 0, 0, 0, 0, 0, 0, 0}) {
58+ t.Fatal("testutil bucket differs")
59+ }
60+}
61+
62+func TestLookup(t *testing.T) {
63+ fx := newFixture(t)
64+ ix, err := openIndexes(fx.dir)
65+ if err != nil {
66+ t.Fatal(err)
67+ }
68+ for i, f := range fx.files {
69+ arc, off, size, ok := ix.lookup(f.EKey[:])
70+ if !ok || arc != 0 || size != uint32(30+len(f.BLTE)) {
71+ t.Fatalf("file %d: %d %d %d %v", i, arc, off, size, ok)
72+ }
73+ }
74+ miss := ekeyForBucket(t, 1, 0xEE)
75+ if _, _, _, ok := ix.lookup(miss[:]); ok {
76+ t.Fatal("unexpected hit")
77+ }
78+}
79+
80+func TestHighestVersion(t *testing.T) {
81+ dir := t.TempDir()
82+ k := ekeyForBucket(t, 2, 0x42)
83+ var key [9]byte
84+ copy(key[:], k[:9])
85+ if _, err := testutil.WriteIDX(dir, 2, 1, []testutil.IDXEntry{{Key: key, Archive: 1, Offset: 10, Size: 40}}); err != nil {
86+ t.Fatal(err)
87+ }
88+ if _, err := testutil.WriteIDX(dir, 2, 0x10, []testutil.IDXEntry{{Key: key, Archive: 3, Offset: 99, Size: 50}}); err != nil {
89+ t.Fatal(err)
90+ }
91+ os.WriteFile(dir+"/0200000099.idx.bak", []byte("x"), 0o644)
92+ ix, err := openIndexes(dir)
93+ if err != nil {
94+ t.Fatal(err)
95+ }
96+ if arc, off, size, ok := ix.lookup(k[:]); !ok || arc != 3 || off != 99 || size != 50 {
97+ t.Fatalf("got %d %d %d %v", arc, off, size, ok)
98+ }
99+}
100+
101+func TestBadSpec(t *testing.T) {
102+ dir := t.TempDir()
103+ p, err := testutil.WriteIDX(dir, 0, 1, nil)
104+ if err != nil {
105+ t.Fatal(err)
106+ }
107+ raw, _ := os.ReadFile(p)
108+ raw[0x0F] = 31
109+ os.WriteFile(p, raw, 0o644)
110+ if _, err := openIndexes(dir); err == nil || !strings.Contains(err.Error(), p) {
111+ t.Fatalf("err = %v", err)
112+ }
113+}
114+
115+func TestReadEKey(t *testing.T) {
116+ fx := newFixture(t)
117+ ix, err := openIndexes(fx.dir)
118+ if err != nil {
119+ t.Fatal(err)
120+ }
121+ a := newArchives(fx.dir, ix)
122+ defer a.Close()
123+ for i, f := range fx.files {
124+ out, _, err := a.readEKey(f.EKey[:], nil)
125+ if err != nil || string(out) != fmt.Sprintf("payload-%d", i) {
126+ t.Fatalf("file %d: %q, %v", i, out, err)
127+ }
128+ }
129+ miss := ekeyForBucket(t, 7, 0xEE)
130+ if _, _, err := a.readEKey(miss[:], nil); err == nil || !strings.Contains(err.Error(), "not found") {
131+ t.Fatalf("err = %v", err)
132+ }
133+}
134+
135+func TestReadEKeyHeaderMismatch(t *testing.T) {
136+ fx := newFixture(t)
137+ path := fx.dir + "/data.000"
138+ raw, _ := os.ReadFile(path)
139+ raw[15] ^= 0xFF // first file's reversed ekey[0]
140+ os.WriteFile(path, raw, 0o644)
141+ ix, err := openIndexes(fx.dir)
142+ if err != nil {
143+ t.Fatal(err)
144+ }
145+ a := newArchives(fx.dir, ix)
146+ defer a.Close()
147+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err == nil || !strings.Contains(err.Error(), "header key mismatch") {
148+ t.Fatalf("err = %v", err)
149+ }
150+}
151+
152+func TestReadEKeyConcurrent(t *testing.T) {
153+ fx := newFixture(t)
154+ ix, err := openIndexes(fx.dir)
155+ if err != nil {
156+ t.Fatal(err)
157+ }
158+ a := newArchives(fx.dir, ix)
159+ defer a.Close()
160+ var wg sync.WaitGroup
161+ errs := make(chan error, 8)
162+ for g := range 8 {
163+ wg.Add(1)
164+ go func() {
165+ defer wg.Done()
166+ for i := range 50 {
167+ f := fx.files[(g+i)%len(fx.files)]
168+ if _, _, err := a.readEKey(f.EKey[:], nil); err != nil {
169+ errs <- err
170+ return
171+ }
172+ }
173+ }()
174+ }
175+ wg.Wait()
176+ close(errs)
177+ for err := range errs {
178+ t.Fatal(err)
179+ }
180+}
181+
182+func TestReadEKeyOversizeEntry(t *testing.T) {
183+ dir := t.TempDir()
184+ k := ekeyForBucket(t, 4, 0x33)
185+ entries, err := testutil.WriteArchive(dir, 0, []testutil.ArchiveFile{{EKey: k, BLTE: testutil.BLTERaw([]byte("abc"))}})
186+ if err != nil {
187+ t.Fatal(err)
188+ }
189+ entries[0].Size = 1 << 29
190+ if err := testutil.WriteIDXBuckets(dir, 1, entries); err != nil {
191+ t.Fatal(err)
192+ }
193+ ix, err := openIndexes(dir)
194+ if err != nil {
195+ t.Fatal(err)
196+ }
197+ a := newArchives(dir, ix)
198+ defer a.Close()
199+ if _, _, err := a.readEKey(k[:], nil); err == nil || !strings.Contains(err.Error(), "exceeds file size") {
200+ t.Fatalf("err = %v", err)
201+ }
202+}
203+
204+func TestReadAfterClose(t *testing.T) {
205+ fx := newFixture(t)
206+ ix, err := openIndexes(fx.dir)
207+ if err != nil {
208+ t.Fatal(err)
209+ }
210+ a := newArchives(fx.dir, ix)
211+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err != nil {
212+ t.Fatal(err)
213+ }
214+ a.Close()
215+ if _, _, err := a.readEKey(fx.files[0].EKey[:], nil); err == nil || !strings.Contains(err.Error(), "closed") {
216+ t.Fatalf("err = %v", err)
217+ }
218+}
219+
220+func FuzzParseIndex(f *testing.F) {
221+ dir := f.TempDir()
222+ k := [9]byte{1, 2, 3}
223+ p, err := testutil.WriteIDX(dir, 3, 1, []testutil.IDXEntry{{Key: k, Archive: 1, Offset: 2, Size: 40}})
224+ if err != nil {
225+ f.Fatal(err)
226+ }
227+ seed, _ := os.ReadFile(p)
228+ f.Add(seed)
229+ f.Fuzz(func(t *testing.T, data []byte) {
230+ path := filepath.Join(t.TempDir(), "x.idx")
231+ os.WriteFile(path, data, 0o644)
232+ raw, err := parseIndex(path)
233+ if err == nil && len(raw)%idxEntrySize != 0 {
234+ t.Fatal("partial entries")
235+ }
236+ })
237+}
A internal/casc/encoding.go +100 -0
@@ -0,0 +1,100 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "fmt"
7+ "sort"
8+)
9+
10+const encHeaderSize = 22
11+
12+// encoding maps content keys to encoding keys using the decoded encoding file.
13+type encoding struct {
14+ buf []byte
15+ pageSize int
16+ pageIndex []byte // cePageCount × (firstCKey[16] + md5[16])
17+ pages int
18+ pagesOff int
19+}
20+
21+func parseEncoding(buf []byte) (*encoding, error) {
22+ if len(buf) < encHeaderSize {
23+ return nil, fmt.Errorf("encoding: truncated header")
24+ }
25+ if string(buf[:2]) != "EN" {
26+ return nil, fmt.Errorf("encoding: bad magic %q", buf[:2])
27+ }
28+ if buf[2] != 1 {
29+ return nil, fmt.Errorf("encoding: unsupported version %d", buf[2])
30+ }
31+ if buf[3] != 16 || buf[4] != 16 {
32+ return nil, fmt.Errorf("encoding: unsupported key sizes %d/%d", buf[3], buf[4])
33+ }
34+ pageKB := int(binary.BigEndian.Uint16(buf[5:]))
35+ pages := int(binary.BigEndian.Uint32(buf[9:]))
36+ especSize := int(binary.BigEndian.Uint32(buf[18:]))
37+ idxOff := encHeaderSize + especSize
38+ pagesOff := idxOff + pages*32
39+ pageSize := pageKB * 1024
40+ if pageSize == 0 || especSize < 0 || pagesOff < idxOff || pagesOff > len(buf) {
41+ return nil, fmt.Errorf("encoding: truncated page index")
42+ }
43+ if pagesOff+pages*pageSize > len(buf) {
44+ return nil, fmt.Errorf("encoding: truncated pages")
45+ }
46+ return &encoding{buf: buf, pageSize: pageSize, pageIndex: buf[idxOff:pagesOff], pages: pages, pagesOff: pagesOff}, nil
47+}
48+
49+// find returns the entry offset for ckey in buf.
50+func (e *encoding) find(ckey []byte) (int, bool) {
51+ if len(ckey) != 16 || e.pages == 0 {
52+ return 0, false
53+ }
54+ // first page whose firstCKey > ckey, minus one
55+ p := sort.Search(e.pages, func(i int) bool {
56+ return bytes.Compare(e.pageIndex[i*32:i*32+16], ckey) > 0
57+ }) - 1
58+ if p < 0 {
59+ return 0, false
60+ }
61+ q := e.pagesOff + p*e.pageSize
62+ end := q + e.pageSize
63+ for q+6+16 <= end {
64+ kc := int(e.buf[q])
65+ if kc == 0 {
66+ break
67+ }
68+ next := q + 6 + 16 + kc*16
69+ if next > end {
70+ break
71+ }
72+ if bytes.Equal(e.buf[q+6:q+22], ckey) {
73+ return q, true
74+ }
75+ q = next
76+ }
77+ return 0, false
78+}
79+
80+// EKey returns the first encoding key for ckey.
81+func (e *encoding) EKey(ckey []byte) ([]byte, bool) {
82+ q, ok := e.find(ckey)
83+ if !ok {
84+ return nil, false
85+ }
86+ return bytes.Clone(e.buf[q+22 : q+38]), true
87+}
88+
89+// Size returns the decoded file size for ckey.
90+func (e *encoding) Size(ckey []byte) (uint64, bool) {
91+ q, ok := e.find(ckey)
92+ if !ok {
93+ return 0, false
94+ }
95+ var v uint64
96+ for _, b := range e.buf[q+1 : q+6] {
97+ v = v<<8 | uint64(b)
98+ }
99+ return v, true
100+}
@@ -0,0 +1,100 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "fmt"
7+ "sort"
8+)
9+
10+const encHeaderSize = 22
11+
12+// encoding maps content keys to encoding keys using the decoded encoding file.
13+type encoding struct {
14+ buf []byte
15+ pageSize int
16+ pageIndex []byte // cePageCount × (firstCKey[16] + md5[16])
17+ pages int
18+ pagesOff int
19+}
20+
21+func parseEncoding(buf []byte) (*encoding, error) {
22+ if len(buf) < encHeaderSize {
23+ return nil, fmt.Errorf("encoding: truncated header")
24+ }
25+ if string(buf[:2]) != "EN" {
26+ return nil, fmt.Errorf("encoding: bad magic %q", buf[:2])
27+ }
28+ if buf[2] != 1 {
29+ return nil, fmt.Errorf("encoding: unsupported version %d", buf[2])
30+ }
31+ if buf[3] != 16 || buf[4] != 16 {
32+ return nil, fmt.Errorf("encoding: unsupported key sizes %d/%d", buf[3], buf[4])
33+ }
34+ pageKB := int(binary.BigEndian.Uint16(buf[5:]))
35+ pages := int(binary.BigEndian.Uint32(buf[9:]))
36+ especSize := int(binary.BigEndian.Uint32(buf[18:]))
37+ idxOff := encHeaderSize + especSize
38+ pagesOff := idxOff + pages*32
39+ pageSize := pageKB * 1024
40+ if pageSize == 0 || especSize < 0 || pagesOff < idxOff || pagesOff > len(buf) {
41+ return nil, fmt.Errorf("encoding: truncated page index")
42+ }
43+ if pagesOff+pages*pageSize > len(buf) {
44+ return nil, fmt.Errorf("encoding: truncated pages")
45+ }
46+ return &encoding{buf: buf, pageSize: pageSize, pageIndex: buf[idxOff:pagesOff], pages: pages, pagesOff: pagesOff}, nil
47+}
48+
49+// find returns the entry offset for ckey in buf.
50+func (e *encoding) find(ckey []byte) (int, bool) {
51+ if len(ckey) != 16 || e.pages == 0 {
52+ return 0, false
53+ }
54+ // first page whose firstCKey > ckey, minus one
55+ p := sort.Search(e.pages, func(i int) bool {
56+ return bytes.Compare(e.pageIndex[i*32:i*32+16], ckey) > 0
57+ }) - 1
58+ if p < 0 {
59+ return 0, false
60+ }
61+ q := e.pagesOff + p*e.pageSize
62+ end := q + e.pageSize
63+ for q+6+16 <= end {
64+ kc := int(e.buf[q])
65+ if kc == 0 {
66+ break
67+ }
68+ next := q + 6 + 16 + kc*16
69+ if next > end {
70+ break
71+ }
72+ if bytes.Equal(e.buf[q+6:q+22], ckey) {
73+ return q, true
74+ }
75+ q = next
76+ }
77+ return 0, false
78+}
79+
80+// EKey returns the first encoding key for ckey.
81+func (e *encoding) EKey(ckey []byte) ([]byte, bool) {
82+ q, ok := e.find(ckey)
83+ if !ok {
84+ return nil, false
85+ }
86+ return bytes.Clone(e.buf[q+22 : q+38]), true
87+}
88+
89+// Size returns the decoded file size for ckey.
90+func (e *encoding) Size(ckey []byte) (uint64, bool) {
91+ q, ok := e.find(ckey)
92+ if !ok {
93+ return 0, false
94+ }
95+ var v uint64
96+ for _, b := range e.buf[q+1 : q+6] {
97+ v = v<<8 | uint64(b)
98+ }
99+ return v, true
100+}
A internal/casc/encoding_test.go +102 -0
@@ -0,0 +1,102 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "strings"
7+ "testing"
8+
9+ "github.com/bnema/forever-db/internal/testutil"
10+)
11+
12+func ck(i int) [16]byte {
13+ var k [16]byte
14+ binary.BigEndian.PutUint32(k[0:], uint32(i*2+10)) // even values, gaps between
15+ return k
16+}
17+
18+func ek(i int) [16]byte {
19+ var k [16]byte
20+ k[0] = 0xEE
21+ binary.BigEndian.PutUint32(k[12:], uint32(i))
22+ return k
23+}
24+
25+func buildEnc(n int) []byte {
26+ var es []testutil.EncodingEntry
27+ for i := range n {
28+ es = append(es, testutil.EncodingEntry{CKey: ck(i), EKeys: [][16]byte{ek(i), ek(1000 + i)}, Size: uint64(i) + 1<<33})
29+ }
30+ return testutil.BuildEncoding(1, es)
31+}
32+
33+func TestEncodingLookup(t *testing.T) {
34+ const n = 40 // 54 bytes per entry → 18 per 1 KiB page → 3 pages
35+ enc, err := parseEncoding(buildEnc(n))
36+ if err != nil {
37+ t.Fatal(err)
38+ }
39+ if enc.pages < 2 {
40+ t.Fatalf("pages = %d", enc.pages)
41+ }
42+ for _, i := range []int{0, 17, 18, 35, 36, n - 1} {
43+ k := ck(i)
44+ got, ok := enc.EKey(k[:])
45+ want := ek(i)
46+ if !ok || !bytes.Equal(got, want[:]) {
47+ t.Fatalf("entry %d: %x %v", i, got, ok)
48+ }
49+ if s, ok := enc.Size(k[:]); !ok || s != uint64(i)+1<<33 {
50+ t.Fatalf("size %d: %d %v", i, s, ok)
51+ }
52+ }
53+ between := ck(18)
54+ between[3]--
55+ before := [16]byte{}
56+ after := ck(n)
57+ for name, k := range map[string][16]byte{"between": between, "before": before, "after": after} {
58+ if _, ok := enc.EKey(k[:]); ok {
59+ t.Fatalf("%s: unexpected hit", name)
60+ }
61+ }
62+}
63+
64+func TestEncodingErrors(t *testing.T) {
65+ good := buildEnc(5)
66+ mod := func(f func(b []byte) []byte) []byte { return f(bytes.Clone(good)) }
67+ tests := map[string]struct {
68+ buf []byte
69+ want string
70+ }{
71+ "magic": {mod(func(b []byte) []byte { b[0] = 'X'; return b }), "bad magic"},
72+ "version": {mod(func(b []byte) []byte { b[2] = 2; return b }), "version"},
73+ "key size": {mod(func(b []byte) []byte { b[4] = 9; return b }), "key sizes"},
74+ "index": {good[:22+2+10], "truncated page index"},
75+ "pages": {good[:len(good)-1], "truncated pages"},
76+ "header": {good[:10], "truncated header"},
77+ }
78+ for name, tt := range tests {
79+ t.Run(name, func(t *testing.T) {
80+ if _, err := parseEncoding(tt.buf); err == nil || !strings.Contains(err.Error(), tt.want) {
81+ t.Fatalf("err = %v", err)
82+ }
83+ })
84+ }
85+}
86+
87+func FuzzParseEncoding(f *testing.F) {
88+ f.Add(buildEnc(5))
89+ f.Add(buildEnc(40))
90+ f.Fuzz(func(t *testing.T, data []byte) {
91+ enc, err := parseEncoding(data)
92+ if err != nil {
93+ return
94+ }
95+ k := ck(1)
96+ enc.EKey(k[:])
97+ enc.Size(k[:])
98+ if len(data) >= 16 {
99+ enc.EKey(data[:16])
100+ }
101+ })
102+}
@@ -0,0 +1,102 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "strings"
7+ "testing"
8+
9+ "github.com/bnema/forever-db/internal/testutil"
10+)
11+
12+func ck(i int) [16]byte {
13+ var k [16]byte
14+ binary.BigEndian.PutUint32(k[0:], uint32(i*2+10)) // even values, gaps between
15+ return k
16+}
17+
18+func ek(i int) [16]byte {
19+ var k [16]byte
20+ k[0] = 0xEE
21+ binary.BigEndian.PutUint32(k[12:], uint32(i))
22+ return k
23+}
24+
25+func buildEnc(n int) []byte {
26+ var es []testutil.EncodingEntry
27+ for i := range n {
28+ es = append(es, testutil.EncodingEntry{CKey: ck(i), EKeys: [][16]byte{ek(i), ek(1000 + i)}, Size: uint64(i) + 1<<33})
29+ }
30+ return testutil.BuildEncoding(1, es)
31+}
32+
33+func TestEncodingLookup(t *testing.T) {
34+ const n = 40 // 54 bytes per entry → 18 per 1 KiB page → 3 pages
35+ enc, err := parseEncoding(buildEnc(n))
36+ if err != nil {
37+ t.Fatal(err)
38+ }
39+ if enc.pages < 2 {
40+ t.Fatalf("pages = %d", enc.pages)
41+ }
42+ for _, i := range []int{0, 17, 18, 35, 36, n - 1} {
43+ k := ck(i)
44+ got, ok := enc.EKey(k[:])
45+ want := ek(i)
46+ if !ok || !bytes.Equal(got, want[:]) {
47+ t.Fatalf("entry %d: %x %v", i, got, ok)
48+ }
49+ if s, ok := enc.Size(k[:]); !ok || s != uint64(i)+1<<33 {
50+ t.Fatalf("size %d: %d %v", i, s, ok)
51+ }
52+ }
53+ between := ck(18)
54+ between[3]--
55+ before := [16]byte{}
56+ after := ck(n)
57+ for name, k := range map[string][16]byte{"between": between, "before": before, "after": after} {
58+ if _, ok := enc.EKey(k[:]); ok {
59+ t.Fatalf("%s: unexpected hit", name)
60+ }
61+ }
62+}
63+
64+func TestEncodingErrors(t *testing.T) {
65+ good := buildEnc(5)
66+ mod := func(f func(b []byte) []byte) []byte { return f(bytes.Clone(good)) }
67+ tests := map[string]struct {
68+ buf []byte
69+ want string
70+ }{
71+ "magic": {mod(func(b []byte) []byte { b[0] = 'X'; return b }), "bad magic"},
72+ "version": {mod(func(b []byte) []byte { b[2] = 2; return b }), "version"},
73+ "key size": {mod(func(b []byte) []byte { b[4] = 9; return b }), "key sizes"},
74+ "index": {good[:22+2+10], "truncated page index"},
75+ "pages": {good[:len(good)-1], "truncated pages"},
76+ "header": {good[:10], "truncated header"},
77+ }
78+ for name, tt := range tests {
79+ t.Run(name, func(t *testing.T) {
80+ if _, err := parseEncoding(tt.buf); err == nil || !strings.Contains(err.Error(), tt.want) {
81+ t.Fatalf("err = %v", err)
82+ }
83+ })
84+ }
85+}
86+
87+func FuzzParseEncoding(f *testing.F) {
88+ f.Add(buildEnc(5))
89+ f.Add(buildEnc(40))
90+ f.Fuzz(func(t *testing.T, data []byte) {
91+ enc, err := parseEncoding(data)
92+ if err != nil {
93+ return
94+ }
95+ k := ck(1)
96+ enc.EKey(k[:])
97+ enc.Size(k[:])
98+ if len(data) >= 16 {
99+ enc.EKey(data[:16])
100+ }
101+ })
102+}
A internal/casc/index.go +120 -0
@@ -0,0 +1,120 @@
1+// Package casc reads a local CASC storage (indexes, archives, encoding, root).
2+package casc
3+
4+import (
5+ "bytes"
6+ "encoding/binary"
7+ "fmt"
8+ "os"
9+ "path/filepath"
10+ "sort"
11+ "strconv"
12+)
13+
14+const idxEntrySize = 18
15+
16+// indexes holds the raw sorted entry bytes of the newest .idx file per bucket.
17+type indexes struct {
18+ buckets [16][]byte
19+}
20+
21+// openIndexes loads the highest-version .idx file of each bucket in dataDir.
22+func openIndexes(dataDir string) (*indexes, error) {
23+ names, err := filepath.Glob(filepath.Join(dataDir, "*.idx"))
24+ if err != nil {
25+ return nil, err
26+ }
27+ var best [16]struct {
28+ version uint64
29+ path string
30+ }
31+ for _, p := range names {
32+ base := filepath.Base(p)
33+ if len(base) != 14 {
34+ continue
35+ }
36+ b, err1 := strconv.ParseUint(base[:2], 16, 8)
37+ v, err2 := strconv.ParseUint(base[2:10], 16, 32)
38+ if err1 != nil || err2 != nil || b > 15 {
39+ continue
40+ }
41+ if best[b].path == "" || v > best[b].version {
42+ best[b].version, best[b].path = v, p
43+ }
44+ }
45+ ix := &indexes{}
46+ found := false
47+ for b, e := range best {
48+ if e.path == "" {
49+ continue
50+ }
51+ raw, err := parseIndex(e.path)
52+ if err != nil {
53+ return nil, err
54+ }
55+ ix.buckets[b] = raw
56+ found = true
57+ }
58+ if !found {
59+ return nil, fmt.Errorf("no .idx files in %s", dataDir)
60+ }
61+ return ix, nil
62+}
63+
64+func parseIndex(path string) ([]byte, error) {
65+ data, err := os.ReadFile(path)
66+ if err != nil {
67+ return nil, err
68+ }
69+ if len(data) < 16 {
70+ return nil, fmt.Errorf("index %s: truncated header", path)
71+ }
72+ if !bytes.Equal(data[0x0C:0x10], []byte{4, 5, 9, 30}) {
73+ return nil, fmt.Errorf("index %s: unsupported spec % X", path, data[0x0C:0x10])
74+ }
75+ hsz := int(binary.LittleEndian.Uint32(data[0:]))
76+ start := (8 + hsz + 0x0F) &^ 0x0F
77+ if start+8 > len(data) || start < 0 {
78+ return nil, fmt.Errorf("index %s: truncated", path)
79+ }
80+ esize := int(binary.LittleEndian.Uint32(data[start:]))
81+ p := start + 8
82+ n := esize / idxEntrySize
83+ if p+n*idxEntrySize > len(data) {
84+ return nil, fmt.Errorf("index %s: entries exceed file size", path)
85+ }
86+ return data[p : p+n*idxEntrySize], nil
87+}
88+
89+func bucketOf(ekey []byte) int {
90+ var x byte
91+ for _, b := range ekey[:9] {
92+ x ^= b
93+ }
94+ return int((x & 0xF) ^ (x >> 4))
95+}
96+
97+// lookup finds ekey (first 9 bytes) and returns its archive location.
98+func (ix *indexes) lookup(ekey []byte) (archive int, offset, size uint32, ok bool) {
99+ if len(ekey) < 9 {
100+ return 0, 0, 0, false
101+ }
102+ raw := ix.buckets[bucketOf(ekey)]
103+ key := ekey[:9]
104+ n := len(raw) / idxEntrySize
105+ i := sort.Search(n, func(i int) bool {
106+ return bytes.Compare(raw[i*idxEntrySize:i*idxEntrySize+9], key) >= 0
107+ })
108+ if i >= n {
109+ return 0, 0, 0, false
110+ }
111+ e := raw[i*idxEntrySize : (i+1)*idxEntrySize]
112+ if !bytes.Equal(e[:9], key) {
113+ return 0, 0, 0, false
114+ }
115+ var v uint64
116+ for _, b := range e[9:14] {
117+ v = v<<8 | uint64(b)
118+ }
119+ return int(v >> 30), uint32(v & 0x3FFFFFFF), binary.LittleEndian.Uint32(e[14:18]), true
120+}
@@ -0,0 +1,120 @@
1+// Package casc reads a local CASC storage (indexes, archives, encoding, root).
2+package casc
3+
4+import (
5+ "bytes"
6+ "encoding/binary"
7+ "fmt"
8+ "os"
9+ "path/filepath"
10+ "sort"
11+ "strconv"
12+)
13+
14+const idxEntrySize = 18
15+
16+// indexes holds the raw sorted entry bytes of the newest .idx file per bucket.
17+type indexes struct {
18+ buckets [16][]byte
19+}
20+
21+// openIndexes loads the highest-version .idx file of each bucket in dataDir.
22+func openIndexes(dataDir string) (*indexes, error) {
23+ names, err := filepath.Glob(filepath.Join(dataDir, "*.idx"))
24+ if err != nil {
25+ return nil, err
26+ }
27+ var best [16]struct {
28+ version uint64
29+ path string
30+ }
31+ for _, p := range names {
32+ base := filepath.Base(p)
33+ if len(base) != 14 {
34+ continue
35+ }
36+ b, err1 := strconv.ParseUint(base[:2], 16, 8)
37+ v, err2 := strconv.ParseUint(base[2:10], 16, 32)
38+ if err1 != nil || err2 != nil || b > 15 {
39+ continue
40+ }
41+ if best[b].path == "" || v > best[b].version {
42+ best[b].version, best[b].path = v, p
43+ }
44+ }
45+ ix := &indexes{}
46+ found := false
47+ for b, e := range best {
48+ if e.path == "" {
49+ continue
50+ }
51+ raw, err := parseIndex(e.path)
52+ if err != nil {
53+ return nil, err
54+ }
55+ ix.buckets[b] = raw
56+ found = true
57+ }
58+ if !found {
59+ return nil, fmt.Errorf("no .idx files in %s", dataDir)
60+ }
61+ return ix, nil
62+}
63+
64+func parseIndex(path string) ([]byte, error) {
65+ data, err := os.ReadFile(path)
66+ if err != nil {
67+ return nil, err
68+ }
69+ if len(data) < 16 {
70+ return nil, fmt.Errorf("index %s: truncated header", path)
71+ }
72+ if !bytes.Equal(data[0x0C:0x10], []byte{4, 5, 9, 30}) {
73+ return nil, fmt.Errorf("index %s: unsupported spec % X", path, data[0x0C:0x10])
74+ }
75+ hsz := int(binary.LittleEndian.Uint32(data[0:]))
76+ start := (8 + hsz + 0x0F) &^ 0x0F
77+ if start+8 > len(data) || start < 0 {
78+ return nil, fmt.Errorf("index %s: truncated", path)
79+ }
80+ esize := int(binary.LittleEndian.Uint32(data[start:]))
81+ p := start + 8
82+ n := esize / idxEntrySize
83+ if p+n*idxEntrySize > len(data) {
84+ return nil, fmt.Errorf("index %s: entries exceed file size", path)
85+ }
86+ return data[p : p+n*idxEntrySize], nil
87+}
88+
89+func bucketOf(ekey []byte) int {
90+ var x byte
91+ for _, b := range ekey[:9] {
92+ x ^= b
93+ }
94+ return int((x & 0xF) ^ (x >> 4))
95+}
96+
97+// lookup finds ekey (first 9 bytes) and returns its archive location.
98+func (ix *indexes) lookup(ekey []byte) (archive int, offset, size uint32, ok bool) {
99+ if len(ekey) < 9 {
100+ return 0, 0, 0, false
101+ }
102+ raw := ix.buckets[bucketOf(ekey)]
103+ key := ekey[:9]
104+ n := len(raw) / idxEntrySize
105+ i := sort.Search(n, func(i int) bool {
106+ return bytes.Compare(raw[i*idxEntrySize:i*idxEntrySize+9], key) >= 0
107+ })
108+ if i >= n {
109+ return 0, 0, 0, false
110+ }
111+ e := raw[i*idxEntrySize : (i+1)*idxEntrySize]
112+ if !bytes.Equal(e[:9], key) {
113+ return 0, 0, 0, false
114+ }
115+ var v uint64
116+ for _, b := range e[9:14] {
117+ v = v<<8 | uint64(b)
118+ }
119+ return int(v >> 30), uint32(v & 0x3FFFFFFF), binary.LittleEndian.Uint32(e[14:18]), true
120+}
A internal/casc/root.go +77 -0
@@ -0,0 +1,77 @@
1+package casc
2+
3+import (
4+ "encoding/binary"
5+ "errors"
6+ "fmt"
7+)
8+
9+// ErrUnsupportedRoot means the root file is not a TSFM v2 root.
10+var ErrUnsupportedRoot = errors.New("casc: unsupported root format")
11+
12+const (
13+ rootBlockHeaderSize = 17
14+ flagNoNameHash = 0x10000000
15+)
16+
17+func rootContentFlags(unk1, unk2 uint32, unk3 uint8) uint32 {
18+ return unk1 | unk2 | uint32(unk3)<<17
19+}
20+
21+// resolveRoot returns the content keys of the wanted FileDataIDs whose block
22+// matches localeMask. The first match per FDID wins.
23+func resolveRoot(buf []byte, want map[uint32]struct{}, localeMask uint32) (map[uint32][16]byte, error) {
24+ if len(buf) < 20 {
25+ return nil, fmt.Errorf("%w: truncated header", ErrUnsupportedRoot)
26+ }
27+ if string(buf[:4]) != "TSFM" {
28+ return nil, fmt.Errorf("%w: magic %q", ErrUnsupportedRoot, buf[:4])
29+ }
30+ le := binary.LittleEndian
31+ hsize := le.Uint32(buf[4:])
32+ version := le.Uint32(buf[8:])
33+ if hsize != 24 || version != 2 {
34+ return nil, fmt.Errorf("%w: header size %d, version %d", ErrUnsupportedRoot, hsize, version)
35+ }
36+ total, named := le.Uint32(buf[12:]), le.Uint32(buf[16:])
37+ out := make(map[uint32][16]byte, len(want))
38+ p := int(hsize)
39+ for blk := 0; p < len(buf); blk++ {
40+ if p+rootBlockHeaderSize > len(buf) {
41+ return nil, fmt.Errorf("casc: root block %d: truncated header", blk)
42+ }
43+ count := int(le.Uint32(buf[p:]))
44+ locale := le.Uint32(buf[p+4:])
45+ flags := rootContentFlags(le.Uint32(buf[p+8:]), le.Uint32(buf[p+12:]), buf[p+16])
46+ p += rootBlockHeaderSize
47+ size := count * (4 + 16)
48+ if total != named && flags&flagNoNameHash != 0 {
49+ // no name hashes
50+ } else {
51+ size += count * 8
52+ }
53+ if count < 0 || size < 0 || p+size > len(buf) {
54+ return nil, fmt.Errorf("casc: root block %d: truncated (%d records)", blk, count)
55+ }
56+ if locale&localeMask != 0 && len(want) > 0 {
57+ deltas := buf[p : p+count*4]
58+ ckeys := buf[p+count*4 : p+count*20]
59+ fd := int64(-1)
60+ for i := range count {
61+ fd += 1 + int64(int32(le.Uint32(deltas[i*4:])))
62+ id := uint32(fd)
63+ if _, ok := want[id]; !ok {
64+ continue
65+ }
66+ if _, seen := out[id]; seen {
67+ continue
68+ }
69+ var k [16]byte
70+ copy(k[:], ckeys[i*16:])
71+ out[id] = k
72+ }
73+ }
74+ p += size
75+ }
76+ return out, nil
77+}
@@ -0,0 +1,77 @@
1+package casc
2+
3+import (
4+ "encoding/binary"
5+ "errors"
6+ "fmt"
7+)
8+
9+// ErrUnsupportedRoot means the root file is not a TSFM v2 root.
10+var ErrUnsupportedRoot = errors.New("casc: unsupported root format")
11+
12+const (
13+ rootBlockHeaderSize = 17
14+ flagNoNameHash = 0x10000000
15+)
16+
17+func rootContentFlags(unk1, unk2 uint32, unk3 uint8) uint32 {
18+ return unk1 | unk2 | uint32(unk3)<<17
19+}
20+
21+// resolveRoot returns the content keys of the wanted FileDataIDs whose block
22+// matches localeMask. The first match per FDID wins.
23+func resolveRoot(buf []byte, want map[uint32]struct{}, localeMask uint32) (map[uint32][16]byte, error) {
24+ if len(buf) < 20 {
25+ return nil, fmt.Errorf("%w: truncated header", ErrUnsupportedRoot)
26+ }
27+ if string(buf[:4]) != "TSFM" {
28+ return nil, fmt.Errorf("%w: magic %q", ErrUnsupportedRoot, buf[:4])
29+ }
30+ le := binary.LittleEndian
31+ hsize := le.Uint32(buf[4:])
32+ version := le.Uint32(buf[8:])
33+ if hsize != 24 || version != 2 {
34+ return nil, fmt.Errorf("%w: header size %d, version %d", ErrUnsupportedRoot, hsize, version)
35+ }
36+ total, named := le.Uint32(buf[12:]), le.Uint32(buf[16:])
37+ out := make(map[uint32][16]byte, len(want))
38+ p := int(hsize)
39+ for blk := 0; p < len(buf); blk++ {
40+ if p+rootBlockHeaderSize > len(buf) {
41+ return nil, fmt.Errorf("casc: root block %d: truncated header", blk)
42+ }
43+ count := int(le.Uint32(buf[p:]))
44+ locale := le.Uint32(buf[p+4:])
45+ flags := rootContentFlags(le.Uint32(buf[p+8:]), le.Uint32(buf[p+12:]), buf[p+16])
46+ p += rootBlockHeaderSize
47+ size := count * (4 + 16)
48+ if total != named && flags&flagNoNameHash != 0 {
49+ // no name hashes
50+ } else {
51+ size += count * 8
52+ }
53+ if count < 0 || size < 0 || p+size > len(buf) {
54+ return nil, fmt.Errorf("casc: root block %d: truncated (%d records)", blk, count)
55+ }
56+ if locale&localeMask != 0 && len(want) > 0 {
57+ deltas := buf[p : p+count*4]
58+ ckeys := buf[p+count*4 : p+count*20]
59+ fd := int64(-1)
60+ for i := range count {
61+ fd += 1 + int64(int32(le.Uint32(deltas[i*4:])))
62+ id := uint32(fd)
63+ if _, ok := want[id]; !ok {
64+ continue
65+ }
66+ if _, seen := out[id]; seen {
67+ continue
68+ }
69+ var k [16]byte
70+ copy(k[:], ckeys[i*16:])
71+ out[id] = k
72+ }
73+ }
74+ p += size
75+ }
76+ return out, nil
77+}
A internal/casc/root_test.go +99 -0
@@ -0,0 +1,99 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "errors"
7+ "strings"
8+ "testing"
9+
10+ "github.com/bnema/forever-db/internal/testutil"
11+)
12+
13+const enUS, frFR = 0x2, 0x10
14+
15+func key(b byte) [16]byte { return [16]byte{b, b, b} }
16+
17+func set(ids ...uint32) map[uint32]struct{} {
18+ m := map[uint32]struct{}{}
19+ for _, id := range ids {
20+ m[id] = struct{}{}
21+ }
22+ return m
23+}
24+
25+func TestResolveRoot(t *testing.T) {
26+ buf := testutil.BuildRoot([]testutil.RootBlock{
27+ {LocaleFlags: frFR, FDIDs: []uint32{5, 100}, CKeys: [][16]byte{key(0xF5), key(0xF1)}},
28+ {LocaleFlags: enUS | frFR, FDIDs: []uint32{0, 5, 1302850}, CKeys: [][16]byte{key(1), key(2), key(3)}, NoNames: true},
29+ {LocaleFlags: enUS, FDIDs: []uint32{5, 100, 200}, CKeys: [][16]byte{key(9), key(4), key(5)}},
30+ })
31+ got, err := resolveRoot(buf, set(0, 5, 100, 1302850, 999), enUS)
32+ if err != nil {
33+ t.Fatal(err)
34+ }
35+ want := map[uint32][16]byte{0: key(1), 5: key(2), 100: key(4), 1302850: key(3)}
36+ if len(got) != len(want) {
37+ t.Fatalf("got %v", got)
38+ }
39+ for id, k := range want {
40+ if got[id] != k {
41+ t.Fatalf("fdid %d: %x want %x", id, got[id], k)
42+ }
43+ }
44+ if got, _ := resolveRoot(buf, nil, enUS); len(got) != 0 {
45+ t.Fatalf("nil want: %v", got)
46+ }
47+}
48+
49+func TestRootNamedBlockWhenAllNoNames(t *testing.T) {
50+ // total == named: hashes are present even with the flag set.
51+ buf := testutil.BuildRoot([]testutil.RootBlock{{LocaleFlags: enUS, FDIDs: []uint32{7}, CKeys: [][16]byte{key(7)}}})
52+ binary.LittleEndian.PutUint32(buf[24+8:], flagNoNameHash)
53+ got, err := resolveRoot(buf, set(7), enUS)
54+ if err != nil || got[7] != key(7) {
55+ t.Fatalf("got %v, %v", got, err)
56+ }
57+}
58+
59+func TestRootContentFlags(t *testing.T) {
60+ if f := rootContentFlags(0x1, 0x8, 0x3); f != 0x1|0x8|0x3<<17 {
61+ t.Fatalf("flags = %#x", f)
62+ }
63+}
64+
65+func TestRootErrors(t *testing.T) {
66+ good := testutil.BuildRoot([]testutil.RootBlock{{LocaleFlags: enUS, FDIDs: []uint32{1, 2}, CKeys: [][16]byte{key(1), key(2)}}})
67+ mod := func(off int, v uint32) []byte {
68+ b := bytes.Clone(good)
69+ binary.LittleEndian.PutUint32(b[off:], v)
70+ return b
71+ }
72+ for name, buf := range map[string][]byte{
73+ "magic": append([]byte("MFST"), good[4:]...),
74+ "hsize": mod(4, 28),
75+ "version": mod(8, 1),
76+ } {
77+ if _, err := resolveRoot(buf, set(1), enUS); !errors.Is(err, ErrUnsupportedRoot) {
78+ t.Fatalf("%s: err = %v", name, err)
79+ }
80+ }
81+ for name, buf := range map[string][]byte{
82+ "records": good[:len(good)-1],
83+ "header": append(bytes.Clone(good), 1, 2, 3),
84+ } {
85+ if _, err := resolveRoot(buf, set(1), enUS); err == nil || !strings.Contains(err.Error(), "truncated") || errors.Is(err, ErrUnsupportedRoot) {
86+ t.Fatalf("%s: err = %v", name, err)
87+ }
88+ }
89+}
90+
91+func FuzzResolveRoot(f *testing.F) {
92+ f.Add(testutil.BuildRoot([]testutil.RootBlock{
93+ {LocaleFlags: enUS, FDIDs: []uint32{1, 5}, CKeys: [][16]byte{key(1), key(2)}},
94+ {LocaleFlags: enUS, FDIDs: []uint32{9}, CKeys: [][16]byte{key(3)}, NoNames: true},
95+ }))
96+ f.Fuzz(func(t *testing.T, data []byte) {
97+ resolveRoot(data, set(1, 5, 9), enUS)
98+ })
99+}
@@ -0,0 +1,99 @@
1+package casc
2+
3+import (
4+ "bytes"
5+ "encoding/binary"
6+ "errors"
7+ "strings"
8+ "testing"
9+
10+ "github.com/bnema/forever-db/internal/testutil"
11+)
12+
13+const enUS, frFR = 0x2, 0x10
14+
15+func key(b byte) [16]byte { return [16]byte{b, b, b} }
16+
17+func set(ids ...uint32) map[uint32]struct{} {
18+ m := map[uint32]struct{}{}
19+ for _, id := range ids {
20+ m[id] = struct{}{}
21+ }
22+ return m
23+}
24+
25+func TestResolveRoot(t *testing.T) {
26+ buf := testutil.BuildRoot([]testutil.RootBlock{
27+ {LocaleFlags: frFR, FDIDs: []uint32{5, 100}, CKeys: [][16]byte{key(0xF5), key(0xF1)}},
28+ {LocaleFlags: enUS | frFR, FDIDs: []uint32{0, 5, 1302850}, CKeys: [][16]byte{key(1), key(2), key(3)}, NoNames: true},
29+ {LocaleFlags: enUS, FDIDs: []uint32{5, 100, 200}, CKeys: [][16]byte{key(9), key(4), key(5)}},
30+ })
31+ got, err := resolveRoot(buf, set(0, 5, 100, 1302850, 999), enUS)
32+ if err != nil {
33+ t.Fatal(err)
34+ }
35+ want := map[uint32][16]byte{0: key(1), 5: key(2), 100: key(4), 1302850: key(3)}
36+ if len(got) != len(want) {
37+ t.Fatalf("got %v", got)
38+ }
39+ for id, k := range want {
40+ if got[id] != k {
41+ t.Fatalf("fdid %d: %x want %x", id, got[id], k)
42+ }
43+ }
44+ if got, _ := resolveRoot(buf, nil, enUS); len(got) != 0 {
45+ t.Fatalf("nil want: %v", got)
46+ }
47+}
48+
49+func TestRootNamedBlockWhenAllNoNames(t *testing.T) {
50+ // total == named: hashes are present even with the flag set.
51+ buf := testutil.BuildRoot([]testutil.RootBlock{{LocaleFlags: enUS, FDIDs: []uint32{7}, CKeys: [][16]byte{key(7)}}})
52+ binary.LittleEndian.PutUint32(buf[24+8:], flagNoNameHash)
53+ got, err := resolveRoot(buf, set(7), enUS)
54+ if err != nil || got[7] != key(7) {
55+ t.Fatalf("got %v, %v", got, err)
56+ }
57+}
58+
59+func TestRootContentFlags(t *testing.T) {
60+ if f := rootContentFlags(0x1, 0x8, 0x3); f != 0x1|0x8|0x3<<17 {
61+ t.Fatalf("flags = %#x", f)
62+ }
63+}
64+
65+func TestRootErrors(t *testing.T) {
66+ good := testutil.BuildRoot([]testutil.RootBlock{{LocaleFlags: enUS, FDIDs: []uint32{1, 2}, CKeys: [][16]byte{key(1), key(2)}}})
67+ mod := func(off int, v uint32) []byte {
68+ b := bytes.Clone(good)
69+ binary.LittleEndian.PutUint32(b[off:], v)
70+ return b
71+ }
72+ for name, buf := range map[string][]byte{
73+ "magic": append([]byte("MFST"), good[4:]...),
74+ "hsize": mod(4, 28),
75+ "version": mod(8, 1),
76+ } {
77+ if _, err := resolveRoot(buf, set(1), enUS); !errors.Is(err, ErrUnsupportedRoot) {
78+ t.Fatalf("%s: err = %v", name, err)
79+ }
80+ }
81+ for name, buf := range map[string][]byte{
82+ "records": good[:len(good)-1],
83+ "header": append(bytes.Clone(good), 1, 2, 3),
84+ } {
85+ if _, err := resolveRoot(buf, set(1), enUS); err == nil || !strings.Contains(err.Error(), "truncated") || errors.Is(err, ErrUnsupportedRoot) {
86+ t.Fatalf("%s: err = %v", name, err)
87+ }
88+ }
89+}
90+
91+func FuzzResolveRoot(f *testing.F) {
92+ f.Add(testutil.BuildRoot([]testutil.RootBlock{
93+ {LocaleFlags: enUS, FDIDs: []uint32{1, 5}, CKeys: [][16]byte{key(1), key(2)}},
94+ {LocaleFlags: enUS, FDIDs: []uint32{9}, CKeys: [][16]byte{key(3)}, NoNames: true},
95+ }))
96+ f.Fuzz(func(t *testing.T, data []byte) {
97+ resolveRoot(data, set(1, 5, 9), enUS)
98+ })
99+}
A internal/casc/storage.go +166 -0
A internal/casc/storage_test.go +83 -0
A internal/db2/db2.go +95 -0
A internal/db2/db2_test.go +36 -0
A internal/dbd/dbd.go +282 -0
A internal/dbd/dbd_test.go +179 -0
A internal/defs/data/README.md +23 -0
A internal/defs/data/forever.json.gz +0 -0 binary file: no text diff
A internal/defs/defs.go +474 -0
A internal/defs/defs_test.go +308 -0
A internal/defs/generate.go +224 -0
A internal/defs/generate_test.go +186 -0
A internal/export/export.go +418 -0
A internal/export/export_test.go +406 -0
A internal/export/integration_test.go +124 -0
A internal/export/keys.go +94 -0
A internal/export/keys_test.go +154 -0
A internal/export/snapshot_test.go +78 -0
A internal/export/status.go +141 -0
A internal/export/status_test.go +138 -0
A internal/export/table.go +92 -0
A internal/export/writer.go +270 -0
A internal/export/writer_test.go +289 -0
A internal/fsutil/fsutil.go +51 -0
A internal/fsutil/fsutil_test.go +54 -0
A internal/hotfix/apply.go +181 -0
A internal/hotfix/apply_test.go +125 -0
A internal/hotfix/consistency_test.go +46 -0
A internal/hotfix/integration_test.go +303 -0
A internal/hotfix/reader.go +105 -0
A internal/hotfix/reader_test.go +114 -0
A internal/install/install.go +166 -0
A internal/install/install_test.go +129 -0
A internal/salsa20/salsa20.go +92 -0
A internal/salsa20/salsa20_test.go +98 -0
A internal/schema/schema.go +158 -0
A internal/schema/schema_test.go +136 -0
A internal/sources/manifest.go +74 -0
A internal/sources/manifest_test.go +113 -0
A internal/sources/sources.go +475 -0
A internal/sources/sources_test.go +381 -0
A internal/tactkeys/tactkeys.go +104 -0
A internal/tactkeys/tactkeys_test.go +78 -0
A internal/testutil/blte.go +96 -0
A internal/testutil/casc.go +93 -0
A internal/testutil/encoding.go +62 -0
A internal/testutil/hotfix.go +40 -0
A internal/testutil/install.go +84 -0
A internal/testutil/root.go +56 -0
A internal/testutil/wdc5.go +194 -0
A internal/wdc5/decode.go +39 -0
A internal/wdc5/dense.go +390 -0
A internal/wdc5/dense_test.go +410 -0
A internal/wdc5/header.go +256 -0
A internal/wdc5/header_test.go +163 -0
A internal/wdc5/integration_test.go +277 -0
A internal/wdc5/sparse.go +153 -0
A internal/wdc5/sparse_test.go +114 -0
A main.go +7 -0

Comments00 unresolved

    no comments yet.

    Keyboard shortcuts

    Single-key shortcuts are on. ctrl k and esc work whatever this says.

    ctrl k :
    go to a section, branch, tag, file or repository
    ?
    this list
    j k
    move the row cursor down / up
    enter
    open the row under the cursor; on Files, a directory opens or closes in place
    ↑ ↓ ← → home end
    in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
    l h
    on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. On pages with a side panel: into the panel (on a merge request, its files) / back to the content; there j k move between its controls
    g g G
    first / last row
    /
    filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
    b
    switch branch or tag
    g s g f g c g b g m g i g r g a
    tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
    g h
    home
    w
    wide mode: use the whole width of the screen, or not (remembered)
    y
    copy a permalink pinned to the commit; in a file, click a line number to select it, shift-click for a range
    d u x
    diff: split / unified / collapse or expand all
    e E
    diff: the whole file in view / every file, with the lines the hunks hide
    n
    merge request: next note in the diff
    l
    merge request: the list of files (j k move, enter opens, esc back)
    M
    merge request: the merge menu; there 1–3 pick the mode, D deletes the branch, enter merges
    R
    merge request: mark the head read
    esc
    close a dialog, leave a field

    Branches 2

    Tags 1

    ↑↓ moveenter openesc close