json: --json output and libsfile linkable library
- sfile --json: one JSON object per file (JSON Lines) carrying format, offsets, decoded fields and geotags when present; default CLI output byte-identical (verified against the pre-refactor binary). - libsfile: src/sfile.h + src/sfile_lib.c expose the decoder (sfile_decode_file/mem, sfile_result_to_json, format table introspection); make lib builds libsfile.a and libsfile.so.1.1.0, make install installs them plus the header. - tests/test_json.py: JSON parses and matches the text table on the same files (make test-json); tests/test_library.c + test_lib.sh: static and shared link test (make test-lib).
This commit is contained in:
1 parent
b21573d47d
commit
a2106045a6
12 files changed
+2062
-267
No files matched your search
@@ -11,3 +11,8 @@ LOOP_STATUS
|
||||
loop.log
|
||||
driver.pid
|
||||
scar
|
||||
|
||||
libsfile.a
|
||||
libsfile.so
|
||||
libsfile.so.1
|
||||
libsfile.so.*
|
||||
@@ -3,7 +3,13 @@ CC ?= gcc
|
||||
CFLAGS ?= -O2 -Wall -Wextra -std=c11
|
||||
PREFIX ?= /usr/local
|
||||
|
||||
SRC = src/sfile.c src/geotag.c
|
||||
SRC = src/sfile.c
|
||||
LIB_SRC = src/sfile_lib.c src/geotag.c
|
||||
LIB_HDR = src/sfile.h src/geotag.h
|
||||
LIB_OBJ = sfile_lib.o geotag.o
|
||||
LIB_A = libsfile.a
|
||||
LIB_SO = libsfile.so.1.1.0
|
||||
LIB_SONAME = libsfile.so.1
|
||||
BIN = sfile
|
||||
GEN = tools/gen_formats.py
|
||||
TABLE = src/formats.h src/formats.json
|
||||
@@ -11,10 +17,32 @@ TABLE = src/formats.h src/formats.json
|
||||
SCAR_SRC = src/scar.c
|
||||
SCAR_BIN = scar
|
||||
|
||||
all: $(BIN) $(SCAR_BIN)
|
||||
all: $(BIN) $(SCAR_BIN) lib
|
||||
|
||||
$(BIN): $(SRC) src/formats.h
|
||||
$(CC) $(CFLAGS) -o $@ $(SRC)
|
||||
$(BIN): $(SRC) $(LIB_OBJ) src/formats.h
|
||||
$(CC) $(CFLAGS) -o $@ $(SRC) $(LIB_OBJ)
|
||||
|
||||
# libsfile — the decode engine as a linkable library (see docs/library.md).
|
||||
# The CLI links the same objects, so library and CLI results agree.
|
||||
# geotag.c is part of the library: sfile_decode_file fills the geotag
|
||||
# fields of sfile_result via geotag_scan().
|
||||
lib: $(LIB_A) libsfile.so
|
||||
|
||||
sfile_lib.o: src/sfile_lib.c $(LIB_HDR) src/formats.h
|
||||
$(CC) $(CFLAGS) -c -o $@ src/sfile_lib.c
|
||||
|
||||
geotag.o: src/geotag.c src/geotag.h
|
||||
$(CC) $(CFLAGS) -c -o $@ src/geotag.c
|
||||
|
||||
$(LIB_A): $(LIB_OBJ)
|
||||
ar rcs $@ $(LIB_OBJ)
|
||||
|
||||
$(LIB_SO): $(LIB_SRC) $(LIB_HDR) src/formats.h
|
||||
$(CC) $(CFLAGS) -fPIC -shared -Wl,-soname,$(LIB_SONAME) -o $@ $(LIB_SRC)
|
||||
|
||||
libsfile.so: $(LIB_SO)
|
||||
ln -sf $(LIB_SO) $(LIB_SONAME)
|
||||
ln -sf $(LIB_SONAME) libsfile.so
|
||||
|
||||
# scar — file carver built on sfile's format table (src/scar.c).
|
||||
# Links zlib: gzip members are sized by inflating the stream.
|
||||
@@ -39,16 +67,28 @@ table: $(GEN) tools/all_formats.cpp
|
||||
test: $(BIN)
|
||||
./tests/run_tests.sh
|
||||
|
||||
test-json: $(BIN)
|
||||
python3 tests/test_json.py
|
||||
|
||||
test-lib: lib
|
||||
./tests/test_lib.sh
|
||||
|
||||
test-geotag: $(BIN)
|
||||
python3 tests/geotag/run_geotag_tests.py
|
||||
|
||||
test-scar: $(SCAR_BIN)
|
||||
python3 tests/test_scar.py
|
||||
|
||||
install: $(BIN) $(SCAR_BIN)
|
||||
mkdir -p $(PREFIX)/bin
|
||||
install: $(BIN) $(SCAR_BIN) lib
|
||||
mkdir -p $(PREFIX)/bin $(PREFIX)/lib $(PREFIX)/include
|
||||
cp $(BIN) $(PREFIX)/bin/
|
||||
cp $(SCAR_BIN) $(PREFIX)/bin/
|
||||
cp $(LIB_A) $(PREFIX)/lib/
|
||||
cp -P $(LIB_SO) $(LIB_SONAME) libsfile.so $(PREFIX)/lib/
|
||||
cp $(LIB_HDR) $(PREFIX)/include/
|
||||
chmod 755 $(PREFIX)/bin/$(BIN) $(PREFIX)/bin/$(SCAR_BIN)
|
||||
|
||||
clean:
|
||||
rm -f $(BIN) $(SCAR_BIN) stag sgeo *.o
|
||||
rm -f $(BIN) $(SCAR_BIN) stag sgeo *.o $(LIB_A) $(LIB_SO) $(LIB_SONAME) libsfile.so
|
||||
|
||||
.PHONY: all table test test-scar install clean
|
||||
.PHONY: all table test test-json test-lib test-geotag test-scar install clean lib
|
||||
@@ -183,11 +183,15 @@ samples, gzip files saved as .bson) are deleted, not tested.
|
||||
**Table-driven, generic engine.** All per-format knowledge lives in the
|
||||
generated table `src/formats.h` (one entry per format: extension, name,
|
||||
magic bytes + offset, field list of name/offset/size/kind, endianness).
|
||||
The engine (`src/sfile.c`) contains no per-format decode logic — it walks
|
||||
the table, matches magic, and formats the fields. A format is never
|
||||
"guessed": the decode is derived from the collected reference code, a
|
||||
published format spec (the hand overrides), or a verified sample file,
|
||||
and the derivation is recorded per format in `src/formats.json`.
|
||||
The engine (`src/sfile_lib.c`, shipped as `libsfile` — see below)
|
||||
contains no per-format decode logic — it walks the table, matches
|
||||
magic, and formats the fields. The `sfile` CLI (`src/sfile.c`) is a
|
||||
thin wrapper over the library: it parses arguments and prints the
|
||||
library's `sfile_result`, as the human table or as JSON. A format is
|
||||
never "guessed": the decode is derived from the collected reference
|
||||
code, a published format spec (the hand overrides), or a verified
|
||||
sample file, and the derivation is recorded per format in
|
||||
`src/formats.json`.
|
||||
|
||||
**Identification order.** Longest magic match wins. Several formats share
|
||||
a magic (all ZIP-based formats share `PK\x03\x04`; all RIFF formats share
|
||||
@@ -207,9 +211,13 @@ first line.
|
||||
|
||||
```
|
||||
make # builds ./sfile and ./scar (gcc, -O2 -Wall -Wextra, no exotic deps)
|
||||
make lib # builds libsfile.a + libsfile.so.1.1.0 (see below)
|
||||
make stag sgeo # builds the geotag tools (see below)
|
||||
make table # regenerate src/formats.h from tools/all_formats.cpp
|
||||
make test # run the per-format test loop over samples/
|
||||
make test-json # JSON output tests (parses + matches the text table)
|
||||
make test-lib # library link test, static and shared
|
||||
make test-geotag # geotag decoder tests (26 fixtures)
|
||||
make install # install to /usr/local/bin (PREFIX=... to change)
|
||||
```
|
||||
|
||||
@@ -217,12 +225,51 @@ make install # install to /usr/local/bin (PREFIX=... to change)
|
||||
## Usage
|
||||
|
||||
```
|
||||
sfile <file> identify + decode the header
|
||||
sfile <file>... identify + decode the header (several files OK)
|
||||
sfile --json <file>... same decode as JSON, one object per file (one per line)
|
||||
sfile --list list all known formats (task, extension, name)
|
||||
sfile --help
|
||||
sfile --version
|
||||
```
|
||||
|
||||
Exit codes: 0 identified, 1 usage error, 2 file unreadable, 3 unknown format.
|
||||
With several files the worst code wins (unreadable beats unknown).
|
||||
|
||||
## JSON output
|
||||
|
||||
`sfile --json` prints the same decode as JSON (one compact object per
|
||||
file, one per line): format, offsets, decoded fields, and `geotags`
|
||||
when the file carries a location (from `geotag_scan()` — EXIF GPS,
|
||||
XMP, QuickTime, GeoTIFF, EXR, PSD, CR3). See `docs/json.md` for the
|
||||
schema and real examples.
|
||||
|
||||
```sh
|
||||
$ sfile --json photo.png
|
||||
{"file":"photo.png","size":29,"identified":true,"format":{"task":564,"ext":".PNG","name":"PNG image","kind":"binary","endian":"big"},"identified_by":"magic","magic":{"bytes":"89 50 4e 47 0d 0a 1a 0a","offset":0},"header":{"endian":"big","fields":[{"offset":0,"size":8,"name":"signature","type":"bytes","value":"89 50 4e 47 0d 0a 1a 0a"},{"offset":8,"size":4,"name":"ihdr_length","type":"u32","value":13},{"offset":12,"size":4,"name":"ihdr_type","type":"ascii","value":"IHDR"},{"offset":16,"size":4,"name":"width","type":"u32","value":800},{"offset":20,"size":4,"name":"height","type":"u32","value":600},{"offset":24,"size":1,"name":"bit_depth","type":"u8","value":8},{"offset":25,"size":1,"name":"color_type","type":"u8","value":2},{"offset":26,"size":1,"name":"compression","type":"u8","value":0},{"offset":27,"size":1,"name":"filter","type":"u8","value":0},{"offset":28,"size":1,"name":"interlace","type":"u8","value":0}]},"geotags":[]}
|
||||
```
|
||||
|
||||
## Library mode: libsfile
|
||||
|
||||
The decode engine is also a linkable C library — `make lib` builds
|
||||
`libsfile.a` and `libsfile.so.1.1.0`, `make install` puts them in
|
||||
`$(PREFIX)/lib` with `sfile.h` + `geotag.h` in `$(PREFIX)/include`.
|
||||
Link it instead of shelling out to the `sfile` binary:
|
||||
|
||||
```c
|
||||
#include "sfile.h"
|
||||
sfile_result r;
|
||||
sfile_decode_file("photo.png", &r); /* 0 identified, 2 unreadable, 3 unknown */
|
||||
printf("%s, task %d, %d fields\n", r.name, r.task, r.nfields);
|
||||
sfile_free_result(&r);
|
||||
```
|
||||
|
||||
```sh
|
||||
gcc prog.c -lsfile # shared (after make install)
|
||||
gcc prog.c libsfile.a # static
|
||||
```
|
||||
|
||||
See `docs/library.md` for the full API, a worked example with real
|
||||
output, and the tests (`make test-lib`).
|
||||
|
||||
## Testing
|
||||
|
||||
@@ -250,7 +297,11 @@ values) is fixed in `tools/overrides.json` and the table regenerated.
|
||||
|
||||
```
|
||||
sfile/
|
||||
src/sfile.c the engine (generic; no per-format code)
|
||||
src/sfile.c the CLI (thin wrapper over libsfile)
|
||||
src/sfile.h libsfile public API
|
||||
src/sfile_lib.c the decode engine (generic; no per-format code)
|
||||
src/geotag.c geotag decoders (EXIF/XMP/QuickTime/GeoTIFF/EXR/PSD/CR3)
|
||||
src/geotag.h geotag_scan() / GeoResult API
|
||||
src/scar.c file carver built on the format table
|
||||
src/stag.c geotag CSV tabulator (see below)
|
||||
src/sgeo.c geotag map plotter (see below)
|
||||
@@ -266,9 +317,15 @@ sfile/
|
||||
tools/extract_cpp.py extracts all_formats.cpp from the raw pages
|
||||
tests/run_tests.py the per-format test loop
|
||||
tests/run_tests.sh the stag/sgeo test suite (8 checks, fake sfile + local tile server)
|
||||
tests/test_json.py --json tests: parses + matches the text table (make test-json)
|
||||
tests/test_lib.sh library link test, static + shared (make test-lib)
|
||||
tests/test_library.c link-test program (decodes via the public API only)
|
||||
tests/make_fixtures.py synthetic fixtures shared by the JSON/library tests
|
||||
tests/test_scar.py synthetic-image test for scar (make test-scar)
|
||||
tests/results.json latest test results
|
||||
docs/scar.md scar usage, carving decisions, limits
|
||||
docs/json.md --json output: schema, geotags, examples
|
||||
docs/library.md libsfile: API, building, example, tests
|
||||
docs/stag-sgeo.md stag/sgeo usage, CSV format, map + attribution, network dependency
|
||||
docs/geotag-contract.md the sfile <-> stag/sgeo geotag seam (what sfile prints, what the client accepts)
|
||||
samples/ one real sample file per format + manifests
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
# sfile --json — machine-readable decode output
|
||||
|
||||
`sfile --json <file>...` prints the same decode as the human-readable
|
||||
table, as JSON: **one compact JSON object per file, one per line**
|
||||
(JSON Lines). Each line parses on its own; with several files the
|
||||
output is one object per line, in argument order.
|
||||
|
||||
```sh
|
||||
sfile --json photo.png
|
||||
sfile --json *.png > decodes.jsonl # one object per file
|
||||
```
|
||||
|
||||
Exit codes are unchanged from the text mode: 0 identified, 1 usage
|
||||
error, 2 file unreadable, 3 unknown format. With several files the
|
||||
worst code wins (unreadable beats unknown). An unreadable file still
|
||||
produces a JSON object on stdout (with `size: null` and an `error`
|
||||
string); the `perror`-style message also goes to stderr, so stdout
|
||||
stays pure JSON.
|
||||
|
||||
## Example: a PNG header
|
||||
|
||||
The CLI emits compact one-line JSON; the object below is the real
|
||||
output of `sfile --json` on a 29-byte PNG, reformatted for reading:
|
||||
|
||||
```json
|
||||
{
|
||||
"file": "/tmp/fx/sample.png",
|
||||
"size": 29,
|
||||
"identified": true,
|
||||
"format": {"task": 564, "ext": ".PNG", "name": "PNG image",
|
||||
"kind": "binary", "endian": "big"},
|
||||
"identified_by": "magic",
|
||||
"magic": {"bytes": "89 50 4e 47 0d 0a 1a 0a", "offset": 0},
|
||||
"header": {
|
||||
"endian": "big",
|
||||
"fields": [
|
||||
{"offset": 0, "size": 8, "name": "signature", "type": "bytes",
|
||||
"value": "89 50 4e 47 0d 0a 1a 0a"},
|
||||
{"offset": 8, "size": 4, "name": "ihdr_length", "type": "u32",
|
||||
"value": 13},
|
||||
{"offset": 12, "size": 4, "name": "ihdr_type", "type": "ascii",
|
||||
"value": "IHDR"},
|
||||
{"offset": 16, "size": 4, "name": "width", "type": "u32",
|
||||
"value": 800},
|
||||
{"offset": 20, "size": 4, "name": "height", "type": "u32",
|
||||
"value": 600},
|
||||
{"offset": 24, "size": 1, "name": "bit_depth", "type": "u8",
|
||||
"value": 8},
|
||||
{"offset": 25, "size": 1, "name": "color_type", "type": "u8",
|
||||
"value": 2},
|
||||
{"offset": 26, "size": 1, "name": "compression", "type": "u8",
|
||||
"value": 0},
|
||||
{"offset": 27, "size": 1, "name": "filter", "type": "u8",
|
||||
"value": 0},
|
||||
{"offset": 28, "size": 1, "name": "interlace", "type": "u8",
|
||||
"value": 0}
|
||||
]
|
||||
},
|
||||
"geotags": []
|
||||
}
|
||||
```
|
||||
|
||||
Compare with the text mode on the same file: the field values agree
|
||||
(`width` 800, `ihdr_type` `"IHDR"`, …) — JSON is a re-encoding of the
|
||||
same decode, not a second implementation. `tests/test_json.py`
|
||||
checks this parity on every fixture (`make test-json`).
|
||||
|
||||
## Schema
|
||||
|
||||
| key | when present | meaning |
|
||||
|---|---|---|
|
||||
| `file` | always | path as given on the command line |
|
||||
| `size` | always | file size in bytes, or `null` when unreadable |
|
||||
| `identified` | always | `true` when a format was identified |
|
||||
| `error` | `status != 0` | human-readable reason (`"unknown format (no magic match, no known extension)"`, or the `strerror` text for unreadable files) |
|
||||
| `format` | identified | `task` (fileformat task number), `ext`, `name`, `kind` (`"binary"` / `"text"` / `"unknown"`), `endian` (`"big"` / `"little"`) |
|
||||
| `identified_by` | identified | `"magic"` or `"extension"` |
|
||||
| `magic` | magic present | `bytes` (space-separated lowercase hex), `offset` |
|
||||
| `other_candidates` | >1 format shares the magic | the other formats' `ext` + `task` (the chosen format excluded) |
|
||||
| `header` | binary format with a layout | `endian` + `fields[]` |
|
||||
| `document` | text format | see below |
|
||||
| `note` | binary format, no layout | `"no header layout derived (derivation: magic-only)"` or `"(derivation: unknown)"` |
|
||||
| `hexdump` | unknown, or no layout | first 64 bytes, space-separated lowercase hex |
|
||||
| `geotags` | format has a geotagging mechanism | array of locations (empty when none found); omitted when the format has no mechanism at all |
|
||||
|
||||
### Field objects
|
||||
|
||||
`{"offset", "size", "name", "type", "value"}` — `offset`/`size` in
|
||||
bytes, `name` from the format table, `type` one of `u8 u16 u32 u64 i8
|
||||
i16 i32 i64 f32 f64 ascii bytes`.
|
||||
|
||||
`value` is a JSON number for numeric fields (integers exact; floats
|
||||
at full `%.17g` precision, so a latitude survives the round-trip —
|
||||
the text table's `%g` shows only 6 significant digits), a JSON string
|
||||
for `ascii` (unquoted — the text table quotes it: `"IHDR"`) and for
|
||||
`bytes` (space-separated hex, no trailing space).
|
||||
|
||||
A field that runs past the bytes read (empty/truncated file) has
|
||||
`"value": null` and `"unavailable": "beyond header window / EOF"` —
|
||||
the same words the text table prints.
|
||||
|
||||
### Document objects (text formats)
|
||||
|
||||
```json
|
||||
{"type": "xml", "declaration": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
||||
"root_element": "catalog", "version": "2.0"}
|
||||
{"type": "json", "first_key": "name"}
|
||||
{"type": "text", "first_line": "Hello, sfile."}
|
||||
```
|
||||
|
||||
Keys that were not found are omitted (a JSON array has just
|
||||
`{"type": "json"}`; a text file always has `first_line`, possibly
|
||||
`""`).
|
||||
|
||||
### Geotag objects
|
||||
|
||||
`geotags` comes from `geotag_scan()` (`src/geotag.c`) — the same
|
||||
decoders behind the text mode's `Geotagging:` section (EXIF GPS,
|
||||
XMP, QuickTime/ISO 6709, GeoTIFF, EXR, PSD, CR3, …). Each entry:
|
||||
|
||||
```json
|
||||
{"source": "EXIF GPS IFD (JPEG APP1 segment)",
|
||||
"latitude": 37.7749, "longitude": -122.41940000000001,
|
||||
"altitude_m": 10, "datum": "WGS-84",
|
||||
"datetime_utc": "2026-12-01 12:34:56"}
|
||||
```
|
||||
|
||||
`source`, `latitude`, `longitude` are always present;
|
||||
`altitude_m`, `datum`, `datetime_utc` only when the decoder found
|
||||
them. A file can carry several locations (an MP4 with two
|
||||
QuickTime sources yields two entries). `geotags: []` means the
|
||||
format has a mechanism but this file carries no location; the key
|
||||
is omitted entirely when the format has no mechanism. Header
|
||||
fields merely *named* `latitude`/`longitude` (e.g. SPS track
|
||||
files, task 678) are decoded as ordinary fields and are **not**
|
||||
geotags — they do not produce a `geotags` key.
|
||||
|
||||
## Example: geotags, shared magic, unknown, unreadable
|
||||
|
||||
A JPEG with EXIF GPS (the tail of the real output of
|
||||
`sfile --json tests/geotag/test-gps.jpg`):
|
||||
|
||||
```json
|
||||
"geotags": [
|
||||
{
|
||||
"source": "EXIF GPS IFD (JPEG APP1 segment)",
|
||||
"latitude": 37.7749,
|
||||
"longitude": -122.41940000000001,
|
||||
"altitude_m": 10,
|
||||
"datum": "WGS-84",
|
||||
"datetime_utc": "2026-12-01 12:34:56"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
The text mode prints the same location as:
|
||||
|
||||
```
|
||||
Geotagging:
|
||||
source: EXIF GPS IFD (JPEG APP1 segment)
|
||||
gps_latitude: 37.774900 (37°46'29.64"N)
|
||||
gps_longitude: -122.419400 (122°25'09.84"W)
|
||||
gps_altitude_m: 10.000 (above sea level)
|
||||
gps_datum: WGS-84
|
||||
gps_datetime_utc: 2026-12-01 12:34:56
|
||||
```
|
||||
|
||||
An MP4 with two QuickTime location sources
|
||||
(`tests/geotag/test-gps.mp4`) yields two entries — same
|
||||
coordinates, different altitudes:
|
||||
|
||||
```json
|
||||
"geotags": [
|
||||
{"source": "QuickTime location (moov/udta (c)xyz atom)",
|
||||
"latitude": 37.7749, "longitude": -122.4194,
|
||||
"altitude_m": 10, "datum": "WGS-84 (ISO 6709 default)"},
|
||||
{"source": "QuickTime location (moov/udta/meta com.apple.quicktime.location.ISO6709)",
|
||||
"latitude": 37.7749, "longitude": -122.4194,
|
||||
"altitude_m": 30, "datum": "WGS-84 (ISO 6709 default)"}
|
||||
]
|
||||
```
|
||||
|
||||
An XML file shares its `<?xml` magic with 47 other formats, so the
|
||||
chosen format's disambiguation is recorded:
|
||||
|
||||
```json
|
||||
{"file": "/tmp/fx/doc.xml", "size": 80, "identified": true,
|
||||
"format": {"task": 839, "ext": ".XML", "name": "XML", "kind": "text", "endian": "little"},
|
||||
"identified_by": "magic", "magic": {"bytes": "3c 3f 78 6d 6c", "offset": 0},
|
||||
"other_candidates": [{"ext": ".POM", "task": 565}, {"ext": ".KML", "task": 341},
|
||||
{"ext": ".GPX", "task": 266}],
|
||||
"document": {"type": "xml", "declaration": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
|
||||
"root_element": "catalog", "version": "2.0"}}
|
||||
```
|
||||
|
||||
(`other_candidates` above is abridged — the real output lists all 47.)
|
||||
|
||||
Unknown and unreadable files (exit 3 and 2):
|
||||
|
||||
```json
|
||||
{"file": "/tmp/fx/mystery.zzz", "size": 64, "identified": false,
|
||||
"error": "unknown format (no magic match, no known extension)",
|
||||
"hexdump": "01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40"}
|
||||
{"file": "/tmp/fx/does-not-exist.bin", "size": null, "identified": false,
|
||||
"error": "No such file or directory"}
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/test_json.py` (`make test-json`) builds synthetic fixtures
|
||||
(PNG, SPS, JSON, XML, text, unknown, empty PNG, magic-only
|
||||
WEBM/WAB, missing file) and checks that every `--json` line parses,
|
||||
carries the same facts as the text output on the same file
|
||||
(including the `Geotagging:` section vs the `geotags` array), and
|
||||
exits with the same code. The geotag cases use the real fixtures in
|
||||
`tests/geotag/` (EXIF GPS JPEG, two-result MP4, no-location JPEG).
|
||||
Fixture builder: `tests/make_fixtures.py`.
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
# libsfile — the sfile decode engine as a C library
|
||||
|
||||
The `sfile` CLI is a thin wrapper over `libsfile`: the decode engine
|
||||
(`src/sfile_lib.c`, public API in `src/sfile.h`) plus the geotag
|
||||
decoders (`src/geotag.c`, API in `src/geotag.h`). Other tools (stag,
|
||||
sgeo, scar, …) can link it instead of shelling out to the `sfile`
|
||||
binary — and get exactly the same results the CLI prints, since the
|
||||
CLI consumes the same `sfile_result` struct.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
make lib # libsfile.a + libsfile.so.1.1.0 (+ .so.1/.so links)
|
||||
make # also builds ./sfile and ./scar
|
||||
make install # /usr/local/{bin,lib,include} (PREFIX=... to change)
|
||||
```
|
||||
|
||||
`make install` puts `libsfile.a`, `libsfile.so.1.1.0` (plus the
|
||||
`libsfile.so.1` / `libsfile.so` symlinks) in `$(PREFIX)/lib` and
|
||||
`sfile.h` + `geotag.h` in `$(PREFIX)/include`. The library is new
|
||||
in sfile 1.1.0; `sfile_result` is a plain struct with no ABI
|
||||
stability promise across versions — recompile dependents when
|
||||
upgrading.
|
||||
|
||||
## API (`src/sfile.h`)
|
||||
|
||||
| function | what it does |
|
||||
|---|---|
|
||||
| `sfile_decode_file(path, res)` | decode a file from disk; returns 0 identified, 2 unreadable, 3 unknown (the CLI exit codes). Also runs `geotag_scan()` for the `geotags` fields. |
|
||||
| `sfile_decode_mem(buf, n, display_name, fsize, res)` | decode bytes already in memory; same return codes. `display_name` is used for the extension fallback. No geotag scan (no path to scan — call `geotag_scan()` yourself if you have one). |
|
||||
| `sfile_free_result(res)` | release everything the decode allocated. |
|
||||
| `sfile_result_to_json(res)` | serialize the result as one compact JSON object (see `docs/json.md`); malloc'd, caller frees. |
|
||||
| `sfile_format_count()` / `sfile_get_format_info(i, info)` | format-table introspection (powers `sfile --list`). |
|
||||
| `sfile_field_kind_name(kind)` | `"u8"` / `"u16"` / … / `"ascii"` / `"bytes"`. |
|
||||
| `geotag_scan(path, task, out, max)` | (`src/geotag.h`) fill `out[]` with the locations found (EXIF GPS, XMP, QuickTime, GeoTIFF, EXR, PSD, CR3); returns the count, 0 when the format has a mechanism but no location, -1 when it has none. |
|
||||
|
||||
`sfile_result` carries the path and size, the identified format
|
||||
(task/ext/name/kind/endian, `identified_by`, magic bytes, the other
|
||||
formats sharing the magic), the decoded header fields (`offset`,
|
||||
`size`, `name`, `kind`, `value` formatted exactly as the CLI prints
|
||||
it, plus a JSON-friendly `raw` and the numeric value), the text
|
||||
fallback decode (`doc_type` + XML/JSON/first-line strings), the
|
||||
hex dump for unknown/no-layout files, and the geotags
|
||||
(`geotags[8]` + `ngeotags` + `geotag_status`, the `geotag_scan()`
|
||||
return: -1 no mechanism, 0 none found, >0 count).
|
||||
|
||||
Ownership: strings pointing into the format table (format name/ext,
|
||||
field names, candidate exts) are borrowed — do not free them.
|
||||
Everything else in the struct is owned and freed by
|
||||
`sfile_free_result()`. Threading: the table walk holds no shared
|
||||
state, except the geotag scan, which reuses `geotag.c`'s static
|
||||
result buffer — concurrent `sfile_decode_file()` calls are not
|
||||
thread-safe; serialize them or use `sfile_decode_mem()`.
|
||||
|
||||
## Minimal example
|
||||
|
||||
```c
|
||||
/* minimal.c - decode a file with libsfile and print its format + fields */
|
||||
#include <stdio.h>
|
||||
#include "sfile.h"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) return 1;
|
||||
sfile_result r;
|
||||
int st = sfile_decode_file(argv[1], &r);
|
||||
if (st != 0) { printf("cannot decode: %s\n", r.error); sfile_free_result(&r); return st; }
|
||||
printf("%s (%s), task %d, %d fields\n", r.name, r.ext, r.task, r.nfields);
|
||||
for (int i = 0; i < r.nfields; i++)
|
||||
printf(" %s = %s\n", r.fields[i].name, r.fields[i].value);
|
||||
if (r.ngeotags > 0)
|
||||
printf("geotag: %g, %g (%s)\n", r.geotags[0].lat, r.geotags[0].lon,
|
||||
r.geotags[0].source);
|
||||
sfile_free_result(&r);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
# shared library
|
||||
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o minimal minimal.c -L. -lsfile -Wl,-rpath,$PWD
|
||||
# or static
|
||||
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o minimal minimal.c libsfile.a
|
||||
```
|
||||
|
||||
Real output (verified against both):
|
||||
|
||||
```
|
||||
$ ./minimal sample.png
|
||||
PNG image (.PNG), task 564, 10 fields
|
||||
signature = 89 50 4e 47 0d 0a 1a 0a
|
||||
ihdr_length = 13
|
||||
ihdr_type = "IHDR"
|
||||
width = 800
|
||||
height = 600
|
||||
bit_depth = 8
|
||||
color_type = 2
|
||||
compression = 0
|
||||
filter = 0
|
||||
interlace = 0
|
||||
|
||||
$ ./minimal test-gps.jpg
|
||||
JPEG image (.JPG), task 332, 4 fields
|
||||
soi = ff d8
|
||||
marker = ff e1
|
||||
segment_length = 258
|
||||
identifier = "Exif"
|
||||
geotag: 37.7749, -122.419 (EXIF GPS IFD (JPEG APP1 segment))
|
||||
```
|
||||
|
||||
The field values are the CLI's own strings (`"IHDR"` quoted,
|
||||
bytes as hex), so a program printing them reproduces the CLI's
|
||||
header table exactly. `tests/test_library.c` is a fuller example
|
||||
(it also exercises `sfile_decode_mem()` and
|
||||
`sfile_result_to_json()`).
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/test_lib.sh` (`make test-lib`) compiles
|
||||
`tests/test_library.c` against the static library *and* the
|
||||
shared library, then diffs the field lines each prints against the
|
||||
`./sfile` CLI's header table on the same files, checks the
|
||||
`--mem` path, the EXIF GPS geotag (JPEG fixture), and that the
|
||||
library's own JSON parses and carries the right geotags.
|
||||
+123
-252
@@ -4,289 +4,160 @@
|
||||
* filename extension) and prints a detailed decode of the file header:
|
||||
* field names, offsets, sizes and values, in a uniform table.
|
||||
*
|
||||
* The per-format knowledge lives in formats.h, which is GENERATED by
|
||||
* tools/gen_formats.py from the collected C/C++ reference code
|
||||
* (tools/all_formats.cpp) plus a curated magic table and hand overrides
|
||||
* (tools/overrides.json). The engine itself is generic: it contains no
|
||||
* per-format decode logic, only the table walk, the value formatters and
|
||||
* the text/XML fallback decoder.
|
||||
* This file is only the command-line front end. The decode engine lives
|
||||
* in libsfile (src/sfile_lib.c, public API in src/sfile.h); everything
|
||||
* printed here comes from sfile_result, so the CLI and the library
|
||||
* agree by construction. `--json` prints the same result as JSON
|
||||
* (one object per file, one per line) instead of the human table.
|
||||
*
|
||||
* Exit codes: 0 identified, 1 usage error, 2 file unreadable, 3 unknown.
|
||||
* With several files the worst code wins (unreadable beats unknown).
|
||||
*
|
||||
* In text mode, an identified file also gets the "Geotagging:" section
|
||||
* from decode_geotag() (src/geotag.c), exactly as upstream prints it.
|
||||
* In --json mode that section is not printed: the same locations come
|
||||
* from geotag_scan() inside libsfile and are carried in the JSON
|
||||
* "geotags" array instead.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "formats.h"
|
||||
#include "sfile.h"
|
||||
#include "geotag.h"
|
||||
|
||||
#define HDR_WIN 65536 /* header window: how much of the file we read */
|
||||
#define HEXDUMP_LEN 64 /* bytes shown for unknown / magic-only formats */
|
||||
|
||||
static const char *prog;
|
||||
|
||||
/* ---- value readers (respect per-format endianness) ---- */
|
||||
static uint16_t rd16(const uint8_t *p, int be) {
|
||||
return be ? (uint16_t)((p[0] << 8) | p[1]) : (uint16_t)(p[0] | (p[1] << 8));
|
||||
}
|
||||
static uint32_t rd32(const uint8_t *p, int be) {
|
||||
if (be) return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
|
||||
((uint32_t)p[2] << 8) | p[3];
|
||||
return p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
static uint64_t rd64(const uint8_t *p, int be) {
|
||||
uint64_t v = 0;
|
||||
if (be) { for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; }
|
||||
else { for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; }
|
||||
return v;
|
||||
}
|
||||
static float rd_f32(const uint8_t *p, int be) {
|
||||
uint32_t u = rd32(p, be);
|
||||
float f; memcpy(&f, &u, 4); return f;
|
||||
}
|
||||
static double rd_f64(const uint8_t *p, int be) {
|
||||
uint64_t u = rd64(p, be);
|
||||
double d; memcpy(&d, &u, 8); return d;
|
||||
}
|
||||
|
||||
static int printable_ascii(const uint8_t *p, size_t n) {
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (!isprint(p[i]) && p[i] != 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void print_hex(const uint8_t *p, size_t n) {
|
||||
for (size_t i = 0; i < n; i++) printf("%02x ", p[i]);
|
||||
}
|
||||
|
||||
/* ---- identification ---- */
|
||||
static const SFormat *match_magic(const uint8_t *buf, size_t n, const SFormat **cands, int *ncand) {
|
||||
const SFormat *best = NULL;
|
||||
*ncand = 0;
|
||||
for (int i = 0; i < sfile_nformats; i++) {
|
||||
const SFormat *f = &sfile_formats[i];
|
||||
if (f->magic_len == 0) continue;
|
||||
if (f->magic_off + f->magic_len > n) continue;
|
||||
if (memcmp(buf + f->magic_off, f->magic, f->magic_len) == 0) {
|
||||
if (*ncand < 64) cands[(*ncand)++] = f;
|
||||
if (!best || f->magic_len > best->magic_len) best = f;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
static const char *file_ext(const char *path) {
|
||||
const char *dot = strrchr(path, '.');
|
||||
const char *slash = strrchr(path, '/');
|
||||
if (!dot || (slash && dot < slash)) return "";
|
||||
return dot;
|
||||
}
|
||||
|
||||
/* case-insensitive extension compare (".7z" vs ".7Z") */
|
||||
static int ext_eq(const char *a, const char *b) {
|
||||
while (*a && *b) {
|
||||
if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
|
||||
a++; b++;
|
||||
}
|
||||
return *a == *b;
|
||||
}
|
||||
|
||||
/* ---- text / XML fallback decoder ---- */
|
||||
static void decode_text(const uint8_t *buf, size_t n) {
|
||||
/* XML declaration? */
|
||||
if (n >= 5 && memcmp(buf, "<?xml", 5) == 0) {
|
||||
printf("Document type: XML\n");
|
||||
const uint8_t *end = memchr(buf, '>', n);
|
||||
if (end && (size_t)(end - buf) < 200) {
|
||||
printf("XML declaration: %.*s>\n", (int)(end - buf), buf);
|
||||
}
|
||||
/* root element: first '<' after the declaration that is not a comment/PI */
|
||||
size_t i = end ? (size_t)(end - buf) + 1 : 5;
|
||||
while (i < n && isspace(buf[i])) i++;
|
||||
if (i + 1 < n && buf[i] == '<' && buf[i+1] != '?' && buf[i+1] != '!' && buf[i+1] != '/') {
|
||||
size_t j = i + 1;
|
||||
while (j < n && (isalnum(buf[j]) || buf[j] == '_' || buf[j] == '-' || buf[j] == '.' || buf[j] == ':')) j++;
|
||||
printf("Root element: %.*s\n", (int)(j - i - 1), buf + i + 1);
|
||||
/* version attribute on the root element */
|
||||
const uint8_t *v = (const uint8_t *)memmem(buf + i, n - i, "version=\"", 9);
|
||||
if (v && (size_t)(v - buf) < j + 200) {
|
||||
const uint8_t *q = memchr(v + 9, '"', n - (size_t)(v - buf) - 9);
|
||||
if (q) printf("Version attribute: %.*s\n", (int)(q - v - 9), v + 9);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (n >= 1 && buf[0] == '{') {
|
||||
printf("Document type: JSON\n");
|
||||
/* first key, if an object */
|
||||
const uint8_t *q1 = memchr(buf + 1, '"', n - 1);
|
||||
const uint8_t *q2 = q1 ? memchr(q1 + 1, '"', n - (size_t)(q1 - buf) - 1) : NULL;
|
||||
if (q1 && q2 && (size_t)(q2 - q1) < 80)
|
||||
printf("First key: %.*s\n", (int)(q2 - q1 - 1), q1 + 1);
|
||||
return;
|
||||
}
|
||||
if (n >= 2 && buf[0] == '[') {
|
||||
/* a JSON array must start with a value; an INI section header
|
||||
like [PHP] starts with a bare word and must not match */
|
||||
char c = (char)buf[1];
|
||||
if (c == '"' || c == '{' || c == '[' || (c >= '0' && c <= '9') ||
|
||||
c == '-' || c == 't' || c == 'f' || c == 'n') {
|
||||
printf("Document type: JSON\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
/* plain text: first line */
|
||||
printf("Document type: text\n");
|
||||
const uint8_t *nl = memchr(buf, '\n', n < 200 ? n : 200);
|
||||
size_t linelen = nl ? (size_t)(nl - buf) : (n < 200 ? n : 200);
|
||||
while (linelen > 0 && (buf[linelen-1] == '\r' || buf[linelen-1] == '\n')) linelen--;
|
||||
printf("First line: %.*s\n", (int)linelen, buf);
|
||||
}
|
||||
|
||||
/* ---- main decode ---- */
|
||||
static void decode_binary(const SFormat *f, const uint8_t *buf, size_t n, long fsize) {
|
||||
printf("Header (%s-endian):\n", f->endian ? "big" : "little");
|
||||
printf(" %-8s %-6s %-28s %s\n", "offset", "size", "field", "value");
|
||||
for (int i = 0; i < f->nfields; i++) {
|
||||
const SField *fl = &f->fields[i];
|
||||
if (fl->offset + fl->size > (uint32_t)n) {
|
||||
printf(" %-8u %-6u %-28s (beyond header window / EOF)\n",
|
||||
fl->offset, fl->size, fl->name);
|
||||
continue;
|
||||
}
|
||||
const uint8_t *p = buf + fl->offset;
|
||||
printf(" %-8u %-6u %-28s ", fl->offset, fl->size, fl->name);
|
||||
switch (fl->kind) {
|
||||
case FK_U8: printf("%u\n", p[0]); break;
|
||||
case FK_U16: printf("%u\n", rd16(p, f->endian)); break;
|
||||
case FK_U32: printf("%u\n", rd32(p, f->endian)); break;
|
||||
case FK_U64: printf("%llu\n", (unsigned long long)rd64(p, f->endian)); break;
|
||||
case FK_I8: printf("%d\n", (int8_t)p[0]); break;
|
||||
case FK_I16: printf("%d\n", (int16_t)rd16(p, f->endian)); break;
|
||||
case FK_I32: printf("%d\n", (int32_t)rd32(p, f->endian)); break;
|
||||
case FK_I64: printf("%lld\n", (long long)(int64_t)rd64(p, f->endian)); break;
|
||||
case FK_F32: printf("%g\n", (double)rd_f32(p, f->endian)); break;
|
||||
case FK_F64: printf("%g\n", rd_f64(p, f->endian)); break;
|
||||
case FK_ASCII:
|
||||
if (printable_ascii(p, fl->size)) {
|
||||
/* trim at first NUL */
|
||||
size_t m = 0;
|
||||
while (m < fl->size && p[m]) m++;
|
||||
printf("\"%.*s\"\n", (int)m, p);
|
||||
} else {
|
||||
print_hex(p, fl->size); printf("\n");
|
||||
}
|
||||
break;
|
||||
case FK_BYTES:
|
||||
default:
|
||||
print_hex(p, fl->size); printf("\n"); break;
|
||||
}
|
||||
}
|
||||
(void)fsize;
|
||||
}
|
||||
|
||||
static void usage(void) {
|
||||
fprintf(stderr, "Usage: %s <file> [--list]\n", prog);
|
||||
fprintf(stderr, "Usage: %s <file>... [--json] [--list]\n", prog);
|
||||
fprintf(stderr, " sfile identifies a file's format and decodes its header.\n");
|
||||
fprintf(stderr, " --json print machine-readable JSON, one object per file (one per line)\n");
|
||||
fprintf(stderr, " --list list all known formats (task, extension, name, derivation is in formats.json)\n");
|
||||
}
|
||||
|
||||
static int list_formats(void) {
|
||||
printf("%-6s %-8s %s\n", "task", "ext", "name");
|
||||
for (int i = 0; i < sfile_nformats; i++) {
|
||||
const SFormat *f = &sfile_formats[i];
|
||||
printf("%-6d %-8s %s\n", f->task, f->ext, f->name);
|
||||
for (int i = 0; i < sfile_format_count(); i++) {
|
||||
sfile_format_info info;
|
||||
if (sfile_get_format_info(i, &info) != 0) continue;
|
||||
printf("%-6d %-8s %s\n", info.task, info.ext, info.name);
|
||||
}
|
||||
printf("%d formats\n", sfile_nformats);
|
||||
printf("%d formats\n", sfile_format_count());
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* The human-readable table, byte-identical to the historical output. */
|
||||
static void print_result_text(const sfile_result *r) {
|
||||
printf("File: %s (%lld bytes)\n", r->file, (long long)r->size);
|
||||
if (!r->identified) {
|
||||
printf("Format: unknown (no magic match, no known extension)\n");
|
||||
printf("First %d bytes:\n ", HEXDUMP_LEN);
|
||||
printf("%s%s\n", r->hexdump ? r->hexdump : "",
|
||||
r->hexdump && *r->hexdump ? " " : "");
|
||||
return;
|
||||
}
|
||||
|
||||
printf("Format: %s (%s) — task %d\n", r->name, r->ext, r->task);
|
||||
printf("Identified by: %s\n", r->identified_by);
|
||||
if (r->has_magic) {
|
||||
printf("Magic: ");
|
||||
for (uint32_t i = 0; i < r->magic_len; i++) printf("%02x ", r->magic[i]);
|
||||
printf("at offset %u\n", r->magic_off);
|
||||
}
|
||||
if (r->ncandidates > 0) {
|
||||
printf("Note: %d formats share this magic; extension disambiguated to %s.\n",
|
||||
r->ncandidates + 1, r->ext);
|
||||
printf("Other candidates:");
|
||||
for (int i = 0; i < r->ncandidates; i++)
|
||||
printf(" %s (task %d)", r->candidates[i].ext, r->candidates[i].task);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
if (r->doc_type != SFILE_DOC_NONE) {
|
||||
switch (r->doc_type) {
|
||||
case SFILE_DOC_XML:
|
||||
printf("Document type: XML\n");
|
||||
if (r->xml_declaration) printf("XML declaration: %s\n", r->xml_declaration);
|
||||
if (r->root_element) printf("Root element: %s\n", r->root_element);
|
||||
if (r->version_attr) printf("Version attribute: %s\n", r->version_attr);
|
||||
break;
|
||||
case SFILE_DOC_JSON:
|
||||
printf("Document type: JSON\n");
|
||||
if (r->first_key) printf("First key: %s\n", r->first_key);
|
||||
break;
|
||||
case SFILE_DOC_TEXT:
|
||||
default:
|
||||
printf("Document type: text\n");
|
||||
printf("First line: %s\n", r->first_line ? r->first_line : "");
|
||||
break;
|
||||
}
|
||||
} else if (r->has_header) {
|
||||
printf("Header (%s-endian):\n", r->endian ? "big" : "little");
|
||||
printf(" %-8s %-6s %-28s %s\n", "offset", "size", "field", "value");
|
||||
for (int i = 0; i < r->nfields; i++) {
|
||||
const sfile_field *fl = &r->fields[i];
|
||||
printf(" %-8u %-6u %-28s %s\n", fl->offset, fl->size, fl->name, fl->value);
|
||||
}
|
||||
} else {
|
||||
printf("Header layout: not derived for this format (see formats.json, derivation: %s).\n",
|
||||
r->format_kind == SFILE_FORMAT_UNKNOWN ? "unknown" : "magic-only");
|
||||
printf("First %d bytes:\n ", HEXDUMP_LEN);
|
||||
printf("%s%s\n", r->hexdump ? r->hexdump : "",
|
||||
r->hexdump && *r->hexdump ? " " : "");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
prog = argv[0];
|
||||
if (argc < 2) { usage(); return 1; }
|
||||
if (strcmp(argv[1], "--list") == 0) return list_formats();
|
||||
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { usage(); return 0; }
|
||||
const char *path = argv[1];
|
||||
int json = 0, list = 0;
|
||||
const char *files[argc > 1 ? argc : 1];
|
||||
int nfiles = 0;
|
||||
|
||||
struct stat st;
|
||||
if (stat(path, &st) != 0) { perror(path); return 2; }
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) { perror(path); return 2; }
|
||||
size_t cap = st.st_size < HDR_WIN ? (size_t)st.st_size : HDR_WIN;
|
||||
uint8_t *buf = malloc(cap ? cap : 1);
|
||||
if (!buf) { fclose(fp); return 2; }
|
||||
size_t n = fread(buf, 1, cap, fp);
|
||||
fclose(fp);
|
||||
|
||||
printf("File: %s (%lld bytes)\n", path, (long long)st.st_size);
|
||||
|
||||
const SFormat *cands[64];
|
||||
int ncand = 0;
|
||||
const SFormat *best = match_magic(buf, n, cands, &ncand);
|
||||
const SFormat *fmt = best;
|
||||
const char *how = "magic";
|
||||
|
||||
if (!fmt) {
|
||||
/* extension fallback */
|
||||
const char *ext = file_ext(path);
|
||||
if (*ext) {
|
||||
for (int i = 0; i < sfile_nformats; i++) {
|
||||
if (ext_eq(sfile_formats[i].ext, ext)) { fmt = &sfile_formats[i]; break; }
|
||||
}
|
||||
if (fmt) how = "extension";
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--json") == 0) json = 1;
|
||||
else if (strcmp(argv[i], "--list") == 0) list = 1;
|
||||
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
|
||||
usage();
|
||||
return 0;
|
||||
}
|
||||
} else if (ncand > 1) {
|
||||
/* several formats share this magic (e.g. PK zip): prefer the one
|
||||
whose extension matches the filename */
|
||||
const char *ext = file_ext(path);
|
||||
if (*ext) {
|
||||
for (int i = 0; i < ncand; i++) {
|
||||
if (ext_eq(cands[i]->ext, ext)) { fmt = cands[i]; break; }
|
||||
}
|
||||
else if (strcmp(argv[i], "--version") == 0) {
|
||||
printf("sfile %s\n", SFILE_VERSION);
|
||||
return 0;
|
||||
}
|
||||
else files[nfiles++] = argv[i];
|
||||
}
|
||||
|
||||
if (!fmt) {
|
||||
printf("Format: unknown (no magic match, no known extension)\n");
|
||||
printf("First %d bytes:\n ", HEXDUMP_LEN);
|
||||
print_hex(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
|
||||
printf("\n");
|
||||
free(buf);
|
||||
return 3;
|
||||
}
|
||||
if (list) return list_formats();
|
||||
if (nfiles == 0) { usage(); return 1; }
|
||||
|
||||
printf("Format: %s (%s) — task %d\n", fmt->name, fmt->ext, fmt->task);
|
||||
printf("Identified by: %s\n", how);
|
||||
if (fmt->magic_len) {
|
||||
printf("Magic: ");
|
||||
print_hex((const uint8_t *)fmt->magic, fmt->magic_len);
|
||||
printf("at offset %u\n", fmt->magic_off);
|
||||
int rc = 0;
|
||||
for (int i = 0; i < nfiles; i++) {
|
||||
sfile_result r;
|
||||
int st = sfile_decode_file(files[i], &r);
|
||||
if (st == 2) {
|
||||
/* same as the old perror(path) on stderr; stdout stays
|
||||
clean JSON when --json is on */
|
||||
fprintf(stderr, "%s: %s\n", files[i], r.error ? r.error : "unreadable");
|
||||
rc = 2;
|
||||
} else if (st == 3 && rc != 2) {
|
||||
rc = 3;
|
||||
}
|
||||
if (json) {
|
||||
char *js = sfile_result_to_json(&r);
|
||||
if (js) {
|
||||
puts(js);
|
||||
free(js);
|
||||
} else {
|
||||
fprintf(stderr, "%s: failed to serialize JSON\n", files[i]);
|
||||
if (rc == 0) rc = 2;
|
||||
}
|
||||
} else {
|
||||
if (st != 2) print_result_text(&r);
|
||||
if (st == 0) decode_geotag(files[i], r.task);
|
||||
}
|
||||
sfile_free_result(&r);
|
||||
}
|
||||
if (ncand > 1) {
|
||||
printf("Note: %d formats share this magic; extension disambiguated to %s.\n", ncand, fmt->ext);
|
||||
printf("Other candidates:");
|
||||
for (int i = 0; i < ncand; i++)
|
||||
if (cands[i] != fmt) printf(" %s (task %d)", cands[i]->ext, cands[i]->task);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
if (fmt->kind == FMT_TEXT) {
|
||||
decode_text(buf, n);
|
||||
} else if (fmt->nfields > 0) {
|
||||
decode_binary(fmt, buf, n, st.st_size);
|
||||
} else {
|
||||
printf("Header layout: not derived for this format (see formats.json, derivation: %s).\n",
|
||||
fmt->kind == FMT_UNKNOWN ? "unknown" : "magic-only");
|
||||
printf("First %d bytes:\n ", HEXDUMP_LEN);
|
||||
print_hex(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
|
||||
printf("\n");
|
||||
}
|
||||
decode_geotag(path, fmt->task);
|
||||
|
||||
free(buf);
|
||||
return 0;
|
||||
return rc;
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
/* sfile.h — public API for libsfile, the sfile decode engine as a library.
|
||||
*
|
||||
* sfile identifies a file's format (by magic bytes, falling back to the
|
||||
* filename extension) and decodes its header: field names, offsets, sizes
|
||||
* and values. This header exposes that engine so other tools (stag, sgeo,
|
||||
* scar, ...) can link it instead of shelling out to the `sfile` binary.
|
||||
*
|
||||
* The CLI in src/sfile.c is a thin wrapper over this API: everything it
|
||||
* prints comes from sfile_result, so library and CLI results agree by
|
||||
* construction.
|
||||
*
|
||||
* Ownership: strings that point into the format table (format name/ext,
|
||||
* field names, candidate exts) are borrowed — do not free them. Strings
|
||||
* owned by sfile_result (file, error, field value/raw, hexdump, document
|
||||
* strings) are freed by sfile_free_result(). sfile_result_to_json()
|
||||
* returns a malloc'd string the caller frees.
|
||||
*
|
||||
* Threading: the format table is static const and the decode itself
|
||||
* holds no shared state — except the geotag scan, which reuses
|
||||
* geotag.c's static result buffer. Concurrent sfile_decode_file()
|
||||
* calls are therefore NOT thread-safe; serialize them, or use
|
||||
* sfile_decode_mem() (which never scans for geotags).
|
||||
*/
|
||||
#ifndef SFILE_H
|
||||
#define SFILE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "geotag.h"
|
||||
|
||||
#define SFILE_VERSION "1.1.0"
|
||||
|
||||
/* Max locations geotag_scan() can return for one file (geotag.c holds 8). */
|
||||
#define SFILE_MAX_GEOTAGS 8
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Field value kinds — same order/values as FK_* in formats.h. */
|
||||
enum sfile_field_kind {
|
||||
SFILE_U8 = 0, SFILE_U16, SFILE_U32, SFILE_U64,
|
||||
SFILE_I8, SFILE_I16, SFILE_I32, SFILE_I64,
|
||||
SFILE_F32, SFILE_F64, SFILE_ASCII, SFILE_BYTES
|
||||
};
|
||||
|
||||
/* Format kinds — same values as FMT_* in formats.h. */
|
||||
enum sfile_format_kind {
|
||||
SFILE_BINARY = 0, SFILE_TEXT, SFILE_FORMAT_UNKNOWN
|
||||
};
|
||||
|
||||
/* What the text fallback decoder found. */
|
||||
enum sfile_doc_type {
|
||||
SFILE_DOC_NONE = 0, SFILE_DOC_XML, SFILE_DOC_JSON, SFILE_DOC_TEXT
|
||||
};
|
||||
|
||||
/* One decoded header field. `value` is formatted exactly as the CLI
|
||||
* prints it (numbers decimal, ASCII quoted, bytes as space-separated hex
|
||||
* with a trailing space). `raw` is the JSON-friendly form: numbers as
|
||||
* decimal, ASCII unquoted, bytes as hex without the trailing space;
|
||||
* NULL when the field runs past the bytes read (beyond_window). */
|
||||
typedef struct {
|
||||
uint32_t offset;
|
||||
uint32_t size;
|
||||
const char *name; /* borrowed from the format table */
|
||||
int kind; /* enum sfile_field_kind */
|
||||
int beyond_window; /* field runs past the header window / EOF */
|
||||
char *value; /* owned */
|
||||
char *raw; /* owned, NULL when beyond_window */
|
||||
int is_number; /* value is a JSON number */
|
||||
int is_float; /* number came from F32/F64 */
|
||||
unsigned long long unum;
|
||||
long long inum;
|
||||
double fnum;
|
||||
} sfile_field;
|
||||
|
||||
/* Another format sharing the same magic (the chosen format excluded). */
|
||||
typedef struct {
|
||||
const char *ext; /* borrowed from the format table */
|
||||
int task;
|
||||
} sfile_candidate;
|
||||
|
||||
typedef struct {
|
||||
char *file; /* path as given (owned) */
|
||||
long size; /* file size in bytes, -1 when unreadable */
|
||||
int identified; /* 1 = a format was identified */
|
||||
int status; /* 0 ok, 2 unreadable, 3 unknown — mirrors CLI exit codes */
|
||||
char *error; /* human-readable reason when status != 0 (owned) */
|
||||
|
||||
/* identified format (borrowed strings) */
|
||||
int task;
|
||||
const char *ext;
|
||||
const char *name;
|
||||
int format_kind; /* enum sfile_format_kind */
|
||||
int endian; /* 0 little, 1 big */
|
||||
int nfields_table; /* fields the format declares (0 = no layout) */
|
||||
const char *identified_by; /* "magic" | "extension" | NULL */
|
||||
uint8_t magic[32];
|
||||
uint32_t magic_len;
|
||||
uint32_t magic_off;
|
||||
int has_magic;
|
||||
sfile_candidate candidates[64];
|
||||
int ncandidates; /* other formats sharing this magic */
|
||||
|
||||
/* binary header decode */
|
||||
int has_header; /* 1 when fields[] holds a decoded header table */
|
||||
sfile_field *fields;/* owned array, nfields entries */
|
||||
int nfields;
|
||||
int has_layout; /* 0 = binary format with no derived layout */
|
||||
|
||||
/* text fallback decode */
|
||||
int doc_type; /* enum sfile_doc_type */
|
||||
char *xml_declaration; /* "<?xml ...?>" including '>', when present */
|
||||
char *root_element; /* XML root element name, when found */
|
||||
char *version_attr; /* version="..." on the root element, when found */
|
||||
char *first_key; /* first key of a JSON object, when found */
|
||||
char *first_line; /* first line of a plain-text file */
|
||||
|
||||
/* hex dump of the first 64 bytes (owned, space-separated hex, no
|
||||
* trailing space) — set for unknown files and for binary formats
|
||||
* with no derived layout */
|
||||
char *hexdump;
|
||||
|
||||
/* geotags, from geotag_scan() (src/geotag.h): EXIF GPS, XMP,
|
||||
* QuickTime/GeoTIFF/EXR/PSD/CR3 locations. Only sfile_decode_file()
|
||||
* fills these — it has a path to scan. sfile_decode_mem() never
|
||||
* touches the filesystem, so its results carry no geotags.
|
||||
* geotag_status is the geotag_scan() return: -1 no geotagging
|
||||
* mechanism for this format, 0 mechanism but none found, >0 the
|
||||
* number of entries in geotags[]. */
|
||||
GeoResult geotags[SFILE_MAX_GEOTAGS];
|
||||
int ngeotags;
|
||||
int geotag_status;
|
||||
} sfile_result;
|
||||
|
||||
/* Decode a file from disk. Returns 0 (identified), 2 (unreadable) or
|
||||
* 3 (unknown) and fills res either way; call sfile_free_result() when
|
||||
* done. `res` is zeroed on entry. Also runs geotag_scan() for the
|
||||
* geotag fields (see above) when the format was identified. */
|
||||
int sfile_decode_file(const char *path, sfile_result *res);
|
||||
|
||||
/* Decode bytes already in memory. display_name is used for the
|
||||
* extension fallback and reported as `file` (may be NULL). fsize is
|
||||
* the full file size (may differ from n, the bytes available). Same
|
||||
* return codes as sfile_decode_file. No geotag scan is done here:
|
||||
* there is no path to scan (call geotag_scan() yourself if you have
|
||||
* one). */
|
||||
int sfile_decode_mem(const uint8_t *buf, size_t n, const char *display_name,
|
||||
long fsize, sfile_result *res);
|
||||
|
||||
/* Release everything sfile_decode_* allocated inside res. */
|
||||
void sfile_free_result(sfile_result *res);
|
||||
|
||||
/* Serialize a decoded result as one compact JSON object (one line, no
|
||||
* trailing newline). Returns a malloc'd string the caller frees, or
|
||||
* NULL on allocation failure. See docs/json.md for the schema. */
|
||||
char *sfile_result_to_json(const sfile_result *res);
|
||||
|
||||
/* Format-table introspection (powers `sfile --list`). */
|
||||
int sfile_format_count(void);
|
||||
|
||||
typedef struct {
|
||||
int task;
|
||||
const char *ext; /* borrowed from the format table */
|
||||
const char *name; /* borrowed from the format table */
|
||||
int kind; /* enum sfile_format_kind */
|
||||
int endian; /* 0 little, 1 big */
|
||||
int nfields;
|
||||
int has_magic;
|
||||
} sfile_format_info;
|
||||
|
||||
/* Fill info for format index (0 .. sfile_format_count()-1).
|
||||
* Returns 0 on success, -1 when index is out of range. */
|
||||
int sfile_get_format_info(int index, sfile_format_info *info);
|
||||
|
||||
/* "u8" / "u16" / ... / "ascii" / "bytes" for a field kind. */
|
||||
const char *sfile_field_kind_name(int kind);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* SFILE_H */
|
||||
+713
@@ -0,0 +1,713 @@
|
||||
/* sfile_lib.c — the sfile decode engine, as a linkable library.
|
||||
*
|
||||
* This is the engine the `sfile` CLI used to contain inline: value
|
||||
* readers, magic/extension identification, the text/XML fallback
|
||||
* decoder, the binary header-table walk, and the JSON serializer.
|
||||
* It contains no per-format decode logic — the knowledge lives in
|
||||
* formats.h (generated by tools/gen_formats.py), exactly as before.
|
||||
*
|
||||
* The CLI (src/sfile.c) is a thin wrapper: it parses arguments and
|
||||
* prints sfile_result, either as the human-readable table or as JSON.
|
||||
* Moving the engine here changes no output: the text printer consumes
|
||||
* the same strings the old inline code printed.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "sfile.h"
|
||||
#include "formats.h"
|
||||
#include "geotag.h"
|
||||
|
||||
#define HDR_WIN 65536 /* header window: how much of the file we read */
|
||||
#define HEXDUMP_LEN 64 /* bytes shown for unknown / magic-only formats */
|
||||
#define MAX_CANDIDATES 64
|
||||
|
||||
/* Field kinds must stay in step with FK_* in formats.h. */
|
||||
_Static_assert((int)SFILE_U8 == (int)FK_U8 && (int)SFILE_BYTES == (int)FK_BYTES,
|
||||
"sfile_field_kind out of step with formats.h FK_*");
|
||||
_Static_assert((int)SFILE_BINARY == (int)FMT_BINARY &&
|
||||
(int)SFILE_FORMAT_UNKNOWN == (int)FMT_UNKNOWN,
|
||||
"sfile_format_kind out of step with formats.h FMT_*");
|
||||
|
||||
/* ---- value readers (respect per-format endianness) ---- */
|
||||
static uint16_t rd16(const uint8_t *p, int be) {
|
||||
return be ? (uint16_t)((p[0] << 8) | p[1]) : (uint16_t)(p[0] | (p[1] << 8));
|
||||
}
|
||||
static uint32_t rd32(const uint8_t *p, int be) {
|
||||
if (be) return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
|
||||
((uint32_t)p[2] << 8) | p[3];
|
||||
return p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
static uint64_t rd64(const uint8_t *p, int be) {
|
||||
uint64_t v = 0;
|
||||
if (be) { for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; }
|
||||
else { for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; }
|
||||
return v;
|
||||
}
|
||||
static float rd_f32(const uint8_t *p, int be) {
|
||||
uint32_t u = rd32(p, be);
|
||||
float f; memcpy(&f, &u, 4); return f;
|
||||
}
|
||||
static double rd_f64(const uint8_t *p, int be) {
|
||||
uint64_t u = rd64(p, be);
|
||||
double d; memcpy(&d, &u, 8); return d;
|
||||
}
|
||||
|
||||
static int printable_ascii(const uint8_t *p, size_t n) {
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (!isprint(p[i]) && p[i] != 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Space-separated lowercase hex, no trailing space. Caller frees. */
|
||||
static char *hex_string(const uint8_t *p, size_t n) {
|
||||
char *s = malloc(n * 3 + 1);
|
||||
if (!s) return NULL;
|
||||
size_t o = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (i) s[o++] = ' ';
|
||||
o += (size_t)sprintf(s + o, "%02x", p[i]);
|
||||
}
|
||||
s[o] = '\0';
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Same, with a trailing space — exactly what the CLI's old print_hex
|
||||
* printed before the newline. Caller frees. */
|
||||
static char *hex_string_trailing(const uint8_t *p, size_t n) {
|
||||
char *s = malloc(n * 3 + 1);
|
||||
if (!s) return NULL;
|
||||
size_t o = 0;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
o += (size_t)sprintf(s + o, "%02x ", p[i]);
|
||||
s[o] = '\0';
|
||||
return s;
|
||||
}
|
||||
|
||||
static char *xstrdup(const char *s) {
|
||||
if (!s) return NULL;
|
||||
size_t n = strlen(s) + 1;
|
||||
char *d = malloc(n);
|
||||
if (d) memcpy(d, s, n);
|
||||
return d;
|
||||
}
|
||||
|
||||
static char *xstrndup(const char *s, size_t n) {
|
||||
char *d = malloc(n + 1);
|
||||
if (!d) return NULL;
|
||||
memcpy(d, s, n);
|
||||
d[n] = '\0';
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ---- identification ---- */
|
||||
static const SFormat *match_magic(const uint8_t *buf, size_t n, const SFormat **cands, int *ncand) {
|
||||
const SFormat *best = NULL;
|
||||
*ncand = 0;
|
||||
for (int i = 0; i < sfile_nformats; i++) {
|
||||
const SFormat *f = &sfile_formats[i];
|
||||
if (f->magic_len == 0) continue;
|
||||
if (f->magic_off + f->magic_len > n) continue;
|
||||
if (memcmp(buf + f->magic_off, f->magic, f->magic_len) == 0) {
|
||||
if (*ncand < MAX_CANDIDATES) cands[(*ncand)++] = f;
|
||||
if (!best || f->magic_len > best->magic_len) best = f;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
static const char *file_ext(const char *path) {
|
||||
if (!path) return "";
|
||||
const char *dot = strrchr(path, '.');
|
||||
const char *slash = strrchr(path, '/');
|
||||
if (!dot || (slash && dot < slash)) return "";
|
||||
return dot;
|
||||
}
|
||||
|
||||
/* case-insensitive extension compare (".7z" vs ".7Z") */
|
||||
static int ext_eq(const char *a, const char *b) {
|
||||
while (*a && *b) {
|
||||
if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0;
|
||||
a++; b++;
|
||||
}
|
||||
return *a == *b;
|
||||
}
|
||||
|
||||
/* ---- field formatting ---- */
|
||||
static void format_field_value(const SField *fl, const uint8_t *p, int be, sfile_field *out) {
|
||||
out->offset = fl->offset;
|
||||
out->size = fl->size;
|
||||
out->name = fl->name;
|
||||
out->kind = fl->kind;
|
||||
out->beyond_window = 0;
|
||||
char tmp[64];
|
||||
switch (fl->kind) {
|
||||
case FK_U8:
|
||||
out->unum = p[0]; out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%u", p[0]); break;
|
||||
case FK_U16:
|
||||
out->unum = rd16(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%u", rd16(p, be)); break;
|
||||
case FK_U32:
|
||||
out->unum = rd32(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%u", rd32(p, be)); break;
|
||||
case FK_U64:
|
||||
out->unum = rd64(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)rd64(p, be)); break;
|
||||
case FK_I8:
|
||||
out->inum = (int8_t)p[0]; out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%d", (int8_t)p[0]); break;
|
||||
case FK_I16:
|
||||
out->inum = (int16_t)rd16(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%d", (int16_t)rd16(p, be)); break;
|
||||
case FK_I32:
|
||||
out->inum = (int32_t)rd32(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%d", (int32_t)rd32(p, be)); break;
|
||||
case FK_I64:
|
||||
out->inum = (int64_t)rd64(p, be); out->is_number = 1;
|
||||
snprintf(tmp, sizeof tmp, "%lld", (long long)(int64_t)rd64(p, be)); break;
|
||||
case FK_F32: {
|
||||
float f = rd_f32(p, be);
|
||||
out->fnum = f; out->is_number = 1; out->is_float = 1;
|
||||
snprintf(tmp, sizeof tmp, "%g", (double)f); break;
|
||||
}
|
||||
case FK_F64: {
|
||||
double d = rd_f64(p, be);
|
||||
out->fnum = d; out->is_number = 1; out->is_float = 1;
|
||||
snprintf(tmp, sizeof tmp, "%g", d); break;
|
||||
}
|
||||
case FK_ASCII:
|
||||
if (printable_ascii(p, fl->size)) {
|
||||
/* trim at first NUL; CLI prints it quoted */
|
||||
size_t m = 0;
|
||||
while (m < fl->size && p[m]) m++;
|
||||
out->raw = xstrndup((const char *)p, m);
|
||||
out->value = malloc(m + 3);
|
||||
if (out->value) snprintf(out->value, m + 3, "\"%.*s\"", (int)m, p);
|
||||
} else {
|
||||
out->value = hex_string_trailing(p, fl->size);
|
||||
out->raw = hex_string(p, fl->size);
|
||||
}
|
||||
return;
|
||||
case FK_BYTES:
|
||||
default:
|
||||
out->value = hex_string_trailing(p, fl->size);
|
||||
out->raw = hex_string(p, fl->size);
|
||||
return;
|
||||
}
|
||||
out->value = xstrdup(tmp);
|
||||
out->raw = xstrdup(tmp);
|
||||
}
|
||||
|
||||
/* ---- text / XML fallback decoder ---- */
|
||||
static void decode_text_into(const uint8_t *buf, size_t n, sfile_result *res) {
|
||||
/* XML declaration? */
|
||||
if (n >= 5 && memcmp(buf, "<?xml", 5) == 0) {
|
||||
res->doc_type = SFILE_DOC_XML;
|
||||
const uint8_t *end = memchr(buf, '>', n);
|
||||
if (end && (size_t)(end - buf) < 200) {
|
||||
res->xml_declaration = xstrndup((const char *)buf, (size_t)(end - buf) + 1);
|
||||
}
|
||||
/* root element: first '<' after the declaration that is not a comment/PI */
|
||||
size_t i = end ? (size_t)(end - buf) + 1 : 5;
|
||||
while (i < n && isspace(buf[i])) i++;
|
||||
if (i + 1 < n && buf[i] == '<' && buf[i+1] != '?' && buf[i+1] != '!' && buf[i+1] != '/') {
|
||||
size_t j = i + 1;
|
||||
while (j < n && (isalnum(buf[j]) || buf[j] == '_' || buf[j] == '-' || buf[j] == '.' || buf[j] == ':')) j++;
|
||||
res->root_element = xstrndup((const char *)buf + i + 1, j - i - 1);
|
||||
/* version attribute on the root element */
|
||||
const uint8_t *v = (const uint8_t *)memmem(buf + i, n - i, "version=\"", 9);
|
||||
if (v && (size_t)(v - buf) < j + 200) {
|
||||
const uint8_t *q = memchr(v + 9, '"', n - (size_t)(v - buf) - 9);
|
||||
if (q) res->version_attr = xstrndup((const char *)v + 9, (size_t)(q - v - 9));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (n >= 1 && buf[0] == '{') {
|
||||
res->doc_type = SFILE_DOC_JSON;
|
||||
/* first key, if an object */
|
||||
const uint8_t *q1 = memchr(buf + 1, '"', n - 1);
|
||||
const uint8_t *q2 = q1 ? memchr(q1 + 1, '"', n - (size_t)(q1 - buf) - 1) : NULL;
|
||||
if (q1 && q2 && (size_t)(q2 - q1) < 80)
|
||||
res->first_key = xstrndup((const char *)q1 + 1, (size_t)(q2 - q1 - 1));
|
||||
return;
|
||||
}
|
||||
if (n >= 2 && buf[0] == '[') {
|
||||
/* a JSON array must start with a value; an INI section header
|
||||
like [PHP] starts with a bare word and must not match */
|
||||
char c = (char)buf[1];
|
||||
if (c == '"' || c == '{' || c == '[' || (c >= '0' && c <= '9') ||
|
||||
c == '-' || c == 't' || c == 'f' || c == 'n') {
|
||||
res->doc_type = SFILE_DOC_JSON;
|
||||
return;
|
||||
}
|
||||
}
|
||||
/* plain text: first line */
|
||||
res->doc_type = SFILE_DOC_TEXT;
|
||||
const uint8_t *nl = memchr(buf, '\n', n < 200 ? n : 200);
|
||||
size_t linelen = nl ? (size_t)(nl - buf) : (n < 200 ? n : 200);
|
||||
while (linelen > 0 && (buf[linelen-1] == '\r' || buf[linelen-1] == '\n')) linelen--;
|
||||
res->first_line = xstrndup((const char *)buf, linelen);
|
||||
}
|
||||
|
||||
/* ---- decode into a result ---- */
|
||||
static void decode_identified(const SFormat *fmt, const uint8_t *buf, size_t n, sfile_result *res) {
|
||||
res->task = fmt->task;
|
||||
res->ext = fmt->ext;
|
||||
res->name = fmt->name;
|
||||
res->format_kind = fmt->kind;
|
||||
res->endian = fmt->endian;
|
||||
res->nfields_table = fmt->nfields;
|
||||
res->identified = 1;
|
||||
res->status = 0;
|
||||
|
||||
if (fmt->kind == FMT_TEXT) {
|
||||
decode_text_into(buf, n, res);
|
||||
} else if (fmt->nfields > 0) {
|
||||
res->has_header = 1;
|
||||
res->has_layout = 1;
|
||||
res->nfields = fmt->nfields;
|
||||
res->fields = calloc((size_t)fmt->nfields, sizeof *res->fields);
|
||||
if (!res->fields) { res->nfields = 0; return; }
|
||||
for (int i = 0; i < fmt->nfields; i++) {
|
||||
const SField *fl = &fmt->fields[i];
|
||||
sfile_field *out = &res->fields[i];
|
||||
out->offset = fl->offset;
|
||||
out->size = fl->size;
|
||||
out->name = fl->name;
|
||||
out->kind = fl->kind;
|
||||
if (fl->offset + fl->size > (uint32_t)n) {
|
||||
out->beyond_window = 1;
|
||||
out->value = xstrdup("(beyond header window / EOF)");
|
||||
out->raw = NULL;
|
||||
continue;
|
||||
}
|
||||
format_field_value(fl, buf + fl->offset, fmt->endian, out);
|
||||
}
|
||||
/* Geotags are NOT derived from header fields here: the
|
||||
* dedicated decoders in src/geotag.c (EXIF GPS, XMP,
|
||||
* QuickTime, GeoTIFF, EXR, PSD, CR3, ...) are the single
|
||||
* source. sfile_decode_file() runs geotag_scan() for them
|
||||
* (it has a path to scan); sfile_decode_mem() does not. */
|
||||
} else {
|
||||
res->has_layout = 0;
|
||||
res->hexdump = hex_string(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
|
||||
}
|
||||
}
|
||||
|
||||
int sfile_decode_mem(const uint8_t *buf, size_t n, const char *display_name,
|
||||
long fsize, sfile_result *res) {
|
||||
if (!res) return 2;
|
||||
memset(res, 0, sizeof *res);
|
||||
res->file = xstrdup(display_name ? display_name : "");
|
||||
res->size = fsize;
|
||||
res->status = 3;
|
||||
res->geotag_status = -1; /* no scan: decode_mem has no path */
|
||||
|
||||
const SFormat *cands[MAX_CANDIDATES];
|
||||
int ncand = 0;
|
||||
const SFormat *best = match_magic(buf, n, cands, &ncand);
|
||||
const SFormat *fmt = best;
|
||||
const char *how = "magic";
|
||||
|
||||
if (!fmt) {
|
||||
/* extension fallback */
|
||||
const char *ext = file_ext(display_name);
|
||||
if (*ext) {
|
||||
for (int i = 0; i < sfile_nformats; i++) {
|
||||
if (ext_eq(sfile_formats[i].ext, ext)) { fmt = &sfile_formats[i]; break; }
|
||||
}
|
||||
if (fmt) how = "extension";
|
||||
}
|
||||
} else if (ncand > 1) {
|
||||
/* several formats share this magic (e.g. PK zip): prefer the one
|
||||
whose extension matches the filename */
|
||||
const char *ext = file_ext(display_name);
|
||||
if (*ext) {
|
||||
for (int i = 0; i < ncand; i++) {
|
||||
if (ext_eq(cands[i]->ext, ext)) { fmt = cands[i]; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!fmt) {
|
||||
res->error = xstrdup("unknown format (no magic match, no known extension)");
|
||||
res->hexdump = hex_string(buf, n < HEXDUMP_LEN ? n : HEXDUMP_LEN);
|
||||
return 3;
|
||||
}
|
||||
|
||||
res->identified_by = how;
|
||||
if (fmt->magic_len) {
|
||||
res->has_magic = 1;
|
||||
memcpy(res->magic, fmt->magic, fmt->magic_len);
|
||||
res->magic_len = fmt->magic_len;
|
||||
res->magic_off = fmt->magic_off;
|
||||
}
|
||||
if (ncand > 1) {
|
||||
for (int i = 0; i < ncand; i++)
|
||||
if (cands[i] != fmt && res->ncandidates < MAX_CANDIDATES) {
|
||||
res->candidates[res->ncandidates].ext = cands[i]->ext;
|
||||
res->candidates[res->ncandidates].task = cands[i]->task;
|
||||
res->ncandidates++;
|
||||
}
|
||||
}
|
||||
|
||||
decode_identified(fmt, buf, n, res);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int sfile_decode_file(const char *path, sfile_result *res) {
|
||||
if (!res) return 2;
|
||||
memset(res, 0, sizeof *res);
|
||||
res->file = xstrdup(path ? path : "");
|
||||
res->size = -1;
|
||||
res->status = 2;
|
||||
res->geotag_status = -1;
|
||||
|
||||
struct stat st;
|
||||
if (stat(path, &st) != 0) {
|
||||
res->error = xstrdup(strerror(errno));
|
||||
return 2;
|
||||
}
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) {
|
||||
res->error = xstrdup(strerror(errno));
|
||||
return 2;
|
||||
}
|
||||
size_t cap = st.st_size < HDR_WIN ? (size_t)st.st_size : HDR_WIN;
|
||||
uint8_t *buf = malloc(cap ? cap : 1);
|
||||
if (!buf) {
|
||||
fclose(fp);
|
||||
res->error = xstrdup("out of memory");
|
||||
return 2;
|
||||
}
|
||||
size_t n = fread(buf, 1, cap, fp);
|
||||
fclose(fp);
|
||||
|
||||
int rc = sfile_decode_mem(buf, n, path, (long)st.st_size, res);
|
||||
free(buf);
|
||||
if (rc == 0 && path) {
|
||||
/* geotags come from the dedicated decoders in src/geotag.c,
|
||||
* not from the header fields above */
|
||||
int ngeo = geotag_scan(path, res->task, res->geotags, SFILE_MAX_GEOTAGS);
|
||||
res->geotag_status = ngeo;
|
||||
res->ngeotags = ngeo > 0 ? ngeo : 0;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
void sfile_free_result(sfile_result *res) {
|
||||
if (!res) return;
|
||||
free(res->file);
|
||||
free(res->error);
|
||||
if (res->fields) {
|
||||
for (int i = 0; i < res->nfields; i++) {
|
||||
free(res->fields[i].value);
|
||||
free(res->fields[i].raw);
|
||||
}
|
||||
free(res->fields);
|
||||
}
|
||||
free(res->xml_declaration);
|
||||
free(res->root_element);
|
||||
free(res->version_attr);
|
||||
free(res->first_key);
|
||||
free(res->first_line);
|
||||
free(res->hexdump);
|
||||
memset(res, 0, sizeof *res);
|
||||
}
|
||||
|
||||
/* ---- format-table introspection ---- */
|
||||
int sfile_format_count(void) {
|
||||
return sfile_nformats;
|
||||
}
|
||||
|
||||
int sfile_get_format_info(int index, sfile_format_info *info) {
|
||||
if (!info || index < 0 || index >= sfile_nformats) return -1;
|
||||
const SFormat *f = &sfile_formats[index];
|
||||
info->task = f->task;
|
||||
info->ext = f->ext;
|
||||
info->name = f->name;
|
||||
info->kind = f->kind;
|
||||
info->endian = f->endian;
|
||||
info->nfields = f->nfields;
|
||||
info->has_magic = f->magic_len > 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *sfile_field_kind_name(int kind) {
|
||||
switch (kind) {
|
||||
case SFILE_U8: return "u8";
|
||||
case SFILE_U16: return "u16";
|
||||
case SFILE_U32: return "u32";
|
||||
case SFILE_U64: return "u64";
|
||||
case SFILE_I8: return "i8";
|
||||
case SFILE_I16: return "i16";
|
||||
case SFILE_I32: return "i32";
|
||||
case SFILE_I64: return "i64";
|
||||
case SFILE_F32: return "f32";
|
||||
case SFILE_F64: return "f64";
|
||||
case SFILE_ASCII: return "ascii";
|
||||
case SFILE_BYTES: return "bytes";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- JSON serialization ---- */
|
||||
typedef struct {
|
||||
char *s;
|
||||
size_t len;
|
||||
size_t cap;
|
||||
} jbuf;
|
||||
|
||||
static int jb_reserve(jbuf *b, size_t extra) {
|
||||
if (b->len + extra + 1 <= b->cap) return 0;
|
||||
size_t ncap = b->cap ? b->cap : 256;
|
||||
while (ncap < b->len + extra + 1) ncap *= 2;
|
||||
char *ns = realloc(b->s, ncap);
|
||||
if (!ns) return -1;
|
||||
b->s = ns;
|
||||
b->cap = ncap;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int jb_putn(jbuf *b, const char *s, size_t n) {
|
||||
if (jb_reserve(b, n) != 0) return -1;
|
||||
memcpy(b->s + b->len, s, n);
|
||||
b->len += n;
|
||||
b->s[b->len] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int jb_puts(jbuf *b, const char *s) {
|
||||
return jb_putn(b, s, strlen(s));
|
||||
}
|
||||
|
||||
static int jb_printf(jbuf *b, const char *fmt, ...) {
|
||||
char tmp[512];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
int n = vsnprintf(tmp, sizeof tmp, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n < 0) return -1;
|
||||
if ((size_t)n < sizeof tmp) return jb_putn(b, tmp, (size_t)n);
|
||||
/* longer than the scratch buffer: allocate exactly */
|
||||
char *big = malloc((size_t)n + 1);
|
||||
if (!big) return -1;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(big, (size_t)n + 1, fmt, ap);
|
||||
va_end(ap);
|
||||
int rc = jb_putn(b, big, (size_t)n);
|
||||
free(big);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Append a JSON string literal (with quotes), escaping as needed. */
|
||||
static int jb_string(jbuf *b, const char *s) {
|
||||
if (!s) return jb_puts(b, "null");
|
||||
if (jb_puts(b, "\"") != 0) return -1;
|
||||
for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
|
||||
char esc[8];
|
||||
switch (*p) {
|
||||
case '"': if (jb_puts(b, "\\\"") != 0) return -1; break;
|
||||
case '\\': if (jb_puts(b, "\\\\") != 0) return -1; break;
|
||||
case '\b': if (jb_puts(b, "\\b") != 0) return -1; break;
|
||||
case '\f': if (jb_puts(b, "\\f") != 0) return -1; break;
|
||||
case '\n': if (jb_puts(b, "\\n") != 0) return -1; break;
|
||||
case '\r': if (jb_puts(b, "\\r") != 0) return -1; break;
|
||||
case '\t': if (jb_puts(b, "\\t") != 0) return -1; break;
|
||||
default:
|
||||
if (*p < 0x20) {
|
||||
snprintf(esc, sizeof esc, "\\u%04x", *p);
|
||||
if (jb_puts(b, esc) != 0) return -1;
|
||||
} else {
|
||||
if (jb_putn(b, (const char *)p, 1) != 0) return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return jb_puts(b, "\"");
|
||||
}
|
||||
|
||||
static const char *format_kind_name(int kind) {
|
||||
switch (kind) {
|
||||
case SFILE_BINARY: return "binary";
|
||||
case SFILE_TEXT: return "text";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static int jb_field_value(jbuf *b, const sfile_field *fl) {
|
||||
if (fl->beyond_window) return jb_puts(b, "null");
|
||||
if (fl->is_number) {
|
||||
if (fl->is_float) return jb_printf(b, "%.17g", fl->fnum);
|
||||
if (fl->kind == SFILE_I8 || fl->kind == SFILE_I16 ||
|
||||
fl->kind == SFILE_I32 || fl->kind == SFILE_I64)
|
||||
return jb_printf(b, "%lld", fl->inum);
|
||||
return jb_printf(b, "%llu", fl->unum);
|
||||
}
|
||||
return jb_string(b, fl->raw ? fl->raw : "");
|
||||
}
|
||||
|
||||
char *sfile_result_to_json(const sfile_result *res) {
|
||||
jbuf b = { NULL, 0, 0 };
|
||||
if (jb_puts(&b, "{") != 0) goto fail;
|
||||
if (jb_puts(&b, "\"file\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->file ? res->file : "") != 0) goto fail;
|
||||
if (jb_printf(&b, ",\"size\":") != 0) goto fail;
|
||||
if (res->size >= 0) {
|
||||
if (jb_printf(&b, "%lld", (long long)res->size) != 0) goto fail;
|
||||
} else if (jb_puts(&b, "null") != 0) goto fail;
|
||||
if (jb_printf(&b, ",\"identified\":%s", res->identified ? "true" : "false") != 0) goto fail;
|
||||
if (res->error) {
|
||||
if (jb_puts(&b, ",\"error\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->error) != 0) goto fail;
|
||||
}
|
||||
if (!res->identified) {
|
||||
if (res->hexdump) {
|
||||
if (jb_puts(&b, ",\"hexdump\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->hexdump) != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
return b.s;
|
||||
}
|
||||
|
||||
/* format */
|
||||
if (jb_puts(&b, ",\"format\":{\"task\":") != 0) goto fail;
|
||||
if (jb_printf(&b, "%d,\"ext\":", res->task) != 0) goto fail;
|
||||
if (jb_string(&b, res->ext) != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"name\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->name) != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"kind\":") != 0) goto fail;
|
||||
if (jb_string(&b, format_kind_name(res->format_kind)) != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"endian\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->endian ? "big" : "little") != 0) goto fail;
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
|
||||
if (jb_puts(&b, ",\"identified_by\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->identified_by ? res->identified_by : "") != 0) goto fail;
|
||||
|
||||
if (res->has_magic) {
|
||||
char *hex = hex_string(res->magic, res->magic_len);
|
||||
if (!hex) goto fail;
|
||||
if (jb_puts(&b, ",\"magic\":{\"bytes\":") != 0) { free(hex); goto fail; }
|
||||
if (jb_string(&b, hex) != 0) { free(hex); goto fail; }
|
||||
free(hex);
|
||||
if (jb_printf(&b, ",\"offset\":%u}", res->magic_off) != 0) goto fail;
|
||||
}
|
||||
if (res->ncandidates > 0) {
|
||||
if (jb_puts(&b, ",\"other_candidates\":[") != 0) goto fail;
|
||||
for (int i = 0; i < res->ncandidates; i++) {
|
||||
if (i && jb_puts(&b, ",") != 0) goto fail;
|
||||
if (jb_puts(&b, "{\"ext\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->candidates[i].ext) != 0) goto fail;
|
||||
if (jb_printf(&b, ",\"task\":%d}", res->candidates[i].task) != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "]") != 0) goto fail;
|
||||
}
|
||||
|
||||
if (res->doc_type != SFILE_DOC_NONE) {
|
||||
if (jb_puts(&b, ",\"document\":{") != 0) goto fail;
|
||||
switch (res->doc_type) {
|
||||
case SFILE_DOC_XML:
|
||||
if (jb_puts(&b, "\"type\":\"xml\"") != 0) goto fail;
|
||||
if (res->xml_declaration) {
|
||||
if (jb_puts(&b, ",\"declaration\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->xml_declaration) != 0) goto fail;
|
||||
}
|
||||
if (res->root_element) {
|
||||
if (jb_puts(&b, ",\"root_element\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->root_element) != 0) goto fail;
|
||||
}
|
||||
if (res->version_attr) {
|
||||
if (jb_puts(&b, ",\"version\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->version_attr) != 0) goto fail;
|
||||
}
|
||||
break;
|
||||
case SFILE_DOC_JSON:
|
||||
if (jb_puts(&b, "\"type\":\"json\"") != 0) goto fail;
|
||||
if (res->first_key) {
|
||||
if (jb_puts(&b, ",\"first_key\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->first_key) != 0) goto fail;
|
||||
}
|
||||
break;
|
||||
case SFILE_DOC_TEXT:
|
||||
default:
|
||||
if (jb_puts(&b, "\"type\":\"text\",\"first_line\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->first_line ? res->first_line : "") != 0) goto fail;
|
||||
break;
|
||||
}
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
} else if (res->has_header) {
|
||||
if (jb_puts(&b, ",\"header\":{\"endian\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->endian ? "big" : "little") != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"fields\":[") != 0) goto fail;
|
||||
for (int i = 0; i < res->nfields; i++) {
|
||||
const sfile_field *fl = &res->fields[i];
|
||||
if (i && jb_puts(&b, ",") != 0) goto fail;
|
||||
if (jb_printf(&b, "{\"offset\":%u,\"size\":%u,\"name\":",
|
||||
fl->offset, fl->size) != 0) goto fail;
|
||||
if (jb_string(&b, fl->name) != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"type\":") != 0) goto fail;
|
||||
if (jb_string(&b, sfile_field_kind_name(fl->kind)) != 0) goto fail;
|
||||
if (jb_puts(&b, ",\"value\":") != 0) goto fail;
|
||||
if (jb_field_value(&b, fl) != 0) goto fail;
|
||||
if (fl->beyond_window) {
|
||||
if (jb_puts(&b, ",\"unavailable\":\"beyond header window / EOF\"") != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "]}") != 0) goto fail;
|
||||
} else {
|
||||
/* binary format with no derived layout */
|
||||
if (jb_puts(&b, ",\"note\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->format_kind == SFILE_FORMAT_UNKNOWN
|
||||
? "no header layout derived (derivation: unknown)"
|
||||
: "no header layout derived (derivation: magic-only)") != 0) goto fail;
|
||||
if (res->hexdump) {
|
||||
if (jb_puts(&b, ",\"hexdump\":") != 0) goto fail;
|
||||
if (jb_string(&b, res->hexdump) != 0) goto fail;
|
||||
}
|
||||
}
|
||||
|
||||
/* geotags, from geotag_scan(): emitted whenever the format has a
|
||||
* geotagging mechanism (empty array when none was found), omitted
|
||||
* when it has none. Each entry carries the decoder's source
|
||||
* string plus the optional altitude/datum/datetime. */
|
||||
if (res->geotag_status >= 0) {
|
||||
if (jb_puts(&b, ",\"geotags\":[") != 0) goto fail;
|
||||
for (int i = 0; i < res->ngeotags; i++) {
|
||||
const GeoResult *g = &res->geotags[i];
|
||||
if (i && jb_puts(&b, ",") != 0) goto fail;
|
||||
if (jb_puts(&b, "{\"source\":") != 0) goto fail;
|
||||
if (jb_string(&b, g->source) != 0) goto fail;
|
||||
if (jb_printf(&b, ",\"latitude\":%.17g,\"longitude\":%.17g",
|
||||
g->lat, g->lon) != 0) goto fail;
|
||||
if (g->has_alt) {
|
||||
if (jb_printf(&b, ",\"altitude_m\":%.17g", g->alt) != 0) goto fail;
|
||||
}
|
||||
if (g->has_datum) {
|
||||
if (jb_puts(&b, ",\"datum\":") != 0) goto fail;
|
||||
if (jb_string(&b, g->datum) != 0) goto fail;
|
||||
}
|
||||
if (g->has_datetime) {
|
||||
if (jb_puts(&b, ",\"datetime_utc\":") != 0) goto fail;
|
||||
if (jb_string(&b, g->datetime) != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "]") != 0) goto fail;
|
||||
}
|
||||
if (jb_puts(&b, "}") != 0) goto fail;
|
||||
return b.s;
|
||||
|
||||
fail:
|
||||
free(b.s);
|
||||
return NULL;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""make_fixtures.py — build the small synthetic sample files the
|
||||
--json and library tests decode. Shared by tests/test_json.py and
|
||||
tests/test_lib.sh so both test the same bytes.
|
||||
|
||||
Every fixture is built from the format table in src/formats.h, so the
|
||||
expected values below are the table's own ground truth.
|
||||
"""
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
|
||||
def build_fixtures(outdir):
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
paths = {}
|
||||
|
||||
# PNG (task 564, big-endian): 800x600, 8-bit, colour type 2.
|
||||
png = (bytes.fromhex("89504e470d0a1a0a") + struct.pack(">I", 13) + b"IHDR"
|
||||
+ struct.pack(">II", 800, 600) + bytes([8, 2, 0, 0, 0]))
|
||||
paths["png"] = _write(outdir, "sample.png", png)
|
||||
|
||||
# SPS track file (task 678, big-endian, extension-only: no magic).
|
||||
# latitude 37.7749 / longitude -122.4194 at offsets 27 / 35.
|
||||
sps = bytearray(161)
|
||||
sps[0:11] = b"v1.0" + b"\x00" * 7
|
||||
struct.pack_into(">d", sps, 11, 0.0) # start
|
||||
struct.pack_into(">d", sps, 19, 3600.0) # end
|
||||
struct.pack_into(">d", sps, 27, 37.7749) # latitude
|
||||
struct.pack_into(">d", sps, 35, -122.4194) # longitude
|
||||
struct.pack_into(">d", sps, 43, 100.0) # chart_max
|
||||
struct.pack_into(">d", sps, 51, -10.0) # chart_min
|
||||
struct.pack_into(">h", sps, 59, -8) # timezone
|
||||
sps[61:72] = b"GPS" + b"\x00" * 8 # source
|
||||
sps[72:93] = b"sfile-test" + b"\x00" * 11 # author
|
||||
sps[93:114] = b"geo-fixture" + b"\x00" * 10 # name
|
||||
sps[114:155] = b"San Francisco" + b"\x00" * 28 # location
|
||||
struct.pack_into(">h", sps, 155, 2) # channels
|
||||
struct.pack_into(">i", sps, 157, 0) # note_length
|
||||
paths["sps"] = _write(outdir, "track.sps", bytes(sps))
|
||||
|
||||
# JSON document (task 334, text fallback: first key "name").
|
||||
paths["json"] = _write(outdir, "doc.json",
|
||||
b'{"name": "sfile", "version": 1}\n')
|
||||
# XML document (task 839, text fallback: root <catalog version="2.0">).
|
||||
paths["xml"] = _write(outdir, "doc.xml",
|
||||
b'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
b'<catalog version="2.0"><item/></catalog>\n')
|
||||
# Plain text (task 742).
|
||||
paths["txt"] = _write(outdir, "note.txt",
|
||||
b"Hello, sfile.\nSecond line.\n")
|
||||
# Unknown: no magic match, unknown extension.
|
||||
paths["unknown"] = _write(outdir, "mystery.zzz", bytes(range(1, 65)))
|
||||
# Empty PNG: identified by extension, every field beyond the window.
|
||||
paths["empty_png"] = _write(outdir, "empty.png", b"")
|
||||
# WEBM (task 805): magic known, FMT_UNKNOWN, no header layout.
|
||||
paths["webm"] = _write(outdir, "clip.webm",
|
||||
bytes.fromhex("1a45dfa3") + bytes(60))
|
||||
# WAB (task 802): magic known, FMT_BINARY, no header layout.
|
||||
paths["wab"] = _write(outdir, "addr.wab",
|
||||
bytes.fromhex("9ccbcb8d1375d211915800c04f7956a4")
|
||||
+ bytes(48))
|
||||
return paths
|
||||
|
||||
|
||||
def _write(outdir, name, data):
|
||||
path = os.path.join(outdir, name)
|
||||
with open(path, "wb") as fh:
|
||||
fh.write(data)
|
||||
return path
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
outdir = sys.argv[1] if len(sys.argv) > 1 else "."
|
||||
for key, path in build_fixtures(outdir).items():
|
||||
print(f"{key}: {path}")
|
||||
@@ -0,0 +1,306 @@
|
||||
#!/usr/bin/env python3
|
||||
"""test_json.py — verify `sfile --json`.
|
||||
|
||||
For every synthetic fixture (tests/make_fixtures.py) this checks:
|
||||
1. the --json output parses as JSON (one object per line);
|
||||
2. it carries the same facts as the human-readable output on the
|
||||
same file (format, identification method, magic, every header
|
||||
field, document decode, hex dump) — the text table is the
|
||||
reference, JSON must not disagree with it;
|
||||
3. exit codes match between modes (0 identified, 2 unreadable,
|
||||
3 unknown);
|
||||
4. geotags appear when geotag_scan() finds a location (the
|
||||
tests/geotag/ fixtures: a JPEG with EXIF GPS, an MP4 with two
|
||||
QuickTime locations, a JPEG with a mechanism but no location).
|
||||
Header latitude/longitude FIELDS (e.g. the SPS fixture) are not
|
||||
geotags — task 678 has no geotagging mechanism, so no key.
|
||||
|
||||
Usage:
|
||||
python3 tests/test_json.py [sfile_binary]
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from make_fixtures import build_fixtures
|
||||
|
||||
SFILE = sys.argv[1] if len(sys.argv) > 1 else "./sfile"
|
||||
|
||||
FAILURES = []
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
print(f" {'PASS' if cond else 'FAIL'} {name}" + (f" — {detail}" if detail and not cond else ""))
|
||||
if not cond:
|
||||
FAILURES.append(name)
|
||||
|
||||
|
||||
def run(args):
|
||||
return subprocess.run(args, capture_output=True, text=True)
|
||||
|
||||
|
||||
def parse_text_fields(out):
|
||||
"""(offset, size, name, value) rows of the header table.
|
||||
|
||||
Only lines after the "Header (...-endian):" heading count: the
|
||||
hex dump of an unknown file (" 01 02 03 ...") would otherwise
|
||||
match the same shape.
|
||||
"""
|
||||
fields = []
|
||||
in_table = False
|
||||
for line in out.splitlines():
|
||||
if line.startswith("Header ("):
|
||||
in_table = True
|
||||
continue
|
||||
if not in_table:
|
||||
continue
|
||||
m = re.match(r"^ +(\d+) +(\d+) +(\S+) +(.*)$", line)
|
||||
if m:
|
||||
fields.append((int(m.group(1)), int(m.group(2)), m.group(3),
|
||||
m.group(4).rstrip()))
|
||||
return fields
|
||||
|
||||
|
||||
def json_display_value(field):
|
||||
"""Rebuild the CLI's display string for a JSON field value."""
|
||||
v = field["value"]
|
||||
if v is None:
|
||||
return "(beyond header window / EOF)"
|
||||
t = field["type"]
|
||||
if t in ("u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64"):
|
||||
return str(v)
|
||||
if t in ("f32", "f64"):
|
||||
return "%g" % v
|
||||
if t == "ascii":
|
||||
return '"%s"' % v
|
||||
return v # bytes: space-separated hex
|
||||
|
||||
|
||||
def check_parity(name, fixture, text, js):
|
||||
"""The JSON object must say the same thing as the text output."""
|
||||
m = re.search(r"^Format: (.+?) \((\S+)\) — task (\d+)$", text, re.M)
|
||||
if js["identified"]:
|
||||
check(f"{name}: format task", js["format"]["task"] == int(m.group(3)) and
|
||||
js["format"]["ext"] == m.group(2) and js["format"]["name"] == m.group(1))
|
||||
m2 = re.search(r"^Identified by: (\w+)$", text, re.M)
|
||||
check(f"{name}: identified_by", js["identified_by"] == m2.group(1))
|
||||
else:
|
||||
check(f"{name}: unidentified", js["identified"] is False)
|
||||
|
||||
m3 = re.search(r"^Magic: ([0-9a-f ]+)at offset (\d+)$", text, re.M)
|
||||
if m3:
|
||||
check(f"{name}: magic", js["magic"]["bytes"] == m3.group(1).strip() and
|
||||
js["magic"]["offset"] == int(m3.group(2)))
|
||||
elif js.get("magic"):
|
||||
check(f"{name}: magic absent in text", False, "JSON has magic, text does not")
|
||||
|
||||
text_fields = parse_text_fields(text)
|
||||
json_fields = js.get("header", {}).get("fields", [])
|
||||
check(f"{name}: field count", len(text_fields) == len(json_fields),
|
||||
f"text={len(text_fields)} json={len(json_fields)}")
|
||||
for (toff, tsize, tname, tval), jf in zip(text_fields, json_fields):
|
||||
same = (toff == jf["offset"] and tsize == jf["size"]
|
||||
and tname == jf["name"])
|
||||
if jf["type"] in ("f32", "f64") and jf["value"] is not None:
|
||||
try:
|
||||
same = same and math.isclose(float(tval), jf["value"], rel_tol=1e-5) # text uses %g (6 sig. digits)
|
||||
except ValueError:
|
||||
same = False
|
||||
else:
|
||||
same = same and tval == json_display_value(jf)
|
||||
check(f"{name}: field {tname}", same, f"text={tval!r} json={jf}")
|
||||
|
||||
m4 = re.search(r"^Document type: (\w+)$", text, re.M)
|
||||
if m4:
|
||||
doc = js.get("document", {})
|
||||
check(f"{name}: document type", doc.get("type") == m4.group(1).lower())
|
||||
for key, pat in (("declaration", r"^XML declaration: (.*)$"),
|
||||
("root_element", r"^Root element: (.*)$"),
|
||||
("version", r"^Version attribute: (.*)$"),
|
||||
("first_key", r"^First key: (.*)$"),
|
||||
("first_line", r"^First line: (.*)$")):
|
||||
mm = re.search(pat, text, re.M)
|
||||
if mm:
|
||||
check(f"{name}: document {key}", doc.get(key) == mm.group(1))
|
||||
elif key in doc:
|
||||
check(f"{name}: document {key} absent in text", False)
|
||||
|
||||
m5 = re.search(r"^First 64 bytes:\n (.*)$", text, re.M)
|
||||
if m5:
|
||||
check(f"{name}: hexdump", js.get("hexdump") == m5.group(1).strip())
|
||||
|
||||
# Geotagging section (text) vs "geotags" array (JSON) — both come
|
||||
# from geotag_scan(), so they must agree.
|
||||
lats = re.findall(r"^ gps_latitude: (-?[\d.]+)", text, re.M)
|
||||
lons = re.findall(r"^ gps_longitude: (-?[\d.]+)", text, re.M)
|
||||
srcs = re.findall(r"^ source: (.*)$", text, re.M)
|
||||
alts = re.findall(r"^ gps_altitude_m: (-?[\d.]+)", text, re.M)
|
||||
datums = re.findall(r"^ gps_datum: (.*)$", text, re.M)
|
||||
whens = re.findall(r"^ gps_datetime_utc: (.*)$", text, re.M)
|
||||
has_section = "Geotagging:\n" in text
|
||||
if has_section:
|
||||
g = js.get("geotags")
|
||||
check(f"{name}: geotags present", isinstance(g, list))
|
||||
if isinstance(g, list):
|
||||
check(f"{name}: geotag count",
|
||||
len(g) == len(lats) == len(lons) == len(srcs),
|
||||
f"json={len(g)} text lat/lon/src={len(lats)}/{len(lons)}/{len(srcs)}")
|
||||
for i, gg in enumerate(g):
|
||||
if i >= len(lats):
|
||||
break
|
||||
check(f"{name}: geotag[{i}] lat/lon",
|
||||
math.isclose(gg["latitude"], float(lats[i]), abs_tol=1e-6)
|
||||
and math.isclose(gg["longitude"], float(lons[i]), abs_tol=1e-6))
|
||||
check(f"{name}: geotag[{i}] source", gg["source"] == srcs[i])
|
||||
if alts:
|
||||
check(f"{name}: geotag altitudes",
|
||||
sorted(float(a) for a in alts)
|
||||
== sorted(gg.get("altitude_m") for gg in g
|
||||
if "altitude_m" in gg))
|
||||
if datums:
|
||||
check(f"{name}: geotag datums",
|
||||
sorted(datums) == sorted(gg.get("datum") for gg in g
|
||||
if "datum" in gg))
|
||||
if whens:
|
||||
check(f"{name}: geotag datetimes",
|
||||
sorted(whens) == sorted(gg.get("datetime_utc") for gg in g
|
||||
if "datetime_utc" in gg))
|
||||
if "none found (searched" in text:
|
||||
check(f"{name}: geotags empty", g == [])
|
||||
else:
|
||||
check(f"{name}: no geotags key", "geotags" not in js)
|
||||
|
||||
|
||||
def main():
|
||||
tmp = tempfile.mkdtemp(prefix="sfile-json-test-")
|
||||
fx = build_fixtures(tmp)
|
||||
missing = os.path.join(tmp, "does-not-exist.bin")
|
||||
|
||||
print(f"sfile: {SFILE}")
|
||||
print(f"fixtures: {tmp}")
|
||||
|
||||
# --- one file at a time: JSON parses, parity holds, exit codes match
|
||||
for key in ("png", "sps", "json", "xml", "txt", "unknown",
|
||||
"empty_png", "webm", "wab"):
|
||||
path = fx[key]
|
||||
text = run([SFILE, path])
|
||||
js_run = run([SFILE, "--json", path])
|
||||
check(f"{key}: exit code", text.returncode == js_run.returncode,
|
||||
f"text={text.returncode} json={js_run.returncode}")
|
||||
lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()]
|
||||
check(f"{key}: one JSON object", len(lines) == 1,
|
||||
f"{len(lines)} lines")
|
||||
if len(lines) != 1:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(lines[0])
|
||||
except json.JSONDecodeError as exc:
|
||||
check(f"{key}: JSON parses", False, str(exc))
|
||||
continue
|
||||
check(f"{key}: JSON parses", True)
|
||||
check(f"{key}: file/size", obj["file"] == path and
|
||||
obj["size"] == os.path.getsize(path))
|
||||
check_parity(key, path, text.stdout, obj)
|
||||
|
||||
# --- geotags come from geotag_scan(), not from header fields:
|
||||
# the SPS fixture carries latitude/longitude FIELDS but task 678
|
||||
# has no geotagging mechanism, so there is no "geotags" key.
|
||||
obj = json.loads(run([SFILE, "--json", fx["sps"]]).stdout.splitlines()[0])
|
||||
check("sps: no geotags key (no mechanism)", "geotags" not in obj)
|
||||
# This PNG has a mechanism (eXIf/XMP) but carries no location.
|
||||
obj = json.loads(run([SFILE, "--json", fx["png"]]).stdout.splitlines()[0])
|
||||
check("png: geotags empty (none found)", obj.get("geotags") == [])
|
||||
|
||||
# --- real geotags, from tests/geotag/ (EXIF GPS JPEG, two-result
|
||||
# MP4, JPEG with a mechanism but no location)
|
||||
geo_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "geotag")
|
||||
for fname, want in (
|
||||
("test-gps.jpg", {"n": 1,
|
||||
"source": "EXIF GPS IFD (JPEG APP1 segment)",
|
||||
"lat": 37.7749, "lon": -122.4194, "alt": 10.0,
|
||||
"datum": "WGS-84", "when": "2026-12-01 12:34:56"}),
|
||||
("test-gps.mp4", {"n": 2, "lat": 37.7749, "lon": -122.4194}),
|
||||
("test-gps-no-gps.jpg", {"n": 0}),
|
||||
):
|
||||
path = os.path.join(geo_dir, fname)
|
||||
text = run([SFILE, path])
|
||||
js_run = run([SFILE, "--json", path])
|
||||
check(f"{fname}: exit code",
|
||||
text.returncode == js_run.returncode == 0,
|
||||
f"text={text.returncode} json={js_run.returncode}")
|
||||
lines = [ln for ln in js_run.stdout.splitlines() if ln.strip()]
|
||||
check(f"{fname}: one JSON object", len(lines) == 1)
|
||||
if len(lines) != 1:
|
||||
continue
|
||||
obj = json.loads(lines[0])
|
||||
g = obj.get("geotags")
|
||||
check(f"{fname}: geotag count",
|
||||
isinstance(g, list) and len(g) == want["n"], str(g)[:200])
|
||||
if want["n"] > 0 and isinstance(g, list) and len(g) == want["n"]:
|
||||
check(f"{fname}: lat/lon",
|
||||
all(math.isclose(x["latitude"], want["lat"], abs_tol=1e-6)
|
||||
and math.isclose(x["longitude"], want["lon"], abs_tol=1e-6)
|
||||
for x in g))
|
||||
if "source" in want:
|
||||
check(f"{fname}: source", g[0]["source"] == want["source"],
|
||||
str(g[0].get("source")))
|
||||
if "alt" in want:
|
||||
check(f"{fname}: altitude",
|
||||
math.isclose(g[0].get("altitude_m", -1), want["alt"],
|
||||
abs_tol=1e-6))
|
||||
if "datum" in want:
|
||||
check(f"{fname}: datum", g[0].get("datum") == want["datum"])
|
||||
if "when" in want:
|
||||
check(f"{fname}: datetime",
|
||||
g[0].get("datetime_utc") == want["when"])
|
||||
check_parity(fname, path, text.stdout, obj)
|
||||
|
||||
# --- shared magic: the XML fixture's JSON lists the other candidates
|
||||
obj = json.loads(run([SFILE, "--json", fx["xml"]]).stdout.splitlines()[0])
|
||||
check("xml: other_candidates listed",
|
||||
len(obj.get("other_candidates", [])) > 0
|
||||
and all("ext" in c and "task" in c for c in obj["other_candidates"]),
|
||||
str(obj.get("other_candidates"))[:120])
|
||||
|
||||
# --- unreadable file: JSON error object, exit 2, stdout stays JSON
|
||||
r = run([SFILE, "--json", missing])
|
||||
check("missing: exit 2", r.returncode == 2, f"got {r.returncode}")
|
||||
try:
|
||||
obj = json.loads(r.stdout.splitlines()[0])
|
||||
check("missing: JSON error object",
|
||||
obj["identified"] is False and obj["size"] is None
|
||||
and isinstance(obj.get("error"), str) and obj["error"])
|
||||
except (IndexError, json.JSONDecodeError) as exc:
|
||||
check("missing: JSON error object", False, str(exc))
|
||||
|
||||
# --- several files: one JSON object per line, worst exit code wins
|
||||
r = run([SFILE, "--json", fx["png"], fx["sps"], fx["unknown"]])
|
||||
lines = [ln for ln in r.stdout.splitlines() if ln.strip()]
|
||||
check("multi: three JSON lines", len(lines) == 3, f"{len(lines)} lines")
|
||||
check("multi: exit 3 (one unknown)", r.returncode == 3,
|
||||
f"got {r.returncode}")
|
||||
try:
|
||||
objs = [json.loads(ln) for ln in lines]
|
||||
check("multi: all parse", True)
|
||||
check("multi: tasks in order",
|
||||
[o.get("format", {}).get("task") for o in objs] == [564, 678, None])
|
||||
except json.JSONDecodeError as exc:
|
||||
check("multi: all parse", False, str(exc))
|
||||
r = run([SFILE, "--json", fx["png"], missing])
|
||||
check("multi: exit 2 beats 3", r.returncode == 2, f"got {r.returncode}")
|
||||
|
||||
print()
|
||||
if FAILURES:
|
||||
print(f"FAILED: {len(FAILURES)} check(s): {', '.join(FAILURES)}")
|
||||
return 1
|
||||
print("test_json: all checks passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/bin/sh
|
||||
# test_lib.sh — build + run the libsfile link test (static and shared).
|
||||
#
|
||||
# Compiles tests/test_library.c against libsfile.a and against
|
||||
# libsfile.so, then checks both against the `sfile` CLI on the same
|
||||
# fixtures: the field lines must match the CLI's header table exactly,
|
||||
# the geotag must come through, and the JSON the library emits must
|
||||
# parse. Usage: ./tests/test_lib.sh (run from the repo root)
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
TMP=$(mktemp -d /tmp/sfile-lib-test-XXXXXX)
|
||||
trap 'rm -rf "$TMP"' EXIT INT TERM
|
||||
|
||||
python3 tests/make_fixtures.py "$TMP" > /dev/null
|
||||
|
||||
fail=0
|
||||
note() { # note <ok|FAIL> <message>
|
||||
if [ "$1" = ok ]; then echo " PASS $2"; else echo " FAIL $2"; fail=1; fi
|
||||
}
|
||||
|
||||
# CLI field lines in the same "field: name=value" form the C program prints.
|
||||
cli_fields() {
|
||||
./sfile "$1" | grep -E '^ [0-9]+ ' \
|
||||
| sed -E 's/^ +[0-9]+ +[0-9]+ +([^ ]+) +/\1=/' \
|
||||
| sed 's/[[:space:]]*$//; s/^/field: /'
|
||||
}
|
||||
|
||||
for variant in static shared; do
|
||||
echo "link variant: $variant"
|
||||
if [ "$variant" = static ]; then
|
||||
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o "$TMP/t_$variant" \
|
||||
tests/test_library.c libsfile.a
|
||||
else
|
||||
gcc -O2 -Wall -Wextra -std=c11 -Isrc -o "$TMP/t_$variant" \
|
||||
tests/test_library.c -L. -lsfile -Wl,-rpath,"$PWD"
|
||||
fi
|
||||
for fx in sample.png track.sps; do
|
||||
if "$TMP/t_$variant" "$TMP/$fx" > "$TMP/out.txt" 2>&1; then
|
||||
note ok "$variant $fx: exit 0"
|
||||
else
|
||||
note FAIL "$variant $fx: exit $?"
|
||||
fi
|
||||
# fields printed by the library vs fields printed by the CLI
|
||||
grep '^field: ' "$TMP/out.txt" | sed 's/[[:space:]]*$//' > "$TMP/lib_fields.txt"
|
||||
cli_fields "$TMP/$fx" > "$TMP/cli_fields.txt"
|
||||
if diff -q "$TMP/lib_fields.txt" "$TMP/cli_fields.txt" > /dev/null; then
|
||||
note ok "$variant $fx: library fields == CLI fields"
|
||||
else
|
||||
note FAIL "$variant $fx: library fields != CLI fields"
|
||||
diff "$TMP/lib_fields.txt" "$TMP/cli_fields.txt" | head -10
|
||||
fi
|
||||
# the library's own JSON line must parse
|
||||
grep '^json: ' "$TMP/out.txt" | sed 's/^json: //' > "$TMP/lib.json"
|
||||
if python3 -c "import json,sys; json.load(open('$TMP/lib.json'))"; then
|
||||
note ok "$variant $fx: library JSON parses"
|
||||
else
|
||||
note FAIL "$variant $fx: library JSON does not parse"
|
||||
fi
|
||||
if [ "$fx" = sample.png ]; then
|
||||
# PNG has a geotagging mechanism but this fixture has none.
|
||||
if python3 -c "import json,sys; d=json.load(open('$TMP/lib.json')); sys.exit(0 if d.get('geotags')==[] else 1)"; then
|
||||
note ok "$variant $fx: library JSON geotags empty (none found)"
|
||||
else
|
||||
note FAIL "$variant $fx: library JSON geotags should be []"
|
||||
fi
|
||||
fi
|
||||
if [ "$fx" = track.sps ]; then
|
||||
# SPS header lat/lon fields are not a geotag: no mechanism.
|
||||
if python3 -c "import json,sys; d=json.load(open('$TMP/lib.json')); sys.exit(0 if 'geotags' not in d else 1)"; then
|
||||
note ok "$variant $fx: library JSON has no geotags key (no mechanism)"
|
||||
else
|
||||
note FAIL "$variant $fx: library JSON should have no geotags key"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
# --mem path decodes from a buffer, not from disk
|
||||
if "$TMP/t_$variant" --mem "$TMP/sample.png" > "$TMP/mem.txt" 2>&1 \
|
||||
&& grep -q '^field: width=800$' "$TMP/mem.txt"; then
|
||||
note ok "$variant --mem: decodes PNG from memory (width=800)"
|
||||
else
|
||||
note FAIL "$variant --mem: PNG decode from memory"
|
||||
fi
|
||||
done
|
||||
|
||||
# geotags come through the library (EXIF GPS JPEG: one result).
|
||||
# Note: test_library decodes from disk here, so sfile_decode_file()
|
||||
# runs geotag_scan(); --mem mode never scans (no path to scan).
|
||||
if "$TMP/t_static" tests/geotag/test-gps.jpg | grep -q '^geotag: 37.774900 -122.419400 (EXIF GPS IFD (JPEG APP1 segment))$'; then
|
||||
note ok "library geotag: 37.774900 -122.419400 (EXIF GPS)"
|
||||
else
|
||||
note FAIL "library geotag missing or wrong"
|
||||
fi
|
||||
if "$TMP/t_static" tests/geotag/test-gps.jpg > "$TMP/jpg.txt" 2>&1; then
|
||||
grep '^json: ' "$TMP/jpg.txt" | sed 's/^json: //' > "$TMP/jpg.json"
|
||||
if python3 -c "import json,sys,math; d=json.load(open('$TMP/jpg.json')); g=d['geotags'][0]; sys.exit(0 if len(d['geotags'])==1 and math.isclose(g['latitude'],37.7749,abs_tol=1e-6) and math.isclose(g['longitude'],-122.4194,abs_tol=1e-6) and g['source']=='EXIF GPS IFD (JPEG APP1 segment)' and g.get('altitude_m')==10.0 and g.get('datum')=='WGS-84' and g.get('datetime_utc')=='2026-12-01 12:34:56' else 1)"; then
|
||||
note ok "library JSON geotags: EXIF GPS, alt 10.0, WGS-84, 2026-12-01 12:34:56"
|
||||
else
|
||||
note FAIL "library JSON geotags wrong"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$fail" = 0 ]; then
|
||||
echo "test_lib: all checks passed"
|
||||
exit 0
|
||||
else
|
||||
echo "test_lib: FAILED"
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,94 @@
|
||||
/* test_library.c — link test for libsfile.
|
||||
*
|
||||
* Decodes a file through the public API only (no CLI code) and prints
|
||||
* the result in a canonical form that tests/test_lib.sh diffs against
|
||||
* the `sfile` CLI's own output on the same file. If the library and
|
||||
* the CLI disagree, the test fails.
|
||||
*
|
||||
* Usage: test_library [--mem] <file>
|
||||
* --mem decodes from a memory buffer (sfile_decode_mem) instead of
|
||||
* from disk (sfile_decode_file).
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "sfile.h"
|
||||
|
||||
static uint8_t *slurp(const char *path, long *n_out) {
|
||||
FILE *fp = fopen(path, "rb");
|
||||
if (!fp) return NULL;
|
||||
fseek(fp, 0, SEEK_END);
|
||||
long n = ftell(fp);
|
||||
fseek(fp, 0, SEEK_SET);
|
||||
uint8_t *buf = malloc(n > 0 ? (size_t)n : 1);
|
||||
if (!buf) { fclose(fp); return NULL; }
|
||||
size_t got = fread(buf, 1, (size_t)n, fp);
|
||||
fclose(fp);
|
||||
*n_out = (long)got;
|
||||
return buf;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int use_mem = 0;
|
||||
const char *path = NULL;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--mem") == 0) use_mem = 1;
|
||||
else path = argv[i];
|
||||
}
|
||||
if (!path) {
|
||||
fprintf(stderr, "usage: %s [--mem] <file>\n", argv[0]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("version: %s\n", SFILE_VERSION);
|
||||
printf("formats: %d\n", sfile_format_count());
|
||||
|
||||
sfile_result r;
|
||||
int st;
|
||||
if (use_mem) {
|
||||
long n = 0;
|
||||
uint8_t *buf = slurp(path, &n);
|
||||
if (!buf) { fprintf(stderr, "cannot read %s\n", path); return 2; }
|
||||
st = sfile_decode_mem(buf, (size_t)n, path, n, &r);
|
||||
free(buf);
|
||||
} else {
|
||||
st = sfile_decode_file(path, &r);
|
||||
}
|
||||
printf("status: %d\n", st);
|
||||
if (!r.identified) {
|
||||
printf("identified: no\n");
|
||||
if (r.error) printf("error: %s\n", r.error);
|
||||
sfile_free_result(&r);
|
||||
return st;
|
||||
}
|
||||
printf("format: %s (%s) task %d by %s\n",
|
||||
r.name, r.ext, r.task, r.identified_by);
|
||||
for (int i = 0; i < r.nfields; i++)
|
||||
printf("field: %s=%s\n", r.fields[i].name, r.fields[i].value);
|
||||
if (r.doc_type == SFILE_DOC_XML) {
|
||||
printf("doc: xml root=%s\n", r.root_element ? r.root_element : "");
|
||||
if (r.version_attr) printf("doc: version=%s\n", r.version_attr);
|
||||
} else if (r.doc_type == SFILE_DOC_JSON) {
|
||||
printf("doc: json\n");
|
||||
if (r.first_key) printf("doc: first_key=%s\n", r.first_key);
|
||||
} else if (r.doc_type == SFILE_DOC_TEXT) {
|
||||
printf("doc: text first_line=%s\n", r.first_line ? r.first_line : "");
|
||||
}
|
||||
if (r.ngeotags > 0) {
|
||||
for (int i = 0; i < r.ngeotags; i++)
|
||||
printf("geotag: %.6f %.6f (%s)\n",
|
||||
r.geotags[i].lat, r.geotags[i].lon, r.geotags[i].source);
|
||||
} else if (r.geotag_status == 0) {
|
||||
printf("geotag: none found\n");
|
||||
}
|
||||
char *js = sfile_result_to_json(&r);
|
||||
if (js) {
|
||||
printf("json: %s\n", js);
|
||||
free(js);
|
||||
} else {
|
||||
printf("json: (null)\n");
|
||||
}
|
||||
sfile_free_result(&r);
|
||||
return st;
|
||||
}
|
||||
Reference in new issue
Block a user