diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index acbdeff607..02cdf71c82 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -158,7 +158,7 @@ dependencies: repo_id: 192625525 'dtolnay/rust-toolchain@stable': ref: 'stable' - commit: 'sha1-b725eda525362e7cf34af9a7243cac1e3f01a7ec' + commit: 'sha1-39008827e6b4319a349e9a42dfc90579dd25f1ca' owner_id: 1940490 repo_id: 260749683 'step-security/dtolnay-rust-toolchain@v1.0.0': diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index a7a3bb587a..20e9474806 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -10,6 +10,14 @@ on: permissions: contents: read +concurrency: + # Pull requests share one group per branch, so a newer push cancels the older run. Every other + # run (push to main, a release tag, a manual run) gets a group of its own: it is neither + # cancelled nor replaced while queued, so a main run always finishes and saves the dependency + # cache, and a release run is never cancelled. + group: workspace-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: native: name: Workspace @@ -39,6 +47,7 @@ jobs: printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$corpus_fetcher/corpus" >> "$GITHUB_ENV" printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" command: | + python3 scripts/test-workspace-concurrency.py cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 32bae195dc..ef3b98f31f 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -6,6 +6,8 @@ author, source and license. Library code and original assets are under the repos | File | Author | Source | License | |---|---|---|---| +| `licenses/jpeg-encoder-0.6.1/`, `crates/image-codecs/NOTICE` | jpeg-encoder contributors and the IJG, libjpeg-turbo and SIMD authors named in the retained notices | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1), used unmodified; source checksums in `SOURCE.json` | (MIT OR Apache-2.0) AND IJG | +| `crates/smime/testdata/` | MailCraft contributors; RFC 9216 example certificates | [MailCraft at 240d1d42](https://github.com/UCS-Care-Group/mailcraft/tree/240d1d42fe394cf3274402b180663ba9b43ca180/crates/smime/testdata), restored unmodified; provenance in the directory README | MIT OR Apache-2.0 (source repository) | | `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | @@ -94,3 +96,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/raw/docs/raf-corpus.sha256` (hashes only; the files are not bundled) | The photographers who contributed each file to raw.pixls.us | [raw.pixls.us](https://raw.pixls.us/) | CC0-1.0 | | `crates/drawingml/src/preset_text.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_guides.py` from the guide formulas of ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | | `crates/drawingml/tests/fixtures/preset_table.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_table.py` from ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | + +## Binary Apple property lists + +`crates/plist` is extracted from `storytold/craft-anything` (`crates/formats/src/plist.rs` and checked byte reads), at source main `88d1d9cac852aec1c7fd97886db451e005e49d2a`. MIT OR Apache-2.0; source license texts are retained in the crate. Primary import Git authors preserve Brandon Thomas, BFlat, RRFZ and Afloat. Regression imports preserve BFlat. XML, JSON projection, calendar formatting and app policy were not imported into the public API. diff --git a/Cargo.lock b/Cargo.lock index fab3c89a3d..23bcce0b91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,6 +222,16 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "aotuv_lancer_vorbis_sys" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bc4fd1a61860d2f1198b60bedd30910eaffa978f1ee6214dfb24ac70d589225" +dependencies = [ + "cc", + "ogg_next_sys", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -291,6 +301,45 @@ dependencies = [ "libloading", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -554,6 +603,9 @@ name = "bit-vec" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] [[package]] name = "bit-vec" @@ -1083,7 +1135,7 @@ dependencies = [ "crmf", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -1095,7 +1147,19 @@ dependencies = [ "const-oid 0.9.6", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", +] + +[[package]] +name = "cms" +version = "0.3.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d089eddc8a5c984d82fcf1427367a6fa0d019d5af04b6e3197e86c8989533b8d" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", + "x509-cert 0.3.0", ] [[package]] @@ -1342,6 +1406,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "craft-xml", "log", "proptest", "rayon", @@ -1349,8 +1414,13 @@ dependencies = [ "serde_json", "symphonia", "thiserror 2.0.21", + "vorbis_rs", ] +[[package]] +name = "craft-ber" +version = "0.1.0" + [[package]] name = "craft-captions" version = "0.1.0" @@ -1773,6 +1843,13 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gzip" +version = "0.1.0" +dependencies = [ + "flate2", +] + [[package]] name = "craft-hdr" version = "0.1.0" @@ -1850,6 +1927,8 @@ dependencies = [ "craft-heif", "craft-jpeg", "craft-metadata", + "craft-video", + "crc32fast", "exr", "flate2", "half", @@ -1864,6 +1943,7 @@ dependencies = [ "ravif", "rayon", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "zune-core", @@ -1897,6 +1977,13 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-jsonrpc" +version = "0.1.0" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-jxl" version = "0.1.0" @@ -1985,6 +2072,24 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mcp" +version = "0.1.0" +dependencies = [ + "craft-jsonrpc", + "serde_json", +] + [[package]] name = "craft-media" version = "0.1.0" @@ -2172,6 +2277,7 @@ dependencies = [ name = "craft-pcraft-format" version = "0.1.0" dependencies = [ + "flate2", "serde", "serde_json", "thiserror 2.0.21", @@ -2301,6 +2407,13 @@ dependencies = [ "zbus", ] +[[package]] +name = "craft-plist" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-plotter" version = "0.1.0" @@ -2369,6 +2482,16 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-proto" +version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "log", + "proptest", + "zeroize", +] + [[package]] name = "craft-ps" version = "0.1.0" @@ -2419,7 +2542,6 @@ dependencies = [ "base64 0.23.1", "craft-image-codecs", "image", - "rayon", "thiserror 2.0.21", ] @@ -2515,6 +2637,37 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-smime" +version = "0.1.0" +dependencies = [ + "aes 0.9.4", + "base64 0.23.1", + "cbc", + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "craft-ber", + "der 0.8.3", + "des 0.9.0", + "hmac 0.13.0", + "p256 0.14.0", + "p384 0.14.0", + "pbkdf2", + "pkcs1 0.8.0", + "pkcs12", + "proptest", + "rcgen", + "ring", + "rsa 0.10.0-rc.18", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "spki 0.8.1", + "thiserror 2.0.21", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "craft-stencilcraft-document" version = "0.1.0" @@ -2555,6 +2708,7 @@ version = "0.1.0" dependencies = [ "craft-image-codecs", "craft-xml", + "data-url", "flate2", "kurbo 0.13.1", "resvg 0.48.1", @@ -2573,6 +2727,16 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-tcraft" +version = "0.1.0" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-testkit" version = "0.1.0" @@ -2725,6 +2889,7 @@ version = "0.1.0" dependencies = [ "craft-media", "craft-media-testkit", + "rav1e", "rayon", "thiserror 2.0.21", ] @@ -2807,6 +2972,7 @@ dependencies = [ name = "craft-xfl" version = "0.1.0" dependencies = [ + "craft-xml", "miniz_oxide 0.8.9", "thiserror 2.0.21", ] @@ -2881,10 +3047,10 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" dependencies = [ - "cms", + "cms 0.2.3", "der 0.7.10", "spki 0.7.3", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -3108,6 +3274,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -3130,7 +3302,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "der_derive", + "der_derive 0.7.3", "flagset", "pem-rfc7468 0.7.0", "zeroize", @@ -3143,10 +3315,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.3", + "der_derive 0.8.0", + "flagset", "pem-rfc7468 1.0.0", "zeroize", ] +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "der_derive" version = "0.7.3" @@ -3158,6 +3346,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.9" @@ -6613,6 +6812,24 @@ dependencies = [ "phf 0.11.3", ] +[[package]] +name = "ogg_next_sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2d7a48e247c2bb07e633aefb65a38648ea58c7eedd4e4408a5861721ab049b" +dependencies = [ + "cc", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -7102,6 +7319,21 @@ dependencies = [ "spki 0.8.1", ] +[[package]] +name = "pkcs12" +version = "0.2.0-rc.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd993500a1de8a428a2e6cc9a2ec942c99a801a88d58a24fb986c5ad3b767ca" +dependencies = [ + "cms 0.3.0-rc.2", + "const-oid 0.10.3", + "der 0.8.3", + "digest 0.11.3", + "spki 0.8.1", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "pkcs8" version = "0.10.2" @@ -7731,6 +7963,19 @@ dependencies = [ "cipher 0.5.2", ] +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.39.2" @@ -8098,6 +8343,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -8628,7 +8882,7 @@ dependencies = [ "spki 0.7.3", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8677,7 +8931,7 @@ dependencies = [ "sigstore-crypto", "sigstore-types", "thiserror 2.0.21", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -8690,7 +8944,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cmpv2", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "der 0.7.10", "hex", @@ -8702,7 +8956,7 @@ dependencies = [ "sigstore-types", "thiserror 2.0.21", "tracing", - "x509-cert", + "x509-cert 0.2.5", "x509-tsp", ] @@ -8729,7 +8983,7 @@ checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" dependencies = [ "base64 0.22.1", "chrono", - "cms", + "cms 0.2.3", "const-oid 0.9.6", "hex", "pem", @@ -8748,7 +9002,7 @@ dependencies = [ "thiserror 2.0.21", "tls_codec", "tracing", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -9299,6 +9553,17 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -10374,6 +10639,20 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vorbis_rs" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49c5da94d280f7a27e8c937e9b73df2da3e23a2583f48471fd8fb4c72f9c1933" +dependencies = [ + "aotuv_lancer_vorbis_sys", + "errno", + "getrandom 0.4.3", + "ogg_next_sys", + "thiserror 2.0.21", + "tinyvec", +] + [[package]] name = "wait-timeout" version = "0.2.1" @@ -11119,7 +11398,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=72951d7455ebcab569fbd9386c513d3d9f53fb02#72951d7455ebcab569fbd9386c513d3d9f53fb02" +source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57" dependencies = [ "flate2", "fmt-derive", @@ -11290,6 +11569,35 @@ dependencies = [ "tls_codec", ] +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid 0.10.3", + "der 0.8.3", + "spki 0.8.1", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "x509-tsp" version = "0.1.0" @@ -11297,7 +11605,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" dependencies = [ "cmpv2", - "cms", + "cms 0.2.3", "der 0.7.10", ] @@ -11360,6 +11668,16 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec 0.9.1", + "time", +] + [[package]] name = "yeslogic-fontconfig-sys" version = "6.0.1" @@ -11391,7 +11709,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] @@ -11502,7 +11820,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.6", - "synstructure", + "synstructure 0.14.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fab6b70440..6b83f0ab91 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,9 +11,13 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-smime = { path = "crates/smime" } +craft-ber = { path = "crates/ber" } +craft-proto = { path = "crates/proto" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` +craft-plist = { path = "crates/plist" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } @@ -34,6 +38,7 @@ hayro-syntax = { version = "=0.7.2", default-features = false, features = ["std" bytemuck = "1" kurbo = "0.13" thiserror = "2" +craft-gzip = { path = "crates/gzip" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } craft-captions = { path = "crates/captions" } @@ -48,6 +53,7 @@ craft-dialogs = { path = "crates/dialogs" } craft-doc-binary = { path = "crates/doc-binary" } craft-docx = { path = "crates/docx" } craft-document-bundle = { path = "crates/document-bundle" } +craft-mcmat = { path = "crates/mcmat" } craft-designcraft-format = { path = "crates/designcraft-format" } craft-dxf = { path = "crates/dxf" } craft-drawingml = { path = "crates/drawingml" } @@ -85,6 +91,8 @@ craft-indd = { path = "crates/indd" } craft-jmap = { path = "crates/jmap" } craft-ical = { path = "crates/ical" } craft-jpeg = { path = "crates/jpeg" } +craft-jsonrpc = { path = "crates/jsonrpc" } +craft-mcp = { path = "crates/mcp" } craft-jxl = { path = "crates/jxl" } craft-kiwi = { path = "crates/kiwi" } craft-keymap = { path = "crates/keymap" } @@ -140,6 +148,7 @@ craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } +craft-tcraft = { path = "crates/tcraft" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } craft-timeline = { path = "crates/timeline" } diff --git a/NOTICE b/NOTICE index 4fa5e4754e..c3cdbabc8a 100644 --- a/NOTICE +++ b/NOTICE @@ -296,3 +296,126 @@ implementation, https://github.com/macosforge/alac at c38887c5c5e64a4b31108733bd (LICENSE-APACHE). The files are modified: translated to Rust, with bounds checks on hostile input, wrapping integer arithmetic, the unrolled predictor and per-width matrix routines folded into one, and the average bit rate filled in. Those files are Apache-2.0 only. + +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root. +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index d132f23da2..c411a0357b 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -19,18 +19,20 @@ workspace = true # µ-law and free-format MP3 through symphonia. decode = ["decode-native", "symphonia"] # `decode` without symphonia: only the formats with a native decoder (others are Unsupported). -decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log"] +decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-decode", "mp3-decode", "craft-media/isobmff", "craft-media/matroska", "craft-media/ogg", "dep:log", "dep:craft-xml"] # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. # All but Opus are also file formats of `encode` and `FileEncoder`. -encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] +encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] # Encode WAV/BWF/RF64 and AIFF/AIFF-C files. pcm-encode = [] # Encode FLAC files. flac-encode = ["craft-media/bitstream"] +# Encode Ogg Vorbis files (desktop only: builds the reference libvorbis from its C sources). +vorbis-encode = ["dep:vorbis_rs"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. @@ -58,6 +60,7 @@ serde = ["dep:serde", "craft-media/serde"] [dependencies] craft-media = { workspace = true } +craft-xml = { workspace = true, optional = true } thiserror = { workspace = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } @@ -65,6 +68,9 @@ rayon = { workspace = true, optional = true } # symphonia keeps its AAC decoder for AAC in CAF, a container craft-media does not read. symphonia = { version = "0.6.1", optional = true, default-features = false, features = ["mp3", "flac", "vorbis", "ogg", "wav", "pcm", "aiff", "isomp4", "aac", "alac", "adpcm", "caf", "mkv"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +vorbis_rs = { version = "0.5", optional = true } + [dev-dependencies] craft-media-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..63251db8d8 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -761,3 +761,8 @@ The codec modules' public items keep their names, so apps can re-export them CAF. MP4 and Matroska files decode to presentation length. A packet that fails is concealed, not dropped. A failed source read is `AudioError::Io`. + +WAV timestamps use `bext` when present, including a zero timestamp. Otherwise a bounded iXML +`BWFXML/BEXT` time reference supplies the timestamp (two unsigned 32-bit words; an omitted high +word is zero). Only the first iXML chunk is considered. Invalid or oversized optional XML is +ignored without rejecting the audio. This works for byte-backed and streaming sources. diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcfe..33dcdee3b5 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -62,9 +62,12 @@ mod wav; feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", - feature = "eac3-encode" + feature = "eac3-encode", + feature = "vorbis-encode" ))] mod write; +#[cfg(feature = "vorbis-encode")] +pub use write::{OGG_BITRATES, encode_ogg}; /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or /// its own `.flac` writer): planar integer samples in, frames out, and the STREAMINFO to patch in @@ -107,8 +110,6 @@ pub use read::{ pub use read::{RawPcm, aiff_pcm, wav_pcm}; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -118,7 +119,20 @@ pub use write::wav_float_header; feature = "ac3-encode", feature = "eac3-encode" ))] -pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +pub use write::FileEncoder; +#[cfg(feature = "pcm-encode")] +pub use write::wav_float_header; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "vorbis-encode" +))] +pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; @@ -256,6 +270,8 @@ pub enum EncodeFormat { Ac3, /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. Eac3, + /// Ogg Vorbis, whole-buffer encoding only. + Ogg, } impl EncodeFormat { @@ -270,6 +286,7 @@ impl EncodeFormat { EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3, + EncodeFormat::Ogg, ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, @@ -284,6 +301,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3", EncodeFormat::Ac3 => "ac3", EncodeFormat::Eac3 => "eac3", + EncodeFormat::Ogg => "ogg", } } @@ -297,6 +315,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "audio/mpeg", EncodeFormat::Ac3 => "audio/ac3", EncodeFormat::Eac3 => "audio/eac3", + EncodeFormat::Ogg => "audio/ogg", } } @@ -309,6 +328,7 @@ impl EncodeFormat { EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, EncodeFormat::Mp3 => Container::MpegAudio, EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, + EncodeFormat::Ogg => Container::Ogg, } } @@ -322,6 +342,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => CodecId::Mp3, EncodeFormat::Ac3 => CodecId::Ac3, EncodeFormat::Eac3 => CodecId::Eac3, + EncodeFormat::Ogg => CodecId::Vorbis, } } @@ -335,10 +356,11 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3-encode", EncodeFormat::Ac3 => "ac3-encode", EncodeFormat::Eac3 => "eac3-encode", + EncodeFormat::Ogg => "vorbis-encode", } } - /// Whether [`encode`] and [`FileEncoder`] write this format in this build (its + /// Whether [`encode`] writes this format in this build (its /// [`feature`](Self::feature) is on): what to filter [`EncodeFormat::ALL`] by for a menu. pub fn is_built(self) -> bool { match self { @@ -349,6 +371,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + EncodeFormat::Ogg => cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), } } @@ -359,7 +382,7 @@ impl EncodeFormat { EncodeFormat::Aac => Some(&[7350, 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 64_000, 88_200, 96_000]), EncodeFormat::Mp3 => Some(&[16_000, 22_050, 24_000, 32_000, 44_100, 48_000]), EncodeFormat::Ac3 | EncodeFormat::Eac3 => Some(&[32_000, 44_100, 48_000]), - EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac => None, + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac | EncodeFormat::Ogg => None, } } @@ -371,7 +394,7 @@ impl EncodeFormat { EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, EncodeFormat::Ac3 => 6, - EncodeFormat::Mp3 => 2, + EncodeFormat::Mp3 | EncodeFormat::Ogg => 2, } } @@ -385,7 +408,7 @@ impl EncodeFormat { EncodeFormat::Aac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x607], &[0x60F], &[0x70F], &[0xFF]], // Apple's layout tags for 1–8 channels, surrounds as back speakers. EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], - EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + EncodeFormat::Mp3 | EncodeFormat::Ogg => &[&[0x4], &[0x3]], // The coding modes 1/0 to 3/2 with and without an LFE, by channel count. EncodeFormat::Ac3 => &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F]], // The same, and 7.1 with backs and sides. @@ -436,7 +459,7 @@ impl EncodeFormat { /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take /// [`EncodeOptions::rate_control`] and ignore the bit depth and dither. pub fn is_lossy(self) -> bool { - matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3) + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 | EncodeFormat::Ogg) } } @@ -449,7 +472,8 @@ pub enum RateControl { /// set of rates (MP3, AC-3) uses the highest one not above it; a rate outside what the /// stream can carry is moved to the nearest one inside. AAC is written at 6 kbit/s or a /// quarter of the sample rate per channel at least: from about half of that down its encoder - /// codes silence. + /// codes silence. Vorbis treats this as a VBR target (64–500 kbit/s), falling back to + /// a quality preset when that target is unsupported; it does not promise a constant bitrate. Bitrate(u32), /// A constant quality from 0.0 (smallest) to 1.0 (best), at whatever bit rate each frame /// needs. AAC only; values outside the range are clamped, and NaN is an error. diff --git a/crates/audio/src/read/wav.rs b/crates/audio/src/read/wav.rs index bd9c2301ac..c1552d7e29 100644 --- a/crates/audio/src/read/wav.rs +++ b/crates/audio/src/read/wav.rs @@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option { }) } +/// Cap optional metadata independently of audio length, including on range-backed sources. +const IXML_MAX: usize = 1 << 20; + +/// iXML's BEXT mirror is a fallback only: a real `bext` always wins, including timestamp zero. +/// Read the two unsigned 32-bit words, not arbitrary text that merely contains their tag names. +fn ixml_time_reference(bytes: &[u8]) -> Option { + let options = craft_xml::Options { + doctype: craft_xml::Doctype::Reject, + ..craft_xml::Options::default().strict().with_limits(craft_xml::Limits { + max_input: IXML_MAX, + max_depth: 32, + max_nodes: 8192, + max_attrs: 64, + max_attrs_total: 8192, + ..craft_xml::Limits::default() + }) + }; + let root = options.parse(bytes).ok()?; + if root.name != "BWFXML" { + return None; + } + let mut bexts = root.children("BEXT"); + let bext = bexts.next()?; + if bexts.next().is_some() { + return None; + } + let word = |name: &str| -> Option> { + let mut fields = bext.children(name); + let Some(field) = fields.next() else { return Some(None) }; + if fields.next().is_some() || field.children.iter().any(|n| matches!(n, craft_xml::Node::El(_))) { + return None; + } + let text = field.text(); + let text = text.trim(); + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(Some(text.parse().ok()?)) + }; + let low = word("BWF_TIME_REFERENCE_LOW")??; + let high = word("BWF_TIME_REFERENCE_HIGH")?.unwrap_or(0); + Some((u64::from(high) << 32) | u64::from(low)) +} + /// Refuse the WAVE file at `at`, which symphonia reads (A-law, ADPCM, ...), if an INFO entry /// claims more bytes than the file holds: symphonia allocates each entry's length. Chunks are /// walked where symphonia reads them: after the bytes a chunk's parser used, not its length. @@ -239,7 +283,7 @@ fn pcm_layout(fmt: &Fmt) -> Result> { } /// Parse a WAV file's chunks: its format, `bext` metadata and where its samples are. Only chunk -/// headers and the small `fmt `, `bext` and `ds64` bodies are read. +/// headers, small `fmt `, `bext` and `ds64` bodies, and at most one 1 MiB iXML document are read. pub(crate) fn parse(src: &Src<'_>) -> Result { if !is_wav(&src.bytes_upto(0, 12)) { return Err(AudioError::Malformed("not a RIFF/RF64 WAVE file".into())); @@ -249,6 +293,8 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let mut ds64_data: Option = None; let mut fmt: Option = None; let mut bwf: Option = None; + let mut ixml_time = None; + let mut ixml_seen = false; let mut data: Option<(u64, u64)> = None; let mut pos: u64 = 12; @@ -288,7 +334,18 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { let small = |n: u64| src.bytes(body, usize::try_from(declared.min(n)).unwrap_or(0)).unwrap_or_default(); match &id { b"fmt " => fmt = Some(parse_fmt(&small(256))?), - b"bext" => bwf = parse_bext(&small(4096)), + b"bext" => { + if let Some(info) = parse_bext(&small(4096)) { + bwf = Some(info); + } + } + b"iXML" if !ixml_seen => { + // Inspect at most one bounded document, not 100,000 individually bounded trees. + ixml_seen = true; + if declared <= IXML_MAX as u64 { + ixml_time = ixml_time_reference(&small(IXML_MAX as u64)); + } + } b"ds64" => ds64_data = le_u64(&small(64), 8), _ => {} } @@ -297,6 +354,9 @@ pub(crate) fn parse(src: &Src<'_>) -> Result { pos = next; } + if bwf.is_none() { + bwf = ixml_time.map(|time_reference| BwfInfo { time_reference, ..BwfInfo::default() }); + } let fmt = fmt.ok_or_else(|| AudioError::Malformed("WAV has no fmt chunk".into()))?; if fmt.channels == 0 { return Err(AudioError::Malformed("WAV declares zero channels".into())); diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 0de55c394b..ce4b90773b 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -9,6 +9,10 @@ mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; mod pcm; +#[cfg(feature = "vorbis-encode")] +mod vorbis; +#[cfg(feature = "vorbis-encode")] +pub use vorbis::{OGG_BITRATES, encode as encode_ogg}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -17,6 +21,15 @@ mod wav; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; #[cfg(feature = "pcm-encode")] pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] use std::io::{Seek, Write}; /// Encode `buf` as the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float @@ -51,6 +64,18 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { EncodeFormat::Flac => flac::encode(buf, opts.bit_depth, opts.dither, mask), #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => coded::encode(buf, opts), + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => { + if opts.layout.is_some_and(|layout| !EncodeFormat::Ogg.supports_layout(&layout)) { + return Err(AudioError::Unsupported("Vorbis requires a mono or stereo speaker layout".into())); + } + let kbps = match opts.rate_control { + None => 192, + Some(crate::RateControl::Bitrate(bps)) => bps / 1000, + Some(crate::RateControl::Quality(_)) => return Err(AudioError::Unsupported("Ogg export takes a target bitrate".into())), + }; + vorbis::encode(buf, kbps) + } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -62,8 +87,8 @@ fn check_built(format: EncodeFormat) -> Result<()> { } /// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. -const fn extensions() -> ([&'static str; 12], usize) { - let mut all = [""; 12]; +const fn extensions() -> ([&'static str; 13], usize) { + let mut all = [""; 13]; let mut n = 0; macro_rules! add { ($built:expr, $($extension:literal),+) => { @@ -81,10 +106,11 @@ const fn extensions() -> ([&'static str; 12], usize) { add!(cfg!(feature = "mp3-encode"), "mp3"); add!(cfg!(feature = "ac3-encode"), "ac3"); add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + add!(cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), "ogg"); (all, n) } -const EXTENSIONS: ([&str; 12], usize) = extensions(); +const EXTENSIONS: ([&str; 13], usize) = extensions(); /// The file extensions of the formats [`encode`] can write (those whose features are on). pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; @@ -99,7 +125,7 @@ pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("ogg"), None); +/// assert_eq!(encode_format_for("unknown"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -122,6 +148,8 @@ pub fn encode_format_for(name: &str) -> Option { "ac3" => Some(EncodeFormat::Ac3), #[cfg(feature = "eac3-encode")] "eac3" | "ec3" => Some(EncodeFormat::Eac3), + #[cfg(all(feature = "vorbis-encode", not(target_arch = "wasm32")))] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -138,6 +166,15 @@ fn wav_mask(layout: &ChannelLayout, channels: usize) -> Result { /// The error a stream encoder returns for every call after one of its writes has failed: the /// sink may already hold a prefix of the failed block, so the encoder's counters can no longer /// describe the bytes on the sink, and later writes or `finish` must not claim success. +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] fn failed_write_error() -> AudioError { AudioError::Encode("the stream encoder already failed on an earlier write; its output is incomplete".into()) } @@ -163,12 +200,30 @@ fn failed_write_error() -> AudioError { /// assert_eq!(&flac[..4], b"fLaC"); /// # } /// ``` +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] pub struct FileEncoder { writer: Writer, format: EncodeFormat, channels: usize, } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() @@ -177,6 +232,15 @@ impl std::fmt::Debug for FileEncoder { // The writers differ in size with the features built; the coded one is boxed for its encoder. #[allow(clippy::large_enum_variant)] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), @@ -188,6 +252,15 @@ enum Writer { Coded(Box>), } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl FileEncoder { /// Starts a file of `channels` channels at `sample_rate` at the current position of `out`. /// `opts.layout`, when set, must have `channels` channels. @@ -317,9 +390,39 @@ impl EncodeOptions { /// The constant bit rate such a file would be written at ([`FileEncoder::bitrate`]), or the /// error [`EncodeOptions::check`] returns. pub fn bitrate(&self, sample_rate: u32, channels: u16) -> Result> { + #[cfg(feature = "vorbis-encode")] + if self.format == EncodeFormat::Ogg { + // Vorbis is whole-buffer only and VBR has no constant output bitrate. + encode(&AudioBuffer::new(sample_rate, channels, 0), self)?; + return Ok(None); + } // The encoder a file would get, on a sink that is thrown away: what it accepts and the // rate it settles on are then the writer's by construction. - Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + #[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + ))] + { + Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + } + #[cfg(not(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + )))] + { + let _ = (sample_rate, channels); + Err(AudioError::Unsupported("streaming encoders are not built".into())) + } } } diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs new file mode 100644 index 0000000000..f56d01148d --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,130 @@ +//! Ogg Vorbis encoding (RFC 5334): the reference libvorbis encoder, built from its C sources by +//! `vorbis_rs`. Stereo or mono, variable bitrate at the requested kbit/s (64–500), with a +//! fallback to a quality preset when the bitrate is not supported for the rate and channel count. + +use crate::{AudioBuffer, AudioError, Result}; + +/// The bitrates an Ogg Vorbis export is asked for, in kbit/s. +pub const OGG_BITRATES: (u32, u32) = (64, 500); + +/// The block size the encoder processes at a time: small enough that memory stays bounded +/// regardless of file length. +#[cfg(not(target_arch = "wasm32"))] +const BLOCK: usize = 4096; + +#[cfg(not(target_arch = "wasm32"))] +fn encode_error(e: vorbis_rs::VorbisError) -> AudioError { + AudioError::Encode(e.to_string()) +} + +/// Encode `buf` as an Ogg Vorbis stream at about `kbps` (variable, as Vorbis is): stereo, or mono +/// for a mono buffer. A bitrate the encoder has no setup for at that rate and channel count falls +/// back to a quality that suits it. `Err` says why there is nothing. +#[cfg(not(target_arch = "wasm32"))] +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + use std::num::{NonZeroU8, NonZeroU32}; + + let channels = buf.channels.len(); + if !(1..=2).contains(&channels) { + return Err(AudioError::Unsupported("Ogg Vorbis export requires mono or stereo audio".into())); + } + if buf.channels.iter().any(|c| c.len() != buf.frames() || c.iter().any(|s| !s.is_finite())) { + return Err(AudioError::Encode("Vorbis samples must be finite and channels equally long".into())); + } + let (Some(rate), Some(count)) = (NonZeroU32::new(buf.sample_rate), NonZeroU8::new(channels as u8)) else { + return Err(AudioError::Encode("there is no audio to encode".into())); + }; + let target = NonZeroU32::new(kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1) * 1000).unwrap_or(NonZeroU32::MIN); + + let encode = |strategy: vorbis_rs::VorbisBitrateManagementStrategy| -> Result> { + let mut encoder = vorbis_rs::VorbisEncoderBuilder::new_with_serial(rate, count, Vec::new(), 0x4C43_5246) + .bitrate_management_strategy(strategy) + .build() + .map_err(encode_error)?; + let frames = buf.frames(); + let mut at = 0usize; + while at < frames { + let end = (at + BLOCK).min(frames); + let block: Vec<&[f32]> = buf.channels.iter().take(channels).map(|side| side.get(at..end).unwrap_or_default()).collect(); + encoder.encode_audio_block(&block).map_err(encode_error)?; + at = end; + } + encoder.finish().map_err(encode_error) + }; + + // Convert Rust unwinds to an error. This does not catch native crashes or aborts. + let attempt = |strategy| { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encode(strategy))) + .unwrap_or_else(|_| Err(AudioError::Encode("the Vorbis encoder failed".into()))) + }; + match attempt(vorbis_rs::VorbisBitrateManagementStrategy::Vbr { target_bitrate: target }) { + Ok(bytes) => Ok(bytes), + Err(_) => attempt(vorbis_rs::VorbisBitrateManagementStrategy::QualityVbr { target_quality: 0.6 }) + .map_err(|e| AudioError::Encode(format!("the Vorbis encoder refused the audio: {e}"))), + } +} + +/// Ogg Vorbis encoding is unavailable on WASM; returns an unsupported-format error. +#[cfg(target_arch = "wasm32")] +pub fn encode(_buf: &AudioBuffer, _kbps: u32) -> Result> { + Err(AudioError::Unsupported("Ogg Vorbis files are exported by the desktop app".into())) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { + for channels in [0, 3, 6] { + assert!(matches!(encode(&AudioBuffer::new(48_000, channels, 16), 192), Err(AudioError::Unsupported(_)))); + } + let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 16], vec![0.0; 15]] }; + assert!(encode(&ragged, 192).is_err()); + assert!(encode(&AudioBuffer::new(0, 1, 16), 192).is_err()); + let invalid = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN]] }; + assert!(encode(&invalid, 192).is_err()); + } + + #[test] + fn generic_and_direct_encoders_write_mono_and_stereo_ogg() { + for channels in [1, 2] { + let audio = AudioBuffer::new(48_000, channels, 512); + let opts = crate::EncodeOptions::new(crate::EncodeFormat::Ogg); + assert!(opts.check(48_000, channels).is_ok()); + assert_eq!(opts.bitrate(48_000, channels).unwrap(), None); + let direct = encode(&audio, 192).unwrap(); + let generic = crate::encode(&audio, &opts).unwrap(); + assert!(direct.starts_with(b"OggS")); + assert_eq!(direct, generic); + #[cfg(feature = "decode")] + { + let (info, decoded) = crate::decode(&generic, Some("ogg")).unwrap(); + assert_eq!(info.channels, channels); + assert_eq!(decoded.num_channels(), channels); + assert_eq!(decoded.frames(), audio.frames()); + } + } + } + #[cfg(feature = "decode")] + #[test] + fn distinct_signals_survive_full_and_partial_blocks() { + for frames in [4096, 4097, 8193] { + let channels: Vec> = [440.0f32, 880.0] + .into_iter() + .map(|hz| (0..frames).map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin() * 0.4).collect()) + .collect(); + let audio = AudioBuffer { sample_rate: 48_000, channels }; + let bytes = encode(&audio, 192).unwrap(); + let (_, decoded) = crate::decode(&bytes, Some("ogg")).unwrap(); + assert_eq!(decoded.frames(), frames); + assert_eq!(decoded.channels.len(), 2); + for (expected, actual) in audio.channels.iter().zip(&decoded.channels) { + let mse = expected.iter().zip(actual).map(|(a, b)| (a - b).powi(2)).sum::() / frames as f32; + // Vorbis is lossy; this tolerates codec error but rejects silence or swapped channels. + assert!(mse.sqrt() < 0.08, "{frames} frames: RMS error {}", mse.sqrt()); + } + } + } +} diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index 27a5573deb..fc961cc393 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -77,6 +77,6 @@ fn every_encode_format_has_an_extension_it_is_written_and_read_under() { assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); - assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3"]); + assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3", "ogg"]); assert_eq!(EncodeFormat::Aiff.mime_type(), "audio/aiff"); } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 7713f37a5a..e91f93623c 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,15 @@ fn only_formats_the_encoder_writes_are_named() { for name in craft_audio::ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - for other in ["ogg", "opus", "aac", "mp4", "xyz", ""] { + for other in ["opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } + +#[test] +fn ogg_names_follow_the_native_feature() { + let built = cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))); + assert_eq!(EncodeFormat::Ogg.is_built(), built); + assert_eq!(encode_format_for("ogg"), built.then_some(EncodeFormat::Ogg)); + assert_eq!(craft_audio::ENCODE_EXTENSIONS.contains(&"ogg"), built); +} diff --git a/crates/audio/tests/audio/main.rs b/crates/audio/tests/audio/main.rs index 8c37256d69..52e1d17f4b 100644 --- a/crates/audio/tests/audio/main.rs +++ b/crates/audio/tests/audio/main.rs @@ -10,3 +10,4 @@ mod raw_pcm; mod roundtrip; mod stream; mod wav_empty_data; +mod wav_ixml; diff --git a/crates/audio/tests/audio/wav_ixml.rs b/crates/audio/tests/audio/wav_ixml.rs new file mode 100644 index 0000000000..88e0cfcbf5 --- /dev/null +++ b/crates/audio/tests/audio/wav_ixml.rs @@ -0,0 +1,87 @@ +//! iXML timestamp parity with FilmCraft's streaming WAV reader, including hostile metadata. +use std::io::Cursor; + +use craft_audio::{DecodeOptions, Decoder}; +use craft_media::ReadSeekSource; + +fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend_from_slice(&(body.len() as u32).to_le_bytes()); + out.extend_from_slice(body); + if !body.len().is_multiple_of(2) { + out.push(0); + } + out +} + +fn wav(metadata: &[Vec]) -> Vec { + let mut out = b"RIFF\0\0\0\0WAVE".to_vec(); + out.extend(chunk(b"fmt ", &[1, 0, 1, 0, 0x80, 0xbb, 0, 0, 0, 0x77, 1, 0, 2, 0, 16, 0])); + for m in metadata { + out.extend(m); + } + out.extend(chunk(b"data", &[0, 0, 1, 0])); + let len = (out.len() - 8) as u32; + out[4..8].copy_from_slice(&len.to_le_bytes()); + out +} + +fn xml(low: &str, high: Option<&str>) -> Vec { + let high = high.map(|v| format!("{v}")).unwrap_or_default(); + chunk(b"iXML", format!("{low}{high}").as_bytes()) +} + +fn check(file: Vec, expected: Option) { + let options = DecodeOptions::default(); + let mut bytes = Decoder::from_bytes(&file, Some("wav"), &options).unwrap(); + assert_eq!(bytes.info().bwf.as_ref().map(|b| b.time_reference), expected); + let source = ReadSeekSource::new(Cursor::new(file.clone())).unwrap(); + let mut stream = Decoder::open(source, Some("wav"), &options).unwrap(); + assert_eq!(stream.info().bwf.as_ref().map(|b| b.time_reference), expected); + assert_eq!(bytes.info().frames, 2); + assert_eq!(stream.next_block().unwrap().unwrap().frames(), 2); + assert_eq!(bytes.next_block().unwrap().unwrap().frames(), 2); +} + +#[test] +fn ixml_fallback_preserves_large_timestamps_and_optional_high_word() { + check(wav(&[xml(" 5 ", Some("1"))]), Some((1 << 32) + 5)); + check(wav(&[xml("0", None)]), Some(0)); + check(wav(&[xml("4294967295", Some("4294967295"))]), Some(u64::MAX)); +} + +#[test] +fn bext_wins_in_either_chunk_order_including_timestamp_zero() { + let bext = chunk(b"bext", &[0; 602]); + let ixml = xml("5", Some("1")); + check(wav(&[bext.clone(), ixml.clone()]), Some(0)); + check(wav(&[ixml.clone(), bext.clone()]), Some(0)); + check(wav(&[bext, chunk(b"bext", &[0; 12]), ixml.clone()]), Some(0)); + check(wav(&[chunk(b"bext", &[0; 12]), ixml]), Some((1 << 32) + 5)); +} + +#[test] +fn invalid_metadata_never_fabricates_a_timestamp_or_blocks_audio() { + for low in ["4294967296", "-1", "+1", "", "1.5", "5"] { + check(wav(&[xml(low, Some("0"))]), None); + } + for high in ["4294967296", "-1", "", "oops"] { + check(wav(&[xml("5", Some(high))]), None); + } + for text in [ + "5", + "", + "56", + "5", + ] { + check(wav(&[chunk(b"iXML", text.as_bytes())]), None); + } + check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None); + let deep = format!("{}{}", "".repeat(40), "".repeat(40)); + check(wav(&[chunk(b"iXML", deep.as_bytes())]), None); +} + +#[test] +fn only_first_ixml_document_is_considered() { + check(wav(&[xml("5", None), xml("6", None)]), Some(5)); +} diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs index 53947df123..84169f6658 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -397,12 +397,15 @@ fn the_formats_are_named() { for name in ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - assert_eq!(ENCODE_EXTENSIONS.len(), 12); + assert_eq!(ENCODE_EXTENSIONS.len(), 13); for format in CODED { assert!(EncodeFormat::ALL.contains(&format) && format.is_built()); } let features: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.feature()).collect(); - assert_eq!(features, ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode"]); + assert_eq!( + features, + ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode", "vorbis-encode"] + ); } /// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. @@ -495,6 +498,10 @@ fn the_format_queries_agree_with_the_writer() { let layouts = masks.iter().map(|&mask| ChannelLayout::from_mask(mask)).chain((1..=9).map(ChannelLayout::unordered)); for layout in layouts { for &format in EncodeFormat::ALL { + // Vorbis is whole-buffer-only; its direct/generic API and options are tested separately. + if format == EncodeFormat::Ogg { + continue; + } // 24 bits is a depth every format has. let opts = EncodeOptions::new(format).with_layout(layout); for &sample_rate in &rates { @@ -520,7 +527,7 @@ fn the_format_queries_agree_with_the_writer() { // The most channels is the most: one more is refused, by the layouts of a format that has // a fixed set and by the writer of one that has not. let most: Vec = EncodeFormat::ALL.iter().map(|f| f.max_channels()).collect(); - assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8]); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 2]); for &format in EncodeFormat::ALL { let most = format.max_channels(); match format.fixed_layouts(most) { @@ -569,3 +576,16 @@ fn the_bit_rate_used_can_be_asked_for() { assert_eq!(encode(&buf, &opts).unwrap().len() as u32, 43 * 1152 / 8 * opts.bitrate(48_000, 2).unwrap().unwrap() / 48_000); assert!(is_unsupported(EncodeOptions::new(EncodeFormat::Mp3).bitrate(48_000, 6))); } + +#[test] +fn vorbis_is_whole_buffer_only_and_validates_layouts() { + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(ChannelLayout::STEREO); + assert!(opts.check(48_000, 2).is_ok()); + assert_eq!(opts.bitrate(48_000, 2).unwrap(), None); + assert!(FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).is_err()); + let buf = craft_audio::AudioBuffer::new(48_000, 2, 512); + assert!(craft_audio::encode(&buf, &opts).unwrap().starts_with(b"OggS")); + let wrong = opts.with_layout(ChannelLayout::from_mask(0xC)); + assert!(wrong.check(48_000, 2).is_err()); + assert!(craft_audio::encode(&buf, &wrong).is_err()); +} diff --git a/crates/ber/Cargo.toml b/crates/ber/Cargo.toml new file mode 100644 index 0000000000..fa3902e88b --- /dev/null +++ b/crates/ber/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-ber" +description = "ASN.1 BER and DER (X.690): reading TLVs, BER to DER, and what an opaque signed CMS holds" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/ber/src/lib.rs b/crates/ber/src/lib.rs new file mode 100644 index 0000000000..e97c1b0f53 --- /dev/null +++ b/crates/ber/src/lib.rs @@ -0,0 +1,432 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Reading the TLVs of ASN.1 BER and DER (X.690), and turning BER into DER where they differ in +//! what CMS writers use: indefinite lengths (which streaming signers write) and OCTET STRINGs in +//! pieces (constructed). What is DER already is kept byte for byte, an element with a definite +//! length inside an indefinite one too, so that the bytes a signature covers (signed attributes, +//! a certificate's body) are those the signer wrote. For S/MIME: `craft-smime` checks +//! signatures with it, and a message's reader takes out what an opaque signed one holds +//! ([`signed_content`]). +//! +//! The input is hostile: lengths are checked against what is there, nesting is bounded +//! ([`MAX_DEPTH`]), and the work is linear in the input (times the bounded depth). +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// CMS's id-signedData and id-data (RFC 5652 §5.1, §4), as OBJECT IDENTIFIER values. +const SIGNED_DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02]; +const DATA: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01]; + +/// What the CMS `cms` holds when it is SignedData with its content inside, of type id-data: the +/// MIME entity an opaque signed message (`application/pkcs7-mime`, RFC 8551 §3.5) signed, for +/// reading as the message. Nothing is checked here (`craft-smime` checks it); `None` for any +/// other CMS (an Encrypted message's enveloped data) or bytes that aren't one. +pub fn signed_content(cms: &[u8]) -> Option> { + let der = to_der(cms)?; + let (info, rest) = read(&der)?; + if info.tag != 0x30 || !rest.is_empty() { + return None; + } + let info = children(info.value)?; + let [oid, explicit] = info.as_slice() else { return None }; + if oid.tag != 0x06 || oid.value != SIGNED_DATA || explicit.tag != 0xa0 { + return None; + } + let (signed, rest) = read(explicit.value)?; + if signed.tag != 0x30 || !rest.is_empty() { + return None; + } + let signed = children(signed.value)?; + let [version, digests, encap, tail @ ..] = signed.as_slice() else { return None }; + if version.tag != 0x02 || !matches!(version.value, [1 | 3 | 4 | 5]) || digests.tag != 0x31 || encap.tag != 0x30 { + return None; + } + if children(digests.value)?.iter().any(|algorithm| algorithm.tag != 0x30) { + return None; + } + // Certificates and revocation lists are optional, but ordered and present at most once. + let tail = if tail.first().is_some_and(|field| field.tag == 0xa0) { tail.get(1..)? } else { tail }; + let tail = if tail.first().is_some_and(|field| field.tag == 0xa1) { tail.get(1..)? } else { tail }; + let [signers] = tail else { return None }; + if signers.tag != 0x31 || children(signers.value)?.iter().any(|signer| signer.tag != 0x30) { + return None; + } + let encap = children(encap.value)?; + let [kind, content] = encap.as_slice() else { return None }; + if kind.tag != 0x06 || kind.value != DATA || content.tag != 0xa0 { + return None; + } + let (octets, rest) = read(content.value)?; + (octets.tag == 0x04 && rest.is_empty()).then(|| octets.value.to_vec()) +} + +/// How deep elements may nest. +pub const MAX_DEPTH: usize = 48; + +/// Maximum elements materialized or indexed in one parsing operation. This bounds the +/// allocation amplification from hostile, shallow input containing many empty TLVs. +pub const MAX_ELEMENTS: usize = 65_536; + +/// The universal tag of an OCTET STRING, and of one in pieces. +const OCTET_STRING: u8 = 0x04; +const OCTET_STRING_PIECES: u8 = 0x24; + +/// One element: its tag bytes, and its value (the content octets). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Tlv<'a> { + /// The tag's first byte (class, constructed bit, number below 31). + pub tag: u8, + /// The whole element, tag and length included. + pub whole: &'a [u8], + /// Its content octets. + pub value: &'a [u8], +} + +/// The tag bytes at the start of `bytes`: one, or a high tag number in up to four more. +fn tag_len(bytes: &[u8]) -> Option { + let first = *bytes.first()?; + if first & 0x1f != 0x1f { + return Some(1); + } + // High tag number: base-128 bytes, the last without its top bit. + for (i, b) in bytes.iter().enumerate().skip(1).take(4) { + if b & 0x80 == 0 { + return i.checked_add(1); + } + } + None +} + +/// The length at the start of `bytes`: `(length, bytes it took)`, `None` for an indefinite one +/// (`Some((None, 1))`) is told apart by the caller. +fn length(bytes: &[u8]) -> Option<(Option, usize)> { + let first = *bytes.first()?; + if first < 0x80 { + return Some((Some(usize::from(first)), 1)); + } + if first == 0x80 { + return Some((None, 1)); + } + let n = usize::from(first & 0x7f); + if n > 4 { + return None; + } + let digits = bytes.get(1..n.checked_add(1)?)?; + let len = digits.iter().fold(0usize, |acc, d| (acc << 8) | usize::from(*d)); + Some((Some(len), n.checked_add(1)?)) +} + +/// The element at the start of `bytes` with a definite length, and what follows it. `None` for +/// an indefinite length, or one longer than what is there. +pub fn read(bytes: &[u8]) -> Option<(Tlv<'_>, &[u8])> { + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let len = len?; + let start = t.checked_add(l)?; + let end = start.checked_add(len)?; + let value = bytes.get(start..end)?; + let whole = bytes.get(..end)?; + Some((Tlv { tag, whole, value }, bytes.get(end..)?)) +} + +/// The elements of `value`, each with a definite length; `None` when one can't be read. +pub fn children(mut value: &[u8]) -> Option>> { + let mut out = Vec::new(); + while !value.is_empty() { + if out.len() >= MAX_ELEMENTS { + return None; + } + let (tlv, rest) = read(value)?; + out.push(tlv); + value = rest; + } + Some(out) +} + +/// `bytes` as DER as far as CMS needs it: indefinite lengths made definite and OCTET STRINGs in +/// pieces joined into one, everything else as it was. One element is read, and must be all of +/// `bytes` (bar trailing zero bytes, which some writers pad with). `None` when it isn't BER. +pub fn to_der(bytes: &[u8]) -> Option> { + if let Some((_, rest)) = read(bytes) + && rest.iter().all(|b| *b == 0) + && der_shaped(bytes.get(..bytes.len().saturating_sub(rest.len()))?, 0) + { + return bytes.get(..bytes.len().saturating_sub(rest.len())).map(<[u8]>::to_vec); + } + let mut out = Vec::with_capacity(bytes.len()); + let used = element(bytes, 0, &mut out)?; + let rest = bytes.get(used..)?; + rest.iter().all(|b| *b == 0).then_some(out) +} + +/// Whether the elements of `bytes` all have definite lengths and no OCTET STRING is in pieces, +/// as deep as they go: nothing to change. +fn der_shaped(mut bytes: &[u8], depth: usize) -> bool { + if depth > MAX_DEPTH { + return false; + } + while !bytes.is_empty() { + let Some((tlv, rest)) = read(bytes) else { return false }; + if tlv.tag == OCTET_STRING_PIECES || (tlv.tag & 0x20 != 0 && !der_shaped(tlv.value, depth.saturating_add(1))) { + return false; + } + bytes = rest; + } + true +} + +/// What [`measure`] found of one element: how many bytes of the input it was, and how long its +/// content is as DER. +#[derive(Clone, Copy)] +struct Size { + used: usize, + content: usize, + /// It is DER-shaped already (a definite length, and nothing in it to change): copied as it + /// is, its lengths as the writer wrote them, since a signature may cover them. + verbatim: bool, +} + +/// The sizes of the constructed elements of the input, by where each starts in it: worked out +/// once, so that writing them is one pass with no copy of a level for each level above it. +type Sizes = std::collections::HashMap; + +/// The element at `at` in `input`: how many bytes it was, and its length as DER, header and all. +fn measure(input: &[u8], at: usize, depth: usize, sizes: &mut Sizes) -> Option<(usize, usize)> { + if depth > MAX_DEPTH || sizes.len() >= MAX_ELEMENTS { + return None; + } + let bytes = input.get(at..)?; + if let Some((tlv, _)) = read(bytes) + && der_shaped(tlv.whole, depth) + { + sizes.insert(at, Size { used: tlv.whole.len(), content: tlv.value.len(), verbatim: true }); + return Some((tlv.whole.len(), tlv.whole.len())); + } + let t = tag_len(bytes)?; + let tag = *bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + bytes.get(..used)?; + return Some((used, used_der(t, used.checked_sub(start)?)?)); + } + // The children, one after another, to the end of a definite length or to the end mark. + let mut content = 0usize; + let mut pos = start; + let end = match len { + Some(len) => Some(start.checked_add(len)?), + None => None, + }; + loop { + match end { + Some(end) if pos >= end => break, + None if bytes.get(pos..)?.starts_with(&[0, 0]) => { + pos = pos.checked_add(2)?; + break; + } + _ => {} + } + // (The pieces of an OCTET STRING are OCTET STRINGs, in pieces themselves or not.) + if tag == OCTET_STRING_PIECES && !matches!(bytes.get(pos), Some(&OCTET_STRING | &OCTET_STRING_PIECES)) { + return None; + } + let (n, der) = measure(input, at.checked_add(pos)?, depth.checked_add(1)?, sizes)?; + if n == 0 { + return None; + } + // An OCTET STRING in pieces is one of their contents together. + content = content.checked_add(if tag == OCTET_STRING_PIECES { der_content(input, at.checked_add(pos)?, sizes)? } else { der })?; + pos = pos.checked_add(n)?; + } + if let Some(end) = end + && pos != end + { + return None; + } + if sizes.len() >= MAX_ELEMENTS { + return None; + } + sizes.insert(at, Size { used: pos, content, verbatim: false }); + let header_tag = if tag == OCTET_STRING_PIECES { 1 } else { t }; + Some((pos, used_der(header_tag, content)?)) +} + +/// The length of a DER element with a tag of `tag` bytes and `content` bytes of content. +fn used_der(tag: usize, content: usize) -> Option { + let mut l = Vec::new(); + put_length(&mut l, content); + tag.checked_add(l.len())?.checked_add(content) +} + +/// The DER content length of the (measured) element at `at`: a primitive's own. +fn der_content(input: &[u8], at: usize, sizes: &Sizes) -> Option { + if let Some(s) = sizes.get(&at) { + return Some(s.content); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let (len, _) = length(bytes.get(t..)?)?; + len +} + +/// Write the (measured) element at `at` in `input` to `out` as DER; how many bytes it was. +fn write(input: &[u8], at: usize, sizes: &Sizes, pieces: bool, out: &mut Vec) -> Option { + if let Some(s) = sizes.get(&at).filter(|s| s.verbatim && !pieces) { + out.extend_from_slice(input.get(at..at.checked_add(s.used)?)?); + return Some(s.used); + } + let bytes = input.get(at..)?; + let t = tag_len(bytes)?; + let tag_bytes = bytes.get(..t)?; + let tag = *tag_bytes.first()?; + let (len, l) = length(bytes.get(t..)?)?; + let start = t.checked_add(l)?; + if tag & 0x20 == 0 { + let used = start.checked_add(len?)?; + let value = bytes.get(start..used)?; + // (A piece of an OCTET STRING in pieces gives its bytes alone.) + if !pieces { + out.extend_from_slice(tag_bytes); + put_length(out, value.len()); + } + out.extend_from_slice(value); + return Some(used); + } + let size = *sizes.get(&at)?; + if tag == OCTET_STRING_PIECES { + if !pieces { + out.push(OCTET_STRING); + put_length(out, size.content); + } + } else { + out.extend_from_slice(tag_bytes); + put_length(out, size.content); + } + let inner_pieces = tag == OCTET_STRING_PIECES; + let mut pos = start; + while pos < size.used { + if bytes.get(pos..)?.starts_with(&[0, 0]) && len.is_none() { + break; + } + let n = write(input, at.checked_add(pos)?, sizes, inner_pieces, out)?; + pos = pos.checked_add(n)?; + } + Some(size.used) +} + +/// Write the element at the start of `bytes` to `out` as DER; how many bytes of `bytes` it was. +fn element(bytes: &[u8], depth: usize, out: &mut Vec) -> Option { + let mut sizes = Sizes::new(); + let (used, der) = measure(bytes, 0, depth, &mut sizes)?; + out.reserve(der); + write(bytes, 0, &sizes, false, out)?; + Some(used) +} + +/// A definite length in DER's shortest form. +fn put_length(out: &mut Vec, len: usize) { + if len < 0x80 { + out.push(len as u8); + return; + } + let bytes = len.to_be_bytes(); + let skip = bytes.iter().take_while(|b| **b == 0).count(); + let digits = bytes.get(skip..).unwrap_or_default(); + out.push(0x80 | digits.len() as u8); + out.extend_from_slice(digits); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tlv(tag: u8, value: &[u8]) -> Vec { + let mut out = vec![tag]; + put_length(&mut out, value.len()); + out.extend_from_slice(value); + out + } + + fn cms(outer_tag: u8, signed_tag: u8, oid_tag: u8, long_oid: bool, trailing: bool) -> Vec { + let oid = |value: &[u8]| { + if long_oid { + let mut out = vec![oid_tag, 0x81, 9]; + out.extend_from_slice(value); + out + } else { + tlv(oid_tag, value) + } + }; + let mut encap = oid(DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + let mut signed = tlv(0x02, &[1]); + signed.extend(tlv(0x31, &[])); + signed.extend(tlv(0x30, &encap)); + signed.extend(tlv(0x31, &[])); + let mut signed = tlv(signed_tag, &signed); + if trailing { + signed.extend(tlv(0x05, &[])); + } + let mut info = oid(SIGNED_DATA); + info.extend(tlv(0xa0, &signed)); + tlv(outer_tag, &info) + } + + #[test] + fn extracts_content_with_der_and_ber_oid_lengths() { + for long_oid in [false, true] { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, long_oid, false)), Some(b"hello".to_vec())); + } + } + + #[test] + fn rejects_wrong_cms_container_and_oid_tags() { + for (outer, signed, oid) in [(0x31, 0x30, 0x06), (0x30, 0x31, 0x06), (0x30, 0x30, 0x04)] { + assert_eq!(signed_content(&cms(outer, signed, oid, false, false)), None); + } + } + + #[test] + fn rejects_missing_mandatory_signed_data_fields() { + let mut encap = tlv(0x06, DATA); + encap.extend(tlv(0xa0, &tlv(0x04, b"hello"))); + for prefix in [vec![0x05, 0, 0x05, 0], vec![0x02, 1, 1, 0x31, 0]] { + let mut malformed = prefix; + malformed.extend(tlv(0x30, &encap)); + let mut info = tlv(0x06, SIGNED_DATA); + info.extend(tlv(0xa0, &tlv(0x30, &malformed))); + assert_eq!(signed_content(&tlv(0x30, &info)), None); + } + } + + #[test] + fn rejects_extra_signed_data_inside_explicit_container() { + assert_eq!(signed_content(&cms(0x30, 0x30, 0x06, false, true)), None); + } + + #[test] + fn rejects_wide_inputs_before_unbounded_metadata_allocation() { + let children_bytes = [0x05, 0].repeat(MAX_ELEMENTS + 1); + assert!(children(&children_bytes).is_none()); + let mut indefinite = vec![0x30, 0x80]; + indefinite.extend_from_slice(&children_bytes); + indefinite.extend_from_slice(&[0, 0]); + assert!(to_der(&indefinite).is_none()); + } + + #[test] + fn joins_indefinite_octet_string_pieces() { + assert_eq!(to_der(&[0x24, 0x80, 0x04, 1, b'a', 0x04, 1, b'b', 0, 0]), Some(vec![0x04, 2, b'a', b'b'])); + } + + #[test] + fn rejects_truncated_and_over_nested_input() { + assert_eq!(to_der(&[0x04, 2, b'a']), None); + let mut nested = tlv(0x04, &[]); + for _ in 0..=MAX_DEPTH { + nested = tlv(0x30, &nested); + } + assert_eq!(to_der(&nested), None); + } +} diff --git a/crates/cms/src/lutfile.rs b/crates/cms/src/lutfile.rs index 404b5a3156..b7cc99bf33 100644 --- a/crates/cms/src/lutfile.rs +++ b/crates/cms/src/lutfile.rs @@ -531,12 +531,52 @@ pub fn write_cube(l: &LutFile) -> String { s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); } s.push_str(&format!("LUT_3D_SIZE {}\n", l.size)); - for c in l.data.as_chunks::<3>().0 { + cube_rows(s, l.data.as_chunks::<3>().0.iter().copied()) +} + +/// Writes a `.cube` file with a creator comment, section comments and an explicit input domain. +/// +/// This layout is useful for exported LUTs; [`write_cube`] keeps its compact layout for embedded +/// tables. Values retain six decimal places, and their order and quantisation belong to the +/// caller. A default domain is written as `0.0` and `1.0` for compatibility with export consumers. +pub fn write_cube_commented(l: &LutFile, creator: &str) -> String { + let mut s = format!("#Created by: {creator}\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {}\n\n#data domain\n", l.title.replace('"', "'"), l.size); + if l.domain_is_default() { + s.push_str("DOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n"); + } else { + s.push_str(&format!("DOMAIN_MIN {} {} {}\n", l.domain_min[0], l.domain_min[1], l.domain_min[2])); + s.push_str(&format!("DOMAIN_MAX {} {} {}\n", l.domain_max[0], l.domain_max[1], l.domain_max[2])); + } + s.push_str("\n#LUT data points\n"); + cube_rows(s, l.data.as_chunks::<3>().0.iter().copied()) +} + +fn cube_rows(mut s: String, rows: impl Iterator) -> String { + for c in rows { s.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2])); } s } +/// Annotated identity-domain CUBE export, streamed in red-fastest order without a table copy. +/// Callers supply exactly `size³` rows for a valid size (2..=[`MAX_SIZE`]), as with [`write_cube`]. +/// Integer-depth exports clamp/round to 1/32768 steps; floating exports clamp without rounding. +pub fn write_cube_export(creator: &str, title: &str, size: usize, integer_depth: bool, rows: impl Iterator) -> String { + let s = format!( + "#Created by: {creator}\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {size}\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n", + title.replace('"', "'") + ); + cube_rows( + s, + rows.map(|c| { + c.map(|v| { + let v = v.clamp(0.0, 1.0); + if integer_depth { (v * 32768.0).round() / 32768.0 } else { v } + }) + }), + ) +} + fn luma(c: [f32; 3]) -> f32 { 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] } @@ -602,6 +642,30 @@ pub fn builtin(id: &str) -> Option { mod tests { use super::*; + #[test] + fn commented_cube_preserves_export_header_and_rows() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.title = "A \"look\"".into(); + let text = super::write_cube_commented(&lut, "ExampleCraft"); + assert!(text.starts_with("#Created by: ExampleCraft\nTITLE \"A 'look'\"\n\n#LUT size\nLUT_3D_SIZE 2\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n")); + let parsed = super::parse_cube(&text).unwrap(); + assert_eq!(parsed.data, lut.data); + assert_eq!(parsed.title, "A 'look'"); + assert_eq!(text.lines().count(), 11 + 8); + let rows = |s: &str| s.lines().filter(|line| line.starts_with(|c: char| c.is_ascii_digit())).map(str::to_owned).collect::>(); + assert_eq!(rows(&text), rows(&super::write_cube(&lut))); + } + + #[test] + fn commented_cube_keeps_nondefault_domain_and_sample_precision() { + let mut lut = super::LutFile::identity(2).unwrap(); + lut.domain_min = [0.125, 0.25, 0.375]; + lut.domain_max = [0.625, 0.75, 0.875]; + lut.data[0] = 0.833344; + let parsed = super::parse_cube(&super::write_cube_commented(&lut, "ExampleCraft")).unwrap(); + assert_eq!(parsed, lut); + } + #[test] fn cube_title_hashes_and_comment_quotes_are_distinct() { let rows = "LUT_1D_SIZE 2\n0 0 0 # low\n1 1 1 # high\n"; @@ -1299,4 +1363,26 @@ LUT_3D_SIZE 2 assert_eq!(back.domain_min, l.domain_min, "the written table must mean the same"); assert_eq!(back.domain_max, l.domain_max); } + #[test] + fn annotated_cube_export_preserves_header_and_integer_precision() { + let mut lut = LutFile::identity(2).unwrap(); + lut.title = "My \"Look\"".into(); + lut.data[..3].copy_from_slice(&[1.0 / 6.0, 5.0 / 6.0, 160.0 / 255.0]); + let output = write_cube_export("PhotoCraft", &lut.title, lut.size, true, lut.data.as_chunks::<3>().0.iter().copied()); + assert!(output.starts_with("#Created by: PhotoCraft\nTITLE \"My 'Look'\"\n\n#LUT size\nLUT_3D_SIZE 2\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n0.166656 0.833344 0.627441\n")); + assert_eq!(output.lines().count(), 11 + 8); + let parsed = parse_cube(&output).unwrap(); + assert_eq!(parsed.size, 2); + assert_eq!(&parsed.data[3..], &lut.data[3..]); + let float = write_cube_export("PhotoCraft", &lut.title, lut.size, false, lut.data.as_chunks::<3>().0.iter().copied()); + assert!(float.contains("0.166667 0.833333 0.627451\n")); + } + + #[test] + fn annotated_empty_title_and_float_clamping() { + let text = write_cube_export("Exporter", "", 2, false, std::iter::repeat_n([-0.5, 0.25, 1.5], 8)); + assert!(text.contains("TITLE \"\"\n")); + let back = parse_cube(&text).unwrap(); + assert_eq!(back.data, [0.0, 0.25, 1.0].repeat(8)); + } } diff --git a/crates/gzip/Cargo.toml b/crates/gzip/Cargo.toml new file mode 100644 index 0000000000..3d4f046032 --- /dev/null +++ b/crates/gzip/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-gzip" +description = "Streaming gzip writer with stored and compressed segments" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } diff --git a/crates/gzip/src/lib.rs b/crates/gzip/src/lib.rs new file mode 100644 index 0000000000..33f2a5ac15 --- /dev/null +++ b/crates/gzip/src/lib.rs @@ -0,0 +1,119 @@ +//! Streaming gzip output with optional stored segments. +//! +//! Copyright (c) 2026 ArtCraft Team and the VectorCraft contributors. +//! Extracted from VectorCraft, licensed under MIT OR Apache-2.0. +//! +//! `flush` does not emit a deflate block; call [`Gz::finish`] to complete and flush the +//! stream. After an I/O error, discard the writer: the output may be incomplete. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use flate2::{Compress, Compression, Crc, FlushCompress, Status}; +use std::io::{self, Write}; + +/// Bytes of compressed output gathered before they go to the writer. +const OUT_CHUNK: usize = 64 << 10; + +/// A gzip stream, written as [`flate2::write::GzEncoder`] at the default level writes it (the +/// same header and the same data; the deflate blocks are the same too where flate2 deflates with +/// miniz_oxide, not with zlib-rs, which writes them by how the data is fed), except that data which +/// is compressed already ([`Gz::packed`]) is stored as it is: the default level spends a second +/// or more per photo on it for next to nothing, and makes it slower to unpack. Where the level +/// changes the deflate blocks so far end with a sync flush and a fresh compressor writes on, +/// which makes one valid deflate stream that every reader unpacks. +pub struct Gz { + out: W, + deflate: Compress, + /// What `deflate` writes: stored blocks (packed data), else the default level. + stored: bool, + crc: Crc, + buf: Vec, + /// Bytes written (unpacked). + total: u64, +} + +impl Gz { + /// Write a gzip header and construct a writer. + pub fn new(mut out: W) -> io::Result { + // flate2's header for the default level: no name, no time, unknown OS. + out.write_all(&[0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 255])?; + Ok(Self { + out, + deflate: Compress::new(Compression::default(), false), + stored: false, + crc: Crc::new(), + buf: Vec::with_capacity(OUT_CHUNK), + total: 0, + }) + } + + /// Run the compressor over `input` with `flush` until it has taken it all (and, flushing, + /// written everything out). + fn deflate(&mut self, mut input: &[u8], flush: FlushCompress) -> io::Result<()> { + loop { + if self.buf.len() == self.buf.capacity() { + self.out.write_all(&self.buf)?; + self.buf.clear(); + } + let (before_in, before_out) = (self.deflate.total_in(), self.deflate.total_out()); + let status = self.deflate.compress_vec(input, &mut self.buf, flush).map_err(io::Error::other)?; + let taken = usize::try_from(self.deflate.total_in() - before_in).unwrap_or(input.len()).min(input.len()); + input = input.get(taken..).unwrap_or_default(); + let made = self.deflate.total_out() - before_out; + let full = self.buf.len() == self.buf.capacity(); + match flush { + FlushCompress::None if input.is_empty() => return Ok(()), + FlushCompress::Finish if status == Status::StreamEnd => return Ok(()), + // A flush is done once it left room in the output. + FlushCompress::Sync if input.is_empty() && !full => return Ok(()), + _ => {} + } + if taken == 0 && made == 0 && !full { + return Err(io::Error::other("the compressor made no progress")); + } + } + } + + /// Return the number of uncompressed bytes supplied. + pub fn written(&self) -> u64 { + self.total + } + + /// What is written next is compressed already (stored as it is), or not (compressed at the + /// default level). + pub fn packed(&mut self, packed: bool) -> io::Result<()> { + if packed == self.stored { + return Ok(()); + } + self.deflate(&[], FlushCompress::Sync)?; + self.deflate = Compress::new(if packed { Compression::none() } else { Compression::default() }, false); + self.stored = packed; + Ok(()) + } + + /// Complete the gzip trailer and flush the underlying writer. + pub fn finish(mut self) -> io::Result<()> { + self.deflate(&[], FlushCompress::Finish)?; + self.out.write_all(&self.buf)?; + self.out.write_all(&self.crc.sum().to_le_bytes())?; + self.out.write_all(&self.crc.amount().to_le_bytes())?; + self.out.flush() + } +} + +impl Write for Gz { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.write_all(buf)?; + Ok(buf.len()) + } + + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + self.total = self.total.checked_add(buf.len() as u64).ok_or_else(|| io::Error::other("uncompressed byte count overflow"))?; + self.crc.update(buf); + self.deflate(buf, FlushCompress::None) + } + + fn flush(&mut self) -> io::Result<()> { + // Flushing would end a deflate block: the stream is flushed when it is finished. + Ok(()) + } +} diff --git a/crates/gzip/tests/writer.rs b/crates/gzip/tests/writer.rs new file mode 100644 index 0000000000..38981ad0a1 --- /dev/null +++ b/crates/gzip/tests/writer.rs @@ -0,0 +1,77 @@ +use std::io::{self, Read, Write}; + +use craft_gzip::Gz; +use flate2::{Compression, read::GzDecoder, write::GzEncoder}; + +fn decode(bytes: &[u8]) -> Vec { + let mut result = Vec::new(); + GzDecoder::new(bytes).read_to_end(&mut result).unwrap(); + result +} + +#[test] +fn matches_flate2_without_mode_changes() { + let data = b"The quick brown fox jumps over the lazy dog. ".repeat(10000); + let mut expected = GzEncoder::new(Vec::new(), Compression::default()); + let mut actual = Vec::new(); + { + let mut gz = Gz::new(&mut actual).unwrap(); + for chunk in data.chunks(131) { + expected.write_all(chunk).unwrap(); + gz.write_all(chunk).unwrap(); + } + assert_eq!(gz.written(), data.len() as u64); + gz.finish().unwrap(); + } + assert_eq!(actual, expected.finish().unwrap()); + assert_eq!(decode(&actual), data); +} + +#[test] +fn mixed_segments_round_trip_and_stored_bytes_remain_uncompressed() { + let plain = b"repeat me ".repeat(20000); + let packed: Vec = (0..200_000).map(|i| (i * 31) as u8).collect(); + let mut bytes = Vec::new(); + { + let mut gz = Gz::new(&mut bytes).unwrap(); + gz.write_all(&plain).unwrap(); + gz.packed(true).unwrap(); + gz.packed(true).unwrap(); + gz.write_all(&packed).unwrap(); + gz.packed(false).unwrap(); + gz.write_all(&plain).unwrap(); + assert_eq!(gz.written(), (plain.len() * 2 + packed.len()) as u64); + gz.finish().unwrap(); + } + let expected = [plain.as_slice(), packed.as_slice(), plain.as_slice()].concat(); + assert_eq!(decode(&bytes), expected); + assert!(bytes.windows(1024).any(|window| window == &packed[..1024])); + assert!(bytes.len() < expected.len()); +} + +struct FailAfter { + remaining: usize, +} +impl Write for FailAfter { + fn write(&mut self, data: &[u8]) -> io::Result { + if self.remaining == 0 { + return Err(io::Error::other("injected failure")); + } + let n = self.remaining.min(data.len()); + self.remaining -= n; + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::other("injected flush failure")) + } +} + +#[test] +fn propagates_header_body_and_flush_failures() { + assert!(Gz::new(FailAfter { remaining: 0 }).is_err()); + let mut body = Gz::new(FailAfter { remaining: 10 }).unwrap(); + body.packed(true).unwrap(); + assert!(body.write_all(&vec![42; 200_000]).is_err()); + let empty = Gz::new(FailAfter { remaining: usize::MAX }).unwrap(); + assert_eq!(empty.finish().unwrap_err().to_string(), "injected flush failure"); +} diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 2dc9426ac3..df71d98603 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -17,6 +17,7 @@ avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"] heif = ["dep:craft-heif"] [dependencies] +crc32fast = "1.5" thiserror = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "tga", "ico", "qoi", "hdr"] } png = "0.18" @@ -45,6 +46,8 @@ exr = { version = "1.73", default-features = false, features = ["rayon"] } [dev-dependencies] proptest = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff"] } +sha2 = { version = "0.10", default-features = false, features = ["std"] } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +craft-video = { workspace = true, features = ["av1-decode"] } jxl-oxide = { version = "=0.12.6", default-features = false, features = ["rayon"] } diff --git a/crates/image-codecs/NOTICE b/crates/image-codecs/NOTICE new file mode 100644 index 0000000000..b3424a8b7c --- /dev/null +++ b/crates/image-codecs/NOTICE @@ -0,0 +1,123 @@ +JPEG encoding dependency: jpeg-encoder 0.6.1 + +Source: https://crates.io/crates/jpeg-encoder/0.6.1 +Declared license: (MIT OR Apache-2.0) AND IJG. +This software is based in part on the work of the Independent JPEG Group. + +The MIT license and unaltered upstream IJG and SIMD notices follow. The Apache-2.0 +alternative is also retained in licenses/jpeg-encoder-0.6.1 at the repository root +(https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1). +The dependency is used unmodified; no encoder implementation is vendored here. + +LICENSE-MIT + +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +Original src/fdct.rs opening notice + +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ + +Original src/avx2/fdct.rs opening notice + +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 955542c91b..aaf7f54b40 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -302,9 +302,11 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them `DecodeOptions { limits: Limits { max_width, max_height, max_pixels, max_alloc }, .. }` guards decoding. Header dimensions are checked before the pixel buffer is allocated, and the budget is also passed to the underlying decoders. A violation returns `CodecError::LimitExceeded`. The -defaults are 262144 px per side, 2^30 pixels and 8 GiB (2 GiB on 32-bit targets such as wasm). +defaults are 262144 px per side, 2^30 pixels and 8 GiB (1 GiB on 32-bit targets such as wasm). PNG also bounds the aggregate decoded text and XMP (UTF-8 keywords and values) by `max_alloc`, including chunks after IDAT. This budget is separate from pixels, not a total process-memory cap. +`Image::to_rgba_f32(&limits)` checks its output buffer against the same `Limits` and returns +`CodecError::LimitExceeded` before allocating when the RGBA f32 copy would exceed them. PNG `cICP` and `cLLI` values are retained as image color metadata. `encode_png_pq` writes linear-light Rec. 2020 RGB as 16-bit BT.2100 PQ, with measured content-light levels and the required chunks. @@ -324,3 +326,25 @@ Rec. 2020 RGB as 16-bit BT.2100 PQ, with measured content-light levels and the r If `corpus/pngsuite/*.png` exists at the repo root, every file in it is compared against the `image` crate's decoder. Without it, that test is skipped. + +With the `corpus` feature, the deep EXR test reads `11.deep.exr`, `42.deep.exr`, `64.deep.exr`, +`multivariate.deep.exr` and `objectid.deep.exr` from `corpus/exr/` at the repo root. These are the +deep test images in `src/test/bin/test_images` of the +[OpenEXR repository at commit `69b2604fc76e370615438bdc8d2cd95b9349c12e`](https://github.com/AcademySoftwareFoundation/openexr/tree/69b2604fc76e370615438bdc8d2cd95b9349c12e/src/test/bin/test_images). +The test checks each file against the SHA-256 pinned in `REAL_FILE_SHA256` in +`tests/it/deep_exr.rs` before decoding it, and fails when a file is missing, is not a regular +file, is larger than 4 MiB or does not match. It reads no other file in the folder. To fill the +folder, copy the five files from that commit into `corpus/exr/`, or run +`cargo xtask corpus --exr` in a checkout of [PhotoCraft](https://github.com/storytold/PhotoCraft) +at commit `74330157cb601573ae4523a95bb9132822fc3918` and copy its `corpus/exr/` here, as CI does. +The images are not committed here; OpenEXR distributes them under its +[license](https://github.com/AcademySoftwareFoundation/openexr/blob/69b2604fc76e370615438bdc8d2cd95b9349c12e/LICENSE.md). + +## Redistribution notices + +JPEG encoding uses `jpeg-encoder` 0.6.1, including work from the Independent JPEG Group. +Retain this crate's [NOTICE](NOTICE) with binary distributions using that encoder. It includes +its MIT license, the IJG acknowledgement and original IJG/SIMD notices. Both upstream license +alternatives and source checksums are retained in +[`licenses/jpeg-encoder-0.6.1`](https://github.com/storytold/craft-libs/tree/main/licenses/jpeg-encoder-0.6.1) +at the repository root. diff --git a/crates/image-codecs/src/apng.rs b/crates/image-codecs/src/apng.rs new file mode 100644 index 0000000000..30d22efebb --- /dev/null +++ b/crates/image-codecs/src/apng.rs @@ -0,0 +1,201 @@ +//! APNG container assembly for already-compressed RGBA8 frame streams. +//! +//! Extracted from AniCraft's animated export (Tanish Manku, commit a20a488f). +//! Frame selection, timing quantization and pixel compression remain caller policy. +//! Payloads must be complete PNG IDAT zlib streams for non-interlaced RGBA8 images +//! of the declared frame size. They are not decompressed or validated here. + +use crate::CodecError; + +/// One compressed frame. The first must cover the entire canvas. +#[derive(Clone, Copy, Debug)] +pub struct Frame<'a> { + pub width: u32, + pub height: u32, + pub x: u32, + pub y: u32, + /// Exact delay numerator; zero is retained without rounding. + pub delay_num: u16, + /// Exact denominator; zero has the APNG-defined meaning of 100. + pub delay_den: u16, + /// Blend over the previous canvas instead of replacing the rectangle. + pub over: bool, + /// Concatenated IDAT payload, not complete PNG chunks. + pub data: &'a [u8], +} + +fn invalid(message: &str) -> CodecError { + CodecError::InvalidImage(message.into()) +} + +// PNG 3 §7.1 restricts unsigned integers to 31 bits. The last fdAT sequence +// is 2 * count - 2; validate arithmetically without allocating frame headers. +fn animation_count(len: usize, plays: u32) -> Result { + let count = u32::try_from(len).map_err(|_| invalid("too many APNG frames"))?; + if plays > 0x7fff_ffff || count == 0 || count > (0x7fff_ffff / 2) + 1 { + return Err(invalid("APNG play count or sequence exceeds PNG integer range")); + } + Ok(count) +} + +/// Assemble an RGBA8 APNG with dispose-none frames and the first frame as default image. +/// `plays == 0` means infinite looping. `max_bytes` bounds the returned encoded file, +/// not caller-owned inputs or decoded pixels. Checked sizing precedes allocation; +/// malformed geometry, chunk lengths and sequence exhaustion fail before output. +pub fn encode(width: u32, height: u32, plays: u32, frames: &[Frame<'_>], max_bytes: usize) -> Result, CodecError> { + if width == 0 || height == 0 || width > 0x7fff_ffff || height > 0x7fff_ffff || frames.is_empty() { + return Err(invalid("APNG needs a nonempty canvas and frames")); + } + let count = animation_count(frames.len(), plays)?; + let mut size = 8usize + 25 + 20 + 12; // signature, IHDR, acTL, IEND + for (index, f) in frames.iter().enumerate() { + if f.width == 0 + || f.height == 0 + || f.x.checked_add(f.width).is_none_or(|end| end > width) + || f.y.checked_add(f.height).is_none_or(|end| end > height) + || (index == 0 && (f.x != 0 || f.y != 0 || f.width != width || f.height != height)) + { + return Err(invalid("APNG frame is outside canvas or first frame is not full size")); + } + let prefix = if index == 0 { 0 } else { 4 }; + let data_len = f.data.len().checked_add(prefix).ok_or_else(|| invalid("APNG chunk overflow"))?; + if f.data.is_empty() || data_len > 0x7fff_ffff { + return Err(invalid("APNG frame payload is empty or too large")); + } + size = size + .checked_add(38 + 12) + .and_then(|n| n.checked_add(data_len)) + .filter(|n| *n <= max_bytes) + .ok_or_else(|| CodecError::LimitExceeded("APNG output byte budget".into()))?; + } + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded("APNG output allocation".into()))?; + out.extend_from_slice(b"\x89PNG\r\n\x1a\n"); + let mut ihdr = [0u8; 13]; + ihdr[..4].copy_from_slice(&width.to_be_bytes()); + ihdr[4..8].copy_from_slice(&height.to_be_bytes()); + ihdr[8..].copy_from_slice(&[8, 6, 0, 0, 0]); + chunk(&mut out, b"IHDR", &[], &ihdr); + let mut actl = [0u8; 8]; + actl[..4].copy_from_slice(&count.to_be_bytes()); + actl[4..].copy_from_slice(&plays.to_be_bytes()); + chunk(&mut out, b"acTL", &[], &actl); + let mut sequence = 0u32; + for (index, f) in frames.iter().enumerate() { + let mut control = [0u8; 26]; + for (target, value) in control[..20].as_chunks_mut::<4>().0.iter_mut().zip([sequence, f.width, f.height, f.x, f.y]) { + target.copy_from_slice(&value.to_be_bytes()); + } + control[20..22].copy_from_slice(&f.delay_num.to_be_bytes()); + control[22..24].copy_from_slice(&f.delay_den.to_be_bytes()); + control[25] = u8::from(f.over); + chunk(&mut out, b"fcTL", &[], &control); + if index == 0 { + chunk(&mut out, b"IDAT", &[], f.data); + } else { + chunk(&mut out, b"fdAT", &(sequence + 1).to_be_bytes(), f.data); + } + // The final frame does not need a next sequence number. + if index + 1 < frames.len() { + sequence += if index == 0 { 1 } else { 2 }; + } + } + chunk(&mut out, b"IEND", &[], &[]); + Ok(out) +} + +// Lengths and total capacity were validated before writing. Prefix avoids a frame-sized +// intermediate fdAT allocation. CRC covers the type, prefix and payload, as PNG requires. +#[allow(clippy::cast_possible_truncation)] +fn chunk(out: &mut Vec, kind: &[u8; 4], prefix: &[u8], data: &[u8]) { + out.extend_from_slice(&((prefix.len() + data.len()) as u32).to_be_bytes()); + let start = out.len(); + out.extend_from_slice(kind); + out.extend_from_slice(prefix); + out.extend_from_slice(data); + let crc = crc32fast::hash(&out[start..]); + out.extend_from_slice(&crc.to_be_bytes()); +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn frame(data: &[u8]) -> Frame<'_> { + Frame { width: 1, height: 1, x: 0, y: 0, delay_num: 200, delay_den: 2997, over: false, data } + } + + fn chunks(bytes: &[u8]) -> Vec<([u8; 4], Vec)> { + let mut pos = 8; + let mut result = Vec::new(); + while pos < bytes.len() { + let n = u32::from_be_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; + let kind = bytes[pos + 4..pos + 8].try_into().unwrap(); + let end = pos + 8 + n; + assert_eq!(crc32fast::hash(&bytes[pos + 4..end]), u32::from_be_bytes(bytes[end..end + 4].try_into().unwrap())); + result.push((kind, bytes[pos + 8..end].to_vec())); + pos = end + 4; + } + result + } + + #[test] + fn png_integer_boundaries_without_giant_allocations() { + assert_eq!(animation_count(1, 0).unwrap(), 1); + assert_eq!(animation_count(0x4000_0000, 0x7fff_ffff).unwrap(), 0x4000_0000); + assert!(animation_count(0x4000_0001, 0).is_err()); + assert!(animation_count(0, 0).is_err()); + assert!(animation_count(1, 0x8000_0000).is_err()); + assert!(animation_count(1, u32::MAX).is_err()); + assert!(encode(1, 1, 0x8000_0000, &[frame(&[1])], 1000).is_err()); + } + + #[test] + fn preserves_rgba_delays_loop_blend_and_sequences() { + let mut png_bytes = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut png_bytes, 1, 1); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&[12, 34, 56, 128]).unwrap(); + writer.finish().unwrap(); + } + let data: Vec = chunks(&png_bytes).into_iter().filter(|(kind, _)| kind == b"IDAT").flat_map(|(_, data)| data).collect(); + let first = frame(&data); + let second = Frame { over: true, delay_num: 0, delay_den: 0, ..first }; + let encoded = encode(1, 1, 7, &[first, second], 4096).unwrap(); + let parts = chunks(&encoded); + assert_eq!( + parts.iter().map(|(kind, _)| *kind).collect::>(), + vec![*b"IHDR", *b"acTL", *b"fcTL", *b"IDAT", *b"fcTL", *b"fdAT", *b"IEND"] + ); + assert_eq!(parts[1].1, [0, 0, 0, 2, 0, 0, 0, 7]); + assert_eq!(&parts[2].1[20..], &[0, 200, 11, 181, 0, 0]); + assert_eq!(&parts[4].1[..4], &1u32.to_be_bytes()); + assert_eq!(&parts[4].1[20..], &[0, 0, 0, 0, 0, 1]); + assert_eq!(&parts[5].1[..4], &2u32.to_be_bytes()); + assert_eq!(&parts[5].1[4..], data.as_slice()); + let mut reader = png::Decoder::new(std::io::Cursor::new(&encoded)).read_info().unwrap(); + let mut pixels = [0u8; 4]; + reader.next_frame(&mut pixels).unwrap(); + assert_eq!(pixels, [12, 34, 56, 128]); + reader.next_frame(&mut pixels).unwrap(); + assert_eq!(pixels, [12, 34, 56, 128]); + assert!(encode(1, 1, 7, &[first, second], encoded.len() - 1).is_err()); + assert_eq!(encode(1, 1, 7, &[first, second], encoded.len()).unwrap(), encoded); + } + + #[test] + fn rejects_invalid_geometry_empty_payload_and_budget() { + let f = frame(&[1]); + assert!(encode(0, 1, 0, &[f], 1000).is_err()); + assert!(encode(1, 1, 0, &[], 1000).is_err()); + assert!(encode(2, 1, 0, &[f], 1000).is_err()); + assert!(encode(1, 1, 0, &[Frame { data: &[], ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f, Frame { x: u32::MAX, ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f, Frame { height: 0, ..f }], 1000).is_err()); + assert!(encode(1, 1, 0, &[f], 0).is_err()); + } +} diff --git a/crates/image-codecs/src/codecs/avif.rs b/crates/image-codecs/src/codecs/avif.rs index d27112fa18..042b5684b1 100644 --- a/crates/image-codecs/src/codecs/avif.rs +++ b/crates/image-codecs/src/codecs/avif.rs @@ -25,12 +25,17 @@ fn pq_encode(nits: f32) -> f32 { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] fn hlg_signal(rgb: [f32; 3]) -> [f32; 3] { + const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; + const GAMMA: f32 = 1.2; const A: f32 = 0.17883277; const B: f32 = 0.28466892; const C: f32 = 0.559_910_7; - rgb.map(|v| { - let s = if v.is_finite() { v.clamp(0.0, 12.0) / 12.0 } else { 0.0 }; - if s <= 1.0 / 12.0 { (3.0 * s).sqrt() } else { A * (12.0 * s - B).ln() + C } + let display = rgb.map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * (HDR_REFERENCE_WHITE_NITS / crate::cicp::HLG_PEAK_NITS)); + let y = K[0] * display[0] + K[1] * display[1] + K[2] * display[2]; + let inverse_ootf = if y > 0.0 { y.powf((1.0 - GAMMA) / GAMMA) } else { 0.0 }; + display.map(|v| { + let scene = (v * inverse_ootf).clamp(0.0, 1.0); + if scene <= 1.0 / 12.0 { (3.0 * scene).sqrt() } else { A * (12.0 * scene - B).ln() + C } }) } @@ -39,8 +44,14 @@ fn hlg_signal(rgb: [f32; 3]) -> [f32; 3] { pub fn encode_avif_with_speed(img: &Image, quality: u8, speed: u8) -> Result, CodecError> { #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] { - let mut enc = - ravif::Encoder::new().with_quality(f32::from(quality.clamp(1, 100))).with_speed(speed.clamp(1, 10)).with_bit_depth(ravif::BitDepth::Ten); + let mut enc = ravif::Encoder::new() + .with_quality(f32::from(quality.clamp(1, 100))) + .with_alpha_quality(f32::from(quality.clamp(1, 100))) + .with_speed(speed.clamp(1, 10)) + .with_bit_depth(ravif::BitDepth::Ten); + if let Some(exif) = img.meta.exif.as_deref() { + enc = enc.with_exif(exif); + } let alpha_mode = if img.layout().has_alpha() { ravif::AlphaColorMode::UnassociatedClean } else { ravif::AlphaColorMode::UnassociatedDirty }; enc = enc.with_alpha_color_mode(alpha_mode); let w = img.width() as usize; @@ -209,3 +220,94 @@ pub fn encode_avif_hdr( Err(CodecError::unsupported(Format::Avif, "AVIF encoding is not available in this build")) } } + +#[cfg(test)] +mod tests { + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn sdr_avif_uses_requested_alpha_quality() { + use crate::{ChannelLayout, Image}; + + let pixels: Vec = (0..1024).map(|i| ravif::RGBA8::new(100, 120, 140, ((i * 37) % 256) as u8)).collect(); + let samples: Vec = pixels.iter().flat_map(|p| [p.r, p.g, p.b, p.a]).collect(); + let image = Image::from_u8(32, 32, ChannelLayout::Rgba, samples).unwrap(); + let actual = super::encode_avif_with_speed(&image, 20, 10).unwrap(); + let expected = ravif::Encoder::new() + .with_quality(20.0) + .with_alpha_quality(20.0) + .with_speed(10) + .with_bit_depth(ravif::BitDepth::Ten) + .with_alpha_color_mode(ravif::AlphaColorMode::UnassociatedClean) + .encode_rgba(ravif::Img::new(&pixels, 32, 32)) + .unwrap() + .avif_file; + assert!(actual == expected, "encoded alpha must use the requested quality"); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn sdr_avif_keeps_exif_metadata() { + use crate::{ChannelLayout, Image}; + + let exif = b"II*\0shared-avif-exif".to_vec(); + let mut image = Image::from_u8(2, 1, ChannelLayout::Rgb, vec![20, 40, 60, 80, 100, 120]).unwrap(); + image.meta.exif = Some(exif.clone()); + + let avif = super::encode_avif_with_speed(&image, 80, 8).unwrap(); + assert!(avif.windows(exif.len()).any(|window| window == exif.as_slice())); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_mapping_matches_reference_white_and_peak() { + let white = super::hlg_signal([1.0; 3]); + assert!(white.iter().all(|&value| (value - 0.75).abs() < 0.005), "{white:?}"); + + let peak = super::hlg_signal([crate::cicp::HLG_PEAK_NITS / super::HDR_REFERENCE_WHITE_NITS; 3]); + assert!(peak.iter().all(|&value| (value - 1.0).abs() < 0.005), "{peak:?}"); + + let invalid = super::hlg_signal([f32::NAN, -1.0, f32::INFINITY]); + assert_eq!(invalid, [0.0; 3]); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_encoded_output_signals_bt2020_hlg() { + let avif = super::encode_avif_hdr(1, 1, &[1.0; 3], 100, 10, None, super::HdrTransfer::Hlg).unwrap(); + let nclx = avif.windows(4).position(|window| window == b"nclx").expect("the AVIF has nclx color metadata"); + let color = avif.get(nclx + 4..nclx + 11).expect("complete nclx color metadata"); + assert_eq!(&color[..2], &[0, 9], "BT.2020 primaries"); + assert_eq!(&color[2..4], &[0, 18], "BT.2100 HLG transfer"); + assert_eq!(&color[4..6], &[0, 9], "BT.2020 non-constant luminance matrix"); + assert!(!avif.windows(4).any(|window| window == b"clli"), "HLG does not signal PQ content-light metadata"); + } + + #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] + #[test] + fn hlg_encoded_pixels_preserve_reference_white_and_peak() { + let mut rgb = Vec::new(); + for _ in 0..32 { + for x in 0..64 { + let level = if x < 32 { 1.0 } else { crate::cicp::HLG_PEAK_NITS / super::HDR_REFERENCE_WHITE_NITS }; + rgb.extend_from_slice(&[level; 3]); + } + } + let avif = super::encode_avif_hdr(64, 32, &rgb, 100, 10, None, super::HdrTransfer::Hlg).unwrap(); + let mut offset = 0; + let payload = loop { + let header = avif.get(offset..offset + 8).expect("complete AVIF box header"); + let size = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize; + assert!(size >= 8 && offset + size <= avif.len(), "valid AVIF box size"); + if &header[4..] == b"mdat" { + break &avif[offset + 8..offset + size]; + } + offset += size; + }; + let mut decoder = craft_video::av1::decode::Decoder::new(); + let mut frames = decoder.decode(payload).unwrap(); + frames.extend(decoder.flush_result().unwrap()); + let luma = &frames.first().expect("encoded AV1 frame").planes[0]; + assert!((i32::from(luma[16 * 64 + 16]) - 767).abs() <= 5, "diffuse white"); + assert!((i32::from(luma[16 * 64 + 48]) - 1023).abs() <= 5, "peak white"); + } +} diff --git a/crates/image-codecs/src/codecs/pcx.rs b/crates/image-codecs/src/codecs/pcx.rs index 48dbf1169e..bf1b2eee66 100644 --- a/crates/image-codecs/src/codecs/pcx.rs +++ b/crates/image-codecs/src/codecs/pcx.rs @@ -1,5 +1,5 @@ //! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour -//! palettes and 8-bit three-plane RGB. Read-only: modern saves should use PNG. +//! palettes, 8-bit RGB and four-plane RGBA. Read-only: modern saves should use PNG. use crate::SampleType; use crate::error::CodecError; @@ -19,7 +19,7 @@ fn le16(b: &[u8], i: usize) -> u16 { /// PCX lacks a strong magic number. Require plausible complete header fields before /// identifying it, rather than classifying every file starting with 0x0a as PCX. pub(crate) fn looks_like_pcx(b: &[u8]) -> bool { - if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2 | 3 | 5) || b[2] != 1 { + if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2..=5) || b[2] != 1 { return false; } let bits = b[3]; @@ -31,7 +31,12 @@ pub(crate) fn looks_like_pcx(b: &[u8]) -> bool { } let width = u32::from(x1 - x0) + 1; let min_stride = (width * u32::from(bits)).div_ceil(8); - stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4) + stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3 | 4)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4) +} + +/// The dimensions declared by a plausible PCX header, without decoding its pixels. +pub(crate) fn dimensions(b: &[u8]) -> Option<(u32, u32)> { + looks_like_pcx(b).then(|| (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1)) } /// Read one compressed scanline, including all planes. RLE packets never cross a scanline. @@ -61,11 +66,12 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { if !looks_like_pcx(b) { return Err(bad("invalid PCX header or unsupported pixel layout")); } - let (w, h) = (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1); - limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?; + let (w, h) = dimensions(b).ok_or_else(|| bad("invalid PCX header or unsupported pixel layout"))?; + let layout = if b[3] == 8 && b[65] == 4 { ChannelLayout::Rgba } else { ChannelLayout::Rgb }; + limits.check(w, h, layout, SampleType::U8)?; let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66))); let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?; - let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?; + let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(layout.channels())).ok_or_else(|| bad("pixel size overflow"))?; // The last 769 bytes are the optional VGA palette for 8-bit indexed images. let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c; if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 { @@ -102,8 +108,10 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { for y in 0..h as usize { read_row(&b[..image_end], &mut p, &mut row)?; for x in 0..width { - let rgb = if bits == 8 && planes == 3 { - [row[x], row[stride + x], row[2 * stride + x]] + let rgba = if bits == 8 && planes == 4 { + [row[x], row[stride + x], row[2 * stride + x], row[3 * stride + x]] + } else if bits == 8 && planes == 3 { + [row[x], row[stride + x], row[2 * stride + x], 255] } else { let index = if bits == 8 { usize::from(row[x]) @@ -118,19 +126,20 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { }; if vga { let o = image_end + 1 + index * 3; - [b[o], b[o + 1], b[o + 2]] + [b[o], b[o + 1], b[o + 2], 255] } else if bits == 8 { let g = index as u8; - [g, g, g] // palette-info 2: gray scale + [g, g, g, 255] // palette-info 2: gray scale } else { let o = 16 + index * 3; - [b[o], b[o + 1], b[o + 2]] + [b[o], b[o + 1], b[o + 2], 255] } }; - pixels[(y * width + x) * 3..(y * width + x + 1) * 3].copy_from_slice(&rgb); + let start = (y * width + x) * layout.channels(); + pixels[start..start + layout.channels()].copy_from_slice(&rgba[..layout.channels()]); } } - let mut image = Image::from_u8(w, h, ChannelLayout::Rgb, pixels)?; + let mut image = Image::from_u8(w, h, layout, pixels)?; let (xdpi, ydpi) = (le16(b, 12), le16(b, 14)); if xdpi > 0 && ydpi > 0 { image.meta.dpi = Some((f32::from(xdpi), f32::from(ydpi))); diff --git a/crates/image-codecs/src/codecs/png.rs b/crates/image-codecs/src/codecs/png.rs index 4ceb754039..9965dfc303 100644 --- a/crates/image-codecs/src/codecs/png.rs +++ b/crates/image-codecs/src/codecs/png.rs @@ -141,12 +141,12 @@ impl> PngDecodeRows { /// Reads the header and refuses what [`decode`] refuses before any pixel is decoded: sizes /// past `limits`, and a file too small for the image it declares. pub fn new(bytes: B, limits: &Limits) -> Result { - Self::open(bytes, limits, true) + Self::open(bytes, limits, true, false) } /// [`PngDecodeRows::new`], optionally without reserving the whole image: a caller that hands /// the rows on as they come ([`decode_rows`]) never holds them all. - fn open(bytes: B, limits: &Limits, reserve: bool) -> Result { + fn open(bytes: B, limits: &Limits, reserve: bool, bounded_stream: bool) -> Result { let at = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); let bytes = SharedInput(std::sync::Arc::new(bytes)); let input = Tracked { cursor: Cursor::new(bytes.clone()), at: at.clone() }; @@ -187,7 +187,14 @@ impl> PngDecodeRows { let (width, height) = info.frame_control.map_or_else(|| info.size(), |f| (f.width, f.height)); let line = reader.output_line_size(width).ok_or_else(|| err("image too large"))?; // The output layout is known: charge its real bytes per pixel, not RGBA16's worst case. - limits.check(width, height, layout, sample)?; + if bounded_stream { + limits.check_size(width, height)?; + if line > limits.alloc_usize() { + return Err(CodecError::LimitExceeded("one PNG row exceeds max_alloc".into())); + } + } else { + limits.check(width, height, layout, sample)?; + } let height = usize::try_from(height).map_err(|_| err("image too large"))?; if width == 0 || height == 0 { return Err(err("the image is empty")); @@ -234,11 +241,35 @@ impl> PngDecodeRows { /// decode the whole image after all (an interlaced file) calls /// [`PngDecodeRows::reserve_output`] before [`PngDecodeRows::step`]. pub fn new_streaming(bytes: B, limits: &Limits) -> Result { - Self::open(bytes, limits, false) + Self::open(bytes, limits, false, false) + } + + /// Opens a bounded row stream without charging a full image that is never retained. + /// Dimension, pixel-count, plausibility, decoder and metadata limits remain unchanged; + /// `max_alloc` also bounds each row group. It is not a total process-memory limit. + /// Unlike [`Self::new_streaming`], a streamable image may exceed the full-image budget. + /// Non-streamable images still require that budget, as do [`Self::step`] and + /// [`Self::reserve_output`]. The caller must bound any output it retains in its sink. + pub fn new_bounded_streaming(bytes: B, limits: &Limits) -> Result { + let decoder = Self::open(bytes, limits, false, true)?; + if !decoder.streamable() { + decoder.check_full_output()?; + } + Ok(decoder) + } + + fn check_full_output(&self) -> Result<(), CodecError> { + let height = u32::try_from(self.height).map_err(|_| err("image too large"))?; + self.limits.check(self.width, height, self.layout, self.sample)?; + if self.size > self.limits.alloc_usize() { + return Err(CodecError::LimitExceeded("PNG output exceeds max_alloc".into())); + } + Ok(()) } /// Reserves the buffer [`PngDecodeRows::step`] decodes the whole image into. pub fn reserve_output(&mut self) -> Result<(), CodecError> { + self.check_full_output()?; let size = self.size; self.buf.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {size} bytes for the image"))) } @@ -271,6 +302,7 @@ impl> PngDecodeRows { /// Decodes at least one row (the whole image if it is interlaced), then goes on while `more()` /// returns true. `Some` once the image is complete, after which the decoder is spent. pub fn step(&mut self, more: &mut dyn FnMut() -> bool) -> Result, CodecError> { + self.check_full_output()?; if self.done { return Err(err("the image was already decoded")); } @@ -338,7 +370,9 @@ impl> PngDecodeRows { /// `more()` returns true; `Some` with the extras once the file is read to its end, with the /// resolution a format that lacks one takes from its EXIF or XMP. A damaged file fails with /// the error [`decode`] gives, after however many rows were delivered. An orientation (an - /// `eXIf` after the image data may set one) is for the caller to apply. + /// `eXIf` after the image data may set one) is for the caller to apply. A new group size + /// must exceed any partial group retained from an earlier yield; otherwise this returns + /// an error without consuming another row. pub fn step_stream>( &mut self, group: u32, @@ -348,12 +382,29 @@ impl> PngDecodeRows { if self.done { return Err(err("the image was already decoded").into()); } - let group = usize::try_from(group.max(1)).unwrap_or(usize::MAX); + // Tail EXIF may report an orientation after rows have already been delivered; + // that belongs in the returned extras, not a rejection of metadata continuation. + if self.rows == 0 && !self.tail && !self.streamable() { + return Err(err("this PNG requires whole-image decoding").into()); + } + let group = usize::try_from(group.max(1)).unwrap_or(usize::MAX).min(self.height); + if self.rows - self.group_start >= group { + return Err(err("PNG row group is smaller than rows held from the previous step").into()); + } + let group_bytes = group.checked_mul(self.line).ok_or_else(|| err("PNG row group is too large"))?; + if group_bytes > self.limits.alloc_usize() { + return Err(CodecError::LimitExceeded("PNG row group exceeds max_alloc".into()).into()); + } if !self.tail { while self.rows < self.height { let held = self.rows - self.group_start; let at = held.checked_mul(self.line).ok_or_else(|| err("image too large"))?; let end = at.checked_add(self.line).ok_or_else(|| err("image too large"))?; + // A caller may change its group size between yields. Bound the actual held + // bytes as well as the requested group before growing the row buffer. + if end > self.limits.alloc_usize() { + return Err(CodecError::LimitExceeded("PNG row group exceeds max_alloc".into()).into()); + } if self.buf.len() < end { self.buf .try_reserve_exact(end - self.buf.len()) @@ -368,7 +419,7 @@ impl> PngDecodeRows { to_native_endian(row); } self.rows += 1; - if self.rows - self.group_start == group || self.rows == self.height { + if self.rows - self.group_start >= group || self.rows == self.height { let data = self.buf.get(..end).ok_or_else(|| err("invalid PNG row group"))?; sink(u32::try_from(self.group_start).map_err(|_| err("image too large"))?, data)?; self.group_start = self.rows; diff --git a/crates/image-codecs/src/codecs/xpm.rs b/crates/image-codecs/src/codecs/xpm.rs index c20f3c58e9..c74b5f16b3 100644 --- a/crates/image-codecs/src/codecs/xpm.rs +++ b/crates/image-codecs/src/codecs/xpm.rs @@ -96,7 +96,7 @@ fn channel(hex: &str) -> Option { Some(((v * 255 + max / 2) / max) as u8) } -fn named(name: &str) -> Option<[u8; 3]> { +pub(crate) fn named(name: &str) -> Option<[u8; 3]> { let s = name.to_ascii_lowercase().replace([' ', '-', '_'], ""); // XPM imports X11 names, whose RGB values differ from CSS for names // such as gray, maroon and purple. Keep these exact rather than guessing. @@ -114,6 +114,16 @@ fn named(name: &str) -> Option<[u8; 3]> { }) } +/// Exact, normalized X11 lookup for consumers that need table membership rather +/// than XPM's additional aliases and normalization rules. +pub(crate) fn exact_x11_name(name: &str) -> Option<[u8; 3]> { + if name.is_empty() || name.len() > 64 || !name.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()) { + return None; + } + let index = x11_colors::X11_COLORS.binary_search_by_key(&name, |(entry, _)| *entry).ok()?; + Some(x11_colors::X11_COLORS.get(index)?.1) +} + fn color(name: &str) -> Option<[u8; 4]> { if name.eq_ignore_ascii_case("none") { return Some([0, 0, 0, 0]); diff --git a/crates/image-codecs/src/image.rs b/crates/image-codecs/src/image.rs index a6f417c726..8f68197bfd 100644 --- a/crates/image-codecs/src/image.rs +++ b/crates/image-codecs/src/image.rs @@ -8,6 +8,7 @@ use std::fmt; use crate::error::CodecError; use crate::format::Format; +use crate::options::Limits; use half::f16; /// Channel layout of an [`Image`]. Alpha, when present, is always the last @@ -716,9 +717,31 @@ impl Image { self.convert(ChannelLayout::Rgba, SampleType::U16).to_u16_samples().unwrap_or_default() } - /// Interleaved RGBA as f32 (integer inputs normalized to `[0,1]`). - pub fn to_rgba_f32(&self) -> Vec { - convert_layout(&self.to_normalized(), self.layout, ChannelLayout::Rgba) + /// Interleaved RGBA as f32 (integer inputs normalized to `[0,1]`), with the same values as + /// [`Image::convert`] to RGBA F32. The output buffer is checked against `limits` (dimensions, + /// pixel count and `max_alloc`) and reserved before any pixel is converted, and the pixels are + /// written straight into it. A size over the limits, or a reservation the allocator refuses, + /// returns [`CodecError::LimitExceeded`]. An image with no pixels gives an empty vector. + pub fn to_rgba_f32(&self, limits: &Limits) -> Result, CodecError> { + if self.width == 0 || self.height == 0 { + return Ok(Vec::new()); + } + limits.check(self.width, self.height, ChannelLayout::Rgba, SampleType::F32)?; + let len = self + .pixel_count() + .checked_mul(ChannelLayout::Rgba.channels()) + .ok_or_else(|| CodecError::LimitExceeded("RGBA f32 size overflows usize".into()))?; + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|e| CodecError::LimitExceeded(format!("cannot reserve {len} f32 samples for RGBA: {e}")))?; + let fc = self.layout.channels(); + let mut px = [0.0f32; 5]; + for p in 0..self.pixel_count() { + for (c, v) in px[..fc].iter_mut().enumerate() { + *v = read_normalized(&self.data, self.sample, p * fc + c); + } + convert_pixel(&px[..fc], self.layout, ChannelLayout::Rgba, &mut out); + } + Ok(out) } } @@ -890,33 +913,39 @@ pub(crate) fn convert_layout(src: &[f32], from: ChannelLayout, to: ChannelLayout let n = src.len() / fc; let mut out = Vec::with_capacity(n * tc); for px in src.chunks_exact(fc) { - let alpha = if from.has_alpha() { px[fc - 1] } else { 1.0 }; - let color = &px[..from.color_channels()]; - if from.same_model(to) { - out.extend_from_slice(color); - } else { - let rgb = match from { - ChannelLayout::Gray | ChannelLayout::GrayA => [color[0]; 3], - ChannelLayout::Rgb | ChannelLayout::Rgba => [color[0], color[1], color[2]], - ChannelLayout::Cmyk | ChannelLayout::CmykA => cmyk_to_rgb(color[0], color[1], color[2], color[3]), - ChannelLayout::Lab | ChannelLayout::LabA => crate::lab::lab_to_srgb([color[0], color[1], color[2]]), - }; - match to { - ChannelLayout::Gray | ChannelLayout::GrayA => { - out.push(rgb[0] * LUMA[0] + rgb[1] * LUMA[1] + rgb[2] * LUMA[2]); - } - ChannelLayout::Rgb | ChannelLayout::Rgba => out.extend_from_slice(&rgb), - ChannelLayout::Cmyk | ChannelLayout::CmykA => out.extend_from_slice(&rgb_to_cmyk(rgb[0], rgb[1], rgb[2])), - ChannelLayout::Lab | ChannelLayout::LabA => out.extend_from_slice(&crate::lab::srgb_to_lab(rgb)), - } - } - if to.has_alpha() { - out.push(alpha); - } + convert_pixel(px, from, to, &mut out); } out } +/// One pixel of [`convert_layout`]: the normalized samples `px` (`from` layout) appended to `out` +/// in the `to` layout. +fn convert_pixel(px: &[f32], from: ChannelLayout, to: ChannelLayout, out: &mut Vec) { + let alpha = if from.has_alpha() { px[from.channels() - 1] } else { 1.0 }; + let color = &px[..from.color_channels()]; + if from.same_model(to) { + out.extend_from_slice(color); + } else { + let rgb = match from { + ChannelLayout::Gray | ChannelLayout::GrayA => [color[0]; 3], + ChannelLayout::Rgb | ChannelLayout::Rgba => [color[0], color[1], color[2]], + ChannelLayout::Cmyk | ChannelLayout::CmykA => cmyk_to_rgb(color[0], color[1], color[2], color[3]), + ChannelLayout::Lab | ChannelLayout::LabA => crate::lab::lab_to_srgb([color[0], color[1], color[2]]), + }; + match to { + ChannelLayout::Gray | ChannelLayout::GrayA => { + out.push(rgb[0] * LUMA[0] + rgb[1] * LUMA[1] + rgb[2] * LUMA[2]); + } + ChannelLayout::Rgb | ChannelLayout::Rgba => out.extend_from_slice(&rgb), + ChannelLayout::Cmyk | ChannelLayout::CmykA => out.extend_from_slice(&rgb_to_cmyk(rgb[0], rgb[1], rgb[2])), + ChannelLayout::Lab | ChannelLayout::LabA => out.extend_from_slice(&crate::lab::srgb_to_lab(rgb)), + } + } + if to.has_alpha() { + out.push(alpha); + } +} + #[cfg(test)] mod tests { #[test] @@ -1042,6 +1071,52 @@ mod tests { assert!(Image::from_raw(2, 2, ChannelLayout::Rgb, SampleType::U8, vec![0; 11]).is_err()); } + #[test] + fn rgba_f32_limit_rejects_before_allocation() { + // 3x2 pixels: the RGBA f32 output is 3 * 2 * 4 * 4 = 96 bytes. Most sources here are + // smaller than that, so the source fitting the budget does not let the output through. + for sample in SampleType::ALL { + for layout in ChannelLayout::ALL { + let img = Image::new(3, 2, layout, sample).unwrap(); + let tight = Limits::new(3, 2, 6, 95); + assert!(matches!(img.to_rgba_f32(&tight), Err(CodecError::LimitExceeded(_))), "{layout:?} {sample:?}: max_alloc"); + let exact = Limits::new(3, 2, 6, 96); + assert_eq!(img.to_rgba_f32(&exact).map(|v| v.len()).ok(), Some(24), "{layout:?} {sample:?}"); + for limits in [Limits::new(2, 2, 6, 96), Limits::new(3, 1, 6, 96), Limits::new(3, 2, 5, 96)] { + assert!(matches!(img.to_rgba_f32(&limits), Err(CodecError::LimitExceeded(_))), "{layout:?} {sample:?}: {limits:?}"); + } + } + } + } + + #[test] + fn rgba_f32_matches_existing_conversions() { + // Edge, mid and (for float samples) out-of-range values, so the CMYK, Lab and alpha + // formulas and the f16 and f32 reads are all compared bit for bit. + let base = [0.0, 1.0, 0.5, 0.25, 0.75, 1.0 / 255.0, 0.3, 0.9, 1.5, -0.25]; + for sample in SampleType::ALL { + for layout in ChannelLayout::ALL { + let n = 7 * 3 * layout.channels(); + let vals: Vec = (0..n).map(|i| base[(i * 7 + i / 3) % base.len()]).collect(); + let img = Image::from_normalized(7, 3, layout, sample, &vals).unwrap(); + let got = img.to_rgba_f32(&Limits::default()).unwrap(); + let want = convert_layout(&img.to_normalized(), layout, ChannelLayout::Rgba); + let via_convert = img.convert(ChannelLayout::Rgba, SampleType::F32).to_f32_samples().unwrap(); + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&got), bits(&want), "{layout:?} {sample:?}"); + assert_eq!(bits(&got), bits(&via_convert), "{layout:?} {sample:?}: convert"); + } + } + } + + #[test] + fn rgba_f32_of_an_empty_image_is_empty() { + for (w, h) in [(0, 0), (0, 3), (4, 0)] { + let img = Image::new(w, h, ChannelLayout::Rgb, SampleType::U8).unwrap(); + assert_eq!(img.to_rgba_f32(&Limits::new(1, 1, 1, 0)).ok(), Some(Vec::new()), "{w}x{h}"); + } + } + #[test] fn rgba8_of_gray() { let img = Image::from_u8(1, 1, ChannelLayout::GrayA, vec![10, 20]).unwrap(); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 61109faa1e..6516b9ff29 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -15,6 +15,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod allocation; +pub mod apng; pub mod cicp; mod codecs; mod error; @@ -237,6 +238,17 @@ pub fn jpeg_info(bytes: &[u8]) -> Option { jpeg::info(bytes) } +/// PCX's dimensions are available from its fixed-size header without decoding the RLE rows. +pub fn pcx_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { + codecs::pcx::dimensions(bytes) +} + +/// The X11 color-name lookup used by XPM files, expressed as normalized sRGB. +pub fn xpm_named_color_rgb(name: &str) -> Option<[f32; 3]> { + let rgb = codecs::xpm::exact_x11_name(name)?; + Some(rgb.map(|channel| f32::from(channel) / 255.0)) +} + /// The colour table of a GIF's first frame (its Local Color Table, else the Global one) and the /// entry its Graphic Control Extension makes transparent, read without decoding pixels. pub fn gif_palette(bytes: &[u8]) -> Option<(Vec<[u8; 3]>, Option)> { diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index ed96b87332..71f6030b3c 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -32,6 +32,10 @@ impl Default for Limits { } impl Limits { + /// Construct explicit bounds for a caller-owned format adapter. + pub const fn new(max_width: u32, max_height: u32, max_pixels: u64, max_alloc: u64) -> Self { + Limits { max_width, max_height, max_pixels, max_alloc } + } /// For a decoder that writes a band of rows at a time into the document's tiles instead of /// one buffer (TIFF, #8169): the largest document size, 300,000 px a side, on 64-bit /// targets, with `max_alloc` bounding each group of bands. 32-bit targets keep the @@ -85,7 +89,7 @@ impl Limits { /// never beats `max_ratio`:1. Called before the output buffer is allocated, so a /// header-only hostile file cannot make the decoder reserve gigabytes. A fixed 1 MiB of /// slack keeps tiny images and headers with large metadata unaffected. - pub(crate) fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> { + pub fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> { let capacity = (file_len as u64).saturating_mul(max_ratio).saturating_add(1 << 20); if declared_bytes > capacity { return Err(CodecError::LimitExceeded(format!("a {file_len} byte file cannot hold {declared_bytes} bytes of image data"))); diff --git a/crates/image-codecs/tests/it/deep_exr.rs b/crates/image-codecs/tests/it/deep_exr.rs index 37fe315adf..e614f865db 100644 --- a/crates/image-codecs/tests/it/deep_exr.rs +++ b/crates/image-codecs/tests/it/deep_exr.rs @@ -2,11 +2,14 @@ //! specification (NONE, RLE and ZIPS × scanline and tile), the oracle tests check the //! compositing math against hand-computed values, and malformed inputs must error, never //! panic. With the `corpus` feature, the OpenEXR project's deep test images (`corpus/exr/`, -//! pinned) are checked against the ID manifests their sidecars list. +//! each checked against its pinned SHA-256 before decoding) are checked against the ID +//! manifests their sidecars list. use craft_image_codecs::CodecError; use craft_image_codecs::f16; use craft_image_codecs::{Limits, decode, decode_deep_exr}; +use sha2::{Digest, Sha256}; +use std::io::Read as _; use std::io::Write as _; // --------------------------------------------------------------------------------------------- @@ -797,10 +800,55 @@ fn inconsistent_count_table_errors() { } // --------------------------------------------------------------------------------------------- -// Real reference files: the deep test images of the OpenEXR repository, pinned in -// `xtask/src/corpus_pins.rs` and fetched into `corpus/exr/` by `cargo xtask corpus --exr` -// (cargo feature `corpus`; `cargo xtask test-corpus`). Their `.txt` sidecars upstream list the -// ID manifest of each file, an independent oracle for the u32 ID channels. +// Real reference files: the deep test images of the OpenEXR repository at commit +// `69b2604fc76e370615438bdc8d2cd95b9349c12e`, read from `corpus/exr/` at the repo root with the +// cargo feature `corpus`. `REAL_FILE_SHA256` pins each file's SHA-256, and the test refuses a +// file that is missing, is not a regular file, is larger than `MAX_REAL_FILE_BYTES` or does not +// match its digest. The crate README says how to fill the folder. Their `.txt` sidecars upstream +// list the ID manifest of each file, an independent oracle for the u32 ID channels. + +/// The pinned files as name and lowercase hex SHA-256, the same five names as `REAL_FILES`. +const REAL_FILE_SHA256: &[(&str, &str)] = &[ + ("11.deep.exr", "800ec94ffb2085da9a730dcda2f9611f5fb62f922a3f2aef77287e36106b9667"), + ("42.deep.exr", "439907f3448480894264f0c8847f6c572f645441db34a5ad9f36f3f020d101b5"), + ("64.deep.exr", "4d9bfa646323b80630933e114a3112095488e8c008cdf908e210979638e65fe4"), + ("multivariate.deep.exr", "2335ed6052258fe693cb795f2bea57f22ba0564281691c82f2987d31d96e9e74"), + ("objectid.deep.exr", "af8940912bfa856b2650d2005462fd348656385161ccf0745b91b143e934c5f6"), +]; + +/// The largest file read from `corpus/exr/`. The largest pinned file is 611,840 bytes. +#[cfg(feature = "corpus")] +const MAX_REAL_FILE_BYTES: u64 = 4 * 1024 * 1024; + +/// The lowercase hex SHA-256 of `bytes`. +fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// Reads a regular file of at most `limit` bytes. A symbolic link, a folder or a larger file is an +/// error, and a file that grows during the read is cut off at `limit + 1` bytes and refused. +fn read_bounded(path: &std::path::Path, limit: u64) -> Result, String> { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + if !meta.is_file() || meta.len() > limit { + return Err(format!("{}: expected a regular file of at most {limit} bytes", path.display())); + } + let mut bytes = Vec::new(); + std::fs::File::open(path).and_then(|f| f.take(limit + 1).read_to_end(&mut bytes)).map_err(|e| format!("{}: {e}", path.display()))?; + if bytes.len() as u64 > limit { + return Err(format!("{}: exceeds {limit} bytes", path.display())); + } + Ok(bytes) +} + +/// Reads `dir/name` within `limit` bytes and checks its SHA-256 against `pinned`. +fn read_pinned(dir: &std::path::Path, name: &str, pinned: &str, limit: u64) -> Result, String> { + let bytes = read_bounded(&dir.join(name), limit)?; + let got = sha256_hex(&bytes); + if got != pinned { + return Err(format!("{name}: SHA-256 {got} does not match the pinned {pinned}")); + } + Ok(bytes) +} /// One pinned file: name, total samples, most samples in one pixel, and per ID channel the /// manifest IDs its sidecar lists. @@ -846,9 +894,12 @@ const REAL_FILES: &[RealFile] = &[ #[test] fn real_deep_files_decode() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/exr"); - for &(name, total, max_per_pixel, ids) in REAL_FILES { - let path = dir.join(name); - let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --exr`)", path.display())); + let decoded: Vec<&str> = REAL_FILES.iter().map(|f| f.0).collect(); + let pinned: Vec<&str> = REAL_FILE_SHA256.iter().map(|p| p.0).collect(); + assert_eq!(decoded, pinned, "REAL_FILES and REAL_FILE_SHA256 must list the same files"); + for (&(name, total, max_per_pixel, ids), &(_, sha256)) in REAL_FILES.iter().zip(REAL_FILE_SHA256) { + let bytes = read_pinned(&dir, name, sha256, MAX_REAL_FILE_BYTES) + .unwrap_or_else(|e| panic!("{}: {e}; place the pinned OpenEXR deep test images in this folder (see the crate README)", dir.display())); let deep = decode_deep_exr(&bytes, &Limits::none()).unwrap_or_else(|e| panic!("{name}: {e}")); assert_eq!((deep.width, deep.height), (256, 256), "{name}"); assert_eq!(deep.total_samples(), total, "{name}"); @@ -874,6 +925,66 @@ fn real_deep_files_decode() { } } +#[test] +fn real_file_pins_are_well_formed() { + let mut names = std::collections::BTreeSet::new(); + for &(name, sha256) in REAL_FILE_SHA256 { + assert!(name.ends_with(".deep.exr") && !name.contains(['/', '\\']), "{name}"); + assert!(names.insert(name), "{name} is pinned twice"); + assert_eq!(sha256.len(), 64, "{name}"); + assert!(sha256.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')), "{name}: {sha256}"); + } + assert_eq!(names.len(), 5); +} + +/// A folder under the system temp directory, removed when dropped. +struct ScratchDir(std::path::PathBuf); + +impl ScratchDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("craft-image-codecs-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch dir"); + Self(dir) + } +} + +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn pinned_read_refuses_a_changed_byte() { + let dir = ScratchDir::new("deep-exr-pin"); + // SHA-256 of "abc" (FIPS 180-2, appendix B.1). + let abc = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + std::fs::write(dir.0.join("a.deep.exr"), b"abc").expect("write"); + assert_eq!(read_pinned(&dir.0, "a.deep.exr", abc, 16).as_deref(), Ok(&b"abc"[..])); + + std::fs::write(dir.0.join("a.deep.exr"), b"abd").expect("write"); + let err = read_pinned(&dir.0, "a.deep.exr", abc, 16).expect_err("a changed byte must be refused"); + assert!(err.starts_with("a.deep.exr: ") && err.contains(abc) && err.contains(&sha256_hex(b"abd")), "{err}"); +} + +#[test] +fn pinned_read_refuses_missing_oversize_and_folders() { + let dir = ScratchDir::new("deep-exr-bound"); + let pin = sha256_hex(b"12345678"); + std::fs::write(dir.0.join("eight.deep.exr"), b"12345678").expect("write"); + assert!(read_pinned(&dir.0, "eight.deep.exr", &pin, 8).is_ok()); + let err = read_pinned(&dir.0, "eight.deep.exr", &pin, 7).expect_err("a file over the limit must be refused"); + assert!(err.contains("at most 7 bytes"), "{err}"); + + let err = read_pinned(&dir.0, "missing.deep.exr", &pin, 8).expect_err("a missing file must be refused"); + assert!(err.contains("missing.deep.exr"), "{err}"); + + std::fs::create_dir(dir.0.join("folder.deep.exr")).expect("mkdir"); + let err = read_pinned(&dir.0, "folder.deep.exr", &pin, 8).expect_err("a folder must be refused"); + assert!(err.contains("regular file"), "{err}"); +} + /// `gen_deep` for a cropped render: the data window sits at `(dwx, dwy)` inside a larger /// display window of `sw × sh` (the stage the renderer composed onto). Scanline chunk Y /// coordinates are absolute display rows, so they carry the data-window offset. diff --git a/crates/image-codecs/tests/it/png_jpeg.rs b/crates/image-codecs/tests/it/png_jpeg.rs index 6b213ea838..07c57bf245 100644 --- a/crates/image-codecs/tests/it/png_jpeg.rs +++ b/crates/image-codecs/tests/it/png_jpeg.rs @@ -665,3 +665,97 @@ fn step_stream_gives_the_pixels_and_extras_of_decode() { fn dec_line(w: u32, layout: ChannelLayout, sample: SampleType) -> usize { w as usize * layout.channels() * sample.bytes() } + +#[test] +fn bounded_png_stream_does_not_charge_unretained_full_frame() { + let image = synth(256, 1024, ChannelLayout::Rgba, SampleType::U16, 77, 0.5); + let bytes = encode(&image, Format::Png, &EncodeOptions::default()).unwrap(); + let limits = Limits { max_alloc: 512 * 1024, ..Limits::default() }; + assert!(image.data().len() > limits.max_alloc as usize); + assert!(PngDecodeRows::new(bytes.as_slice(), &limits).is_err()); + assert!(PngDecodeRows::new_streaming(bytes.as_slice(), &limits).is_err()); + let mut decoder = PngDecodeRows::new_bounded_streaming(bytes.as_slice(), &limits).unwrap(); + assert!(decoder.streamable()); + // Opening a stream must not become a way to bypass whole-image allocation guards. + assert!(decoder.reserve_output().is_err()); + assert!(decoder.step(&mut || true).is_err()); + let mut next = 0; + let mut sink = |first: u32, rows: &[u8]| -> Result<(), CodecError> { + assert_eq!(first as usize, next); + assert!(rows.len() <= 3 * 256 * 8); + let start = next * 256 * 8; + assert_eq!(rows, &image.data()[start..start + rows.len()]); + next += rows.len() / (256 * 8); + Ok(()) + }; + while decoder.step_stream(3, &mut || false, &mut sink).unwrap().is_none() {} + assert_eq!(next, 1024); +} + +#[test] +fn bounded_png_stream_keeps_group_dimension_and_fallback_limits() { + let image = synth(256, 1024, ChannelLayout::Rgba, SampleType::U16, 81, 0.5); + let bytes = encode(&image, Format::Png, &EncodeOptions::default()).unwrap(); + let limits = Limits { max_alloc: 512 * 1024, ..Limits::default() }; + let mut decoder = PngDecodeRows::new_bounded_streaming(bytes.as_slice(), &limits).unwrap(); + assert!(decoder.step_stream::(1024, &mut || true, &mut |_, _| panic!("oversized group reached sink")).is_err()); + for strict in [ + Limits { max_width: 255, ..limits }, + Limits { max_height: 1023, ..limits }, + Limits { max_pixels: 256 * 1024 - 1, ..limits }, + Limits { max_alloc: 1024, ..limits }, + ] { + assert!(PngDecodeRows::new_bounded_streaming(bytes.as_slice(), &strict).is_err()); + } + let adam7 = interlaced(&image); + assert!(PngDecodeRows::new_bounded_streaming(adam7.as_slice(), &limits).is_err()); +} + +#[test] +fn bounded_png_stream_rejects_shrinking_below_buffered_rows() { + let image = synth(16, 8, ChannelLayout::Rgba, SampleType::U16, 83, 0.5); + let bytes = encode(&image, Format::Png, &EncodeOptions::default()).unwrap(); + let mut decoder = PngDecodeRows::new_bounded_streaming(bytes.as_slice(), &Limits::default()).unwrap(); + for _ in 0..3 { + assert!(decoder.step_stream::(4, &mut || false, &mut |_, _| panic!("group is incomplete")).unwrap().is_none()); + } + assert!(decoder.step_stream::(1, &mut || true, &mut |_, _| panic!("changed group reached sink")).is_err()); + let mut output = Vec::new(); + decoder + .step_stream::(4, &mut || true, &mut |_, rows| { + output.extend_from_slice(rows); + Ok(()) + }) + .unwrap(); + assert_eq!(output, image.data()); +} + +#[test] +fn bounded_png_stream_preserves_late_exif_across_metadata_yields() { + let image = synth(16, 8, ChannelLayout::Rgba, SampleType::U16, 89, 0.5); + let bytes = encode(&image, Format::Png, &EncodeOptions::default()).unwrap(); + let mut exif = sample_exif(); + exif[18..22].copy_from_slice(&6u32.to_le_bytes()); + let mut chunks = vec![png_chunk(b"eXIf", &exif)]; + for i in 0..150 { + chunks.push(png_chunk(b"tEXt", format!("key{i}\0value").as_bytes())); + } + let bytes = with_chunks_before_iend(&bytes, &chunks); + let mut decoder = PngDecodeRows::new_bounded_streaming(bytes.as_slice(), &Limits::default()).unwrap(); + assert!(decoder.streamable()); + let mut output = Vec::new(); + let extras = loop { + if let Some(extras) = decoder + .step_stream::(2, &mut || false, &mut |_, rows| { + output.extend_from_slice(rows); + Ok(()) + }) + .unwrap() + { + break extras; + } + }; + assert_eq!(output, image.data()); + assert_eq!(extras.orientation, 6); + assert_eq!(extras.meta.text.len(), 150); +} diff --git a/crates/jsonrpc/Cargo.toml b/crates/jsonrpc/Cargo.toml new file mode 100644 index 0000000000..7456ececf2 --- /dev/null +++ b/crates/jsonrpc/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-jsonrpc" +description = "Bounded JSON-RPC 2.0 server envelopes without transport or application routing" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde_json = { workspace = true } diff --git a/crates/jsonrpc/README.md b/crates/jsonrpc/README.md new file mode 100644 index 0000000000..8711c25ff4 --- /dev/null +++ b/crates/jsonrpc/README.md @@ -0,0 +1,31 @@ +# craft-jsonrpc + +`craft-jsonrpc` provides bounded JSON-RPC 2.0 server envelopes independently of a transport or an +application's method router. It can read a bounded newline-delimited message, parse it from bytes, +check request IDs and batch sizes, dispatch requests and notifications separately, and build +response envelopes. It does not start a server, choose an MCP protocol version, or interpret tool +names and arguments. + +`Limits` defaults to 64 MiB per message and 4096 batch entries. `parse_json` checks the byte limit +before deserialization, and `process` rejects an oversized batch before calling any handler. +For newline-delimited transports, `read_line` bounds memory while reading; after an over-limit +line, the caller must close the stream or discard the rest of that line. +`serde_json`'s nesting limit remains in effect. Response sizes are the caller's responsibility. + +A valid request receives the handler's result or error with its original string, numeric, or null +ID. The default accepts numeric IDs as required by [JSON-RPC 2.0](https://www.jsonrpc.org/specification#request_object), +which discourages fractional values. Set `integer_ids_only` and clear `allow_null_ids` for +protocols such as MCP that require integer or string IDs. A legacy server can retain its previous +null-ID behavior independently. An omitted ID is a notification: it calls the separate notification +handler and gets no reply. +Malformed batch entries receive an invalid-request error; an empty batch gets one error response; +a batch containing only notifications has no response. Invalid parameter shapes receive an +invalid-params error for requests and no reply for notifications. The handler decides whether +object or array parameters are valid for each method. + +The caller may inspect the bounded parsed value before `process` to support an existing legacy +protocol. Parse failures and limit failures are returned explicitly so each transport can choose +its error and connection policy; `parse_error_response` builds the JSON-RPC parse error. + +The envelope behavior is extracted from StencilCraft's JSON-lines MCP/control server. App-specific +method routing, legacy control requests, and MCP lifecycle policy stay with the app. diff --git a/crates/jsonrpc/src/lib.rs b/crates/jsonrpc/src/lib.rs new file mode 100644 index 0000000000..9f8128d1dc --- /dev/null +++ b/crates/jsonrpc/src/lib.rs @@ -0,0 +1,197 @@ +//! Bounded JSON-RPC 2.0 server envelopes without a transport or application router. +//! +//! Parse a bounded line with [`parse_json`], then pass the value to [`process`]. A host may +//! inspect the parsed value first for a legacy protocol. `process` validates envelopes, dispatches +//! requests and notifications separately, and constructs single or batch replies. The host owns +//! the transport, method semantics and response-size policy. + +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use serde_json::{Value, json}; +use std::io::BufRead; + +/// Bounds on a single JSON document and on the number of requests in a batch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + pub max_message_bytes: usize, + pub max_batch_items: usize, + /// Reject fractional JSON numbers as IDs for protocols that require integer IDs. + pub integer_ids_only: bool, + /// Permit an explicit null request ID, as JSON-RPC does; some protocols prohibit it. + pub allow_null_ids: bool, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_message_bytes: 64 * 1024 * 1024, max_batch_items: 4096, integer_ids_only: false, allow_null_ids: true } + } +} + +/// Failure before dispatch. An over-limit batch is rejected before any callback is invoked. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ParseError { + MessageTooLarge, + InvalidJson, + BatchTooLarge, +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::MessageTooLarge => "JSON-RPC message exceeds the byte limit", + Self::InvalidJson => "invalid JSON", + Self::BatchTooLarge => "JSON-RPC batch exceeds the item limit", + }) + } +} +impl std::error::Error for ParseError {} + +/// Error reading a newline-delimited message. After `TooLong`, close or otherwise discard the +/// remaining input line before reading another message. +#[derive(Debug)] +pub enum LineError { + Io(std::io::Error), + TooLong, +} + +impl std::fmt::Display for LineError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(error) => write!(f, "message read failed: {error}"), + Self::TooLong => f.write_str("message exceeds the byte limit"), + } + } +} +impl std::error::Error for LineError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + Self::TooLong => None, + } + } +} + +/// Read at most `max_bytes` before a newline, without allocating for an oversized line. The +/// newline is consumed but omitted from the returned bytes. EOF with no bytes returns `None`; +/// an empty line returns `Some(Vec::new())`. +pub fn read_line(reader: &mut R, max_bytes: usize) -> Result>, LineError> { + let mut line = Vec::new(); + loop { + let bytes = reader.fill_buf().map_err(LineError::Io)?; + if bytes.is_empty() { + return Ok((!line.is_empty()).then_some(line)); + } + let newline = bytes.iter().position(|&byte| byte == b'\n'); + let len = newline.unwrap_or(bytes.len()); + if line.len().saturating_add(len) > max_bytes { + return Err(LineError::TooLong); + } + line.extend_from_slice(&bytes[..len]); + reader.consume(len + usize::from(newline.is_some())); + if newline.is_some() { + return Ok(Some(line)); + } + } +} + +/// Parse JSON after checking its byte length. `serde_json` also bounds nesting depth. +pub fn parse_json(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.max_message_bytes { + return Err(ParseError::MessageTooLarge); + } + serde_json::from_slice(bytes).map_err(|_| ParseError::InvalidJson) +} + +/// A validated request or notification. A present null `id` is distinct from an omitted `id`. +#[derive(Clone, Copy, Debug)] +pub struct Request<'a> { + pub id: Option<&'a Value>, + pub method: &'a str, + pub params: Option<&'a Value>, +} + +/// Inspect a single request envelope. This validates its JSON-RPC version, method and ID; +/// [`process`] additionally validates parameter shape before dispatching it. +pub fn request(value: &Value, limits: Limits) -> Option> { + let object = value.as_object()?; + let id = object.get("id"); + let valid_id = id.is_none_or(|v| { + (v.is_null() && limits.allow_null_ids) || v.is_string() || if limits.integer_ids_only { v.is_i64() || v.is_u64() } else { v.is_number() } + }); + if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || !valid_id { + return None; + } + Some(Request { id, method: object.get("method")?.as_str()?, params: object.get("params") }) +} + +/// A JSON-RPC error returned by a method handler. +#[derive(Clone, Debug, PartialEq)] +pub struct RpcError { + pub code: i64, + pub message: String, + pub data: Option, +} + +impl RpcError { + pub fn new(code: i64, message: impl Into) -> Self { + Self { code, message: message.into(), data: None } + } +} + +/// Build an error response, including optional error data. +pub fn error_response(id: Value, error: RpcError) -> Value { + let mut detail = json!({"code": error.code, "message": error.message}); + if let (Some(data), Some(object)) = (error.data, detail.as_object_mut()) { + object.insert("data".into(), data); + } + json!({"jsonrpc": "2.0", "id": id, "error": detail}) +} + +/// Build the standard parse-error response for input that is not JSON. +pub fn parse_error_response() -> Value { + error_response(Value::Null, RpcError::new(-32700, "Parse error")) +} + +fn invalid_request() -> Value { + error_response(Value::Null, RpcError::new(-32600, "Invalid Request")) +} + +fn one(value: &Value, limits: Limits, on_request: &mut F, on_notification: &mut N) -> Option +where + F: FnMut(Request<'_>) -> Result, + N: FnMut(Request<'_>), +{ + let Some(request) = request(value, limits) else { return Some(invalid_request()) }; + let id = request.id; + if request.params.is_some_and(|v| !v.is_object() && !v.is_array()) { + return id.map(|id| error_response(id.clone(), RpcError::new(-32602, "Invalid params"))); + } + let Some(id) = id else { + on_notification(request); + return None; + }; + Some(match on_request(request) { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err(error) => error_response(id.clone(), error), + }) +} + +/// Process a parsed JSON-RPC message. Notifications never receive a response. Invalid batch +/// entries produce individual errors; an empty batch produces one invalid-request response. +/// A batch over the limit returns [`ParseError::BatchTooLarge`] without invoking either callback. +pub fn process(value: &Value, limits: Limits, mut on_request: F, mut on_notification: N) -> Result, ParseError> +where + F: FnMut(Request<'_>) -> Result, + N: FnMut(Request<'_>), +{ + let Some(batch) = value.as_array() else { return Ok(one(value, limits, &mut on_request, &mut on_notification)) }; + if batch.len() > limits.max_batch_items { + return Err(ParseError::BatchTooLarge); + } + if batch.is_empty() { + return Ok(Some(invalid_request())); + } + let responses: Vec<_> = batch.iter().filter_map(|v| one(v, limits, &mut on_request, &mut on_notification)).collect(); + Ok((!responses.is_empty()).then_some(Value::Array(responses))) +} diff --git a/crates/jsonrpc/tests/server.rs b/crates/jsonrpc/tests/server.rs new file mode 100644 index 0000000000..a9186f4ae8 --- /dev/null +++ b/crates/jsonrpc/tests/server.rs @@ -0,0 +1,172 @@ +use craft_jsonrpc::{Limits, ParseError, RpcError, parse_error_response, parse_json, process}; +use serde_json::{Value, json}; + +#[test] +fn batches_preserve_ids_order_and_suppress_notification_replies() { + let input = json!([ + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": "a", "method": "ping"}, + {"jsonrpc": "2.0", "id": 2, "method": "unknown"}, + 17, + {"jsonrpc": "2.0", "id": null, "method": "ping"} + ]); + let mut notifications = Vec::new(); + let result = process( + &input, + Limits::default(), + |request| match request.method { + "ping" => Ok(json!({})), + _ => Err(RpcError::new(-32601, "Method not found")), + }, + |request| notifications.push(request.method.to_owned()), + ) + .unwrap() + .unwrap(); + assert_eq!(notifications, ["notifications/initialized"]); + assert_eq!( + result, + json!([ + {"jsonrpc":"2.0", "id":"a", "result":{}}, + {"jsonrpc":"2.0", "id":2, "error":{"code":-32601,"message":"Method not found"}}, + {"jsonrpc":"2.0", "id":null, "error":{"code":-32600,"message":"Invalid Request"}}, + {"jsonrpc":"2.0", "id":null, "result":{}} + ]) + ); +} + +#[test] +fn notifications_never_receive_responses_including_all_notification_batches() { + let input = json!([ + {"jsonrpc":"2.0", "method":"tools/call", "params":{"name":"mutating"}}, + {"jsonrpc":"2.0", "method":"notifications/initialized"} + ]); + let mut requests = 0; + let mut notices = 0; + let result = process( + &input, + Limits::default(), + |_| { + requests += 1; + Ok(Value::Null) + }, + |_| notices += 1, + ) + .unwrap(); + assert!(result.is_none()); + assert_eq!(requests, 0); + assert_eq!(notices, 2); +} + +#[test] +fn invalid_envelopes_and_params_return_standard_errors() { + for id in [json!(true), json!([]), json!({})] { + let input = json!({"jsonrpc":"2.0", "id":id, "method":"ping"}); + let reply = process(&input, Limits::default(), |_| panic!("invalid id dispatched"), |_| panic!("invalid id notified")).unwrap().unwrap(); + assert_eq!(reply["id"], Value::Null); + assert_eq!(reply["error"]["code"], -32600); + } + for input in [json!({}), json!({"jsonrpc":"1.0", "id":1, "method":"ping"}), json!({"jsonrpc":"2.0", "id":1}), json!([])] { + let reply = + process(&input, Limits::default(), |_| panic!("invalid request dispatched"), |_| panic!("invalid notification")).unwrap().unwrap(); + assert_eq!(reply["error"]["code"], -32600); + } + let input = json!({"jsonrpc":"2.0", "id":4, "method":"ping", "params":17}); + let reply = process(&input, Limits::default(), |_| panic!("invalid params dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], 4); + assert_eq!(reply["error"]["code"], -32602); + let notification = json!({"jsonrpc":"2.0", "method":"notice", "params":17}); + assert!(process(¬ification, Limits::default(), |_| panic!("invalid request"), |_| panic!("invalid notification")).unwrap().is_none()); +} + +#[test] +fn arrays_are_valid_params_and_errors_can_include_data() { + let input = json!({"jsonrpc":"2.0", "id":-7, "method":"test", "params":[1, 2]}); + let reply = process( + &input, + Limits::default(), + |request| { + assert_eq!(request.params, Some(&json!([1, 2]))); + let mut error = RpcError::new(-32000, "failure"); + error.data = Some(json!({"why":"example"})); + Err(error) + }, + |_| {}, + ) + .unwrap() + .unwrap(); + assert_eq!(reply, json!({"jsonrpc":"2.0", "id":-7, "error":{"code":-32000,"message":"failure","data":{"why":"example"}}})); +} + +#[test] +fn parse_and_batch_limits_apply_before_dispatch() { + let limits = Limits { max_message_bytes: 3, max_batch_items: 1, ..Limits::default() }; + assert_eq!(parse_json(b"null", limits), Err(ParseError::MessageTooLarge)); + assert_eq!(parse_json(b"123", limits).unwrap(), json!(123)); + assert_eq!(parse_json(b"{", limits), Err(ParseError::InvalidJson)); + assert_eq!(parse_error_response()["error"]["code"], -32700); + let input = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}, {"jsonrpc":"2.0", "method":"notice"}]); + assert_eq!( + process(&input, limits, |_| panic!("over-limit batch dispatched"), |_| panic!("over-limit batch notified")), + Err(ParseError::BatchTooLarge) + ); + let one = json!([{"jsonrpc":"2.0", "id":1, "method":"ping"}]); + assert_eq!(process(&one, limits, |_| Ok(json!({})), |_| {}).unwrap().unwrap().as_array().unwrap().len(), 1); +} + +#[test] +fn invalid_utf8_and_excessive_nesting_are_rejected() { + assert_eq!(parse_json(&[0xff], Limits::default()), Err(ParseError::InvalidJson)); + let nested = format!("{}0{}", "[".repeat(200), "]".repeat(200)); + assert_eq!(parse_json(nested.as_bytes(), Limits::default()), Err(ParseError::InvalidJson)); +} + +#[test] +fn bounded_line_read_handles_chunks_empty_lines_and_eof() { + use std::io::{BufReader, Cursor}; + let mut reader = BufReader::with_capacity(2, Cursor::new(b"abc\n\nxy")); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"abc".to_vec())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(Vec::new())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), Some(b"xy".to_vec())); + assert_eq!(craft_jsonrpc::read_line(&mut reader, 3).unwrap(), None); + let mut too_long = BufReader::with_capacity(2, Cursor::new(b"abcd\n")); + assert!(matches!(craft_jsonrpc::read_line(&mut too_long, 3), Err(craft_jsonrpc::LineError::TooLong))); +} + +#[test] +fn bounded_line_read_propagates_io_errors() { + struct Broken; + impl std::io::Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(std::io::Error::other("broken")) + } + } + let mut reader = std::io::BufReader::new(Broken); + assert!(matches!(craft_jsonrpc::read_line(&mut reader, 1), Err(craft_jsonrpc::LineError::Io(_)))); +} + +#[test] +fn inspect_single_request_distinguishes_null_ids_and_invalid_envelopes() { + let request = json!({"jsonrpc":"2.0", "id":null, "method":"ping"}); + let parsed = craft_jsonrpc::request(&request, Limits::default()).unwrap(); + assert_eq!(parsed.id, Some(&Value::Null)); + assert_eq!(parsed.method, "ping"); + let notification = json!({"jsonrpc":"2.0", "method":"ping"}); + assert!(craft_jsonrpc::request(¬ification, Limits::default()).unwrap().id.is_none()); + assert!(craft_jsonrpc::request(&json!({"jsonrpc":"2.0", "id":false, "method":"ping"}), Limits::default()).is_none()); + assert!(craft_jsonrpc::request(&json!({"method":"ping"}), Limits::default()).is_none()); +} + +#[test] +fn numeric_ids_follow_the_selected_protocol_policy() { + let input = json!({"jsonrpc":"2.0", "id":1.5, "method":"ping"}); + let reply = process(&input, Limits::default(), |_| Ok(json!({})), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], json!(1.5)); + let strict = Limits { integer_ids_only: true, ..Limits::default() }; + let reply = process(&input, strict, |_| panic!("fractional ID dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["id"], Value::Null); + assert_eq!(reply["error"]["code"], -32600); + let no_null = Limits { allow_null_ids: false, ..strict }; + let null_id = json!({"jsonrpc":"2.0", "id":null, "method":"ping"}); + let reply = process(&null_id, no_null, |_| panic!("null ID dispatched"), |_| {}).unwrap().unwrap(); + assert_eq!(reply["error"]["code"], -32600); +} diff --git a/crates/materialx/src/lib.rs b/crates/materialx/src/lib.rs index 72afc8ca19..99701366f9 100644 --- a/crates/materialx/src/lib.rs +++ b/crates/materialx/src/lib.rs @@ -327,7 +327,13 @@ impl Document { .and_then(|i| i.attr("nodename")) .and_then(|n| nodes.get(n).copied()) .and_then(|d| d.children("input").find(|i| i.attr("name") == Some("displacement"))) - .and_then(|i| resolve_value(&self.root, i, None, &nodes, &outputs, 0, &mut warnings).map(|f| f.value)); + .and_then(|i| resolve_value(&self.root, i, None, &nodes, &outputs, 0, &mut warnings)) + .map(|found| { + if tiling.is_none() { + tiling = found.tiling; + } + found.value + }); Ok(Material { name: mat.attr("name").unwrap_or("Material").to_owned(), shader: kind, @@ -552,6 +558,19 @@ mod tests { assert!(matches!(Document::parse(&vec![b' '; MAX_BYTES + 1]), Err(Error::Xml(XmlError::TooLarge(_))))); } + #[test] + fn displacement_image_supplies_tiling_when_surface_inputs_do_not() { + let xml = br#" + + + + + "#; + let material = Document::parse(xml).unwrap().read_material(None).unwrap(); + assert_eq!(material.displacement, Some(Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn resolves_openpbr_values_images_graphs_and_displacement() { let doc = Document::parse(br#" diff --git a/crates/mcmat/Cargo.toml b/crates/mcmat/Cargo.toml new file mode 100644 index 0000000000..ee3a186261 --- /dev/null +++ b/crates/mcmat/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-mcmat" +description = "Bounded portable material archive interchange for Craft applications" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-zip = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md new file mode 100644 index 0000000000..074a0ac447 --- /dev/null +++ b/crates/mcmat/README.md @@ -0,0 +1,17 @@ +# craft-mcmat + +A bounded reader and writer for portable MaterialCraft `.mcmat` ZIP packages. A package +contains `material.json`, named texture maps and a source package. Applications interpret +parameter values and cook or render maps themselves; this crate does not depend on an app's +model. It supports callers that read either version 1 or version 2 of the manifest, or both. + +`is_material` checks for a manifest with a bounded ZIP index; `Material::open` takes caller-provided version, entry-count, map-count, per-entry and total +expanded-byte limits. Each subsequent `read` and `read_source` shares that budget, including +repeated references to the same ZIP member. Duplicate member names are refused. The manifest +preserves unknown fields at the top level and on maps; parameter, input and preset objects are +kept as JSON values so their unknown fields survive too. `write` preserves the caller's source +entry name and map names, and rejects duplicate archive member names through `craft-zip`. + +The source package is opaque. Version 1 commonly names `source.mcraft`; MaterialCraft's version 2 +writer names `source.sbs`. Callers that invoke another application must preserve the source's +format and extension rather than infer it from `.mcmat` alone. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs new file mode 100644 index 0000000000..75b8709ef3 --- /dev/null +++ b/crates/mcmat/src/lib.rs @@ -0,0 +1,216 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Bounded interchange for MaterialCraft portable materials (`.mcmat`). +//! +//! The manifest and its version belong to the format, while interpreting parameter values, +//! cooking maps and opening the source package belong to the caller. Unknown fields survive +//! deserialization and serialization, including fields added by later versions. + +use std::collections::BTreeMap; + +use craft_zip::{Archive, Compression, Writer}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const FORMAT: &str = "craft-material"; +pub const MANIFEST_ENTRY: &str = "material.json"; + +/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Manifest { + pub format: String, + pub version: u32, + pub name: String, + pub graph: String, + pub size: [u32; 2], + pub maps: Vec, + #[serde(default)] + pub parameters: Vec, + #[serde(default)] + pub inputs: Vec, + #[serde(default)] + pub presets: Vec, + pub source: String, + #[serde(flatten)] + pub extra: BTreeMap, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MapEntry { + pub usage: String, + pub file: String, + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// All limits are supplied by the consumer, including the versions it understands. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub min_version: u32, + pub max_version: u32, + pub max_entries: u64, + pub max_maps: usize, + pub max_manifest_bytes: u64, + pub max_entry_bytes: u64, + pub max_total_bytes: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid portable material: {0}")] + Invalid(String), + #[error("unsupported portable material version {0}")] + Version(u32), + #[error("portable material limit: {0}")] + Limit(String), + #[error("portable material archive: {0}")] + Archive(#[from] craft_zip::Error), +} + +/// Whether a bounded ZIP index contains a material manifest. This does not validate the manifest. +pub fn is_material(bytes: &[u8], max_entries: u64) -> bool { + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }) + .is_ok_and(|archive| !archive.has_duplicate_names() && archive.contains(MANIFEST_ENTRY)) +} + +/// Manifest and original archive, retaining one shared expanded-byte budget across reads. +pub struct Material<'a> { + pub manifest: Manifest, + archive: Archive<'a>, + max_entry_bytes: u64, +} + +impl<'a> Material<'a> { + pub fn open(bytes: &'a [u8], limits: Limits) -> Result { + let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; + if archive.has_duplicate_names() { + return Err(Error::Invalid("duplicate archive entries".into())); + } + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("material.json is missing".into()))?; + let manifest: Manifest = serde_json::from_slice(&json).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; + if manifest.format != FORMAT { + return Err(Error::Invalid(format!("format `{}`", manifest.format))); + } + if !(limits.min_version..=limits.max_version).contains(&manifest.version) { + return Err(Error::Version(manifest.version)); + } + if manifest.maps.len() > limits.max_maps { + return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + } + Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) + } + + /// Read one named member, charging it to the same budget as previous reads. + pub fn read(&mut self, name: &str) -> Result, Error> { + self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) + } + + pub fn read_source(&mut self) -> Result, Error> { + self.read(&self.manifest.source.clone()) + } +} + +/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. +pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result, Error> { + // Flattened fields must not serialize a second copy of a known key. + const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; + if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) + || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) + { + return Err(Error::Invalid("an extra field duplicates a known field".into())); + } + let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; + let mut writer = Writer::new(); + writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; + for (name, bytes) in maps { + writer.add(name, bytes, Compression::Stored)?; + } + writer.add(&manifest.source, source, Compression::Stored)?; + Ok(writer.finish()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn limits() -> Limits { + Limits { + min_version: 1, + max_version: 2, + max_entries: 100, + max_maps: 4, + max_manifest_bytes: 4096, + max_entry_bytes: 100, + max_total_bytes: 8192, + } + } + + fn sample(version: u32) -> Manifest { + serde_json::from_value(serde_json::json!({ + "format": "craft-material", "version": version, "name": "Stone", "graph": "Stone", "size": [64, 64], + "maps": [{"usage": "baseColor", "file": "maps/base.png", "colorSpace": "srgb", "futureMap": true}], + "parameters": [{"id": "rough", "value": {"t": "float", "v": 0.25}, "futureParam": 42}], + "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [], + "source": if version == 1 { "source.mcraft" } else { "source.sbs" }, "futureField": {"keep": true} + })) + .unwrap() + } + + #[test] + fn both_protocol_versions_keep_unknown_fields_and_payloads() { + for version in [1, 2] { + let manifest = sample(version); + let bytes = write(&manifest, &[("maps/base.png".into(), vec![1, 2, 3])], b"source").unwrap(); + assert!(is_material(&bytes, 100)); + assert!(!is_material(&bytes, 1)); + let mut material = Material::open(&bytes, limits()).unwrap(); + assert_eq!(material.manifest, manifest); + assert_eq!(material.read("maps/base.png").unwrap(), [1, 2, 3]); + assert_eq!(material.read_source().unwrap(), b"source"); + let json = serde_json::to_value(&material.manifest).unwrap(); + assert_eq!(json["futureField"]["keep"], true); + assert_eq!(json["maps"][0]["futureMap"], true); + assert_eq!(json["parameters"][0]["futureParam"], 42); + } + } + + #[test] + fn limits_apply_to_the_manifest_maps_and_aggregate_reads() { + let manifest = sample(2); + let bytes = write(&manifest, &[("maps/base.png".into(), vec![1; 8])], &[2; 8]).unwrap(); + let mut unsupported = limits(); + unsupported.max_version = 1; + assert!(matches!(Material::open(&bytes, unsupported), Err(Error::Version(2)))); + let mut no_maps = limits(); + no_maps.max_maps = 0; + assert!(matches!(Material::open(&bytes, no_maps), Err(Error::Limit(_)))); + let mut tiny_entry = limits(); + tiny_entry.max_entry_bytes = 7; + assert!(Material::open(&bytes, tiny_entry).unwrap().read("maps/base.png").is_err()); + let json_len = serde_json::to_vec_pretty(&manifest).unwrap().len() as u64; + let mut aggregate = limits(); + aggregate.max_total_bytes = json_len + 15; + let mut material = Material::open(&bytes, aggregate).unwrap(); + assert_eq!(material.read("maps/base.png").unwrap().len(), 8); + assert!(material.read_source().is_err()); + } + + #[test] + fn refuses_extra_fields_that_duplicate_known_keys() { + let mut manifest = sample(2); + manifest.extra.insert("version".into(), 3.into()); + assert!(write(&manifest, &[], b"source").is_err()); + manifest.extra.remove("version"); + manifest.maps[0].extra.insert("file".into(), "other".into()); + assert!(write(&manifest, &[], b"source").is_err()); + } + + #[test] + fn refuses_duplicate_names_on_write() { + let manifest = sample(2); + let duplicate = [("maps/base.png".to_string(), vec![1]), ("maps/base.png".to_string(), vec![2])]; + assert!(write(&manifest, &duplicate, b"source").is_err()); + } +} diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml new file mode 100644 index 0000000000..9aeb746d99 --- /dev/null +++ b/crates/mcp/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-mcp" +description = "Transport-independent MCP server initialization and tool envelopes" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-jsonrpc = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/mcp/README.md b/crates/mcp/README.md new file mode 100644 index 0000000000..e84a1a40c5 --- /dev/null +++ b/crates/mcp/README.md @@ -0,0 +1,17 @@ +# craft-mcp + +Transport-independent MCP 2025-03-26 server initialization and tool result helpers. +Use one `Session` per client connection with `craft-jsonrpc` for message parsing and +batch dispatch. The caller owns transport, tool definitions and execution, response +size limits, and shutdown. Pass the outer envelope's batch status to `Session::request`. + +`Policy::Compatible` retains existing permissive clients: tool calls can precede +initialization, initialization can occur in a batch, and client information needs only +to be an object. `Policy::Strict` requires initialization first (except ping), +rejects batched or repeated initialization, and requires client name and version. +Both respond with the sole supported version, 2025-03-26, even if the client offered +a different version. An initialized notification moves the session to `Ready`. +This crate does not enforce every MCP lifecycle or capability rule; applications +must validate any additional requirements they depend on. + +See the [MCP lifecycle specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle). diff --git a/crates/mcp/src/lib.rs b/crates/mcp/src/lib.rs new file mode 100644 index 0000000000..96cfdc7ae9 --- /dev/null +++ b/crates/mcp/src/lib.rs @@ -0,0 +1,207 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! MCP 2025-03-26 server initialization and tool envelopes, independent of transport and tools. +//! The caller owns routing, transport and JSON-RPC batching. Compatibility mode preserves servers +//! that accepted calls before initialization and initialize in a batch; strict mode enforces the +//! initialization ordering and batch prohibition. Create one session per connection. + +use craft_jsonrpc::{Request, RpcError}; +use serde_json::{Value, json}; + +pub const PROTOCOL_VERSION: &str = "2025-03-26"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Policy { + /// Preserve existing permissive servers, including minimal client information. + #[default] + Compatible, + /// Enforce the initialize request and client identity required by MCP. + Strict, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum State { + #[default] + New, + AwaitingInitialized, + Ready, +} + +/// State for one connection. Unknown requests are left to the caller's router. +pub struct Session { + name: String, + version: String, + policy: Policy, + state: State, + capabilities: Value, +} + +impl Session { + pub fn new(name: impl Into, version: impl Into, policy: Policy) -> Self { + Self { name: name.into(), version: version.into(), policy, state: State::New, capabilities: json!({"tools": {}}) } + } + + /// Set the server capabilities returned at initialization. The value must be an object. + pub fn with_capabilities(mut self, capabilities: Value) -> Result { + if !capabilities.is_object() { + return Err(RpcError::new(-32602, "Capabilities must be an object")); + } + self.capabilities = capabilities; + Ok(self) + } + + pub fn state(&self) -> State { + self.state + } + + /// Handles `initialize` and `ping`. Returns `None` for a request the app should route. + /// `in_batch` must describe the outer JSON-RPC envelope. + pub fn request(&mut self, request: Request<'_>, in_batch: bool) -> Option> { + if request.method == "ping" { + return Some(Ok(json!({}))); + } + if request.method == "initialize" { + if self.policy == Policy::Strict && (in_batch || self.state != State::New) { + return Some(Err(RpcError::new(-32600, "Invalid Request"))); + } + let Some(params) = request.params.and_then(Value::as_object) else { + return Some(Err(invalid_initialize())); + }; + let valid = params.get("protocolVersion").and_then(Value::as_str).is_some() + && params.get("capabilities").is_some_and(Value::is_object) + && params.get("clientInfo").is_some_and(Value::is_object); + let identity = params.get("clientInfo").and_then(Value::as_object); + let strict_identity = identity + .is_some_and(|info| info.get("name").and_then(Value::as_str).is_some() && info.get("version").and_then(Value::as_str).is_some()); + if !valid || (self.policy == Policy::Strict && !strict_identity) { + return Some(Err(invalid_initialize())); + } + self.state = State::AwaitingInitialized; + return Some(Ok( + json!({"protocolVersion": PROTOCOL_VERSION, "capabilities": self.capabilities, "serverInfo": {"name": self.name, "version": self.version}}), + )); + } + if self.policy == Policy::Strict && self.state == State::New { + return Some(Err(RpcError::new(-32600, "Server not initialized"))); + } + None + } + + /// Observe a JSON-RPC notification; notifications never receive replies. + pub fn notification(&mut self, request: Request<'_>) { + if request.method == "notifications/initialized" && self.state == State::AwaitingInitialized { + self.state = State::Ready; + } + } +} + +fn invalid_initialize() -> RpcError { + RpcError::new(-32602, "Invalid initialize parameters") +} + +/// Validate MCP tool-call parameters without owning the application's tool routing. +pub fn tool_call(params: &Value) -> Result<(&str, Value), RpcError> { + let name = params.get("name").and_then(Value::as_str).ok_or_else(|| RpcError::new(-32602, "Missing tool name"))?; + let arguments = params.get("arguments").cloned().unwrap_or_else(|| json!({})); + if !arguments.is_object() { + return Err(RpcError::new(-32602, "Tool arguments must be an object")); + } + Ok((name, arguments)) +} + +/// Wrap an application-provided tool list in the MCP result envelope. +pub fn tool_list(tools: Value) -> Value { + json!({"tools": tools}) +} + +/// Construct the text result currently used by Craft's MCP tools. +pub fn text_tool_result(text: &str, is_error: bool) -> Value { + json!({"content": [{"type": "text", "text": text}], "isError": is_error}) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call<'a>(method: &'a str, params: Option<&'a Value>) -> Request<'a> { + Request { id: None, method, params } + } + + #[test] + fn compatible_negotiation_preserves_existing_clients() { + let mut s = Session::new("test", "1", Policy::Compatible); + assert!(s.request(call("tools/list", None), false).is_none()); + let p = json!({"protocolVersion":"old", "capabilities":{}, "clientInfo":{}}); + let r = s.request(call("initialize", Some(&p)), true).unwrap().unwrap(); + assert_eq!(r["protocolVersion"], PROTOCOL_VERSION); + assert_eq!(r["serverInfo"]["name"], "test"); + assert_eq!(s.state(), State::AwaitingInitialized); + s.notification(call("notifications/initialized", None)); + assert_eq!(s.state(), State::Ready); + } + + #[test] + fn strict_rejects_batch_and_calls_before_initialization() { + let mut s = Session::new("test", "1", Policy::Strict); + assert_eq!(s.request(call("tools/list", None), false).unwrap().unwrap_err().code, -32600); + assert!(s.request(call("ping", None), false).unwrap().is_ok()); + let p = json!({"protocolVersion":PROTOCOL_VERSION, "capabilities":{}, "clientInfo":{"name":"client", "version":"1"}}); + assert!(s.request(call("initialize", Some(&p)), true).unwrap().is_err()); + assert_eq!(s.state(), State::New); + assert!(s.request(call("initialize", Some(&p)), false).unwrap().is_ok()); + assert!(s.request(call("initialize", Some(&p)), false).unwrap().is_err()); + s.notification(call("notifications/initialized", None)); + assert_eq!(s.state(), State::Ready); + } + + #[test] + fn capabilities_are_configurable_and_must_be_an_object() { + assert!(Session::new("test", "1", Policy::Compatible).with_capabilities(json!([])).is_err()); + let mut session = Session::new("test", "1", Policy::Compatible).with_capabilities(json!({"resources": {"subscribe": true}})).unwrap(); + let params = json!({"protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {}}); + let result = session.request(call("initialize", Some(¶ms)), false).unwrap().unwrap(); + assert_eq!(result["capabilities"], json!({"resources": {"subscribe": true}})); + } + + #[test] + fn malformed_initialize_does_not_change_state() { + let mut s = Session::new("test", "1", Policy::Strict); + for p in [json!({}), json!({"protocolVersion":"x", "capabilities":{}, "clientInfo":{}})] { + assert_eq!(s.request(call("initialize", Some(&p)), false).unwrap().unwrap_err().code, -32602); + assert_eq!(s.state(), State::New); + } + } + + #[test] + fn tool_envelopes_validate_arguments_and_preserve_results() { + let p = json!({"name":"open"}); + assert_eq!(tool_call(&p).unwrap(), ("open", json!({}))); + assert_eq!(tool_call(&json!({"name":"open", "arguments":[]})).unwrap_err().code, -32602); + assert_eq!(tool_call(&json!({})).unwrap_err().code, -32602); + assert_eq!(text_tool_result("bad", true), json!({"content":[{"type":"text", "text":"bad"}], "isError":true})); + } + + #[test] + fn jsonrpc_batch_preserves_ids_and_skips_notifications() { + use std::cell::RefCell; + let session = RefCell::new(Session::new("test", "1", Policy::Compatible)); + let input = json!([ + {"jsonrpc":"2.0", "id":1, "method":"initialize", "params":{"protocolVersion":"2025-03-26", "capabilities":{}, "clientInfo":{}}}, + {"jsonrpc":"2.0", "method":"notifications/initialized"}, + {"jsonrpc":"2.0", "id":"tools", "method":"tools/list"} + ]); + let reply = craft_jsonrpc::process( + &input, + craft_jsonrpc::Limits::default(), + |r| session.borrow_mut().request(r, true).unwrap_or_else(|| Ok(tool_list(json!([])))), + |r| session.borrow_mut().notification(r), + ) + .unwrap() + .unwrap(); + assert_eq!(reply.as_array().unwrap().len(), 2); + assert_eq!(reply[0]["id"], 1); + assert_eq!(reply[1]["id"], "tools"); + assert_eq!(reply[1]["result"]["tools"], json!([])); + assert_eq!(session.borrow().state(), State::Ready); + } +} diff --git a/crates/metadata/src/camera_fields.rs b/crates/metadata/src/camera_fields.rs new file mode 100644 index 0000000000..ade8357363 --- /dev/null +++ b/crates/metadata/src/camera_fields.rs @@ -0,0 +1,445 @@ +//! Unnormalized camera-field EXIF view, reused from PhotoCraft (exposure, aperture, +//! ISO, focal length, camera and lens names). Input is the raw TIFF-structured EXIF payload +//! (`II*\0` / `MM\0*`, as stored in `Document.metadata.exif`); malformed data yields `None` +//! fields, never a panic. Tag numbers are from the EXIF 2.32 specification (CIPA DC-008). + +// Semantics originate in PhotoCraft, including Brandon Thomas and Fabio Lussi. +// Unlike read_exif this view does not normalize dates or derive missing fields. +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +/// Camera settings read from EXIF. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CameraInfo { + pub make: Option, + pub model: Option, + pub lens: Option, + /// Seconds. + pub exposure_time: Option, + pub f_number: Option, + pub iso: Option, + /// Millimetres. + pub focal_length: Option, + /// 35 mm-equivalent focal length in millimetres. + pub focal_length_35mm: Option, + /// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`). + pub date_taken: Option, +} + +impl CameraInfo { + /// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene). + pub fn exposure_factor(&self) -> Option { + let t = self.exposure_time?; + let n = self.f_number.unwrap_or(1.0).max(0.1); + Some(t * self.iso.unwrap_or(100.0) / 100.0 / (n * n)) + } +} + +/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes). +const MAX_TEXT_BYTES: usize = 1 << 20; + +struct Tiff<'a> { + b: &'a [u8], + order: craft_tiff::ByteOrder, + /// Text bytes this read may still decode: duplicate tags can share one large blank value. + text_left: std::cell::Cell, +} + +impl Tiff<'_> { + fn u16(&self, o: usize) -> Option { + self.order.read_u16(self.b, o) + } + fn u32(&self, o: usize) -> Option { + self.order.read_u32(self.b, o) + } + /// Entries of the IFD at `off`: (tag, type, count, value offset field position). + fn ifd(&self, off: usize) -> Vec<(u16, u16, u32, usize)> { + let Some(n) = self.u16(off) else { return Vec::new() }; + (0..n as usize) + .filter_map(|k| { + // Checked: offsets come from the file, and usize is 32 bits on wasm. + let e = off.checked_add(2)?.checked_add(k * 12)?; + Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?)) + }) + .collect() + } + fn data_at(&self, typ: u16, _count: u32, field: usize) -> Option { + // Keep this caller's historical classic-TIFF type policy; shared spans also + // support IFD/BigTIFF types which CameraInfo never accepted. + if !(1..=12).contains(&typ) { + return None; + } + let span = craft_tiff::entry_span(self.b, field.checked_sub(8)?, self.order, false, 0)?; + usize::try_from(span.start).ok() + } + fn number(&self, typ: u16, count: u32, field: usize) -> Option { + let at = self.data_at(typ, count, field)?; + match typ { + 3 => self.u16(at).map(f64::from), + 4 => self.u32(at).map(f64::from), + 5 => { + let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + } + 10 => { + let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32); + (d != 0).then(|| n as f64 / d as f64) + } + _ => None, + } + } + fn text(&self, typ: u16, count: u32, field: usize) -> Option { + #[cfg(test)] + TEXT_DECODES.with(|c| c.set(c.get() + 1)); + if typ != 2 { + return None; + } + let at = self.data_at(typ, count, field)?; + let n = usize::try_from(count).ok()?; + self.text_left.set(self.text_left.get().checked_sub(n)?); + let s = self.b.get(at..at.checked_add(n)?)?; + let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string(); + (!s.is_empty()).then_some(s) + } +} + +#[cfg(test)] +thread_local!(static TEXT_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }); + +/// Reads [`CameraInfo`] from a TIFF-structured EXIF payload (an `Exif\0\0` prefix is skipped). +pub fn read(exif: &[u8]) -> CameraInfo { + let b = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + let mut info = CameraInfo::default(); + let le = match b.get(..4) { + Some([b'I', b'I', 42, 0]) => true, + Some([b'M', b'M', 0, 42]) => false, + _ => return info, + }; + let t = Tiff { + b, + order: if le { craft_tiff::ByteOrder::Little } else { craft_tiff::ByteOrder::Big }, + text_left: std::cell::Cell::new(MAX_TEXT_BYTES), + }; + let Some(ifd0) = t.u32(4) else { return info }; + let mut queue = vec![ifd0 as usize]; + let mut seen = Vec::new(); + while let Some(off) = queue.pop() { + if seen.contains(&off) || seen.len() > 8 { + continue; + } + seen.push(off); + for (tag, typ, count, field) in t.ifd(off) { + match tag { + // Duplicate TIFF text tags can point at the same large payload. Keep the first + // recognized value and do not repeatedly decode/copy later duplicates. + 0x010F if info.make.is_none() => info.make = t.text(typ, count, field), + 0x0110 if info.model.is_none() => info.model = t.text(typ, count, field), + 0x829A => info.exposure_time = t.number(typ, count, field), + 0x829D => info.f_number = t.number(typ, count, field), + 0x8827 => info.iso = t.number(typ, count, field), + 0x920A => info.focal_length = t.number(typ, count, field), + 0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0), + 0xA434 if info.lens.is_none() => info.lens = t.text(typ, count, field), + 0x9003 if info.date_taken.is_none() => info.date_taken = t.text(typ, count, field), + 0x8769 => { + if let Some(p) = t.u32(field) { + queue.push(p as usize); + } + } + _ => {} + } + } + } + info +} + +/// Build a classic TIFF EXIF block using the shared TIFF writer. +/// Raw date strings and numeric rounding match the camera-field view. Text is +/// bounded to the reader's 1 MiB aggregate budget; oversized inputs return an error. +/// Physical directory placement is not part of this API's contract. +pub fn try_build(info: &CameraInfo) -> craft_tiff::Result> { + use craft_tiff::{ByteOrder, IfdBuilder, TiffError, TiffWriter, Value}; + let total = + [&info.make, &info.model, &info.lens, &info.date_taken].into_iter().flatten().try_fold(0usize, |n, s| n.checked_add(s.len())?.checked_add(1)); + if total.is_none_or(|n| n > MAX_TEXT_BYTES) { + return Err(TiffError::Limit("camera EXIF text")); + } + let mut root = IfdBuilder::new(); + let mut exif = IfdBuilder::new(); + for (tag, value) in [(0x010f, &info.make), (0x0110, &info.model)] { + if let Some(value) = value { + root.set(tag, Value::Ascii(value.clone())); + } + } + for (tag, value) in [(0x9003, &info.date_taken), (0xa434, &info.lens)] { + if let Some(value) = value { + exif.set(tag, Value::Ascii(value.clone())); + } + } + for (tag, value) in [(0x829a, info.exposure_time), (0x829d, info.f_number), (0x920a, info.focal_length)] { + if let Some(value) = value { + exif.set(tag, Value::Rational(vec![((value * 10000.0).round() as u32, 10000)])); + } + } + for (tag, value) in [(0x8827, info.iso), (0xa405, info.focal_length_35mm)] { + if let Some(value) = value { + exif.set(tag, Value::Short(vec![value as u16])); + } + } + // Empty child IFDs are valid here; the reader yields absent fields. + root.set_child(0x8769, exif); + TiffWriter::new(ByteOrder::Little, false).write(&[root]) +} + +#[cfg(test)] +fn build(info: &CameraInfo) -> Vec { + try_build(info).unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trips_and_survives_garbage() { + let info = CameraInfo { + make: Some("Generic".into()), + model: Some("Camera 1".into()), + lens: Some("24-70mm".into()), + exposure_time: Some(0.004), + f_number: Some(8.0), + iso: Some(200.0), + focal_length: Some(35.0), + focal_length_35mm: Some(52.0), + date_taken: Some("2024:02:17 12:40:19".into()), + }; + let b = build(&info); + let r = read(&b); + assert_eq!(r, info); + assert!((r.exposure_factor().unwrap() - 0.004 * 2.0 / 64.0).abs() < 1e-9); + let mut prefixed = b"Exif\0\0".to_vec(); + prefixed.extend_from_slice(&b); + assert_eq!(read(&prefixed), info); + assert_eq!(read(b"nonsense"), CameraInfo::default()); + for cut in [5, 12, 30, b.len() - 3] { + let _ = read(&b[..cut]); + } + } + + /// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random + /// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm). + #[test] + fn blank_duplicate_text_tags_share_one_decode_budget() { + // Blank values never fill `make`, so every duplicate would decode the same 1 MiB again; + // the per-read budget stops after the first, so the later real value is not reached. + let blank = MAX_TEXT_BYTES; + let entry = |count: u32, off: u32| { + let mut e = Vec::new(); + e.extend_from_slice(&0x010Fu16.to_le_bytes()); + e.extend_from_slice(&2u16.to_le_bytes()); + e.extend_from_slice(&count.to_le_bytes()); + e.extend_from_slice(&off.to_le_bytes()); + e + }; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + b.extend_from_slice(&3u16.to_le_bytes()); + b.extend(entry(blank as u32, 50)); + b.extend(entry(blank as u32, 50)); + b.extend(entry(2, u32::from_le_bytes(*b"M\0\0\0"))); + b.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(b.len(), 50); + b.extend(std::iter::repeat_n(b' ', blank)); + assert_eq!(read(&b).make, None); + } + + #[test] + fn duplicate_text_tags_keep_the_first_value_without_copying_large_duplicates() { + let value = vec![b'X'; 2 * 1024 * 1024]; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + // IFD0: Make="M", a duplicate Make pointing at a 2 MiB payload, and the Exif IFD link. + b.extend_from_slice(&3u16.to_le_bytes()); + b.extend_from_slice(&0x010Fu16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(b"M\0\0\0"); + b.extend_from_slice(&0x010Fu16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&(value.len() as u32).to_le_bytes()); + b.extend_from_slice(&80u32.to_le_bytes()); + b.extend_from_slice(&0x8769u16.to_le_bytes()); + b.extend_from_slice(&4u16.to_le_bytes()); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&50u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + // Exif IFD at 50: DateTimeOriginal="D" and the same large duplicate payload at offset 80. + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&0x9003u16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(b"D\0\0\0"); + b.extend_from_slice(&0x9003u16.to_le_bytes()); + b.extend_from_slice(&2u16.to_le_bytes()); + b.extend_from_slice(&(value.len() as u32).to_le_bytes()); + b.extend_from_slice(&80u32.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + b.extend_from_slice(&value); + + TEXT_DECODES.with(|c| c.set(0)); + let info = read(&b); + assert_eq!(info.make.as_deref(), Some("M")); + assert_eq!(info.date_taken.as_deref(), Some("D")); + // One decode per tag: duplicates must be skipped before `text` copies their payload. + assert_eq!(TEXT_DECODES.with(|c| c.get()), 2); + } + + #[test] + fn hostile_payloads_never_panic() { + let entry = |tag: u16, typ: u16, count: u32, value: u32| { + let mut e = tag.to_le_bytes().to_vec(); + e.extend_from_slice(&typ.to_le_bytes()); + e.extend_from_slice(&count.to_le_bytes()); + e.extend_from_slice(&value.to_le_bytes()); + e + }; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + let entries = [ + entry(0x010F, 2, u32::MAX, 8), // Make: count far past the end + entry(0x0110, 2, 16, u32::MAX - 1), // Model: offset at the top of the range + entry(0x829A, 5, u32::MAX, 20), // ExposureTime: count overflows the size + entry(0x829D, 5, 1, u32::MAX - 3), // FNumber: rational straddles u32::MAX + entry(0x9003, 2, 0x4000_0000, 8), // DateTimeOriginal: size overflow on 32 bits + entry(0x8769, 4, 1, 8), // Exif IFD pointing back at IFD0 + entry(0x8769, 4, 1, u32::MAX), // ... and past the end + ]; + b.extend_from_slice(&(entries.len() as u16 + 3).to_le_bytes()); // claims more entries than exist + for e in entries { + b.extend_from_slice(&e); + } + assert_eq!(read(&b), CameraInfo::default()); + let mut be = b"MM\0*".to_vec(); + be.extend_from_slice(&u32::MAX.to_be_bytes()); + assert_eq!(read(&be), CameraInfo::default()); + // Deterministic noise behind a valid header, and every truncation of a real payload. + let mut x = 0x2545_F491u32; + for _ in 0..200 { + let mut n = b"II*\0\x08\0\0\0".to_vec(); + for _ in 0..96 { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + n.push(x as u8); + } + let _ = read(&n); + } + let good = build(&CameraInfo { + make: Some("Make".into()), + date_taken: Some("2024:02:17 12:40:19".into()), + exposure_time: Some(0.004), + ..Default::default() + }); + for cut in 0..good.len() { + let _ = read(&good[..cut]); + } + } +} + +// Keep the previous byte reader only as a test oracle during the shared-span cutover. +#[cfg(test)] +#[path = "camera_fields_legacy_tests.rs"] +mod legacy; + +#[cfg(test)] +mod shared_span_parity { + use super::*; + + fn compare(bytes: &[u8]) { + assert_eq!(format!("{:?}", read(bytes)), format!("{:?}", legacy::read(bytes))); + } + + #[test] + fn shared_writer_matches_legacy_fields_and_rejects_oversized_text() { + for value in [0.0, -1.0, 0.004, 2.8, 65535.0, f64::INFINITY, f64::NAN] { + let camera = CameraInfo { + exposure_time: Some(value), + f_number: Some(value), + iso: Some(value), + focal_length: Some(value), + focal_length_35mm: Some(value), + date_taken: Some("raw date".into()), + make: Some("M".into()), + model: Some("Model".into()), + lens: Some("Lens".into()), + }; + let old = legacy::CameraInfo { + exposure_time: camera.exposure_time, + f_number: camera.f_number, + iso: camera.iso, + focal_length: camera.focal_length, + focal_length_35mm: camera.focal_length_35mm, + date_taken: camera.date_taken.clone(), + make: camera.make.clone(), + model: camera.model.clone(), + lens: camera.lens.clone(), + }; + let bytes = try_build(&camera).unwrap(); + assert_eq!(format!("{:?}", read(&bytes)), format!("{:?}", legacy::read(&legacy::build(&old)))); + } + assert_eq!(read(&try_build(&CameraInfo::default()).unwrap()), CameraInfo::default()); + assert!(try_build(&CameraInfo { make: Some("x".repeat(MAX_TEXT_BYTES)), ..Default::default() }).is_err()); + assert!(try_build(&CameraInfo { make: Some("x".repeat(MAX_TEXT_BYTES - 1)), ..Default::default() }).is_ok()); + } + + #[test] + fn preserves_camera_selection_for_valid_truncated_and_mutated_payloads() { + let bytes = build(&CameraInfo { + make: Some("Maker".into()), + model: Some("Camera".into()), + lens: Some("Lens".into()), + exposure_time: Some(0.125), + f_number: Some(2.8), + iso: Some(200.0), + focal_length: Some(50.0), + focal_length_35mm: Some(75.0), + date_taken: Some("not normalized: original date".into()), + }); + compare(&bytes); + let mut prefixed = b"Exif\0\0".to_vec(); + prefixed.extend_from_slice(&bytes); + compare(&prefixed); + for end in 0..=bytes.len() { + compare(&bytes[..end]); + } + // Exercise offsets, tags, types, counts and payloads independently, not random + // external data. The complete shared span must remain bounded for every edit. + for index in 0..bytes.len() { + for value in [0, 0xff, 0x80] { + let mut changed = bytes.clone(); + changed[index] = value; + compare(&changed); + } + } + } + + #[test] + fn preserves_partial_entry_and_zero_count_semantics_in_both_orders() { + for little in [true, false] { + let u16b = |v: u16| if little { v.to_le_bytes() } else { v.to_be_bytes() }; + let u32b = |v: u32| if little { v.to_le_bytes() } else { v.to_be_bytes() }; + for count in [0u32, 1, 2, u32::MAX] { + let mut bytes = if little { b"II".to_vec() } else { b"MM".to_vec() }; + bytes.extend(u16b(42)); + bytes.extend(u32b(8)); + bytes.extend(u16b(1)); + bytes.extend(u16b(0x8827)); + bytes.extend(u16b(3)); + bytes.extend(u32b(count)); + bytes.extend(u16b(200)); + compare(&bytes); // two inline bytes, no full 12-byte entry/next pointer + bytes.extend(u16b(0)); + compare(&bytes); + } + } + } +} diff --git a/crates/metadata/src/camera_fields_legacy_tests.rs b/crates/metadata/src/camera_fields_legacy_tests.rs new file mode 100644 index 0000000000..1b560f91f6 --- /dev/null +++ b/crates/metadata/src/camera_fields_legacy_tests.rs @@ -0,0 +1,237 @@ +// Frozen differential oracle: PhotoCraft main abb30dff, exif.rs. Test-only, not a production fallback. +#![allow(dead_code)] +// Minimal EXIF reader for the camera settings the photography commands use (exposure, aperture, +// ISO, focal length, camera and lens names). Input is the raw TIFF-structured EXIF payload +// (`II*\0` / `MM\0*`, as stored in `Document.metadata.exif`); malformed data yields `None` +// fields, never a panic. Tag numbers are from the EXIF 2.32 specification (CIPA DC-008). + +/// Camera settings read from EXIF. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct CameraInfo { + pub make: Option, + pub model: Option, + pub lens: Option, + /// Seconds. + pub exposure_time: Option, + pub f_number: Option, + pub iso: Option, + /// Millimetres. + pub focal_length: Option, + /// 35 mm-equivalent focal length in millimetres. + pub focal_length_35mm: Option, + /// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`). + pub date_taken: Option, +} + +impl CameraInfo { + /// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene). + pub fn exposure_factor(&self) -> Option { + let t = self.exposure_time?; + let n = self.f_number.unwrap_or(1.0).max(0.1); + Some(t * self.iso.unwrap_or(100.0) / 100.0 / (n * n)) + } +} + +/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes). +const MAX_TEXT_BYTES: usize = 1 << 20; + +struct Tiff<'a> { + b: &'a [u8], + le: bool, + /// Text bytes this read may still decode: duplicate tags can share one large blank value. + text_left: std::cell::Cell, +} + +impl Tiff<'_> { + fn u16(&self, o: usize) -> Option { + let s = self.b.get(o..o.checked_add(2)?)?; + Some(if self.le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + } + fn u32(&self, o: usize) -> Option { + let s = self.b.get(o..o.checked_add(4)?)?; + let a = [s[0], s[1], s[2], s[3]]; + Some(if self.le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) }) + } + /// Entries of the IFD at `off`: (tag, type, count, value offset field position). + fn ifd(&self, off: usize) -> Vec<(u16, u16, u32, usize)> { + let Some(n) = self.u16(off) else { return Vec::new() }; + (0..n as usize) + .filter_map(|k| { + // Checked: offsets come from the file, and usize is 32 bits on wasm. + let e = off.checked_add(2)?.checked_add(k * 12)?; + Some((self.u16(e)?, self.u16(e.checked_add(2)?)?, self.u32(e.checked_add(4)?)?, e.checked_add(8)?)) + }) + .collect() + } + fn data_at(&self, typ: u16, count: u32, field: usize) -> Option { + let size = match typ { + 1 | 2 | 6 | 7 => 1usize, + 3 | 8 => 2, + 4 | 9 | 11 => 4, + 5 | 10 | 12 => 8, + _ => return None, + } + .checked_mul(usize::try_from(count).ok()?)?; + let at = if size <= 4 { field } else { usize::try_from(self.u32(field)?).ok()? }; + // The whole value must lie inside the payload, not just its first element. + self.b.get(at..at.checked_add(size)?)?; + Some(at) + } + fn number(&self, typ: u16, count: u32, field: usize) -> Option { + let at = self.data_at(typ, count, field)?; + match typ { + 3 => self.u16(at).map(f64::from), + 4 => self.u32(at).map(f64::from), + 5 => { + let (n, d) = (self.u32(at)?, self.u32(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + } + 10 => { + let (n, d) = (self.u32(at)? as i32, self.u32(at.checked_add(4)?)? as i32); + (d != 0).then(|| n as f64 / d as f64) + } + _ => None, + } + } + fn text(&self, typ: u16, count: u32, field: usize) -> Option { + #[cfg(test)] + TEXT_DECODES.with(|c| c.set(c.get() + 1)); + if typ != 2 { + return None; + } + let at = self.data_at(typ, count, field)?; + let n = usize::try_from(count).ok()?; + self.text_left.set(self.text_left.get().checked_sub(n)?); + let s = self.b.get(at..at.checked_add(n)?)?; + let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string(); + (!s.is_empty()).then_some(s) + } +} + +#[cfg(test)] +thread_local!(static TEXT_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }); + +/// Reads [`CameraInfo`] from a TIFF-structured EXIF payload (an `Exif\0\0` prefix is skipped). +pub fn read(exif: &[u8]) -> CameraInfo { + let b = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + let mut info = CameraInfo::default(); + let le = match b.get(..4) { + Some([b'I', b'I', 42, 0]) => true, + Some([b'M', b'M', 0, 42]) => false, + _ => return info, + }; + let t = Tiff { b, le, text_left: std::cell::Cell::new(MAX_TEXT_BYTES) }; + let Some(ifd0) = t.u32(4) else { return info }; + let mut queue = vec![ifd0 as usize]; + let mut seen = Vec::new(); + while let Some(off) = queue.pop() { + if seen.contains(&off) || seen.len() > 8 { + continue; + } + seen.push(off); + for (tag, typ, count, field) in t.ifd(off) { + match tag { + // Duplicate TIFF text tags can point at the same large payload. Keep the first + // recognized value and do not repeatedly decode/copy later duplicates. + 0x010F if info.make.is_none() => info.make = t.text(typ, count, field), + 0x0110 if info.model.is_none() => info.model = t.text(typ, count, field), + 0x829A => info.exposure_time = t.number(typ, count, field), + 0x829D => info.f_number = t.number(typ, count, field), + 0x8827 => info.iso = t.number(typ, count, field), + 0x920A => info.focal_length = t.number(typ, count, field), + 0xA405 => info.focal_length_35mm = t.number(typ, count, field).filter(|v| *v > 0.0), + 0xA434 if info.lens.is_none() => info.lens = t.text(typ, count, field), + 0x9003 if info.date_taken.is_none() => info.date_taken = t.text(typ, count, field), + 0x8769 => { + if let Some(p) = t.u32(field) { + queue.push(p as usize); + } + } + _ => {} + } + } + } + info +} + +/// Builds a little-endian EXIF payload (used by tests and by synthetic fixtures). +pub fn build(info: &CameraInfo) -> Vec { + // IFD0: Make, Model, ExifIFD pointer; Exif IFD: the rest. Data area after the IFDs. + let mut ifd0: Vec<(u16, u16, u32, Vec)> = Vec::new(); + let mut exif: Vec<(u16, u16, u32, Vec)> = Vec::new(); + let text = |s: &str| { + let mut v = s.as_bytes().to_vec(); + v.push(0); + v + }; + let rational = |v: f64| { + let d = 10000u32; + let mut b = ((v * d as f64).round() as u32).to_le_bytes().to_vec(); + b.extend_from_slice(&d.to_le_bytes()); + b + }; + if let Some(s) = &info.make { + ifd0.push((0x010F, 2, s.len() as u32 + 1, text(s))); + } + if let Some(s) = &info.model { + ifd0.push((0x0110, 2, s.len() as u32 + 1, text(s))); + } + if let Some(v) = info.exposure_time { + exif.push((0x829A, 5, 1, rational(v))); + } + if let Some(v) = info.f_number { + exif.push((0x829D, 5, 1, rational(v))); + } + if let Some(v) = info.iso { + exif.push((0x8827, 3, 1, (v as u16).to_le_bytes().to_vec())); + } + if let Some(s) = &info.date_taken { + exif.push((0x9003, 2, s.len() as u32 + 1, text(s))); + } + if let Some(v) = info.focal_length { + exif.push((0x920A, 5, 1, rational(v))); + } + if let Some(v) = info.focal_length_35mm { + exif.push((0xA405, 3, 1, (v as u16).to_le_bytes().to_vec())); + } + if let Some(s) = &info.lens { + exif.push((0xA434, 2, s.len() as u32 + 1, text(s))); + } + let ifd_len = |n: usize| 2 + 12 * n + 4; + let ifd0_off = 8usize; + let n0 = ifd0.len() + 1; + let exif_off = ifd0_off + ifd_len(n0); + let mut data_off = exif_off + ifd_len(exif.len()); + let mut out = b"II*\0".to_vec(); + out.extend_from_slice(&(ifd0_off as u32).to_le_bytes()); + let mut data = Vec::new(); + let mut write_ifd = |out: &mut Vec, entries: &[(u16, u16, u32, Vec)], extra: Option| { + let n = entries.len() + usize::from(extra.is_some()); + out.extend_from_slice(&(n as u16).to_le_bytes()); + for (tag, typ, count, bytes) in entries { + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&typ.to_le_bytes()); + out.extend_from_slice(&count.to_le_bytes()); + if bytes.len() <= 4 { + let mut f = bytes.clone(); + f.resize(4, 0); + out.extend_from_slice(&f); + } else { + out.extend_from_slice(&(data_off as u32).to_le_bytes()); + data.extend_from_slice(bytes); + data_off += bytes.len(); + } + } + if let Some(p) = extra { + out.extend_from_slice(&0x8769u16.to_le_bytes()); + out.extend_from_slice(&4u16.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); + out.extend_from_slice(&p.to_le_bytes()); + } + out.extend_from_slice(&0u32.to_le_bytes()); + }; + write_ifd(&mut out, &ifd0, Some(exif_off as u32)); + write_ifd(&mut out, &exif, None); + out.extend_from_slice(&data); + out +} diff --git a/crates/metadata/src/cr3.rs b/crates/metadata/src/cr3.rs index a7538e88bb..4ae189a801 100644 --- a/crates/metadata/src/cr3.rs +++ b/crates/metadata/src/cr3.rs @@ -351,28 +351,70 @@ fn trak(bytes: &[u8], t: &BoxRef, budget: &mut usize) -> Option { } } let stbl = stbl?; - let (mut kind, mut size, mut offset) = (None, None, None); + let (mut kind, mut size, mut offset, mut mapping, mut sample_count) = (None, None, None, None, 0); for b in boxes(bytes, stbl.body, stbl.end, budget) { let body = bytes.get(b.body..b.end)?; match &b.kind { // full box: version/flags, entry count, entries b"stsd" if be32(body, 4)? > 0 => kind = boxes(bytes, b.body + 8, b.end, budget).first().map(|e| sample_entry(bytes, e, budget)), + b"stsc" => { + // Only the first sample is exposed. It must map chunk 1 to + // the first sample description; don't trust offsets without + // that mapping, or a damaged/raw track could become a JPEG. + // A malformed mapping invalidates sample data, not the track's + // identity: dropping the largest raw track could select a reduced + // raw successfully and disguise corruption in the main image. + mapping = (|| { + let count = be32(body, 4)? as usize; + if be32(body, 0)? != 0 || count == 0 || count > body.len().saturating_sub(8) / 12 { + return None; + } + Some((be32(body, 8)?, be32(body, 12)?, be32(body, 16)?)) + })(); + } // version/flags, sample_size (0 = per-sample table), count, sizes b"stsz" => { - size = match be32(body, 4)? { - 0 if be32(body, 8)? > 0 => be32(body, 12), - 0 => None, - n if be32(body, 8)? > 0 => Some(n), + // A truncated size table invalidates data without hiding a known track. + sample_count = be32(body, 8).unwrap_or(0); + size = match be32(body, 4) { + // A first entry cannot justify an incomplete per-sample + // table, nor an impossible constant-size sample count. + Some(0) if sample_count > 0 && sample_count as usize <= body.len().saturating_sub(12) / 4 => be32(body, 12), + Some(n) + if n > 0 + && sample_count > 0 + && u64::from(n).checked_mul(u64::from(sample_count)).is_some_and(|total| total <= bytes.len() as u64) => + { + Some(n) + } _ => None, } } - b"co64" if be32(body, 4)? > 0 => offset = be64(body, 8).and_then(|v| usize::try_from(v).ok()), - b"stco" if be32(body, 4)? > 0 => offset = be32(body, 8).map(|v| v as usize), + // Missing or truncated offset-table counts deny sample access, but the known + // track must remain available to the largest-raw-track selector. + b"co64" => { + offset = match be32(body, 4) { + Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 8 => { + be64(body, 8).and_then(|v| usize::try_from(v).ok()) + } + _ => None, + }; + } + b"stco" => { + offset = match be32(body, 4) { + Some(count) if count > 0 && count as usize <= body.len().saturating_sub(8) / 4 => be32(body, 8).map(|v| v as usize), + _ => None, + }; + } _ => {} } } - let data = match (offset, size) { - (Some(o), Some(s)) if o.checked_add(s as usize).is_some_and(|e| e <= bytes.len()) => Some((o, s as usize)), + let data = match (offset, size, mapping) { + (Some(o), Some(s), Some((1, samples, 1))) + if samples > 0 && samples <= sample_count && o.checked_add(s as usize).is_some_and(|e| e <= bytes.len()) => + { + Some((o, s as usize)) + } _ => None, }; Some(Cr3Track { kind: kind?, data }) @@ -495,6 +537,13 @@ mod tests { bx(b"CRAW", &b) } fn trak(entry: Vec, offset: u64, size: u32) -> Vec { + let stsc = [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(); + trak_with_mapping(entry, offset, size, &stsc) + } + fn trak_with_mapping(entry: Vec, offset: u64, size: u32, mapping: &[u8]) -> Vec { + trak_with_table(entry, offset, size, b"stsc", mapping) + } + fn trak_with_table(entry: Vec, offset: u64, size: u32, table: &[u8; 4], payload: &[u8]) -> Vec { let mut stsd = 1u32.to_be_bytes().to_vec(); stsd.extend(entry); let mut stsz = 0u32.to_be_bytes().to_vec(); @@ -502,7 +551,15 @@ mod tests { stsz.extend(size.to_be_bytes()); let mut co64 = 1u32.to_be_bytes().to_vec(); co64.extend(offset.to_be_bytes()); - let stbl = [full(b"stsd", &stsd), full(b"stsz", &stsz), full(b"co64", &co64)].concat(); + let stsc = [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(); + let offsets = if table == b"stco" { full(b"stco", payload) } else { full(b"co64", if table == b"co64" { payload } else { &co64 }) }; + let stbl = [ + full(b"stsd", &stsd), + full(b"stsc", if table == b"stsc" { payload } else { &stsc }), + full(b"stsz", if table == b"stsz" { payload } else { &stsz }), + offsets, + ] + .concat(); bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl)))) } fn tiff_with(tag: u16, v: craft_tiff::Value) -> Vec { @@ -543,6 +600,97 @@ mod tests { assert_eq!(c.tracks[1].data, Some((4112, 32))); } + #[test] + fn first_sample_requires_a_complete_valid_sample_to_chunk_mapping() { + let file = |track: Vec| { + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &track)); + file.resize(4112, 0); + file + }; + let valid = trak(craw(16, 16, &bx(b"JPEG", &[0; 4])), 4096, 16); + assert_eq!(parse_cr3(&file(valid.clone())).unwrap().tracks[0].data, Some((4096, 16))); + let at = valid.windows(4).position(|bytes| bytes == b"stsc").unwrap(); + // Missing table, impossible first chunk, zero samples, a different + // description and a count that extends beyond this box all deny data. + for (field, value) in [(0, u32::from_be_bytes(*b"xxxx")), (8, 0), (8, 2), (12, 0), (12, 2), (16, 0), (16, 2), (4, u32::MAX)] { + let mut damaged = valid.clone(); + let offset = if field == 0 { at } else { at + 4 + field }; + damaged[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + let bytes = file(damaged); + let parsed = parse_cr3(&bytes).unwrap(); + assert_eq!(parsed.tracks.len(), 1, "invalid mapping must not erase an identifiable track"); + assert_eq!(parsed.tracks[0].kind, Cr3TrackKind::Jpeg); + assert!(parsed.tracks[0].data.is_none()); + } + for entry in [craw(16, 16, &[]), craw(16, 16, &bx(b"CMP1", &[0xff, 0x10, 0, 0x30]))] { + let bytes = file(trak(entry, 4096, 16)); + let parsed = parse_cr3(&bytes).unwrap(); + assert!(!matches!(parsed.tracks[0].kind, Cr3TrackKind::Jpeg)); + } + } + + #[test] + fn truncated_sample_mapping_preserves_larger_raw_track_identity_and_valid_reduced_track() { + let reduced = trak(craw(4, 4, &bx(b"CMP1", &compression_payload(0))), 4096, 16); + for table in [b"stsc", b"stsz", b"co64", b"stco"] { + for payload in [Vec::new(), vec![0; 4], 1u32.to_be_bytes().to_vec()] { + // full() supplies version/flags; an empty payload leaves only + // those four bytes, with the table's required count missing. + let main = trak_with_table(craw(8, 4, &bx(b"CMP1", &compression_payload(0))), 4112, 32, table, &payload); + for main_first in [false, true] { + let tracks = if main_first { [main.clone(), reduced.clone()].concat() } else { [reduced.clone(), main.clone()].concat() }; + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &tracks)); + file.resize(4144, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 2, "truncated {table:?} cannot hide the larger track"); + let (main, reduced) = if main_first { (&parsed.tracks[0], &parsed.tracks[1]) } else { (&parsed.tracks[1], &parsed.tracks[0]) }; + assert!(matches!(reduced.kind, Cr3TrackKind::Raw { width: 4, height: 4, .. })); + assert_eq!(reduced.data, Some((4096, 16))); + assert!(matches!(main.kind, Cr3TrackKind::Raw { width: 8, height: 4, cmp1: Some(_), .. })); + assert!(main.data.is_none()); + assert!(main.compression(&file).is_some(), "only sample location is invalid"); + } + } + let mut offsets = 1u32.to_be_bytes().to_vec(); + offsets.extend(4112u64.to_be_bytes()); + let valid = match table { + b"stsc" => [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(), + b"stsz" => [0u32, 1, 32].into_iter().flat_map(u32::to_be_bytes).collect(), + b"stco" => [1u32, 4112].into_iter().flat_map(u32::to_be_bytes).collect(), + _ => offsets, + }; + let main = trak_with_table(craw(8, 4, &bx(b"CMP1", &compression_payload(0))), 4112, 32, table, &valid); + for main_first in [false, true] { + let tracks = if main_first { [main.clone(), reduced.clone()].concat() } else { [reduced.clone(), main.clone()].concat() }; + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &tracks)); + file.resize(4144, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 2); + let main = &parsed.tracks[if main_first { 0 } else { 1 }]; + assert_eq!(main.data, Some((4112, 32)), "complete valid {table:?} stays usable"); + } + } + } + + #[test] + fn first_sample_size_requires_a_complete_bounded_sample_table() { + let valid = trak(craw(16, 16, &bx(b"JPEG", &[0; 4])), 4096, 16); + let at = valid.windows(4).position(|bytes| bytes == b"stsz").unwrap(); + for (constant, count, accepted) in [(0u32, 1u32, true), (16, 1, true), (0, 2, false), (0, u32::MAX, false), (16, u32::MAX, false)] { + let mut track = valid.clone(); + track[at + 8..at + 12].copy_from_slice(&constant.to_be_bytes()); + track[at + 12..at + 16].copy_from_slice(&count.to_be_bytes()); + let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + file.extend(bx(b"moov", &track)); + file.resize(4112, 0); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks[0].data, accepted.then_some((4096, 16)), "size {constant}, count {count}"); + } + } + #[test] fn hevc_preview_is_distinct_from_an_equal_size_raw_track() { let preview = trak(craw(6000, 4000, &bx(b"HEVC", &[0; 4])), 4096, 16); @@ -714,7 +862,10 @@ mod tests { let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); file.extend(bx(b"moov", &bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl)))))); file.resize(512, 0); - assert!(parse_cr3(&file).unwrap().tracks.is_empty()); + let parsed = parse_cr3(&file).unwrap(); + assert_eq!(parsed.tracks.len(), 1, "a truncated table must not hide the identifiable raw track"); + assert!(matches!(parsed.tracks[0].kind, Cr3TrackKind::Raw { width: 16, height: 16, .. })); + assert!(parsed.tracks[0].data.is_none(), "the empty stsz must not borrow size bytes from the following co64 box"); } #[test] diff --git a/crates/metadata/src/lib.rs b/crates/metadata/src/lib.rs index 1bc9660b85..ff2c530fa2 100644 --- a/crates/metadata/src/lib.rs +++ b/crates/metadata/src/lib.rs @@ -19,6 +19,7 @@ //! HEIF, PSD and MRW files are read by their own crates. Put the blocks they return into an //! [`Embedded`] and call [`from_embedded`]. +pub mod camera_fields; mod container; pub mod cr3; mod datetime; diff --git a/crates/midi/README.md b/crates/midi/README.md index fda624de8d..584bd567e0 100644 --- a/crates/midi/README.md +++ b/crates/midi/README.md @@ -1,6 +1,6 @@ # craft-midi -MIDI file formats. Bytes in, a neutral model out, and back. No file access: callers pass bytes, +MIDI file formats and synchronization wire messages. Bytes in, a neutral model out, and back. No file access: callers pass bytes, so the crate builds for wasm32. | Format | Read | Write | @@ -79,3 +79,17 @@ of two, more than 65535 tracks or a gap beyond the 28-bit delta limit is an erro Written from the public Standard MIDI Files 1.0 specification (the MIDI Association). No other product's code, assets or strings were used. The code comes from SoundCraft's `soundcraft-midi` crate; the tests build every file they read in code, so the crate ships no binary test data. + +## Synchronization wire messages + +`sync` provides MIDI Clock/Start/Continue/Stop and Song Position Pointer parsing, +clamped song-position encoding, and full-frame/quarter-frame MIDI Time Code serialization. +It is allocation-free and contains no port access, clocks, tempo estimation or transport scheduling. +`SyncMessage::parse` accepts a status-first prefix and ignores trailing bytes, matching LoopCraft; +it is not a byte-stream parser. Time code supports only 24/25/30 non-drop fps, not 29.97 drop-frame. + +These wire helpers are extracted from LoopCraft's `crates/midi/src/sync.rs` at +[`18c68c6e`](https://github.com/storytold/loopcraft/blob/18c68c6e18b13d90db3001dd9f95462cdc4b05a8/crates/midi/src/sync.rs). +The source history credits bflatastic. Transport state and scheduling remain app-owned. +Tests cover known wire vectors, truncated/invalid input, all song-position input values and +legacy conversion behavior. No application consumer cutover is claimed by this library addition. diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs index 2eb947addb..aa82e3e016 100644 --- a/crates/midi/src/lib.rs +++ b/crates/midi/src/lib.rs @@ -12,6 +12,7 @@ mod sequence; mod smf; +pub mod sync; pub use sequence::{CtrlEvent, CtrlKind, Note, Sequence}; pub use smf::{LenientRead, MAX_EVENTS, MAX_TRACKS, MAX_WARNINGS, Smf, SmfTrack, read_smf, read_smf_lenient, write_smf}; diff --git a/crates/midi/src/sync.rs b/crates/midi/src/sync.rs new file mode 100644 index 0000000000..153c8a77bd --- /dev/null +++ b/crates/midi/src/sync.rs @@ -0,0 +1,135 @@ +//! MIDI synchronization wire messages, separate from transport scheduling. +//! +//! Extracted from LoopCraft `crates/midi/src/sync.rs` at +//! `18c68c6e18b13d90db3001dd9f95462cdc4b05a8` (source history credits bflatastic). +//! This module preserves its prefix-parser, clamped song-position and non-drop time-code +//! behavior. It does not parse a byte stream or schedule clocks; hosts retain those policies. +//! +//! Only 24, 25 and 30 non-drop frames per second are represented, not 29.97 drop-frame. + +/// MIDI clock: 24 to the quarter note. +pub const CLOCKS_PER_QUARTER: u32 = 24; +pub const CLOCK: u8 = 0xF8; +pub const START: u8 = 0xFA; +pub const CONTINUE: u8 = 0xFB; +pub const STOP: u8 = 0xFC; +pub const SONG_POSITION: u8 = 0xF2; +pub const QUARTER_FRAME: u8 = 0xF1; +/// The furthest Song Position Pointer reaches, in sixteenth notes (fourteen bits). +pub const MAX_POSITION: u16 = 0x3FFF; + +/// What a device that leads the time sends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SyncMessage { + Clock, + Start, + Continue, + Stop, + /// Song Position Pointer: sixteenth notes from the start of the song. + Position(u16), +} + +impl SyncMessage { + /// Parse a status-first message prefix; trailing bytes are ignored for compatibility. + /// Returns `None` for an unknown status, truncated song position, or non-seven-bit data. + /// This is not a stream parser and does not remove interleaved real-time messages. + pub fn parse(message: &[u8]) -> Option { + Some(match *message { + [CLOCK, ..] => SyncMessage::Clock, + [START, ..] => SyncMessage::Start, + [CONTINUE, ..] => SyncMessage::Continue, + [STOP, ..] => SyncMessage::Stop, + [SONG_POSITION, low, high, ..] if low < 0x80 && high < 0x80 => SyncMessage::Position(u16::from(high) << 7 | u16::from(low)), + _ => return None, + }) + } +} + +/// Song Position Pointer at `sixteenths` from the start, the low seven bits first. +pub fn song_position(sixteenths: u16) -> [u8; 3] { + let at = sixteenths.min(MAX_POSITION); + [SONG_POSITION, (at & 0x7F) as u8, (at >> 7) as u8] +} + +/// The frame rates time code is sent at (non-drop). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Rate { + Fps24, + #[default] + Fps25, + Fps30, +} + +impl Rate { + /// 24 and 30 frames a second are themselves; anything else is 25. + pub fn of(fps: u8) -> Rate { + match fps { + 24 => Rate::Fps24, + 30 => Rate::Fps30, + _ => Rate::Fps25, + } + } + + pub fn fps(self) -> u8 { + match self { + Rate::Fps24 => 24, + Rate::Fps25 => 25, + Rate::Fps30 => 30, + } + } + + /// As the hours byte carries it: 0 for 24, 1 for 25, 3 for 30 non-drop. + fn code(self) -> u8 { + match self { + Rate::Fps24 => 0, + Rate::Fps25 => 1, + Rate::Fps30 => 3, + } + } +} + +/// Hours, minutes, seconds and frames at `secs`; the hours wrap at a day. +fn timecode(secs: f64, rate: Rate) -> [u8; 4] { + let fps = u64::from(rate.fps()); + // `as` saturates: before the start, and NaN, is the start. The nudge keeps a frame's own + // start in it when the sum lands a hair short. + let frames = (secs * fps as f64 + 1e-6) as u64; + let s = frames / fps; + [(s / 3600 % 24) as u8, (s / 60 % 60) as u8, (s % 60) as u8, (frames % fps) as u8] +} + +/// The full-frame message (universal real-time SysEx, all devices) locating to `secs`. +/// +/// Compatibility conversion: negative values and NaN locate to zero; positive overflow +/// saturates the frame count at `u64::MAX`. Hours wrap at 24. No drop-frame conversion. +pub fn full_frame(secs: f64, rate: Rate) -> [u8; 10] { + let [h, m, s, f] = timecode(secs, rate); + [0xF0, 0x7F, 0x7F, 0x01, 0x01, rate.code() << 5 | h, m, s, f, 0xF7] +} + +/// Quarter frame `piece` (0..8) of `time` (hours, minutes, seconds, frames): eight of them, a +/// quarter of a frame apart, carry the whole time, the frames' low nibble first. +fn quarter_frame(time: [u8; 4], rate: Rate, piece: u8) -> [u8; 2] { + let [h, m, s, f] = time; + let piece = piece & 7; + let nibble = match piece { + 0 => f, + 1 => f >> 4, + 2 => s, + 3 => s >> 4, + 4 => m, + 5 => m >> 4, + 6 => h, + _ => h >> 4 | rate.code() << 1, + }; + [QUARTER_FRAME, piece << 4 | nibble & 0x0F] +} + +/// All eight quarter-frame wire messages for a single time-code snapshot, in wire order. +/// +/// This is serialization only: the host must send each piece at the appropriate time and +/// account for transport direction/latency. Seconds use the same conversion as [`full_frame`]. +pub fn quarter_frames(secs: f64, rate: Rate) -> [[u8; 2]; 8] { + let time = timecode(secs, rate); + [0, 1, 2, 3, 4, 5, 6, 7].map(|piece| quarter_frame(time, rate, piece)) +} diff --git a/crates/midi/tests/it/main.rs b/crates/midi/tests/it/main.rs index 368d7dc71c..45f95c70ca 100644 --- a/crates/midi/tests/it/main.rs +++ b/crates/midi/tests/it/main.rs @@ -3,3 +3,4 @@ mod lenient; mod sequence; mod smf; +mod sync; diff --git a/crates/midi/tests/it/sync.rs b/crates/midi/tests/it/sync.rs new file mode 100644 index 0000000000..0a73faad7a --- /dev/null +++ b/crates/midi/tests/it/sync.rs @@ -0,0 +1,54 @@ +use craft_midi::sync::{CLOCK, CONTINUE, MAX_POSITION, Rate, SONG_POSITION, START, STOP, SyncMessage, full_frame, quarter_frames, song_position}; + +#[test] +fn transport_prefix_compatibility() { + for (status, expected) in [(CLOCK, SyncMessage::Clock), (START, SyncMessage::Start), (CONTINUE, SyncMessage::Continue), (STOP, SyncMessage::Stop)] + { + assert_eq!(SyncMessage::parse(&[status]), Some(expected)); + assert_eq!(SyncMessage::parse(&[status, 0, 0xff]), Some(expected)); + } + for invalid in [&[][..], &[0x90, 60, 127], &[SONG_POSITION], &[SONG_POSITION, 0], &[SONG_POSITION, 0x80, 0], &[SONG_POSITION, 0, 0x80]] { + assert_eq!(SyncMessage::parse(invalid), None); + } +} + +#[test] +fn song_position_preserves_clamping_and_seven_bit_order() { + for value in 0..=u16::MAX { + let bytes = song_position(value); + assert!(bytes[1] < 128 && bytes[2] < 128); + assert_eq!(SyncMessage::parse(&bytes), Some(SyncMessage::Position(value.min(MAX_POSITION)))); + } + assert_eq!(song_position(128), [0xf2, 0, 1]); + assert_eq!(SyncMessage::parse(&[0xf2, 1, 2, 0xff]), Some(SyncMessage::Position(257))); +} + +#[test] +fn full_frame_known_vectors_and_legacy_conversion() { + for (rate, bits) in [(Rate::Fps24, 0), (Rate::Fps25, 0x20), (Rate::Fps30, 0x60)] { + assert_eq!(full_frame(3723.0, rate), [0xf0, 0x7f, 0x7f, 1, 1, bits | 1, 2, 3, 0, 0xf7]); + assert_eq!(full_frame(86400.0, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(-1.0, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(f64::NAN, rate), full_frame(0.0, rate)); + assert_eq!(full_frame(1.0 / f64::from(rate.fps()), rate)[8], 1); + } + assert_eq!(Rate::of(24), Rate::Fps24); + assert_eq!(Rate::of(30), Rate::Fps30); + assert_eq!(Rate::of(29), Rate::Fps25); +} + +#[test] +fn quarter_frames_known_vector() { + assert_eq!( + quarter_frames(3723.04, Rate::Fps25), + [[0xf1, 1], [0xf1, 0x10], [0xf1, 0x23], [0xf1, 0x30], [0xf1, 0x42], [0xf1, 0x50], [0xf1, 0x61], [0xf1, 0x72]] + ); + for rate in [Rate::Fps24, Rate::Fps25, Rate::Fps30] { + for secs in [0.0, 59.99, 3599.99, 86399.99, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] { + for bytes in quarter_frames(secs, rate) { + assert_eq!(bytes[0], 0xf1); + assert!(bytes[1] < 128); + } + } + } +} diff --git a/crates/mime/src/base64.rs b/crates/mime/src/base64.rs index a93a6fdfb4..856f333981 100644 --- a/crates/mime/src/base64.rs +++ b/crates/mime/src/base64.rs @@ -8,8 +8,9 @@ //! counts it; an unpadded one refuses `=`), a length that can be, and the unused bits of the last //! symbol zero (so every value has one spelling). A caller that reads mail, where line breaks and //! missing padding are everyday, cleans its input first, as it always has; the strictness is what -//! the signature, key and credential checks want. No input panics, and the output is never longer -//! than three quarters of the input. +//! the signature, key and credential checks want. [`Config::decode_optional_padding`] explicitly +//! permits missing terminal padding without relaxing alphabet, padding placement or unused bits. +//! No input panics, and the output is never longer than three quarters of the input. use std::fmt; @@ -108,9 +109,20 @@ impl Config { /// The bytes of `text`, which must be exactly base64 of this config's kind (see the module). pub fn decode(self, text: impl AsRef<[u8]>) -> Result, DecodeError> { - let text = text.as_ref(); - let (symbols, pad) = if self.padded { - if text.len() % 4 != 0 { + self.decode_inner(text.as_ref(), false) + } + + /// Decode this alphabet with zero, partial or complete terminal padding, regardless of the + /// config's encoding padding. Whitespace, junk, internal/excess padding and nonzero unused + /// bits still fail. Use this only when the calling format permits missing padding; [`Self::decode`] + /// remains strict for signatures and credentials that require one spelling. + pub fn decode_optional_padding(self, text: impl AsRef<[u8]>) -> Result, DecodeError> { + self.decode_inner(text.as_ref(), true) + } + + fn decode_inner(self, text: &[u8], optional_padding: bool) -> Result, DecodeError> { + let (symbols, pad) = if self.padded || optional_padding { + if !optional_padding && !text.len().is_multiple_of(4) { return Err(DecodeError); } let pad = text.iter().rev().take(2).take_while(|c| **c == b'=').count(); @@ -120,7 +132,8 @@ impl Config { }; // A last group of one symbol holds under eight bits; with padding, `=` fills it to four. let rest = symbols.len() % 4; - if rest == 1 || (self.padded && pad != (4 - rest) % 4) { + let needed = (4 - rest) % 4; + if rest == 1 || (optional_padding && pad > needed) || (!optional_padding && self.padded && pad != needed) { return Err(DecodeError); } let mut out = Vec::with_capacity(symbols.len().saturating_mul(3) / 4); diff --git a/crates/mime/src/base64_tests.rs b/crates/mime/src/base64_tests.rs index e3d52794e5..07fee89c78 100644 --- a/crates/mime/src/base64_tests.rs +++ b/crates/mime/src/base64_tests.rs @@ -79,3 +79,45 @@ proptest! { } } } + +/// Missing padding is opt-in; other canonical validation stays unchanged. +#[test] +fn optional_padding_keeps_alphabet_placement_and_tail_bit_checks() { + for cfg in CONFIGS { + for (input, expected) in [("", ""), ("Zg", "f"), ("Zg=", "f"), ("Zg==", "f"), ("Zm8", "fo"), ("Zm8=", "fo"), ("Zm9v", "foo")] { + assert_eq!(cfg.decode_optional_padding(input).unwrap(), expected.as_bytes()); + } + for bad in ["=", "====", "Z", "Z===", "Zg===", "Zm8==", "Zm9v=", "QQ==QUJD", "Zm=v", "Zh", "Zh=", "Zh==", "Zm9", "Zm9=", "Zg\n", " Zg", "é"] + { + assert!(cfg.decode_optional_padding(bad).is_err(), "{cfg:?}: {bad:?}"); + } + } + assert_eq!(STANDARD.decode_optional_padding("+/8").unwrap(), [251, 255]); + assert_eq!(URL_SAFE.decode_optional_padding("-_8=").unwrap(), [251, 255]); + assert!(STANDARD.decode_optional_padding("-_8=").is_err()); + assert!(URL_SAFE.decode_optional_padding("+/8=").is_err()); + assert!(STANDARD.decode("Zg=").is_err()); + assert!(STANDARD_NO_PAD.decode("Zg==").is_err()); +} + +proptest! { + #[test] + fn optional_padding_accepts_only_a_suffix_of_required_padding( + data in proptest::collection::vec(any::(), 0..400), + junk in proptest::collection::vec(any::(), 0..128), + ) { + for cfg in [STANDARD, URL_SAFE] { + let encoded = cfg.encode(&data); + let bare = encoded.trim_end_matches('='); + for length in bare.len()..=encoded.len() { + prop_assert_eq!(cfg.decode_optional_padding(&encoded[..length]).ok(), Some(data.clone())); + } + if let Ok(decoded) = cfg.decode_optional_padding(&junk) { + let canonical = cfg.encode(decoded); + let bare = canonical.trim_end_matches('='); + prop_assert!(junk.len() >= bare.len() && junk.len() <= canonical.len()); + prop_assert_eq!(canonical.as_bytes().get(..junk.len()), Some(junk.as_slice())); + } + } + } +} diff --git a/crates/pcraft-bundle/src/lib.rs b/crates/pcraft-bundle/src/lib.rs index acbe739b6d..1368fa7479 100644 --- a/crates/pcraft-bundle/src/lib.rs +++ b/crates/pcraft-bundle/src/lib.rs @@ -370,7 +370,8 @@ impl DirectoryBundleWriter { /// Saves an entry set incrementally. Existing objects are reused only after a hash check; /// unchanged file signatures may skip checks until they enter the rolling verification /// window. The manifest is atomically published last, then stale previews and objects are - /// collected while the bundle lock is held. + /// collected while the bundle lock is held. Collection is best-effort after publication: + /// inaccessible or unsafe leftovers cannot turn a committed save into a reported failure. pub fn save_directory(&mut self, root: &Path, bundle: ZipBundleWriter) -> Result { if !bundle.entries.contains_key(craft_pcraft_format::MANIFEST) { return Err(Error::InvalidBundle("manifest not set".into())); @@ -401,6 +402,10 @@ impl DirectoryBundleWriter { Err(std::fs::TryLockError::Error(_)) => break None, } }; + // A known unsafe manifest cannot be published. Refuse it before writing objects or + // previews, and still recheck immediately before publication below. + let manifest_path = root.join(craft_pcraft_format::MANIFEST); + refuse_symlink(&manifest_path)?; self.generation = self.generation.saturating_add(1); let generation = self.generation; let recheck = self.rolling_recheck(&bundle.entries); @@ -449,43 +454,33 @@ impl DirectoryBundleWriter { } let manifest = bundle.entries.get(craft_pcraft_format::MANIFEST).ok_or_else(|| Error::InvalidBundle("manifest not set".into()))?; - let manifest_path = root.join(craft_pcraft_format::MANIFEST); refuse_symlink(&manifest_path)?; craft_atomic::atomic_write(&manifest_path, manifest).map_err(io_error)?; stats.written = stats.written.saturating_add(1); - let mut removed_paths = Vec::new(); + // The durable manifest is the commit boundary. Cleanup owns only canonical regular + // object files and previews; leave unsafe, inaccessible or locked leftovers for later. for kind in [craft_pcraft_format::TILES_DIR, craft_pcraft_format::BLOBS_DIR] { let dir = root.join(kind); - if !dir.exists() { + if !cleanup_directory(&dir) { continue; } - refuse_symlink(&dir)?; - for entry in fs::read_dir(&dir).map_err(io_error)? { - let entry = entry.map_err(io_error)?; + let Ok(entries) = fs::read_dir(&dir) else { continue }; + for entry in entries { + let Ok(entry) = entry else { continue }; let name = entry.file_name(); let path = format!("{kind}/{}", name.to_string_lossy()); - if is_object_path(&path) && !bundle.entries.contains_key(&path) { - let metadata = fs::symlink_metadata(entry.path()).map_err(io_error)?; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(Error::InvalidBundle(format!("refusing to collect non-file object {path}"))); - } - fs::remove_file(entry.path()).map_err(io_error)?; - removed_paths.push(path); + if is_object_path(&path) && !bundle.entries.contains_key(&path) && remove_cleanup_file(&entry.path()) { stats.removed = stats.removed.saturating_add(1); } } } for path in [craft_pcraft_format::THUMB, craft_pcraft_format::COMPOSITE, craft_pcraft_format::FULL_COMPOSITE] { if !bundle.entries.contains_key(path) { - let target = root.join(path); - refuse_symlink(&target)?; - if fs::symlink_metadata(&target).is_ok() { - fs::remove_file(&target).map_err(io_error)?; - } + let _ = remove_cleanup_file(&root.join(path)); } } - self.verified.retain(|path, _| bundle.entries.contains_key(path) && !removed_paths.contains(path)); + self.verified.retain(|path, _| bundle.entries.contains_key(path)); Ok(stats) } @@ -510,7 +505,32 @@ impl DirectoryBundleWriter { } fn is_object_path(path: &str) -> bool { - path.starts_with("tiles/") || path.starts_with("blobs/") + valid_object_path(path) +} + +/// Do not traverse symlinked object/preview directories, including Windows junctions. +fn cleanup_directory(path: &Path) -> bool { + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && !cleanup_link(&metadata)) +} + +fn cleanup_link(metadata: &fs::Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + metadata.file_attributes() & 0x400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT includes junctions. + } + #[cfg(not(windows))] + { + metadata.file_type().is_symlink() + } +} + +/// Cleanup never follows or removes a directory/link and never reports a post-commit failure. +fn remove_cleanup_file(path: &Path) -> bool { + if path.parent().is_none_or(|parent| !cleanup_directory(parent)) { + return false; + } + fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_file() && !cleanup_link(&metadata)) && fs::remove_file(path).is_ok() } fn file_signature(path: &Path) -> Result> { diff --git a/crates/pcraft-bundle/tests/directory_cleanup.rs b/crates/pcraft-bundle/tests/directory_cleanup.rs new file mode 100644 index 0000000000..29015bd230 --- /dev/null +++ b/crates/pcraft-bundle/tests/directory_cleanup.rs @@ -0,0 +1,344 @@ +//! Publication succeeds independently of best-effort cleanup of the previous entry set. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use craft_pcraft_bundle::{DirectoryBundle, DirectoryBundleWriter, Limits, ObjectKind, ZipBundleWriter}; +use craft_pcraft_format::{COMPOSITE, FULL_COMPOSITE, MANIFEST, THUMB}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const OLD: &[u8] = br#"{"revision":1}"#; +const NEW: &[u8] = br#"{"revision":2}"#; + +struct Temporary(PathBuf); + +impl Temporary { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!("craft-bundle-cleanup-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + fs::create_dir(&path).unwrap(); + Self(path) + } + + fn bundle(&self) -> PathBuf { + self.0.join("document.pcraft") + } +} + +impl Drop for Temporary { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn entries(manifest: &[u8]) -> ZipBundleWriter { + let mut bundle = ZipBundleWriter::default(); + bundle.set_manifest(manifest.to_vec()).unwrap(); + bundle +} + +fn assert_manifest(root: &Path, expected: &[u8]) { + assert_eq!(fs::read(root.join(MANIFEST)).unwrap(), expected); + assert_eq!(DirectoryBundle::open(root, Limits::default()).unwrap().manifest().unwrap(), expected); +} + +#[test] +fn non_file_stale_object_does_not_fail_the_committed_save() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let stuck = root.join("tiles").join(format!("{}.zst", "0".repeat(64))); + fs::create_dir_all(stuck.join("inner")).unwrap(); + fs::write(stuck.join("inner/keep"), b"not an object file").unwrap(); + + let stats = writer.save_directory(&root, entries(NEW)).expect("cleanup cannot fail after manifest publication"); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(stuck.join("inner/keep")).unwrap(), b"not an object file"); +} + +#[test] +fn cleanup_removes_only_canonical_stale_regular_objects_and_reuses_current_objects() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let retained = first.add_object(ObjectKind::Tile, b"still referenced").unwrap(); + let stale = first.add_object(ObjectKind::Blob, b"old blob").unwrap(); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + first.set_preview(preview, b"old preview".to_vec()).unwrap(); + } + writer.save_directory(&root, first).unwrap(); + let retained_bytes = fs::read(root.join(&retained)).unwrap(); + let unrelated = [ + "tiles/personal-notes.zst".to_string(), + "blobs/012345.zst".to_string(), + format!("blobs/{}.zst", "A".repeat(64)), + format!("tiles/{}.zst.backup", "b".repeat(64)), + ]; + for path in &unrelated { + fs::write(root.join(path), b"unrelated").unwrap(); + } + let nested = root.join("blobs/not-an-object-folder"); + fs::create_dir(&nested).unwrap(); + fs::write(nested.join(format!("{}.zst", "c".repeat(64))), b"unrelated nested file").unwrap(); + let mut second = entries(NEW); + assert_eq!(second.add_object(ObjectKind::Tile, b"still referenced").unwrap(), retained); + let stats = writer.save_directory(&root, second).unwrap(); + + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 1); + assert_eq!(stats.reused, 1); + assert_eq!(stats.reused_objects.as_slice(), std::slice::from_ref(&retained)); + assert!(stats.written_objects.is_empty()); + assert!(!root.join(stale).exists()); + assert_eq!(fs::read(root.join(retained)).unwrap(), retained_bytes); + for path in unrelated { + assert_eq!(fs::read(root.join(path)).unwrap(), b"unrelated"); + } + assert!(nested.is_dir()); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + assert!(!root.join(preview).exists()); + } +} + +#[test] +fn stale_preview_directories_are_preserved_after_commit() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + fs::create_dir_all(root.join(preview)).unwrap(); + fs::write(root.join(preview).join("keep"), b"directory contents").unwrap(); + } + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + for preview in [THUMB, COMPOSITE, FULL_COMPOSITE] { + assert_eq!(fs::read(root.join(preview).join("keep")).unwrap(), b"directory contents"); + } +} + +#[test] +fn required_non_file_objects_and_previews_fail_before_manifest_publication() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let mut changed = entries(NEW); + let object = changed.add_object(ObjectKind::Tile, b"required object").unwrap(); + fs::create_dir_all(root.join(&object)).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + + for preview in [THUMB, COMPOSITE] { + fs::create_dir_all(root.join(preview)).unwrap(); + let mut changed = entries(NEW); + changed.set_preview(preview, b"required preview".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + } +} + +#[cfg(windows)] +#[test] +fn locked_stale_object_and_preview_do_not_fail_commit_and_are_collected_on_retry() { + use std::fs::OpenOptions; + use std::os::windows::fs::OpenOptionsExt; + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let stale = first.add_object(ObjectKind::Tile, b"locked stale tile").unwrap(); + first.set_preview(FULL_COMPOSITE, b"locked preview".to_vec()).unwrap(); + writer.save_directory(&root, first).unwrap(); + let tile_lock = OpenOptions::new().read(true).share_mode(0).open(root.join(&stale)).unwrap(); + let preview_lock = OpenOptions::new().read(true).share_mode(0).open(root.join(FULL_COMPOSITE)).unwrap(); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert!(root.join(&stale).exists()); + assert!(root.join(FULL_COMPOSITE).exists()); + drop(tile_lock); + drop(preview_lock); + let retry = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(retry.removed, 1); + assert!(!root.join(stale).exists()); + assert!(!root.join(FULL_COMPOSITE).exists()); +} + +#[cfg(unix)] +#[test] +fn cleanup_preserves_symlinks_and_does_not_traverse_linked_directories() { + use std::os::unix::fs::symlink; + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside"); + fs::create_dir(&outside).unwrap(); + let object_name = format!("{}.zst", "d".repeat(64)); + fs::write(outside.join(&object_name), b"outside object").unwrap(); + fs::write(outside.join("preview.png"), b"outside preview").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + symlink(&outside, root.join("blobs")).unwrap(); + symlink(&outside, root.join("composite")).unwrap(); + symlink(outside.join("preview.png"), root.join(THUMB)).unwrap(); + fs::create_dir(root.join("tiles")).unwrap(); + let linked_object = root.join("tiles").join(&object_name); + symlink(outside.join(&object_name), &linked_object).unwrap(); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(outside.join(object_name)).unwrap(), b"outside object"); + assert_eq!(fs::read(outside.join("preview.png")).unwrap(), b"outside preview"); + for link in [root.join("blobs"), root.join("composite"), root.join(THUMB), linked_object] { + assert!(fs::symlink_metadata(link).unwrap().file_type().is_symlink()); + } +} + +#[cfg(unix)] +#[test] +fn required_symlink_objects_and_previews_still_fail_before_commit() { + use std::os::unix::fs::symlink; + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside-file"); + fs::write(&outside, b"unchanged outside bytes").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let mut changed = entries(NEW); + let object = changed.add_object(ObjectKind::Tile, b"required object").unwrap(); + fs::create_dir(root.join("tiles")).unwrap(); + symlink(&outside, root.join(object)).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + symlink(&outside, root.join(THUMB)).unwrap(); + let mut changed = entries(NEW); + changed.set_preview(THUMB, b"new preview".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_manifest(&root, OLD); + assert_eq!(fs::read(outside).unwrap(), b"unchanged outside bytes"); +} + +#[cfg(windows)] +#[test] +fn cleanup_does_not_traverse_windows_directory_junctions() { + use std::os::windows::process::CommandExt; + struct Junction(PathBuf); + impl Drop for Junction { + fn drop(&mut self) { + let _ = fs::remove_dir(&self.0); + } + } + fn junction(link: PathBuf, target: &Path) -> Junction { + // Fixture-owned absolute paths only; junctions require no symlink privilege. + assert!(link.is_absolute() && target.is_absolute()); + let output = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(&link) + .arg(target) + .creation_flags(0x0800_0000) // CREATE_NO_WINDOW + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + Junction(link) + } + let temp = Temporary::new(); + let root = temp.bundle(); + let outside = temp.0.join("outside"); + fs::create_dir(&outside).unwrap(); + let object_name = format!("{}.zst", "e".repeat(64)); + fs::write(outside.join(&object_name), b"outside object").unwrap(); + fs::write(outside.join("preview.png"), b"outside preview").unwrap(); + fs::write(outside.join("full.png"), b"outside full preview").unwrap(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + let _objects = junction(root.join("blobs"), &outside); + let _previews = junction(root.join("composite"), &outside); + let stats = writer.save_directory(&root, entries(NEW)).unwrap(); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 0); + assert_eq!(fs::read(outside.join(object_name)).unwrap(), b"outside object"); + assert_eq!(fs::read(outside.join("preview.png")).unwrap(), b"outside preview"); + assert_eq!(fs::read(outside.join("full.png")).unwrap(), b"outside full preview"); + assert!(root.join("blobs").exists()); + assert!(root.join("composite").exists()); +} + +#[cfg(any(unix, windows))] +#[test] +fn manifest_symlink_is_refused_before_writing_any_objects_or_previews() { + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + writer.save_directory(&root, entries(OLD)).unwrap(); + assert_manifest(&root, OLD); // Ordinary publication remains supported. + let external = temp.0.join("external-manifest.json"); + fs::write(&external, b"unchanged external manifest").unwrap(); + fs::remove_file(root.join(MANIFEST)).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&external, root.join(MANIFEST)).unwrap(); + #[cfg(windows)] + if let Err(error) = std::os::windows::fs::symlink_file(&external, root.join(MANIFEST)) { + if error.raw_os_error() == Some(1314) || error.kind() == std::io::ErrorKind::Unsupported { + eprintln!("SKIP manifest symlink fixture: {error}"); + return; + } + panic!("create manifest symlink fixture: {error}"); + } + let mut changed = entries(NEW); + changed.add_object(ObjectKind::Tile, b"must not write tile").unwrap(); + changed.add_object(ObjectKind::Blob, b"must not write blob").unwrap(); + changed.set_preview(THUMB, b"must not write thumbnail".to_vec()).unwrap(); + changed.set_preview(FULL_COMPOSITE, b"must not write composite".to_vec()).unwrap(); + assert!(writer.save_directory(&root, changed).is_err()); + assert_eq!(fs::read(&external).unwrap(), b"unchanged external manifest"); + assert!(fs::symlink_metadata(root.join(MANIFEST)).unwrap().file_type().is_symlink()); + for unwritten in ["tiles", "blobs", THUMB, "composite"] { + assert!(!root.join(unwritten).exists(), "manifest refusal must precede {unwritten} publication"); + } +} + +#[cfg(unix)] +#[test] +fn chosen_root_symlink_cleanup_works_with_search_only_root_and_composite_permissions() { + use std::os::unix::fs::{PermissionsExt, symlink}; + struct Restore(PathBuf, fs::Permissions); + impl Restore { + fn restrict(path: &Path) -> Self { + let old = fs::metadata(path).unwrap().permissions(); + fs::set_permissions(path, fs::Permissions::from_mode(0o300)).unwrap(); + Self(path.to_path_buf(), old) + } + } + impl Drop for Restore { + fn drop(&mut self) { + let _ = fs::set_permissions(&self.0, self.1.clone()); + } + } + let temp = Temporary::new(); + let root = temp.bundle(); + let mut writer = DirectoryBundleWriter::default(); + let mut first = entries(OLD); + let stale = first.add_object(ObjectKind::Blob, b"stale blob").unwrap(); + first.set_preview(THUMB, b"stale thumbnail".to_vec()).unwrap(); + first.set_preview(COMPOSITE, b"stale preview".to_vec()).unwrap(); + writer.save_directory(&root, first).unwrap(); + let chosen = temp.0.join("chosen.pcraft"); + symlink(&root, &chosen).unwrap(); + let composite_mode = Restore::restrict(&root.join("composite")); + let root_mode = Restore::restrict(&root); + let result = writer.save_directory(&chosen, entries(NEW)); + drop(root_mode); + drop(composite_mode); + let stats = result.expect("chosen root resolves before cleanup; traversal does not require directory read permission"); + assert_manifest(&root, NEW); + assert_eq!(stats.removed, 1); + assert!(!root.join(stale).exists()); + assert!(!root.join(THUMB).exists()); + assert!(!root.join(COMPOSITE).exists()); + assert!(fs::symlink_metadata(chosen).unwrap().file_type().is_symlink()); +} diff --git a/crates/pcraft-format/Cargo.toml b/crates/pcraft-format/Cargo.toml index ce1d6873fd..f54bb0c820 100644 --- a/crates/pcraft-format/Cargo.toml +++ b/crates/pcraft-format/Cargo.toml @@ -16,3 +16,6 @@ serde = { workspace = true } # the nesting against `Limits::max_depth` before parsing. serde_json = { workspace = true, features = ["unbounded_depth"] } thiserror = { workspace = true } + +# Same pure-Rust backend as the PhotoCraft source codec. MIT OR Apache-2.0. +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } diff --git a/crates/pcraft-format/README.md b/crates/pcraft-format/README.md index 5d8869b742..f5b0dfa731 100644 --- a/crates/pcraft-format/README.md +++ b/crates/pcraft-format/README.md @@ -5,7 +5,7 @@ references, the entry paths, the limits for reading a manifest, and the runner f migrations. The document model stays in PhotoCraft and is a type parameter here. The crate does not read ZIP archives, open files or decode tiles. No `unsafe`, no panics on malformed input, and it builds for `wasm32-unknown-unknown`. The dependencies are `serde`, `serde_json` -and `thiserror`. +`thiserror`, and `flate2`. ```toml craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "" } @@ -120,3 +120,15 @@ limits.max_manifest_bytes = 16 << 20; `.github/workflows/pcraft-format.yml` runs fmt, clippy and the tests on Linux and Windows, and a `wasm32-unknown-unknown` check. + +## Brush-tip envelope + +`tip::encode`, `tip::decode` and `tip::decode_with_max_side` share PhotoCraft's PCTIP1 +brush-tip codec: a six-byte magic, one-byte depth, little-endian width/height and zlib +samples. Eight-bit-compatible samples use 8 bits, otherwise 16-bit little-endian. +Dimensions, sample count, exact inflated length and caller preview side limits are checked. +Preset group schemas, tip hashes and storage policy remain application-owned. + +Ported from `storytold/photocraft` commit `19aec5eb44131de44361189d64910e7b3e19e57c`, +`crates/engine/src/preset_store.rs`. Original codec by Brandon Thomas (PhotoCraft #82), +with later bounds/backend/storage changes by David Mann and FinnNk, under MIT OR Apache-2.0. diff --git a/crates/pcraft-format/src/lib.rs b/crates/pcraft-format/src/lib.rs index 18868da2d7..f12bc52134 100644 --- a/crates/pcraft-format/src/lib.rs +++ b/crates/pcraft-format/src/lib.rs @@ -36,6 +36,9 @@ mod limits; mod migrate; mod read; +/// Lossless brush-tip envelope used by PhotoCraft preset libraries. +pub mod tip; + use serde::{Deserialize, Serialize}; pub use limits::{ diff --git a/crates/pcraft-format/src/tip.rs b/crates/pcraft-format/src/tip.rs new file mode 100644 index 0000000000..9b971f5d98 --- /dev/null +++ b/crates/pcraft-format/src/tip.rs @@ -0,0 +1,102 @@ +//! PhotoCraft's PCTIP1 brush-tip envelope and lossless grayscale sample serialization. +//! +//! Extracted from PhotoCraft preset_store.rs at 19aec5eb44131de44361189d64910e7b3e19e57c. +//! Original implementation: Brandon Thomas; subsequent codec changes: David Mann and FinnNk. +//! Group schemas, file naming, content hashes and storage policy remain with the application. + +/// Largest accepted tip side. +pub const MAX_SIDE: u32 = 16384; +/// Largest accepted sample count. +pub const MAX_SAMPLES: u64 = 1 << 26; +const TIP_MAGIC: &[u8; 6] = b"PCTIP1"; +const TIP_HEADER: usize = 6 + 1 + 4 + 4; + +/// Decoded grayscale samples. Eight-bit samples expand losslessly by multiplication by 257. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tip { + pub width: u32, + pub height: u32, + pub data: Vec, +} + +/// `PCTIP1`, bits (8|16), width, height (u32 LE), then the zlib-deflated samples. +/// Returns an empty vector for invalid dimensions/sample counts or compression failure. +pub fn encode(width: u32, height: u32, data: &[u16]) -> Vec { + use std::io::Write; + let count = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE || count > MAX_SAMPLES || count != data.len() as u64 { + return Vec::new(); + } + let eight = data.iter().all(|v| v % 257 == 0); + let mut out = Vec::with_capacity(TIP_HEADER + data.len() / 4); + out.extend_from_slice(TIP_MAGIC); + out.push(if eight { 8 } else { 16 }); + out.extend_from_slice(&width.to_le_bytes()); + out.extend_from_slice(&height.to_le_bytes()); + // Level 3: zlib-rs level 1 writes static Huffman blocks only, 13-30% bigger than miniz's level 1. + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); + let mut buf = Vec::with_capacity(8192); + let mut ok = true; + for chunk in data.chunks(4096) { + buf.clear(); + if eight { + buf.extend(chunk.iter().map(|v| (v / 257) as u8)); + } else { + for v in chunk { + buf.extend_from_slice(&v.to_le_bytes()); + } + } + ok &= z.write_all(&buf).is_ok(); + } + match z.finish() { + Ok(v) if ok => v, + _ => Vec::new(), + } +} + +/// Inverse of [`encode`]; any malformed, truncated or oversized input is an error. +pub fn decode(bytes: &[u8]) -> Result { + decode_with_max_side(bytes, MAX_SIDE) +} + +/// [`decode`] refusing (before inflating anything) a bitmap with a side over `max_side`. +pub fn decode_with_max_side(bytes: &[u8], max_side: u32) -> Result { + let head = bytes.get(..TIP_HEADER).ok_or("truncated tip header")?; + if &head[..6] != TIP_MAGIC { + return Err("not a PhotoCraft tip".into()); + } + let bits = head[6]; + let u32_at = |i: usize| u32::from_le_bytes([head[i], head[i + 1], head[i + 2], head[i + 3]]); + let (w, h) = (u32_at(7), u32_at(11)); + if w == 0 || h == 0 || w > MAX_SIDE.min(max_side) || h > MAX_SIDE.min(max_side) { + return Err(format!("bad tip size {w}×{h}")); + } + let n = u64::from(w) * u64::from(h); + if n > MAX_SAMPLES { + return Err(format!("tip too large ({w}×{h})")); + } + let bytes_per = match bits { + 8 => 1u64, + 16 => 2, + b => return Err(format!("unsupported tip depth {b}")), + }; + let want = n * bytes_per; + // One byte beyond the declared size detects overlong output, without allocating for + // an attacker-controlled expansion. Require the zlib trailer, not merely enough samples. + let mut raw = Vec::with_capacity(want as usize + 1); + let status = flate2::Decompress::new(true) + .decompress_vec(&bytes[TIP_HEADER..], &mut raw, flate2::FlushDecompress::Finish) + .map_err(|e| format!("tip data: {e}"))?; + if status != flate2::Status::StreamEnd { + return Err("tip data: truncated or oversized zlib stream".into()); + } + if raw.len() as u64 != want { + return Err(format!("tip data has {} bytes, expected {want}", raw.len())); + } + let data: Vec = if bits == 8 { + raw.iter().map(|&v| u16::from(v) * 257).collect() + } else { + raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect() + }; + Ok(Tip { width: w, height: h, data }) +} diff --git a/crates/pcraft-format/tests/tip.rs b/crates/pcraft-format/tests/tip.rs new file mode 100644 index 0000000000..e54b44ac82 --- /dev/null +++ b/crates/pcraft-format/tests/tip.rs @@ -0,0 +1,58 @@ +use craft_pcraft_format::tip::{MAX_SAMPLES, MAX_SIDE, decode, decode_with_max_side, encode}; +use std::io::Write; + +fn fixture(bits: u8, width: u32, height: u32, samples: &[u8]) -> Vec { + let mut out = b"PCTIP1".to_vec(); + out.push(bits); + out.extend(width.to_le_bytes()); + out.extend(height.to_le_bytes()); + let mut z = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(3)); + z.write_all(samples).unwrap(); + z.finish().unwrap() +} + +#[test] +fn legacy_eight_and_sixteen_bit_fixtures_and_roundtrips() { + for (bits, raw, samples) in [(8, vec![0, 128, 255], vec![0, 32896, 65535]), (16, vec![1, 0, 52, 18, 255, 255], vec![1, 0x1234, 65535])] { + let legacy = fixture(bits, 3, 1, &raw); + let tip = decode(&legacy).unwrap(); + assert_eq!((tip.width, tip.height), (3, 1)); + assert_eq!(tip.data, samples); + let encoded = encode(3, 1, &samples); + assert_eq!(&encoded[..15], &legacy[..15]); + assert_eq!(decode(&encoded).unwrap(), tip); + } +} + +#[test] +fn checks_headers_limits_and_sample_lengths() { + let good = fixture(8, 1, 1, &[255]); + for n in 0..good.len() { + assert!(decode(&good[..n]).is_err(), "truncation at {n}"); + } + let mut bad = good.clone(); + bad[0] = b'X'; + assert!(decode(&bad).is_err()); + for (bits, w, h) in [(7, 1, 1), (8, 0, 1), (8, 1, 0), (8, MAX_SIDE + 1, 1), (8, MAX_SIDE, MAX_SIDE)] { + assert!(decode(&fixture(bits, w, h, &[])).is_err()); + } + assert!(MAX_SAMPLES < u64::from(MAX_SIDE) * u64::from(MAX_SIDE)); + for raw in [vec![], vec![0, 1], vec![0; 10000]] { + assert!(decode(&fixture(8, 1, 1, &raw)).is_err()); + } + assert!(decode(&fixture(16, 1, 1, &[1])).is_err()); + let mut checksum = good; + *checksum.last_mut().unwrap() ^= 1; + assert!(decode(&checksum).is_err()); + assert!(encode(0, 1, &[]).is_empty()); + assert!(encode(1, 1, &[]).is_empty()); + assert!(encode(MAX_SIDE + 1, 1, &[0]).is_empty()); +} + +#[test] +fn preview_side_limit_is_checked_before_inflation() { + let good = encode(2, 1, &[0, 65535]); + assert!(decode_with_max_side(&good, 1).is_err()); + assert!(decode_with_max_side(&good, 2).is_ok()); + assert!(decode_with_max_side(&good, 0).is_err()); +} diff --git a/crates/plist/Cargo.toml b/crates/plist/Cargo.toml new file mode 100644 index 0000000000..7ae95aae09 --- /dev/null +++ b/crates/plist/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-plist" +description = "Bounded cross-platform binary Apple property-list reader" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror.workspace = true diff --git a/crates/plist/LICENSE-APACHE b/crates/plist/LICENSE-APACHE new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/crates/plist/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/crates/plist/LICENSE-MIT b/crates/plist/LICENSE-MIT new file mode 100644 index 0000000000..8e63994018 --- /dev/null +++ b/crates/plist/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/plist/README.md b/crates/plist/README.md new file mode 100644 index 0000000000..dc5c520079 --- /dev/null +++ b/crates/plist/README.md @@ -0,0 +1,11 @@ +# craft-plist + +A cross-platform bounded binary (`bplist00`) reader, extracted from Craft Anything's existing implementation and hardening history. Typed dictionaries retain order and duplicate keys; `get` returns the first match. Strings retain the source reader's lossy decoding policy. Shared references expand under node and decoded-byte budgets, and cycles are rejected. + +`parse_binary_with_limits` accepts explicit input, object, expanded-node, nesting and decoded-byte limits. Recursion always has a hard ceiling of 256 even if a caller supplies a larger depth. Counts are checked before container reservation; allocations can return a resource error. Limits are per parse, not a promise of a precise process RSS cap. + +This first PR contains reading only. XML parsing/writing and keyed-archive interpretation are not implemented. JSON projection, date formatting, OS file access and preference/locale selection are not part of this crate. Existing updater/Photo streaming `plist` users remain unchanged. + +Initial consumers: PhotoCraft's AppleLanguages binary-reader path; later Craft Anything binary parsing and LightCraft XML presets (after XML support/parity). Photo must retain its 4 MiB input policy and first-language selection. + +Source: `storytold/craft-anything` at `88d1d9cac852aec1c7fd97886db451e005e49d2a`, `crates/formats/src/plist.rs` and checked byte reader. Source license files retained. Imported changes retain Brandon Thomas, BFlat, RRFZ and Afloat as primary Git authors; imported regression tests are BFlat's. No external specification implementation copied. diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs new file mode 100644 index 0000000000..3fe6aed926 --- /dev/null +++ b/crates/plist/src/binary.rs @@ -0,0 +1,391 @@ +use crate::{FormatError, Limits, bytes::Reader}; + +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + Dict(Vec<(String, Value)>), + Array(Vec), + String(String), + Integer(i128), + Real(f64), + Bool(bool), + /// Seconds since 2001-01-01T00:00:00Z (binary), or the ISO text (XML). + Date(DateValue), + Data(Vec), + /// A keyed-archive object reference. + Uid(u64), + Null, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DateValue { + Seconds(f64), + Text(String), +} + +impl Value { + pub fn get(&self, key: &str) -> Option<&Value> { + match self { + Value::Dict(d) => d.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::String(s) => Some(s), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(a) => Some(a), + _ => None, + } + } + + pub fn as_uid(&self) -> Option { + match self { + Value::Uid(u) => Some(*u), + _ => None, + } + } + + pub fn as_int(&self) -> Option { + match self { + Value::Integer(i) => Some(*i), + _ => None, + } + } +} +struct Bin<'a> { + r: Reader<'a>, + offsets: Vec, + ref_size: usize, + nodes: usize, + /// Data and text bytes still allowed to be copied out. + bytes_left: usize, + limits: Limits, +} + +/// Parse a `bplist00` binary property list. +pub fn parse_binary(data: &[u8]) -> Result { + parse_binary_with_limits(data, Limits::default()) +} + +/// Parse a binary property list, with caller-selected input, object, expansion and nesting limits. +pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result { + let (mut b, top) = reader(data, limits)?; + let mut stack = reserved(limits.max_depth.min(256))?; + b.object(top, &mut stack) +} + +fn reader(data: &[u8], limits: Limits) -> Result<(Bin<'_>, usize), FormatError> { + if data.len() > limits.max_input_bytes { + return Err(FormatError::TooLarge("input bytes".into())); + } + if !data.starts_with(b"bplist") { + return Err(FormatError::Malformed("not a binary plist".into())); + } + if !data.starts_with(b"bplist00") { + return Err(FormatError::Unsupported("unknown binary plist version".into())); + } + let len = data.len(); + if len < 8 + 32 { + return Err(FormatError::Truncated("binary plist trailer".into())); + } + let r = Reader::new(data); + let t = len - 32; + let off_size = usize::from(r.u8(t + 6).unwrap_or(0)); + let ref_size = usize::from(r.u8(t + 7).unwrap_or(0)); + let num = r.u64_be(t + 8).unwrap_or(0); + let top = r.u64_be(t + 16).unwrap_or(0); + let table = r.u64_be(t + 24).unwrap_or(0); + if !(1..=8).contains(&off_size) || !(1..=8).contains(&ref_size) { + return Err(FormatError::Malformed("bad offset or reference size".into())); + } + let num = usize::try_from(num).map_err(|_| FormatError::Malformed("object count".into()))?; + let table = usize::try_from(table).map_err(|_| FormatError::Malformed("offset table".into()))?; + if num == 0 || num > len { + return Err(FormatError::Malformed(format!("{num} objects in a {len}-byte file"))); + } + if num > limits.max_objects { + return Err(FormatError::TooLarge("object count".into())); + } + let need = num.checked_mul(off_size).and_then(|n| n.checked_add(table)).ok_or_else(|| FormatError::Malformed("offset table".into()))?; + if need > t || table < 8 { + return Err(FormatError::Truncated("offset table runs past the trailer".into())); + } + let mut offsets = reserved(num)?; + for i in 0..num { + let o = read_be(&r, table + i * off_size, off_size).ok_or_else(|| FormatError::Truncated("offset table".into()))?; + let o = usize::try_from(o).map_err(|_| FormatError::Malformed("object offset".into()))?; + if o < 8 || o >= table { + return Err(FormatError::Malformed(format!("object {i} lies outside the object area"))); + } + offsets.push(o); + } + let top = usize::try_from(top).map_err(|_| FormatError::Malformed("top object".into()))?; + // Object payloads and references must not borrow bytes from the offset table or trailer. + let objects = data.get(..table).ok_or_else(|| FormatError::Truncated("object area".into()))?; + let b = Bin { r: Reader::new(objects), offsets, ref_size, nodes: 0, bytes_left: limits.max_expanded_bytes, limits }; + Ok((b, top)) +} + +fn read_be(r: &Reader<'_>, off: usize, n: usize) -> Option { + let s = r.slice(off, n)?; + Some(s.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) +} + +/// UTF-8 size of `String::from_utf8_lossy(bytes)`: each damaged sequence becomes a U+FFFD. +fn lossy_utf8_len(bytes: &[u8]) -> usize { + bytes.utf8_chunks().fold(0usize, |n, c| { + let replacement = if c.invalid().is_empty() { 0 } else { char::REPLACEMENT_CHARACTER.len_utf8() }; + n.saturating_add(c.valid().len()).saturating_add(replacement) + }) +} + +/// UTF-8 size of `String::from_utf16_lossy` over big-endian code units: a lone surrogate becomes +/// a U+FFFD. +fn lossy_utf16_len(bytes: &[u8]) -> usize { + let units = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); + char::decode_utf16(units).fold(0usize, |n, c| n.saturating_add(c.map_or(char::REPLACEMENT_CHARACTER.len_utf8(), char::len_utf8))) +} + +impl Bin<'_> { + fn count(&self, at: usize, low: u8) -> Result<(usize, usize), FormatError> { + if low != 0xf { + return Ok((usize::from(low), at + 1)); + } + let m = self.r.u8(at + 1).ok_or_else(|| FormatError::Truncated("length".into()))?; + if m & 0xf0 != 0x10 { + return Err(FormatError::Malformed("bad extended length marker".into())); + } + if m & 0x0f > 3 { + return Err(FormatError::Malformed("extended length width exceeds 64 bits".into())); + } + let n = 1usize << (m & 0x0f); + let v = read_be(&self.r, at + 2, n).ok_or_else(|| FormatError::Truncated("length".into()))?; + let v = usize::try_from(v).map_err(|_| FormatError::Malformed("length".into()))?; + Ok((v, at + 2 + n)) + } + + fn reference(&self, at: usize, i: usize) -> Result { + let off = i.checked_mul(self.ref_size).and_then(|x| x.checked_add(at)).ok_or_else(|| FormatError::Malformed("reference".into()))?; + let v = read_be(&self.r, off, self.ref_size).ok_or_else(|| FormatError::Truncated("object reference".into()))?; + usize::try_from(v).map_err(|_| FormatError::Malformed("reference".into())) + } + + /// Refuse a container whose `children` would pass the node limit, before space is reserved for them. + fn room_for_nodes(&self, children: usize) -> Result<(), FormatError> { + if children > self.limits.max_nodes.saturating_sub(self.nodes) { + return Err(FormatError::TooLarge("expanded node count".into())); + } + Ok(()) + } + + /// Spend `n` bytes of the data and text budget before copying them out. + fn spend(&mut self, n: usize) -> Result<(), FormatError> { + self.bytes_left = + self.bytes_left.checked_sub(n).ok_or_else(|| FormatError::TooLarge("repeated data and text expand past the plist byte budget".into()))?; + Ok(()) + } + + /// Read object `idx`. `stack` holds the containers on the current path, so a cycle is refused. + fn object(&mut self, idx: usize, stack: &mut Vec) -> Result { + self.nodes += 1; + if self.nodes > self.limits.max_nodes { + return Err(FormatError::TooLarge("expanded node count".into())); + } + if stack.len() >= self.limits.max_depth.min(256) { + return Err(FormatError::Malformed("nesting too deep".into())); + } + if stack.contains(&idx) { + return Err(FormatError::Malformed(format!("object {idx} contains itself"))); + } + let at = *self.offsets.get(idx).ok_or_else(|| FormatError::Malformed(format!("reference to missing object {idx}")))?; + let m = self.r.u8(at).ok_or_else(|| FormatError::Truncated("object marker".into()))?; + let (hi, lo) = (m >> 4, m & 0x0f); + let v = match hi { + 0x0 => match lo { + 0x0 => Value::Null, + 0x8 => Value::Bool(false), + 0x9 => Value::Bool(true), + _ => return Err(FormatError::Malformed(format!("unknown simple plist object {m:#04x}"))), + }, + 0x1 => { + if lo > 4 { + return Err(FormatError::Malformed("integer width exceeds 128 bits".into())); + } + let n = 1usize << lo; + let bytes = self.r.slice(at + 1, n).ok_or_else(|| FormatError::Truncated("integer".into()))?; + let v = match n { + 8 => i128::from(i64::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?)), + 16 => i128::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?), + _ => i128::from(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))), + }; + Value::Integer(v) + } + 0x2 => { + let v = match lo { + 2 => self.r.u32_be(at + 1).map(|b| f64::from(f32::from_bits(b))), + 3 => self.r.u64_be(at + 1).map(f64::from_bits), + _ => None, + }; + Value::Real(v.ok_or_else(|| FormatError::Truncated("real".into()))?) + } + 0x3 if lo == 3 => { + Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)) + } + 0x4 => { + let (n, s) = self.count(at, lo)?; + let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?; + self.spend(bytes.len())?; + { + let mut out = reserved(bytes.len())?; + out.extend_from_slice(bytes); + Value::Data(out) + } + } + 0x5 => { + let (n, s) = self.count(at, lo)?; + let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?; + let size = lossy_utf8_len(bytes); + self.spend(size)?; + let mut out = reserved_string(size)?; + for chunk in bytes.utf8_chunks() { + out.push_str(chunk.valid()); + if !chunk.invalid().is_empty() { + out.push(char::REPLACEMENT_CHARACTER); + } + } + Value::String(out) + } + 0x6 => { + let (n, s) = self.count(at, lo)?; + let bytes = self + .r + .slice(s, n.checked_mul(2).ok_or_else(|| FormatError::Malformed("string".into()))?) + .ok_or_else(|| FormatError::Truncated("string".into()))?; + let size = lossy_utf16_len(bytes); + self.spend(size)?; + let mut out = reserved_string(size)?; + let units = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); + for ch in char::decode_utf16(units) { + out.push(ch.unwrap_or(char::REPLACEMENT_CHARACTER)); + } + Value::String(out) + } + 0x8 => { + if lo > 7 { + return Err(FormatError::Malformed("uid width exceeds 64 bits".into())); + } + let n = usize::from(lo) + 1; + Value::Uid(read_be(&self.r, at + 1, n).ok_or_else(|| FormatError::Truncated("uid".into()))?) + } + 0xa | 0xc => { + let (n, s) = self.count(at, lo)?; + // Writers store equal values once, so an array may name one object many times: + // only its references have to fit in the file. the node limit and the byte budget bound + // the expansion. + if s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { + return Err(FormatError::Malformed("array larger than the file".into())); + } + self.room_for_nodes(n)?; + stack.push(idx); + let mut out = reserved(n)?; + for i in 0..n { + let child = self.reference(s, i)?; + out.push(self.object(child, stack)?); + } + stack.pop(); + Value::Array(out) + } + 0xd => { + let (n, s) = self.count(at, lo)?; + if s.saturating_add(n.saturating_mul(self.ref_size).saturating_mul(2)) > self.r.len() { + return Err(FormatError::Malformed("dictionary larger than the file".into())); + } + self.room_for_nodes(n.saturating_mul(2))?; + stack.push(idx); + let mut out = reserved(n)?; + for i in 0..n { + let k = self.reference(s, i)?; + let v = self.reference(s, i + n)?; + let key = match self.object(k, stack)? { + Value::String(s) => s, + _ => return Err(FormatError::Unsupported("non-string dictionary keys cannot be represented in this plist view".into())), + }; + out.push((key, self.object(v, stack)?)); + } + stack.pop(); + Value::Dict(out) + } + _ => return Err(FormatError::Malformed(format!("unknown object marker {m:#04x}"))), + }; + Ok(v) + } +} + +fn reserved(n: usize) -> Result, FormatError> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| FormatError::TooLarge("allocation".into()))?; + Ok(v) +} + +fn reserved_string(n: usize) -> Result { + let mut s = String::new(); + s.try_reserve_exact(n).map_err(|_| FormatError::TooLarge("string allocation".into()))?; + Ok(s) +} + +/// Select the first string in one top-level dictionary array without expanding unrelated values. +/// First matching dictionary key wins. Missing/wrong-typed values return `None`; malformed +/// selected objects and resource exhaustion return errors. Unselected value graphs are not +/// validated. This permits preference readers to ignore unrelated future object kinds. +pub fn first_string_in_array(data: &[u8], key: &str, limits: Limits) -> Result, FormatError> { + let (mut b, top) = reader(data, limits)?; + let (kind, n, start) = b.header(top)?; + if kind != 0xd { + return Ok(None); + } + if n > limits.max_nodes { + return Err(FormatError::TooLarge("dictionary lookup entries".into())); + } + let bytes = n.checked_mul(2).and_then(|n| n.checked_mul(b.ref_size)).ok_or_else(|| FormatError::Malformed("dictionary references".into()))?; + b.r.slice(start, bytes).ok_or_else(|| FormatError::Truncated("dictionary references".into()))?; + for i in 0..n { + let k = b.reference(start, i)?; + if b.selected_string(k)?.as_deref() != Some(key) { + continue; + } + let value = b.reference(start, n + i)?; + let (kind, count, payload) = b.header(value)?; + if kind != 0xa || count == 0 { + return Ok(None); + } + let first = b.reference(payload, 0)?; + return b.selected_string(first); + } + Ok(None) +} +impl Bin<'_> { + fn header(&self, idx: usize) -> Result<(u8, usize, usize), FormatError> { + let at = *self.offsets.get(idx).ok_or_else(|| FormatError::Malformed("missing object".into()))?; + let marker = self.r.u8(at).ok_or_else(|| FormatError::Truncated("object marker".into()))?; + let kind = marker >> 4; + // Only containers and strings use an extended length. Unknown types are not traversed. + let (n, start) = if matches!(kind, 0x5 | 0x6 | 0xa | 0xd) { self.count(at, marker & 15)? } else { (usize::from(marker & 15), at + 1) }; + Ok((kind, n, start)) + } + fn selected_string(&mut self, idx: usize) -> Result, FormatError> { + let (kind, _, _) = self.header(idx)?; + if !matches!(kind, 0x5 | 0x6) { + return Ok(None); + } + match self.object(idx, &mut Vec::new())? { + Value::String(s) => Ok(Some(s)), + _ => Ok(None), + } + } +} diff --git a/crates/plist/src/bytes.rs b/crates/plist/src/bytes.rs new file mode 100644 index 0000000000..bdfecc668b --- /dev/null +++ b/crates/plist/src/bytes.rs @@ -0,0 +1,37 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u32_be(&self, off: usize) -> Option { + self.arr(off).map(u32::from_be_bytes) + } + + pub fn u64_be(&self, off: usize) -> Option { + self.arr(off).map(u64::from_be_bytes) + } +} diff --git a/crates/plist/src/lib.rs b/crates/plist/src/lib.rs new file mode 100644 index 0000000000..f3af79ddcb --- /dev/null +++ b/crates/plist/src/lib.rs @@ -0,0 +1,33 @@ +//! Bounded binary Apple property lists, independent of operating-system preferences. +//! XML and writing are intentionally not implemented in this first extraction. +//! File discovery, locale selection, bundle validation and application policy stay in callers. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod binary; +mod bytes; +pub use binary::{DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits}; + +/// Caller-selected resource limits. Zero values refuse the corresponding resource. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub max_input_bytes: usize, + pub max_objects: usize, + pub max_nodes: usize, + pub max_depth: usize, + pub max_expanded_bytes: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { max_input_bytes: 16 << 20, max_objects: 100_000, max_nodes: 100_000, max_depth: 64, max_expanded_bytes: 64 << 20 } + } +} +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("malformed property list: {0}")] + Malformed(String), + #[error("truncated property list: {0}")] + Truncated(String), + #[error("unsupported property list: {0}")] + Unsupported(String), + #[error("property list resource limit: {0}")] + TooLarge(String), +} diff --git a/crates/plist/tests/limits.rs b/crates/plist/tests/limits.rs new file mode 100644 index 0000000000..dc18826980 --- /dev/null +++ b/crates/plist/tests/limits.rs @@ -0,0 +1,75 @@ +use craft_plist::{Limits, Value, parse_binary, parse_binary_with_limits}; +fn plist(objects: &[&[u8]]) -> Vec { + let mut b = b"bplist00".to_vec(); + let mut offsets = Vec::new(); + for obj in objects { + offsets.push(b.len() as u8); + b.extend_from_slice(obj); + } + let table = b.len() as u64; + b.extend_from_slice(&offsets); + b.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + b.extend_from_slice(&(objects.len() as u64).to_be_bytes()); + b.extend_from_slice(&0u64.to_be_bytes()); + b.extend_from_slice(&table.to_be_bytes()); + b +} +#[test] +fn languages_and_every_truncation() { + let b = plist(&[&[0xd1, 1, 2], b"\x5eAppleLanguages", &[0xa1, 3], b"\x55ja-JP"]); + let p = parse_binary(&b).unwrap(); + assert_eq!(p.get("AppleLanguages").unwrap().as_array().unwrap()[0].as_str(), Some("ja-JP")); + for n in 0..b.len() { + assert!(parse_binary(&b[..n]).is_err(), "prefix {n}"); + } +} +#[test] +fn cycles_and_repeated_references() { + assert!(parse_binary(&plist(&[&[0xa1, 0]])).is_err()); + let b = plist(&[&[0xa3, 1, 1, 1], b"\x51x"]); + assert_eq!(parse_binary(&b).unwrap(), Value::Array(vec![Value::String("x".into()); 3])); + assert!(parse_binary_with_limits(&b, Limits { max_nodes: 3, ..Limits::default() }).is_err()); + assert!(parse_binary_with_limits(&b, Limits { max_expanded_bytes: 2, ..Limits::default() }).is_err()); +} +#[test] +fn explicit_limits_and_version() { + let b = plist(&[&[0xa1, 1], b"\x51x"]); + for l in [ + Limits { max_input_bytes: b.len() - 1, ..Limits::default() }, + Limits { max_objects: 1, ..Limits::default() }, + Limits { max_depth: 1, ..Limits::default() }, + Limits { max_nodes: 0, ..Limits::default() }, + ] { + assert!(parse_binary_with_limits(&b, l).is_err()); + } + let mut future = b; + future[7] = b'1'; + assert!(parse_binary(&future).is_err()); +} +#[test] +fn utf16_and_lossy_expansion_spend_budget() { + let b = plist(&[&[0x62, 0xd8, 0x3d, 0xde, 0x00]]); + assert_eq!(parse_binary(&b).unwrap().as_str(), Some("😀")); + assert!(parse_binary_with_limits(&b, Limits { max_expanded_bytes: 3, ..Limits::default() }).is_err()); + let bad = plist(&[&[0x51, 0xff]]); + assert_eq!(parse_binary(&bad).unwrap().as_str(), Some("�")); + assert!(parse_binary_with_limits(&bad, Limits { max_expanded_bytes: 2, ..Limits::default() }).is_err()); +} + +#[test] +fn selective_lookup_ignores_unrelated_graphs_and_preserves_first_match() { + use craft_plist::first_string_in_array; + let b = plist(&[&[0xd2, 1, 2, 3, 4], b"\x55Other", b"\x5eAppleLanguages", &[0xaf], &[0xa2, 5, 6], b"\x55ja-JP", &[0xff]]); + assert!(parse_binary(&b).is_err()); + assert_eq!(first_string_in_array(&b, "AppleLanguages", Limits::default()).unwrap().as_deref(), Some("ja-JP")); + let duplicate = plist(&[&[0xd2, 1, 1, 2, 3], b"\x5eAppleLanguages", &[0xa1, 4], &[0xa1, 5], b"\x55zh-TW", b"\x55ko-KR"]); + assert_eq!(first_string_in_array(&duplicate, "AppleLanguages", Limits::default()).unwrap().as_deref(), Some("zh-TW")); + assert!(first_string_in_array(&b, "AppleLanguages", Limits { max_expanded_bytes: 1, ..Limits::default() }).is_err()); +} + +#[test] +fn selective_lookup_requires_an_array_not_a_set() { + use craft_plist::first_string_in_array; + let b = plist(&[&[0xd1, 1, 2], b"\x5eAppleLanguages", &[0xc1, 3], b"\x55ja-JP"]); + assert_eq!(first_string_in_array(&b, "AppleLanguages", Limits::default()).unwrap(), None); +} diff --git a/crates/plist/tests/plist_marker_widths.rs b/crates/plist/tests/plist_marker_widths.rs new file mode 100644 index 0000000000..5873371e76 --- /dev/null +++ b/crates/plist/tests/plist_marker_widths.rs @@ -0,0 +1,47 @@ +use craft_plist::{Value, parse_binary}; + +fn single_object(object: &[u8]) -> Vec { + let mut data = b"bplist00".to_vec(); + data.extend_from_slice(object); + let table = data.len() as u64; + data.push(8); + data.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + data.extend_from_slice(&1u64.to_be_bytes()); + data.extend_from_slice(&0u64.to_be_bytes()); + data.extend_from_slice(&table.to_be_bytes()); + data +} + +#[test] +fn unsupported_integer_widths_are_not_clamped() { + for marker in 0x15..=0x1f { + let mut object = vec![marker]; + object.extend_from_slice(&[0; 16]); + assert!(parse_binary(&single_object(&object)).is_err(), "accepted {marker:#x}"); + } +} + +#[test] +fn extended_lengths_and_uids_do_not_lose_high_bytes() { + let mut length = vec![0x4f, 0x14]; + length.extend_from_slice(&[0; 16]); + assert!(parse_binary(&single_object(&length)).is_err()); + for marker in 0x88..=0x8f { + let mut object = vec![marker, 1]; + object.resize(usize::from(marker & 15) + 2, 0); + assert!(parse_binary(&single_object(&object)).is_err(), "accepted {marker:#x}"); + } +} + +#[test] +fn supported_maximum_widths_keep_their_values() { + let mut integer = vec![0x14]; + integer.extend_from_slice(&i128::MAX.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&integer)), Ok(Value::Integer(i)) if i == i128::MAX)); + let mut uid = vec![0x87]; + uid.extend_from_slice(&u64::MAX.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&uid)), Ok(Value::Uid(i)) if i == u64::MAX)); + let mut empty = vec![0x4f, 0x13]; + empty.extend_from_slice(&0u64.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&empty)), Ok(Value::Data(d)) if d.is_empty())); +} diff --git a/crates/plist/tests/plist_object_bounds.rs b/crates/plist/tests/plist_object_bounds.rs new file mode 100644 index 0000000000..d35fd91b13 --- /dev/null +++ b/crates/plist/tests/plist_object_bounds.rs @@ -0,0 +1,31 @@ +use craft_plist::{Value, parse_binary}; + +fn single_object(object: &[u8], offset: u8) -> Vec { + let mut data = b"bplist00".to_vec(); + data.extend_from_slice(object); + let table = data.len() as u64; + data.push(offset); + data.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + data.extend_from_slice(&1u64.to_be_bytes()); + data.extend_from_slice(&0u64.to_be_bytes()); + data.extend_from_slice(&table.to_be_bytes()); + data +} + +#[test] +fn binary_values_cannot_consume_the_offset_table_or_trailer() { + for object in [&[0x54, b'x'][..], &[0x43, 0x42], &[0x13], &[0x87], &[0x62, 0, b'x']] { + assert!(parse_binary(&single_object(object, 8)).is_err(), "accepted object {object:02x?}"); + } +} + +#[test] +fn binary_offsets_cannot_point_inside_the_file_header() { + assert!(parse_binary(&single_object(&[0x00], 0)).is_err()); + assert!(matches!(parse_binary(&single_object(&[0x00], 8)), Ok(Value::Null))); +} + +#[test] +fn objects_ending_at_the_table_boundary_are_valid() { + assert!(matches!(parse_binary(&single_object(&[0x51, b'x'], 8)), Ok(Value::String(s)) if s == "x")); +} diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index fca9d4a64b..7d4229f373 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -35,8 +35,9 @@ workspace = true # ticket (winprint.rs#12, storytold/pdfcraft#3823), and reads whitespace-padded integers in # PrintCapabilities (winprint.rs#3, storytold/pdfcraft#2430). Pinned to an immutable revision; # review before bumping. The settings chosen in a driver's own dialog become a ticket through -# `PrintTicket::from_dev_mode`. -winprint = { git = "https://github.com/storytold/winprint.rs", rev = "72951d7455ebcab569fbd9386c513d3d9f53fb02", default-features = false } +# `PrintTicket::from_dev_mode` (winprint.rs#24, pinned at its merge commit on winprint.rs's +# `main`). +winprint = { git = "https://github.com/storytold/winprint.rs", rev = "8ae097ef941b432b0e7671b1ec3a506800e65e57", default-features = false } # GetDefaultPrinter (MIT). winsafe = { version = "0.0.29", default-features = false, features = ["winspool"] } # The job file's private folder. diff --git a/crates/print/src/cups/mod.rs b/crates/print/src/cups/mod.rs new file mode 100644 index 0000000000..1a0a9360b7 --- /dev/null +++ b/crates/print/src/cups/mod.rs @@ -0,0 +1,955 @@ +//! Based on the direct CUPS transport from contributor PR #156 (ahmedhosnypro), +//! kept separate from the broader network-printing registry in PR #116. +//! IPP/1.1 straight to the local CUPS server: printer discovery (`CUPS-Get-Printers`, +//! `CUPS-Get-Default`) and job submission (`Print-Job`) over HTTP/1.1, for when `lpstat`/`lp` +//! are missing (a sandboxed install, where the print dialog would otherwise have no printers). +//! Implemented from the public IPP encoding (RFC 2910/8010) and semantics (RFC 8011) and +//! CUPS's IPP documentation; the scheduler is reached on its socket or selected TCP endpoint. +//! +//! # Blocking and authorization +//! The caller authorizes endpoint selection. The absolute exchange deadline covers all request +//! writes and reply reads **after connection**. Standard-library DNS resolution and Unix socket +//! connection are blocking OS calls outside that deadline. TCP connection attempts have their +//! own timeout. This is not a whole-operation deadline API: do not call it on a UI thread or +//! promise bounded completion for arbitrary named hosts/Unix listeners. No detached timeout +//! thread is spawned; callers needing cancellation must supply a separately bounded transport. + +#[cfg(all(test, unix))] +mod tests; + +use super::{Duplex, Error, Job, Printer, Scaling}; +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; +#[cfg(unix)] +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant}; + +/// Where the local scheduler listens: its socket, else its loopback port. +const CUPS_SOCKET: &str = "/run/cups/cups.sock"; + +/// Caps on what the server may hand back: a reply is read into memory before it is parsed. +const MAX_BODY: usize = 1 << 20; +const MAX_HEADERS: usize = 8 << 10; +const MAX_PRINTERS: usize = 256; +const MAX_NAME: usize = 256; +/// A job's title on the wire; IPP values are u16-length, and no real title is this long. +const MAX_JOB_NAME: usize = 255; + +/// A wedged scheduler must not hang the dialog; a job may carry megabytes and is given longer. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(1); +const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(2); +const JOB_TIMEOUT: Duration = Duration::from_secs(30); + +/// IPP operation codes: the standard Print-Job, and CUPS's discovery extensions. +const OPERATION_PRINT_JOB: u16 = 0x0002; +const OPERATION_CUPS_GET_DEFAULT: u16 = 0x4001; +const OPERATION_CUPS_GET_PRINTERS: u16 = 0x4002; + +/// IPP value tags and group delimiters (RFC 8010 §5.1); the ones this client sends or reads. +const GROUP_OPERATION: u8 = 0x01; +const GROUP_JOB: u8 = 0x02; +const GROUP_END: u8 = 0x03; +const GROUP_PRINTER: u8 = 0x04; +const TAG_INTEGER: u8 = 0x21; +const TAG_BOOLEAN: u8 = 0x22; +const TAG_NAME: u8 = 0x42; +const TAG_KEYWORD: u8 = 0x44; +const TAG_URI: u8 = 0x45; +const TAG_CHARSET: u8 = 0x47; +const TAG_LANGUAGE: u8 = 0x48; +const TAG_MIME: u8 = 0x49; + +static REQUEST_ID: AtomicU32 = AtomicU32::new(1); + +/// How the scheduler is reached: its unix socket, else its loopback port. +#[derive(Clone, Debug)] +pub enum Server { + Unix(PathBuf), + Tcp(SocketAddr), + /// A caller-authorized host. DNS is resolved once for each connection attempt. + Named(String, u16), +} + +impl Server { + /// Parse an explicitly selected CUPS_SERVER value, without connecting. No URLs, + /// credentials, control characters or HTTP authority delimiters are accepted. + pub fn parse(value: &str) -> Result { + if value.starts_with('/') { + return Ok(Self::Unix(value.into())); + } + if value.is_empty() || value.len() > 255 || value.bytes().any(|c| c.is_ascii_control() || c.is_ascii_whitespace() || b"/@?#\\".contains(&c)) { + return Err(Error::Spool("invalid CUPS server".into())); + } + let (host, port) = if let Some(rest) = value.strip_prefix('[') { + let (host, tail) = rest.split_once(']').ok_or_else(|| Error::Spool("invalid CUPS IPv6 host".into()))?; + if !host.contains(':') { + return Err(Error::Spool("bracketed CUPS host must be IPv6".into())); + } + let port = if tail.is_empty() { + 631 + } else { + tail.strip_prefix(':') + .and_then(|p| p.parse::().ok()) + .filter(|p| *p != 0) + .ok_or_else(|| Error::Spool("invalid CUPS port".into()))? + }; + (host, port) + } else if value.matches(':').count() > 1 { + // A bare IPv6 address is a host. A colon after its scope name may + // specify a port without cutting an address hextet in half. + if let Some((_, zone)) = value.split_once('%') + && zone.contains(':') + { + let (host, port) = value.rsplit_once(':').ok_or_else(|| Error::Spool("invalid CUPS endpoint".into()))?; + (host, port.parse::().ok().filter(|p| *p != 0).ok_or_else(|| Error::Spool("invalid CUPS port".into()))?) + } else { + (value, 631) + } + } else { + match value.rsplit_once(':') { + Some((host, port)) => (host, port.parse::().ok().filter(|p| *p != 0).ok_or_else(|| Error::Spool("invalid CUPS port".into()))?), + None => (value, 631), + } + }; + if host.is_empty() || host.contains(['[', ']']) { + return Err(Error::Spool("invalid CUPS host".into())); + } + if let Ok(ip) = host.parse::() { + return Ok(Self::Tcp(SocketAddr::new(ip, port))); + } + if host.contains(':') { + let (ip, zone) = host.split_once('%').ok_or_else(|| Error::Spool("invalid CUPS IPv6 host".into()))?; + if ip.parse::().is_err() + || zone.is_empty() + || !zone.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) + { + return Err(Error::Spool("invalid CUPS IPv6 scope".into())); + } + } else if host.contains('%') { + return Err(Error::Spool("invalid CUPS host".into())); + } + Ok(Self::Named(host.into(), port)) + } + + fn authority(&self) -> String { + match self { + Self::Unix(_) => "localhost".into(), + Self::Tcp(addr) => addr.to_string().replace('%', "%25"), + Self::Named(host, port) if host.contains(':') => format!("[{}]:{port}", host.replace('%', "%25")), + Self::Named(host, port) => format!("{host}:{port}"), + } + } +} + +/// Local scheduler candidates, honoring the user's explicit CUPS_SERVER setting. +/// No requests are made by this function; apps must authorize selection before use. +pub fn configured_servers() -> Result, Error> { + if let Some(value) = std::env::var_os("CUPS_SERVER").filter(|v| !v.is_empty()) { + return Ok(vec![Server::parse(&value.to_string_lossy())?]); + } + Ok(vec![ + Server::Unix(CUPS_SOCKET.into()), + Server::Unix("/var/run/cups/cups.sock".into()), + Server::Unix("/private/var/run/cupsd".into()), + Server::Tcp(([127, 0, 0, 1], 631).into()), + ]) +} + +fn endpoints() -> [Server; 2] { + [Server::Unix(PathBuf::from(CUPS_SOCKET)), Server::Tcp(([127, 0, 0, 1], 631).into())] +} + +/// Whether the local CUPS server is reachable: its socket, else its loopback port. A missing +/// scheduler is a normal `false`, not an error. +pub fn cups_reachable() -> bool { + endpoints().iter().any(reachable) +} + +/// Probe a caller-authorized endpoint without sending a print request. +/// DNS and Unix connect have the blocking limitations documented on this module. +pub fn reachable(server: &Server) -> bool { + connect(server).is_ok() +} + +fn connect(server: &Server) -> std::io::Result { + match server { + #[cfg(unix)] + Server::Unix(path) => UnixStream::connect(path).map(Stream::Unix), + #[cfg(not(unix))] + Server::Unix(_) => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "Unix sockets unavailable")), + Server::Named(host, port) => { + // Validate even directly constructed public variants before resolving or writing headers. + let endpoint = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; + let parsed = Server::parse(&endpoint).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?; + if matches!(parsed, Server::Unix(_)) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "a named CUPS host cannot be a Unix path")); + } + let addr = (host.as_str(), *port) + .to_socket_addrs()? + .next() + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "CUPS host has no address"))?; + TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map(Stream::Tcp) + } + // A loopback connect either answers promptly or the server is not there. + Server::Tcp(addr) => TcpStream::connect_timeout(addr, CONNECT_TIMEOUT).map(|s| { + let _ = s.set_nodelay(true); + Stream::Tcp(s) + }), + } +} + +/// A connection to the scheduler. +enum Stream { + #[cfg(unix)] + Unix(UnixStream), + Tcp(TcpStream), +} + +impl Stream { + fn set_timeouts(&self, timeout: Duration) -> std::io::Result<()> { + let (read, write) = match self { + #[cfg(unix)] + Stream::Unix(s) => (s.set_read_timeout(Some(timeout)), s.set_write_timeout(Some(timeout))), + Stream::Tcp(s) => (s.set_read_timeout(Some(timeout)), s.set_write_timeout(Some(timeout))), + }; + read.and(write) + } +} + +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.read(buf), + Stream::Tcp(s) => s.read(buf), + } + } +} + +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.write(buf), + Stream::Tcp(s) => s.write(buf), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + #[cfg(unix)] + Stream::Unix(s) => s.flush(), + Stream::Tcp(s) => s.flush(), + } + } +} + +/// The server's queues (CUPS-Get-Printers) and its default destination (CUPS-Get-Default), for +/// the Print dialog when `lpstat` is missing. A default the queue list lacks is appended, so +/// the dialog always has a selection to restore; a default that cannot be named still leaves +/// the queues usable. +pub fn printers() -> Result, Error> { + printers_at(&endpoints()) +} + +pub fn printers_at(endpoints: &[Server]) -> Result, Error> { + let queues = discover(endpoints, OPERATION_CUPS_GET_PRINTERS)?; + let default = discover(endpoints, OPERATION_CUPS_GET_DEFAULT).ok().and_then(|names| names.into_iter().next()); + let mut printers: Vec = Vec::new(); + for name in queues { + if printers.len() >= MAX_PRINTERS { + break; + } + if !printers.iter().any(|p| p.name == name) { + printers.push(Printer { description: String::new(), default: default.as_deref() == Some(name.as_str()), name, two_sided: None }); + } + } + if let Some(name) = default + && !printers.iter().any(|p| p.name == name) + { + printers.push(Printer { description: String::new(), name, default: true, two_sided: None }); + } + Ok(printers) +} + +/// The printer names a discovery reply carries: every queue (CUPS-Get-Printers), or the default +/// destination (CUPS-Get-Default). +fn discover(endpoints: &[Server], operation: u16) -> Result, Error> { + let reply = post(endpoints, "/", &discovery_request(operation), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if status_ok(parsed.status) { Ok(parsed.names) } else { Err(refused(parsed.status)) } +} + +/// Submit the PDF as a Print-Job to the printer (the job's, else the server's default); the +/// reply is the job message, like `lp` prints it (`request id is Office-12`). The driver's own +/// job options (PPD keywords) are not sent on this path: they have no IPP equivalents without +/// reading the printer's capabilities, which is another request. +pub fn print_job(pdf: &[u8], job: &Job) -> Result { + print_job_at(&endpoints(), pdf, job) +} + +pub(crate) fn print_job_at(endpoints: &[Server], pdf: &[u8], job: &Job) -> Result { + let queue = match &job.printer { + Some(name) => name.clone(), + None => discover(endpoints, OPERATION_CUPS_GET_DEFAULT)? + .into_iter() + .next() + .ok_or_else(|| Error::Spool("the print server has no default printer; choose one in the dialog".into()))?, + }; + if !is_queue_name(&queue) { + return Err(Error::Spool(format!("not a printer name: {queue}"))); + } + let reply = post(endpoints, &format!("/printers/{queue}"), &print_job_request(&queue, pdf, job), JOB_TIMEOUT, false)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + Ok(match parsed.job_id { + Some(id) => format!("request id is {queue}-{id}"), + None => format!("the job was accepted by {queue}"), + }) +} + +/// A queue class can route a job to any member printer. Keep the destination kind +/// explicit rather than guessing it from a name shared by a printer and a class. +#[derive(Clone, Debug)] +pub struct Destination { + pub name: String, + pub is_class: bool, +} + +/// List both printer queues and classes from caller-selected CUPS endpoints. +/// The caller owns endpoint selection/authorization; this API does not discover network hosts. +pub fn destinations_at(endpoints: &[Server]) -> Result, Error> { + let mut out = queues_at(endpoints, false)?; + out.extend(queues_at(endpoints, true)?); + if out.len() > MAX_PRINTERS { + return Err(Error::Spool("too many CUPS destinations".into())); + } + let default = default_at(endpoints)?; + for queue in &mut out { + queue.is_default = default.as_deref() == Some(queue.name.as_str()); + } + Ok(out) +} + +/// List either printer queues or classes, without resolving defaults. Applications can +/// explicitly choose whether an optional class/default query failure should hide otherwise +/// usable printer queues. No error is swallowed here except CUPS's absent/unsupported list. +pub fn queues_at(endpoints: &[Server], is_class: bool) -> Result, Error> { + let operation = if is_class { 0x4005 } else { OPERATION_CUPS_GET_PRINTERS }; + let reply = post(endpoints, "/", &discovery_request(operation), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + if parsed.status == 0x0406 || (is_class && parsed.status == 0x0501) { + return Ok(Vec::new()); + } + return Err(refused(parsed.status)); + } + let mut queues = parsed.queues; + for queue in &mut queues { + queue.is_class = is_class; + } + Ok(queues) +} + +/// The scheduler's default queue; not-found means no default has been configured. +pub fn default_at(endpoints: &[Server]) -> Result, Error> { + let reply = post(endpoints, "/", &discovery_request(OPERATION_CUPS_GET_DEFAULT), DISCOVERY_TIMEOUT, true)?; + let parsed = parse_reply(&reply)?; + if parsed.status == 0x0406 { + return Ok(None); + } + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + Ok(parsed.names.into_iter().next()) +} + +/// Metadata from one CUPS printer group, without losing which fields belong together. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Queue { + pub name: String, + pub info: String, + pub state: u32, + pub accepting_jobs: bool, + pub is_default: bool, + pub is_class: bool, +} +impl Default for Queue { + fn default() -> Self { + Self { name: String::new(), info: String::new(), state: 3, accepting_jobs: true, is_default: false, is_class: false } + } +} + +/// Submit once to an explicitly selected queue/class, returning the numeric server job id. +/// An absent id is an uncertain accepted outcome, not permission to retry the document. +pub fn submit_at(endpoints: &[Server], destination: &Destination, pdf: &[u8], job: &Job) -> Result { + submit_as_at(endpoints, destination, pdf, job, "") +} + +/// As [`submit_at`], with the user name supplied by the application, never inferred from +/// process credentials. Once any request bytes may have been sent, no other endpoint is tried. +pub fn submit_as_at(endpoints: &[Server], destination: &Destination, pdf: &[u8], job: &Job, user: &str) -> Result { + let path = destination_path(destination)?; + if user.len() > MAX_JOB_NAME || user.chars().any(char::is_control) { + return Err(Error::Spool("invalid CUPS user name".into())); + } + if job.copies == 0 || job.copies > 999 { + return Err(Error::Spool("copies must be between 1 and 999".into())); + } + let mut last = Error::Spool("no CUPS endpoint selected".into()); + for endpoint in endpoints { + let mut stream = match connect(endpoint) { + Ok(stream) => stream, + Err(error) => { + last = Error::Spool(format!("CUPS connection failed: {error}")); + continue; + } + }; + let authority = endpoint.authority(); + let request = print_job_request_for(&authority, &path, pdf, job, user); + // Never retry exchange errors: the scheduler may already have accepted the job. + let reply = exchange(&mut stream, &authority, &path, &request, JOB_TIMEOUT)?; + let parsed = parse_reply(&reply)?; + if !status_ok(parsed.status) { + return Err(refused(parsed.status)); + } + return parsed + .job_id + .filter(|id| *id != 0 && *id <= i32::MAX as u32) + .ok_or_else(|| Error::Spool("CUPS accepted the job without a usable job id; do not resubmit".into())); + } + Err(last) +} + +/// Encode one destination as a URI path segment, never as routing syntax. Names from +/// discovery may include spaces or Unicode. Reject separators, controls and dot segments +/// rather than relying on a server to keep an encoded traversal request harmless. +fn destination_path(destination: &Destination) -> Result { + let name = &destination.name; + if name.is_empty() + || name.len() > MAX_NAME + || matches!(name.as_str(), "." | "..") + || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\')) + { + return Err(Error::Spool("invalid CUPS destination name".into())); + } + let kind = if destination.is_class { "classes" } else { "printers" }; + let mut path = format!("/{kind}/"); + for byte in name.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + path.push(char::from(byte)); + } else { + use std::fmt::Write as _; + write!(&mut path, "%{byte:02X}").map_err(|_| Error::Spool("could not encode CUPS destination".into()))?; + } + } + Ok(path) +} + +/// A CUPS queue name: ASCII letters, digits and `_`, `-`, `.` — what the scheduler accepts, and +/// what cannot break the printer URI's path. +fn is_queue_name(name: &str) -> bool { + !name.is_empty() && name.len() <= MAX_NAME && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) +} + +/// One IPP request and its reply body. Discovery may try each endpoint in turn; a job is given +/// to the first endpoint that accepts a connection, once: a retry could print it twice. +pub(crate) fn post(endpoints: &[Server], path: &str, body: &[u8], timeout: Duration, retry: bool) -> Result, Error> { + let mut failed: Option = None; + for server in endpoints { + let mut stream = match connect(server) { + Ok(stream) => stream, + Err(e) => { + failed = Some(Error::Spool(format!("the print server could not be reached: {e}"))); + continue; + } + }; + match exchange(&mut stream, &server.authority(), path, body, timeout) { + Ok(reply) => return Ok(reply), + Err(e) => { + failed = Some(e); + if !retry { + break; + } + } + } + } + Err(failed.unwrap_or_else(|| Error::Spool("the print server could not be reached".into()))) +} + +/// Send one IPP request and read the reply's body. +fn exchange(stream: &mut Stream, authority: &str, path: &str, body: &[u8], timeout: Duration) -> Result, Error> { + let mut stream = DeadlineReader { stream, end: Instant::now() + timeout }; + let head = format!( + "POST {path} HTTP/1.1\r\nHost: {authority}\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ); + stream + .write_all(head.as_bytes()) + .and_then(|()| stream.write_all(body)) + .and_then(|()| stream.flush()) + .map_err(|e| Error::Spool(format!("the request could not be sent to the print server: {e}")))?; + let reply = read_reply(&mut stream)?; + validate_reply_identity(body, &reply)?; + Ok(reply) +} + +/// One absolute deadline shared by request writes and reply reads after connection. +struct DeadlineReader<'a> { + stream: &'a mut Stream, + end: Instant, +} +impl Write for DeadlineReader<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let left = self + .end + .checked_duration_since(Instant::now()) + .filter(|d| !d.is_zero()) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS exchange deadline exceeded"))?; + self.stream.set_timeouts(left)?; + self.stream.write(buf) + } + fn flush(&mut self) -> std::io::Result<()> { + self.stream.flush() + } +} + +fn validate_reply_identity(request: &[u8], reply: &[u8]) -> Result<(), Error> { + if reply.get(..2) != Some(&[1, 1]) || request.get(4..8).is_none() || request.get(4..8) != reply.get(4..8) { + return Err(Error::Spool("CUPS reply version or request id does not match; do not resubmit".into())); + } + Ok(()) +} + +impl Read for DeadlineReader<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let left = self + .end + .checked_duration_since(Instant::now()) + .filter(|d| !d.is_zero()) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::TimedOut, "CUPS reply deadline exceeded"))?; + #[cfg(not(target_os = "macos"))] + self.stream.set_timeouts(left)?; + #[cfg(target_os = "macos")] + if let Err(error) = self.stream.set_timeouts(left) { + // Darwin rejects timeout updates on a disconnected Unix socket even + // when a complete reply is still buffered. Never fall back to a + // blocking read: drain at most this buffer, or fail on WouldBlock. + // Every subsequent read rechecks the same absolute deadline above. + if error.raw_os_error() == Some(22) + && let Stream::Unix(stream) = self.stream + { + stream.set_nonblocking(true)?; + let result = stream.read(buf); + let restored = stream.set_nonblocking(false); + return result.and_then(|count| restored.map(|()| count)); + } + return Err(error); + } + self.stream.read(buf) + } +} + +fn read_reply(stream: &mut impl Read) -> Result, Error> { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + loop { + if head.len() >= MAX_HEADERS { + return Err(Error::Spool("the print server sent a header block that is too large".into())); + } + match stream.read(&mut byte) { + Ok(0) => return Err(Error::Spool("the print server closed the connection before sending its reply".into())), + Ok(_) => head.push(byte[0]), + Err(e) => return Err(Error::Spool(format!("the print server's reply could not be read: {e}"))), + } + if head.ends_with(b"\r\n\r\n") { + break; + } + } + let head = String::from_utf8_lossy(&head); + let Some(status_line) = head.lines().next() else { return Err(Error::Spool("the print server sent an unreadable reply".into())) }; + let code = status_line + .strip_prefix("HTTP/") + .and_then(|rest| rest.split_once(' ')) + .and_then(|(_, code)| code.split_whitespace().next()) + .and_then(|code| code.parse::().ok()) + .ok_or_else(|| Error::Spool("the print server sent an unreadable reply".into()))?; + match code { + 200..=299 => {} + 401 => return Err(Error::Spool("the print server requires authentication".into())), + 426 => return Err(Error::Spool("the print server only accepts encrypted connections".into())), + _ => return Err(Error::Spool(format!("the print server refused the request (HTTP {code})"))), + } + let mut content_length: Option = None; + let mut chunked = false; + for line in head.lines().skip(1) { + // The empty line ends the header block; any other line without a colon is malformed. + if line.is_empty() { + continue; + } + let Some((name, value)) = line.split_once(':') else { + return Err(Error::Spool("the print server sent an unreadable header".into())); + }; + match name.trim().to_ascii_lowercase().as_str() { + "content-length" => { + let len = value.trim().parse::().map_err(|_| Error::Spool("invalid Content-Length".into()))?; + if content_length.replace(len).is_some() { + return Err(Error::Spool("duplicate Content-Length".into())); + } + } + // Only `identity` is not a transfer encoding to be decoded. + "transfer-encoding" => { + if chunked || !value.trim().eq_ignore_ascii_case("chunked") { + return Err(Error::Spool("unsupported Transfer-Encoding".into())); + } + chunked = true; + } + _ => {} + } + } + if chunked { + if content_length.is_some() { + return Err(Error::Spool("ambiguous reply framing".into())); + } + return read_chunks(stream); + } + let Some(len) = content_length else { return Err(Error::Spool("the print server sent no Content-Length".into())) }; + if len > MAX_BODY { + return Err(Error::Spool(format!("the print server's reply is too large ({len} bytes)"))); + } + let mut body = vec![0u8; len]; + stream.read_exact(&mut body).map_err(|e| Error::Spool(format!("the print server's reply was cut short: {e}")))?; + Ok(body) +} + +fn read_chunks(stream: &mut impl Read) -> Result, Error> { + fn line(stream: &mut impl Read) -> Result, Error> { + let mut out = Vec::new(); + for _ in 0..MAX_HEADERS { + let mut byte = [0]; + stream.read_exact(&mut byte).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + out.push(byte[0]); + if out.ends_with(b"\r\n") { + out.truncate(out.len() - 2); + return Ok(out); + } + } + Err(Error::Spool("chunk line exceeds limit".into())) + } + let mut body = Vec::new(); + for _ in 0..100_000 { + let header = line(stream)?; + let size = header.split(|b| *b == b';').next().unwrap_or_default(); + if size.is_empty() || !size.iter().all(u8::is_ascii_hexdigit) { + return Err(Error::Spool("invalid chunk size".into())); + } + let len = std::str::from_utf8(size) + .ok() + .and_then(|s| usize::from_str_radix(s, 16).ok()) + .ok_or_else(|| Error::Spool("invalid chunk size".into()))?; + if len == 0 { + let mut total = 0usize; + loop { + let trailer = line(stream)?; + total = total.saturating_add(trailer.len() + 2); + if total > MAX_HEADERS { + return Err(Error::Spool("chunk trailers exceed limit".into())); + } + if trailer.is_empty() { + return Ok(body); + } + if !trailer.contains(&b':') { + return Err(Error::Spool("invalid chunk trailer".into())); + } + } + } + let end = body.len().checked_add(len).filter(|n| *n <= MAX_BODY).ok_or_else(|| Error::Spool("chunked reply exceeds limit".into()))?; + let start = body.len(); + body.resize(end, 0); + stream.read_exact(&mut body[start..]).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + let mut crlf = [0; 2]; + stream.read_exact(&mut crlf).map_err(|e| Error::Spool(format!("truncated chunk: {e}")))?; + if crlf != *b"\r\n" { + return Err(Error::Spool("invalid chunk terminator".into())); + } + } + Err(Error::Spool("too many chunks".into())) +} + +/// An IPP request being built: a version, an operation and a request id, then attributes, then +/// the document. +struct Request { + bytes: Vec, +} + +impl Request { + fn new(operation: u16) -> Self { + // IPP 1.1: version, operation, a request id (any nonzero value). + let mut bytes = vec![1, 1]; + bytes.extend(operation.to_be_bytes()); + bytes.extend(REQUEST_ID.fetch_add(1, Ordering::Relaxed).max(1).to_be_bytes()); + Request { bytes } + } + + fn group(&mut self, tag: u8) { + self.bytes.push(tag); + } + + fn end(&mut self) { + self.bytes.push(GROUP_END); + } + + fn attribute(&mut self, tag: u8, name: &str, value: &[u8]) { + let (Ok(name_len), Ok(value_len)) = (u16::try_from(name.len()), u16::try_from(value.len())) else { + return; + }; + self.bytes.push(tag); + self.bytes.extend(name_len.to_be_bytes()); + self.bytes.extend(name.as_bytes()); + self.bytes.extend(value_len.to_be_bytes()); + self.bytes.extend(value); + } + + /// An additional value of the previous attribute (a `1setOf`): the name is empty. + fn additional(&mut self, tag: u8, value: &str) { + self.attribute(tag, "", value.as_bytes()); + } +} + +/// A discovery request: the operation's required attributes, then the names to be answered with. +fn discovery_request(operation: u16) -> Vec { + let mut r = Request::new(operation); + r.group(GROUP_OPERATION); + r.attribute(TAG_CHARSET, "attributes-charset", b"utf-8"); + r.attribute(TAG_LANGUAGE, "attributes-natural-language", b"en"); + r.attribute(TAG_URI, "printer-uri", b"ipp://localhost/"); + r.attribute(TAG_KEYWORD, "requested-attributes", b"printer-name"); + r.additional(TAG_KEYWORD, "printer-info"); + r.additional(TAG_KEYWORD, "printer-state"); + r.additional(TAG_KEYWORD, "printer-is-accepting-jobs"); + r.end(); + r.bytes +} + +/// A Print-Job request for `queue`: the job's options as IPP attributes, the PDF as the document +/// data that follows the end of attributes. +fn print_job_request(queue: &str, pdf: &[u8], job: &Job) -> Vec { + print_job_request_path(&format!("/printers/{queue}"), pdf, job) +} + +fn print_job_request_path(path: &str, pdf: &[u8], job: &Job) -> Vec { + print_job_request_for("localhost", path, pdf, job, "") +} + +fn print_job_request_for(authority: &str, path: &str, pdf: &[u8], job: &Job, user: &str) -> Vec { + let mut r = Request::new(OPERATION_PRINT_JOB); + r.group(GROUP_OPERATION); + r.attribute(TAG_CHARSET, "attributes-charset", b"utf-8"); + r.attribute(TAG_LANGUAGE, "attributes-natural-language", b"en"); + r.attribute(TAG_URI, "printer-uri", format!("ipp://{authority}{path}").as_bytes()); + if !user.is_empty() { + r.attribute(TAG_NAME, "requesting-user-name", user.as_bytes()); + } + r.attribute(TAG_NAME, "job-name", truncate_utf8(&job.title, MAX_JOB_NAME).as_bytes()); + r.attribute(TAG_MIME, "document-format", b"application/pdf"); + r.group(GROUP_JOB); + r.attribute(TAG_INTEGER, "copies", &job.copies.clamp(1, 999).to_be_bytes()); + r.attribute(TAG_BOOLEAN, "collate", &[u8::from(job.collate)]); + if let Some(duplex) = job.duplex { + r.attribute( + TAG_KEYWORD, + "sides", + match duplex { + Duplex::Off => "one-sided", + Duplex::LongEdge => "two-sided-long-edge", + Duplex::ShortEdge => "two-sided-short-edge", + } + .as_bytes(), + ); + } + if job.grayscale { + r.attribute(TAG_KEYWORD, "print-color-mode", b"monochrome"); + } + // PWG 5100.13 §6.2.5: `none` keeps every sheet at its size, `auto-fit` shrinks only + // oversized ones — the same choices `lp`'s fit-to-page and print-scaling options make. + r.attribute( + TAG_KEYWORD, + "print-scaling", + match job.scaling { + Scaling::Exact => "none", + Scaling::ShrinkToFit => "auto-fit", + } + .as_bytes(), + ); + r.end(); + r.bytes.extend(pdf); + r.bytes +} + +/// The string cut to at most `max` bytes, at a character boundary. +fn truncate_utf8(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut end = max; + while !s.is_char_boundary(end) { + end -= 1; + } + // `end` is a checked boundary; nothing is the only name that cannot be cut. + s.get(..end).unwrap_or_default() +} + +/// The parsed parts of a reply: the IPP status, the printer names in its printer groups, and a +/// submission's job id. +struct Reply { + status: u16, + names: Vec, + queues: Vec, + job_id: Option, +} + +/// A cursor over a reply: `None` at the end or past a length, never an over-read. +struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, len: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(len)?; + let taken = self.bytes.get(self.pos..end)?; + self.pos = end; + Some(taken) + } + + fn array(&mut self) -> Option<[u8; N]> { + <[u8; N]>::try_from(self.take(N)?).ok() + } + + fn u16(&mut self) -> Option { + self.array::<2>().map(u16::from_be_bytes) + } +} + +fn parse_reply(reply: &[u8]) -> Result { + let malformed = || Error::Spool("the print server sent a malformed reply".into()); + let mut r = Reader { bytes: reply, pos: 0 }; + let _version = r.array::<2>().ok_or_else(malformed)?; + let status = r.u16().ok_or_else(malformed)?; + let _request_id = r.array::<4>().ok_or_else(malformed)?; + let (mut names, mut job_id, mut group) = (Vec::new(), None, 0u8); + let mut queues = Vec::new(); + let mut queue = Queue::default(); + loop { + let Some(tag) = r.array::<1>().map(|t| t[0]) else { return Err(malformed()) }; + match tag { + GROUP_END => { + if !queue.name.is_empty() { + queues.push(queue); + } + break; + } + GROUP_OPERATION | GROUP_JOB | GROUP_PRINTER | 0x05 => { + if !queue.name.is_empty() { + if queues.len() >= MAX_PRINTERS { + return Err(malformed()); + } + queues.push(std::mem::take(&mut queue)); + } else { + queue = Queue::default(); + } + group = tag; + } + // An attribute: name and value, each u16-length. An empty name is an additional + // value of the previous one (the attributes read here are single-valued, so those + // are ignored). Group tags not in the registry and collections (the attributes + // requested here are never collections) are refused, not guessed. + 0x10..=0x33 | 0x35..=0x4A => { + let name_len = r.u16().ok_or_else(malformed)?; + if usize::from(name_len) > MAX_NAME { + return Err(malformed()); + } + let name_bytes = r.take(usize::from(name_len)).ok_or_else(malformed)?; + let name = std::str::from_utf8(name_bytes).map_err(|_| malformed())?; + let value_len = r.u16().ok_or_else(malformed)?; + let value = r.take(usize::from(value_len)).ok_or_else(malformed)?; + match (group, name, tag) { + (GROUP_PRINTER, "printer-name", TAG_NAME) => { + if let Some(printer) = std::str::from_utf8(value).ok().filter(|n| !n.is_empty() && n.len() <= MAX_NAME) { + if names.len() >= MAX_PRINTERS { + return Err(Error::Spool("too many CUPS destinations".into())); + } + if !queue.name.is_empty() { + return Err(malformed()); + } + queue.name = printer.to_string(); + names.push(printer.to_string()); + } + } + (GROUP_PRINTER, "printer-info", 0x41 | TAG_NAME) => { + // Human descriptions are text, not queue identifiers. Their u16 + // wire length and the whole-response MAX_BODY cap bound allocation. + queue.info = std::str::from_utf8(value).map_err(|_| malformed())?.to_owned(); + } + (GROUP_PRINTER, "printer-state", 0x23 | TAG_INTEGER) => { + queue.state = u32::from_be_bytes(value.try_into().map_err(|_| malformed())?); + } + (GROUP_PRINTER, "printer-is-accepting-jobs", TAG_BOOLEAN) => { + queue.accepting_jobs = match value { + [0] => false, + [1] => true, + _ => return Err(malformed()), + }; + } + (GROUP_JOB, "job-id", TAG_INTEGER) => { + if let Ok(id) = <[u8; 4]>::try_from(value) { + job_id = Some(u32::from_be_bytes(id)); + } + } + _ => {} + } + } + _ => return Err(malformed()), + } + } + Ok(Reply { status, names, queues, job_id }) +} + +/// Successful IPP status codes are `0x00xx` (RFC 8011 Appendix B). +fn status_ok(status: u16) -> bool { + status < 0x0100 +} + +/// The IPP status code's name, for the error the user sees. +fn status_name(status: u16) -> Option<&'static str> { + Some(match status { + 0x0400 => "bad request", + 0x0401 => "forbidden", + 0x0402 => "not authenticated", + 0x0403 => "not authorized", + 0x0404 => "not possible", + 0x0406 => "printer not found", + 0x0408 => "request too large", + 0x040A => "PDF is not a supported document format for this printer", + 0x0412 => "the document could not be accessed", + 0x0500 => "internal error", + 0x0501 => "operation not supported", + 0x0502 => "service unavailable", + 0x0503 => "IPP version not supported", + 0x0504 => "device error", + 0x0505 => "temporary error", + 0x0506 => "the printer is not accepting jobs", + 0x0507 => "the printer is busy", + _ => return None, + }) +} + +fn refused(status: u16) -> Error { + match status_name(status) { + Some(name) => Error::Spool(format!("the print server refused the request ({name})")), + None => Error::Spool(format!("the print server refused the request (IPP status 0x{status:04X})")), + } +} diff --git a/crates/print/src/cups/tests.rs b/crates/print/src/cups/tests.rs new file mode 100644 index 0000000000..978246e560 --- /dev/null +++ b/crates/print/src/cups/tests.rs @@ -0,0 +1,593 @@ +//! The IPP client against a fake CUPS server (a unix socket or a loopback port): discovery, +//! Print-Job, and the malformed replies it must refuse without a panic. + +use super::*; +use crate as spool; +use crate::cups::{self as ipp, Server}; +use std::collections::VecDeque; +use std::io::{Read, Write}; +use std::sync::Mutex; +use std::sync::mpsc::{self, Receiver}; +use std::time::Duration; + +const TIMEOUT: Duration = Duration::from_secs(2); + +/// A fake CUPS server: each connection carries one request; the next canned reply goes back +/// (nothing, when the list is out — the client then sees a hang-up). Every request is recorded +/// for the assertions. +struct FakeCups { + server: Server, + requests: Receiver>, +} + +impl FakeCups { + fn on_unix(replies: Vec>) -> std::io::Result { + let dir = tempfile::tempdir()?; + let path = dir.path().join("cups.sock"); + let listener = std::os::unix::net::UnixListener::bind(&path)?; + // The socket must outlive this function; the folder is left for the process to reap. + std::mem::forget(dir); + let requests = listen_unix(listener, replies); + Ok(FakeCups { server: Server::Unix(path), requests }) + } + + fn on_tcp(replies: Vec>) -> std::io::Result { + let listener = std::net::TcpListener::bind("127.0.0.1:0")?; + let server = Server::Tcp(listener.local_addr()?); + let requests = listen_tcp(listener, replies); + Ok(FakeCups { server, requests }) + } + + fn request(&self) -> Result, mpsc::RecvTimeoutError> { + self.requests.recv_timeout(Duration::from_secs(5)) + } + + /// The server as the one-endpoint list the client functions take. + fn endpoint(&self) -> &[Server] { + std::slice::from_ref(&self.server) + } +} + +fn listen_unix(listener: std::os::unix::net::UnixListener, replies: Vec>) -> Receiver> { + let (tx, rx) = mpsc::channel(); + let replies = Mutex::new(VecDeque::from(replies)); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &replies, &tx); + } + }); + rx +} + +fn listen_tcp(listener: std::net::TcpListener, replies: Vec>) -> Receiver> { + let (tx, rx) = mpsc::channel(); + let replies = Mutex::new(VecDeque::from(replies)); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &replies, &tx); + } + }); + rx +} + +fn serve(mut stream: impl Read + Write, replies: &Mutex>>, requests: &mpsc::Sender>) { + let Some(request) = read_request(&mut stream) else { return }; + let Some(body) = ipp_body(&request) else { return }; + let request_id = body.get(4..8).map(|id| id.to_vec()); + let _ = requests.send(request); + // A list out of replies is a server that hangs up before answering. + let Ok(mut replies) = replies.lock() else { return }; + if let Some(mut reply) = replies.pop_front() { + if let Some(body) = reply.windows(4).position(|w| w == b"\r\n\r\n").map(|at| at + 4) + && reply.get(body..body + 2) == Some(&[1, 1]) + && let Some(id) = request_id + && let Some(destination) = reply.get_mut(body + 4..body + 8) + { + destination.copy_from_slice(&id); + } + let _ = stream.write_all(&reply); + let _ = stream.flush(); + } +} + +/// One HTTP request: the headers (bounded), then the `Content-Length` body it announces. +fn read_request(stream: &mut impl Read) -> Option> { + let mut buf = Vec::new(); + let mut byte = [0u8; 1]; + loop { + match stream.read(&mut byte) { + Ok(0) | Err(_) => return None, + Ok(_) => buf.push(byte[0]), + } + if buf.ends_with(b"\r\n\r\n") { + break; + } + if buf.len() > 1 << 16 { + return None; + } + } + let head = String::from_utf8_lossy(&buf); + let len: usize = head.lines().find_map(|l| l.strip_prefix("Content-Length:")).and_then(|v| v.trim().parse().ok())?; + let head_len = buf.len(); + buf.resize(head_len + len, 0); + stream.read_exact(&mut buf[head_len..]).ok()?; + Some(buf) +} + +/// An HTTP reply carrying `body`, as CUPS would send it. +fn http_reply(body: &[u8]) -> Vec { + let mut out = format!("HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\nContent-Length: {}\r\n\r\n", body.len()).into_bytes(); + out.extend(body); + out +} + +/// An IPP reply body: `status`, then the attribute groups as raw bytes, then end of attributes. +fn ipp_reply(status: u16, groups: &[&[u8]]) -> Vec { + let mut out = vec![1, 1]; + out.extend(status.to_be_bytes()); + out.extend(1u32.to_be_bytes()); + for &group in groups { + out.extend(group); + } + out.push(0x03); + out +} + +fn group(tag: u8) -> Vec { + vec![tag] +} + +fn printer_name(name: &str) -> Vec { + attr(0x42, "printer-name", name.as_bytes()) +} + +/// One attribute, framed the way the client frames them, so `has` finds it in a request. +fn attr(tag: u8, name: &str, value: &[u8]) -> Vec { + let mut out = vec![tag]; + out.extend((name.len() as u16).to_be_bytes()); + out.extend(name.as_bytes()); + out.extend((value.len() as u16).to_be_bytes()); + out.extend(value); + out +} + +fn has(bytes: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && bytes.windows(needle.len()).any(|w| w == needle) +} + +/// The IPP part of a recorded request: everything after the HTTP head. +fn ipp_body(request: &[u8]) -> Option<&[u8]> { + let at = request.windows(4).position(|w| w == b"\r\n\r\n")?; + request.get(at + 4..) +} + +fn entry(name: &str, default: bool) -> spool::Printer { + spool::Printer { description: String::new(), name: name.into(), default, two_sided: None } +} + +#[test] +fn discovery_finds_queues_and_the_default_over_a_unix_socket() { + let fake = FakeCups::on_unix(vec![ + http_reply(&ipp_reply( + 0x0000, + &[ + &group(0x01), + &printer_name("Office_Laser"), + &group(0x04), + &printer_name("Office_Laser"), + &group(0x04), + &printer_name("Label_Writer"), + &group(0x04), + &printer_name("Office_Laser"), + ], + )), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office_Laser")])), + ]) + .unwrap(); + let printers = ipp::printers_at(fake.endpoint()).unwrap(); + assert_eq!(printers, [entry("Office_Laser", true), entry("Label_Writer", false)], "each queue once, the default marked"); + let taken = fake.request().unwrap(); + let queues = ipp_body(&taken).unwrap(); + assert_eq!(&queues[..4], &[1, 1, 0x40, 0x02], "IPP 1.1, CUPS-Get-Printers"); + assert!(has(queues, b"ipp://localhost/")); + assert!(has(queues, &attr(0x44, "requested-attributes", b"printer-name"))); + assert!(has(queues, b"printer-is-accepting-jobs"), "only the attributes the dialog needs are asked for"); + let taken = fake.request().unwrap(); + let default = ipp_body(&taken).unwrap(); + assert_eq!(&default[..4], &[1, 1, 0x40, 0x01], "CUPS-Get-Default"); +} + +#[test] +fn a_print_job_carries_the_pdf_and_the_options() { + let pdf: Vec = b"%PDF-1.7 fake print job\n".iter().copied().cycle().take(1 << 20).collect(); + let job = spool::Job { + printer: Some("Office".into()), + copies: 2, + collate: false, + duplex: Some(spool::Duplex::LongEdge), + grayscale: true, + scaling: spool::Scaling::ShrinkToFit, + title: "memo.pdf".into(), + ..Job::default() + }; + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply( + 0x0000, + &[&group(0x01), &group(0x02), &attr(0x21, "job-id", &12u32.to_be_bytes()), &attr(0x23, "job-state", &[3u8])], + ))]) + .unwrap(); + let message = ipp::print_job_at(fake.endpoint(), &pdf, &job).unwrap(); + assert_eq!(message, "request id is Office-12", "the same message lp prints"); + let taken = fake.request().unwrap(); + let request = ipp_body(&taken).unwrap(); + assert_eq!(&request[..4], &[1, 1, 0x00, 0x02], "IPP 1.1, Print-Job"); + assert!(has(request, b"ipp://localhost/printers/Office")); + let mut copies = group(0x02); + copies.extend(attr(0x21, "copies", &2u32.to_be_bytes())); + assert!(has(request, &copies), "copies are a job attribute"); + assert!(has(request, &attr(0x22, "collate", &[0]))); + assert!(has(request, &attr(0x44, "sides", b"two-sided-long-edge"))); + assert!(has(request, &attr(0x44, "print-color-mode", b"monochrome"))); + assert!(has(request, &attr(0x44, "print-scaling", b"auto-fit"))); + assert!(has(request, &attr(0x49, "document-format", b"application/pdf"))); + assert!(has(request, &attr(0x42, "job-name", b"memo.pdf"))); + assert!(request.ends_with(&pdf), "the whole job is the document data"); +} + +#[test] +fn the_default_printer_is_used_when_the_job_has_none() { + let fake = FakeCups::on_tcp(vec![ + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office")])), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x02), &attr(0x21, "job-id", &7u32.to_be_bytes())])), + ]) + .unwrap(); + let message = ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &Job::default()).unwrap(); + assert_eq!(message, "request id is Office-7"); + let default = fake.request().unwrap(); + assert_eq!(&ipp_body(&default).unwrap()[..4], &[1, 1, 0x40, 0x01], "the default comes from CUPS-Get-Default"); + let taken = fake.request().unwrap(); + assert!(has(ipp_body(&taken).unwrap(), b"ipp://localhost/printers/Office"), "the resolved default is the target"); +} + +#[test] +fn a_default_outside_the_queue_list_still_gets_its_marker() { + let fake = FakeCups::on_unix(vec![ + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Office_Laser")])), + http_reply(&ipp_reply(0x0000, &[&group(0x01), &group(0x04), &printer_name("Label_Writer")])), + ]) + .unwrap(); + let printers = ipp::printers_at(fake.endpoint()).unwrap(); + assert_eq!( + printers, + [entry("Office_Laser", false), entry("Label_Writer", true)], + "the default joins the list, so the dialog has a selection to restore" + ); +} + +#[test] +fn no_default_printer_is_an_error_when_the_job_names_none() { + let fake = FakeCups::on_unix(vec![http_reply(&ipp_reply(0x0000, &[&group(0x01)]))]).unwrap(); + let err = ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &Job::default()).unwrap_err(); + assert!(err.to_string().contains("no default printer"), "{err}"); +} + +#[test] +fn a_printer_name_that_cannot_be_a_uri_path_is_refused() { + let fake = FakeCups::on_tcp(vec![]).unwrap(); + let mut long = "x".repeat(257); + long.push('y'); + for name in ["Office (east)", "../../admin", "", "a b", "Brother/HL", "Копир", long.as_str()] { + let job = spool::Job { printer: Some(name.into()), ..Job::default() }; + assert_eq!( + ipp::print_job_at(fake.endpoint(), b"pdf", &job), + Err(spool::Error::Spool(format!("not a printer name: {name}"))), + "{name:?} cannot go in the printer URI's path" + ); + } +} + +#[test] +fn an_ipp_refusal_is_an_error_that_names_the_problem() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0506, &[&group(0x01)]))]).unwrap(); + let job = spool::Job { printer: Some("Office".into()), ..Job::default() }; + assert_eq!( + ipp::print_job_at(fake.endpoint(), b"%PDF-1.7\n", &job), + Err(spool::Error::Spool("the print server refused the request (the printer is not accepting jobs)".into())) + ); +} + +#[test] +fn malformed_replies_are_errors_never_a_panic() { + let bodies: Vec<(&str, Vec)> = vec![ + // Shorter than an IPP header. + ("shorter than an IPP header", vec![1, 1, 0]), + // A reply that ends inside an attribute: the name is announced, the value never comes. + ("cut inside an attribute", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0x20, b'p']), + // A value tag the registry does not know. + ("unknown value tag", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0xFF, 0x00, 0x00, 0x00, 0x00]), + // A collection, which the attributes asked for never are. + ("collection", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x34, 0x00, 0x00, 0x00, 0x00]), + // A group tag that is no delimiter in the registry. + ("reserved delimiter", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x06]), + // A length within the cap that runs past the reply, and one past the cap. + ("length past the reply", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0xFE, b'p']), + ("length past the cap", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0xFF, 0xFF, b'p']), + // No end of attributes before the body runs out. + ("no end of attributes", vec![1, 1, 0, 0, 0, 0, 0, 1, 0x04, 0x42, 0x00, 0x01, b'x']), + ]; + for (why, body) in bodies { + let fake = FakeCups::on_unix(vec![http_reply(&body)]).unwrap(); + let result = ipp::printers_at(fake.endpoint()); + assert!(result.is_err(), "{why}: the reply must be an error, not a panic or a success"); + } +} + +#[test] +fn http_replies_that_cannot_carry_an_answer_are_refused() { + let replies: Vec<(&str, Vec)> = vec![ + ("requires authentication", b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n".to_vec()), + ("demands a TLS upgrade", b"HTTP/1.1 426 Upgrade Required\r\nContent-Length: 0\r\n\r\n".to_vec()), + ("chunked", b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n25\r\nthe body is chunked\r\n0\r\n\r\n".to_vec()), + ("no Content-Length", b"HTTP/1.1 200 OK\r\nContent-Type: application/ipp\r\n\r\n".to_vec()), + ("Content-Length past the cap", b"HTTP/1.1 200 OK\r\nContent-Length: 99999999\r\n\r\n".to_vec()), + ("unreadable status line", b"not HTTP at all\r\n\r\n".to_vec()), + ]; + for (why, reply) in replies { + let fake = FakeCups::on_unix(vec![reply]).unwrap(); + let result = ipp::post(&[fake.server], "/", b"ignored", TIMEOUT, true); + assert!(result.is_err(), "{why}: the reply must be an error, not a panic or a success"); + } + // A server that takes the request and hangs up. + let fake = FakeCups::on_unix(vec![]).unwrap(); + assert!(ipp::post(&[fake.server], "/", b"ignored", TIMEOUT, true).is_err(), "a hang-up is an error"); +} + +#[test] +fn a_server_that_answers_is_reachable_and_silence_is_not() { + let fake = FakeCups::on_unix(vec![]).unwrap(); + assert!(ipp::reachable(&fake.server), "a unix socket that accepts connections is reachable"); + let fake = FakeCups::on_tcp(vec![]).unwrap(); + assert!(ipp::reachable(&fake.server), "a loopback port that accepts connections is reachable"); + let absent = Server::Unix("/nonexistent/craft-print-test.sock".into()); + assert!(!ipp::reachable(&absent), "a socket nothing listens on is not reachable"); + let addr = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap() + }; + assert!(!ipp::reachable(&Server::Tcp(addr)), "a port nothing listens on is not reachable"); +} + +#[test] +fn chunked_reply_is_bounded_and_rejects_ambiguous_framing() { + let good = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n"; + assert_eq!(super::read_reply(&mut &good[..]).unwrap(), b"abcde"); + for bad in [ + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n0\r\n\r\n".as_slice(), + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n100001\r\n", + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\na", + b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nContent-Length: 0\r\n\r\n", + ] { + assert!(super::read_reply(&mut &bad[..]).is_err()); + } +} + +#[test] +fn explicit_server_rejects_header_injection_and_malformed_port() { + for value in ["host\r\nInjected: yes", "host:0", "host:99999", "http://host", "user@host", ""] { + assert!(Server::parse(value).is_err(), "{value:?}"); + } + assert_eq!(Server::parse("[::1]:631").unwrap().authority(), "[::1]:631"); + assert_eq!(Server::parse("print.example:8631").unwrap().authority(), "print.example:8631"); +} + +#[test] +fn class_submission_preserves_authority_user_and_numeric_job_id() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(2), &attr(0x21, "job-id", &42u32.to_be_bytes())]))]).unwrap(); + let destination = super::Destination { name: "Studio".into(), is_class: true }; + assert_eq!(super::submit_as_at(fake.endpoint(), &destination, b"pdf", &Job::default(), "artist").unwrap(), 42); + let request = fake.request().unwrap(); + assert!(has(&request, b"POST /classes/Studio HTTP/1.1")); + assert!(has(&request, format!("Host: {}", fake.server.authority()).as_bytes())); + assert!(has(ipp_body(&request).unwrap(), format!("ipp://{}/classes/Studio", fake.server.authority()).as_bytes())); + assert!(has(ipp_body(&request).unwrap(), &attr(0x42, "requesting-user-name", b"artist"))); +} + +#[test] +fn uncertain_submission_never_tries_the_second_endpoint() { + let first = FakeCups::on_tcp(vec![]).unwrap(); + let second = FakeCups::on_tcp(vec![]).unwrap(); + let destination = super::Destination { name: "Studio".into(), is_class: false }; + assert!(super::submit_at(&[first.server.clone(), second.server.clone()], &destination, b"pdf", &Job::default()).is_err()); + let _ = first.request().unwrap(); + assert!(second.requests.recv_timeout(Duration::from_millis(100)).is_err()); +} + +#[test] +fn queue_metadata_stays_with_its_printer_group() { + let bytes = ipp_reply( + 0, + &[ + &group(4), + &attr(0x41, "printer-info", b"Studio printer"), + &printer_name("First"), + &attr(0x23, "printer-state", &5u32.to_be_bytes()), + &attr(0x22, "printer-is-accepting-jobs", &[0]), + &group(4), + &printer_name("Second"), + ], + ); + let reply = super::parse_reply(&bytes).unwrap(); + assert_eq!(reply.queues.len(), 2); + assert_eq!(reply.queues[0].info, "Studio printer"); + assert_eq!(reply.queues[0].state, 5); + assert!(!reply.queues[0].accepting_jobs); + assert!(reply.queues[1].info.is_empty()); + assert!(reply.queues[1].accepting_jobs); +} + +#[test] +fn reply_identity_and_metadata_request_are_checked() { + let request = super::discovery_request(0x4002); + assert!(has(&request, b"printer-info")); + let mut reply = vec![1, 1, 0, 0]; + reply.extend_from_slice(&request[4..8]); + reply.push(3); + assert!(super::validate_reply_identity(&request, &reply).is_ok()); + reply[7] ^= 1; + assert!(super::validate_reply_identity(&request, &reply).is_err()); + reply[4..8].copy_from_slice(&request[4..8]); + reply[0] = 9; + assert!(super::validate_reply_identity(&request, &reply).is_err()); +} + +#[test] +fn slow_reply_cannot_reset_the_absolute_deadline() { + let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let producer = std::thread::spawn(move || { + // Finite work and a joined handle: no abandoned timeout worker. + for _ in 0..20 { + if peer.write_all(b"x").is_err() { + break; + } + std::thread::sleep(Duration::from_millis(20)); + } + }); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut bytes = [0; 20]; + assert!(reader.read_exact(&mut bytes).is_err(), "trickle reads must not extend the absolute deadline"); + drop(stream); + producer.join().unwrap(); + assert!(start.elapsed() < Duration::from_secs(3)); +} + +#[test] +fn blocked_upload_obeys_the_same_absolute_deadline() { + let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut writer = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let chunk = [0u8; 64 * 1024]; + let mut timed_out = false; + // A peer that never drains cannot turn each partial write into a fresh timeout budget. + for _ in 0..512 { + if writer.write_all(&chunk).is_err() { + timed_out = true; + break; + } + } + assert!(timed_out, "blocked upload must terminate without a reader"); + assert!(start.elapsed() < Duration::from_secs(3)); +} + +#[test] +fn recorded_request_body_requires_complete_http_headers() { + assert!(ipp_body(b"POST / HTTP/1.1\r\n").is_none()); + assert_eq!(ipp_body(b"POST / HTTP/1.1\r\n\r\nbody"), Some(b"body".as_slice())); +} + +#[test] +fn named_destinations_encode_one_path_segment_on_both_wire_fields() { + for is_class in [false, true] { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(2), &attr(0x21, "job-id", &42u32.to_be_bytes())]))]).unwrap(); + let destination = super::Destination { name: "Office café%20?#".into(), is_class }; + assert_eq!(super::submit_as_at(fake.endpoint(), &destination, b"pdf", &Job::default(), "artist").unwrap(), 42); + let kind = if is_class { "classes" } else { "printers" }; + let path = format!("/{kind}/Office%20caf%C3%A9%2520%3F%23"); + let request = fake.request().unwrap(); + assert!(has(&request, format!("POST {path} HTTP/1.1").as_bytes())); + assert!(has(ipp_body(&request).unwrap(), format!("ipp://{}{path}", fake.server.authority()).as_bytes())); + } +} + +#[test] +fn destination_path_rejects_routing_syntax_before_connecting() { + for name in ["", ".", "..", "../admin", "a/b", "a\\b", "a\r\nb", "a\0b"] { + let destination = super::Destination { name: name.into(), is_class: false }; + assert!(super::destination_path(&destination).is_err(), "{name:?}"); + } + let destination = super::Destination { name: "x".repeat(257), is_class: false }; + assert!(super::destination_path(&destination).is_err()); +} + +#[test] +fn separate_queue_query_preserves_optional_discovery_errors() { + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0403, &[&group(1)]))]).unwrap(); + assert!(super::queues_at(fake.endpoint(), true).is_err(), "authorization refusal is not an empty class list"); + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0x0501, &[&group(1)]))]).unwrap(); + assert!(super::queues_at(fake.endpoint(), true).unwrap().is_empty(), "unsupported class operation is absent"); + let fake = FakeCups::on_tcp(vec![http_reply(&ipp_reply(0, &[&group(1), &group(4), &printer_name("Pool")]))]).unwrap(); + let queues = super::queues_at(fake.endpoint(), true).unwrap(); + assert_eq!(queues.len(), 1); + assert!(queues[0].is_class); + assert!(!queues[0].is_default, "default resolution is caller-owned for this API"); + let request = fake.request().unwrap(); + assert_eq!(&ipp_body(&request).unwrap()[..4], &[1, 1, 0x40, 0x05]); +} + +#[test] +fn ipv6_endpoint_keeps_scope_for_resolution_and_escapes_wire_authority() { + assert_eq!(Server::parse("[::1]").unwrap().authority(), "[::1]:631"); + assert_eq!(Server::parse("::1").unwrap().authority(), "[::1]:631"); + let scoped = Server::parse("[fe80::1%en0]:8631").unwrap(); + assert!(matches!(&scoped, Server::Named(host, 8631) if host == "fe80::1%en0")); + assert_eq!(scoped.authority(), "[fe80::1%25en0]:8631"); + assert_eq!(Server::parse("fe80::1%en0:8631").unwrap().authority(), scoped.authority()); + assert_eq!(Server::parse("fe80::1%en0").unwrap().authority(), "[fe80::1%25en0]:631"); + assert!(Server::parse("[host]:631").is_err()); + assert_eq!(super::connect(&Server::Named("/invalid".into(), 631)).err().unwrap().kind(), std::io::ErrorKind::InvalidInput); + for bad in ["[::1]junk", "[::1]:0", "[::1]:abc", "[fe80::1%]:631", "[fe80::1%x%y]:631", "host%zone"] { + assert!(Server::parse(bad).is_err(), "{bad}"); + } +} + +#[test] +fn long_printer_descriptions_are_not_limited_like_queue_names() { + let description = "Studio ".repeat(200); + let body = ipp_reply(0, &[&group(1), &group(4), &printer_name("Studio"), &attr(0x41, "printer-info", description.as_bytes())]); + let parsed = super::parse_reply(&body).unwrap(); + assert_eq!(parsed.queues[0].info, description); +} + +#[test] +fn destination_limit_is_explicit_and_never_silently_truncates() { + let mut body = vec![1, 1, 0, 0, 0, 0, 0, 1]; + for index in 0..super::MAX_PRINTERS { + body.push(4); + body.extend(printer_name(&format!("Printer{index}"))); + } + body.push(3); + assert_eq!(super::parse_reply(&body).unwrap().queues.len(), super::MAX_PRINTERS); + assert_eq!(body.pop(), Some(3)); + body.push(4); + body.extend(printer_name("OneTooMany")); + body.push(3); + assert!(super::parse_reply(&body).err().unwrap().to_string().contains("too many CUPS destinations")); +} + +#[test] +fn closed_unix_peer_keeps_its_buffered_reply_readable_with_a_deadline() { + let (client, mut peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let body = ipp_reply(0, &[&group(1), &group(4), &printer_name("Studio")]); + peer.write_all(&http_reply(&body)).unwrap(); + drop(peer); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: std::time::Instant::now() + Duration::from_secs(1) }; + assert_eq!(super::read_reply(&mut reader).unwrap(), body); + let mut byte = [0]; + assert_eq!(reader.read(&mut byte).unwrap(), 0); + reader.end = std::time::Instant::now(); + assert_eq!(reader.read(&mut byte).unwrap_err().kind(), std::io::ErrorKind::TimedOut); +} + +#[test] +fn stalled_unix_peer_still_fails_within_the_absolute_read_deadline() { + let (client, _peer) = std::os::unix::net::UnixStream::pair().unwrap(); + let start = std::time::Instant::now(); + let mut stream = super::Stream::Unix(client); + let mut reader = super::DeadlineReader { stream: &mut stream, end: start + Duration::from_millis(80) }; + let mut byte = [0]; + let error = reader.read(&mut byte).unwrap_err(); + assert!(matches!(error.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)); + assert!(start.elapsed() < Duration::from_secs(3)); +} diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index dcc9c53f9e..bf50e3a3fc 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -8,6 +8,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Direct local-CUPS transport, independent of command-line spooler selection. +#[cfg(not(target_arch = "wasm32"))] +pub mod cups; + #[cfg(any(test, windows))] mod progress; #[cfg(any(test, windows))] diff --git a/crates/proto/Cargo.toml b/crates/proto/Cargo.toml new file mode 100644 index 0000000000..528e407a87 --- /dev/null +++ b/crates/proto/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "craft-proto" +description = "Mail protocols without sockets: IMAP4rev1 and SMTP clients over any Read + Write stream" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +base64 = "0.23" +zeroize = "1" +# Internationalization: error messages and user-facing text. +log = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/proto/src/i18n.rs b/crates/proto/src/i18n.rs new file mode 100644 index 0000000000..af0499154d --- /dev/null +++ b/crates/proto/src/i18n.rs @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: Craft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Error message handling for protocol errors. +//! +//! Provides the `said!` macro and related types for creating user-facing error messages. + +pub use crate::said; +use std::fmt; + +/// A value that can be converted to an argument for error messages. +pub trait ToArg { + fn to_arg(&self) -> Arg; +} + +impl ToArg for T { + fn to_arg(&self) -> Arg { + Arg::Plain(format!("{}", self)) + } +} + +/// An argument for error messages. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Arg { + Plain(String), +} + +impl fmt::Display for Arg { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Arg::Plain(s) => f.write_str(s), + } + } +} + +impl Arg { + /// Create an argument from a string. + pub fn said(t: Text) -> Self { + Arg::Plain(format!("{}", t)) + } +} + +/// A text with values: `said!("no folder named {name}", name)`, or +/// `said!("{name} is larger than {mb} MB", name, mb = MAX >> 20)`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Text { + template: String, +} + +impl Text { + /// Preserve text supplied by a server or host without interpreting it. + pub fn verbatim(text: String) -> Self { + Self { template: text } + } + + /// Create a new text with the given template and arguments. + pub fn new(template: &str, args: Vec<(&str, Arg)>) -> Self { + // Substitute only placeholders in the template, never text inserted by a server. + let mut filled = String::new(); + let mut rest = template; + while let Some(open) = rest.find('{') { + filled.push_str(rest.get(..open).unwrap_or_default()); + let after = rest.get(open.saturating_add(1)..).unwrap_or_default(); + let Some(close) = after.find('}') else { + filled.push_str(rest.get(open..).unwrap_or_default()); + rest = ""; + break; + }; + let key = after.get(..close).unwrap_or_default(); + if let Some((_, arg)) = args.iter().find(|(name, _)| *name == key) { + filled.push_str(&arg.to_string()); + } else { + filled.push('{'); + filled.push_str(key); + filled.push('}'); + } + rest = after.get(close.saturating_add(1)..).unwrap_or_default(); + } + filled.push_str(rest); + Text { template: filled } + } +} + +impl fmt::Display for Text { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.template) + } +} + +impl From<&str> for Text { + fn from(s: &str) -> Self { + Text { template: s.to_string() } + } +} + +impl From for Text { + fn from(s: String) -> Self { + Self::verbatim(s) + } +} + +/// The `said!` macro for creating error messages. +#[macro_export] +macro_rules! said { + (@arg $k:ident) => { $crate::i18n::ToArg::to_arg(&$k) }; + (@arg $k:ident = $v:expr) => { $crate::i18n::ToArg::to_arg(&$v) }; + ($t:literal $(, $k:ident $(= $v:expr)?)* $(,)?) => { + $crate::i18n::Text::new($t, vec![$((stringify!($k), $crate::said!(@arg $k $(= $v)?))),*]) + }; +} + +/// Trace only recognized protocol structure, never arbitrary reply text or command arguments. +/// Uppercase text can be private too; capitalization must not determine what is safe to log. +pub fn for_trace(line: &str) -> String { + let line = line.trim_end(); + let mut words = line.split_ascii_whitespace(); + let first = words.next().unwrap_or_default(); + let known = |word: &str| { + matches!( + word, + "OK" | "NO" + | "BAD" + | "BYE" + | "PREAUTH" + | "CAPABILITY" + | "LOGIN" + | "LOGOUT" + | "AUTHENTICATE" + | "SELECT" + | "EXAMINE" + | "CREATE" + | "DELETE" + | "RENAME" + | "SUBSCRIBE" + | "UNSUBSCRIBE" + | "LIST" + | "LSUB" + | "STATUS" + | "APPEND" + | "CHECK" + | "CLOSE" + | "EXPUNGE" + | "SEARCH" + | "FETCH" + | "STORE" + | "COPY" + | "MOVE" + | "UID" + | "IDLE" + | "DONE" + | "NOOP" + | "EHLO" + | "HELO" + | "STARTTLS" + | "AUTH" + | "MAIL" + | "RCPT" + | "DATA" + | "RSET" + | "QUIT" + | "EXISTS" + | "RECENT" + | "FLAGS" + ) + }; + let smtp_code = first.get(..3).is_some_and(|code| code.bytes().all(|b| b.is_ascii_digit())) + && first.as_bytes().first().is_some_and(|b| matches!(b, b'1'..=b'5')); + let tag = first.strip_prefix('A').is_some_and(|digits| !digits.is_empty() && digits.len() <= 16 && digits.bytes().all(|b| b.is_ascii_digit())); + let end = if smtp_code && (first.len() == 3 || first.get(3..4) == Some("-")) { + if first.len() > 3 { 4 } else { 3 } + } else if known(first) { + first.len() + } else if first == "*" || tag { + let second = words.next().unwrap_or_default(); + let last = if first == "*" && !second.is_empty() && second.bytes().all(|b| b.is_ascii_digit()) { + words.next().filter(|word| known(word)) + } else { + known(second).then_some(second) + }; + last.and_then(|word| line.find(word)?.checked_add(word.len())).unwrap_or(first.len()) + } else if first == "+" { + 1 + } else { + 0 + }; + let kept = line.get(..end).unwrap_or_default(); + let left = line.get(end..).unwrap_or_default().trim_start().len(); + match (kept.is_empty(), left) { + (_, 0) => kept.to_owned(), + (true, _) => format!("({left} bytes)"), + (false, _) => format!("{kept} … ({left} bytes)"), + } +} + +/// Server text made fit for an error message: one line, no control characters, not too long. +pub fn tidy(text: &str) -> String { + const MAX_CHARS: usize = 300; + let mut out = String::new(); + let mut space = false; + for (n, c) in text.trim().chars().enumerate() { + if n >= MAX_CHARS { + out.push('…'); + break; + } + if c.is_control() || c.is_whitespace() { + space = !out.is_empty(); + } else { + if space { + out.push(' '); + space = false; + } + out.push(c); + } + } + out +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn inserted_arguments_are_not_interpreted() { + let msg = Text::new("{a} {b}", vec![("a", Arg::Plain("{b}".into())), ("b", Arg::Plain("secret".into()))]); + assert_eq!(msg.to_string(), "{b} secret"); + } + + #[test] + fn simple_message() { + let msg = said!("the server closed the connection"); + assert_eq!(msg.to_string(), "the server closed the connection"); + } + + #[test] + fn message_with_args() { + let msg = said!("the server sent {n} bytes", n = 123); + assert_eq!(msg.to_string(), "the server sent 123 bytes"); + } + + #[test] + fn tidy_removes_control_chars() { + assert_eq!(tidy("hello\x01world"), "hello world"); + assert_eq!(tidy("hello\nworld"), "hello world"); + } +} diff --git a/crates/proto/src/imap/gmail_labels_tests.rs b/crates/proto/src/imap/gmail_labels_tests.rs new file mode 100644 index 0000000000..441e3220bf --- /dev/null +++ b/crates/proto/src/imap/gmail_labels_tests.rs @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Gmail's labels of a message (`X-GM-LABELS`, Google's "Gmail IMAP extensions", #1153). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +fn labels(server: &str) -> Vec<(u32, Option>)> { + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap_or_default(); + got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect() +} + +fn owned(labels: &[&str]) -> Option> { + Some(labels.iter().map(|l| l.to_string()).collect()) +} + +#[test] +fn labels_come_with_the_flags() { + let mut server = String::new(); + // Atoms, quoted strings, Gmail's own with their backslash, an empty list. + server += "* 1 FETCH (UID 1 FLAGS (\\Seen) X-GM-MSGID 11 X-GM-LABELS (\\Inbox \\Sent Important \"Muy Importante\"))\r\n"; + server += "* 2 FETCH (X-GM-LABELS (foo) UID 2 FLAGS ())\r\n"; + server += "* 3 FETCH (UID 3 FLAGS () X-GM-LABELS ())\r\n"; + // A literal, and modified UTF-7 as mailbox names are written. + server += "* 4 FETCH (UID 4 FLAGS () X-GM-LABELS ({12}\r\nWork/Clients \"Caf&AOk-\" &AOk-t&AOk-))\r\n"; + // UTF-8 as it stands, and an ampersand that isn't the start of a shifted run. + server += "* 5 FETCH (UID 5 FLAGS () X-GM-LABELS (\"Été\" \"Tom & Jerry\" \\Drafts))\r\n"; + // A message the server gave none for. + server += "* 6 FETCH (UID 6 FLAGS ())\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap(); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-MSGID X-GM-LABELS)\r\n"); + let got: Vec<(u32, Option>)> = got.into_iter().map(|f| (f.uid, f.gmail_labels)).collect(); + assert_eq!( + got, + [ + (1, owned(&["\\Inbox", "\\Sent", "Important", "Muy Importante"])), + (2, owned(&["foo"])), + (3, owned(&[])), + (4, owned(&["Work/Clients", "Café", "été"])), + (5, owned(&["Été", "Tom & Jerry", "\\Drafts"])), + (6, None), + ] + ); +} + +#[test] +fn the_later_word_counts_and_other_servers_are_not_asked() { + let got = labels( + "* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\n* 1 FETCH (UID 1 X-GM-LABELS (b c))\r\n* 1 FETCH (UID 1 FLAGS ())\r\nA0001 OK done\r\n", + ); + assert_eq!(got, [(1, owned(&["b", "c"]))]); + // Without asking for them, labels the server gives anyway are not taken. + let mut s = Script::new("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\nA0001 OK done\r\n"); + let plain = Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(); + assert_eq!(plain.first().and_then(|f| f.gmail_labels.clone()), None); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); +} + +#[test] +fn hostile_label_lists_are_kept_small() { + // A huge list: only so many are kept. + let many: String = (0..1000).map(|n| format!(" L{n}")).collect(); + let got = labels(&format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({many}))\r\nA0001 OK done\r\n")); + assert_eq!(got.first().and_then(|(_, l)| l.as_ref()).map(Vec::len), Some(MAX_GMAIL_LABELS)); + // A long label is cut, at a character boundary. + let long = "é".repeat(400); + let got = labels(&format!("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (\"{long}\"))\r\nA0001 OK done\r\n")); + let label = got.first().and_then(|(_, l)| l.as_ref()).and_then(|l| l.first()).cloned().unwrap_or_default(); + assert!(label.len() <= MAX_GMAIL_LABEL_LEN && !label.is_empty() && label.chars().all(|c| c == 'é')); + // A NUL in a literal is carried as text for the model to clean; a list inside the list is + // skipped; a list that isn't closed is read as far as it goes. + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS ({3}\r\na\0b (nested list) ok))\r\nA0001 OK done\r\n"); + assert_eq!(got, [(1, owned(&["a\0b", "ok"]))]); + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a (b\r\nA0001 OK done\r\n"); + assert!(got.len() <= 1); + // Something other than a list is no labels. + let got = labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS NIL)\r\nA0001 OK done\r\n"); + assert_eq!(got, [(1, None)]); +} + +#[test] +fn a_fetch_keeps_no_more_label_bytes_than_its_budget() { + // Labels as literals, which the cap on a command's text doesn't count: each message with as + // many as a response may carry, of 256 bytes each. Past 32 MiB the rest come without. + let label = "x".repeat(MAX_GMAIL_LABEL_LEN); + let list: String = (0..MAX_LITERALS).map(|_| format!(" {{{}}}\r\n{label}", label.len())).collect(); + let count = MAX_GMAIL_LABEL_BYTES / (MAX_GMAIL_LABEL_LEN * MAX_LITERALS) + 4; + let mut server = String::new(); + for uid in 1..=count { + server += &format!("* {uid} FETCH (UID {uid} FLAGS () X-GM-LABELS ({list}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::try_from(count).unwrap_or(u32::MAX), uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags_gmail("1:*").unwrap(); + assert_eq!(got.len(), count); + let kept: usize = got.iter().filter_map(|f| f.gmail_labels.as_ref()).flatten().map(String::len).sum(); + assert!(kept <= MAX_GMAIL_LABEL_BYTES); + assert!(got.last().is_some_and(|f| f.gmail_labels.is_none())); +} + +proptest! { + #[test] + fn arbitrary_label_lists_never_panic(inside in proptest::collection::vec(any::(), 0..400)) { + let mut server = b"* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (".to_vec(); + server.extend(inside.iter().filter(|b| **b != b'\r' && **b != b'\n')); + server.extend_from_slice(b"))\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + if let Ok(got) = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*") { + for labels in got.iter().filter_map(|f| f.gmail_labels.as_ref()) { + prop_assert!(labels.len() <= MAX_GMAIL_LABELS); + } + } + } + + #[test] + fn arbitrary_server_bytes_never_panic_in_a_gmail_fetch(server in proptest::collection::vec(any::(), 0..600)) { + let mut s = Script::new(server); + let _ = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*"); + } +} + +#[test] +fn a_folder_other_than_the_inbox_asks_for_labels_alone() { + let mut s = Script::new("* 1 FETCH (UID 1 FLAGS () X-GM-MSGID 5 X-GM-LABELS (a))\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-LABELS)\r\n"); + // An id it wasn't asked for is not taken. + assert_eq!(got.into_iter().map(|f| (f.uid, f.gmail_id, f.gmail_labels)).collect::>(), [(1, None, owned(&["a"]))]); +} + +#[test] +fn nil_in_a_list_is_no_label() { + assert_eq!(labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (NIL))\r\nA0001 OK done\r\n"), [(1, owned(&[]))]); + // A label called so comes quoted, and is one. + assert_eq!(labels("* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (nil \"NIL\"))\r\nA0001 OK done\r\n"), [(1, owned(&["NIL"]))]); +} + +#[test] +fn tiny_labels_count_against_the_budget_too() { + // Empty labels, as many as a message keeps: each costs its overhead, so the budget still ends. + let list: String = (0..MAX_GMAIL_LABELS).map(|_| " \"\"").collect(); + let per_message = MAX_GMAIL_LABELS * LABEL_OVERHEAD; + let count = MAX_GMAIL_LABEL_BYTES / per_message + 4; + let mut server = String::new(); + for uid in 1..=count { + server += &format!("* {uid} FETCH (UID {uid} FLAGS () X-GM-LABELS ({list}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::try_from(count).unwrap_or(u32::MAX), uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags_labels("1:*").unwrap(); + assert_eq!(got.len(), count); + let kept = got.iter().filter(|f| f.gmail_labels.is_some()).count(); + assert!(kept * per_message <= MAX_GMAIL_LABEL_BYTES && kept < count); +} + +#[test] +fn a_big_folders_listing_is_not_cut_short_for_its_size() { + // 300,000 messages with labels: more text than one command may otherwise bring (32 MiB). + let count: u32 = 300_000; + let mut server = String::with_capacity(count as usize * 200); + for uid in 1..=count { + server += &format!( + "* {uid} FETCH (FLAGS (\\Seen) UID {uid} X-GM-LABELS (\\Inbox \\Important \"Work/Clients and partners\" \"Receipts 2026\" \"Travel/Japan\"))\r\n" + ); + } + assert!(server.len() > MAX_COMMAND_TEXT); + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: count, uid_validity: 1, uid_next: count + 1 }; + assert_eq!(imap.uid_fetch_flags_labels("1:*").map(|got| got.len()), Ok(count as usize)); + // The room is the listing's alone: the next command has the usual cap again. + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); +} + +#[test] +fn a_mailbox_claimed_huge_cant_fill_memory_with_flags() { + // Any server (no Gmail here): ten million messages claimed, then message after message with + // every flag it may have. The text it may send is capped, and so are the flags kept: the + // listing fails, and never hands back messages that seem to have lost their flags. + let flags: Vec = (0..MAX_FLAGS).map(|n| format!("f{n}")).collect(); + let flags = flags.join(" "); + let mut server = String::new(); + let mut uid = 0u32; + while server.len() < MAX_FETCH_TEXT / 4 { + uid += 1; + server += &format!("* {uid} FETCH (UID {uid} FLAGS ({flags}))\r\n"); + } + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: 10_000_000, uid_validity: 1, uid_next: 0 }; + let got = imap.uid_fetch_flags("1:*"); + assert!(matches!(&got, Err(ProtoError::Protocol(m)) if format!("{m:?}").contains("more flags")), "{:?}", got.as_ref().map(Vec::len)); + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); + // And what it may send at all stays within the ceiling, however many messages are claimed. + let mut s = Script::new(format!("* OK {}\r\n", "x".repeat(60_000)).repeat(MAX_FETCH_TEXT / 60_000 + 8)); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: u32::MAX, uid_validity: 1, uid_next: 0 }; + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn an_honest_big_mailboxs_flags_fit_the_budget() { + // A million messages with three flags each. + const { assert!(1_000_000 * (ENTRY_OVERHEAD + 3 * (FLAG_OVERHEAD + 8)) <= MAX_FLAG_BYTES) }; +} + +#[test] +fn a_small_folders_listing_still_has_its_cap() { + // One message, and more than 32 MiB of other lines before it: refused as before. + let junk = format!("* OK {}\r\n", "x".repeat(60_000)); + let mut server = junk.repeat(MAX_COMMAND_TEXT / 60_000 + 8); + server += "* 1 FETCH (UID 1 FLAGS () X-GM-LABELS (a))\r\nA0001 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.selected = Selected { exists: 1, uid_validity: 1, uid_next: 2 }; + assert!(matches!(imap.uid_fetch_flags_labels("1:*"), Err(ProtoError::Protocol(_)))); + assert_eq!(imap.text_cap, MAX_COMMAND_TEXT); +} diff --git a/crates/proto/src/imap/gmail_tests.rs b/crates/proto/src/imap/gmail_tests.rs new file mode 100644 index 0000000000..451690bc51 --- /dev/null +++ b/crates/proto/src/imap/gmail_tests.rs @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Gmail's IMAP extensions (#911): `X-GM-MSGID` and `X-GM-RAW`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; +use crate::script::Script; + +#[test] +fn gmail_ids_come_with_the_flags() { + let mut server = String::new(); + server += "* 1 FETCH (UID 4 FLAGS (\\Seen) X-GM-MSGID 1278455344230334865)\r\n"; + server += "* 2 FETCH (X-GM-MSGID 18446744073709551615 UID 7 FLAGS ())\r\n"; + // An id that is no number, or 0, is none; a later word about a message without one keeps it. + server += "* 3 FETCH (UID 9 FLAGS () X-GM-MSGID 12ab)\r\n"; + server += "* 4 FETCH (UID 10 FLAGS () X-GM-MSGID 0)\r\n"; + server += "* 2 FETCH (UID 7 FLAGS (\\Flagged))\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags_gmail("1:*").unwrap(); + let ids: Vec<(u32, Option)> = got.iter().map(|f| (f.uid, f.gmail_id)).collect(); + assert_eq!(ids, [(4, Some(1_278_455_344_230_334_865)), (7, Some(u64::MAX)), (9, None), (10, None)]); + assert_eq!(got.get(1).map(|f| f.flags.clone()), Some(vec!["\\Flagged".to_string()])); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS X-GM-MSGID X-GM-LABELS)\r\n"); + // Without asking for them, an id the server gives anyway is not taken. + let mut s = Script::new("* 1 FETCH (UID 4 FLAGS () X-GM-MSGID 5)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap().first().and_then(|f| f.gmail_id), None); +} + +#[test] +fn gmail_search_is_quoted_and_kept_to_its_set() { + let mut s = Script::new("* SEARCH 9 4 0 x 4 12 600\r\nA0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + // In UID order, once each, and only what the set names. + assert_eq!(imap.uid_search_gmail("4:12", "category:social"), Ok(vec![4, 9, 12])); + // Quotes are quoted; CR, LF and NUL never go out. + assert_eq!(imap.uid_search_gmail("1:*", "category:\"x\"\r\nA9 DELETE INBOX\0"), Ok(vec![])); + assert_eq!( + s.sent(), + "A0001 UID SEARCH UID 4:12 UNDELETED X-GM-RAW \"category:social\"\r\n\ + A0002 UID SEARCH UID 1:* UNDELETED X-GM-RAW \"category:\\\"x\\\"A9 DELETE INBOX\"\r\n" + ); + // A refusal is said. + let mut s = Script::new("A0001 BAD no such search\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:forums"), Err(ProtoError::Rejected(_)))); + // What can't be sent is refused unsent. + for (set, query) in [("1:*", ""), ("1:*", "\r\n"), ("1:*", "kategorie:äöü"), ("1 2", "category:social"), ("", "category:social")] { + let mut s = Script::new("A0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail(set, query), Err(ProtoError::Protocol(_))), "{set:?} {query:?}"); + assert_eq!(s.sent(), "", "{set:?} {query:?}"); + } +} + +#[test] +fn gmail_search_takes_no_more_than_its_cap() { + let many: String = (1..=6000).map(|n| format!(" {n}")).collect(); + let mut s = Script::new(format!("* SEARCH{many}\r\nA0001 OK done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:promotions").map(|uids| uids.len()), Ok(MAX_GMAIL_FOUND)); + // As many as the cap, at the longest a UID is written, fit in one line. + let longest: String = (0..MAX_GMAIL_FOUND).map(|_| " 4294967295").collect(); + assert!(format!("* SEARCH{longest}").len() < crate::MAX_LINE); +} + +#[test] +fn a_gmail_answer_too_long_is_refused_and_the_session_goes_on() { + let long: String = (0..20_000).map(|n| format!(" {}", 1_000_000_000u32 + n)).collect(); + assert!(long.len() > crate::MAX_LINE); + let server = format!("* SEARCH{long}\r\n* SEARCH 3\r\nA0001 OK done\r\n* SEARCH 5\r\nA0002 OK done\r\n"); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_search_gmail("1:*", "category:social"), Err(ProtoError::Rejected(_)))); + // The next command is answered as if nothing had happened. + assert_eq!(imap.uid_search_gmail("1:*", "category:social"), Ok(vec![5])); + // Elsewhere a line that long still ends the session, and a tagged one is never read past. + let mut s = Script::new(format!("* SEARCH{long}\r\nA0001 OK done\r\n")); + assert!(matches!(Imap::resume(&mut s).uid_search_header("Message-ID", "x"), Err(ProtoError::Protocol(_)))); + let mut s = Script::new(format!("A0001 OK{long}\r\n")); + assert!(matches!(Imap::resume(&mut s).uid_search_gmail("1:*", "category:social"), Err(ProtoError::Protocol(_)))); +} diff --git a/crates/proto/src/imap/idle.rs b/crates/proto/src/imap/idle.rs new file mode 100644 index 0000000000..ecccec50cc --- /dev/null +++ b/crates/proto/src/imap/idle.rs @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! IDLE (RFC 2177): the server says when a mailbox changes, instead of being asked. The session +//! is in one of two states, and this module only moves it between them: a mailbox is selected +//! (EXAMINE), [`Imap::idle_begin`] puts the server to waiting, [`Imap::idle_poll`] hears what it +//! says (a line a second at most, so that the caller can look at the clock and at whether it was +//! told to stop), and [`Imap::idle_end`] says DONE and reads on to the command's end. +//! +//! The server's word is bounded as everywhere: a line over [`crate::MAX_LINE`] and a line that +//! announces a literal end the session, and the caller counts what it hears. + +use std::io::{Read, Write}; + +use super::Imap; +use super::parse; +use crate::i18n::{Arg, said}; +use crate::{ProtoError, for_trace}; + +/// Most lines [`Imap::idle_end`] reads on the way to the command's end. +const MAX_ENDING: usize = 256; +/// Most quiet reads [`Imap::idle_end`] waits through for one line. +const MAX_QUIET: usize = 30; + +/// What the server said while it was waiting. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdleEvent { + /// `* n EXISTS`: the mailbox now has `n` messages. + Exists(u32), + /// `* n EXPUNGE`: the message with that sequence number is gone. + Expunge(u32), + /// `* n RECENT`: `n` messages are new since the mailbox was opened. + Recent(u32), + /// Anything else the server said unasked (a flag change, a status line): not news of mail. + Other, + /// The server ended the command itself (`tag OK`): IDLE has to be begun again. + Ended, +} + +/// From the text after `* `: `3 EXISTS`. +fn event_from(rest: &[u8], secrets: &crate::Secrets) -> Result { + let text = String::from_utf8_lossy(rest); + let mut words = text.split_whitespace(); + let (first, second) = (words.next().unwrap_or(""), words.next().unwrap_or("")); + let count = first.parse::().ok(); + Ok(match (count, second.to_ascii_uppercase().as_str()) { + (Some(n), "EXISTS") => IdleEvent::Exists(n), + (Some(n), "EXPUNGE") => IdleEvent::Expunge(n), + (Some(n), "RECENT") => IdleEvent::Recent(n), + _ if first.eq_ignore_ascii_case("BYE") => { + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = crate::tidy(&secrets.hide(&text))))); + } + _ => IdleEvent::Other, + }) +} + +impl Imap { + /// Send IDLE and wait for the server's go-ahead. The session has to have a mailbox selected; + /// a server that refuses (NO, BAD) is an error. While idle, the only commands that may follow + /// are [`Imap::idle_poll`] and [`Imap::idle_end`]. + pub fn idle_begin(&mut self) -> Result<(), ProtoError> { + if self.idle_tag.is_some() { + return Err(ProtoError::Protocol(said!("the server is already idling"))); + } + self.idle_pending.clear(); + let tag = self.tag(); + self.text_seen = 0; + log::trace!("C: {tag} IDLE"); + self.wire.write(format!("{tag} IDLE\r\n").as_bytes())?; + self.wire.flush()?; + self.idle_tag = Some(tag.clone()); + // Untagged lines may come before the `+`; the tagged answer is a refusal. + for _ in 0..MAX_ENDING { + match self.read_response()? { + super::Response::GoAhead => return Ok(()), + super::Response::Status { tag: Some(answered), line } => { + self.idle_tag = None; + if answered != tag { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + return Err(ProtoError::Rejected(self.refusal(&line))); + } + super::Response::Status { tag: None, line } => { + if line.status == parse::Status::Bye { + self.idle_tag = None; + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said(self.refusal(&line))))); + } + self.note_status(&line); + } + super::Response::Data(values) => { + self.note_data(&values); + let event = match (values.first().and_then(parse::Value::number), values.get(1).and_then(parse::Value::atom)) { + (Some(n), Some(word)) if word.eq_ignore_ascii_case("EXISTS") => IdleEvent::Exists(n), + (Some(n), Some(word)) if word.eq_ignore_ascii_case("EXPUNGE") => IdleEvent::Expunge(n), + (Some(n), Some(word)) if word.eq_ignore_ascii_case("RECENT") => IdleEvent::Recent(n), + _ => IdleEvent::Other, + }; + self.idle_pending.push_back(event); + } + } + } + self.idle_tag = None; + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// The next thing the server says while idle, or `None` after one read if the line is + /// incomplete or no bytes arrived (see [`crate::MAX_LINE`] for the bound on a line). + pub fn idle_poll(&mut self) -> Result, ProtoError> { + let Some(tag) = self.idle_tag.clone() else { + return Err(ProtoError::Protocol(said!("the server isn't idling"))); + }; + if let Some(event) = self.idle_pending.pop_front() { + return Ok(Some(event)); + } + let Some(line) = self.wire.poll_line()? else { return Ok(None) }; + if log::log_enabled!(log::Level::Trace) { + log::trace!("S: {}", for_trace(&self.secrets.hide(&String::from_utf8_lossy(&line)))); + } + if let Some(rest) = line.strip_prefix(b"* ") { + // A literal in what is said while idle is nothing a server has a reason to send. + if parse::literal_marker(rest).is_some() { + return Err(ProtoError::Protocol(said!("the server sent data it has no reason to send while idle"))); + } + return event_from(rest, &self.secrets).map(Some); + } + let text = String::from_utf8_lossy(&line); + if text.strip_prefix(tag.as_str()).is_some_and(|rest| rest.starts_with(' ')) { + // The server ended IDLE by itself (a timeout of its own, say). + self.idle_tag = None; + let status = text.split_ascii_whitespace().nth(1).and_then(parse::Status::parse); + return match status { + Some(parse::Status::Ok) => Ok(Some(IdleEvent::Ended)), + Some(parse::Status::No | parse::Status::Bad) => Err(ProtoError::Rejected(said!("the server didn't end IDLE properly"))), + _ => Err(ProtoError::Protocol(said!("the server returned an invalid IDLE completion"))), + }; + } + Err(ProtoError::Protocol(said!("the server said something that is no news while idle"))) + } + + /// Say DONE and read what the server still has to say, up to the end of the command. What was + /// said on the way is given back. After this the session is as it was before + /// [`Imap::idle_begin`]. + pub fn idle_end(&mut self) -> Result, ProtoError> { + let Some(tag) = self.idle_tag.take() else { + return Err(ProtoError::Protocol(said!("the server isn't idling"))); + }; + log::trace!("C: DONE"); + self.wire.write(b"DONE\r\n")?; + self.wire.flush()?; + let mut events: Vec<_> = self.idle_pending.drain(..).collect(); + for _ in 0..MAX_ENDING { + // The server may take a moment to answer: a few polls of the stream's own wait. + let mut polled = None; + for _ in 0..MAX_QUIET { + polled = self.wire.poll_line()?; + if polled.is_some() { + break; + } + } + let Some(line) = polled else { return Err(ProtoError::Io(said!("the server took too long to answer"))) }; + if let Some(rest) = line.strip_prefix(b"* ") { + if parse::literal_marker(rest).is_some() { + return Err(ProtoError::Protocol(said!("the server sent data it has no reason to send while idle"))); + } + events.push(event_from(rest, &self.secrets)?); + continue; + } + let text = String::from_utf8_lossy(&line); + let mut words = text.splitn(3, ' '); + let (answered, status) = (words.next().unwrap_or(""), words.next().unwrap_or("")); + if answered != tag { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + return match parse::Status::parse(status) { + Some(parse::Status::Ok) => Ok(events), + _ => Err(ProtoError::Rejected(said!("the server didn't end IDLE properly"))), + }; + } + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// Whether the server said it can do IDLE (upper-cased capability list as last said). + pub fn offers_idle(&self) -> bool { + self.offers("IDLE") + } +} diff --git a/crates/proto/src/imap/idle_tests.rs b/crates/proto/src/imap/idle_tests.rs new file mode 100644 index 0000000000..cb0515cdd5 --- /dev/null +++ b/crates/proto/src/imap/idle_tests.rs @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +// Polling now yields after each underlying read, including partial lines. +fn next_event(imap: &mut Imap<&mut Script>) -> Result, ProtoError> { + for _ in 0..crate::MAX_LINE + 2 { + match imap.idle_poll() { + Ok(None) => continue, + result => return result, + } + } + panic!("script failed to produce an event within its bounded input"); +} + +#[test] +fn idle_goes_ahead_hears_news_and_ends() { + // The go-ahead is the first line; the rest is heard by polling. + let mut s2 = Script::new("+ idling\r\n* 4 EXISTS\r\n* 1 RECENT\r\n* 2 FETCH (FLAGS (\\Seen))\r\n* 3 EXPUNGE\r\n"); + let mut imap2 = Imap::resume(&mut s2); + imap2.idle_begin().unwrap(); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Exists(4))); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Recent(1))); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Other)); + assert_eq!(next_event(&mut imap2).unwrap(), Some(IdleEvent::Expunge(3))); + assert_eq!(s2.sent(), "A0001 IDLE\r\n"); + + let mut s3 = Script::new("+ idling\r\n* 5 EXISTS\r\nA0001 OK IDLE terminated\r\n"); + let mut imap3 = Imap::resume(&mut s3); + imap3.idle_begin().unwrap(); + assert_eq!(imap3.idle_end().unwrap(), vec![IdleEvent::Exists(5)]); + assert_eq!(s3.sent(), "A0001 IDLE\r\nDONE\r\n"); +} + +#[test] +fn a_refusal_or_an_early_end_or_a_goodbye_is_said() { + let mut s = Script::new("A0001 NO [CANNOT] not now\r\n"); + assert!(matches!(Imap::resume(&mut s).idle_begin(), Err(ProtoError::Rejected(_)))); + let mut s = Script::new("+ idling\r\nA0001 OK the server gave up waiting\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert_eq!(next_event(&mut imap).unwrap(), Some(IdleEvent::Ended)); + // Not idling any more: nothing to poll or to end. + assert!(matches!(next_event(&mut imap), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.idle_end(), Err(ProtoError::Protocol(_)))); + let mut s = Script::new("+ idling\r\n* BYE going away\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert!(matches!(next_event(&mut imap), Err(ProtoError::Io(_)))); +} + +#[test] +fn what_a_server_has_no_reason_to_send_while_idle_ends_the_session() { + for hostile in ["* 1 FETCH (BODY[] {5}\r\n", "A0099 OK that was never asked\r\n", "garbage\r\n", "* 1 EXISTS\r\n".repeat(0).as_str()] { + let mut s = Script::new(format!("+ idling\r\n{hostile}")); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + let got = next_event(&mut imap); + assert!(got.is_err() || hostile.is_empty(), "{hostile:?}: {got:?}"); + } + // A line longer than any a server is allowed. + let mut long = b"+ idling\r\n* ".to_vec(); + long.extend(std::iter::repeat_n(b'x', crate::MAX_LINE + 10)); + long.extend_from_slice(b"\r\n"); + let mut s = Script::whole(long); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert!(matches!(next_event(&mut imap), Err(ProtoError::Protocol(_)))); +} + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_while_idle(server in proptest::collection::vec(any::(), 0..800), greeted in any::()) { + let mut bytes = if greeted { b"+ idling\r\n".to_vec() } else { Vec::new() }; + bytes.extend_from_slice(&server); + let mut s = Script::new(&bytes); + let mut imap = Imap::resume(&mut s); + if imap.idle_begin().is_ok() { + // However much is said, polling ends (the script runs out) and nothing is kept without bound. + for _ in 0..2_000 { + match next_event(&mut imap) { + Ok(Some(_)) => {} + Ok(None) | Err(_) => break, + } + } + let _ = imap.idle_end(); + } + } + + #[test] + fn idle_shaped_noise_never_panics(words in proptest::collection::vec(proptest::sample::select(&["* ", "1 ", "EXISTS", "EXPUNGE", "RECENT", " ", "\r\n", "A0001 OK ", "BYE ", "{9}", "FETCH (", ")"][..]), 0..60)) { + let mut s = Script::new(format!("+ go\r\n{}", words.concat())); + let mut imap = Imap::resume(&mut s); + if imap.idle_begin().is_ok() { + for _ in 0..200 { + if !matches!(next_event(&mut imap), Ok(Some(_))) { + break; + } + } + let _ = imap.idle_end(); + } + } +} + +#[test] +fn notifications_before_continuation_are_delivered() { + let mut s = Script::new("* 4 EXISTS\r\n* 2 EXPUNGE\r\n+ idling\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + assert_eq!(imap.idle_poll().unwrap(), Some(IdleEvent::Exists(4))); + assert_eq!(imap.idle_end().unwrap(), vec![IdleEvent::Expunge(2)]); +} + +#[test] +fn idle_bye_errors_hide_registered_secrets() { + for ending in [false, true] { + let mut s = Script::new("+ idling\r\n* BYE test-token\r\n"); + let mut imap = Imap::resume(&mut s); + imap.secrets.add("test-token"); + imap.idle_begin().unwrap(); + let error = if ending { imap.idle_end().unwrap_err() } else { next_event(&mut imap).unwrap_err() }; + assert!(!error.to_string().contains("test-token")); + } +} + +#[test] +fn idle_completion_requires_a_valid_success_status() { + for (status, rejected) in [("NO", true), ("BAD", true), ("nonsense", false)] { + let mut s = Script::new(format!("+ idling\r\nA0001 {status} failed\r\n")); + let mut imap = Imap::resume(&mut s); + imap.idle_begin().unwrap(); + let error = next_event(&mut imap).unwrap_err(); + assert!(if rejected { matches!(error, ProtoError::Rejected(_)) } else { matches!(error, ProtoError::Protocol(_)) }); + } +} diff --git a/crates/proto/src/imap/limits_tests.rs b/crates/proto/src/imap/limits_tests.rs new file mode 100644 index 0000000000..9b802055c0 --- /dev/null +++ b/crates/proto/src/imap/limits_tests.rs @@ -0,0 +1,215 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! What one command may make the client keep or read, however much the server sends. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +/// A session whose open mailbox has `exists` messages and the next UID `uid_next`. +fn opened(s: &mut Script, exists: u32, uid_next: u32) -> Imap<&mut Script> { + let mut imap = Imap::resume(s); + imap.selected = Selected { exists, uid_validity: 1, uid_next }; + imap +} + +/// `lines` lines made by `line(n)`. +fn flood(lines: usize, line: impl Fn(usize) -> String) -> String { + (0..lines).map(line).collect() +} + +fn padding() -> String { + "x".repeat(60 * 1024) +} + +#[test] +fn a_flood_of_long_lines_ends_the_command() { + let pad = padding(); + // 600 lines of 60 KB are more than the 32 MB one command may bring. + let server = flood(600, |n| format!("* {n} FETCH (UID {} FLAGS ({pad}))\r\n", n + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let err = opened(&mut s, 1000, 2000).uid_fetch_flags("1:*").unwrap_err(); + assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too much")), "{err:?}"); + // The same in a list. + let server = flood(600, |n| format!("* LIST () \"/\" \"{n}{pad}\"\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + assert!(matches!(opened(&mut s, 0, 0).list(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn a_flood_of_responses_ends_the_command() { + let server = "* OK still here\r\n".repeat(MAX_RESPONSES + 1) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let err = opened(&mut s, 0, 0).uid_fetch_sizes("1:*").unwrap_err(); + assert!(matches!(err, ProtoError::Protocol(ref m) if m.to_string().contains("too many")), "{err:?}"); +} + +#[test] +fn a_list_keeps_a_capped_number_of_mailboxes() { + let server = flood(MAX_MAILBOXES + 500, |n| format!("* LIST () \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = opened(&mut s, 0, 0).list().unwrap(); + assert_eq!(got.len(), MAX_MAILBOXES); + assert_eq!(got.first().map(|m| m.raw.as_str()), Some("f0")); + // #991: and how many were dropped is said; none, for a list kept whole. + let server = flood(MAX_MAILBOXES + 500, |n| format!("* LIST () \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + assert_eq!(opened(&mut s, 0, 0).list_counted().unwrap().1, 500); + let mut s = Script::new("* LIST () \"/\" a\r\n* LIST () \"/\" a\r\nA0001 OK done\r\n"); + assert_eq!( + opened(&mut s, 0, 0).list_counted().unwrap(), + (vec![Mailbox { name: "a".into(), raw: "a".into(), delimiter: Some('/'), flags: Vec::new() }], 0) + ); +} + +/// #991: a list keeps a bounded number of bytes too, however many mailboxes that is. +#[test] +fn a_list_keeps_a_capped_number_of_bytes() { + let flags: Vec = (0..MAX_FLAGS).map(|n| format!("\\F{n}{}", "x".repeat(MAX_FLAG_LEN - 8))).collect(); + let flags = flags.join(" "); + let server = flood(1_500, |n| format!("* LIST ({flags}) \"/\" f{n}\r\n")) + "A0001 OK done\r\n"; + let mut s = Script::new(server); + let (got, dropped) = opened(&mut s, 0, 0).list_counted().unwrap(); + assert_eq!(got.len() + dropped, 1_500); + let kept: usize = got.iter().map(|m| m.raw.len() * 2 + m.name.len() + m.flags.iter().map(String::len).sum::()).sum(); + assert!(!got.is_empty() && got.len() < 1_500, "{}", got.len()); + // The last one kept may take it over by one mailbox's worth, never more. + assert!(kept < MAX_LIST_BYTES + MAX_LINE, "{kept}"); +} + +#[test] +fn names_and_flags_are_kept_short() { + let long_flag = "é".repeat(400); + let long_name = "n".repeat(MAX_MAILBOX_NAME + 1); + let server = format!("* LIST ({long_flag} \\Sent) \"/\" Fine\r\n* LIST () \"/\" {long_name}\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + let got = opened(&mut s, 0, 0).list().unwrap(); + // The mailbox with the oversized name is left out, not cut into another one. + assert_eq!(got.len(), 1); + assert!(got[0].flags[0].len() <= MAX_FLAG_LEN && got[0].flags[0].chars().all(|c| c == 'é')); + assert_eq!(got[0].flags[1], "\\Sent"); + + let server = format!("* 1 FETCH (UID 1 FLAGS ({long_flag}))\r\nA0001 OK done\r\n"); + let mut s = Script::new(server); + let got = opened(&mut s, 1, 2).uid_fetch_flags("1:*").unwrap(); + assert!(got[0].flags[0].len() <= MAX_FLAG_LEN); +} + +#[test] +fn only_uids_that_were_asked_for_and_exist_are_kept() { + let server = "* 1 FETCH (UID 3 FLAGS (\\Seen))\r\n* 2 FETCH (UID 7 FLAGS ())\r\n* 3 FETCH (UID 9 FLAGS ())\r\n* 4 FETCH (UID 4000000000 FLAGS ())\r\n\ + * 5 FETCH (UID 10 FLAGS ())\r\nA0001 OK done\r\n"; + // Not in the set. + let mut s = Script::new(server); + let got = opened(&mut s, 5, 11).uid_fetch_flags("3,8:9").unwrap(); + assert_eq!(got.iter().map(|f| f.uid).collect::>(), [3, 9]); + // UIDNEXT is only a snapshot: later deliveries must not be discarded. + let sizes = server.replace("FLAGS (\\Seen)", "RFC822.SIZE 5").replace("FLAGS ()", "RFC822.SIZE 6"); + let mut s = Script::new(sizes); + let got = opened(&mut s, 5, 10).uid_fetch_sizes("1:*").unwrap(); + assert_eq!(got, [(3, 5), (7, 6), (9, 6), (10, 6), (4000000000, 6)]); +} + +#[test] +fn more_distinct_uids_than_the_mailbox_can_hold_fail_the_command() { + // 3 messages: room for 2 * 3 + FETCH_SLACK distinct UIDs, and not one more. + let room = 2 * 3 + FETCH_SLACK; + let many = |n: usize| flood(n, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(many(room)); + assert_eq!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*").unwrap().len(), room); + let mut s = Script::new(many(room + 1)); + assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + let sizes = flood(room + 1, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(sizes); + assert!(matches!(opened(&mut s, 3, u32::MAX).uid_fetch_sizes("1:*"), Err(ProtoError::Protocol(_)))); + // The same UID again and again is one. + let same = flood(room * 3, |_| "* 1 FETCH (UID 1 FLAGS ())\r\n".to_string()) + "A0001 OK done\r\n"; + let mut s = Script::new(same); + assert_eq!(opened(&mut s, 3, 100).uid_fetch_flags("1:*").unwrap().len(), 1); +} + +#[test] +fn set_ranges_read_what_is_written() { + assert_eq!(set_ranges("1:*", 9), Some(vec![(1, 9)])); + assert_eq!(set_ranges("5,9,20:12", 9), Some(vec![(5, 5), (9, 9), (12, 20)])); + assert_eq!(set_ranges("1:x", 9), None); + assert_eq!(set_ranges("", 9), None); +} + +proptest! { + /// Whatever the server sends, the command ends, and what it keeps is bounded by the caps. + #[test] + fn arbitrary_responses_are_kept_within_bounds(lines in proptest::collection::vec(("[ -~]{0,200}", any::(), 0usize..4), 0..400)) { + let server: String = lines + .iter() + .map(|(text, uid, kind)| match kind { + 0 => format!("* LIST (\\{text}) \"/\" {text}\r\n"), + 1 => format!("* 1 FETCH (UID {uid} FLAGS ({text}))\r\n"), + 2 => format!("* 1 FETCH (UID {uid} RFC822.SIZE {uid})\r\n"), + _ => format!("* {text}\r\n"), + }) + .collect::() + + "A0001 OK done\r\n"; + let mut s = Script::new(server.clone()); + if let Ok(list) = opened(&mut s, 10, 50).list() { + prop_assert!(list.len() <= MAX_MAILBOXES); + prop_assert!(list.iter().all(|m| m.raw.len() <= MAX_MAILBOX_NAME && m.flags.len() <= MAX_FLAGS && m.flags.iter().all(|f| f.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server.clone()); + // A fixed range retains its UID bound even if the server sends newer deliveries. + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_flags("1:49") { + prop_assert!(got.len() <= 2 * 10 + FETCH_SLACK); + prop_assert!(got.iter().all(|f| f.uid >= 1 && f.uid < 50 && f.flags.len() <= MAX_FLAGS && f.flags.iter().all(|x| x.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server.clone()); + // Wildcards admit deliveries newer than SELECT's UIDNEXT, but retain all storage caps. + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_flags("1:*") { + prop_assert!(got.len() <= 2 * 10 + FETCH_SLACK); + prop_assert!(got.iter().all(|f| f.uid >= 1 && f.flags.len() <= MAX_FLAGS && f.flags.iter().all(|x| x.len() <= MAX_FLAG_LEN))); + } + let mut s = Script::new(server); + if let Ok(got) = opened(&mut s, 10, 50).uid_fetch_sizes("5:20") { + prop_assert!(got.iter().all(|(uid, _)| (5..=20).contains(uid))); + } + } +} + +#[test] +fn a_folder_with_more_messages_than_other_commands_may_answer_still_reads() { + let exists = 300_000u32; + let lines = |n: u32| flood(n as usize, |i| format!("* {i} FETCH (UID {} FLAGS ())\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(lines(exists)); + assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_flags("1:*").unwrap().len(), exists as usize); + let sizes = flood(exists as usize, |i| format!("* {i} FETCH (UID {} RFC822.SIZE 1)\r\n", i + 1)) + "A0001 OK done\r\n"; + let mut s = Script::new(sizes); + assert_eq!(opened(&mut s, exists, exists + 1).uid_fetch_sizes("1:*").unwrap().len(), exists as usize); + // Responses that are not messages still end at the cap for that folder, and the next command is back to the usual one. + let noise = "* OK still here\r\n".repeat(2 * exists as usize + FETCH_SLACK + 1) + "A0001 OK done\r\n"; + let mut s = Script::new(noise); + let mut imap = opened(&mut s, exists, exists + 1); + assert!(matches!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(_)))); + assert_eq!(imap.response_cap, MAX_RESPONSES); +} + +#[test] +fn short_flags_release_large_backing_allocations() { + let flags = short_flags(vec![Value::Atom("A".repeat(1024 * 1024))]); + assert_eq!(flags[0].len(), MAX_FLAG_LEN); + assert!(flags[0].capacity() <= MAX_FLAG_LEN); +} + +#[test] +fn wildcard_fetch_accepts_deliveries_after_select() { + let server = "* 1 FETCH (UID 10 FLAGS ())\r\nA0001 OK done\r\n"; + let mut s = Script::new(server); + assert_eq!(opened(&mut s, 1, 10).uid_fetch_flags("*").unwrap()[0].uid, 10); +} + +#[test] +fn brackets_in_flag_keywords_do_not_consume_body_sections() { + for flag in ["x[", "BODY["] { + let mut s = Script::new(format!("* 1 FETCH (UID 3 FLAGS ({flag}) BODY[] {{2}}\r\nok)\r\nA0001 OK done\r\n")); + assert_eq!(opened(&mut s, 1, 4).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); + } +} diff --git a/crates/proto/src/imap/mod.rs b/crates/proto/src/imap/mod.rs new file mode 100644 index 0000000000..d469bffcc0 --- /dev/null +++ b/crates/proto/src/imap/mod.rs @@ -0,0 +1,1405 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An IMAP4rev1 client (RFC 3501) with the commands a two-way synchronisation needs: reading +//! mailboxes, and changing flags, moving, copying, removing and filing messages (UID MOVE of +//! RFC 6851; UID EXPUNGE and the `COPYUID` answer of RFC 4315). Special-use mailbox flags +//! (RFC 6154) come through in [`Mailbox::flags`] as the server wrote them. Password sign-in prefers +//! advertised SASL PLAIN, with LOGIN as a fallback when PLAIN is not offered; OAuth uses XOAUTH2. +//! +//! There is no plain EXPUNGE and no CLOSE here, on purpose: both remove every message marked +//! `\Deleted` in the mailbox, also those another program marked. + +mod idle; +#[cfg(test)] +mod idle_tests; +mod parse; +mod password; +#[cfg(test)] +mod password_tests; +mod status; +#[cfg(test)] +mod status_tests; +mod utf7; + +pub use idle::IdleEvent; +pub use status::{FolderStatus, MAX_STATUS_BATCH}; + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::io::{Read, Write}; + +use parse::{Piece, Status, StatusLine, Value}; +pub use utf7::{decode_utf7, encode_utf7}; + +use crate::i18n::{Arg, Text}; +use crate::line::Wire; +use crate::said; +use crate::{MAX_LINE, MAX_LITERAL, ProtoError, Secrets, for_trace, tidy, xoauth2}; + +/// Most responses the server may send to one command. +const MAX_RESPONSES: usize = 250_000; +/// Most text (everything outside literals) the server may send in answer to one command. +const MAX_COMMAND_TEXT: usize = 32 << 20; +/// Most mailboxes one LIST keeps; the ones after are read and dropped. More than a run reads +/// (10,000, #991), since some of those listed are never read (views, folders that can't be +/// opened). What is kept is bounded in bytes too ([`MAX_LIST_BYTES`]). +const MAX_MAILBOXES: usize = 12_000; +/// Most bytes of names and flags one LIST keeps, literals included (which +/// [`MAX_COMMAND_TEXT`] doesn't count): 12,000 mailboxes as most servers list them take a +/// megabyte or two; past this the ones after are read and dropped. +const MAX_LIST_BYTES: usize = 16 << 20; +/// Longest mailbox name kept (as the server wrote it); a mailbox with a longer one is left out, +/// since a name cut short would name another mailbox or none. +const MAX_MAILBOX_NAME: usize = 1_024; +/// Longest flag kept, in bytes. +const MAX_FLAG_LEN: usize = 256; +/// Most distinct messages a FETCH may report, beyond twice the mailbox's `EXISTS`. +const FETCH_SLACK: usize = 1_000; +/// Most literals one response may carry. +const MAX_LITERALS: usize = 32; +/// Most text one response may carry outside its literals. +const MAX_TEXT: usize = 4 * MAX_LINE; +/// Most flags kept for one message or mailbox, and most sent in one command. +const MAX_FLAGS: usize = 64; +/// Most of Gmail's labels kept for one message (`X-GM-LABELS`, #1153); the rest are dropped. +pub const MAX_GMAIL_LABELS: usize = 64; +/// Longest of Gmail's labels kept, in bytes as the server wrote it (cut at a character boundary). +const MAX_GMAIL_LABEL_LEN: usize = 256; +/// Most bytes of Gmail's labels one fetch keeps, all its messages together, each label counted +/// with [`LABEL_OVERHEAD`]: past it, a message's labels are not taken (`None`), as if the server +/// hadn't said them. +const MAX_GMAIL_LABEL_BYTES: usize = 32 << 20; +/// What a label kept costs beyond its bytes (its `String`), counted against +/// [`MAX_GMAIL_LABEL_BYTES`] so that many empty or tiny labels can't get past it. +const LABEL_OVERHEAD: usize = std::mem::size_of::(); +/// Text a listing of flags may take for each message the mailbox may report, beyond +/// [`MAX_COMMAND_TEXT`]: a big folder's listing (Gmail's, with labels, runs to a few hundred +/// bytes a message) is never cut short for being big (#1153), and what a hostile server can send +/// stays bounded by the mailbox's size, and by [`MAX_FETCH_TEXT`] whatever size it claims. Only +/// a count: what is kept is bounded on its own ([`MAX_FLAG_BYTES`], [`MAX_GMAIL_LABEL_BYTES`]). +const FETCH_TEXT_PER_MESSAGE: usize = 2 << 10; +/// Most text a listing of flags may take, however many messages the mailbox claims. +const MAX_FETCH_TEXT: usize = 256 << 20; +/// Most bytes of flags one fetch keeps, all its messages together, each message counted with +/// [`ENTRY_OVERHEAD`] and each flag with [`FLAG_OVERHEAD`]: past it the listing fails, so that a +/// server claiming a huge mailbox can't fill memory and no message is taken to have lost its flags. +/// Room for over a million messages with a few flags each. +const MAX_FLAG_BYTES: usize = 256 << 20; +/// What a flag kept costs beyond its bytes (its `String`). +const FLAG_OVERHEAD: usize = std::mem::size_of::(); +/// What a message kept in a listing costs beyond its flags and labels: its entry in the map, with +/// room for the map's own nodes. +const ENTRY_OVERHEAD: usize = 2 * std::mem::size_of::<(u32, (Vec, Option, Option>))>(); +const MAX_CAPABILITIES: usize = 256; +/// Longest string sent in quotes; a longer one goes as a literal. +const MAX_QUOTED: usize = 1_000; +/// Most messages named in one set by [`uid_sets`], and most a `COPYUID` answer may speak of. +const MAX_SET_UIDS: usize = 500; +/// Longest set [`uid_sets`] writes, in characters. +const MAX_SET_TEXT: usize = 800; +/// The most UIDs a search answers with that are taken in. +const MAX_FOUND: usize = 1_000; +/// The most UIDs one of Gmail's searches ([`Imap::uid_search_gmail`]) answers with that are taken +/// in: as many as fit the longest line read, at the longest a UID is written. +pub const MAX_GMAIL_FOUND: usize = 5_000; + +/// An IMAP session on a stream. +pub struct Imap { + wire: Wire, + /// The number in the next command's tag. + next_tag: u32, + secrets: Secrets, + /// What the server said it can do, upper-cased; `None` until it has. + capabilities: Option>, + authenticated: bool, + /// What the mailbox being opened has said about itself so far. + selected: Selected, + /// Every `COPYUID` answer since the last copy or move was sent (`None` for one that couldn't + /// be read); two are as many as it takes to know there was more than one. + copied: Vec>, + /// Every `APPENDUID` answer since the last APPEND was sent, as [`Imap::copied`] is kept. + appended: Vec>, + /// LOGOUT was sent, so BYE is the answer we asked for. + leaving: bool, + /// Bytes of text (outside literals) read since the current command was sent. + text_seen: usize, + /// Most responses the current command may bring. + response_cap: usize, + /// Most text (outside literals) the current command may bring: [`MAX_COMMAND_TEXT`], or more + /// for a listing of a big mailbox's flags. + text_cap: usize, + /// Untagged lines too long to take are read past instead of ending the session, for the + /// current command alone (a Gmail search, #911); `skipped` says one was. + skip_long: bool, + skipped: bool, + /// The tag of the IDLE command the server is waiting in, if it is ([`Imap::idle_begin`]). + idle_tag: Option, + idle_pending: std::collections::VecDeque, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Mailbox { + /// Decoded from modified UTF-7. + pub name: String, + /// The name exactly as the server wrote it (use this in commands). + pub raw: String, + pub delimiter: Option, + /// Flags as written, e.g. `\\Noselect`, `\\Sent`, `\\HasChildren`. + pub flags: Vec, +} + +/// The personal IMAP namespace (RFC 2342): `prefix` (as the server spells it, e.g. `"INBOX."`) and +/// hierarchy `delimiter` (`'.'`, `'/'`), if any. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Namespace { + pub prefix: String, + pub delimiter: Option, +} + +impl Mailbox { + /// Whether the mailbox has `flag` (`\Noselect`), whatever the letter case. + pub fn has_flag(&self, flag: &str) -> bool { + self.flags.iter().any(|f| f.eq_ignore_ascii_case(flag)) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Selected { + pub exists: u32, + pub uid_validity: u32, + pub uid_next: u32, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Fetched { + pub uid: u32, + pub flags: Vec, + /// INTERNALDATE as written by the server, when asked for. + pub internal_date: Option, + /// The whole message (BODY[]), when asked for. + pub body: Option>, + /// Gmail's own id of the message (`X-GM-MSGID`, Google's "Gmail IMAP extensions"), when + /// asked for and given; `None` from every other server. + pub gmail_id: Option, + /// Gmail's labels of the message (`X-GM-LABELS`, Google's "Gmail IMAP extensions", #1153), + /// when asked for and given: as the server wrote them, modified UTF-7 decoded, Gmail's own + /// (`\Inbox`, `\Important`…) with their backslash; at most [`MAX_GMAIL_LABELS`], each cut + /// short. Text from the server, not yet cleaned for showing. `None` from every other server. + pub gmail_labels: Option>, +} + +/// What became of the messages a UID COPY or UID MOVE named, when the server says (the `COPYUID` +/// response code of RFC 4315). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Copied { + /// `UIDVALIDITY` of the mailbox the messages went to. + pub uid_validity: u32, + /// Each message's UID where it was, and its UID where it is now. + pub uids: Vec<(u32, u32)>, +} + +/// Where a message given with APPEND went, when the server says (the `APPENDUID` response code +/// of RFC 4315). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Appended { + /// `UIDVALIDITY` of the mailbox it went to. + pub uid_validity: u32, + /// Its UID there. + pub uid: u32, +} + +/// Neither the stream nor anything secret is shown. +impl std::fmt::Debug for Imap { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Imap").field("next_tag", &self.next_tag).field("authenticated", &self.authenticated).finish_non_exhaustive() + } +} + +/// One response from the server. +enum Response { + /// `+ …`: the server is ready for the rest of the command. + GoAhead, + Status { + tag: Option, + line: StatusLine, + }, + /// Untagged data: `* 3 EXISTS`, `* LIST …`, `* 3 FETCH (…)`. + Data(Vec), +} + +enum Part<'a> { + Text(Vec), + Literal(&'a [u8]), +} + +/// A command being put together (without its tag). +struct Command<'a> { + parts: Vec>, + /// What the log shows in place of the command. + shown: Option<&'static str>, + /// An argument has a NUL, which no IMAP string can carry. + unsendable: bool, +} + +impl<'a> Command<'a> { + fn new(verb: &str) -> Self { + Command { parts: vec![Part::Text(verb.as_bytes().to_vec())], shown: None, unsendable: false } + } + + fn text(&mut self, bytes: &[u8]) { + match self.parts.last_mut() { + Some(Part::Text(text)) => text.extend_from_slice(bytes), + _ => self.parts.push(Part::Text(bytes.to_vec())), + } + } + + /// A bare argument: our own words, or text that was checked. + fn arg(mut self, word: &str) -> Self { + self.text(b" "); + self.text(word.as_bytes()); + self + } + + /// An argument as a quoted string, or as a literal when quotes can't carry it. + fn string(mut self, bytes: &'a [u8]) -> Self { + self.text(b" "); + if bytes.len() <= MAX_QUOTED && bytes.iter().all(|b| matches!(b, b' '..=b'~')) { + let mut quoted = Vec::with_capacity(bytes.len() + 2); + quoted.push(b'"'); + for b in bytes { + if matches!(b, b'"' | b'\\') { + quoted.push(b'\\'); + } + quoted.push(*b); + } + quoted.push(b'"'); + self.text("ed); + } else { + self.unsendable |= bytes.contains(&0); + self.parts.push(Part::Literal(bytes)); + } + self + } + + /// An argument that always goes as a literal (a message). + fn literal(mut self, bytes: &'a [u8]) -> Self { + self.text(b" "); + self.parts.push(Part::Literal(bytes)); + self + } + + fn shown_as(mut self, shown: &'static str) -> Self { + self.shown = Some(shown); + self + } + + /// The command for the log: literals by size only. + fn for_log(&self) -> String { + if let Some(shown) = self.shown { + return shown.to_string(); + } + self.parts + .iter() + .map(|part| match part { + Part::Text(text) => String::from_utf8_lossy(text).into_owned(), + Part::Literal(bytes) => format!("({} bytes)", bytes.len()), + }) + .collect() + } +} + +/// What one FETCH response says about a message. +#[derive(Default)] +struct Item { + uid: u32, + flags: Option>, + internal_date: Option, + body: Option>, + /// The header alone (`BODY[HEADER]`). + header: Option>, + size: Option, + /// Gmail's id of the message (`X-GM-MSGID`). + gmail_id: Option, + /// Gmail's labels of the message (`X-GM-LABELS`). + gmail_labels: Option>, +} + +impl Item { + /// From `n FETCH (name value name value …)`, the names in any order. + fn from(values: Vec) -> Option { + let mut values = values.into_iter(); + values.next()?.number()?; + if !values.next()?.atom()?.eq_ignore_ascii_case("FETCH") { + return None; + } + let Value::List(pairs) = values.next()? else { return None }; + let mut item = Item::default(); + let mut pairs = pairs.into_iter(); + while let Some(name) = pairs.next() { + // Something that isn't a name is skipped, in the hope that a name follows. + let Some(name) = name.atom().map(str::to_ascii_uppercase) else { continue }; + let Some(value) = pairs.next() else { break }; + match (name.as_str(), value) { + ("UID", value) => item.uid = value.number().unwrap_or(0), + ("FLAGS", Value::List(flags)) => item.flags = Some(short_flags(flags)), + ("INTERNALDATE", Value::Str(date)) => item.internal_date = Some(String::from_utf8_lossy(&date).into_owned()), + ("RFC822.SIZE", value) => item.size = value.atom().and_then(|n| n.parse().ok()), + ("X-GM-MSGID", value) => item.gmail_id = value.atom().and_then(gmail_id), + ("X-GM-LABELS", Value::List(labels)) => item.gmail_labels = Some(gmail_labels(labels)), + ("BODY[]" | "RFC822", Value::Str(body)) => item.body = Some(body), + ("BODY[HEADER]" | "RFC822.HEADER", Value::Str(header)) => item.header = Some(header), + _ => {} + } + } + Some(item) + } +} + +/// From `LIST (flags) "delimiter" name`. +fn mailbox_from(values: Vec) -> Option { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("LIST") { + return None; + } + let Value::List(flags) = values.next()? else { return None }; + let delimiter = match values.next()? { + Value::Str(d) => String::from_utf8_lossy(&d).chars().next(), + _ => None, + }; + let raw = values.next()?.into_text()?; + if raw.len() > MAX_MAILBOX_NAME { + return None; + } + Some(Mailbox { name: decode_utf7(&raw), raw, delimiter, flags: short_flags(flags) }) +} + +/// From `NAMESPACE ((prefix delimiter) ...) other shared` (RFC 2342): the first personal namespace. +fn namespace_from(values: Vec) -> Option { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("NAMESPACE") { + return None; + } + let Value::List(personal) = values.next()? else { return None }; + let Value::List(desc) = personal.into_iter().next()? else { return None }; + let mut desc = desc.into_iter(); + let prefix = desc.next()?.into_text()?; + if prefix.len() > MAX_MAILBOX_NAME { + return None; + } + let delimiter = match desc.next()? { + Value::Str(d) => String::from_utf8_lossy(&d).chars().next(), + _ => None, + }; + Some(Namespace { prefix, delimiter }) +} + +/// The flags of a list, as many as are kept and each cut at a character boundary. +fn short_flags(flags: Vec) -> Vec { + flags + .into_iter() + .filter_map(Value::into_text) + .take(MAX_FLAGS) + .map(|mut flag| { + if flag.len() > MAX_FLAG_LEN { + let mut end = MAX_FLAG_LEN; + while !flag.is_char_boundary(end) { + end = end.saturating_sub(1); + } + flag = flag.get(..end).unwrap_or_default().to_owned(); + } + flag + }) + .collect() +} + +/// Gmail's labels of a message (`X-GM-LABELS`): a list of atoms and strings, modified UTF-7 as +/// mailbox names are; as many as are kept, each cut at a character boundary before it is decoded. +/// Anything in the list that isn't an atom or a string (a list) is skipped. +fn gmail_labels(labels: Vec) -> Vec { + labels + .into_iter() + // `NIL` in the list is nothing, not a label (a label called so comes quoted). + .filter(|value| !value.atom().is_some_and(|atom| atom.eq_ignore_ascii_case("NIL"))) + .filter_map(Value::into_text) + .take(MAX_GMAIL_LABELS) + .map(|mut label| { + if label.len() > MAX_GMAIL_LABEL_LEN { + let mut end = MAX_GMAIL_LABEL_LEN; + while !label.is_char_boundary(end) { + end = end.saturating_sub(1); + } + label.truncate(end); + } + decode_utf7(&label) + }) + .collect() +} + +/// A message set as ranges of UIDs (`*` as `top`); `None` when it can't be read. +fn set_ranges(set: &str, top: u32) -> Option> { + let bound = |text: &str| if text == "*" { Some(top) } else { number(text) }; + set.split(',') + .map(|part| { + // A wildcard-only fetch is resolved by the server, not a stale client snapshot. + if part == "*" || part == "*:*" { + return Some((1, top)); + } + let (a, b) = match part.split_once(':') { + Some((a, b)) => (bound(a)?, bound(b)?), + None => (bound(part)?, bound(part)?), + }; + Some((a.min(b), a.max(b))) + }) + .collect() +} + +/// What a FETCH of a set may report: only UIDs in the set, and not more distinct +/// ones than a mailbox of this size can hold. +struct Wanted { + ranges: Vec<(u32, u32)>, + cap: usize, + over: bool, +} + +impl Wanted { + fn new(set: &str, selected: &Selected) -> Option { + // UIDNEXT is a SELECT-time snapshot; new deliveries can have larger UIDs. + let ranges = set_ranges(set, u32::MAX)?; + let cap = usize::try_from(selected.exists).unwrap_or(usize::MAX).saturating_mul(2).saturating_add(FETCH_SLACK); + Some(Wanted { ranges, cap, over: false }) + } + + /// Most responses a fetch of this mailbox may bring: one for each message it may report, but + /// never fewer than any other command. + fn responses(&self) -> usize { + self.cap.max(MAX_RESPONSES) + } + + fn wants(&self, uid: u32) -> bool { + uid != 0 && self.ranges.iter().any(|(from, to)| (*from..=*to).contains(&uid)) + } + + /// Whether one more distinct UID fits after `count`; if not, the command fails. + fn room(&mut self, count: usize) -> bool { + if count >= self.cap { + self.over = true; + } + !self.over + } + + fn check(&self) -> Result<(), ProtoError> { + if self.over { Err(ProtoError::Protocol(said!("the server reported more messages than the mailbox holds"))) } else { Ok(()) } + } +} + +/// A message set: `1:*`, `5,9,12:20`. +fn is_set(set: &str) -> bool { + !set.is_empty() && set.len() <= MAX_QUOTED && set.bytes().all(|b| b.is_ascii_digit() || matches!(b, b':' | b',' | b'*')) +} + +/// A flag or keyword: `\Seen`, `$Forwarded`. +fn is_flag(flag: &str) -> bool { + let word = flag.strip_prefix('\\').unwrap_or(flag); + !word.is_empty() + && word.len() <= 100 + && word.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b'(' | b')' | b'{' | b'%' | b'*' | b'"' | b'\\' | b']')) +} + +/// `(\Seen \Flagged)`, once every flag is known to be one. +fn flag_list(flags: &[&str]) -> Result { + if flags.len() > MAX_FLAGS { + return Err(ProtoError::Protocol(said!("too many flags for one command"))); + } + match flags.iter().find(|f| !is_flag(f)) { + Some(bad) => Err(ProtoError::Protocol(said!("\"{flag}\" can't be used as a flag", flag = tidy(bad)))), + None => Ok(format!("({})", flags.join(" "))), + } +} + +/// Gmail's id of a message (`X-GM-MSGID`): a 64-bit number, written in digits alone; 0 is none. +fn gmail_id(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok().filter(|id| *id != 0) +} + +/// A number as IMAP writes one: digits and nothing else. +fn number(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok() +} + +/// The UIDs a set names, in the order written (`4,7:9` is 4, 7, 8, 9). `None` for a set that +/// doesn't name its messages one by one beyond doubt: `*`, zero, a range written backwards, or +/// more than [`MAX_SET_UIDS`] numbers. +fn uids_of(set: &str) -> Option> { + let mut out: Vec = Vec::new(); + for part in set.split(',') { + let (first, last) = match part.split_once(':') { + Some((first, last)) => (number(first)?, number(last)?), + None => { + let one = number(part)?; + (one, one) + } + }; + if first == 0 || first > last || (last - first) as usize >= MAX_SET_UIDS.saturating_sub(out.len()) { + return None; + } + out.extend(first..=last); + } + Some(out) +} + +/// A set for a command that changes things: it names its messages number by number. `1:*` +/// would take in messages nobody looked at. +fn named(set: &str) -> Result<&str, ProtoError> { + if set.len() <= MAX_QUOTED && uids_of(set).is_some() { + Ok(set) + } else { + Err(ProtoError::Protocol(said!("\"{set}\" doesn't name the messages to change", set = tidy(set)))) + } +} + +/// From the text of a `COPYUID` code: ` `. +/// `None` unless it pairs every message beyond doubt (the first set strictly ascending, the +/// second as long and without repeats): a wrong pairing would tie a message here to another one +/// on the server. +fn copied_from(arg: &str) -> Option { + let mut words = arg.split_whitespace(); + let uid_validity = number(words.next()?).filter(|validity| *validity != 0)?; + let (from, to) = (uids_of(words.next()?)?, uids_of(words.next()?)?); + let mut distinct = to.clone(); + distinct.sort_unstable(); + distinct.dedup(); + if words.next().is_some() || from.len() != to.len() || distinct.len() != to.len() || !from.is_sorted_by(|a, b| a < b) { + return None; + } + Some(Copied { uid_validity, uids: from.into_iter().zip(to).collect() }) +} + +/// From the text of an `APPENDUID` code: ` `, for one message. `None` for +/// anything else (a set of UIDs speaks of more than the one message given). +fn appended_from(arg: &str) -> Option { + let mut words = arg.split_whitespace(); + let uid_validity = number(words.next()?).filter(|validity| *validity != 0)?; + let uid = number(words.next()?).filter(|uid| *uid != 0)?; + words.next().is_none().then_some(Appended { uid_validity, uid }) +} + +/// Whether `text` is an IMAP `date-time` without its quotes (RFC 3501): `01-Jul-2003 09:52:37 +/// +0000`, the day padded with a space or a nought. +fn is_date_time(text: &str) -> bool { + let b = text.as_bytes(); + let digits = |range: std::ops::Range| b.get(range).is_some_and(|d| d.iter().all(u8::is_ascii_digit)); + let at = |i: usize, c: u8| b.get(i) == Some(&c); + b.len() == 26 + && (digits(0..2) || (at(0, b' ') && digits(1..2))) + && at(2, b'-') + && b.get(3..6).is_some_and(|m| m.iter().all(u8::is_ascii_alphabetic)) + && at(6, b'-') + && digits(7..11) + && at(11, b' ') + && digits(12..14) + && at(14, b':') + && digits(15..17) + && at(17, b':') + && digits(18..20) + && at(20, b' ') + && (at(21, b'+') || at(21, b'-')) + && digits(22..26) +} + +/// Whether [`Imap::uid_search_header`] can look for `text`: printable ASCII, at most +/// [`MAX_QUOTED`] bytes. What it can't be asked for, it refuses unsent. +pub fn searchable(text: &str) -> bool { + !text.is_empty() && text.len() <= MAX_QUOTED && text.bytes().all(|b| matches!(b, b' '..=b'~')) +} + +/// UIDs as message sets for commands (`4,7:9,12`), each with the UIDs it names: sorted, each UID +/// once, consecutive numbers as ranges, and no set longer than one command should carry. A +/// range only ever spans numbers that were asked for. +pub fn uid_sets(uids: &[u32]) -> Vec<(String, Vec)> { + let mut sorted: Vec = uids.iter().copied().filter(|uid| *uid != 0).collect(); + sorted.sort_unstable(); + sorted.dedup(); + let mut sets = Vec::new(); + let (mut text, mut uids_named) = (String::new(), Vec::new()); + let mut at = 0; + // Every round takes at least one UID off the list. + while let Some(&first) = sorted.get(at) { + let (mut last, mut next) = (first, at + 1); + while uids_named.len() + (next - at) < MAX_SET_UIDS && sorted.get(next).is_some_and(|uid| last.checked_add(1) == Some(*uid)) { + last = last.saturating_add(1); + next += 1; + } + let range = if last == first { first.to_string() } else { format!("{first}:{last}") }; + if !text.is_empty() && text.len() + 1 + range.len() > MAX_SET_TEXT { + sets.push((std::mem::take(&mut text), std::mem::take(&mut uids_named))); + } + if !text.is_empty() { + text.push(','); + } + text.push_str(&range); + uids_named.extend_from_slice(sorted.get(at..next).unwrap_or(&[])); + at = next; + if uids_named.len() >= MAX_SET_UIDS { + sets.push((std::mem::take(&mut text), std::mem::take(&mut uids_named))); + } + } + if !text.is_empty() { + sets.push((text, uids_named)); + } + sets +} + +fn ignore(_: Vec) {} + +impl Imap { + /// Read the greeting (`* OK` or `* PREAUTH`; `* BYE` is an error). + pub fn connect(stream: S) -> Result { + let mut imap = Self::resume(stream); + match imap.read_response()? { + Response::Status { tag: None, line } => match line.status { + Status::Ok | Status::Preauth => { + imap.authenticated = line.status == Status::Preauth; + imap.note_status(&line); + Ok(imap) + } + Status::Bye => Err(ProtoError::Rejected(imap.refusal(&line))), + Status::No | Status::Bad => { + Err(ProtoError::Protocol(said!("the server greeted with a refusal: {reason}", reason = Arg::said(imap.refusal(&line))))) + } + }, + _ => Err(ProtoError::Protocol(said!("the server didn't greet like an IMAP server"))), + } + } + + /// Continue on a stream that already greeted (after the caller wrapped it in TLS). + pub fn resume(stream: S) -> Self { + Imap { + wire: Wire::new(stream), + next_tag: 1, + secrets: Secrets::default(), + capabilities: None, + authenticated: false, + selected: Selected::default(), + copied: Vec::new(), + appended: Vec::new(), + leaving: false, + text_seen: 0, + response_cap: MAX_RESPONSES, + text_cap: MAX_COMMAND_TEXT, + skip_long: false, + skipped: false, + idle_tag: None, + idle_pending: std::collections::VecDeque::new(), + } + } + + /// Whether the session is signed in: after [`login`](Self::login) or + /// [`authenticate_xoauth2`](Self::authenticate_xoauth2), or from the start when the server greeted with PREAUTH. + pub fn is_authenticated(&self) -> bool { + self.authenticated + } + + /// The stream the session runs on, for its owner to set up between commands (how long a + /// socket waits, say). Reading from it or writing to it would take the session apart. + pub fn get_mut(&mut self) -> &mut S { + self.wire.get_mut() + } + + /// Whether the server has said it can do `capability` (upper-cased); `false` while it hasn't said anything. + fn offers(&self, capability: &str) -> bool { + self.capabilities.as_ref().is_some_and(|caps| caps.iter().any(|c| c == capability)) + } + + /// Upper-cased capability atoms (`IMAP4REV1`, `STARTTLS`, `SPECIAL-USE`…). + pub fn capabilities(&mut self) -> Result, ProtoError> { + self.capabilities = None; + self.run(Command::new("CAPABILITY"), &mut ignore)?; + Ok(self.capabilities.clone().unwrap_or_default()) + } + + /// Send STARTTLS and hand the stream back for the caller to wrap; call `resume` afterwards. + pub fn starttls(mut self) -> Result { + self.run(Command::new("STARTTLS"), &mut ignore)?; + // Anything after the go-ahead was slipped in before encryption started. + if self.wire.has_pending() { + return Err(ProtoError::Protocol(said!("the server sent data before the secure connection started"))); + } + Ok(self.wire.into_inner()) + } + + /// LOGIN with properly quoted (or literal) strings. NO → `ProtoError::Auth`. + pub fn login(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("the user name or password has a character that can't be sent"))); + } + // RFC 3501 §6.2.3: a server that says LOGINDISABLED must not be sent a password. + if self.offers("LOGINDISABLED") { + return Err(ProtoError::Auth(said!("the server doesn't take a password on this connection"))); + } + self.secrets.add(password); + let command = Command::new("LOGIN").string(user.as_bytes()).string(password.as_bytes()).shown_as("LOGIN ***"); + let line = self.exchange(command, &mut ignore)?; + match line.status { + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&line))), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// AUTHENTICATE XOAUTH2: an OAuth access token in place of a password. NO → `ProtoError::Auth`. + /// + /// The token goes out with the command (RFC 4959) only to a server that listed both + /// `SASL-IR` and `AUTH=XOAUTH2`. Any other server, one that listed neither or hasn't said + /// what it can do, is tried all the same, but asked first: it gets the token after its + /// go-ahead, so one that doesn't know the mechanism refuses without having seen it. + pub fn authenticate_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { + let payload = xoauth2(user, token)?; + self.secrets.add(token); + self.secrets.add(&payload); + let inline = self.offers("SASL-IR") && self.offers("AUTH=XOAUTH2"); + let tag = self.tag(); + log::trace!("C: {tag} AUTHENTICATE XOAUTH2{}", if inline { " ***" } else { "" }); + let mut out = format!("{tag} AUTHENTICATE XOAUTH2"); + if inline { + out.push(' '); + out.push_str(&payload); + } + out.push_str("\r\n"); + self.wire.write(out.as_bytes())?; + self.wire.flush()?; + // What each `+` from the server is answered with: the token (unless it went with the + // command), an empty line for the reasons a refusal starts with (JSON in base64), and + // for a question after that, the end of the exchange. + let answers = [(payload.as_str(), "***"), ("", ""), ("*", "*")]; + let mut asked = usize::from(inline); + let line = loop { + if let Some(line) = self.read_until(&tag, true, &mut ignore)? { + break line; + } + let Some((answer, shown)) = answers.get(asked) else { + return Err(ProtoError::Protocol(said!("the server asked for more than a sign-in has"))); + }; + asked += 1; + log::trace!("C: {shown}"); + self.wire.write(format!("{answer}\r\n").as_bytes())?; + self.wire.flush()?; + }; + match line.status { + // The exchange was called off, whatever the server makes of that. + _ if asked == answers.len() => Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))), + // Nobody is signed in by a token that was never sent. + Status::Ok if asked == 0 => Err(ProtoError::Protocol(said!("the server ended the command early"))), + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&line))), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// LIST "" "*". + pub fn list(&mut self) -> Result, ProtoError> { + self.list_counted().map(|(list, _)| list) + } + + /// [`list`](Self::list), and how many more mailboxes the server listed that were read and + /// dropped because the list was full ([`MAX_MAILBOXES`], [`MAX_LIST_BYTES`]): 0 when it + /// was kept whole. + pub fn list_counted(&mut self) -> Result<(Vec, usize), ProtoError> { + let mut out: Vec = Vec::new(); + let mut seen = HashSet::new(); + let (mut kept, mut dropped) = (0usize, 0usize); + self.run(Command::new("LIST").arg("\"\"").arg("\"*\""), &mut |values| { + let full = out.len() >= MAX_MAILBOXES || kept >= MAX_LIST_BYTES; + // A mailbox the server names twice is listed once; past either cap, nothing is kept. + let Some(mailbox) = mailbox_from(values) else { return }; + if full { + dropped = dropped.saturating_add(1); + } else if seen.insert(mailbox.raw.clone()) { + // The name twice (as written, decoded) and once more in `seen`, and the flags. + let size = mailbox.raw.len().saturating_mul(2).saturating_add(mailbox.name.len()); + kept = mailbox.flags.iter().fold(kept.saturating_add(size), |kept, flag| kept.saturating_add(flag.len())); + out.push(mailbox); + } + })?; + Ok((out, dropped)) + } + + /// NAMESPACE (RFC 2342): the server's first personal namespace, or `None` when the server + /// offers no `NAMESPACE` capability or names no personal namespace. + pub fn namespace(&mut self) -> Result, ProtoError> { + if !self.offers("NAMESPACE") { + return Ok(None); + } + let mut found = None; + self.run(Command::new("NAMESPACE"), &mut |values| { + if found.is_none() { + found = namespace_from(values); + } + })?; + Ok(found) + } + + /// EXAMINE (read-only) or SELECT. + pub fn select(&mut self, raw_name: &str, read_only: bool) -> Result { + self.selected = Selected::default(); + let command = Command::new(if read_only { "EXAMINE" } else { "SELECT" }).string(raw_name.as_bytes()); + self.run(command, &mut ignore)?; + Ok(self.selected.clone()) + } + + /// UID FETCH (UID FLAGS): every message in the set with its flags. `set` like "1:*" or "5,9,12:20". + /// + /// The messages come back in UID order, each once. + pub fn uid_fetch_flags(&mut self, set: &str) -> Result, ProtoError> { + self.fetch_flags(set, false, false) + } + + /// [`uid_fetch_flags`](Self::uid_fetch_flags), with Gmail's id and labels of each message as + /// well (`UID FETCH (UID FLAGS X-GM-MSGID X-GM-LABELS)`, in [`Fetched::gmail_id`] and + /// [`Fetched::gmail_labels`]): for Gmail's server alone, which documents them among its IMAP + /// extensions. A message it gives no id, or one that isn't a number, has none; one it gives + /// no labels has `None` there, and one past [`MAX_GMAIL_LABEL_BYTES`] of labels in the fetch + /// too. + pub fn uid_fetch_flags_gmail(&mut self, set: &str) -> Result, ProtoError> { + self.fetch_flags(set, true, true) + } + + /// [`uid_fetch_flags`](Self::uid_fetch_flags), with Gmail's labels of each message as well but + /// not its id (`UID FETCH (UID FLAGS X-GM-LABELS)`, in [`Fetched::gmail_labels`]): for a + /// Gmail folder whose ids aren't wanted (every folder but the Inbox), so that its listing is + /// no longer than it has to be. + pub fn uid_fetch_flags_labels(&mut self, set: &str) -> Result, ProtoError> { + self.fetch_flags(set, false, true) + } + + fn fetch_flags(&mut self, set: &str, ids: bool, labels_wanted: bool) -> Result, ProtoError> { + type FetchedFlags = (Vec, Option, Option>); + let mut found: BTreeMap = BTreeMap::new(); + // The bytes of labels and of flags kept so far, all messages together. + let mut label_bytes = 0usize; + let mut flag_bytes = 0usize; + let items = match (ids, labels_wanted) { + (true, true) => "(UID FLAGS X-GM-MSGID X-GM-LABELS)", + (true, false) => "(UID FLAGS X-GM-MSGID)", + (false, true) => "(UID FLAGS X-GM-LABELS)", + (false, false) => "(UID FLAGS)", + }; + let command = Self::fetch(set, items)?; + let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + self.response_cap = wanted.responses(); + let claimed = usize::try_from(self.selected.exists).unwrap_or(usize::MAX); + self.text_cap = claimed.saturating_mul(FETCH_TEXT_PER_MESSAGE).clamp(MAX_COMMAND_TEXT, MAX_FETCH_TEXT); + let answered = self.run(command, &mut |values| { + // A response with a UID shows the message is there, even one that forgot the flags. + if flag_bytes <= MAX_FLAG_BYTES + && let Some(item) = Item::from(values) + && wanted.wants(item.uid) + && (found.contains_key(&item.uid) || wanted.room(found.len())) + { + // Each word counted as it comes, a repeat included: past the budget nothing more + // is kept and the listing fails below. + let size = item.flags.iter().flatten().map(|flag| flag.len().saturating_add(FLAG_OVERHEAD)).sum::(); + let entry = if found.contains_key(&item.uid) { 0 } else { ENTRY_OVERHEAD }; + flag_bytes = flag_bytes.saturating_add(size).saturating_add(entry); + if flag_bytes > MAX_FLAG_BYTES { + return; + } + let (flags, id, labels) = found.entry(item.uid).or_default(); + // When the server speaks of a message twice, its later word counts. + if let Some(later) = item.flags { + *flags = later; + } + if ids && item.gmail_id.is_some() { + *id = item.gmail_id; + } + if labels_wanted && let Some(later) = item.gmail_labels { + let size = later.iter().map(|label| label.len().saturating_add(LABEL_OVERHEAD)).sum::(); + if label_bytes.saturating_add(size) <= MAX_GMAIL_LABEL_BYTES { + label_bytes = label_bytes.saturating_add(size); + *labels = Some(later); + } + } + } + }); + self.response_cap = MAX_RESPONSES; + self.text_cap = MAX_COMMAND_TEXT; + answered?; + if flag_bytes > MAX_FLAG_BYTES { + return Err(ProtoError::Protocol(said!("more flags than one listing keeps"))); + } + wanted.check()?; + Ok(found + .into_iter() + .map(|(uid, (flags, gmail_id, gmail_labels))| Fetched { uid, flags, internal_date: None, body: None, gmail_id, gmail_labels }) + .collect()) + } + + /// UID FETCH (UID RFC822.SIZE): the size in bytes of every message in the set, in UID order. + pub fn uid_fetch_sizes(&mut self, set: &str) -> Result, ProtoError> { + let mut out: Vec<(u32, u64)> = Vec::new(); + let command = Self::fetch(set, "(UID RFC822.SIZE)")?; + let mut wanted = Wanted::new(set, &self.selected).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + self.response_cap = wanted.responses(); + let answered = self.run(command, &mut |values| { + if let Some(Item { uid, size: Some(size), .. }) = Item::from(values) + && wanted.wants(uid) + && wanted.room(out.len()) + { + out.push((uid, size)); + } + }); + self.response_cap = MAX_RESPONSES; + answered?; + wanted.check()?; + out.sort_by_key(|(uid, _)| *uid); + out.dedup_by_key(|(uid, _)| *uid); + Ok(out) + } + + /// UID FETCH (UID FLAGS INTERNALDATE BODY.PEEK[]); `None` when the UID is gone. + pub fn uid_fetch_message(&mut self, uid: u32) -> Result, ProtoError> { + self.fetch_one(uid, "(UID FLAGS INTERNALDATE BODY.PEEK[])", false) + } + + /// UID FETCH (UID FLAGS INTERNALDATE BODY.PEEK[HEADER]): the header alone of a message + /// that is not taken whole (one that is too large), in [`Fetched::body`], up to and with the + /// empty line that ends it. `None` when the UID is gone. + pub fn uid_fetch_header(&mut self, uid: u32) -> Result, ProtoError> { + self.fetch_one(uid, "(UID FLAGS INTERNALDATE BODY.PEEK[HEADER])", true) + } + + /// One message with its flags and date, and either all of it or (`header_only`) its header. + fn fetch_one(&mut self, uid: u32, items: &str, header_only: bool) -> Result, ProtoError> { + if uid == 0 { + return Ok(None); + } + let mut found: Option = None; + self.run(Self::fetch(&uid.to_string(), items)?, &mut |values| { + // Other messages may be mentioned in passing; this one may come in more than one response. + if let Some(item) = Item::from(values) + && item.uid == uid + { + let message = found.get_or_insert_with(|| Fetched { uid, ..Default::default() }); + if let Some(flags) = item.flags { + message.flags = flags; + } + message.internal_date = item.internal_date.or(message.internal_date.take()); + // Only what was asked for: a whole message in answer to a question about its + // header is not taken in. + let asked_for = if header_only { item.header } else { item.body }; + message.body = asked_for.or(message.body.take()); + } + })?; + Ok(found.filter(|message| message.body.is_some())) + } + + /// UID STORE +FLAGS.SILENT / -FLAGS.SILENT (flags). + pub fn uid_store(&mut self, uid: u32, add: bool, flags: &[&str]) -> Result<(), ProtoError> { + let flags = flag_list(flags)?; + if uid == 0 { + return Err(ProtoError::Protocol(said!("a message that isn't on the server has no flags there"))); + } + self.store(&uid.to_string(), add, &flags) + } + + /// UID STORE +FLAGS.SILENT / -FLAGS.SILENT (flags): the same change for every message + /// the set names (number by number, as [`uid_sets`] writes it; `1:*` is refused). A UID that + /// is no longer there is passed over by the server without a word. + pub fn uid_store_set(&mut self, set: &str, add: bool, flags: &[&str]) -> Result<(), ProtoError> { + let flags = flag_list(flags)?; + self.store(named(set)?, add, &flags) + } + + /// UID SEARCH UNDELETED HEADER : the messages of the open mailbox, other than + /// those marked as deleted, whose header field `field` has `text` in it (the server matches a + /// part of the field, whatever its case), by UID in UID order, at most [`MAX_FOUND`] of them. + /// `field` is a field's name, and `text` one that [`searchable`] lets through: anything else + /// is refused unsent. + pub fn uid_search_header(&mut self, field: &str, text: &str) -> Result, ProtoError> { + if field.is_empty() || !field.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') { + return Err(ProtoError::Protocol(said!("\"{field}\" is not the name of a header field", field = tidy(field)))); + } + if !searchable(text) { + return Err(ProtoError::Protocol(said!("the text can't be looked for on the server"))); + } + let mut found = BTreeSet::new(); + let command = Command::new("UID SEARCH UNDELETED HEADER").arg(field).string(text.as_bytes()); + self.run(command, &mut |values| { + if values.first().and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("SEARCH")) { + let uids = values.iter().skip(1).filter_map(Value::atom).filter_map(|n| n.parse::().ok()).filter(|uid| *uid != 0); + for uid in uids { + if found.len() >= MAX_FOUND { + break; + } + found.insert(uid); + } + } + })?; + Ok(found.into_iter().collect()) + } + + /// UID SEARCH UID UNDELETED X-GM-RAW "": the messages of the open mailbox, among + /// those `set` names and not marked as deleted, that Gmail's own search finds for `query` + /// (`category:social`), by UID in UID order. `X-GM-RAW` is Gmail's (Google's "Gmail IMAP extensions"): for Gmail's server alone. + /// + /// The query goes in quotes, without the CR, LF and NUL that could end the command early; one + /// that is empty then, or isn't printable ASCII within [`MAX_QUOTED`] bytes, is refused unsent. + /// Of the answer, only UIDs inside `set` are taken, at most [`MAX_GMAIL_FOUND`] of them: a + /// caller that wants them all asks for sets of fewer messages than that. An answer longer than + /// [`MAX_LINE`](crate::MAX_LINE) is read past and refused ([`ProtoError::Rejected`]): the + /// session goes on. + pub fn uid_search_gmail(&mut self, set: &str, query: &str) -> Result, ProtoError> { + if !is_set(set) { + return Err(ProtoError::Protocol(said!("\"{set}\" is not a set of messages", set = tidy(set)))); + } + let ranges = set_ranges(set, u32::MAX).ok_or_else(|| ProtoError::Protocol(said!("not a set of messages")))?; + let query: String = query.chars().filter(|c| !matches!(c, '\r' | '\n' | '\0')).collect(); + if !searchable(&query) { + return Err(ProtoError::Protocol(said!("the text can't be looked for on the server"))); + } + let mut found = BTreeSet::new(); + // Messages marked as deleted aren't shown, so they aren't asked about either. + let command = Command::new("UID SEARCH UID").arg(set).arg("UNDELETED X-GM-RAW").string(query.as_bytes()); + (self.skip_long, self.skipped) = (true, false); + let answer = self.run(command, &mut |values| { + if values.first().and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("SEARCH")) { + let uids = values.iter().skip(1).filter_map(Value::number).filter(|uid| *uid != 0); + for uid in uids.filter(|uid| ranges.iter().any(|(from, to)| (*from..=*to).contains(uid))) { + if found.len() >= MAX_GMAIL_FOUND { + break; + } + found.insert(uid); + } + } + }); + let skipped = std::mem::take(&mut self.skipped); + self.skip_long = false; + answer?; + // An answer too long to read is no answer: the session goes on without it. + if skipped { + return Err(ProtoError::Rejected(said!("the server's answer was longer than {kb} KB", kb = crate::MAX_LINE / 1024))); + } + Ok(found.into_iter().collect()) + } + + fn store(&mut self, set: &str, add: bool, flags: &str) -> Result<(), ProtoError> { + // No flags: nothing to ask of the server. + if flags == "()" { + return Ok(()); + } + let command = Command::new("UID STORE").arg(set).arg(if add { "+FLAGS.SILENT" } else { "-FLAGS.SILENT" }).arg(flags); + self.run(command, &mut ignore).map(|_| ()) + } + + /// UID MOVE (RFC 6851, for a server that offers `MOVE`): the messages leave + /// the open mailbox for the named one in one step. Answers where they are now when the + /// server says so beyond doubt (`COPYUID`), `None` otherwise. + pub fn uid_move(&mut self, set: &str, raw_name: &str) -> Result, ProtoError> { + self.transfer("UID MOVE", set, raw_name) + } + + /// UID COPY : copies of the messages are added to the named mailbox. Answers + /// like [`uid_move`](Self::uid_move). + pub fn uid_copy(&mut self, set: &str, raw_name: &str) -> Result, ProtoError> { + self.transfer("UID COPY", set, raw_name) + } + + fn transfer(&mut self, verb: &str, set: &str, raw_name: &str) -> Result, ProtoError> { + let command = Command::new(verb).arg(named(set)?).string(raw_name.as_bytes()); + self.copied.clear(); + let done = self.run(command, &mut ignore); + // One answer that could be read, or nothing is known: two that might disagree are none. + let copied = match std::mem::take(&mut self.copied).as_mut_slice() { + [only] => only.take(), + _ => None, + }; + done.map(|_| copied) + } + + /// UID EXPUNGE (RFC 4315): the messages of the set that are marked `\Deleted` go for + /// good, and no others. Refused unsent unless the server has said `UIDPLUS`: a server + /// without it only knows the EXPUNGE that takes every marked message of the mailbox. + pub fn uid_expunge(&mut self, set: &str) -> Result<(), ProtoError> { + let set = named(set)?; + if !self.offers("UIDPLUS") { + return Err(ProtoError::Protocol(said!("the server can't remove single messages (it doesn't offer UIDPLUS)"))); + } + self.run(Command::new("UID EXPUNGE").arg(set), &mut ignore).map(|_| ()) + } + + /// CREATE . `raw_name` is the name as the server wants it: in modified UTF-7 + /// ([`encode_utf7`]), its levels joined with the server's own delimiter. + pub fn create(&mut self, raw_name: &str) -> Result<(), ProtoError> { + self.run(Command::new("CREATE").string(raw_name.as_bytes()), &mut ignore).map(|_| ()) + } + + /// SUBSCRIBE : other mail programs list subscribed mailboxes only. + pub fn subscribe(&mut self, raw_name: &str) -> Result<(), ProtoError> { + self.run(Command::new("SUBSCRIBE").string(raw_name.as_bytes()), &mut ignore).map(|_| ()) + } + + /// APPEND with a literal (handles the `+` continuation). + pub fn append(&mut self, raw_name: &str, flags: &[&str], message: &[u8]) -> Result<(), ProtoError> { + self.append_at(raw_name, flags, None, message).map(|_| ()) + } + + /// [`append`](Self::append), with the time the server is to keep as the message's arrival + /// (its `INTERNALDATE`, an IMAP `date-time` such as `01-Jul-2003 09:52:37 +0000`) when one is + /// given. Answers where the message went when the server says so beyond doubt (`APPENDUID`), + /// `None` otherwise. + pub fn append_at(&mut self, raw_name: &str, flags: &[&str], date: Option<&str>, message: &[u8]) -> Result, ProtoError> { + let mut command = Command::new("APPEND").string(raw_name.as_bytes()); + if !flags.is_empty() { + command = command.arg(&flag_list(flags)?); + } + if let Some(date) = date { + if !is_date_time(date) { + return Err(ProtoError::Protocol(said!("\"{date}\" is not a date and time IMAP can carry", date = tidy(date)))); + } + command = command.arg(&format!("\"{date}\"")); + } + self.appended.clear(); + let done = self.run(command.literal(message), &mut ignore); + // One answer that could be read, or nothing is known. + let appended = match std::mem::take(&mut self.appended).as_mut_slice() { + [only] => only.take(), + _ => None, + }; + done.map(|_| appended) + } + + /// LOGOUT. A server that hangs up without answering has logged us out all the same. + pub fn logout(mut self) -> Result<(), ProtoError> { + self.leaving = true; + match self.run(Command::new("LOGOUT"), &mut ignore) { + Ok(_) | Err(ProtoError::Io(_)) => Ok(()), + Err(e) => Err(e), + } + } + + fn fetch(set: &str, items: &str) -> Result, ProtoError> { + if !is_set(set) { + return Err(ProtoError::Protocol(said!("\"{set}\" is not a set of messages", set = tidy(set)))); + } + Ok(Command::new("UID FETCH").arg(set).arg(items)) + } + + /// How many commands have been sent on this connection (the tags used so far). + pub fn commands(&self) -> u32 { + self.next_tag.wrapping_sub(1) + } + + /// The tag of the next command. + fn tag(&mut self) -> String { + let tag = format!("A{:04}", self.next_tag); + self.next_tag = self.next_tag.wrapping_add(1); + tag + } + + /// Run a command that must end in OK; untagged data goes to `on_data` as it arrives. + fn run(&mut self, command: Command<'_>, on_data: &mut dyn FnMut(Vec)) -> Result { + let line = self.exchange(command, on_data)?; + match line.status { + Status::Ok => Ok(line), + _ => Err(ProtoError::Rejected(self.refusal(&line))), + } + } + + /// Send a command and read up to its tagged answer: OK, NO or BAD. + fn exchange(&mut self, command: Command<'_>, on_data: &mut dyn FnMut(Vec)) -> Result { + if command.unsendable { + return Err(ProtoError::Protocol(said!("the text has a character that can't be sent"))); + } + let tag = self.tag(); + self.text_seen = 0; + if log::log_enabled!(log::Level::Trace) { + log::trace!("C: {tag} {}", for_trace(&self.secrets.hide(&command.for_log()))); + } + let mut out = Vec::with_capacity(128); + out.extend_from_slice(tag.as_bytes()); + out.push(b' '); + for part in &command.parts { + match part { + Part::Text(text) => out.extend_from_slice(text), + Part::Literal(bytes) => { + // A literal is announced, and only sent once the server says `+`. + out.extend_from_slice(format!("{{{}}}\r\n", bytes.len()).as_bytes()); + self.wire.write(&out)?; + self.wire.flush()?; + out.clear(); + match self.read_until(&tag, true, on_data)? { + None => {} + // The command can't have succeeded without the rest of it. + Some(line) if line.status == Status::Ok => return Err(ProtoError::Protocol(said!("the server ended the command early"))), + Some(refused) => return Ok(refused), + } + self.wire.write(bytes)?; + } + } + } + out.extend_from_slice(b"\r\n"); + self.wire.write(&out)?; + self.wire.flush()?; + match self.read_until(&tag, false, on_data)? { + Some(line) => Ok(line), + None => Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + } + } + + /// Read responses up to the command's tagged answer (`Some`) or, when a literal is waiting to + /// be sent, the server's go-ahead (`None`). + fn read_until(&mut self, tag: &str, literal_waiting: bool, on_data: &mut dyn FnMut(Vec)) -> Result, ProtoError> { + for _ in 0..self.response_cap { + let response = self.read_response()?; + if self.text_seen > self.text_cap { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + match response { + Response::GoAhead if literal_waiting => return Ok(None), + Response::GoAhead => return Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + Response::Status { tag: Some(answered), line } => { + if answered != tag || !matches!(line.status, Status::Ok | Status::No | Status::Bad) { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + self.note_status(&line); + return Ok(Some(line)); + } + Response::Status { tag: None, line } => { + if line.status == Status::Bye && !self.leaving { + return Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said(self.refusal(&line))))); + } + self.note_status(&line); + } + Response::Data(values) => { + self.note_data(&values); + on_data(values); + } + } + } + Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))) + } + + /// A line of the server's text, counted against what one command may take. + fn read_text(&mut self) -> Result, ProtoError> { + loop { + let line = if self.skip_long { self.wire.read_line_or_skip()? } else { Some(self.wire.read_line()?) }; + let Some(line) = line else { + self.skipped = true; + self.text_seen = self.text_seen.saturating_add(crate::MAX_LINE); + if self.text_seen > self.text_cap { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + continue; + }; + self.text_seen = self.text_seen.saturating_add(line.len()).saturating_add(2); + return Ok(line); + } + } + + fn read_response(&mut self) -> Result { + let line = self.read_text()?; + if log::log_enabled!(log::Level::Trace) { + log::trace!("S: {}", for_trace(&self.secrets.hide(&String::from_utf8_lossy(&line)))); + } + if line.first() == Some(&b'+') { + return Ok(Response::GoAhead); + } + let Some(rest) = line.strip_prefix(b"* ") else { + // Tagged: `A0001 OK done`. + let text = String::from_utf8_lossy(&line); + let mut words = text.splitn(3, ' '); + let (tag, word, rest) = (words.next().unwrap_or(""), words.next().unwrap_or(""), words.next().unwrap_or("")); + return match Status::parse(word) { + Some(status) if !tag.is_empty() && tag != "*" => { + Ok(Response::Status { tag: Some(tag.to_string()), line: StatusLine::new(status, rest) }) + } + _ => Err(ProtoError::Protocol(said!("\"{line}\" is not an IMAP response", line = tidy(&self.secrets.hide(&text))))), + }; + }; + // `* OK …`, `* BYE …`: the rest is text for people, where `{5}` is no literal. + let word_end = rest.iter().position(|b| *b == b' ').unwrap_or(rest.len()); + let word = String::from_utf8_lossy(rest.get(..word_end).unwrap_or(&[])); + if let Some(status) = Status::parse(&word) { + let text = String::from_utf8_lossy(rest.get(word_end..).unwrap_or(&[])); + return Ok(Response::Status { tag: None, line: StatusLine::new(status, &text) }); + } + // Data: a line, and for as long as a line ends in `{n}`, n bytes and another line. + let mut pieces = Vec::new(); + let mut text = rest.to_vec(); + let (mut text_bytes, mut literal_bytes) = (text.len(), 0usize); + for _ in 0..=MAX_LITERALS { + let Some((_, claimed)) = parse::literal_marker(&text) else { + pieces.push(Piece::Text(text)); + return Ok(Response::Data(parse::values(pieces)?)); + }; + let size = usize::try_from(claimed).ok().filter(|n| literal_bytes.saturating_add(*n) <= MAX_LITERAL).ok_or_else(|| { + ProtoError::Protocol(said!( + "the server sent {claimed} bytes in one piece, more than the {mb} MB MailCraft accepts", + claimed, + mb = MAX_LITERAL >> 20 + )) + })?; + let literal = self.wire.read_block(size)?; + literal_bytes = literal_bytes.saturating_add(size); + log::trace!("S: ({size} bytes)"); + pieces.push(Piece::Text(text)); + pieces.push(Piece::Literal(literal)); + text = self.read_text()?; + text_bytes = text_bytes.saturating_add(text.len()); + if text_bytes > MAX_TEXT { + return Err(ProtoError::Protocol(said!("the server's response is too long"))); + } + } + Err(ProtoError::Protocol(said!("the server's response has too many parts"))) + } + + /// Keep what a status line says in its response code. + fn note_status(&mut self, line: &StatusLine) { + match line.code.as_str() { + "UIDVALIDITY" => self.selected.uid_validity = line.arg.parse().unwrap_or(0), + "UIDNEXT" => self.selected.uid_next = line.arg.parse().unwrap_or(0), + "COPYUID" if self.copied.len() < 2 => self.copied.push(copied_from(&line.arg)), + "APPENDUID" if self.appended.len() < 2 => self.appended.push(appended_from(&line.arg)), + "CAPABILITY" => self.capabilities = Some(line.arg.split_whitespace().take(MAX_CAPABILITIES).map(str::to_ascii_uppercase).collect()), + _ => {} + } + } + + /// Keep what untagged data says about the session, whichever command it arrives during. + fn note_data(&mut self, values: &[Value]) { + match (values.first().and_then(Value::atom), values.get(1).and_then(Value::atom)) { + (Some(count), Some(word)) if word.eq_ignore_ascii_case("EXISTS") => self.selected.exists = count.parse().unwrap_or(0), + (Some(word), _) if word.eq_ignore_ascii_case("CAPABILITY") => { + self.capabilities = Some(values.iter().skip(1).filter_map(Value::atom).take(MAX_CAPABILITIES).map(str::to_ascii_uppercase).collect()); + } + _ => {} + } + } + + /// The server's own words for why it said no, fit to show. + /// What the server said for itself, as it said it; MailCraft's words when it said nothing. + fn refusal(&self, line: &StatusLine) -> Text { + // Hidden before it is shortened: a secret cut in half would no longer be recognised. + let text = tidy(&self.secrets.hide(&line.text)); + if text.is_empty() { said!("the command was refused") } else { Text::verbatim(text) } + } +} + +#[cfg(test)] +mod gmail_labels_tests; +#[cfg(test)] +mod gmail_tests; +#[cfg(test)] +mod limits_tests; +#[cfg(test)] +mod tests; diff --git a/crates/proto/src/imap/parse.rs b/crates/proto/src/imap/parse.rs new file mode 100644 index 0000000000..f18ba92992 --- /dev/null +++ b/crates/proto/src/imap/parse.rs @@ -0,0 +1,346 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Reading IMAP responses: the pieces a response arrives in, the values in it, and status lines. + +use crate::ProtoError; +use crate::i18n::said; + +/// Deepest that parenthesised lists may nest. +const MAX_DEPTH: usize = 32; + +/// A response as it came off the wire: lines of text with the literals between them. +#[derive(Debug)] +pub(crate) enum Piece { + Text(Vec), + Literal(Vec), +} + +/// One value of a response. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Value { + /// A bare word: a number, a flag, `NIL`, `BODY[]`. + Atom(String), + /// A quoted string or a literal. + Str(Vec), + List(Vec), +} + +impl Value { + pub(crate) fn atom(&self) -> Option<&str> { + match self { + Value::Atom(a) => Some(a), + _ => None, + } + } + + pub(crate) fn number(&self) -> Option { + self.atom()?.parse().ok() + } + + /// The text of a string or a bare word (what the grammar calls an `astring`). + pub(crate) fn into_text(self) -> Option { + match self { + Value::Atom(a) => Some(a), + Value::Str(bytes) => Some(String::from_utf8_lossy(&bytes).into_owned()), + Value::List(_) => None, + } + } +} + +/// Where a line ends in a literal marker (`{123}`, also `{123+}`) outside any quoted string: the +/// marker's position and the size it names. +pub(crate) fn literal_marker(line: &[u8]) -> Option<(usize, u64)> { + let inner_end = line.len().checked_sub(1).filter(|last| line.get(*last) == Some(&b'}'))?; + let open = line.iter().rposition(|b| *b == b'{')?; + let inner = line.get(open + 1..inner_end)?; + let digits = inner.strip_suffix(b"+").unwrap_or(inner); + if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) { + return None; + } + // A brace inside a quoted string is just text. + let (mut quoted, mut escaped) = (false, false); + for b in line.get(..open)? { + if escaped { + escaped = false; + } else if quoted && *b == b'\\' { + escaped = true; + } else if *b == b'"' { + quoted = !quoted; + } + } + if quoted { + return None; + } + // A size beyond u64 is as large as can be, and refused like any other that is too large. + let size = digits.iter().try_fold(0u64, |n, d| n.checked_mul(10)?.checked_add(u64::from(d.wrapping_sub(b'0')))).unwrap_or(u64::MAX); + Some((open, size)) +} + +/// The values of a response. Unbalanced parentheses are forgiven; lists nested too deeply are not. +pub(crate) fn values(pieces: Vec) -> Result, ProtoError> { + // The list being filled is on top; the response itself is at the bottom. + let mut stack: Vec> = vec![Vec::new()]; + let mut pieces = pieces.into_iter().peekable(); + while let Some(piece) = pieces.next() { + match piece { + Piece::Literal(bytes) => push(&mut stack, Value::Str(bytes)), + Piece::Text(text) => { + // The marker of the literal that follows is not a value. + let end = match (pieces.peek(), literal_marker(&text)) { + (Some(Piece::Literal(_)), Some((at, _))) => at, + _ => text.len(), + }; + scan(text.get(..end).unwrap_or(&[]), &mut stack)?; + } + } + } + while stack.len() > 1 { + close(&mut stack); + } + Ok(stack.pop().unwrap_or_default()) +} + +fn push(stack: &mut [Vec], value: Value) { + if let Some(top) = stack.last_mut() { + top.push(value); + } +} + +fn close(stack: &mut Vec>) { + if stack.len() > 1 + && let Some(list) = stack.pop() + { + push(stack, Value::List(list)); + } +} + +fn scan(text: &[u8], stack: &mut Vec>) -> Result<(), ProtoError> { + // A `[` only opens a section (`BODY[HEADER.FIELDS (TO)]`) when a `]` follows somewhere. + let last_close = text.iter().rposition(|b| *b == b']'); + let mut i = 0; + // Every arm moves `i` forward. + while let Some(&b) = text.get(i) { + match b { + b' ' | b'\t' => i += 1, + b'(' => { + if stack.len() > MAX_DEPTH { + return Err(ProtoError::Protocol(said!("the server's response is nested too deeply"))); + } + stack.push(Vec::new()); + i += 1; + } + b')' => { + close(stack); + i += 1; + } + b'"' => { + let (string, next) = quoted(text, i + 1); + push(stack, Value::Str(string)); + i = next; + } + _ => { + let fetch_attribute = stack.len() == 2 + && stack.first().and_then(|root| root.get(1)).and_then(Value::atom).is_some_and(|word| word.eq_ignore_ascii_case("FETCH")); + let end = atom_end(text, i, if fetch_attribute { last_close } else { None }); + push(stack, Value::Atom(String::from_utf8_lossy(text.get(i..end).unwrap_or(&[])).into_owned())); + i = end; + } + } + } + Ok(()) +} + +/// The contents of the quoted string that starts at `start` (after its opening quote), and where +/// the text goes on. A string the line ends in the middle of is taken as far as it goes. +fn quoted(text: &[u8], start: usize) -> (Vec, usize) { + let mut out = Vec::new(); + let mut i = start; + while let Some(&b) = text.get(i) { + match b { + b'"' => return (out, i + 1), + b'\\' => { + out.extend(text.get(i + 1)); + i += 2; + } + _ => { + out.push(b); + i += 1; + } + } + } + (out, i) +} + +/// Where the bare word starting at `start` ends: at a space or parenthesis outside `[…]`. +fn atom_end(text: &[u8], start: usize, last_close: Option) -> usize { + let mut i = start; + while let Some(&b) = text.get(i) { + match b { + b' ' | b'\t' | b'(' | b')' if i > start => break, + b'[' if last_close.is_some_and(|close| close > i) + && text.get(start..i).is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"BODY") || prefix.eq_ignore_ascii_case(b"BODY.PEEK")) => + { + let close = text.get(i..).and_then(|rest| rest.iter().position(|b| *b == b']')).unwrap_or(0); + i += close + 1; + } + _ => i += 1, + } + } + i +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Status { + Ok, + No, + Bad, + Bye, + Preauth, +} + +impl Status { + pub(crate) fn parse(word: &str) -> Option { + match word.to_ascii_uppercase().as_str() { + "OK" => Some(Status::Ok), + "NO" => Some(Status::No), + "BAD" => Some(Status::Bad), + "BYE" => Some(Status::Bye), + "PREAUTH" => Some(Status::Preauth), + _ => None, + } + } +} + +/// `OK [UIDVALIDITY 3857529045] UIDs valid`, tagged or not. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct StatusLine { + pub(crate) status: Status, + /// The name of the response code, upper-cased (`UIDVALIDITY`); empty when there is none. + pub(crate) code: String, + /// What follows the name inside the brackets. + pub(crate) arg: String, + /// Everything after the status word, code included. + pub(crate) text: String, +} + +impl StatusLine { + pub(crate) fn new(status: Status, rest: &str) -> StatusLine { + let text = rest.trim(); + let inner = text.strip_prefix('[').and_then(|r| r.split_once(']')).map_or("", |(inner, _)| inner.trim()); + let (code, arg) = inner.split_once(' ').unwrap_or((inner, "")); + StatusLine { status, code: code.to_ascii_uppercase(), arg: arg.trim().to_string(), text: text.to_string() } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + fn text(s: &str) -> Piece { + Piece::Text(s.as_bytes().to_vec()) + } + + fn atom(s: &str) -> Value { + Value::Atom(s.into()) + } + + fn string(s: &str) -> Value { + Value::Str(s.as_bytes().to_vec()) + } + + fn parse(s: &str) -> Vec { + values(vec![text(s)]).unwrap() + } + + #[test] + fn atoms_strings_and_lists() { + assert_eq!( + parse(r#"LIST (\HasNoChildren \Sent) "/" "Sent \"old\" \\ mail""#), + vec![atom("LIST"), Value::List(vec![atom("\\HasNoChildren"), atom("\\Sent")]), string("/"), string("Sent \"old\" \\ mail")] + ); + assert_eq!( + parse("12 FETCH (UID 7 FLAGS ())"), + vec![atom("12"), atom("FETCH"), Value::List(vec![atom("UID"), atom("7"), atom("FLAGS"), Value::List(vec![])])] + ); + assert_eq!( + parse("a ((b) (c (d))) NIL"), + vec![atom("a"), Value::List(vec![Value::List(vec![atom("b")]), Value::List(vec![atom("c"), Value::List(vec![atom("d")])])]), atom("NIL")] + ); + assert_eq!(parse(""), vec![]); + assert_eq!(parse(" "), vec![]); + } + + #[test] + fn sections_are_part_of_the_word() { + assert_eq!( + parse("12 FETCH (BODY[HEADER.FIELDS (FROM TO)] x BODY[]<0> y)"), + vec![atom("12"), atom("FETCH"), Value::List(vec![atom("BODY[HEADER.FIELDS (FROM TO)]"), atom("x"), atom("BODY[]<0>"), atom("y")])] + ); + assert_eq!(parse(r#"LIST () "/" [Gmail]/Trash"#), vec![atom("LIST"), Value::List(vec![]), string("/"), atom("[Gmail]/Trash")]); + // A bracket that never closes is an ordinary character. + assert_eq!(parse("(a[b c)"), vec![Value::List(vec![atom("a[b"), atom("c")])]); + assert_eq!(parse("[[[[ x"), vec![atom("[[[["), atom("x")]); + } + + #[test] + fn broken_text_is_read_as_far_as_it_goes() { + assert_eq!(parse("(a (b"), vec![Value::List(vec![atom("a"), Value::List(vec![atom("b")])])]); + assert_eq!(parse("a) b))"), vec![atom("a"), atom("b")]); + assert_eq!(parse(r#""never closed"#), vec![string("never closed")]); + assert_eq!(parse(r#""ends in a backslash\"#), vec![string("ends in a backslash")]); + assert_eq!(parse("a\"b c"), vec![atom("a\"b"), atom("c")]); + let deep = "(".repeat(MAX_DEPTH + 5); + assert!(matches!(values(vec![text(&deep)]), Err(ProtoError::Protocol(_)))); + assert!(values(vec![text(&"(".repeat(MAX_DEPTH))]).is_ok()); + } + + #[test] + fn literals_take_the_place_of_their_marker() { + let pieces = + vec![text("1 FETCH (BODY[] {5}"), Piece::Literal(b"a (\"b".to_vec()), text(" UID 3 X {0}"), Piece::Literal(Vec::new()), text(")")]; + assert_eq!( + values(pieces).unwrap(), + vec![atom("1"), atom("FETCH"), Value::List(vec![atom("BODY[]"), string("a (\"b"), atom("UID"), atom("3"), atom("X"), string("")])] + ); + // Without a literal after it, a marker is only a word. + assert_eq!(parse("a {5}"), vec![atom("a"), atom("{5}")]); + } + + #[test] + fn markers() { + assert_eq!(literal_marker(b"* 1 FETCH (BODY[] {123}"), Some((18, 123))); + assert_eq!(literal_marker(b"{0}"), Some((0, 0))); + assert_eq!(literal_marker(b"x {7+}"), Some((2, 7))); + assert_eq!(literal_marker(b"\"quoted\" {7}"), Some((9, 7))); + assert_eq!(literal_marker(b"x {99999999999999999999999}"), Some((2, u64::MAX))); + for not in ["", "}", "{}", "{+}", "{5} ", "{-5}", "{5 }", "\"in a string {5}", "\"a \\\" {5}", "{5}x", "{ 5}", "5}"] { + assert_eq!(literal_marker(not.as_bytes()), None, "{not:?}"); + } + } + + #[test] + fn status_lines() { + let s = StatusLine::new(Status::Ok, " [UIDVALIDITY 3857529045] UIDs valid "); + assert_eq!((s.code.as_str(), s.arg.as_str(), s.text.as_str()), ("UIDVALIDITY", "3857529045", "[UIDVALIDITY 3857529045] UIDs valid")); + let s = StatusLine::new(Status::No, "[alert] disk full"); + assert_eq!((s.code.as_str(), s.arg.as_str()), ("ALERT", "")); + let s = StatusLine::new(Status::Ok, "done [not a code]"); + assert_eq!((s.code.as_str(), s.text.as_str()), ("", "done [not a code]")); + assert_eq!(StatusLine::new(Status::Bad, "[unclosed").code, ""); + assert_eq!(StatusLine::new(Status::Bad, "").text, ""); + assert_eq!(Status::parse("preauth"), Some(Status::Preauth)); + assert_eq!(Status::parse("FETCH"), None); + } + + #[test] + fn values_as_numbers_and_text() { + assert_eq!(atom("42").number(), Some(42)); + assert_eq!(atom("4294967296").number(), None); + assert_eq!(atom("-1").number(), None); + assert_eq!(string("42").number(), None); + assert_eq!(string("Entw&APw-rfe").into_text().as_deref(), Some("Entw&APw-rfe")); + assert_eq!(Value::Str(vec![0xFF, b'a']).into_text().as_deref(), Some("\u{FFFD}a")); + assert_eq!(Value::List(vec![]).into_text(), None); + } +} diff --git a/crates/proto/src/imap/password.rs b/crates/proto/src/imap/password.rs new file mode 100644 index 0000000000..acc7d0ec08 --- /dev/null +++ b/crates/proto/src/imap/password.rs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Password authentication from RFC 4616 and RFC 4959, over an already secured stream. + +use super::{Imap, ProtoError, Read, Status, Write, ignore, said}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +impl Imap { + /// Prefer the server's advertised PLAIN mechanism; otherwise use LOGIN. The host must + /// secure the stream first. Unknown capabilities are queried here; known ones are reused. + /// A refusal never triggers a second attempt with another mechanism. + pub fn authenticate_password(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if password.is_empty() { + return Err(ProtoError::Auth(said!("enter a password to sign in"))); + } + if user.is_empty() { + return Err(ProtoError::Auth(said!("enter a user name to sign in"))); + } + if self.capabilities.is_none() { + self.capabilities()?; + } + if !self.offers("AUTH=PLAIN") { + return self.login(user, password); + } + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("PLAIN needs a user name and password without NUL characters"))); + } + if user.len().saturating_add(password.len()) > 32 * 1024 { + return Err(ProtoError::Auth(said!("the user name or password is too long"))); + } + // Empty authorization identity: the server derives it from the authentication identity. + let response = STANDARD.encode(format!("\0{user}\0{password}").as_bytes()); + self.secrets.add(password); + self.secrets.add(&response); + let inline = self.offers("SASL-IR"); + let tag = self.tag(); + let command = if inline { format!("{tag} AUTHENTICATE PLAIN {response}\r\n") } else { format!("{tag} AUTHENTICATE PLAIN\r\n") }; + log::trace!("C: {tag} AUTHENTICATE PLAIN{}", if inline { " ***" } else { "" }); + self.wire.write(command.as_bytes())?; + self.wire.flush()?; + let mut sent = inline; + let mut cancelled = false; + let verdict = loop { + if let Some(verdict) = self.read_until(&tag, true, &mut ignore)? { + break verdict; + } + if cancelled { + return Err(ProtoError::Protocol(said!("the server continued a cancelled password authentication"))); + } + let answer = if sent { + cancelled = true; + "*" + } else { + sent = true; + response.as_str() + }; + log::trace!("C: ***"); + self.wire.write(format!("{answer}\r\n").as_bytes())?; + self.wire.flush()?; + }; + match verdict.status { + _ if cancelled => Err(ProtoError::Auth(said!("the server requested more than one PLAIN response"))), + Status::Ok if !sent => Err(ProtoError::Protocol(said!("the server accepted a password that was not sent"))), + Status::Ok => { + self.authenticated = true; + Ok(()) + } + Status::No => Err(ProtoError::Auth(self.refusal(&verdict))), + _ => Err(ProtoError::Rejected(self.refusal(&verdict))), + } + } +} diff --git a/crates/proto/src/imap/password_tests.rs b/crates/proto/src/imap/password_tests.rs new file mode 100644 index 0000000000..cbd0989fcc --- /dev/null +++ b/crates/proto/src/imap/password_tests.rs @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; +use crate::script::Script; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +fn greeting(caps: &str, replies: &str) -> String { + format!("* OK [CAPABILITY IMAP4rev1 {caps}] ready\r\n{replies}") +} + +#[test] +fn plain_uses_an_initial_response_only_when_advertised() { + let payload = STANDARD.encode(b"\0user@example.org\0invented"); + for inline in [false, true] { + let caps = if inline { "AUTH=PLAIN SASL-IR LOGINDISABLED" } else { "AUTH=PLAIN LOGINDISABLED" }; + let replies = if inline { "A0001 OK welcome\r\n" } else { "+ continue\r\nA0001 OK welcome\r\n" }; + let mut stream = Script::new(greeting(caps, replies)); + let mut imap = Imap::connect(&mut stream).unwrap(); + imap.authenticate_password("user@example.org", "invented").unwrap(); + assert!(imap.is_authenticated()); + let expected = if inline { format!("A0001 AUTHENTICATE PLAIN {payload}\r\n") } else { format!("A0001 AUTHENTICATE PLAIN\r\n{payload}\r\n") }; + assert_eq!(stream.sent(), expected); + } +} + +#[test] +fn login_remains_available_when_plain_is_not_advertised() { + let mut stream = Script::new(greeting("SASL-IR", "A0001 OK welcome\r\n")); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").unwrap(); + assert_eq!(stream.sent(), "A0001 LOGIN \"user@example.org\" \"invented\"\r\n"); +} + +#[test] +fn a_plain_refusal_is_redacted_and_never_retried_with_login() { + let payload = STANDARD.encode(b"\0user@example.org\0invented"); + let mut stream = Script::new(greeting("AUTH=PLAIN SASL-IR", &format!("A0001 NO [AUTHENTICATIONFAILED] invented {payload}\r\n"))); + let mut imap = Imap::connect(&mut stream).unwrap(); + let error = imap.authenticate_password("user@example.org", "invented").unwrap_err(); + assert!(matches!(error, ProtoError::Auth(_))); + assert!(!format!("{error:?} {imap:?}").contains("invented")); + assert!(!format!("{error:?} {imap:?}").contains(&payload)); + assert!(!imap.is_authenticated()); + assert!(!stream.sent().contains(" LOGIN ")); +} + +#[test] +fn a_refusal_before_the_challenge_sends_no_password() { + let mut stream = Script::new(greeting("AUTH=PLAIN", "A0001 NO unavailable\r\n")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").is_err()); + assert_eq!(stream.sent(), "A0001 AUTHENTICATE PLAIN\r\n"); +} + +#[test] +fn repeated_challenges_cancel_and_never_authenticate() { + for replies in ["+ first\r\n+ second\r\nA0001 OK ignored\r\n", "+ first\r\n+ second\r\n+ third\r\n"] { + let mut stream = Script::new(greeting("AUTH=PLAIN", replies)); + let mut imap = Imap::connect(&mut stream).unwrap(); + assert!(imap.authenticate_password("user@example.org", "invented").is_err()); + assert!(!imap.is_authenticated()); + assert!(stream.sent().ends_with("\r\n*\r\n")); + } +} + +#[test] +fn premature_success_and_invalid_credentials_are_refused() { + let mut stream = Script::new(greeting("AUTH=PLAIN", "A0001 OK too early\r\n")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").is_err()); + for (user, password) in [("", "invented"), ("user@example.org", ""), ("bad\0user", "invented"), ("user@example.org", "bad\0password")] { + let mut stream = Script::new(greeting("AUTH=PLAIN", "")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password(user, password).is_err()); + assert!(stream.sent().is_empty()); + } + let mut stream = Script::new(greeting("AUTH=PLAIN", "")); + assert!(Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", &"x".repeat(32769)).is_err()); + assert!(stream.sent().is_empty()); +} + +#[test] +fn utf8_and_line_breaks_are_encoded_not_protocol_lines() { + let mut stream = Script::new(greeting("auth=plain sasl-ir", "A0001 OK welcome\r\n")); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "päss\r\nword").unwrap(); + assert_eq!(stream.sent().lines().count(), 1); + assert!(stream.sent().contains(&STANDARD.encode("\0user@example.org\0päss\r\nword".as_bytes()))); +} + +#[test] +fn unknown_capabilities_are_queried_once_by_password_authentication() { + let mut stream = Script::new("* OK ready\r\n* CAPABILITY IMAP4rev1 AUTH=PLAIN SASL-IR\r\nA0001 OK done\r\nA0002 OK welcome\r\n"); + Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "invented").unwrap(); + assert!(stream.sent().starts_with("A0001 CAPABILITY\r\nA0002 AUTHENTICATE PLAIN ")); + assert_eq!(stream.sent().matches(" CAPABILITY").count(), 1); +} +#[test] +fn a_missing_password_has_its_own_message_without_network_commands() { + let mut stream = Script::new("* OK ready\r\n"); + let error = Imap::connect(&mut stream).unwrap().authenticate_password("user@example.org", "").unwrap_err(); + assert!(error.to_string().contains("enter a password")); + assert!(!error.to_string().contains("NUL")); + assert!(stream.sent().is_empty()); +} + +#[test] +fn an_empty_user_name_is_explained_before_any_commands() { + for text in ["* OK ready\r\n".to_string(), greeting("AUTH=PLAIN", ""), greeting("", "")] { + let mut stream = Script::new(text); + let error = Imap::connect(&mut stream).unwrap().authenticate_password("", "invented").unwrap_err(); + assert!(error.to_string().contains("enter a user name")); + assert!(!error.to_string().contains("NUL")); + assert!(stream.sent().is_empty()); + } +} diff --git a/crates/proto/src/imap/status.rs b/crates/proto/src/imap/status.rs new file mode 100644 index 0000000000..3c378308a3 --- /dev/null +++ b/crates/proto/src/imap/status.rs @@ -0,0 +1,164 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! STATUS (RFC 3501 §6.3.10): what a mailbox holds, asked without opening it, for a program to +//! tell whether it has changed since it was last read (#276). Many mailboxes are asked in one +//! go: the commands are written together and the answers read together (pipelining, RFC 3501 +//! §5.5), so a hundred mailboxes cost about one round trip, not a hundred. + +use std::io::{Read, Write}; + +use super::parse::{Status, Value}; +use super::{Command, Imap, MAX_COMMAND_TEXT, MAX_QUOTED, Part, Response}; +use crate::i18n::said; +use crate::{ProtoError, for_trace}; + +/// Most mailboxes asked in one go: their commands are a few kilobytes at most, so the server +/// can't be left waiting to be read while we write. +pub const MAX_STATUS_BATCH: usize = 50; + +/// What STATUS says of a mailbox: all four counts, or nothing at all (a server that leaves one +/// out gets its mailbox read, never passed over on a guess). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FolderStatus { + /// How many messages there are. + pub messages: u32, + /// The UID the next message to arrive gets. + pub uid_next: u32, + pub uid_validity: u32, + /// How many are not marked `\Seen`. + pub unseen: u32, +} + +/// From `STATUS name (MESSAGES 3 UIDNEXT 9 …)`; `None` when it isn't one, or a count is missing. +fn status_from(values: Vec) -> Option { + let mut values = values.into_iter(); + if !values.next()?.atom()?.eq_ignore_ascii_case("STATUS") { + return None; + } + values.next()?; + let Value::List(pairs) = values.next()? else { return None }; + let (mut messages, mut uid_next, mut uid_validity, mut unseen) = (None, None, None, None); + let mut pairs = pairs.into_iter(); + while let (Some(name), Some(value)) = (pairs.next(), pairs.next()) { + let Some(number) = value.number() else { continue }; + match name.atom().map(str::to_ascii_uppercase).as_deref() { + Some("MESSAGES") => messages = Some(number), + Some("UIDNEXT") => uid_next = Some(number), + Some("UIDVALIDITY") => uid_validity = Some(number), + Some("UNSEEN") => unseen = Some(number), + _ => {} + } + } + Some(FolderStatus { messages: messages?, uid_next: uid_next?, uid_validity: uid_validity?, unseen: unseen? }) +} + +fn command(raw_name: &str) -> Command<'_> { + Command::new("STATUS").string(raw_name.as_bytes()).arg("(MESSAGES UIDNEXT UIDVALIDITY UNSEEN)") +} + +impl Imap { + /// STATUS of one mailbox; `None` when the server refuses or leaves a count out. + pub fn status(&mut self, raw_name: &str) -> Result, ProtoError> { + let mut found = None; + let line = self.exchange(command(raw_name), &mut |values| { + if found.is_none() { + found = status_from(values); + } + })?; + Ok(found.filter(|_| line.status == Status::Ok)) + } + + /// STATUS of each of `raw_names`, in the same order, `None` for one the server refuses or + /// leaves a count out of. At most [`MAX_STATUS_BATCH`] are asked in one go; a name that + /// can't go in a quoted string is asked alone. + /// + /// An error is the connection's: the answers read before it are lost with it. + pub fn status_many(&mut self, raw_names: &[&str]) -> Result>, ProtoError> { + let mut out = Vec::with_capacity(raw_names.len()); + for batch in raw_names.chunks(MAX_STATUS_BATCH) { + let plain = batch.iter().all(|name| name.len() <= MAX_QUOTED && name.bytes().all(|b| matches!(b, b' '..=b'~'))); + if plain && batch.len() > 1 { + out.extend(self.status_batch(batch)?); + } else { + for name in batch { + out.push(self.status(name)?); + } + } + } + Ok(out) + } + + /// One batch, written together: the answers come in the order of the commands. + fn status_batch(&mut self, batch: &[&str]) -> Result>, ProtoError> { + let mut tags = Vec::with_capacity(batch.len()); + let mut out = Vec::with_capacity(batch.len().saturating_mul(64)); + for name in batch { + let command = command(name); + if command.unsendable { + return Err(ProtoError::Protocol(said!("the text has a character that can't be sent"))); + } + let tag = self.tag(); + if log::log_enabled!(log::Level::Trace) { + log::trace!("C: {tag} {}", for_trace(&self.secrets.hide(&command.for_log()))); + } + out.extend_from_slice(tag.as_bytes()); + out.push(b' '); + for part in &command.parts { + if let Part::Text(text) = part { + out.extend_from_slice(text); + } + } + out.extend_from_slice(b"\r\n"); + tags.push(tag); + } + self.wire.write(&out)?; + self.wire.flush()?; + self.text_seen = 0; + let mut found: Vec> = vec![None; batch.len()]; + let mut answered = 0usize; + // Each command brings one STATUS and its tagged answer; the rest is slack for what a + // server says unasked. + let cap = batch.len().saturating_mul(2).saturating_add(64); + for _ in 0..cap { + if answered >= tags.len() { + break; + } + match self.read_response()? { + Response::GoAhead => return Err(ProtoError::Protocol(said!("the server asked for more than the command had"))), + Response::Status { tag: Some(tag), line } => { + if tags.get(answered) != Some(&tag) || !matches!(line.status, Status::Ok | Status::No | Status::Bad) { + return Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent"))); + } + self.note_status(&line); + if line.status != Status::Ok + && let Some(slot) = found.get_mut(answered) + { + *slot = None; + } + answered += 1; + } + Response::Status { tag: None, line } => { + if line.status == Status::Bye && !self.leaving { + return Err(ProtoError::Io(said!("the server ended the session"))); + } + self.note_status(&line); + } + Response::Data(values) => { + if self.text_seen > MAX_COMMAND_TEXT { + return Err(ProtoError::Protocol(said!("the server sent too much in answer to one command"))); + } + self.note_data(&values); + if let Some(slot) = found.get_mut(answered) + && slot.is_none() + { + *slot = status_from(values); + } + } + } + } + if answered < tags.len() { + return Err(ProtoError::Protocol(said!("the server sent too many responses to one command"))); + } + Ok(found) + } +} diff --git a/crates/proto/src/imap/status_tests.rs b/crates/proto/src/imap/status_tests.rs new file mode 100644 index 0000000000..a0f252b35d --- /dev/null +++ b/crates/proto/src/imap/status_tests.rs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use proptest::prelude::*; + +use super::*; +use crate::script::Script; + +fn status(messages: u32, uid_next: u32, uid_validity: u32, unseen: u32) -> FolderStatus { + FolderStatus { messages, uid_next, uid_validity, unseen } +} + +#[test] +fn one_mailbox_is_asked_its_four_counts() { + let mut s = Script::new("* STATUS \"Work\" (MESSAGES 3 UIDNEXT 9 UIDVALIDITY 77 UNSEEN 1)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).status("Work").unwrap(); + assert_eq!(got, Some(status(3, 9, 77, 1))); + assert_eq!(s.sent(), "A0001 STATUS \"Work\" (MESSAGES UIDNEXT UIDVALIDITY UNSEEN)\r\n"); +} + +#[test] +fn a_count_left_out_or_a_refusal_is_no_status() { + let mut s = Script::new("* STATUS Work (MESSAGES 3 UIDNEXT 9 UIDVALIDITY 77)\r\nA0001 OK done\r\nA0002 NO [NONEXISTENT] no such mailbox\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.status("Work").unwrap(), None); + assert_eq!(imap.status("Gone").unwrap(), None); +} + +#[test] +fn many_mailboxes_are_asked_in_one_write() { + let mut s = Script::new( + "* STATUS A (MESSAGES 1 UIDNEXT 2 UIDVALIDITY 5 UNSEEN 0)\r\nA0001 OK done\r\n\ + A0002 NO [NONEXISTENT] no\r\n\ + * STATUS \"C d\" (UNSEEN 4 UIDVALIDITY 7 UIDNEXT 8 MESSAGES 9 HIGHESTMODSEQ 12)\r\nA0003 OK done\r\n", + ); + let got = Imap::resume(&mut s).status_many(&["A", "B", "C d"]).unwrap(); + assert_eq!(got, vec![Some(status(1, 2, 5, 0)), None, Some(status(9, 8, 7, 4))]); + let sent = s.sent(); + assert_eq!(sent.matches("STATUS").count(), 3); + assert!(sent.starts_with("A0001 STATUS \"A\" ") && sent.contains("A0003 STATUS \"C d\" "), "{sent}"); +} + +#[test] +fn answers_out_of_turn_or_too_many_end_the_session_not_the_program() { + let mut s = Script::new("A0002 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Protocol(_)))); + let flood = "* 1 EXISTS\r\n".repeat(500); + let mut s = Script::new(flood); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Protocol(_)))); + let mut s = Script::new("* BYE going\r\n"); + assert!(matches!(Imap::resume(&mut s).status_many(&["A", "B"]), Err(ProtoError::Io(_)))); +} + +#[test] +fn a_name_that_needs_a_literal_is_asked_alone() { + let mut s = Script::new("+ go\r\n* STATUS x (MESSAGES 1 UIDNEXT 2 UIDVALIDITY 3 UNSEEN 0)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).status_many(&["é", "A"]).unwrap_or_default(); + assert!(got.len() <= 2); +} + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_in_status(server in proptest::collection::vec(any::(), 0..600), names in 0usize..120) { + let list: Vec = (0..names).map(|n| format!("F{n}")).collect(); + let refs: Vec<&str> = list.iter().map(String::as_str).collect(); + let mut s = Script::new(&server); + let got = Imap::resume(&mut s).status_many(&refs); + if let Ok(got) = got { + prop_assert_eq!(got.len(), names); + } + } + + #[test] + fn any_status_line_is_read_or_not(line in "[ -~]{0,80}") { + let mut s = Script::new(format!("* STATUS {line}\r\nA0001 OK done\r\n")); + let _ = Imap::resume(&mut s).status("x"); + } +} diff --git a/crates/proto/src/imap/tests.rs b/crates/proto/src/imap/tests.rs new file mode 100644 index 0000000000..c384d01546 --- /dev/null +++ b/crates/proto/src/imap/tests.rs @@ -0,0 +1,1068 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::ErrorKind; + +use proptest::prelude::*; + +use super::*; +use crate::script::{Broken, Script}; + +fn mailbox(name: &str, raw: &str, delimiter: Option, flags: &[&str]) -> Mailbox { + Mailbox { name: name.into(), raw: raw.into(), delimiter, flags: flags.iter().map(|f| f.to_string()).collect() } +} + +fn fetched(uid: u32, flags: &[&str]) -> Fetched { + Fetched { uid, flags: flags.iter().map(|f| f.to_string()).collect(), internal_date: None, body: None, gmail_id: None, gmail_labels: None } +} + +/// A FETCH response carrying `body` as a literal, between `before` and `after`. +fn with_literal(before: &str, body: &[u8], after: &str) -> Vec { + let mut out = format!("{before}{{{}}}\r\n", body.len()).into_bytes(); + out.extend_from_slice(body); + out.extend_from_slice(after.as_bytes()); + out +} + +#[test] +fn greetings() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 STARTTLS] mail.example.org ready\r\n"); + let imap = Imap::connect(&mut s).unwrap(); + assert!(!imap.is_authenticated()); + assert_eq!(imap.capabilities, Some(vec!["IMAP4REV1".to_string(), "STARTTLS".to_string()])); + + let mut s = Script::new("* PREAUTH welcome back\r\n"); + assert!(Imap::connect(&mut s).unwrap().is_authenticated()); + + let mut s = Script::new("* BYE overloaded, try later\r\n"); + assert_eq!(Imap::connect(&mut s).unwrap_err(), ProtoError::Rejected("overloaded, try later".into())); + + for junk in ["hello\r\n", "+ go on\r\n", "* 3 EXISTS\r\n", "A0001 OK early\r\n", "* NO\r\n", "\r\n", "*\r\n", "220 smtp.example.org ESMTP\r\n"] { + let mut s = Script::new(junk); + assert!(matches!(Imap::connect(&mut s), Err(ProtoError::Protocol(_))), "{junk:?}"); + } + let mut s = Script::new(""); + assert!(matches!(Imap::connect(&mut s), Err(ProtoError::Io(_)))); +} + +#[test] +fn capabilities_are_upper_cased() { + let mut s = Script::new( + "* CAPABILITY IMAP4rev1 StartTLS special-use AUTH=PLAIN\r\nA0001 OK done\r\nA0002 OK [CAPABILITY IMAP4rev1 IDLE] done\r\nA0003 OK none\r\n", + ); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.capabilities().unwrap(), ["IMAP4REV1", "STARTTLS", "SPECIAL-USE", "AUTH=PLAIN"]); + // Some servers answer in the tagged line. + assert_eq!(imap.capabilities().unwrap(), ["IMAP4REV1", "IDLE"]); + assert_eq!(imap.capabilities().unwrap(), Vec::::new()); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 CAPABILITY\r\nA0003 CAPABILITY\r\n"); +} + +#[test] +fn login_quotes_its_strings() { + let mut s = Script::new("A0001 OK [CAPABILITY IMAP4rev1] welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login(r#"ada "the" \ lovelace"#, r#"p"w\d {5}"#).unwrap(); + assert!(imap.is_authenticated()); + assert_eq!(s.sent(), "A0001 LOGIN \"ada \\\"the\\\" \\\\ lovelace\" \"p\\\"w\\\\d {5}\"\r\n"); +} + +#[test] +fn login_sends_what_quotes_cannot_carry_as_literals() { + let mut s = Script::new("+ go on\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login("ada", "pässwörd").unwrap(); + assert_eq!(s.sent(), "A0001 LOGIN \"ada\" {10}\r\npässwörd\r\n"); + + // Both as literals, each after its own go-ahead; a line break can't end the command early. + let mut s = Script::new("+ go on\r\n+ go on\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + imap.login("ädä", "two\r\nA0002 LOGOUT").unwrap(); + assert_eq!(s.sent(), "A0001 LOGIN {5}\r\nädä {17}\r\ntwo\r\nA0002 LOGOUT\r\n"); + + // A very long password too. + let long = "x".repeat(MAX_QUOTED + 1); + let mut s = Script::new("+ go on\r\nA0001 OK welcome\r\n"); + Imap::resume(&mut s).login("ada", &long).unwrap(); + assert!(s.sent().starts_with("A0001 LOGIN \"ada\" {1001}\r\nxxx")); +} + +#[test] +fn a_wrong_password_is_an_auth_error_that_never_shows_it() { + // A careless server repeats what it was sent. + let mut s = Script::new("A0001 NO [AUTHENTICATIONFAILED] no user ada with password hunter2\r\n"); + let mut imap = Imap::resume(&mut s); + let err = imap.login("ada", "hunter2").unwrap_err(); + assert_eq!(err, ProtoError::Auth("[AUTHENTICATIONFAILED] no user ada with password ***".into())); + assert!(!imap.is_authenticated()); + assert!(!format!("{err} {err:?} {imap:?}").contains("hunter2")); + + // BAD is not about the password. + let mut s = Script::new("A0001 BAD what\r\n"); + assert_eq!(Imap::resume(&mut s).login("ada", "hunter2"), Err(ProtoError::Rejected("what".into()))); + + // Refused before the literal went out: the password is never sent. + let mut s = Script::new("A0001 NO no literals here\r\n"); + assert!(matches!(Imap::resume(&mut s).login("ada", "pässwörd"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), "A0001 LOGIN \"ada\" {10}\r\n"); + + // Nothing at all is sent when it can't be. + let mut s = Script::new("A0001 OK welcome\r\n"); + assert!(matches!(Imap::resume(&mut s).login("ada", "nul\0"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), ""); +} + +#[test] +fn no_password_for_a_server_that_disabled_login() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED] ready\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + assert!(matches!(imap.login("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert_eq!(s.sent(), ""); +} + +const TOKEN: &str = "tok.en-123"; + +/// What goes out for `ada@example.org` with [`TOKEN`]. +fn bearer() -> String { + let payload = xoauth2("ada@example.org", TOKEN).unwrap(); + assert_eq!(payload, "dXNlcj1hZGFAZXhhbXBsZS5vcmcBYXV0aD1CZWFyZXIgdG9rLmVuLTEyMwEB"); + payload +} + +#[test] +fn a_token_goes_with_the_command_when_the_server_takes_it_that_way() { + let mut s = Script::new("* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=PLAIN AUTH=XOAUTH2] ready\r\nA0001 OK [CAPABILITY IMAP4rev1 IDLE] welcome\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap(); + assert!(imap.is_authenticated()); + // What the server can do once signed in is noted. + assert_eq!(imap.capabilities, Some(vec!["IMAP4REV1".to_string(), "IDLE".to_string()])); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2 {}\r\n", bearer())); + assert!(s.finished()); +} + +#[test] +fn a_token_waits_for_the_go_ahead_otherwise() { + // A server that hasn't said what it can do, one without SASL-IR, and one that has SASL-IR + // but didn't list the mechanism: each is asked first. + for greeting in ["", "* OK [CAPABILITY IMAP4rev1 AUTH=XOAUTH2] ready\r\n", "* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=PLAIN] ready\r\n"] { + let mut s = Script::new(format!("{greeting}+ \r\n* CAPABILITY IMAP4rev1 IDLE\r\nA0001 OK welcome\r\n")); + let mut imap = if greeting.is_empty() { Imap::resume(&mut s) } else { Imap::connect(&mut s).unwrap() }; + imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap(); + assert!(imap.is_authenticated(), "{greeting:?}"); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{}\r\n", bearer()), "{greeting:?}"); + } +} + +#[test] +fn a_refused_token_is_an_auth_error_that_never_shows_it() { + let payload = bearer(); + let caps = "* OK [CAPABILITY IMAP4rev1 SASL-IR AUTH=XOAUTH2] ready\r\n"; + // The reasons come first (JSON in base64) and the verdict after an empty line; a careless + // server repeats what it was sent. + let reasons = "+ eyJzdGF0dXMiOiI0MDEiLCJzY2hlbWVzIjoiYmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZXhhbXBsZS5vcmcvIn0=\r\n"; + let mut s = Script::new(format!("{caps}{reasons}A0001 NO [AUTHENTICATIONFAILED] no good: {TOKEN} ({payload})\r\n")); + let mut imap = Imap::connect(&mut s).unwrap(); + let err = imap.authenticate_xoauth2("ada@example.org", TOKEN).unwrap_err(); + assert_eq!(err, ProtoError::Auth("[AUTHENTICATIONFAILED] no good: *** (***)".into())); + assert!(!imap.is_authenticated()); + assert!(!format!("{err} {err:?} {imap:?}").contains(TOKEN)); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2 {payload}\r\n\r\n")); + assert!(s.finished()); + + // The same after a go-ahead. + let mut s = Script::new(format!("+ \r\n{reasons}A0001 NO AUTHENTICATE failed.\r\n")); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth("AUTHENTICATE failed.".into()))); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{payload}\r\n\r\n")); + + // Refused in one word, without reasons. + let mut s = Script::new("+ \r\nA0001 NO AUTHENTICATE failed.\r\n"); + assert_eq!(Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth("AUTHENTICATE failed.".into()))); + assert_eq!(s.sent(), format!("A0001 AUTHENTICATE XOAUTH2\r\n{payload}\r\n")); + + // A token echoed in a long answer is hidden before the answer is shortened. + let long = format!("head.{}.tail", "x".repeat(2_000)); + let mut s = Script::new(format!("+ \r\nA0001 NO {} bad token {long}\r\n", "no ".repeat(80))); + let err = Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", &long).unwrap_err(); + let shown = format!("{err} {err:?}"); + assert!(matches!(err, ProtoError::Auth(_))); + assert!(!shown.contains("head.") && !shown.contains("xxxx"), "{shown}"); +} + +#[test] +fn a_server_without_the_mechanism_never_sees_the_token() { + for (server, expected) in [ + ("A0001 NO [CANNOT] unsupported authentication mechanism\r\n", ProtoError::Auth("[CANNOT] unsupported authentication mechanism".into())), + ("A0001 BAD what\r\n", ProtoError::Rejected("what".into())), + // "Signed in" without having been shown anything can't be true. + ("A0001 OK welcome\r\n", ProtoError::Protocol(said!("the server ended the command early"))), + ] { + let mut s = Script::new(format!("* OK [CAPABILITY IMAP4rev1 AUTH=PLAIN] ready\r\n{server}")); + let mut imap = Imap::connect(&mut s).unwrap(); + assert_eq!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(expected), "{server:?}"); + assert!(!imap.is_authenticated()); + assert_eq!(s.sent(), "A0001 AUTHENTICATE XOAUTH2\r\n", "{server:?}"); + } +} + +#[test] +fn questions_a_token_has_no_answer_to_end_the_sign_in() { + // After the reasons, another question: the exchange is cancelled. + let mut s = Script::new("+ \r\n+ e30=\r\n+ more?\r\nA0001 BAD cancelled\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n\r\n*\r\n")); + // A server that calls a cancelled exchange a success is not believed. + let mut s = Script::new("+ \r\n+ e30=\r\n+ more?\r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Auth(_)))); + assert!(!imap.is_authenticated()); + // One that never stops asking. + let mut s = Script::new("+ \r\n".repeat(50)); + assert!(matches!(Imap::resume(&mut s).authenticate_xoauth2("ada@example.org", TOKEN), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent().matches("\r\n").count(), 4); +} + +#[test] +fn a_token_or_name_that_cannot_be_sent_is_refused() { + let mut s = Script::new("+ \r\nA0001 OK welcome\r\n"); + let mut imap = Imap::resume(&mut s); + for (user, token) in + [("ada", ""), ("ada", "tok\r\nA0002 LOGOUT"), ("ada", "tok\x01"), ("ada\x01auth=Bearer x", "tok"), ("a\0da", "tok"), ("ada\n", "tok")] + { + assert!(matches!(imap.authenticate_xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert!(!imap.is_authenticated()); + assert_eq!(s.sent(), ""); +} + +#[test] +fn mailboxes_are_listed_with_names_in_every_form() { + let mut server = String::new(); + server += "* LIST (\\HasNoChildren) \"/\" INBOX\r\n"; + server += "* LIST (\\HasNoChildren \\Sent) \"/\" \"Sent Items\"\r\n"; + server += "* LIST (\\Noselect \\HasChildren) \"/\" \"[Gmail]\"\r\n"; + server += "* LIST (\\HasNoChildren \\Trash) \"/\" [Gmail]/Trash\r\n"; + server += "* LIST () NIL \"Entw&APw-rfe\"\r\n"; + server += "* LIST (\\HasNoChildren) \".\" {12}\r\nINBOX.&Jjo-!\r\n"; + server += "* LIST () \"/\" \"quoted \\\"name\\\" \\\\ here\"\r\n"; + server += "* LSUB () \"/\" subscribed\r\n"; + server += "* 5 EXISTS\r\n"; + server += "* LIST (\\HasNoChildren) \"/\" INBOX\r\n"; + server += "* LIST broken\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let list = Imap::resume(&mut s).list().unwrap(); + assert_eq!(s.sent(), "A0001 LIST \"\" \"*\"\r\n"); + assert_eq!( + list, + [ + mailbox("INBOX", "INBOX", Some('/'), &["\\HasNoChildren"]), + mailbox("Sent Items", "Sent Items", Some('/'), &["\\HasNoChildren", "\\Sent"]), + mailbox("[Gmail]", "[Gmail]", Some('/'), &["\\Noselect", "\\HasChildren"]), + mailbox("[Gmail]/Trash", "[Gmail]/Trash", Some('/'), &["\\HasNoChildren", "\\Trash"]), + mailbox("Entwürfe", "Entw&APw-rfe", None, &[]), + mailbox("INBOX.☺!", "INBOX.&Jjo-!", Some('.'), &["\\HasNoChildren"]), + mailbox("quoted \"name\" \\ here", "quoted \"name\" \\ here", Some('/'), &[]), + ] + ); + assert!(list[2].has_flag("\\NOSELECT") && !list[0].has_flag("\\Noselect")); +} + +#[test] +fn opening_a_mailbox() { + let mut server = String::new(); + server += "* 172 EXISTS\r\n* 1 RECENT\r\n* OK [UNSEEN 12] Message 12 is first unseen\r\n"; + server += "* OK [UIDVALIDITY 3857529045] UIDs valid\r\n* OK [UIDNEXT 4392] Predicted next UID\r\n"; + server += "* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)\r\n* OK [PERMANENTFLAGS ()] No permanent flags permitted\r\n"; + server += "A0001 OK [READ-ONLY] EXAMINE completed\r\n"; + // The next one is empty and says little. + server += "* 0 EXISTS\r\n* OK [UIDVALIDITY 7]\r\nA0002 OK [READ-WRITE] SELECT completed\r\n"; + server += "A0003 NO [NONEXISTENT] no such mailbox\r\n"; + server += "+ go on\r\n* 3 EXISTS\r\n* OK [UIDVALIDITY 99999999999] too large to be one\r\nA0004 OK done\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.select("Sent Items", true).unwrap(), Selected { exists: 172, uid_validity: 3_857_529_045, uid_next: 4392 }); + assert_eq!(imap.select("INBOX", false).unwrap(), Selected { exists: 0, uid_validity: 7, uid_next: 0 }); + assert_eq!(imap.select("Nowhere", true), Err(ProtoError::Rejected("[NONEXISTENT] no such mailbox".into()))); + // A name the server wrote in UTF-8 goes back as a literal. + assert_eq!(imap.select("Entwürfe", true).unwrap(), Selected { exists: 3, uid_validity: 0, uid_next: 0 }); + assert_eq!(s.sent(), "A0001 EXAMINE \"Sent Items\"\r\nA0002 SELECT \"INBOX\"\r\nA0003 EXAMINE \"Nowhere\"\r\nA0004 EXAMINE {9}\r\nEntwürfe\r\n"); +} + +#[test] +fn flags_of_every_message_with_other_news_in_between() { + let mut server = String::new(); + server += "* 1 FETCH (UID 4 FLAGS (\\Seen \\Answered))\r\n"; + server += "* 2 FETCH (FLAGS (\\Flagged $Forwarded) UID 7)\r\n"; + server += "* 3 EXPUNGE\r\n* 9 EXISTS\r\n* 1 RECENT\r\n* FLAGS (\\Seen)\r\n"; + // Text for people may end like a literal without being one. + server += "* OK [ALERT] still here {5}\r\n"; + // Without a UID there is no telling which message this is. + server += "* 4 FETCH (FLAGS (\\Deleted))\r\n"; + server += "* 3 FETCH (UID 9 FLAGS ())\r\n"; + // The later word about a message counts. + server += "* 2 FETCH (UID 7 FLAGS (\\Seen))\r\n"; + // A message named without its flags is there all the same, and one named again keeps the flags it had. + server += "* 5 FETCH (UID 2 RFC822.SIZE 100)\r\n"; + server += "* 1 FETCH (UID 4)\r\n"; + server += "A0001 OK done\r\n"; + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(); + assert_eq!(got, [fetched(2, &[]), fetched(4, &["\\Seen", "\\Answered"]), fetched(7, &["\\Seen"]), fetched(9, &[])]); + assert_eq!(s.sent(), "A0001 UID FETCH 1:* (UID FLAGS)\r\n"); + + let mut s = Script::new("A0001 OK nothing there\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("5,9,12:20").unwrap(), []); + assert_eq!(s.sent(), "A0001 UID FETCH 5,9,12:20 (UID FLAGS)\r\n"); +} + +#[test] +fn sizes() { + let mut s = + Script::new("* 2 FETCH (RFC822.SIZE 99999999999 UID 9)\r\n* 1 FETCH (UID 4 RFC822.SIZE 2048)\r\n* 3 FETCH (UID 5)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_sizes("4:9").unwrap(), [(4, 2048), (9, 99_999_999_999)]); + assert_eq!(s.sent(), "A0001 UID FETCH 4:9 (UID RFC822.SIZE)\r\n"); +} + +#[test] +fn sets_that_are_not_sets_are_never_sent() { + for bad in ["", "1:* (BODY[])", "1 2", "a", "1:*\r\nA0002 LOGOUT"] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_fetch_flags(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_fetch_sizes(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn a_message_arrives_whole_whatever_is_in_it() { + // A body full of things that look like protocol. + let body = b"Subject: Hi\r\n\r\nA0001 OK fake\r\n* 1 FETCH (UID 2)\r\n{5}\r\n\"(\\\r\n)"; + let mut server = with_literal("* 5 FETCH (UID 12 FLAGS (\\Seen $Forwarded) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" BODY[] ", body, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(12).unwrap().unwrap(); + assert_eq!( + got, + Fetched { + uid: 12, + flags: vec!["\\Seen".into(), "$Forwarded".into()], + internal_date: Some("17-Jul-1996 02:44:25 -0700".into()), + body: Some(body.to_vec()), + gmail_id: None, + gmail_labels: None + } + ); + assert_eq!(s.sent(), "A0001 UID FETCH 12 (UID FLAGS INTERNALDATE BODY.PEEK[])\r\n"); + assert!(s.finished()); +} + +#[test] +fn fetch_items_come_in_any_order() { + let body = b"From: ada@example.org\r\n\r\nBody\r\n"; + let mut server = with_literal( + "* 5 FETCH (BODY[] ", + body, + " INTERNALDATE \" 7-Jul-1996 02:44:25 +0000\" RFC822.SIZE 31 FLAGS () UID 12 X-UNKNOWN (a (b)))\r\n", + ); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(12).unwrap().unwrap(); + assert_eq!( + (got.uid, got.flags.len(), got.internal_date.as_deref(), got.body.as_deref()), + (12, 0, Some(" 7-Jul-1996 02:44:25 +0000"), Some(&body[..])) + ); +} + +#[test] +fn bodies_at_the_edges() { + // Empty, as a literal of no bytes. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] {0}\r\n)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(Vec::new())); + // Short, in quotes. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] \"tiny \\\"body\\\"\")\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(b"tiny \"body\"".to_vec())); + // Under its old name. + let mut s = Script::new("* 1 FETCH (UID 3 RFC822 {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(b"ok".to_vec())); + // Flags in one response, the body in another. + let mut s = Script::new("* 1 FETCH (UID 3 FLAGS (\\Seen))\r\n* 1 FETCH (UID 3 BODY[] {2}\r\nok)\r\nA0001 OK done\r\n"); + let got = Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap(); + assert_eq!((got.flags, got.body), (vec!["\\Seen".to_string()], Some(b"ok".to_vec()))); + // A megabyte in one piece. + let big = vec![b'x'; 1 << 20]; + let mut server = with_literal("* 1 FETCH (UID 3 BODY[] ", &big, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::whole(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3).unwrap().unwrap().body, Some(big)); +} + +#[test] +fn a_message_that_is_gone_is_none() { + for server in [ + "A0001 OK nothing\r\n", + "* 1 FETCH (UID 3 BODY[] NIL)\r\nA0001 OK done\r\n", + "* 1 FETCH (UID 3 FLAGS (\\Seen))\r\nA0001 OK done\r\n", + "* 1 FETCH (UID 4 BODY[] {2}\r\nno)\r\n* 2 EXPUNGE\r\nA0001 OK done\r\n", + "* 1 FETCH (BODY[] {2}\r\nno)\r\nA0001 OK done\r\n", + ] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Ok(None), "{server:?}"); + } + // There is no message 0 to ask for. + let mut s = Script::new(""); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(0), Ok(None)); + assert_eq!(s.sent(), ""); + let mut s = Script::new("A0001 NO [SERVERBUG] can't read it\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Rejected("[SERVERBUG] can't read it".into()))); +} + +#[test] +fn a_header_arrives_alone() { + let header = b"From: ada@example.org\r\nSubject: Sixty megabytes\r\n\r\n"; + let mut server = with_literal("* 5 FETCH (UID 12 FLAGS (\\Seen) INTERNALDATE \"17-Jul-1996 02:44:25 -0700\" BODY[HEADER] ", header, ")\r\n"); + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_header(12).unwrap().unwrap(); + assert_eq!( + got, + Fetched { + uid: 12, + flags: vec!["\\Seen".into()], + internal_date: Some("17-Jul-1996 02:44:25 -0700".into()), + body: Some(header.to_vec()), + gmail_id: None, + gmail_labels: None + } + ); + assert_eq!(s.sent(), "A0001 UID FETCH 12 (UID FLAGS INTERNALDATE BODY.PEEK[HEADER])\r\n"); + assert!(s.finished()); + // Under its old name, and empty. + let mut s = Script::new("* 1 FETCH (UID 3 RFC822.HEADER {2}\r\n\r\n)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3).unwrap().unwrap().body, Some(b"\r\n".to_vec())); + // A server that sends the whole message when asked for its header is not taken at its word, + // nor is a header taken for a message. + let mut s = Script::new("* 1 FETCH (UID 3 BODY[] {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Ok(None)); + let mut s = Script::new("* 1 FETCH (UID 3 BODY[HEADER] {2}\r\nok)\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Ok(None)); + // Gone, never there, refused. + let mut s = Script::new("A0001 OK nothing\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Ok(None)); + let mut s = Script::new(""); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(0), Ok(None)); + assert_eq!(s.sent(), ""); + let mut s = Script::new("A0001 NO [SERVERBUG] can't read it\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_header(3), Err(ProtoError::Rejected("[SERVERBUG] can't read it".into()))); + // A header as large as no header is: refused unread, like a message. + let mut s = Script::new(format!("* 1 FETCH (UID 3 BODY[HEADER] {{{}}}\r\nxxxx", MAX_LITERAL + 1)); + assert!(matches!(Imap::resume(&mut s).uid_fetch_header(3), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn the_stream_can_be_reached_between_commands() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.select("INBOX", true).unwrap(); + // Looked at, not read from: the session goes on where it was. + assert_eq!(imap.get_mut().sent(), "A0001 EXAMINE \"INBOX\"\r\n"); + imap.select("Sent", true).unwrap(); + assert!(s.finished()); +} + +#[test] +fn oversized_literals_are_refused_unread() { + for size in [(MAX_LITERAL + 1).to_string(), "99999999999999999999999999".to_string(), u64::MAX.to_string()] { + let mut s = Script::new(format!("* 1 FETCH (UID 3 BODY[] {{{size}}}\r\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")); + let err = Imap::resume(&mut s).uid_fetch_message(3).unwrap_err(); + assert!(matches!(&err, ProtoError::Protocol(text) if text.to_string().contains("64 MB")), "{err:?}"); + // The x's were not read as if they were the message. + assert!(!s.finished()); + } + // Several literals that are only too much together. + let mut s = Script::new(format!("* 1 FETCH (A {{2}}\r\nab B {{{}}}\r\n", MAX_LITERAL - 1)); + assert!(matches!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn responses_without_end_are_refused() { + // More literals than any response has. + let mut s = Script::whole(format!("* 1 FETCH ({}", "X {0}\r\n ".repeat(MAX_LITERALS + 2))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response has too many parts")))); + // More text than any response has. + let line = format!("{} {{0}}\r\n", "x".repeat(MAX_LINE - 100)); + let mut s = Script::whole(format!("* 1 FETCH ({}", line.repeat(6))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response is too long")))); + // A line that never ends. + let mut s = Script::whole(format!("* 1 FETCH ({}", "x".repeat(MAX_LINE * 2))); + assert!(matches!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(_)))); + // Lists inside lists inside lists. + let mut s = Script::new(format!("* 1 FETCH {}\r\nA0001 OK done\r\n", "(".repeat(200))); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Protocol(said!("the server's response is nested too deeply")))); +} + +#[test] +fn storing_flags() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\nA0003 NO [READ-ONLY] mailbox is read-only\r\n"); + let mut imap = Imap::resume(&mut s); + imap.uid_store(7, true, &["\\Seen", "\\Flagged"]).unwrap(); + imap.uid_store(7, false, &["$Forwarded"]).unwrap(); + assert_eq!(imap.uid_store(8, true, &["\\Deleted"]), Err(ProtoError::Rejected("[READ-ONLY] mailbox is read-only".into()))); + assert_eq!( + s.sent(), + "A0001 UID STORE 7 +FLAGS.SILENT (\\Seen \\Flagged)\r\nA0002 UID STORE 7 -FLAGS.SILENT ($Forwarded)\r\nA0003 UID STORE 8 +FLAGS.SILENT (\\Deleted)\r\n" + ); + + // Nothing to store, or nothing to store it on: the server isn't asked. + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.uid_store(7, true, &[]), Ok(())); + assert!(matches!(imap.uid_store(0, true, &["\\Seen"]), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); + + for bad in ["", "\\", "two words", "\\Seen) (\\Deleted", "\\\\Seen", "a\r\nb", "sée"] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.uid_store(7, true, &[bad]), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.append("Sent", &["\\Seen", bad], b"x"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn flags_are_stored_for_many_messages_at_once() { + let mut s = Script::new("A0001 OK done\r\nA0002 OK done\r\nA0003 NO [READ-ONLY] mailbox is read-only\r\n"); + let mut imap = Imap::resume(&mut s); + imap.uid_store_set("4,7:9,12", true, &["\\Seen"]).unwrap(); + imap.uid_store_set("5", false, &["\\Flagged", "\\Answered"]).unwrap(); + assert_eq!(imap.uid_store_set("6", true, &["\\Deleted"]), Err(ProtoError::Rejected("[READ-ONLY] mailbox is read-only".into()))); + assert_eq!( + s.sent(), + "A0001 UID STORE 4,7:9,12 +FLAGS.SILENT (\\Seen)\r\nA0002 UID STORE 5 -FLAGS.SILENT (\\Flagged \\Answered)\r\nA0003 UID STORE 6 +FLAGS.SILENT (\\Deleted)\r\n" + ); +} + +#[test] +fn a_set_for_a_change_names_its_messages() { + // Nothing that reaches for messages nobody looked at, and nothing that isn't a set at all. + let long = format!("1:{}", MAX_SET_UIDS + 1); + for bad in ["1:*", "*", "", "0", "5:3", "1,,2", "1:2:3", "4 5", "+4", "4,", "4\r\nA0002 EXPUNGE", "4294967296", long.as_str()] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["UIDPLUS".into(), "MOVE".into()]); + assert!(matches!(imap.uid_store_set(bad, true, &["\\Deleted"]), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_move(bad, "Archive"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_copy(bad, "Archive"), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert!(matches!(imap.uid_expunge(bad), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } + // Reading may ask for everything. + let mut s = Script::new("A0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_fetch_flags("1:*").unwrap(), []); +} + +#[test] +fn moving_and_copying_say_where_the_messages_went() { + // A copy answers in its last line, a move before the messages leave (RFC 6851). + let mut server = String::new(); + server += "A0001 OK [COPYUID 38505 304,319:320 3956:3958] Done\r\n"; + server += "* OK [COPYUID 432432 42:43 1202:1203] moved\r\n* 2 EXPUNGE\r\n* 1 EXPUNGE\r\nA0002 OK Done\r\n"; + // Nothing matched, or a server without UIDPLUS: done, and nothing known. + server += "A0003 OK No messages\r\nA0004 OK done\r\n"; + server += "A0005 NO [TRYCREATE] no such mailbox\r\n"; + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + assert_eq!( + imap.uid_copy("304,319:320", "Archive").unwrap(), + Some(Copied { uid_validity: 38_505, uids: vec![(304, 3956), (319, 3957), (320, 3958)] }) + ); + assert_eq!(imap.uid_move("42:43", "Entw&APw-rfe").unwrap(), Some(Copied { uid_validity: 432_432, uids: vec![(42, 1202), (43, 1203)] })); + assert_eq!(imap.uid_move("99", "Archive"), Ok(None)); + assert_eq!(imap.uid_copy("7", "Sent \"old\" mail"), Ok(None)); + assert_eq!(imap.uid_copy("7", "Nowhere"), Err(ProtoError::Rejected("[TRYCREATE] no such mailbox".into()))); + assert_eq!( + s.sent(), + "A0001 UID COPY 304,319:320 \"Archive\"\r\nA0002 UID MOVE 42:43 \"Entw&APw-rfe\"\r\nA0003 UID MOVE 99 \"Archive\"\r\n\ + A0004 UID COPY 7 \"Sent \\\"old\\\" mail\"\r\nA0005 UID COPY 7 \"Nowhere\"\r\n" + ); +} + +#[test] +fn a_doubtful_copyuid_is_no_answer() { + // A wrong pairing would tie a message here to another one there: anything short of certain + // counts as not said. + for doubtful in [ + "[COPYUID 7 4 9,10]", + "[COPYUID 7 4,5 9]", + "[COPYUID 7 5,4 9,10]", + "[COPYUID 7 4:5 10:9]", + "[COPYUID 7 5:4 9:10]", + "[COPYUID 7 4,4 9,10]", + "[COPYUID 7 4,5 9,9]", + "[COPYUID 0 4 9]", + "[COPYUID 7 0 9]", + "[COPYUID 7 4 0]", + "[COPYUID 7 4 *]", + "[COPYUID 7 1:* 1:*]", + "[COPYUID 7 4 9 12]", + "[COPYUID 7 4]", + "[COPYUID 7]", + "[COPYUID]", + "[COPYUID x 4 9]", + "[COPYUID 7 +4 9]", + "[COPYUID -7 4 9]", + "[COPYUID 99999999999 4 9]", + "[COPYUID 7 4 99999999999]", + "[COPYUID 7 1:4000000000 1:4000000000]", + "[COPYUID 7 4, 9]", + "COPYUID 7 4 9", + ] { + let mut s = Script::new(format!("A0001 OK {doubtful} done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_copy("4:5", "Archive"), Ok(None), "{doubtful}"); + } + // Said twice is said in two ways, even when one can be read; and what was said during + // another command says nothing about this one. + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\nA0001 OK [COPYUID 7 4 10] done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Ok(None)); + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\n* OK [COPYUID 7 nonsense] moved\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Ok(None)); + let mut s = Script::new("* OK [COPYUID 7 4 9] out of the blue\r\nA0001 OK done\r\nA0002 OK done\r\nA0003 OK [COPYUID 7 4 11] done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.select("INBOX", false).unwrap(); + assert_eq!(imap.uid_copy("4", "Archive"), Ok(None)); + assert_eq!(imap.uid_copy("4", "Archive"), Ok(Some(Copied { uid_validity: 7, uids: vec![(4, 11)] }))); + // A refused move knows nothing either. + let mut s = Script::new("* OK [COPYUID 7 4 9] moved\r\nA0001 NO [OVERQUOTA] full\r\n"); + assert_eq!(Imap::resume(&mut s).uid_move("4", "Archive"), Err(ProtoError::Rejected("[OVERQUOTA] full".into()))); + // As many as one set names are taken; more is more than was asked about. + let all = format!("1:{MAX_SET_UIDS}"); + let mut s = Script::new(format!("A0001 OK [COPYUID 7 {all} {all}] done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_copy(&all, "Archive").unwrap().map(|c| c.uids.len()), Some(MAX_SET_UIDS)); +} + +#[test] +fn single_messages_are_removed_only_by_a_server_that_can() { + // A server that didn't say UIDPLUS only knows the EXPUNGE that takes every marked message: + // it is never asked. + for capabilities in [None, Some(vec!["IMAP4REV1".to_string(), "MOVE".to_string()])] { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = capabilities; + assert!(matches!(imap.uid_expunge("4"), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); + } + let mut s = Script::new( + "* CAPABILITY IMAP4rev1 UIDPLUS\r\nA0001 OK done\r\n* 3 EXPUNGE\r\n* 3 EXPUNGE\r\nA0002 OK gone\r\nA0003 NO [NOPERM] not yours\r\n", + ); + let mut imap = Imap::resume(&mut s); + imap.capabilities().unwrap(); + imap.uid_expunge("4,7:8").unwrap(); + assert_eq!(imap.uid_expunge("9"), Err(ProtoError::Rejected("[NOPERM] not yours".into()))); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 UID EXPUNGE 4,7:8\r\nA0003 UID EXPUNGE 9\r\n"); +} + +#[test] +fn mailboxes_are_made_and_subscribed_to() { + let mut s = Script::new("A0001 OK made\r\nA0002 OK done\r\nA0003 NO [ALREADYEXISTS] there is one\r\n+ go on\r\nA0004 OK made\r\n"); + let mut imap = Imap::resume(&mut s); + let name = format!("Projects/{}", encode_utf7("Entwürfe & Pläne")); + imap.create(&name).unwrap(); + imap.subscribe(&name).unwrap(); + assert_eq!(imap.create("INBOX"), Err(ProtoError::Rejected("[ALREADYEXISTS] there is one".into()))); + // A name that isn't in the mailbox encoding still can't break the command. + imap.create("Pläne\r\nA0005 LOGOUT").unwrap(); + assert!(matches!(imap.create("nul\0here"), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.subscribe("nul\0here"), Err(ProtoError::Protocol(_)))); + assert_eq!( + s.sent(), + "A0001 CREATE \"Projects/Entw&APw-rfe &- Pl&AOQ-ne\"\r\nA0002 SUBSCRIBE \"Projects/Entw&APw-rfe &- Pl&AOQ-ne\"\r\nA0003 CREATE \"INBOX\"\r\n\ + A0004 CREATE {20}\r\nPläne\r\nA0005 LOGOUT\r\n" + ); +} + +#[test] +fn uids_are_written_as_short_exact_sets() { + let texts = |uids: &[u32]| uid_sets(uids).into_iter().map(|(text, _)| text).collect::>(); + assert_eq!(texts(&[]), Vec::::new()); + assert_eq!(texts(&[0]), Vec::::new()); + assert_eq!(texts(&[7]), ["7"]); + assert_eq!(texts(&[9, 4, 8, 7, 12, 4, 0]), ["4,7:9,12"]); + assert_eq!(texts(&[u32::MAX, u32::MAX - 1, 1]), ["1,4294967294:4294967295"]); + assert_eq!(uid_sets(&[9, 4, 8]), [("4,8:9".to_string(), vec![4, 8, 9])]); + // A long run is cut where a set is full, not stretched over it. + let run: Vec = (10..10 + 2 * MAX_SET_UIDS as u32 + 3).collect(); + assert_eq!(texts(&run), ["10:509", "510:1009", "1010:1012"]); + // Scattered numbers fill a set by its length first. + let scattered: Vec = (0..400).map(|n| 4_000_000_000 + 2 * n).collect(); + let sets = uid_sets(&scattered); + assert!(sets.len() > 1 && sets.iter().all(|(text, _)| text.len() <= MAX_SET_TEXT)); + assert_eq!(sets.iter().map(|(_, uids)| uids.len()).sum::(), 400); +} + +#[test] +fn appending_waits_for_the_go_ahead() { + let message = b"Subject: Sent\r\n\r\nKept.\r\n"; + let mut s = Script::new("+ Ready for literal data\r\nA0001 OK [APPENDUID 38505 3955] done\r\n+ go\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.append("Sent Items", &["\\Seen"], message).unwrap(); + imap.append("Entw&APw-rfe", &[], b"").unwrap(); + assert_eq!(s.sent(), "A0001 APPEND \"Sent Items\" (\\Seen) {24}\r\nSubject: Sent\r\n\r\nKept.\r\n\r\nA0002 APPEND \"Entw&APw-rfe\" {0}\r\n\r\n"); + + // Refused before the message was sent: it stays here. + let mut s = Script::new("A0001 NO [TRYCREATE] no such mailbox\r\n"); + assert_eq!(Imap::resume(&mut s).append("Nowhere", &[], message), Err(ProtoError::Rejected("[TRYCREATE] no such mailbox".into()))); + assert_eq!(s.sent(), "A0001 APPEND \"Nowhere\" {24}\r\n"); + + // Refused after. + let mut s = Script::new("+ go\r\nA0001 NO [OVERQUOTA] mailbox full\r\n"); + assert_eq!(Imap::resume(&mut s).append("Sent", &[], message), Err(ProtoError::Rejected("[OVERQUOTA] mailbox full".into()))); + + // "Done" before the message was sent can't be true. + let mut s = Script::new("A0001 OK done already\r\n"); + assert!(matches!(Imap::resume(&mut s).append("Sent", &[], message), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn appending_with_a_date_says_where_the_message_went() { + let message = b"Subject: Moved\r\n\r\nKept.\r\n"; + let date = "01-Jul-2003 09:52:37 +0000"; + let mut s = Script::new("+ go\r\nA0001 OK [APPENDUID 38505 3955] done\r\n+ go\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert_eq!(imap.append_at("INBOX", &["\\Seen"], Some(date), message), Ok(Some(Appended { uid_validity: 38505, uid: 3955 }))); + // A server that doesn't say: nothing is known of where it went. + assert_eq!(imap.append_at("INBOX", &[], Some(" 1-Jul-2003 09:52:37 -0700"), message), Ok(None)); + assert_eq!( + s.sent(), + "A0001 APPEND \"INBOX\" (\\Seen) \"01-Jul-2003 09:52:37 +0000\" {25}\r\nSubject: Moved\r\n\r\nKept.\r\n\r\n\ + A0002 APPEND \"INBOX\" \" 1-Jul-2003 09:52:37 -0700\" {25}\r\nSubject: Moved\r\n\r\nKept.\r\n\r\n" + ); + // An answer that doesn't pair one message with one UID beyond doubt is no answer. + for code in ["[APPENDUID 0 5]", "[APPENDUID 38505 0]", "[APPENDUID 38505 1:3]", "[APPENDUID 38505]", "[APPENDUID 38505 7 8]", "[APPENDUID x 7]"] { + let mut s = Script::new(format!("+ go\r\nA0001 OK {code} done\r\n")); + assert_eq!(Imap::resume(&mut s).append_at("INBOX", &[], None, message), Ok(None), "{code}"); + } + // Two answers to one message might disagree: neither is taken. + let mut s = Script::new("+ go\r\n* OK [APPENDUID 1 2] one\r\nA0001 OK [APPENDUID 1 3] two\r\n"); + assert_eq!(Imap::resume(&mut s).append_at("INBOX", &[], None, message), Ok(None)); + // A date that isn't one is never sent, nor is what it carries. + for bad in + ["1-Jul-2003 09:52:37 +0000", "01-Jul-2003 09:52:37", "01-Jul-2003 09:52:37 +0000\r\nA2 DELETE INBOX", "01-Jul-2003 09:52:37 +00\"0", ""] + { + let mut s = Script::new("+ go\r\nA0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).append_at("INBOX", &[], Some(bad), message), Err(ProtoError::Protocol(_))), "{bad:?}"); + assert_eq!(s.sent(), "", "{bad:?}"); + } +} + +#[test] +fn searching_a_header_answers_the_uids_it_names() { + let mut s = Script::new("* SEARCH 9 4 0 x 4 4294967295\r\n* 3 EXISTS\r\nA0001 OK done\r\nA0002 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + // In UID order and once each; what isn't a UID is passed over. + assert_eq!(imap.uid_search_header("Message-ID", ""), Ok(vec![4, 9, u32::MAX])); + // Quotes in the text are quoted. + assert_eq!(imap.uid_search_header("Message-ID", ""), Ok(vec![])); + assert_eq!( + s.sent(), + "A0001 UID SEARCH UNDELETED HEADER Message-ID \"\"\r\n\ + A0002 UID SEARCH UNDELETED HEADER Message-ID \"\"\r\n" + ); + // A refusal is said. + let mut s = Script::new("A0001 NO no searching here\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_header("Message-ID", ""), Err(ProtoError::Rejected(_)))); + // What could end the command early, or isn't text, is never sent. + for (field, text) in [ + ("Message-ID", "\r\nA2 DELETE INBOX"), + ("Message-ID", "<ä@example.org>"), + ("Message-ID", ""), + ("Message ID", ""), + ("", ""), + ] { + let mut s = Script::new("A0001 OK done\r\n"); + assert!(matches!(Imap::resume(&mut s).uid_search_header(field, text), Err(ProtoError::Protocol(_))), "{field:?} {text:?}"); + assert_eq!(s.sent(), "", "{field:?} {text:?}"); + } + // A server that names more messages than are ever looked for is taken at its first word. + let many: String = (1..=5000).map(|n| format!(" {n}")).collect(); + let mut s = Script::new(format!("* SEARCH{many}\r\nA0001 OK done\r\n")); + assert_eq!(Imap::resume(&mut s).uid_search_header("Message-ID", "").map(|uids| uids.len()), Ok(MAX_FOUND)); +} + +#[test] +fn starttls_hands_the_stream_back() { + let mut s = Script::new("* OK ready\r\n* CAPABILITY IMAP4rev1 STARTTLS\r\nA0001 OK done\r\nA0002 OK begin TLS now\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + assert!(imap.capabilities().unwrap().contains(&"STARTTLS".to_string())); + let stream = imap.starttls().unwrap(); + assert_eq!(stream.sent(), "A0001 CAPABILITY\r\nA0002 STARTTLS\r\n"); + // The session starts afresh inside TLS. + let mut s = Script::new("A0001 OK done\r\n"); + Imap::resume(&mut s).capabilities().unwrap(); + + let mut s = Script::new("A0001 BAD no TLS here\r\n"); + assert_eq!(Imap::resume(&mut s).starttls().unwrap_err(), ProtoError::Rejected("no TLS here".into())); +} + +#[test] +fn text_slipped_in_before_tls_is_refused() { + // Both lines arrive in one read, as an attacker in the middle would send them. + let mut s = Script::whole("A0001 OK begin TLS now\r\nA0002 OK [CAPABILITY IMAP4rev1] injected\r\n"); + assert!(matches!(Imap::resume(&mut s).starttls(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn logging_out() { + let mut s = Script::new("* BYE logging out\r\nA0001 OK done\r\n"); + assert_eq!(Imap::resume(&mut s).logout(), Ok(())); + assert_eq!(s.sent(), "A0001 LOGOUT\r\n"); + // A server that hangs up without the last word has logged us out too. + for server in ["* BYE\r\n", ""] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).logout(), Ok(()), "{server:?}"); + } + let mut s = Script::new("A0001 BAD what\r\n"); + assert!(matches!(Imap::resume(&mut s).logout(), Err(ProtoError::Rejected(_)))); +} + +#[test] +fn a_server_that_says_bye_has_ended_the_session() { + let mut s = Script::new("* 3 EXISTS\r\n* BYE [UNAVAILABLE] shutting down\r\n"); + assert_eq!( + Imap::resume(&mut s).select("INBOX", true), + Err(ProtoError::Io(said!("the server ended the session: {reason}", reason = Arg::said("[UNAVAILABLE] shutting down".into())))) + ); +} + +#[test] +fn tags_count_up_and_must_match() { + let mut s = Script::new("* OK ready\r\nA0001 OK one\r\nA0002 OK two\r\nA0003 OK three\r\nA0009 OK not ours\r\n"); + let mut imap = Imap::connect(&mut s).unwrap(); + imap.capabilities().unwrap(); + imap.list().unwrap(); + imap.select("INBOX", true).unwrap(); + assert_eq!(imap.uid_fetch_flags("1:*"), Err(ProtoError::Protocol(said!("the server answered a command that wasn't sent")))); + assert_eq!(s.sent(), "A0001 CAPABILITY\r\nA0002 LIST \"\" \"*\"\r\nA0003 EXAMINE \"INBOX\"\r\nA0004 UID FETCH 1:* (UID FLAGS)\r\n"); +} + +#[test] +fn junk_in_a_session_is_a_protocol_error() { + for junk in ["+ send more\r\n", "garbage\r\n", "A0001 FETCH x\r\n", "A0001 BYE\r\n", "A0001 PREAUTH hi\r\n", "\r\n", "A0001\r\n", " OK\r\n"] { + let mut s = Script::new(junk); + assert!(matches!(Imap::resume(&mut s).capabilities(), Err(ProtoError::Protocol(_))), "{junk:?}"); + } + // Refusals keep the server's words; one without words still says something. + let mut s = Script::new("A0001 NO\r\n"); + assert_eq!(Imap::resume(&mut s).capabilities(), Err(ProtoError::Rejected(said!("the command was refused")))); +} + +#[test] +fn a_dead_connection_is_an_io_error() { + // In the middle of a line, and in the middle of a literal. + for server in ["* 1 FETCH (UID 3 BO", "* 1 FETCH (UID 3 BODY[] {50}\r\nonly this much", "* 1 FETCH (UID 3 BODY[] {5}\r\nabcde"] { + let mut s = Script::new(server); + assert_eq!(Imap::resume(&mut s).uid_fetch_message(3), Err(ProtoError::Io(said!("the server closed the connection"))), "{server:?}"); + } + assert!(matches!(Imap::connect(Broken(ErrorKind::TimedOut)), Err(ProtoError::Io(_)))); + assert!(matches!(Imap::resume(Broken(ErrorKind::ConnectionReset)).list(), Err(ProtoError::Io(_)))); +} + +#[test] +fn text_that_cannot_be_sent_is_refused() { + let mut s = Script::new("A0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + assert!(matches!(imap.select("nul\0here", true), Err(ProtoError::Protocol(_)))); + assert!(matches!(imap.append("nul\0here", &[], b"x"), Err(ProtoError::Protocol(_)))); + assert_eq!(s.sent(), ""); +} + +/// Everything a client does, against whatever the "server" says. +fn drive(server: &[u8]) { + let mut s = Script::new(server); + if let Ok(mut imap) = Imap::connect(&mut s) { + let _ = imap.capabilities(); + let _ = imap.login("ada", "hunter2"); + let _ = imap.login("ädä", "pässword"); + let _ = imap.list(); + let _ = imap.select("INBOX", true); + let _ = imap.uid_fetch_flags("1:*"); + let _ = imap.uid_fetch_sizes("1:*"); + let _ = imap.uid_fetch_message(1); + let _ = imap.uid_fetch_header(1); + let _ = imap.uid_store(1, true, &["\\Seen"]); + let _ = imap.uid_store_set("1:3,7", false, &["\\Flagged"]); + let _ = imap.uid_move("1:3", "Archive"); + let _ = imap.uid_copy("7", "Entw&APw-rfe"); + let _ = imap.uid_expunge("7"); + let _ = imap.create("Projects/New"); + let _ = imap.subscribe("Projects/New"); + let _ = imap.append("Sent", &["\\Seen"], b"Subject: x\r\n\r\n"); + let _ = imap.uid_search_header("Message-ID", ""); + let _ = imap.uid_fetch_flags_gmail("1:*"); + let _ = imap.uid_search_gmail("1:500", "category:social"); + let _ = imap.logout(); + } + // Changes, by a session that was told it may make them. + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["MOVE".into(), "UIDPLUS".into()]); + let _ = imap.select("INBOX", false); + let _ = imap.uid_move("1,3:5", "Archive"); + let _ = imap.uid_copy("1", "Archive"); + let _ = imap.uid_expunge("1,3:5"); + let _ = imap.uid_store_set("2", true, &["\\Deleted"]); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + let _ = imap.uid_fetch_message(1); + let _ = imap.uid_fetch_header(1); + let _ = imap.list(); + let _ = imap.uid_fetch_flags("1:*"); + let _ = imap.starttls(); + // With a token: after a go-ahead, and with the command. + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + let _ = imap.authenticate_xoauth2("ada@example.org", "tok.en-123"); + let _ = imap.list(); + let mut s = Script::new(server); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["SASL-IR".into(), "AUTH=XOAUTH2".into()]); + let _ = imap.authenticate_xoauth2("ada@example.org", "tok.en-123"); + let _ = imap.select("INBOX", true); +} + +const WORDS: [&str; 43] = [ + "SEARCH ", + "4294967295 ", + "BODY[HEADER] ", + "[COPYUID 7 1 9] ", + "[COPYUID 7 1,3:5 9:12] ", + "[COPYUID ", + "1:4 ", + "9,10 ", + "EXPUNGE", + "* ", + "A0001 ", + "A0002 ", + "A0003 ", + "OK ", + "NO ", + "BAD ", + "BYE ", + "PREAUTH ", + "+ ", + "1 ", + "FETCH ", + "LIST ", + "EXISTS", + "CAPABILITY ", + "(", + ")", + "UID 1 ", + "FLAGS ", + "BODY[] ", + "INTERNALDATE ", + "RFC822.SIZE 9 ", + "{3}\r\n", + "{0}\r\n", + "{99999999999}\r\n", + "abc", + "\"", + "\\", + "NIL ", + "\r\n", + "[UIDNEXT 5] ", + "[", + "]", + "é", +]; + +proptest! { + #[test] + fn arbitrary_server_bytes_never_panic_or_hang(server in proptest::collection::vec(any::(), 0..600)) { + drive(&server); + // And after a proper greeting, so the session gets going. + let mut greeted = b"* OK ready\r\n".to_vec(); + greeted.extend_from_slice(&server); + drive(&greeted); + } + + #[test] + fn response_shaped_noise_never_panics(words in proptest::collection::vec(proptest::sample::select(&WORDS[..]), 0..80), greeted in any::()) { + let server = format!("{}{}", if greeted { "* OK ready\r\n" } else { "" }, words.concat()); + drive(server.as_bytes()); + } + + #[test] + fn any_body_arrives_as_it_was_sent(body in proptest::collection::vec(any::(), 0..2000), flags_first in any::()) { + let mut server = if flags_first { + with_literal("* 1 FETCH (UID 9 FLAGS (\\Seen) BODY[] ", &body, ")\r\n") + } else { + with_literal("* 1 FETCH (BODY[] ", &body, " FLAGS (\\Seen) UID 9)\r\n") + }; + server.extend_from_slice(b"A0001 OK done\r\n"); + let mut s = Script::new(server); + let got = Imap::resume(&mut s).uid_fetch_message(9).unwrap().unwrap(); + prop_assert_eq!(got.body, Some(body)); + prop_assert_eq!(got.flags, vec!["\\Seen".to_string()]); + } + + #[test] + fn any_uids_are_named_once_each_by_sets_that_read_back(uids in proptest::collection::vec(prop_oneof![1u32..40, 1u32..3000, any::()], 0..1500)) { + let mut expected: Vec = uids.iter().copied().filter(|uid| *uid != 0).collect(); + expected.sort_unstable(); + expected.dedup(); + let mut named_in_all = Vec::new(); + for (text, named_here) in uid_sets(&uids) { + // A set says what it is said to say, and is one a changing command takes. + prop_assert_eq!(uids_of(&text), Some(named_here.clone()), "{}", text); + prop_assert!(named(&text).is_ok() && is_set(&text), "{}", text); + prop_assert!(text.len() <= MAX_SET_TEXT && !named_here.is_empty() && named_here.len() <= MAX_SET_UIDS); + named_in_all.extend(named_here); + } + prop_assert_eq!(named_in_all, expected); + } + + #[test] + fn any_copyuid_text_is_read_or_not(text in "[0-9,:*+ -]{0,40}") { + if let Some(copied) = copied_from(&text) { + prop_assert!(copied.uid_validity != 0 && copied.uids.len() <= MAX_SET_UIDS); + prop_assert!(copied.uids.iter().all(|(from, to)| *from != 0 && *to != 0)); + prop_assert!(copied.uids.iter().zip(copied.uids.iter().skip(1)).all(|(a, b)| a.0 < b.0 && a.1 != b.1)); + } + } + + #[test] + fn any_mailbox_name_survives_quoting(name in "[ -~]{1,40}") { + // What the client would send as a quoted string, a server sends back in LIST. + let mut s = Script::new("A0001 OK done\r\n"); + Imap::resume(&mut s).select(&name, true).unwrap(); + let sent = s.sent(); + let quoted = sent.strip_prefix("A0001 EXAMINE ").unwrap().strip_suffix("\r\n").unwrap(); + let mut s = Script::new(format!("* LIST () \"/\" {quoted}\r\nA0001 OK done\r\n")); + let list = Imap::resume(&mut s).list().unwrap(); + prop_assert_eq!(list.len(), 1); + prop_assert_eq!(&list[0].raw, &name); + } +} + +#[test] +fn namespace_reads_personal_prefix_and_delimiter() { + let mut s = Script::new("* NAMESPACE ((\"INBOX.\" \".\")) NIL NIL\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into(), "NAMESPACE".into()]); + assert_eq!(imap.namespace().unwrap(), Some(Namespace { prefix: "INBOX.".into(), delimiter: Some('.') })); + assert_eq!(s.sent(), "A0001 NAMESPACE\r\n"); + + let mut s = Script::new("* NAMESPACE ((\"\" \"/\")) NIL NIL\r\nA0001 OK done\r\n"); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into(), "NAMESPACE".into()]); + assert_eq!(imap.namespace().unwrap(), Some(Namespace { prefix: String::new(), delimiter: Some('/') })); + + let mut s = Script::new(""); + let mut imap = Imap::resume(&mut s); + imap.capabilities = Some(vec!["IMAP4REV1".into()]); + assert_eq!(imap.namespace().unwrap(), None); + assert_eq!(s.sent(), ""); +} diff --git a/crates/proto/src/imap/utf7.rs b/crates/proto/src/imap/utf7.rs new file mode 100644 index 0000000000..7c7990e760 --- /dev/null +++ b/crates/proto/src/imap/utf7.rs @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Modified UTF-7, the encoding of mailbox names (RFC 3501 §5.1.3). +//! +//! Printable ASCII stands for itself, except `&`, which is written `&-`. Everything else is +//! UTF-16 in base64 (with `,` in place of `/`, and no padding) between `&` and `-`. + +const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"; + +fn digit(six_bits: u32) -> char { + DIGITS.get((six_bits & 0x3F) as usize).map_or('A', |b| char::from(*b)) +} + +/// A mailbox name as people read it. Text that isn't valid modified UTF-7 is kept as it is. +pub fn decode_utf7(name: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut rest = name; + // Every round takes at least the `&` off `rest`. + while let Some(at) = rest.find('&') { + out.push_str(rest.get(..at).unwrap_or("")); + let after = rest.get(at + 1..).unwrap_or(""); + rest = match after.find('-') { + Some(0) => { + out.push('&'); + after.get(1..).unwrap_or("") + } + Some(end) => match shifted(after.get(..end).unwrap_or("")) { + Some(text) => { + out.push_str(&text); + after.get(end + 1..).unwrap_or("") + } + // Not base64 after all: an ampersand like any other character. + None => { + out.push('&'); + after + } + }, + None => { + out.push('&'); + after + } + }; + } + out.push_str(rest); + out +} + +/// The text of one base64 run, or `None` when it isn't one. +fn shifted(encoded: &str) -> Option { + let mut units = Vec::with_capacity(encoded.len() * 3 / 8 + 1); + let (mut bits, mut count) = (0u32, 0u32); + for b in encoded.bytes() { + let value = DIGITS.iter().position(|d| *d == b)? as u32; + bits = (bits << 6) | value; + count += 6; + if count >= 16 { + count -= 16; + units.push((bits >> count) as u16); + bits &= (1 << count) - 1; + } + } + // What is left over is padding: less than one digit's worth. + if count >= 6 || units.is_empty() { + return None; + } + String::from_utf16(&units).ok() +} + +/// A mailbox name as a server wants it. +pub fn encode_utf7(name: &str) -> String { + let mut out = String::with_capacity(name.len()); + let mut pending: Vec = Vec::new(); + for c in name.chars() { + if matches!(c, ' '..='~') { + flush(&mut pending, &mut out); + out.push(c); + if c == '&' { + out.push('-'); + } + } else { + let mut units = [0u16; 2]; + pending.extend_from_slice(c.encode_utf16(&mut units)); + } + } + flush(&mut pending, &mut out); + out +} + +/// Write the characters waiting to be encoded as one base64 run. +fn flush(pending: &mut Vec, out: &mut String) { + if pending.is_empty() { + return; + } + out.push('&'); + let (mut bits, mut count) = (0u32, 0u32); + for unit in pending.drain(..) { + bits = (bits << 16) | u32::from(unit); + count += 16; + while count >= 6 { + count -= 6; + out.push(digit(bits >> count)); + } + bits &= (1 << count) - 1; + } + if count > 0 { + out.push(digit(bits << (6 - count))); + } + out.push('-'); +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use proptest::prelude::*; + + use super::*; + + #[test] + fn the_examples_of_the_rfc() { + // RFC 3501 §5.1.3. + assert_eq!(decode_utf7("~peter/mail/&U,BTFw-/&ZeVnLIqe-"), "~peter/mail/台北/日本語"); + assert_eq!(encode_utf7("~peter/mail/台北/日本語"), "~peter/mail/&U,BTFw-/&ZeVnLIqe-"); + assert_eq!(decode_utf7("&Jjo-!"), "☺!"); + assert_eq!(encode_utf7("☺!"), "&Jjo-!"); + } + + #[test] + fn ordinary_names() { + assert_eq!(encode_utf7("INBOX"), "INBOX"); + assert_eq!(encode_utf7("Tom & Jerry"), "Tom &- Jerry"); + assert_eq!(decode_utf7("Tom &- Jerry"), "Tom & Jerry"); + assert_eq!(encode_utf7("Entwürfe"), "Entw&APw-rfe"); + assert_eq!(decode_utf7("Entw&APw-rfe"), "Entwürfe"); + assert_eq!(encode_utf7("Gelöschte Elemente"), "Gel&APY-schte Elemente"); + // Outside the basic plane: a surrogate pair. + assert_eq!(decode_utf7(&encode_utf7("📬 Post")), "📬 Post"); + assert_eq!(encode_utf7("📬"), "&2D3c7A-"); + // Control characters are encoded too. + assert_eq!(encode_utf7("a\tb"), "a&AAk-b"); + assert_eq!(encode_utf7(""), ""); + } + + #[test] + fn junk_is_kept_as_it_is() { + for junk in ["&", "a&b", "&&&", "&!!!-", "&A-", "&AAAAA-x", "R&D", "&2D0-", "&-&", "é&é-"] { + let decoded = decode_utf7(junk); + assert!(!decoded.is_empty(), "{junk}"); + } + assert_eq!(decode_utf7("R&D"), "R&D"); + assert_eq!(decode_utf7("&!!!-"), "&!!!-"); + // A lone surrogate is not text. + assert_eq!(decode_utf7("&2D0-"), "&2D0-"); + assert_eq!(decode_utf7("AT&T-Mobile"), "AT&T-Mobile"); + } + + proptest! { + #[test] + fn any_name_round_trips(name in "\\PC{0,40}") { + let encoded = encode_utf7(&name); + prop_assert!(encoded.bytes().all(|b| (0x20..=0x7E).contains(&b)), "{encoded}"); + prop_assert_eq!(decode_utf7(&encoded), name); + } + + #[test] + fn any_text_round_trips_with_control_characters(name in proptest::collection::vec(any::(), 0..40)) { + let name: String = name.into_iter().collect(); + prop_assert_eq!(decode_utf7(&encode_utf7(&name)), name); + } + + #[test] + fn decoding_never_panics(name in "[&A-Za-z0-9+,\\-é ]{0,60}") { + let _ = decode_utf7(&name); + } + } +} diff --git a/crates/proto/src/lib.rs b/crates/proto/src/lib.rs new file mode 100644 index 0000000000..08833beca1 --- /dev/null +++ b/crates/proto/src/lib.rs @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Craft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 + +//! Mail protocols without sockets. +//! +//! [`smtp::Smtp`] and [`imap::Imap`] speak SMTP (RFC 5321, 3207, 4954) and IMAP4rev1 (RFC 3501, +//! 4315, 4959, 6154, 6851) over any `Read + Write` stream: a TLS socket on the desktop, a scripted +//! transcript in the tests. Everything a server sends is treated as hostile: lines, literals and +//! response counts are capped, and nothing here panics on junk. +//! +//! Passwords and access tokens never reach a log or an error text, even when a server echoes +//! them back. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod i18n; +pub mod imap; +mod line; +pub mod smtp; + +#[cfg(test)] +mod script; + +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use i18n::{Arg, Text}; + +pub(crate) use i18n::{for_trace, tidy}; + +/// Longest line a server may send. +pub const MAX_LINE: usize = 64 * 1024; +/// Largest counted block (an IMAP literal, so: the largest message) a server may send. +pub const MAX_LITERAL: usize = 64 * 1024 * 1024; +/// Longest user name and access token, together, that one sign-in may carry. +const MAX_XOAUTH2: usize = 32 * 1024; + +/// What went wrong. Each holds the reason as a [`Text`]: Craft's own words are a template +/// displayed in its language ([`said!`]), and what a server or the system said is kept as +/// it said it ([`Text::verbatim`]). The English ([`Display`](std::fmt::Display)) is what the CLI, MCP +/// and the log read, and it is the same either way. + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProtoError { + Io(Text), + Protocol(Text), + /// The server refused the command (IMAP NO/BAD, SMTP 4xx/5xx); the text is the server's. + Rejected(Text), + Auth(Text), +} + +impl ProtoError { + /// The underlying reason, without its error category prefix. + pub fn reason(&self) -> &Text { + match self { + Self::Io(why) | Self::Protocol(why) | Self::Rejected(why) | Self::Auth(why) => why, + } + } + + /// The error as the user is told it: what kind of trouble, and why. + pub fn said(&self) -> Text { + match self { + ProtoError::Io(why) => said!("connection problem: {reason}", reason = Arg::said(why.clone())), + ProtoError::Protocol(why) => said!("unexpected server response: {reason}", reason = Arg::said(why.clone())), + ProtoError::Rejected(why) => said!("the server said: {reason}", reason = Arg::said(why.clone())), + ProtoError::Auth(why) => said!("sign-in failed: {reason}", reason = Arg::said(why.clone())), + } + } +} + +impl std::fmt::Display for ProtoError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&self.said(), f) + } +} + +impl std::error::Error for ProtoError {} + +/// Secrets: passwords and tokens, never shown in logs or errors. +#[derive(Default)] +pub(crate) struct Secrets(Vec>); + +impl Secrets { + pub(crate) fn add(&mut self, secret: &str) { + if !secret.is_empty() && !self.0.iter().any(|s| s.as_str() == secret) { + self.0.push(zeroize::Zeroizing::new(secret.to_owned())); + // Longer overlapping secrets must be hidden before their prefixes. + self.0.sort_by_key(|s| std::cmp::Reverse(s.len())); + } + } + + pub(crate) fn hide(&self, text: &str) -> String { + self.0.iter().fold(text.to_owned(), |text, secret| text.replace(secret.as_str(), "***")) + } +} + +/// Build a bounded, base64-encoded SASL XOAUTH2 initial response. +pub(crate) fn xoauth2(user: &str, token: &str) -> Result { + if user.is_empty() || token.is_empty() || user.chars().chain(token.chars()).any(char::is_control) { + return Err(ProtoError::Auth(said!("the user name or token has a character that can't be sent"))); + } + if user.len().saturating_add(token.len()) > MAX_XOAUTH2 { + return Err(ProtoError::Auth(said!("the user name or token is too long"))); + } + let plain = zeroize::Zeroizing::new(format!("user={user}\x01auth=Bearer {token}\x01\x01")); + Ok(STANDARD.encode(plain.as_bytes())) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn secrets_redact_overlapping_values() { + let mut secrets = Secrets::default(); + secrets.add("token"); + secrets.add("token-long"); + assert_eq!(secrets.hide("token-long token"), "*** ***"); + } + + #[test] + fn xoauth2_rejects_injection_and_oversized_values() { + assert!(xoauth2("user\x01auth=Bearer injected", "token").is_err()); + assert!(xoauth2("user", &"x".repeat(MAX_XOAUTH2)).is_err()); + } + + #[test] + fn error_display() { + let err = ProtoError::Io(said!("connection problem")); + assert_eq!(err.to_string(), "connection problem: connection problem"); + assert_eq!(err.reason().to_string(), "connection problem"); + } + + #[test] + fn error_said() { + let err = ProtoError::Auth(said!("invalid password")); + assert_eq!(err.said().to_string(), "sign-in failed: invalid password"); + } + + #[test] + fn xoauth2_format() { + let result = xoauth2("user@example.com", "token123").unwrap(); + let result = String::from_utf8(STANDARD.decode(result).unwrap()).unwrap(); + assert!(result.contains("user=user@example.com")); + assert!(result.contains("auth=Bearer token123")); + } +} + +#[cfg(test)] +mod source_regression_tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + #[test] + fn the_wire_trace_keeps_keywords_and_no_address_name_or_text() { + // (Line, what the trace shows.) + for (line, _old_shown) in [ + ("A0001 OK ada@example.org authenticated (Success)\r\n", "A0001 OK … (39 bytes)"), + ("A0002 LOGIN ***", "A0002 LOGIN ***"), + ("MAIL FROM: SIZE=120", "MAIL FROM: … (26 bytes)"), + ("RCPT TO:", "RCPT TO: … (17 bytes)"), + ("550 5.1.1 : Recipient address rejected", "550 5.1.1 … (45 bytes)"), + ("250-mx.example.org at your service", "250- … (30 bytes)"), + ("250-AUTH LOGIN PLAIN XOAUTH2", "250-AUTH LOGIN PLAIN XOAUTH2"), + ("A0003 SELECT \"Letters from Grace\"", "A0003 SELECT … (20 bytes)"), + ("* LIST (\\HasNoChildren) \"/\" Grace", "* LIST … (26 bytes)"), + ("* 12 FETCH (UID 40 FLAGS (\\Seen) BODY[HEADER.FIELDS (SUBJECT)] \"Subject: Quarterly figures\")", "* 12 FETCH … (81 bytes)"), + ("* 3 EXISTS", "* 3 EXISTS"), + ("UID FETCH 1:40,42 (UID FLAGS)", "UID FETCH 1:40,42 … (11 bytes)"), + ("hello there", "(11 bytes)"), + ("", ""), + ] { + let traced = for_trace(line); + assert!(traced.len() <= line.len().saturating_add(32), "{line:?}"); + for private in ["ada", "bob", "Grace", "Quarterly", "mx.example"] { + assert!(!traced.contains(private), "{line:?}: {traced}"); + } + } + assert!(for_trace(&format!("A0001 OK {}", "X ".repeat(500))).len() < 160); + assert_eq!(for_trace("ünïcödé ä"), "(14 bytes)"); + } + + #[test] + fn uppercase_private_text_is_not_protocol_structure() { + assert_eq!(for_trace("550 CUSTOMER ALICE PAYMENT OVERDUE"), "550 … (30 bytes)"); + assert_eq!(for_trace("A0003 SELECT PRIVATE_MAILBOX"), "A0003 SELECT … (15 bytes)"); + assert_eq!(for_trace("250-PRIVATE_CUSTOMER_DOMAIN"), "250- … (23 bytes)"); + assert_eq!(for_trace("A0001 OK PRIVATE CUSTOMER"), "A0001 OK … (16 bytes)"); + } + + #[test] + fn secrets_are_hidden_longest_first() { + let mut s = Secrets::default(); + s.add("hunter2"); + s.add("hunter2-and-more"); + s.add(""); + assert_eq!(s.hide("no hunter2-and-more, no hunter2, nothing"), "no ***, no ***, nothing"); + assert_eq!(Secrets::default().hide("plain"), "plain"); + } + + #[test] + fn the_xoauth2_response_is_user_and_bearer_token_between_control_a() { + let decoded = |payload: String| STANDARD.decode(payload).unwrap(); + assert_eq!(decoded(xoauth2("ada@example.org", "tok.en-123").unwrap()), b"user=ada@example.org\x01auth=Bearer tok.en-123\x01\x01"); + // The example of the mechanism's description. + assert_eq!( + xoauth2("someuser@example.com", "ya29.vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg").unwrap(), + "dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5LnZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ==" + ); + assert_eq!(decoded(xoauth2("ädä", "t").unwrap()), "user=ädä\x01auth=Bearer t\x01\x01".as_bytes()); + // Nothing that could end the name, the token or the line early. + for (user, token) in [("ada\x01auth=Bearer other", "t"), ("ada", "t\x01"), ("ada\r\n", "t"), ("ada", "t\nQUIT"), ("a\0", "t"), ("ada", "\0")] + { + assert!(matches!(xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert!(matches!(xoauth2("ada", ""), Err(ProtoError::Auth(_)))); + assert!(xoauth2("ada", &"t".repeat(MAX_XOAUTH2 - 3)).is_ok()); + let err = xoauth2("ada", &"t".repeat(MAX_XOAUTH2)).unwrap_err(); + assert!(matches!(&err, ProtoError::Auth(why) if why.to_string().len() < 100), "{err:?}"); + } + + #[test] + fn server_text_is_tidied() { + assert_eq!(tidy(" 5.7.8\tBad\r\n credentials \u{7}"), "5.7.8 Bad credentials"); + let long = tidy(&"é".repeat(1000)); + assert_eq!(long.chars().count(), 301); + assert!(long.ends_with('…')); + assert_eq!(tidy(""), ""); + } +} diff --git a/crates/proto/src/line.rs b/crates/proto/src/line.rs new file mode 100644 index 0000000000..90d0937f1c --- /dev/null +++ b/crates/proto/src/line.rs @@ -0,0 +1,318 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The bounded reader both protocols share: lines and counted blocks from a stream that may be hostile. + +use std::io::{ErrorKind, Read, Write}; + +use crate::said; +use crate::{MAX_LINE, MAX_LITERAL, ProtoError}; + +/// How much is asked of the stream in one read. +const CHUNK: usize = 16 * 1024; +/// Most bytes of one over-long untagged line read past ([`Wire::read_line_or_skip`]). +const MAX_SKIPPED: usize = 4 * 1024 * 1024; +/// Reads interrupted in a row before giving up. +const MAX_INTERRUPTS: u32 = 1_000; + +/// A stream with the bytes read ahead of what was asked for. +pub(crate) struct Wire { + stream: S, + /// Bytes read from the stream and not handed out yet (from `start`). + buf: Vec, + start: usize, + // Bytes already searched for a newline in the current pending polling line. + poll_scanned: usize, +} + +fn closed() -> ProtoError { + ProtoError::Io(said!("the server closed the connection")) +} + +fn io_error(e: &std::io::Error) -> ProtoError { + match e.kind() { + ErrorKind::TimedOut | ErrorKind::WouldBlock => ProtoError::Io(said!("the server took too long to answer")), + ErrorKind::UnexpectedEof | ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::BrokenPipe => closed(), + // The system's own words, as it said them. + _ => ProtoError::Io(crate::tidy(&e.to_string()).into()), + } +} + +impl Wire { + pub(crate) fn new(stream: S) -> Self { + Wire { stream, buf: Vec::new(), start: 0, poll_scanned: 0 } + } + + /// Whether the server sent more than has been read so far. + pub(crate) fn has_pending(&self) -> bool { + self.start < self.buf.len() + } + + pub(crate) fn into_inner(self) -> S { + self.stream + } + + /// The stream itself, for its owner to set up (what a socket waits for, say). Reading from + /// it or writing to it here would take the session apart. + pub(crate) fn get_mut(&mut self) -> &mut S { + &mut self.stream + } +} + +impl Wire { + /// Read some more into the buffer; the end of the stream is an error. + fn fill(&mut self) -> Result<(), ProtoError> { + self.poll_scanned = 0; + if self.start > 0 { + self.buf.drain(..self.start.min(self.buf.len())); + self.start = 0; + } + let mut tmp = vec![0u8; CHUNK]; + let n = read_some(&mut self.stream, &mut tmp)?; + self.buf.extend_from_slice(tmp.get(..n).unwrap_or(&[])); + Ok(()) + } + + /// The next line without its line ending (CRLF, or a bare LF). + pub(crate) fn read_line(&mut self) -> Result, ProtoError> { + self.next_line(false)?.ok_or_else(too_long) + } + + /// The next line, or `None` for an untagged one (`* …`) longer than [`MAX_LINE`], which is + /// read past to its end (at most [`MAX_SKIPPED`] bytes of it) so that the session goes on. + /// Any other line that long is an error, as for [`Wire::read_line`]. + pub(crate) fn read_line_or_skip(&mut self) -> Result>, ProtoError> { + self.next_line(true) + } + + fn next_line(&mut self, skip: bool) -> Result>, ProtoError> { + self.poll_scanned = 0; + // How much of the pending bytes has been searched for a line feed already. + let mut scanned = 0usize; + // Bytes of an over-long line dropped so far, when one is being read past. + let mut skipped: Option = None; + loop { + let pending = self.buf.get(self.start..).unwrap_or(&[]); + if let Some(i) = pending.get(scanned..).and_then(|rest| rest.iter().position(|b| *b == b'\n')) { + let end = scanned.saturating_add(i); + let line = pending.get(..end).unwrap_or(&[]); + let line = line.strip_suffix(b"\r").unwrap_or(line); + let line = if skipped.is_some() { + None + } else if line.len() > MAX_LINE { + if !(skip && line.starts_with(b"* ")) { + return Err(too_long()); + } + None + } else { + Some(line.to_vec()) + }; + self.start = self.start.saturating_add(end).saturating_add(1); + return Ok(line); + } + scanned = pending.len(); + // The limit is on the line itself; a CR may still come on top. + if scanned > MAX_LINE + 1 { + let dropped = match skipped { + Some(n) => n, + None if skip && pending.starts_with(b"* ") => 0, + None => return Err(too_long()), + }; + let dropped = dropped.saturating_add(scanned); + if dropped > MAX_SKIPPED { + return Err(too_long()); + } + skipped = Some(dropped); + self.start = self.buf.len(); + scanned = 0; + } + // Each round reads at least one byte, so this ends at the line feed, the cap or the end of the stream. + self.fill()?; + } + } + + /// The next line after at most one underlying read; `None` for a partial line or when + /// the stream times out (IDLE waits like this, a second at a time, so that its owner can + /// look at the clock and at whether it was told to stop). Bytes of a line that came so far are + /// kept for the next call. A line over [`MAX_LINE`] is an error, as for [`Wire::read_line`]. + pub(crate) fn poll_line(&mut self) -> Result>, ProtoError> { + let mut read_once = false; + loop { + let pending = self.buf.get(self.start..).unwrap_or(&[]); + let scanned = self.poll_scanned.min(pending.len()); + if let Some(offset) = pending.get(scanned..).unwrap_or(&[]).iter().position(|b| *b == b'\n') { + let end = scanned.saturating_add(offset); + let line = pending.get(..end).unwrap_or(&[]); + let line = line.strip_suffix(b"\r").unwrap_or(line); + if line.len() > MAX_LINE { + return Err(too_long()); + } + let line = line.to_vec(); + self.start = self.start.saturating_add(end).saturating_add(1); + self.poll_scanned = 0; + return Ok(Some(line)); + } + if pending.len() > MAX_LINE + 1 { + return Err(too_long()); + } + self.poll_scanned = pending.len(); + // One underlying read per poll lets the caller check cancellation even when + // a hostile peer trickles bytes without ever triggering the read timeout. + if read_once { + return Ok(None); + } + if self.start > 0 { + self.buf.drain(..self.start.min(self.buf.len())); + self.start = 0; + } + let mut tmp = vec![0u8; CHUNK]; + read_once = true; + match self.stream.read(&mut tmp) { + Ok(0) => return Err(closed()), + Ok(n) => self.buf.extend_from_slice(tmp.get(..n.min(tmp.len())).unwrap_or(&[])), + Err(e) if matches!(e.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted) => return Ok(None), + Err(e) => return Err(io_error(&e)), + } + } + } + + /// Exactly `n` bytes (at most [`MAX_LITERAL`]). + pub(crate) fn read_block(&mut self, n: usize) -> Result, ProtoError> { + self.poll_scanned = 0; + if n > MAX_LITERAL { + return Err(ProtoError::Protocol(said!("the server sent {n} bytes in one piece, more than MailCraft accepts", n))); + } + // The size is the server's word: memory is taken as the bytes arrive. + let mut out = Vec::with_capacity(n.min(CHUNK)); + let pending = self.buf.get(self.start..).unwrap_or(&[]); + let take = pending.len().min(n); + out.extend_from_slice(pending.get(..take).unwrap_or(&[])); + self.start = self.start.saturating_add(take); + let mut tmp = vec![0u8; CHUNK]; + while out.len() < n { + let want = (n - out.len()).min(tmp.len()); + let got = read_some(&mut self.stream, tmp.get_mut(..want).unwrap_or(&mut []))?; + out.extend_from_slice(tmp.get(..got.min(want)).unwrap_or(&[])); + } + Ok(out) + } + + pub(crate) fn write(&mut self, mut bytes: &[u8]) -> Result<(), ProtoError> { + // Not `write_all`: that retries an interrupted write for ever. + let mut interrupts = 0; + while !bytes.is_empty() { + match self.stream.write(bytes) { + Ok(0) => return Err(closed()), + Ok(n) => bytes = bytes.get(n..).unwrap_or(&[]), + Err(e) if e.kind() == ErrorKind::Interrupted && interrupts < MAX_INTERRUPTS => interrupts += 1, + Err(e) => return Err(io_error(&e)), + } + } + Ok(()) + } + + pub(crate) fn flush(&mut self) -> Result<(), ProtoError> { + self.stream.flush().map_err(|e| io_error(&e)) + } +} + +fn too_long() -> ProtoError { + ProtoError::Protocol(said!("the server sent a line longer than {kb} KB", kb = MAX_LINE / 1024)) +} + +/// One read of at least one byte; the end of the stream is an error. +fn read_some(stream: &mut S, buf: &mut [u8]) -> Result { + let mut interrupts = 0; + loop { + match stream.read(buf) { + Ok(0) => return Err(closed()), + // A stream that claims more than the buffer holds is lying. + Ok(n) => return Ok(n.min(buf.len())), + Err(e) if e.kind() == ErrorKind::Interrupted && interrupts < MAX_INTERRUPTS => interrupts += 1, + Err(e) => return Err(io_error(&e)), + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use crate::script::{Broken, Script}; + + #[test] + fn polling_reads_once_and_retains_linear_scan_progress() { + struct ByteAtATime { + bytes: std::io::Cursor>, + reads: usize, + } + impl Read for ByteAtATime { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + self.reads += 1; + self.bytes.read(&mut out[..1]) + } + } + impl Write for ByteAtATime { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut wire = Wire::new(ByteAtATime { bytes: std::io::Cursor::new(b"abc\n".to_vec()), reads: 0 }); + for scanned in 1..=3 { + assert_eq!(wire.poll_line().unwrap(), None); + assert_eq!(wire.poll_scanned, scanned); + assert_eq!(wire.get_mut().reads, scanned); + } + assert_eq!(wire.poll_line().unwrap(), Some(b"abc".to_vec())); + assert_eq!(wire.get_mut().reads, 4); + assert_eq!(wire.poll_scanned, 0); + } + + #[test] + fn lines_and_blocks_arrive_in_pieces() { + let mut s = Script::new("first\r\nsecond\nab\r\ncd\r\nlast\r\n"); + let mut w = Wire::new(&mut s); + assert_eq!(w.read_line().unwrap(), b"first"); + assert_eq!(w.read_line().unwrap(), b"second"); + assert_eq!(w.read_block(6).unwrap(), b"ab\r\ncd"); + assert_eq!(w.read_block(0).unwrap(), b""); + assert_eq!(w.read_line().unwrap(), b""); + assert_eq!(w.read_line().unwrap(), b"last"); + assert!(!w.has_pending()); + } + + #[test] + fn the_end_of_the_stream_is_an_error() { + let mut s = Script::new("no line ending"); + let mut w = Wire::new(&mut s); + assert_eq!(w.read_line(), Err(ProtoError::Io(said!("the server closed the connection")))); + let mut s = Script::new("short"); + assert!(matches!(Wire::new(&mut s).read_block(10), Err(ProtoError::Io(_)))); + } + + #[test] + fn long_lines_and_large_blocks_are_refused() { + let mut s = Script::whole(vec![b'x'; MAX_LINE + CHUNK * 2]); + assert!(matches!(Wire::new(&mut s).read_line(), Err(ProtoError::Protocol(_)))); + // A line of exactly the limit is fine. + let mut ok = vec![b'x'; MAX_LINE]; + ok.extend_from_slice(b"\r\n"); + let mut s = Script::whole(ok); + assert_eq!(Wire::new(&mut s).read_line().unwrap().len(), MAX_LINE); + // The claim alone is refused: nothing is read or allocated. + let mut s = Script::new(""); + assert!(matches!(Wire::new(&mut s).read_block(MAX_LITERAL + 1), Err(ProtoError::Protocol(_)))); + } + + #[test] + fn stream_errors_become_connection_problems() { + let mut w = Wire::new(Broken(ErrorKind::TimedOut)); + assert_eq!(w.read_line(), Err(ProtoError::Io(said!("the server took too long to answer")))); + assert!(matches!(w.write(b"x"), Err(ProtoError::Io(_)))); + // A stream that is interrupted for ever hangs neither the reader nor the writer. + assert!(matches!(Wire::new(Broken(ErrorKind::Interrupted)).read_line(), Err(ProtoError::Io(_)))); + assert!(matches!(Wire::new(Broken(ErrorKind::Interrupted)).write(b"x"), Err(ProtoError::Io(_)))); + } +} diff --git a/crates/proto/src/script.rs b/crates/proto/src/script.rs new file mode 100644 index 0000000000..a3d952efb3 --- /dev/null +++ b/crates/proto/src/script.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Test streams: a scripted server, and a stream that only fails. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::{Error, ErrorKind, Read, Write}; + +/// A canned server: reads hand out what the server "says" (a few bytes at a time, so every +/// boundary gets split somewhere), writes are kept for the test to look at. +#[derive(Debug)] +pub(crate) struct Script { + input: Vec, + pos: usize, + step: usize, + trickle: bool, + pub(crate) written: Vec, +} + +impl Script { + /// Hands the bytes out 1–7 at a time. + pub(crate) fn new(server: impl AsRef<[u8]>) -> Script { + Script { input: server.as_ref().to_vec(), pos: 0, step: 0, trickle: true, written: Vec::new() } + } + + /// Hands out as much as each read asks for. + pub(crate) fn whole(server: impl AsRef<[u8]>) -> Script { + Script { trickle: false, ..Script::new(server) } + } + + /// What the client wrote, as text. + pub(crate) fn sent(&self) -> String { + String::from_utf8_lossy(&self.written).into_owned() + } + + /// Whether the client read everything the script had. + pub(crate) fn finished(&self) -> bool { + self.pos >= self.input.len() + } +} + +impl Read for Script { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let left = &self.input[self.pos.min(self.input.len())..]; + let mut n = left.len().min(buf.len()); + if self.trickle { + n = n.min([3, 1, 7, 2, 5, 4, 6][self.step % 7]); + self.step += 1; + } + buf[..n].copy_from_slice(&left[..n]); + self.pos += n; + Ok(n) + } +} + +impl Write for Script { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.written.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// A stream whose every read and write fails. +#[derive(Debug)] +pub(crate) struct Broken(pub(crate) ErrorKind); + +impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + Err(Error::from(self.0)) + } +} + +impl Write for Broken { + fn write(&mut self, _: &[u8]) -> std::io::Result { + Err(Error::from(self.0)) + } + + fn flush(&mut self) -> std::io::Result<()> { + Err(Error::from(self.0)) + } +} diff --git a/crates/proto/src/smtp/mod.rs b/crates/proto/src/smtp/mod.rs new file mode 100644 index 0000000000..cbf5034c45 --- /dev/null +++ b/crates/proto/src/smtp/mod.rs @@ -0,0 +1,419 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An SMTP client (RFC 5321) with STARTTLS (RFC 3207) and AUTH PLAIN / LOGIN / XOAUTH2 (RFC 4954). + +use std::io::{Read, Write}; + +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +use crate::i18n::{Arg, Text}; +use crate::line::Wire; +use crate::said; +use crate::{ProtoError, Secrets, for_trace, tidy, xoauth2}; + +/// Most lines one reply may have. +const MAX_REPLY_LINES: usize = 256; +/// Longest command line without its line ending (RFC 5321 §4.5.3.1.4). +const MAX_COMMAND: usize = 510; +/// Longest address (RFC 5321 §4.5.3.1.3 allows 256; some servers take more). +const MAX_ADDRESS: usize = 320; +/// Most recipients one message may have. +const MAX_RECIPIENTS: usize = 10_000; + +/// An SMTP session on a stream. +pub struct Smtp { + wire: Wire, + ext: Extensions, + secrets: Secrets, +} + +/// What the server offered in its answer to EHLO. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Extensions { + pub starttls: bool, + pub auth_plain: bool, + pub auth_login: bool, + /// The server takes an OAuth access token instead of a password (SASL XOAUTH2). + pub auth_xoauth2: bool, + /// The largest message the server takes; `Some(0)` when it names no limit. + pub size: Option, + pub eight_bit_mime: bool, +} + +/// Neither the stream nor anything secret is shown. +impl std::fmt::Debug for Smtp { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Smtp").field("extensions", &self.ext).finish_non_exhaustive() + } +} + +/// One reply: `250-first`, `250 last`. +struct Reply { + code: u16, + lines: Vec, +} + +impl Reply { + fn class(&self) -> u16 { + self.code / 100 + } + + /// `550 5.1.1 No such user`, as the server wrote it. + fn text(&self) -> String { + format!("{} {}", self.code, self.lines.join(" ")) + } +} + +impl Smtp { + /// Read the 220 greeting. + pub fn connect(stream: S) -> Result { + let mut smtp = Self::resume(stream); + let greeting = smtp.reply()?; + if greeting.code == 220 { Ok(smtp) } else { Err(smtp.refused(&greeting)) } + } + + /// Continue on a stream that already greeted (after the caller wrapped it in TLS). + pub fn resume(stream: S) -> Self { + Smtp { wire: Wire::new(stream), ext: Extensions::default(), secrets: Secrets::default() } + } + + /// What the last [`hello`](Self::hello) learned. + pub fn extensions(&self) -> &Extensions { + &self.ext + } + + /// The stream the session runs on, for its owner to set up between commands (how long a + /// socket waits, say). Reading from it or writing to it would take the session apart. + pub fn get_mut(&mut self) -> &mut S { + self.wire.get_mut() + } + + /// EHLO (falling back to HELO); remembers and returns what the server offers. + pub fn hello(&mut self, client_name: &str) -> Result { + // A name that could break the command line is not sent. + let name = if is_word(client_name) { client_name } else { "localhost" }; + let reply = self.command(&format!("EHLO {name}"))?; + if reply.code == 250 { + self.ext = extensions(&reply.lines); + return Ok(self.ext.clone()); + } + if reply.class() != 5 { + return Err(self.refused(&reply)); + } + // A server from before 1995 (or one hiding its extensions). + let reply = self.command(&format!("HELO {name}"))?; + if reply.code != 250 { + return Err(self.refused(&reply)); + } + self.ext = Extensions::default(); + Ok(self.ext.clone()) + } + + /// Send STARTTLS and hand the stream back for the caller to wrap; call `resume` + `hello` afterwards. + pub fn starttls(mut self) -> Result { + let reply = self.command("STARTTLS")?; + if reply.code != 220 { + return Err(self.refused(&reply)); + } + // Anything after the go-ahead was slipped in before encryption started (RFC 3207 §6). + if self.wire.has_pending() { + return Err(ProtoError::Protocol(said!("the server sent data before the secure connection started"))); + } + Ok(self.wire.into_inner()) + } + + /// AUTH PLAIN when offered, else AUTH LOGIN. 535 and friends → `ProtoError::Auth`. + pub fn auth(&mut self, user: &str, password: &str) -> Result<(), ProtoError> { + if user.contains('\0') || password.contains('\0') { + return Err(ProtoError::Auth(said!("the user name or password has a character that can't be sent"))); + } + self.secrets.add(password); + if self.ext.auth_plain { + let payload = STANDARD.encode(format!("\0{user}\0{password}")); + self.secrets.add(&payload); + let line = format!("AUTH PLAIN {payload}"); + let reply = if line.len() <= MAX_COMMAND { + self.secret_command(&line, "AUTH PLAIN ***")? + } else { + // Too long for one line: wait for the server to ask (RFC 4954 §4). + let ask = self.command("AUTH PLAIN")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + self.secret_command(&payload, "***")? + }; + return self.signed_in(&reply); + } + if self.ext.auth_login { + let ask = self.command("AUTH LOGIN")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + let ask = self.secret_command(&STANDARD.encode(user), "***")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + let encoded = STANDARD.encode(password); + self.secrets.add(&encoded); + let reply = self.secret_command(&encoded, "***")?; + return self.signed_in(&reply); + } + Err(ProtoError::Auth(said!("the server offers no way to sign in with a password"))) + } + + /// AUTH XOAUTH2: an OAuth access token in place of a password. A server that doesn't offer + /// it isn't shown the token. 535 and friends → `ProtoError::Auth`. + pub fn auth_xoauth2(&mut self, user: &str, token: &str) -> Result<(), ProtoError> { + let payload = xoauth2(user, token)?; + if !self.ext.auth_xoauth2 { + return Err(ProtoError::Auth(said!("the server offers no way to sign in with an access token"))); + } + self.secrets.add(token); + self.secrets.add(&payload); + let line = format!("AUTH XOAUTH2 {payload}"); + let reply = if line.len() <= MAX_COMMAND { + self.secret_command(&line, "AUTH XOAUTH2 ***")? + } else { + // Too long for one line, as tokens mostly are: wait for the server to ask (RFC 4954 §4). + let ask = self.command("AUTH XOAUTH2")?; + if ask.code != 334 { + return Err(self.sign_in_failed(&ask)); + } + self.secret_command(&payload, "***")? + }; + match reply.code { + 235 => Ok(()), + 334 => { + // A refusal comes in two parts: the reasons (JSON in base64), and, once an empty + // line has acknowledged them, the verdict. + let verdict = self.command("")?; + match verdict.code { + 235 => Ok(()), + 334 => { + let _ = self.command("*"); + Err(ProtoError::Auth(said!("the server asked for more than a user name and access token"))) + } + _ => Err(self.sign_in_failed(&verdict)), + } + } + _ => Err(self.sign_in_failed(&reply)), + } + } + + /// MAIL FROM, RCPT TO (every recipient must be accepted), DATA with CRLF normalisation and dot-stuffing. + pub fn send(&mut self, from: &str, recipients: &[&str], message: &[u8]) -> Result<(), ProtoError> { + // Nothing is sent unless every address is safe to put on a command line. + if !from.is_empty() && !is_address(from) { + return Err(bad_address(from)); + } + if recipients.is_empty() { + return Err(ProtoError::Protocol(said!("the message has no recipients"))); + } + if recipients.len() > MAX_RECIPIENTS { + return Err(ProtoError::Protocol(said!("the message has too many recipients"))); + } + if let Some(bad) = recipients.iter().find(|r| !is_address(r)) { + return Err(bad_address(bad)); + } + let (data, size) = data_block(message); + let mut mail = format!("MAIL FROM:<{from}>"); + if self.ext.size.is_some() { + mail.push_str(&format!(" SIZE={size}")); + } + if self.ext.eight_bit_mime && !message.is_ascii() { + mail.push_str(" BODY=8BITMIME"); + } + let reply = self.command(&mail)?; + if reply.class() != 2 { + return Err(self.refused(&reply)); + } + for rcpt in recipients { + let reply = self.command(&format!("RCPT TO:<{rcpt}>"))?; + if reply.class() != 2 { + let refused = match self.refused(&reply) { + // (The address, then what the server said of it: no words of MailCraft's to say.) + ProtoError::Rejected(text) => { + ProtoError::Rejected(Text::new("{rcpt}: {text}", vec![("rcpt", Arg::Plain(rcpt.to_string())), ("text", Arg::said(text))])) + } + other => other, + }; + return Err(self.give_up(refused)); + } + } + let reply = self.command("DATA")?; + if reply.code != 354 { + let refused = self.refused(&reply); + return Err(self.give_up(refused)); + } + log::trace!("C: ({size} bytes)"); + self.wire.write(&data)?; + self.wire.flush()?; + let reply = self.reply()?; + if reply.class() != 2 { + return Err(self.refused(&reply)); + } + Ok(()) + } + + /// QUIT. A server that hangs up without answering has quit all the same. + pub fn quit(mut self) -> Result<(), ProtoError> { + match self.command("QUIT") { + Ok(reply) if reply.class() == 2 => Ok(()), + Ok(reply) => Err(self.refused(&reply)), + // A server that hangs up instead of saying goodbye has quit all the same. + Err(ProtoError::Io(_)) => Ok(()), + Err(e) => Err(e), + } + } + + /// Forget the message being composed, so the session can go on; hands the error back. + fn give_up(&mut self, error: ProtoError) -> ProtoError { + let _ = self.command("RSET"); + error + } + + fn command(&mut self, line: &str) -> Result { + self.secret_command(line, line) + } + + /// Send `line`; the log gets `shown` instead. + fn secret_command(&mut self, line: &str, shown: &str) -> Result { + log::trace!("C: {}", for_trace(&self.secrets.hide(shown))); + let mut out = Vec::with_capacity(line.len() + 2); + out.extend_from_slice(line.as_bytes()); + out.extend_from_slice(b"\r\n"); + self.wire.write(&out)?; + self.wire.flush()?; + self.reply() + } + + fn reply(&mut self) -> Result { + let mut reply = Reply { code: 0, lines: Vec::new() }; + for n in 0..MAX_REPLY_LINES { + let raw = self.wire.read_line()?; + let line = String::from_utf8_lossy(&raw); + log::trace!("S: {}", for_trace(&self.secrets.hide(&line))); + // Three digits, then `-` (more lines follow), a space or nothing (the last line). + let code = line.get(..3).filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse::().ok()); + let rest = line.get(3..).unwrap_or(""); + let more = match (code, rest.chars().next()) { + (Some(code), Some('-')) if n == 0 || code == reply.code => true, + (Some(code), Some(' ') | None) if n == 0 || code == reply.code => false, + _ => return Err(ProtoError::Protocol(said!("\"{line}\" is not an SMTP reply", line = tidy(&self.secrets.hide(&line))))), + }; + reply.code = code.unwrap_or(0); + reply.lines.push(rest.get(1..).unwrap_or("").to_string()); + if !more { + return Ok(reply); + } + } + Err(ProtoError::Protocol(said!("the server's reply has too many lines"))) + } + + /// The error for a reply that isn't the one hoped for. + fn refused(&self, reply: &Reply) -> ProtoError { + // Hidden before it is shortened: a secret cut in half would no longer be recognised. + let text = tidy(&self.secrets.hide(&reply.text())); + if matches!(reply.class(), 4 | 5) { ProtoError::Rejected(text.into()) } else { ProtoError::Protocol(text.into()) } + } + + fn sign_in_failed(&mut self, reply: &Reply) -> ProtoError { + match self.refused(reply) { + ProtoError::Rejected(text) => ProtoError::Auth(text), + other => other, + } + } + + fn signed_in(&mut self, reply: &Reply) -> Result<(), ProtoError> { + match reply.code { + 235 => Ok(()), + 334 => { + // Another question we have no answer to: cancel the exchange (RFC 4954 §4). + let _ = self.command("*"); + Err(ProtoError::Auth(said!("the server asked for more than a user name and password"))) + } + _ => Err(self.sign_in_failed(reply)), + } + } +} + +/// The extensions named in an EHLO reply (its first line is the server's name). +fn extensions(lines: &[String]) -> Extensions { + let mut ext = Extensions::default(); + for line in lines.iter().skip(1) { + let upper = line.to_ascii_uppercase(); + // `AUTH=PLAIN LOGIN` is how some old servers spell `AUTH PLAIN LOGIN`. + let mut words = upper.split([' ', '\t', '=']).filter(|w| !w.is_empty()); + match words.next() { + Some("STARTTLS") => ext.starttls = true, + Some("8BITMIME") => ext.eight_bit_mime = true, + Some("SIZE") => ext.size = Some(words.next().and_then(|n| n.parse().ok()).unwrap_or(0)), + Some("AUTH") => { + for mechanism in words { + match mechanism { + "PLAIN" => ext.auth_plain = true, + "LOGIN" => ext.auth_login = true, + "XOAUTH2" => ext.auth_xoauth2 = true, + _ => {} + } + } + } + _ => {} + } + } + ext +} + +/// Visible ASCII without spaces: safe as one word of a command line. +fn is_word(s: &str) -> bool { + !s.is_empty() && s.len() <= 255 && s.bytes().all(|b| b.is_ascii_graphic()) +} + +/// An address that can go between `<` and `>` as it is. +fn is_address(s: &str) -> bool { + is_word(s) && s.len() <= MAX_ADDRESS && !s.contains(['<', '>']) +} + +fn bad_address(address: &str) -> ProtoError { + ProtoError::Protocol(said!("\"{address}\" can't be used as an address", address = tidy(address))) +} + +/// The message as DATA wants it: every line ending CRLF, a leading dot doubled, the closing +/// `.` line added. Also returns the size without the added dots and closing line (RFC 1870). +fn data_block(message: &[u8]) -> (Vec, usize) { + let mut out = Vec::with_capacity(message.len().saturating_add(message.len() / 32).saturating_add(8)); + let mut dots = 0usize; + let mut line_start = true; + let mut bytes = message.iter().copied().peekable(); + while let Some(b) = bytes.next() { + match b { + b'\r' => { + bytes.next_if_eq(&b'\n'); + out.extend_from_slice(b"\r\n"); + line_start = true; + } + b'\n' => { + out.extend_from_slice(b"\r\n"); + line_start = true; + } + b'.' if line_start => { + out.extend_from_slice(b".."); + dots += 1; + line_start = false; + } + _ => { + out.push(b); + line_start = false; + } + } + } + if !line_start { + out.extend_from_slice(b"\r\n"); + } + let size = out.len().saturating_sub(dots); + out.extend_from_slice(b".\r\n"); + (out, size) +} + +#[cfg(test)] +mod tests; diff --git a/crates/proto/src/smtp/tests.rs b/crates/proto/src/smtp/tests.rs new file mode 100644 index 0000000000..37777d5e8f --- /dev/null +++ b/crates/proto/src/smtp/tests.rs @@ -0,0 +1,455 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use std::io::ErrorKind; + +use proptest::prelude::*; + +use super::*; +use crate::script::{Broken, Script}; + +const EHLO: &str = + "250-mail.example.org greets you\r\n250-SIZE 35882577\r\n250-8BITMIME\r\n250-STARTTLS\r\n250-AUTH LOGIN PLAIN XOAUTH2\r\n250 HELP\r\n"; + +fn rejected(r: Result<(), ProtoError>) -> String { + match r { + Err(ProtoError::Rejected(text)) => text.to_string(), + other => panic!("expected a rejection, got {other:?}"), + } +} + +#[test] +fn a_whole_session() { + let mut s = Script::new(format!( + "220-mail.example.org ESMTP\r\n220 ready\r\n{EHLO}235 2.7.0 Accepted\r\n250 OK\r\n250 OK\r\n251 will forward\r\n354 go ahead\r\n250 queued as 1\r\n221 bye\r\n" + )); + let mut smtp = Smtp::connect(&mut s).unwrap(); + let ext = smtp.hello("[127.0.0.1]").unwrap(); + assert_eq!( + ext, + Extensions { starttls: true, auth_plain: true, auth_login: true, auth_xoauth2: true, size: Some(35_882_577), eight_bit_mime: true } + ); + assert_eq!(smtp.extensions(), &ext); + smtp.auth("ada@example.org", "hunter2").unwrap(); + smtp.send("ada@example.org", &["bob@example.org", "carol@example.org"], b"Subject: Hi\r\n\r\nHello.\r\n").unwrap(); + smtp.quit().unwrap(); + assert!(s.finished()); + assert_eq!( + s.sent(), + "EHLO [127.0.0.1]\r\n\ + AUTH PLAIN AGFkYUBleGFtcGxlLm9yZwBodW50ZXIy\r\n\ + MAIL FROM: SIZE=23\r\n\ + RCPT TO:\r\n\ + RCPT TO:\r\n\ + DATA\r\n\ + Subject: Hi\r\n\r\nHello.\r\n.\r\n\ + QUIT\r\n" + ); +} + +#[test] +fn the_plain_payload_is_nul_user_nul_password() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth("grace", "pässword \"1\"").unwrap(); + let sent = s.sent(); + let payload = sent.lines().nth(1).unwrap().strip_prefix("AUTH PLAIN ").unwrap(); + assert_eq!(STANDARD.decode(payload).unwrap(), "\0grace\0pässword \"1\"".as_bytes()); +} + +#[test] +fn a_long_plain_payload_waits_for_the_server_to_ask() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n334 \r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let password = "p".repeat(600); + smtp.auth("grace", &password).unwrap(); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines[1], "AUTH PLAIN"); + assert_eq!(STANDARD.decode(lines[2]).unwrap(), format!("\0grace\0{password}").as_bytes()); +} + +#[test] +fn login_is_used_when_plain_is_not_offered() { + let mut s = Script::new("250-x\r\n250 AUTH=LOGIN CRAM-MD5\r\n334 VXNlcm5hbWU6\r\n334 UGFzc3dvcmQ6\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + let ext = smtp.hello("localhost").unwrap(); + assert!(ext.auth_login && !ext.auth_plain); + smtp.auth("ada", "hunter2").unwrap(); + assert_eq!(s.sent(), "EHLO localhost\r\nAUTH LOGIN\r\nYWRh\r\naHVudGVyMg==\r\n"); +} + +#[test] +fn a_wrong_password_is_an_auth_error_that_never_shows_it() { + // A careless server repeats what it was sent. + let echo = "535-5.7.8 no such password: hunter2\r\n535 5.7.8 (AGFkYQBodW50ZXIy)\r\n"; + let mut s = Script::new(format!("250-x\r\n250 AUTH PLAIN\r\n{echo}")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth("ada", "hunter2").unwrap_err(); + assert_eq!(err, ProtoError::Auth("535 5.7.8 no such password: *** 5.7.8 (***)".into())); + assert!(!format!("{err} {err:?} {smtp:?}").contains("hunter2")); + + // The same over LOGIN, where the password travels alone. + let mut s = Script::new("250-x\r\n250 AUTH LOGIN\r\n334 VXNlcm5hbWU6\r\n334 UGFzc3dvcmQ6\r\n535 bad aHVudGVyMg== / hunter2\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth("535 bad *** / ***".into()))); +} + +#[test] +fn sign_in_needs_a_method_and_sendable_text() { + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert!(matches!(smtp.auth("ada", "hun\0ter2"), Err(ProtoError::Auth(_)))); + // Neither attempt put anything on the wire. + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +/// What an XOAUTH2 response says under its base64. +fn bearer(payload: &str) -> String { + String::from_utf8(STANDARD.decode(payload).unwrap()).unwrap() +} + +#[test] +fn a_token_signs_in_with_xoauth2() { + let mut s = Script::new("250-x\r\n250 AUTH LOGIN XOAUTH2\r\n235 2.7.0 Authentication successful\r\n"); + let mut smtp = Smtp::resume(&mut s); + assert!(smtp.hello("localhost").unwrap().auth_xoauth2); + smtp.auth_xoauth2("ada@example.org", "tok.en-123").unwrap(); + assert!(s.finished()); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines.len(), 2); + assert_eq!(bearer(lines[1].strip_prefix("AUTH XOAUTH2 ").unwrap()), "user=ada@example.org\x01auth=Bearer tok.en-123\x01\x01"); +} + +#[test] +fn a_long_token_waits_for_the_server_to_ask() { + // Real tokens run to a couple of thousand characters. + let token = "t".repeat(2_000); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth_xoauth2("ada@example.org", &token).unwrap(); + let sent = s.sent(); + let lines: Vec<&str> = sent.lines().collect(); + assert_eq!(lines[1], "AUTH XOAUTH2"); + assert_eq!(bearer(lines[2]), format!("user=ada@example.org\x01auth=Bearer {token}\x01\x01")); + + // The longest that still fits goes in one line. + let token = "t".repeat(349); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.auth_xoauth2("ada", &token).unwrap(); + let sent = s.sent(); + assert_eq!((sent.lines().count(), sent.lines().nth(1).unwrap().len()), (2, MAX_COMMAND - 1)); + + // A server that won't ask is not shown the token. + let token = "t".repeat(2_000); + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n504 5.5.4 not that way\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", &token), Err(ProtoError::Auth("504 5.5.4 not that way".into()))); + assert_eq!(s.sent(), "EHLO localhost\r\nAUTH XOAUTH2\r\n"); +} + +#[test] +fn a_refused_token_is_an_auth_error_that_never_shows_it() { + let payload = xoauth2("ada", "tok.en-123").unwrap(); + let reasons = STANDARD.encode(r#"{"status":"401","schemes":"bearer","scope":"https://mail.example.org/"}"#); + // The reasons come first and the verdict after an empty line; a careless server repeats what it was sent. + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 {reasons}\r\n535-5.7.3 no good: tok.en-123\r\n535 5.7.3 ({payload})\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth_xoauth2("ada", "tok.en-123").unwrap_err(); + assert_eq!(err, ProtoError::Auth("535 5.7.3 no good: *** 5.7.3 (***)".into())); + assert!(!format!("{err} {err:?} {smtp:?}").contains("tok.en-123")); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2 {payload}\r\n\r\n")); + assert!(s.finished()); + + // The same when the token went on a line of its own. + let token = "t".repeat(2_000); + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n334 {reasons}\r\n535 5.7.3 Authentication unsuccessful\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", &token), Err(ProtoError::Auth("535 5.7.3 Authentication unsuccessful".into()))); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2\r\n{}\r\n\r\n", xoauth2("ada", &token).unwrap())); + assert!(s.finished()); + + // Refused in one word, without reasons. + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n535 5.7.3 Authentication unsuccessful\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth("535 5.7.3 Authentication unsuccessful".into()))); + assert_eq!(s.sent(), format!("EHLO localhost\r\nAUTH XOAUTH2 {payload}\r\n")); + + // A question after the reasons has no answer: the exchange is cancelled. + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 {reasons}\r\n334 more?\r\n501 cancelled\r\n")); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n\r\n*\r\n")); +} + +#[test] +fn a_token_echoed_in_a_long_reply_is_hidden_whole() { + // The reply is shortened for the error text: not before the token is out of it. + let token = format!("head.{}.tail", "x".repeat(2_000)); + let mut s = Script::new(format!("250-x\r\n250 AUTH XOAUTH2\r\n334 \r\n535 5.7.3 {} bad token {token}\r\n", "no ".repeat(80))); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + let err = smtp.auth_xoauth2("ada", &token).unwrap_err(); + let shown = format!("{err} {err:?}"); + assert!(matches!(err, ProtoError::Auth(_))); + assert!(!shown.contains("head.") && !shown.contains("xxxx"), "{shown}"); +} + +#[test] +fn a_token_needs_a_server_that_takes_one_and_sendable_text() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN LOGIN\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert_eq!(smtp.auth_xoauth2("ada", "tok.en-123"), Err(ProtoError::Auth(said!("the server offers no way to sign in with an access token")))); + assert_eq!(s.sent(), "EHLO localhost\r\n"); + + let mut s = Script::new("250-x\r\n250 AUTH XOAUTH2\r\n235 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + for (user, token) in + [("ada", ""), ("ada", "tok\r\nQUIT"), ("ada", "tok\x01"), ("ada\x01auth=Bearer x", "tok"), ("a\0da", "tok"), ("ada\n", "tok")] + { + assert!(matches!(smtp.auth_xoauth2(user, token), Err(ProtoError::Auth(_))), "{user:?} {token:?}"); + } + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +#[test] +fn an_unexpected_second_question_cancels_the_sign_in() { + let mut s = Script::new("250-x\r\n250 AUTH PLAIN\r\n334 more?\r\n501 cancelled\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + assert!(matches!(smtp.auth("ada", "hunter2"), Err(ProtoError::Auth(_)))); + assert!(s.sent().ends_with("\r\n*\r\n")); +} + +#[test] +fn helo_is_the_fallback() { + let mut s = Script::new("220 old.example.org\r\n502 what?\r\n250 old.example.org\r\n"); + let mut smtp = Smtp::connect(&mut s).unwrap(); + assert_eq!(smtp.hello("localhost").unwrap(), Extensions::default()); + assert_eq!(s.sent(), "EHLO localhost\r\nHELO localhost\r\n"); + + // A server on its way out is not asked twice. + let mut s = Script::new("421 shutting down\r\n"); + assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Rejected("421 shutting down".into()))); + assert_eq!(s.sent(), "EHLO localhost\r\n"); +} + +#[test] +fn a_client_name_that_could_break_the_line_is_replaced() { + for bad in ["", "two words", "evil\r\nMAIL FROM:", "nön-ascii"] { + let mut s = Script::new("250 ok\r\n"); + Smtp::resume(&mut s).hello(bad).unwrap(); + assert_eq!(s.sent(), "EHLO localhost\r\n", "{bad:?}"); + } +} + +#[test] +fn extensions_are_read_whatever_their_case() { + let mut s = Script::new("250-x\r\n250-starttls\r\n250-Size\r\n250-auth plain\r\n250 8bitmime\r\n"); + let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); + assert_eq!(ext, Extensions { starttls: true, auth_plain: true, auth_login: false, auth_xoauth2: false, size: Some(0), eight_bit_mime: true }); + let mut s = Script::new("250-x\r\n250 auth=login xoauth2 OAUTHBEARER\r\n"); + let ext = Smtp::resume(&mut s).hello("localhost").unwrap(); + assert_eq!(ext, Extensions { auth_login: true, auth_xoauth2: true, ..Default::default() }); +} + +#[test] +fn starttls_hands_the_stream_back() { + let mut s = Script::new("220 hi\r\n250-x\r\n250 STARTTLS\r\n220 go ahead\r\n"); + let mut smtp = Smtp::connect(&mut s).unwrap(); + assert!(smtp.hello("localhost").unwrap().starttls); + let stream = smtp.starttls().unwrap(); + assert_eq!(stream.sent(), "EHLO localhost\r\nSTARTTLS\r\n"); + + let mut s = Script::new("454 TLS not available\r\n"); + assert_eq!(Smtp::resume(&mut s).starttls().unwrap_err(), ProtoError::Rejected("454 TLS not available".into())); +} + +#[test] +fn text_slipped_in_before_tls_is_refused() { + // Both lines arrive in one read, as an attacker in the middle would send them. + let mut s = Script::whole("220 go ahead\r\n250 injected\r\n"); + assert!(matches!(Smtp::resume(&mut s).starttls(), Err(ProtoError::Protocol(_)))); +} + +#[test] +fn data_is_normalised_and_dot_stuffed() { + let message = b"Subject: dots\n\n.leading\r\n..two\rbare CR\n.\nno dot. here\n\nlast line without an ending"; + let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.send("ada@example.org", &["bob@example.org"], message).unwrap(); + let sent = s.sent(); + let data = sent.split_once("DATA\r\n").unwrap().1; + assert_eq!(data, "Subject: dots\r\n\r\n..leading\r\n...two\r\nbare CR\r\n..\r\nno dot. here\r\n\r\nlast line without an ending\r\n.\r\n"); + // No SIZE or BODY parameter for a server that didn't offer them. + assert!(sent.starts_with("MAIL FROM:\r\n")); +} + +#[test] +fn data_blocks() { + assert_eq!(data_block(b""), (b".\r\n".to_vec(), 0)); + assert_eq!(data_block(b"a"), (b"a\r\n.\r\n".to_vec(), 3)); + assert_eq!(data_block(b"."), (b"..\r\n.\r\n".to_vec(), 3)); + assert_eq!(data_block(b"\r\r\n\n"), (b"\r\n\r\n\r\n.\r\n".to_vec(), 6)); + assert_eq!(data_block(b"a\r"), (b"a\r\n.\r\n".to_vec(), 3)); +} + +#[test] +fn eight_bit_mail_says_so_when_the_server_takes_it() { + let mut s = Script::new("250-x\r\n250 8BITMIME\r\n250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n"); + let mut smtp = Smtp::resume(&mut s); + smtp.hello("localhost").unwrap(); + smtp.send("ada@example.org", &["bob@example.org"], "Subject: é\r\n\r\n".as_bytes()).unwrap(); + smtp.send("", &["bob@example.org"], b"Subject: e\r\n\r\n").unwrap(); + let sent = s.sent(); + assert!(sent.contains("MAIL FROM: BODY=8BITMIME\r\n")); + // An empty sender is the bounce address. + assert!(sent.contains("MAIL FROM:<>\r\n")); +} + +#[test] +fn a_refused_recipient_stops_the_message_and_resets() { + let mut s = Script::new("250 ok\r\n250 ok\r\n550 5.1.1 no such user\r\n250 reset\r\n"); + let mut smtp = Smtp::resume(&mut s); + let text = rejected(smtp.send("ada@example.org", &["bob@example.org", "nobody@example.org", "carol@example.org"], b"x")); + assert_eq!(text, "nobody@example.org: 550 5.1.1 no such user"); + assert!(s.sent().ends_with("RCPT TO:\r\nRSET\r\n")); +} + +#[test] +fn refusals_at_each_step() { + // MAIL FROM. + let mut s = Script::new("552 5.3.4 too big\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "552 5.3.4 too big"); + // DATA. + let mut s = Script::new("250 ok\r\n250 ok\r\n554 no\r\n250 reset\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "554 no"); + assert!(s.sent().ends_with("DATA\r\nRSET\r\n")); + // After the message. + let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n451 4.3.0 try later\r\n"); + assert_eq!(rejected(Smtp::resume(&mut s).send("a@example.org", &["b@example.org"], b"x")), "451 4.3.0 try later"); + // The greeting. + let mut s = Script::new("554 no service for you\r\n"); + assert_eq!(Smtp::connect(&mut s).unwrap_err(), ProtoError::Rejected("554 no service for you".into())); +} + +#[test] +fn unsafe_addresses_are_never_sent() { + let cases: [(&str, &[&str]); 6] = [ + ("ada@example.org", &[]), + ("ada@example.org", &["bob@example.org>\r\nRCPT TO:(), 0..600)) { + drive(&server); + } + + #[test] + fn reply_shaped_noise_never_panics(lines in proptest::collection::vec(("[0-9]{3}", "[- ]?", "[ -~]{0,30}"), 0..40)) { + let server: String = lines.iter().map(|(code, sep, text)| format!("{code}{sep}{text}\r\n")).collect(); + drive(server.as_bytes()); + } + + #[test] + fn data_blocks_never_end_early(message in proptest::collection::vec(prop_oneof![Just(b'.'), Just(b'\r'), Just(b'\n'), any::()], 0..300)) { + let (data, size) = data_block(&message); + prop_assert!(data.ends_with(b".\r\n")); + let body = &data[..data.len() - 3]; + prop_assert!(body.is_empty() || body.ends_with(b"\r\n")); + // No bare CR or LF, and no line that is just a dot before the end. + let text = String::from_utf8_lossy(body); + prop_assert_eq!(body.iter().filter(|b| **b == b'\r').count(), body.iter().filter(|b| **b == b'\n').count()); + prop_assert!(!text.contains("\r\n.\r\n") && !text.starts_with(".\r\n")); + prop_assert_eq!(body.windows(2).filter(|w| w[0] == b'\r' && w[1] == b'\n').count(), body.iter().filter(|b| **b == b'\n').count()); + // Taking the stuffing out gives the size that was announced. + let unstuffed: usize = body.split_inclusive(|b| *b == b'\n').map(|l| l.len() - usize::from(l.starts_with(b"."))).sum(); + prop_assert_eq!(unstuffed, size); + } +} diff --git a/crates/psd/src/annotations.rs b/crates/psd/src/annotations.rs new file mode 100644 index 0000000000..57b466843a --- /dev/null +++ b/crates/psd/src/annotations.rs @@ -0,0 +1,230 @@ +//! Bounded, borrowed views and serialization of PSD global `Anno` records. +//! +//! Framing follows PhotoCraft's annotation reader (Brandon Thomas, aa87012a), with +//! David Mann's minimum-length guard and the per-entry span fix from PhotoCraft +//! #11138. Coordinates, colour conversion, text decoding and popup defaults are +//! deliberately caller policy. Unknown records can be carried through byte-exact. + +use crate::{PsdError, Result}; + +/// Explicit limits shared by readers and writers. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// Maximum complete block size. + pub bytes: usize, + /// Maximum annotation count. + pub records: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { bytes: 16 * 1024 * 1024, records: 4096 } + } +} + +struct Reader<'a> { + d: &'a [u8], + p: usize, +} +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.p.checked_add(n).ok_or(PsdError::LimitExceeded("annotation offset"))?; + let s = self.d.get(self.p..end).ok_or(PsdError::UnexpectedEof { offset: self.p, needed: n })?; + self.p = end; + Ok(s) + } + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or_default()) + } + fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.take(2)?.try_into().map_err(|_| PsdError::invalid("annotation u16"))?)) + } + fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.take(4)?.try_into().map_err(|_| PsdError::invalid("annotation u32"))?)) + } + fn key(&mut self) -> Result<[u8; 4]> { + self.take(4)?.try_into().map_err(|_| PsdError::invalid("annotation key")) + } + fn rect(&mut self) -> Result<[i32; 4]> { + Ok([self.u32()? as i32, self.u32()? as i32, self.u32()? as i32, self.u32()? as i32]) + } + fn pascal(&mut self) -> Result<&'a [u8]> { + let n = usize::from(self.u8()?); + let bytes = self.take(n)?; + if (n + 1) % 2 == 1 { + self.take(1)?; + } + Ok(bytes) + } +} + +/// A borrowed record, including its original length, padding and unknown fields. +#[derive(Clone, Copy, Debug)] +pub struct Record<'a> { + raw: &'a [u8], +} +impl<'a> Record<'a> { + /// Complete self-counting record, suitable for lossless passthrough. + pub fn raw(&self) -> &'a [u8] { + self.raw + } + /// Parse text records; other record kinds remain opaque. + pub fn text(&self) -> Result>> { + let mut r = Reader { d: self.raw, p: 4 }; + if r.key()? != *b"txtA" { + return Ok(None); + } + // Never read beyond this record, even if a text length points into its neighbour. + let open = r.u8()?; + let flags = r.u8()?; + let optional_blocks = r.u16()?; + let icon = r.rect()?; + let popup = r.rect()?; + let color_space = r.u16()?; + let color = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + let author = r.pascal()?; + let name = r.pascal()?; + let modified = r.pascal()?; + let data_length = r.u32()?; + let data_key = r.key()?; + let size = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation text"))?; + let data = r.take(size)?; + Ok(Some(Text { open, flags, optional_blocks, icon, popup, color_space, color, author, name, modified, data_length, data_key, data })) + } +} + +/// Wire-level text annotation. Text payload and Pascal strings remain bytes. +/// No text normalisation or application colour/coordinate policy is applied. +#[derive(Clone, Copy, Debug)] +pub struct Text<'a> { + /// Open state byte. + pub open: u8, + /// Flags byte. + pub flags: u8, + /// Optional block flags. + pub optional_blocks: u16, + /// Icon rectangle, top/left/bottom/right. + pub icon: [i32; 4], + /// Popup rectangle, top/left/bottom/right. + pub popup: [i32; 4], + /// PSD colour space. + pub color_space: u16, + /// Raw colour components. + pub color: [u16; 4], + /// Pascal author bytes, maximum 255. + pub author: &'a [u8], + /// Pascal name bytes, maximum 255. + pub name: &'a [u8], + /// Pascal modification-date bytes, maximum 255. + pub modified: &'a [u8], + /// Original self-counting data length, exposed for diagnostics. + /// The writer recomputes this field. + pub data_length: u32, + /// Usually `txtC`; retained without imposing application policy. + pub data_key: [u8; 4], + /// Payload, including any text byte-order mark. + pub data: &'a [u8], +} + +/// Parse complete framing before exposing records. Borrowed payloads do not allocate. +/// Trailing block bytes are accepted as in the existing PhotoCraft reader. +pub fn read(data: &[u8], limits: Limits) -> Result>> { + if data.len() > limits.bytes { + return Err(PsdError::LimitExceeded("annotation bytes")); + } + let mut r = Reader { d: data, p: 0 }; + r.u16()?; + r.u16()?; + let count = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation count"))?; + if count > limits.records || count > data.len().saturating_sub(8) / 8 { + return Err(PsdError::LimitExceeded("annotation count")); + } + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| PsdError::OutOfMemory("annotation records"))?; + for _ in 0..count { + let start = r.p; + let len = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation length"))?; + // David Mann's zero-length guard: a self-counting record must advance. + if len < 8 { + return Err(PsdError::invalid("annotation record shorter than its header")); + } + r.p = start; + let record = Record { raw: r.take(len)? }; + record.text()?; // validate text spans, including data borrowed by later consumers + out.push(record); + } + Ok(out) +} + +fn append(out: &mut Vec, bytes: &[u8], limit: usize) -> Result<()> { + let len = out.len().checked_add(bytes.len()).ok_or(PsdError::LimitExceeded("annotation bytes"))?; + if len > limit { + return Err(PsdError::LimitExceeded("annotation bytes")); + } + out.try_reserve(bytes.len()).map_err(|_| PsdError::OutOfMemory("annotation bytes"))?; + out.extend_from_slice(bytes); + Ok(()) +} + +fn pascal(out: &mut Vec, bytes: &[u8], limit: usize) -> Result<()> { + let n = u8::try_from(bytes.len()).map_err(|_| PsdError::LimitExceeded("annotation Pascal string"))?; + append(out, &[n], limit)?; + append(out, bytes, limit)?; + if (bytes.len() + 1) % 2 == 1 { + append(out, &[0], limit)?; + } + Ok(()) +} + +/// Serialize one text record, computing both length fields. Caller supplies raw +/// text bytes and already-mapped colour/coordinates; nothing is truncated. +pub fn write_text(text: &Text<'_>, limits: Limits) -> Result> { + let mut out = Vec::new(); + append(&mut out, &[0; 4], limits.bytes)?; + append(&mut out, b"txtA", limits.bytes)?; + append(&mut out, &[text.open, text.flags], limits.bytes)?; + append(&mut out, &text.optional_blocks.to_be_bytes(), limits.bytes)?; + for value in text.icon.into_iter().chain(text.popup) { + append(&mut out, &value.to_be_bytes(), limits.bytes)?; + } + append(&mut out, &text.color_space.to_be_bytes(), limits.bytes)?; + for value in text.color { + append(&mut out, &value.to_be_bytes(), limits.bytes)?; + } + for value in [text.author, text.name, text.modified] { + pascal(&mut out, value, limits.bytes)?; + } + let n = u32::try_from(text.data.len()).map_err(|_| PsdError::LimitExceeded("annotation text"))?; + let data_length = n.checked_add(12).ok_or(PsdError::LimitExceeded("annotation data length"))?; + append(&mut out, &data_length.to_be_bytes(), limits.bytes)?; + append(&mut out, &text.data_key, limits.bytes)?; + append(&mut out, &n.to_be_bytes(), limits.bytes)?; + append(&mut out, text.data, limits.bytes)?; + let len = u32::try_from(out.len()).map_err(|_| PsdError::LimitExceeded("annotation record length"))?; + out.get_mut(..4).ok_or_else(|| PsdError::invalid("annotation header"))?.copy_from_slice(&len.to_be_bytes()); + Ok(out) +} + +/// Combine already-framed records into a version 2.1 block. Unknown record types +/// are preserved byte-exact; malformed text records are refused. +pub fn write(records: &[&[u8]], limits: Limits) -> Result> { + if records.len() > limits.records { + return Err(PsdError::LimitExceeded("annotation count")); + } + let count = u32::try_from(records.len()).map_err(|_| PsdError::LimitExceeded("annotation count"))?; + let mut out = Vec::new(); + append(&mut out, &[0, 2, 0, 1], limits.bytes)?; + append(&mut out, &count.to_be_bytes(), limits.bytes)?; + for raw in records { + let mut r = Reader { d: raw, p: 0 }; + let declared = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation record length"))?; + if raw.len() < 8 || declared != raw.len() { + return Err(PsdError::invalid("annotation record length mismatch")); + } + Record { raw }.text()?; + append(&mut out, raw, limits.bytes)?; + } + Ok(out) +} + +#[cfg(test)] +mod tests; diff --git a/crates/psd/src/annotations/tests.rs b/crates/psd/src/annotations/tests.rs new file mode 100644 index 0000000000..e207852d41 --- /dev/null +++ b/crates/psd/src/annotations/tests.rs @@ -0,0 +1,117 @@ +use super::*; + +fn note() -> Text<'static> { + Text { + open: 1, + flags: 0x1c, + optional_blocks: 1, + icon: [10, 20, 30, 36], + popup: [30, 40, 190, 280], + color_space: 0, + color: [65535, 1000, 3000, 0], + author: b"Writer", + name: b"", + modified: b"2026", + data_length: 0, + data_key: *b"txtC", + data: &[0xfe, 0xff, 0, 65, 0, 13, 0, 66], + } +} + +#[test] +fn text_and_unknown_sound_round_trip_without_copying_payloads() { + let limits = Limits::default(); + let text = write_text(¬e(), limits).unwrap(); + let sound = [0, 0, 0, 11, b's', b'n', b'd', b'A', 42, 3, 9]; + let block = write(&[&text, &sound], limits).unwrap(); + let parsed = read(&block, limits).unwrap(); + assert_eq!(parsed.len(), 2); + let view = parsed[0].text().unwrap().unwrap(); + assert_eq!(view.author, note().author); + assert_eq!(view.data, note().data); + assert_eq!(view.icon, note().icon); + assert_eq!(view.color, note().color); + assert_eq!(view.data_length, 20); + assert!(parsed[1].text().unwrap().is_none()); + assert_eq!(parsed[1].raw(), sound); + let slices: Vec<_> = parsed.iter().map(Record::raw).collect(); + assert_eq!(write(&slices, limits).unwrap(), block); + assert!(view.data.as_ptr() >= block.as_ptr()); + assert!(view.data.as_ptr() < block.as_ptr().wrapping_add(block.len())); +} + +#[test] +fn text_cannot_read_past_the_declared_entry_into_its_neighbour() { + // Regression from PhotoCraft #11138, without its app Note/Color policy. + let mut record = write_text(¬e(), Limits::default()).unwrap(); + let shortened = record.len() - note().data.len(); + record[..4].copy_from_slice(&(shortened as u32).to_be_bytes()); + let mut block = vec![0, 2, 0, 1, 0, 0, 0, 1]; + block.extend_from_slice(&record); + assert!(read(&block, Limits::default()).is_err()); + assert!(write(&[&record], Limits::default()).is_err()); +} + +#[test] +fn truncation_and_hostile_counts_lengths_fail_closed() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let block = write(&[&record], Limits::default()).unwrap(); + for end in 0..block.len() { + assert!(read(&block[..end], Limits::default()).is_err(), "{end}"); + } + for len in [0u32, 1, 7, u32::MAX] { + let mut bad = block.clone(); + bad[8..12].copy_from_slice(&len.to_be_bytes()); + assert!(read(&bad, Limits::default()).is_err()); + } + let mut bad = block; + bad[4..8].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(read(&bad, Limits::default()).is_err()); +} + +#[test] +fn explicit_limits_and_pascal_length_are_not_silently_truncated() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let block = write(&[&record], Limits::default()).unwrap(); + assert!(read(&block, Limits { records: 0, ..Limits::default() }).is_err()); + assert!(read(&block, Limits { bytes: block.len() - 1, ..Limits::default() }).is_err()); + assert!(write(&[&record], Limits { records: 0, ..Limits::default() }).is_err()); + assert!(write_text(¬e(), Limits { bytes: record.len() - 1, ..Limits::default() }).is_err()); + let long = [0; 256]; + let mut text = note(); + text.author = &long; + assert!(write_text(&text, Limits::default()).is_err()); +} + +#[test] +fn preserves_legacy_version_and_unused_data_header_acceptance() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let mut block = write(&[&record], Limits::default()).unwrap(); + block[..4].copy_from_slice(&[0, 9, 0, 8]); + block.extend_from_slice(b"trailing"); + assert_eq!(read(&block, Limits::default()).unwrap()[0].raw(), record); +} + +#[test] +fn canonical_layout_matches_the_existing_photocraft_writer() { + // PhotoCraft annotations_map::write_note layout (Brandon Thomas, aa87012a). + // App RGB/position/text conversion happens before this shared wire writer. + let n = note(); + let mut expected = vec![0, 0, 0, 0]; + expected.extend_from_slice(b"txtA"); + expected.extend_from_slice(&[1, 0x1c, 0, 1]); + for value in [10i32, 20, 30, 36, 30, 40, 190, 280] { + expected.extend_from_slice(&value.to_be_bytes()); + } + for value in [0u16, 65535, 1000, 3000, 0] { + expected.extend_from_slice(&value.to_be_bytes()); + } + expected.extend_from_slice(b"\x06Writer\x00\x00\x00\x042026\x00"); + expected.extend_from_slice(&20u32.to_be_bytes()); + expected.extend_from_slice(b"txtC"); + expected.extend_from_slice(&8u32.to_be_bytes()); + expected.extend_from_slice(n.data); + let len = expected.len() as u32; + expected[..4].copy_from_slice(&len.to_be_bytes()); + assert_eq!(write_text(&n, Limits::default()).unwrap(), expected); +} diff --git a/crates/psd/src/displace_map.rs b/crates/psd/src/displace_map.rs new file mode 100644 index 0000000000..fbe8a73328 --- /dev/null +++ b/crates/psd/src/displace_map.rs @@ -0,0 +1,116 @@ +//! Bounded two-plane PSD Displace (`DspD`) payloads. +//! App filter settings, image conversion and external-path policy belong to the caller. +//! Ported from PhotoCraft `crates/io/src/displace_map.rs` (MIT/Apache-2.0). + +const HEADER: usize = 10; +const MODE_TWO_PLANES: u16 = 3; +/// Maximum supported decoded pixel count (8K by 8K). +pub const MAX_MAP_PIXELS: usize = 1 << 26; + +/// A parsed embedded map: size and the two 8-bit planes (borrowed from the blob). +#[derive(Debug, PartialEq)] +pub struct EmbeddedMap<'a> { + /// Width in pixels. + pub width: usize, + /// Height in pixels. + pub height: usize, + /// Horizontal displacement samples. + pub horizontal: &'a [u8], + /// Vertical displacement samples. + pub vertical: &'a [u8], +} + +/// Parses an embedded displacement map; `None` for any other mode, a zero or oversized map, or a +/// blob shorter than the header plus both planes. +pub fn parse_map(data: &[u8]) -> Option> { + let u32_at = |i: usize| Some(u32::from_le_bytes(data.get(i..i + 4)?.try_into().ok()?)); + let height = usize::try_from(u32_at(0)?).ok()?; + let width = usize::try_from(u32_at(4)?).ok()?; + let mode = u16::from_le_bytes(data.get(8..HEADER)?.try_into().ok()?); + let n = width.checked_mul(height)?; + if mode != MODE_TWO_PLANES || n == 0 || n > MAX_MAP_PIXELS { + return None; + } + let horizontal = data.get(HEADER..HEADER.checked_add(n)?)?; + let vertical = data.get(HEADER + n..HEADER.checked_add(n.checked_mul(2)?)?)?; + Some(EmbeddedMap { width, height, horizontal, vertical }) +} + +/// Writes a mode-3 payload from exact-sized 8-bit planes, without padding. +/// Returns `None` for empty/oversized dimensions, mismatched planes or allocation failure. +/// Callers retain their own (possibly lower) embedding and image-conversion budgets. +pub fn write_map(width: usize, height: usize, horizontal: &[u8], vertical: &[u8]) -> Option> { + write_map_iter(width, height, horizontal.iter().copied(), vertical.iter().copied()) +} + +/// Writes exact-sized sample iterators without allocating intermediate planes. +/// Iterators must terminate after exactly width times height samples; extra or missing +/// samples are rejected. At most that many samples plus one are consumed per plane. +pub fn write_map_iter( + width: usize, + height: usize, + mut horizontal: impl Iterator, + mut vertical: impl Iterator, +) -> Option> { + let n = width.checked_mul(height)?; + if n == 0 || n > MAX_MAP_PIXELS { + return None; + } + let width = u32::try_from(width).ok()?; + let height = u32::try_from(height).ok()?; + let len = HEADER.checked_add(n.checked_mul(2)?)?; + let mut out = Vec::new(); + out.try_reserve_exact(len).ok()?; + out.extend_from_slice(&height.to_le_bytes()); + out.extend_from_slice(&width.to_le_bytes()); + out.extend_from_slice(&MODE_TWO_PLANES.to_le_bytes()); + for samples in [&mut horizontal as &mut dyn Iterator, &mut vertical] { + for _ in 0..n { + out.push(samples.next()?); + } + if samples.next().is_some() { + return None; + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_planes_roundtrip_and_padding_is_ignored() { + let mut bytes = write_map(2, 1, &[0, 255], &[128, 64]).unwrap(); + assert_eq!(bytes, [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 255, 128, 64]); + bytes.extend_from_slice(&[99, 88]); + let m = parse_map(&bytes).unwrap(); + assert_eq!((m.width, m.height), (2, 1)); + assert_eq!(m.horizontal, &[0, 255]); + assert_eq!(m.vertical, &[128, 64]); + } + + #[test] + fn truncated_unsupported_and_overflow_are_rejected() { + let bytes = write_map(2, 1, &[0, 255], &[128, 64]).unwrap(); + for end in 0..bytes.len() { + assert!(parse_map(&bytes[..end]).is_none()); + } + let mut invalid = bytes.clone(); + invalid[8] = 4; + assert!(parse_map(&invalid).is_none()); + invalid[8] = 3; + invalid[..8].fill(255); + assert!(parse_map(&invalid).is_none()); + invalid[..8].fill(0); + assert!(parse_map(&invalid).is_none()); + invalid[..4].copy_from_slice(&1u32.to_le_bytes()); + invalid[4..8].copy_from_slice(&((MAX_MAP_PIXELS + 1) as u32).to_le_bytes()); + assert!(parse_map(&invalid).is_none()); + assert!(write_map_iter(2, 1, std::iter::repeat(0), std::iter::repeat(0)).is_none()); + assert!(write_map(usize::MAX, 2, &[], &[]).is_none()); + assert!(write_map(MAX_MAP_PIXELS + 1, 1, &[], &[]).is_none()); + assert!(write_map(2, 1, &[0], &[0, 0]).is_none()); + assert!(write_map(2, 1, &[0, 0], &[0, 0, 0]).is_none()); + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 93acd5f396..acd3c8853e 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -54,6 +54,7 @@ pub mod aco; pub mod act; pub mod adjust; pub mod animation; +pub mod annotations; pub mod ase; pub mod asl; pub mod atn; @@ -63,6 +64,7 @@ mod codepage; pub mod compression; pub mod csh; pub mod descriptor; +pub mod displace_map; pub mod engine_data; pub mod error; pub mod file; diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index a8f778ccd0..a2195bf5da 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -470,6 +470,55 @@ fn linked_file(item: &[u8], at: usize) -> Result { Ok(out) } +/// Header of an embedded (`liFD`) linked-layer item, without reading its payload. +/// Offsets are relative to the item (not its enclosing eight-byte length field). +/// A deferred reader can supply just the header, then validate the payload range +/// against the full record length before reading those bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EmbeddedFileHeader { + /// Lossy UTF-8 identifier, matching Photoshop metadata display semantics. + pub uuid: String, + /// Lossy UTF-16 filename with trailing NULs removed. + pub name: String, + /// Start of the payload within the item. + pub data_offset: usize, + /// Declared payload length; the payload need not be resident. + pub data_len: usize, +} + +impl EmbeddedFileHeader { + /// Borrow the payload only when the supplied complete item contains it. + pub fn payload<'a>(&self, item: &'a [u8]) -> Option<&'a [u8]> { + item.get(self.data_offset..self.data_offset.checked_add(self.data_len)?) + } +} + +/// Read an embedded item's header from a possibly partial/deferred item buffer. +/// This deliberately does not require its declared payload to be present. A malformed +/// header or a non-embedded item is an error, not an empty embedded file. Callers walking +/// framed records may continue to the next record after such an error. +/// Ported from PhotoCraft's linked-item reader; record versions remain forward-compatible. +pub fn embedded_file_header(item: &[u8]) -> Result { + let mut r = Reader::new(item); + let kind = r.array::<4>()?; + let _version = r.u32()?; + let uuid = String::from_utf8_lossy(&read_pascal(&mut r, 1)?).into_owned(); + // A filename is metadata, never an unbounded allocation. Check before decoding. + if r.clone().u32()? > 32_768 { + return Err(PsdError::LimitExceeded("linked filename exceeds 32768 UTF-16 units")); + } + let name = UnicodeString::read(&mut r)?.to_string_lossy(); + r.skip(8)?; // file type and creator + let data_len = usize::try_from(r.u64()?).map_err(|_| PsdError::LimitExceeded("linked payload exceeds address space"))?; + if r.u8()? != 0 { + crate::descriptor::VersionedDescriptor::read(&mut r)?; + } + if kind != *b"liFD" { + return Err(PsdError::invalid("linked item is not embedded")); + } + Ok(EmbeddedFileHeader { uuid, name, data_offset: r.pos(), data_len }) +} + /// The four-character file type Photoshop records for an embedded file, from its first bytes: /// `8BPS` (`8BPB` for a PSB), `PNGf`, `JPEG`, `TIFF`, `GIFf`, or four spaces. pub fn file_type(bytes: &[u8]) -> [u8; 4] { @@ -519,7 +568,29 @@ pub struct LinkedRecord<'a> { pub raw: &'a [u8], } -impl LinkedRecord<'_> { +impl<'a> LinkedRecord<'a> { + /// The complete item, excluding framing and padding; absent for a damaged tail. + pub fn item(&self) -> Option<&'a [u8]> { + framed_record(self.raw).map(|(item, _)| item) + } + + /// Copy this complete record under a new ID, leaving the payload byte-identical. + /// Selection policy belongs to the caller; malformed tails cannot be copied. + pub fn copy_with_uuid(&self, new_uuid: &str) -> Option> { + let item = self.item()?; + let old_end = 9usize.checked_add(usize::from(*item.get(8)?))?; + let new_len = u8::try_from(new_uuid.len()).ok()?; + let mut copy = item.get(..8)?.to_vec(); + copy.push(new_len); + copy.extend_from_slice(new_uuid.as_bytes()); + copy.extend_from_slice(item.get(old_end..)?); + let mut out = Vec::with_capacity(copy.len() + 11); + out.put_u64(copy.len() as u64); + out.extend(copy); + out.resize(out.len().next_multiple_of(4), 0); + Some(out) + } + /// The unique id as text, when it is readable and valid UTF-8. pub fn uuid_str(&self) -> Option<&str> { std::str::from_utf8(self.uuid?).ok() @@ -545,17 +616,26 @@ fn record_uuid(item: &[u8]) -> Option<&[u8]> { /// The records of a linked layer block's data, in order, each with its unique id when its header /// is readable. A tail that is no complete record is returned as one record without an id. pub fn linked_records(data: &[u8]) -> Vec> { - let mut out = Vec::new(); + iter_linked_records(data).collect() +} + +/// Stream the same raw views as [`linked_records`] without allocating a record list. +/// Complete frames with malformed inner headers do not hide subsequent frames; +/// an incomplete tail is yielded once with no identifier. +pub fn iter_linked_records(data: &[u8]) -> impl Iterator> { let mut rest = data; - while !rest.is_empty() { + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } let Some((item, raw)) = framed_record(rest) else { - out.push(LinkedRecord { uuid: None, raw: rest }); - break; + let tail = rest; + rest = &[]; + return Some(LinkedRecord { uuid: None, raw: tail }); }; - out.push(LinkedRecord { uuid: record_uuid(item), raw }); rest = rest.get(raw.len()..).unwrap_or_default(); - } - out + Some(LinkedRecord { uuid: record_uuid(item), raw }) + }) } /// The unique ids of every record of a linked layer block's data that has a readable one. @@ -653,18 +733,7 @@ pub fn contains_linked_record(data: &[u8], record: &[u8]) -> bool { /// field and padding; the rest of the record (embedded, external or alias data) is kept. pub fn copy_linked_record(data: &[u8], uuid: &str, new_uuid: &str) -> Option> { let record = linked_records(data).into_iter().find(|r| r.uuid == Some(uuid.as_bytes()))?; - let (item, _) = framed_record(record.raw)?; - let old_end = 9usize.checked_add(usize::from(*item.get(8)?))?; - let new_len = u8::try_from(new_uuid.len()).ok()?; - let mut copy = item.get(..8)?.to_vec(); - copy.push(new_len); - copy.extend_from_slice(new_uuid.as_bytes()); - copy.extend_from_slice(item.get(old_end..)?); - let mut out = Vec::with_capacity(copy.len() + 11); - out.put_u64(copy.len() as u64); - out.extend(copy); - out.resize(out.len().next_multiple_of(4), 0); - Some(out) + record.copy_with_uuid(new_uuid) } impl PsdFile { @@ -1111,3 +1180,57 @@ mod tests { assert!(u64::from(w) * u64::from(h) <= MAX_BAKE_PIXELS); } } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod embedded_header_tests { + use super::*; + + #[test] + fn headers_do_not_require_resident_payload() { + let data = encode_embedded_file("id", "a.psd", b"payload"); + let record = iter_linked_records(&data).next().unwrap(); + let item = record.item().unwrap(); + let header = embedded_file_header(item).unwrap(); + assert_eq!(header.uuid, "id"); + assert_eq!(header.name, "a.psd"); + assert_eq!(header.payload(item), Some(&b"payload"[..])); + assert_eq!(embedded_file_header(&item[..header.data_offset]).unwrap(), header); + assert_eq!(header.payload(&item[..header.data_offset]), None); + for n in 0..header.data_offset { + assert!(embedded_file_header(&item[..n]).is_err()); + } + } + + #[test] + fn filename_limits_and_lossy_metadata_are_preserved() { + let data = encode_embedded_file("x", &"a".repeat(32767), b""); + let item = iter_linked_records(&data).next().unwrap().item().unwrap(); + assert_eq!(embedded_file_header(item).unwrap().name.len(), 32767); + let data = encode_embedded_file("x", &"a".repeat(32768), b""); + assert!(embedded_file_header(iter_linked_records(&data).next().unwrap().item().unwrap()).is_err()); + let data = encode_embedded_file("x", "y", b"payload"); + let mut item = iter_linked_records(&data).next().unwrap().item().unwrap().to_vec(); + item[9] = 0xff; + item[14..16].copy_from_slice(&0xd800u16.to_be_bytes()); + let h = embedded_file_header(&item).unwrap(); + assert_eq!(h.uuid, "\u{fffd}"); + assert_eq!(h.name, "\u{fffd}"); + item[0..4].copy_from_slice(b"liFE"); + assert!(embedded_file_header(&item).is_err()); + } + + #[test] + fn malformed_inner_records_do_not_hide_later_files() { + let mut data = vec![0; 8]; // A complete empty item, not a truncated frame. + data.extend(encode_embedded_file("wanted", "x", b"ok")); + data.extend([1, 2, 3]); // Incomplete tail retained, never interpreted as an item. + let records: Vec<_> = iter_linked_records(&data).collect(); + assert_eq!(records, linked_records(&data)); + assert!(embedded_file_header(records[0].item().unwrap()).is_err()); + let item = records[1].item().unwrap(); + assert_eq!(embedded_file_header(item).unwrap().payload(item), Some(&b"ok"[..])); + assert_eq!(records[2].item(), None); + assert_eq!(records[2].raw, &[1, 2, 3]); + } +} diff --git a/crates/raster-codecs/Cargo.toml b/crates/raster-codecs/Cargo.toml index 002012b807..50bb61de8d 100644 --- a/crates/raster-codecs/Cargo.toml +++ b/crates/raster-codecs/Cargo.toml @@ -15,7 +15,3 @@ base64 = "0.23" craft-image-codecs = { workspace = true } thiserror = { workspace = true } image = { version = "0.25", default-features = false } - -# The DDS encoder compresses rows of blocks in parallel on native; wasm stays single-threaded. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -rayon = { workspace = true } diff --git a/crates/raster-codecs/README.md b/crates/raster-codecs/README.md index 6735769ae1..907e73763a 100644 --- a/crates/raster-codecs/README.md +++ b/crates/raster-codecs/README.md @@ -1,12 +1,9 @@ # craft-raster-codecs -Small raster image formats for the Craft apps, from PhotoCraft's `photocraft-codecs`: one module -per format, one implementation of each. Decoders take untrusted bytes and `Limits`, check the -declared size before allocating, and never panic. No `unsafe`; it builds for -`wasm32-unknown-unknown`. The `common` RGBA image facade delegates PNG/JPEG/BMP/GIF/TIFF/WebP -decoding and PNG/JPEG encoding to [`craft-image-codecs`](../image-codecs/README.md), the shared -depth- and metadata-preserving codec implementation. Other dependencies are `thiserror`, and -`rayon` on native targets (the DDS encoder compresses rows of blocks in parallel). +Compatibility facade for the small raster-format modules in older Craft app versions. The +format readers and writers are implemented once in [`craft-image-codecs`](../image-codecs/README.md); +these modules forward calls and adapt the older `Image` and `Limits` types. The `common` RGBA +image facade also delegates to that crate. ```toml craft-raster-codecs = { git = "https://github.com/storytold/craft-libs", rev = "" } @@ -37,9 +34,8 @@ assert_eq!(image.data(), &[0, 255]); let bytes = pnm::encode(&image)?; ``` -Each module has a `looks_like_*` (or `is_dicom`) sniffer for the format's signature. `dds` and -`fits` also have `has_additional_images`, which says without decoding whether a file holds -more than the one image `decode` returns (cube faces, array slices, further HDUs). +The module sniffers and the `dds`/`fits` additional-image queries forward to shared detection and +metadata inspection in `craft-image-codecs`. `xpm::x11_color_rgb` also looks up exact normalized X11 names as RGB channels in `0..=1`. It accepts only 1–64 lowercase ASCII letters or digits, without normalization, XPM-only aliases, diff --git a/crates/raster-codecs/src/bridge.rs b/crates/raster-codecs/src/bridge.rs new file mode 100644 index 0000000000..a1bd061db5 --- /dev/null +++ b/crates/raster-codecs/src/bridge.rs @@ -0,0 +1,79 @@ +//! Compatibility between this crate's small-format facade and the canonical image codec model. + +use crate::{ChannelLayout, CodecError, DecodeWarning, Image, Limits, SampleType}; +use craft_image_codecs::{DecodeOptions, Format, Metadata}; + +pub(crate) fn format(format: Format, bytes: &[u8], limits: &Limits) -> Result { + let shared_limits = craft_image_codecs::Limits::new(limits.max_width, limits.max_height, limits.max_pixels, limits.max_alloc); + let options = DecodeOptions { limits: shared_limits, ..DecodeOptions::default() }; + let image = craft_image_codecs::decode_as_with(format, bytes, &options).map_err(from_shared_error)?; + from_shared_image(image) +} + +pub(crate) fn shared_image(image: &Image) -> Result { + let layout = match image.layout() { + ChannelLayout::Gray => craft_image_codecs::ChannelLayout::Gray, + ChannelLayout::GrayA => craft_image_codecs::ChannelLayout::GrayA, + ChannelLayout::Rgb => craft_image_codecs::ChannelLayout::Rgb, + ChannelLayout::Rgba => craft_image_codecs::ChannelLayout::Rgba, + ChannelLayout::Cmyk => craft_image_codecs::ChannelLayout::Cmyk, + ChannelLayout::CmykA => craft_image_codecs::ChannelLayout::CmykA, + }; + let sample = match image.sample_type() { + SampleType::U8 => craft_image_codecs::SampleType::U8, + SampleType::U16 => craft_image_codecs::SampleType::U16, + SampleType::F32 => craft_image_codecs::SampleType::F32, + }; + let meta = Metadata { dpi: image.dpi, text: image.text.clone(), ..Metadata::default() }; + craft_image_codecs::Image::from_raw(image.width(), image.height(), layout, sample, image.data().to_vec()) + .map(|image| image.with_meta(meta)) + .map_err(from_shared_error) +} + +fn from_shared_image(image: craft_image_codecs::Image) -> Result { + let layout = match image.layout() { + craft_image_codecs::ChannelLayout::Gray => ChannelLayout::Gray, + craft_image_codecs::ChannelLayout::GrayA => ChannelLayout::GrayA, + craft_image_codecs::ChannelLayout::Rgb => ChannelLayout::Rgb, + craft_image_codecs::ChannelLayout::Rgba => ChannelLayout::Rgba, + craft_image_codecs::ChannelLayout::Cmyk => ChannelLayout::Cmyk, + craft_image_codecs::ChannelLayout::CmykA => ChannelLayout::CmykA, + _ => return Err(CodecError::InvalidImage(format!("unsupported small-codec layout {:?}", image.layout()))), + }; + let sample = match image.sample_type() { + craft_image_codecs::SampleType::U8 => SampleType::U8, + craft_image_codecs::SampleType::U16 => SampleType::U16, + craft_image_codecs::SampleType::F32 => SampleType::F32, + _ => return Err(CodecError::InvalidImage(format!("unsupported small-codec sample type {:?}", image.sample_type()))), + }; + let mut out = Image::from_raw(image.width(), image.height(), layout, sample, image.data().to_vec())?; + out.dpi = image.meta.dpi; + out.text = image.meta.text; + out.warnings = image + .warnings + .into_iter() + .filter_map(|warning| match warning { + craft_image_codecs::DecodeWarning::MorePages { total } | craft_image_codecs::DecodeWarning::MoreParts { total } => { + Some(DecodeWarning::MorePages { total }) + } + _ => None, + }) + .collect(); + Ok(out) +} + +pub(crate) fn from_shared_error(error: craft_image_codecs::CodecError) -> CodecError { + match error { + craft_image_codecs::CodecError::UnknownFormat => CodecError::unsupported("image", "unrecognized image format"), + craft_image_codecs::CodecError::Unsupported { format, reason } => CodecError::unsupported(format.name(), reason), + craft_image_codecs::CodecError::Malformed { format, message } => CodecError::malformed(format.name(), message), + craft_image_codecs::CodecError::LimitExceeded(message) => CodecError::LimitExceeded(message), + craft_image_codecs::CodecError::Encode { format, message } => CodecError::Encode { format: format.name(), message }, + craft_image_codecs::CodecError::InvalidImage(message) => CodecError::InvalidImage(message), + } +} + +pub(crate) fn encode(image: &Image, format: Format, options: &craft_image_codecs::EncodeOptions) -> Result, CodecError> { + let image = shared_image(image)?; + craft_image_codecs::encode(&image, format, options).map_err(from_shared_error) +} diff --git a/crates/raster-codecs/src/dds.rs b/crates/raster-codecs/src/dds.rs index 1249cb5b77..eb703a0744 100644 --- a/crates/raster-codecs/src/dds.rs +++ b/crates/raster-codecs/src/dds.rs @@ -1,616 +1,75 @@ -//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", -//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). -//! -//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel -//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 -//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume -//! textures are refused rather than flattened to one face or slice. -//! -//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or -//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these, -//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written. +//! DDS compatibility facade; implementation and BC block codecs live in craft-image-codecs. +use crate::{CodecError, Image, Limits, SampleType, bridge}; +use craft_image_codecs::Format; -use std::borrow::Cow; - -use crate::dds_bc::{self, Block, Mask}; -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -/// `DDS ` plus the 124-byte DDS_HEADER. -const HEADER: usize = 128; -/// DDS_HEADER_DXT10, present when the FourCC is `DX10`. -const DX10_HEADER: usize = 20; - -const DDSD_DEPTH: u32 = 0x80_0000; -const DDPF_ALPHAPIXELS: u32 = 0x1; -const DDPF_FOURCC: u32 = 0x4; -const DDPF_RGB: u32 = 0x40; -const DDPF_LUMINANCE: u32 = 0x2_0000; -const DDSCAPS2_CUBEMAP: u32 = 0x200; -const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; -const DDSCAPS2_VOLUME: u32 = 0x20_0000; -const DIMENSION_TEXTURE2D: u32 = 3; -const MISC_TEXTURECUBE: u32 = 0x4; - -fn bad(reason: impl std::fmt::Display) -> CodecError { - CodecError::malformed("DDS", reason) +pub fn looks_like_dds(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Dds) } -fn unsupported(reason: impl Into) -> CodecError { - CodecError::unsupported("DDS", reason) -} -fn le32(b: &[u8], at: usize) -> Result { - let bytes = b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or_else(|| bad("truncated header"))?; - Ok(u32::from_le_bytes(bytes)) -} - -/// The `DDS ` magic. -pub fn looks_like_dds(b: &[u8]) -> bool { - b.starts_with(b"DDS ") -} - -/// Header-declared extra subresources cannot survive a single-image rewrite, even without presence flags. pub fn has_additional_images(bytes: &[u8]) -> Result { - let depth = le32(bytes, 24)?; - let mips = le32(bytes, 28)?; - let faces = (le32(bytes, 112)? & DDSCAPS2_CUBEMAP_FACES).count_ones(); - let dx10 = le32(bytes, 80)? & DDPF_FOURCC != 0 && bytes.get(84..88) == Some(b"DX10"); - let (cube, array) = if dx10 { (le32(bytes, 136)? & MISC_TEXTURECUBE != 0, le32(bytes, 140)?) } else { (false, 0) }; - Ok(depth > 1 || mips > 1 || faces > 1 || cube || array > 1) + craft_image_codecs::has_unretained_source_data(bytes).map_err(bridge::from_shared_error) +} +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + bridge::format(Format::Dds, bytes, limits) } -/// A FourCC as text when it is printable, else as the number legacy writers store there. -fn fourcc_name(fourcc: u32) -> String { - let bytes = fourcc.to_le_bytes(); - if bytes.iter().all(|c| c.is_ascii_graphic() || *c == b' ') { bytes.iter().map(|&c| char::from(c)).collect() } else { fourcc.to_string() } -} - -/// One channel of an uncompressed pixel: where it sits and its largest value. -#[derive(Clone, Copy)] -struct Field { - shift: u32, - max: u32, -} - -impl Field { - /// `None` for an empty mask; an error for one with gaps or wider than the pixel. - fn new(mask: u32, bits: u32) -> Result, CodecError> { - if mask == 0 { - return Ok(None); - } - let shift = mask.trailing_zeros(); - let max = mask >> shift; - if max & max.wrapping_add(1) != 0 || (bits < 32 && mask >> bits != 0) { - return Err(bad(format!("channel mask {mask:#x} is not a contiguous field of a {bits}-bit pixel"))); - } - Ok(Some(Field { shift, max })) - } - - fn get(self, pixel: u32) -> u8 { - let v = u64::from((pixel >> self.shift) & self.max); - let max = u64::from(self.max); - ((v * 255 + max / 2) / max) as u8 - } -} - -enum Encoding { - /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. - Masks { - bytes: usize, - gray: bool, - fields: [Option; 4], - }, - Bc1, - Bc2, - Bc3, -} - -impl Encoding { - fn masks(bits: u32, masks: [u32; 4], gray: bool) -> Result { - if !matches!(bits, 8 | 16 | 24 | 32) { - return Err(bad(format!("{bits} bits per pixel is not 8, 16, 24 or 32"))); - } - let mut fields = [None; 4]; - for (field, mask) in fields.iter_mut().zip(masks) { - *field = Field::new(mask, bits)?; - } - let colour = if gray { fields[0].is_some() } else { fields[..3].iter().any(Option::is_some) }; - if !colour { - return Err(bad("the pixel format has no colour channel masks")); - } - Ok(Encoding::Masks { bytes: bits as usize / 8, gray, fields }) - } - - fn layout(&self) -> ChannelLayout { - match self { - Encoding::Masks { gray: true, fields, .. } if fields[3].is_some() => ChannelLayout::GrayA, - Encoding::Masks { gray: true, .. } => ChannelLayout::Gray, - Encoding::Masks { fields, .. } if fields[3].is_none() => ChannelLayout::Rgb, - _ => ChannelLayout::Rgba, - } - } - - /// Stored row stride and byte size of the top mip level (block rows for BC). - fn level_layout(&self, width: u32, height: u32, pitch: Option) -> Result<(usize, usize), CodecError> { - let overflow = || bad("pixel data size overflow"); - let (w, h) = (usize::try_from(width).map_err(|_| overflow())?, usize::try_from(height).map_err(|_| overflow())?); - let (row_bytes, rows) = match self { - Encoding::Masks { bytes, .. } => { - let packed = w.checked_mul(*bytes).ok_or_else(overflow)?; - let row_bytes = match pitch { - Some(pitch) => usize::try_from(pitch).map_err(|_| overflow())?, - None => packed, - }; - if row_bytes < packed { - return Err(bad(format!("row pitch {row_bytes} is smaller than the {packed}-byte pixel row"))); - } - (row_bytes, h) - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block = if matches!(self, Encoding::Bc1) { 8 } else { 16 }; - (w.div_ceil(4).checked_mul(block).ok_or_else(overflow)?, h.div_ceil(4)) - } - }; - let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; - Ok((row_bytes, size)) - } -} - -/// The legacy pixel format: a FourCC, or channel masks. -fn legacy_encoding(b: &[u8]) -> Result { - let (flags, fourcc, bits) = (le32(b, 80)?, le32(b, 84)?, le32(b, 88)?); - let alpha = if flags & DDPF_ALPHAPIXELS != 0 { le32(b, 104)? } else { 0 }; - if flags & DDPF_FOURCC != 0 { - return match &fourcc.to_le_bytes() { - b"DXT1" => Ok(Encoding::Bc1), - b"DXT3" => Ok(Encoding::Bc2), - b"DXT5" => Ok(Encoding::Bc3), - b"DXT2" | b"DXT4" => Err(unsupported("premultiplied-alpha DXT2/DXT4 textures are not supported")), - _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3 and DXT5 are)", fourcc_name(fourcc)))), - }; - } - if flags & DDPF_RGB != 0 { - return Encoding::masks(bits, [le32(b, 92)?, le32(b, 96)?, le32(b, 100)?, alpha], false); - } - if flags & DDPF_LUMINANCE != 0 { - return Encoding::masks(bits, [le32(b, 92)?, 0, 0, alpha], true); - } - Err(unsupported(format!("pixel format flags {flags:#x} are not RGB, luminance or a supported compression"))) -} - -/// The DX10 header's DXGI format, refusing anything but a single 2D texture. -fn dx10_encoding(b: &[u8]) -> Result { - let (dxgi, dimension, misc, array) = (le32(b, HEADER)?, le32(b, HEADER + 4)?, le32(b, HEADER + 8)?, le32(b, HEADER + 12)?); - if misc & MISC_TEXTURECUBE != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if dimension != DIMENSION_TEXTURE2D { - return Err(unsupported(format!("only 2D textures are supported (resource dimension {dimension})"))); - } - if array > 1 { - return Err(unsupported(format!("texture arrays are not supported ({array} textures)"))); - } - const RGBA: [u32; 4] = [0xff, 0xff00, 0xff_0000, 0xff00_0000]; - const BGRA: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0xff00_0000]; - const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; - match dxgi { - 27..=29 => Encoding::masks(32, RGBA, false), - 87 | 90 | 91 => Encoding::masks(32, BGRA, false), - 88 | 92 | 93 => Encoding::masks(32, BGRX, false), - 70..=72 => Ok(Encoding::Bc1), - 73..=75 => Ok(Encoding::Bc2), - 76..=78 => Ok(Encoding::Bc3), - _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1, BC2, BC3 and 8-bit RGBA or BGRA are)"))), - } -} - -pub fn decode(b: &[u8], limits: &Limits) -> Result { - if !b.starts_with(b"DDS ") { - return Err(bad("missing the `DDS ` signature")); - } - if le32(b, 4)? != 124 { - return Err(bad("header size is not 124")); - } - let (flags, height, width, depth, caps2) = (le32(b, 8)?, le32(b, 12)?, le32(b, 16)?, le32(b, 24)?, le32(b, 112)?); - if caps2 & DDSCAPS2_CUBEMAP != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if caps2 & DDSCAPS2_VOLUME != 0 || (flags & DDSD_DEPTH != 0 && depth > 1) { - return Err(unsupported("volume textures are not supported")); - } - let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; - let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; - let layout = encoding.layout(); - limits.check(width, height, layout, SampleType::U8)?; - // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. - let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; - let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; - let data = b.get(start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; - let (w, h) = (width as usize, height as usize); - let channels = layout.channels(); - let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; - let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = vec![0u8; total]; - match encoding { - Encoding::Masks { bytes, gray, fields } => { - for (src_row, dst_row) in data.chunks_exact(row_pitch).zip(pixels.chunks_exact_mut(row_size)) { - // Stop at the output width, leaving any stored row padding unread. - for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { - let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); - let channel = |i: usize| fields[i].map_or(0, |f| f.get(pixel)); - let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; - dst.copy_from_slice(&values[..channels]); - } - } - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block_size = if matches!(encoding, Encoding::Bc1) { 8 } else { 16 }; - let blocks_x = w.div_ceil(4); - for (i, block) in data.chunks_exact(block_size).enumerate() { - let texels = match encoding { - Encoding::Bc1 => bc1(block, true), - Encoding::Bc2 => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc2_alpha(block)), - _ => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc3_alpha(block)), - }; - let (bx, by) = ((i % blocks_x) * 4, (i / blocks_x) * 4); - for (t, texel) in texels.iter().enumerate() { - let (x, y) = (bx + t % 4, by + t / 4); - if x < w && y < h { - let at = (y * w + x) * 4; - if let Some(dst) = pixels.get_mut(at..at + 4) { - dst.copy_from_slice(texel); - } - } - } - } - } - } - Image::from_u8(width, height, layout, pixels) -} - -/// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's -/// `c0 <= c1` order selects three colours and transparent black. -fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); - let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); - let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) -} - -/// BC2: four explicit bits of alpha per texel. -fn bc2_alpha(block: &[u8]) -> [u8; 16] { - let bits = u64::from_le_bytes(std::array::from_fn(|i| block.get(i).copied().unwrap_or(0))); - std::array::from_fn(|t| ((bits >> (4 * t)) & 0xf) as u8 * 17) -} - -/// BC3: two alpha endpoints and a 3-bit index per texel into eight values, or into six plus -/// 0 and 255 when `a0 <= a1`. -fn bc3_alpha(block: &[u8]) -> [u8; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let palette = dds_bc::alpha_palette(byte(0), byte(1)); - let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); - std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) -} - -fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { - for (texel, a) in texels.iter_mut().zip(alpha) { - texel[3] = a; - } - texels -} - -const DDSD_CAPS: u32 = 0x1; -const DDSD_HEIGHT: u32 = 0x2; -const DDSD_WIDTH: u32 = 0x4; -const DDSD_PITCH: u32 = 0x8; -const DDSD_PIXELFORMAT: u32 = 0x1000; -const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; -const DDSD_LINEARSIZE: u32 = 0x8_0000; -const DDSCAPS_COMPLEX: u32 = 0x8; -const DDSCAPS_TEXTURE: u32 = 0x1000; -const DDSCAPS_MIPMAP: u32 = 0x40_0000; - -fn encode_err(reason: impl std::fmt::Display) -> CodecError { - CodecError::encode("DDS", reason) -} - -/// How a written texture stores its pixels. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Store { - /// 8-bit luminance. - Luminance, - /// 8-bit luminance, then 8-bit alpha. - LuminanceAlpha, - /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for - /// alpha still sees an opaque texture). - Bgrx, - Bgra, - Bc1, - Bc2, - Bc3, -} - -impl Store { - /// The storage for an image of `layout`. - fn new(compression: DdsCompression, layout: ChannelLayout) -> Result { - Ok(match (compression, layout) { - (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance, - (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha, - (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx, - (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra, - (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1, - (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2, - (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3, - (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), - }) - } - - /// Bytes per pixel, or per 4×4 block for a block compression. - fn unit(self) -> usize { - match self { - Store::Luminance => 1, - Store::LuminanceAlpha => 2, - Store::Bgrx | Store::Bgra => 4, - Store::Bc1 => 8, - Store::Bc2 | Store::Bc3 => 16, - } - } - - fn is_block(self) -> bool { - matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3) - } - - /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. - fn row_bytes(self, width: usize) -> Option { - if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } - } - - fn level_bytes(self, width: usize, height: usize) -> Option { - let rows = if self.is_block() { height.div_ceil(4) } else { height }; - self.row_bytes(width)?.checked_mul(rows) - } - - /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. - fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { - match self { - Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), - Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), - Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), - Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), - Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), - Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), - Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), - } - } -} - -/// Levels in a full mip chain: the larger side halves down to 1. -fn mip_levels(width: u32, height: u32) -> u32 { - 32 - width.max(height).max(1).leading_zeros() -} - -fn half((w, h): (usize, usize)) -> (usize, usize) { - ((w / 2).max(1), (h / 2).max(1)) -} - -/// How a DDS texture stores its pixels. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum DdsCompression { - /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or - /// without alpha for grayscale. Lossless. #[default] None, - /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become - /// transparent black. Bc1, - /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. Bc2, - /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. Bc3, } - impl DdsCompression { - pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; - - /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`. + pub const ALL: [Self; 4] = [Self::None, Self::Bc1, Self::Bc2, Self::Bc3]; pub fn name(self) -> &'static str { match self { - DdsCompression::None => "none", - DdsCompression::Bc1 => "bc1", - DdsCompression::Bc2 => "bc2", - DdsCompression::Bc3 => "bc3", + Self::None => "none", + Self::Bc1 => "bc1", + Self::Bc2 => "bc2", + Self::Bc3 => "bc3", } } - - /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`, - /// `dxt5`), in any case. Anything else is `None`. pub fn from_name(name: &str) -> Option { match name.to_ascii_lowercase().as_str() { - "none" => Some(DdsCompression::None), - "bc1" | "dxt1" => Some(DdsCompression::Bc1), - "bc2" | "dxt3" => Some(DdsCompression::Bc2), - "bc3" | "dxt5" => Some(DdsCompression::Bc3), + "none" => Some(Self::None), + "bc1" | "dxt1" => Some(Self::Bc1), + "bc2" | "dxt3" => Some(Self::Bc2), + "bc3" | "dxt5" => Some(Self::Bc3), _ => None, } } - - /// A block compression (lossy), not uncompressed pixels. pub fn is_block(self) -> bool { - self != DdsCompression::None + self != Self::None } } - -/// What a DDS file is written with. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct DdsOptions { pub compression: DdsCompression, - /// Write the full mip chain down to 1×1, each level a box filter of the one above. pub mipmaps: bool, } - -/// Writes `img` (8 bits per channel) as a DDS texture. Uncompressed stores gray, gray with -/// alpha, RGB and RGBA; the block compressions take RGBA only. -pub fn encode(img: &Image, opts: DdsOptions) -> Result, CodecError> { - if img.sample_type() != SampleType::U8 { - return Err(encode_err("DDS is written at 8 bits per channel")); +pub fn encode(image: &Image, options: DdsOptions) -> Result, CodecError> { + if image.sample_type() != SampleType::U8 { + return Err(CodecError::encode("DDS", "DDS is written at 8 bits per channel")); } - let pixels = img.data(); - let store = Store::new(opts.compression, img.layout())?; - let (width, height) = (img.width(), img.height()); - let levels = if opts.mipmaps { mip_levels(width, height) } else { 1 }; - let top = (width as usize, height as usize); - // Every level's size, checked before anything is allocated. - let mut sizes = Vec::new(); - let mut size = top; - for _ in 0..levels { - sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); - size = half(size); - } - let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; - let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; - let mut out = crate::alloc_zeroed::(total)?; - out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); - - let channels = img.layout().channels(); - let mut level = Cow::Borrowed(pixels); - let (mut size, mut at) = (top, HEADER); - for (i, &bytes) in sizes.iter().enumerate() { - let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; - write_level(store, &level, size, dst)?; - at += bytes; - if i + 1 < sizes.len() { - let next = half(size); - level = Cow::Owned(downsample(&level, size, next, channels)?); - size = next; - } - } - Ok(out) -} - -/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes. -fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> { - let mut b = [0u8; HEADER]; - let mut put = |at: usize, v: u32| { - if let Some(d) = b.get_mut(at..at + 4) { - d.copy_from_slice(&v.to_le_bytes()); - } + // BC storage encodes RGBA blocks. The generic image API can plan a + // conversion from other layouts, but this compatibility facade accepts + // only layouts its former writer stored directly. + let allowed = if options.compression.is_block() { + image.layout() == crate::ChannelLayout::Rgba + } else { + matches!(image.layout(), crate::ChannelLayout::Gray | crate::ChannelLayout::GrayA | crate::ChannelLayout::Rgb | crate::ChannelLayout::Rgba) }; - // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). - let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; - let pitch_or_size = pitch_or_size - .and_then(|v| u32::try_from(v).ok()) - .ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; - let mipmapped = levels > 1; - put(4, 124); - put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); - put(12, height); - put(16, width); - put(20, pitch_or_size); - put(28, levels); - let (flags, fourcc, bits, masks) = store.pixel_format(); - put(76, 32); - put(80, flags); - put(84, u32::from_le_bytes(fourcc)); - put(88, bits); - for (i, mask) in masks.into_iter().enumerate() { - put(92 + 4 * i, mask); + if !allowed { + return Err(CodecError::encode("DDS", format!("{:?} pixels can't be written as `{}`", image.layout(), options.compression.name()))); } - put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); - b[..4].copy_from_slice(b"DDS "); - Ok(b) -} - -/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets. -fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); - } - #[cfg(target_arch = "wasm32")] - for (i, row) in out.chunks_mut(len.max(1)).enumerate() { - f(i, row); - } -} - -/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. -fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> { - let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; - match store { - Store::Luminance | Store::LuminanceAlpha => { - // The image's gray (and alpha) samples, in the same order. - let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; - dst.copy_from_slice(src); - } - Store::Bgrx | Store::Bgra => { - let channels = if store == Store::Bgra { 4 } else { 3 }; - rows(dst, row_bytes, |y, row| { - let src = pixels.get(y * width * channels..).unwrap_or_default(); - for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { - let byte = |i: usize| s.get(i).copied().unwrap_or(255); - *d = [byte(2), byte(1), byte(0), byte(3)]; - } - }); - } - Store::Bc1 | Store::Bc2 | Store::Bc3 => { - let (texels, _) = pixels.as_chunks::<4>(); - rows(dst, row_bytes, |by, row| { - for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { - let (block, inside) = gather(texels, (width, height), bx, by); - let encoded: &[u8] = match store { - Store::Bc1 => &dds_bc::encode_bc1(&block, inside), - Store::Bc2 => &dds_bc::encode_bc2(&block, inside), - _ => &dds_bc::encode_bc3(&block, inside), - }; - for (d, s) in d.iter_mut().zip(encoded) { - *d = *s; - } - } - }); - } - } - Ok(()) -} - -/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. -fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { - let mut block = [[0u8; 4]; 16]; - let mut inside: Mask = 0; - for (t, texel) in block.iter_mut().enumerate() { - let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); - if x < width - && y < height - && let Some(p) = texels.get(y * width + x) - { - *texel = *p; - inside |= 1 << t; - } - } - (block, inside) -} - -/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or -/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. -fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, CodecError> { - let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; - let mut dst = crate::alloc_zeroed::(len)?; - let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; - rows(&mut dst, nw * channels, |y, row| { - let ys = span(y, nh, h); - for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { - let xs = span(x, nw, w); - for (c, v) in px.iter_mut().enumerate() { - let (mut sum, mut n) = (0u32, 0u32); - for sy in ys.clone() { - for sx in xs.clone() { - if let Some(&s) = src.get((sy * w + sx) * channels + c) { - sum += u32::from(s); - n += 1; - } - } - } - *v = ((sum + n / 2) / n.max(1)) as u8; - } - } - }); - Ok(dst) + let compression = match options.compression { + DdsCompression::None => craft_image_codecs::DdsCompression::None, + DdsCompression::Bc1 => craft_image_codecs::DdsCompression::Bc1, + DdsCompression::Bc2 => craft_image_codecs::DdsCompression::Bc2, + DdsCompression::Bc3 => craft_image_codecs::DdsCompression::Bc3, + }; + let opts = + craft_image_codecs::EncodeOptions { dds: craft_image_codecs::DdsOptions { compression, mipmaps: options.mipmaps }, ..Default::default() }; + bridge::encode(image, Format::Dds, &opts) } diff --git a/crates/raster-codecs/src/dds_bc.rs b/crates/raster-codecs/src/dds_bc.rs deleted file mode 100644 index df60e462cd..0000000000 --- a/crates/raster-codecs/src/dds_bc.rs +++ /dev/null @@ -1,369 +0,0 @@ -//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression -//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D -//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses. -//! -//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, -//! refines them by least squares, and scores every candidate against the exact palette the -//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows. - -/// The 16 texels of a 4×4 block, row by row, as RGBA. -pub(crate) type Block = [[u8; 4]; 16]; - -/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is -/// not a multiple of four have texels outside the image. -pub(crate) type Mask = u16; - -pub(crate) fn rgb565(c: u16) -> [u8; 3] { - let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; - [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] -} - -/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every -/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and -/// transparent black. -pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { - let (a, b) = (rgb565(c0), rgb565(c1)); - let mix = |wa: u32, wb: u32| { - let d = wa + wb; - let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; - [at(0), at(1), at(2), 255] - }; - if four { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] - } else { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] - } -} - -/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four -/// interpolated at fifths followed by 0 and 255. -pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { - let (a0, a1) = (u32::from(a0), u32::from(a1)); - let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; - if a0 > a1 { - for (k, v) in palette.iter_mut().enumerate().skip(2) { - let k = k as u32; - *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; - } - } else { - for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { - let k = k as u32; - *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; - } - } - palette.map(|v| v as u8) -} - -/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the -/// three-colour mode; an opaque block takes whichever mode fits its colours better. -pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { - let transparent = select(block, inside, |t| t[3] < 128); - colour_block(block, inside & !transparent, transparent, true) -} - -/// A BC2 block: four bits of alpha per texel, then a four-colour block. -pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { - let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t)); - join(bits.to_le_bytes(), colour_block(block, inside, 0, false)) -} - -/// A BC3 block: an interpolated alpha block, then a four-colour block. -pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { - join(alpha_block(block, inside), colour_block(block, inside, 0, false)) -} - -fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { - std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0)) -} - -/// The texels of `inside` for which `f` holds. -fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask { - block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t) -} - -fn rgb_of(texel: &[u8; 4]) -> [f32; 3] { - [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])] -} - -/// RGB565 of a colour, rounding each channel to the nearest level. -fn to565(c: [f32; 3]) -> u16 { - let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16; - q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0) -} - -fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { - (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum() -} - -/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the -/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and -/// BC3 always decode four colours. -fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { - let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect(); - if colours.is_empty() { - // Nothing visible: every texel on the transparent index (or index 0 of black). - let indices = if transparent != 0 { u32::MAX } else { 0 }; - return pack(0, 0, indices); - } - let (lo, hi) = principal_endpoints(&colours); - let mut candidates = vec![(to565(lo), to565(hi))]; - let modes: &[bool] = if transparent != 0 { - &[false] - } else if bc1 { - &[true, false] - } else { - &[true] - }; - let mut best: Option<(u32, [u8; 8])> = None; - // Each refinement starts from the best block so far: its indices give the least-squares - // endpoints, which become one more candidate. - for round in 0..3 { - for &(e0, e1) in &candidates { - for &four in modes { - let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); - if best.is_none_or(|(e, _)| error < e) { - best = Some((error, bytes)); - } - } - } - let Some((error, bytes)) = best else { break }; - if error == 0 || round == 2 { - break; - } - candidates = least_squares(block, opaque, &bytes).into_iter().collect(); - if candidates.is_empty() { - break; - } - } - best.map_or([0; 8], |(_, bytes)| bytes) -} - -/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three) -/// and picks each texel's nearest palette colour. Returns the block and its squared error. -fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) { - let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) }; - // Equal endpoints can't be in four-colour order; the palette is then one colour either way. - let palette = colour_palette(c0, c1, four && c0 > c1); - let choices = if four && c0 > c1 { 4 } else { 3 }; - let mut indices = 0u32; - let mut error = 0u32; - for (t, texel) in block.iter().enumerate() { - let index = if transparent >> t & 1 != 0 { - 3 - } else if opaque >> t & 1 != 0 { - let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); - error += d; - i as u32 - } else { - 0 - }; - indices |= index << (2 * t); - } - (pack(c0, c1, indices), error) -} - -fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] { - let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes()); - [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]] -} - -/// The ends of the colours' spread along their principal axis (the covariance's dominant -/// eigenvector, by power iteration), clamped to the RGB cube. -fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { - let n = colours.len().max(1) as f32; - let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::() / n); - let mut cov = [[0f32; 3]; 3]; - for c in colours { - let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]]; - for (i, row) in cov.iter_mut().enumerate() { - for (j, v) in row.iter_mut().enumerate() { - *v += d[i] * d[j]; - } - } - } - let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]); - let iterate = |start: usize| { - let mut axis = [0f32; 3]; - axis[start] = 1.0; - for _ in 0..8 { - let next = times(axis); - let len = next.iter().map(|v| v * v).sum::().sqrt(); - if !len.is_normal() { - break; - } - axis = next.map(|v| v / len); - } - axis - }; - // From each channel's axis, keeping the one the colours spread along most: a channel that - // varies on its own is already an eigenvector, so a single start there would never leave it - // even when the others vary more together. - let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::(); - let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]); - let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2]; - let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t))); - let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0)); - if lo > hi { (mean, mean) } else { (at(lo), at(hi)) } -} - -/// The endpoints that minimise the squared error for the indices `bytes` already chose: each -/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per -/// channel. `None` when the indices don't constrain both endpoints. -fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> { - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); - let four = c0 > c1; - // How much of c0 each index holds. - let weight = |i: u32| match (four, i) { - (_, 0) => Some(1.0f32), - (_, 1) => Some(0.0), - (true, 2) => Some(2.0 / 3.0), - (true, _) => Some(1.0 / 3.0), - (false, 2) => Some(0.5), - (false, _) => None, - }; - let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32); - let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]); - for (t, texel) in block.iter().enumerate() { - if opaque >> t & 1 == 0 { - continue; - } - let Some(a) = weight(indices >> (2 * t) & 3) else { continue }; - let b = 1.0 - a; - let c = rgb_of(texel); - aa += a * a; - ab += a * b; - bb += b * b; - for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) { - *x0 += a * v; - *x1 += b * v; - } - } - let det = aa * bb - ab * ab; - if det.abs() < 1e-3 { - return None; - } - let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det); - let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det); - Some((to565(e0), to565(e1))) -} - -/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six -/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better. -fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] { - let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]); - let range = - |values: &mut dyn Iterator| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))); - let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0)); - // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. - let eight = alpha_fit(block, inside, hi, lo); - let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0)); - let six = alpha_fit(block, inside, mid_lo, mid_hi); - if six.1 < eight.1 { six.0 } else { eight.0 } -} - -fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { - let palette = alpha_palette(a0, a1); - let mut bits = 0u64; - let mut error = 0u32; - for (t, texel) in block.iter().enumerate() { - if inside >> t & 1 == 0 { - continue; - } - let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); - error += d; - bits |= (i as u64) << (3 * t); - } - let b = bits.to_le_bytes(); - ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block { - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - let palette = colour_palette(c0, c1, c0 > c1 || !bc1); - let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) - } - - #[test] - fn solid_blocks_land_on_the_nearest_565_colour() { - for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { - let block = [colour; 16]; - let out = decode_colour(&encode_bc1(&block, u16::MAX), true); - for texel in out { - assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}"); - } - } - } - - #[test] - fn two_colour_blocks_are_exact_when_the_colours_are_565() { - let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); - let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b }); - for bc1 in [true, false] { - let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) }; - assert_eq!(decode_colour(&bytes, bc1), block); - } - } - - #[test] - fn bc1_punches_through_texels_under_half_alpha() { - let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] }); - let bytes = encode_bc1(&block, u16::MAX); - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - assert!(c0 <= c1, "three-colour mode"); - let out = decode_colour(&bytes, true); - assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}"); - } - - #[test] - fn four_colour_blocks_keep_c0_above_c1() { - // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but - // older decoders read c0 <= c1 as three colours, so the encoder never writes that. - let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]); - let bytes = colour_block(&block, u16::MAX, 0, false); - assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]])); - } - - #[test] - fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { - // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. - let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); - let bytes = alpha_block(&block, u16::MAX); - assert!(bytes[0] <= bytes[1], "six-value mode"); - let palette = alpha_palette(bytes[0], bytes[1]); - let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); - for (t, texel) in block.iter().enumerate() { - let got = palette[(bits >> (3 * t)) as usize & 7]; - assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]); - } - } - - #[test] - fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() { - // Red alternates on its own (variance 64); green and blue alternate together (variance 49 - // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would - // keep red's axis and flatten green and blue; the block must do better than its bounding box. - let block: Block = std::array::from_fn(|t| { - let gb = if (t / 2) % 2 == 0 { 121 } else { 135 }; - [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255] - }); - let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::(); - let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true); - let ours = error(&colour_block(&block, u16::MAX, 0, false)); - assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); - } - - #[test] - fn texels_outside_the_image_are_ignored() { - // Only the top-left texel is inside: its colour alone decides the endpoints. - let mut block: Block = [[0, 255, 0, 255]; 16]; - block[0] = [255, 0, 255, 255]; - let out = decode_colour(&encode_bc1(&block, 1), true); - assert_eq!(out[0], [255, 0, 255, 255]); - } -} diff --git a/crates/raster-codecs/src/dicom.rs b/crates/raster-codecs/src/dicom.rs index 31f99839ff..ee6c73208c 100644 --- a/crates/raster-codecs/src/dicom.rs +++ b/crates/raster-codecs/src/dicom.rs @@ -1,526 +1,10 @@ -//! DICOM (medical imaging) reader, uncompressed transfer syntaxes only. -//! -//! Supports what a viewer needs from a single-frame image: MONOCHROME1/2 (gray) and RGB or -//! YBR_FULL, 8- and 16-bit samples, interleaved or planar, both byte orders and explicit or -//! implicit VR. Undefined-length sequences outside the pixel data are skipped (clinical files -//! contain them); compressed transfer syntaxes, encapsulated pixel data and other photometric -//! interpretations are refused with a clear error. Read-only in this crate. +//! DICOM compatibility facade; implementation and detection live in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use std::collections::HashMap; - -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -const F: &str = "DICOM"; -const PREAMBLE: usize = 132; // 128 zero bytes + "DICM" -const UNDEFINED: u32 = 0xFFFF_FFFF; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) +pub fn is_dicom(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Dicom) } - -/// A DICOM file begins with a 128-byte preamble and the `DICM` magic. -pub fn is_dicom(b: &[u8]) -> bool { - b.get(128..132) == Some(b"DICM") -} - -#[derive(Clone, Copy)] -struct Endian { - big: bool, -} - -/// The transfer syntax: byte order and whether value representations are explicit. -#[derive(Clone, Copy)] -struct Syntax { - endian: Endian, - explicit: bool, -} - -/// The value representations whose length field is 2 reserved bytes + `u32` in explicit VR. -fn long_vr(vr: &[u8]) -> bool { - matches!(vr, b"OB" | b"OW" | b"OF" | b"SQ" | b"UT" | b"UN" | b"OD" | b"OL" | b"OV" | b"UC" | b"UR") -} - -/// A cursor over the byte stream. -struct Cur<'a> { - b: &'a [u8], - pos: usize, - big: bool, -} - -impl<'a> Cur<'a> { - fn take(&mut self, n: usize) -> Option<&'a [u8]> { - let s = self.b.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(s) - } - fn u16(&mut self) -> Option { - let c = self.take(2)?; - Some(if self.big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) - } - fn u32(&mut self) -> Option { - let c = self.take(4)?; - Some(if self.big { u32::from_be_bytes([c[0], c[1], c[2], c[3]]) } else { u32::from_le_bytes([c[0], c[1], c[2], c[3]]) }) - } - /// Skip `len` bytes, refusing to run past the buffer. - fn skip(&mut self, len: usize) -> Result<(), CodecError> { - self.pos = self.pos.checked_add(len).filter(|p| *p <= self.b.len()).ok_or_else(|| bad("a value runs past the end of the file"))?; - Ok(()) - } -} - -/// Read one element's tag and value length, leaving the cursor at the value. Item and delimiter -/// tags (group `FFFE`) carry a `u32` length with no VR even under explicit VR. -fn read_header(c: &mut Cur, syn: &Syntax) -> Result<(u16, u16, [u8; 2], u32), CodecError> { - let group = c.u16().ok_or_else(|| bad("truncated element tag"))?; - let elem = c.u16().ok_or_else(|| bad("truncated element tag"))?; - let (vr, len) = if group == 0xFFFE { - ([0, 0], c.u32().ok_or_else(|| bad("truncated item length"))?) - } else if syn.explicit { - let vr = c.take(2).ok_or_else(|| bad("truncated VR"))?; - let v = [vr[0], vr[1]]; - let len = if long_vr(&v) { - c.take(2).ok_or_else(|| bad("truncated VR"))?; // reserved - c.u32().ok_or_else(|| bad("truncated length"))? - } else { - u32::from(c.u16().ok_or_else(|| bad("truncated length"))?) - }; - (v, len) - } else { - ([0, 0], c.u32().ok_or_else(|| bad("truncated length"))?) - }; - Ok((group, elem, vr, len)) -} - -/// Skip an undefined-length sequence, ending just after its `FFFE,E0DD` delimiter. Nesting is -/// tracked through undefined-length items and nested sequences; everything else is skipped by -/// its length. Returns the position after the delimiter. -fn skip_undefined(c: &mut Cur, syn: &Syntax) -> Result<(), CodecError> { - let mut depth = 1u32; - while depth > 0 { - let (group, elem, _, len) = read_header(c, syn)?; - // Item (E00D) and sequence (E0DD) delimiters close one undefined length; they carry no - // content of their own. - if group == 0xFFFE && matches!(elem, 0xE00D | 0xE0DD) { - depth -= 1; - continue; - } - if len == UNDEFINED { - depth += 1; - } else { - c.skip(len as usize)?; - } - } - Ok(()) -} - -/// Walk the elements from `start`, calling `f` with each `(group, element, value)`. An -/// undefined-length sequence outside the pixel data is skipped; encapsulated (undefined-length) -/// pixel data is refused. Returns the number of bytes walked. -fn elements(b: &[u8], start: usize, syn: &Syntax, mut f: impl FnMut(u16, u16, &Elem) -> Result<(), CodecError>) -> Result { - let mut c = Cur { b, pos: start, big: syn.endian.big }; - loop { - if c.pos >= b.len() { - return Ok(c.pos - start); - } - let (group, elem, vr, len) = read_header(&mut c, syn)?; - if len == UNDEFINED { - if (group, elem) == (0x7FE0, 0x0010) { - return Err(CodecError::unsupported(F, "encapsulated (compressed) pixel data")); - } - skip_undefined(&mut c, syn)?; - continue; - } - let len = len as usize; - let start = c.pos; - if b.len() < start.saturating_add(len) { - return Err(bad("an element value runs past the end of the file")); - } - f(group, elem, &Elem { vr, start, len })?; - c.pos = start + len; - } -} - -/// A parsed element: its VR and the byte range of its value. -struct Elem { - vr: [u8; 2], - start: usize, - len: usize, -} - -fn u16_val(b: &[u8], e: &Elem, big: bool) -> Option { - let c = b.get(e.start..e.start.checked_add(2)?)?; - Some(if big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) -} - -/// The transfer syntax (byte order and explicit/implicit VR) and the data-set start. The file -/// meta group is always explicit VR little-endian; the data set follows its `(0002,0010)` -/// TransferSyntaxUID. -fn transfer_syntax(b: &[u8]) -> Result<(Syntax, usize), CodecError> { - let meta = Syntax { endian: Endian { big: false }, explicit: true }; - let mut ts: Option = None; - let mut data_start = b.len(); - let mut c = Cur { b, pos: PREAMBLE, big: false }; - while c.pos + 8 <= b.len() { - let save = c.pos; - let (group, elem, _, len) = read_header(&mut c, &meta)?; - if group != 0x0002 { - // A non-meta group begins the data set. - data_start = save; - break; - } - if len == UNDEFINED { - return Err(CodecError::unsupported(F, "undefined-length meta element")); - } - let start = c.pos; - if b.len() < start.saturating_add(len as usize) { - return Err(bad("a meta element runs past the end of the file")); - } - if elem == 0x0010 { - ts = Some(String::from_utf8_lossy(&b[start..start + len as usize]).trim_end_matches(['\0', ' ']).to_string()); - } - c.pos = start + len as usize; - } - let syn = match ts.as_deref() { - Some("1.2.840.10008.1.2") => Syntax { endian: Endian { big: false }, explicit: false }, - Some("1.2.840.10008.1.2.1") => Syntax { endian: Endian { big: false }, explicit: true }, - Some("1.2.840.10008.1.2.2") => Syntax { endian: Endian { big: true }, explicit: true }, - Some(other) => return Err(CodecError::unsupported(F, format!("transfer syntax {other} (only uncompressed is read)"))), - // No meta: the historical default is implicit VR little-endian. - None => Syntax { endian: Endian { big: false }, explicit: false }, - }; - Ok((syn, data_start)) -} - -pub fn decode(b: &[u8], limits: &Limits) -> Result { - if !is_dicom(b) { - return Err(bad("not a DICOM file (no DICM magic)")); - } - let (syn, start) = transfer_syntax(b)?; - let mut tags: HashMap<(u16, u16), Elem> = HashMap::new(); - elements(b, start, &syn, |g, e, el| { - // Later duplicates must not silently override the first (DICOM forbids duplicates). - tags.entry((g, e)).or_insert_with(|| Elem { vr: el.vr, start: el.start, len: el.len }); - Ok(()) - })?; - let big = syn.endian.big; - let get_u16 = |tag: (u16, u16)| tags.get(&tag).and_then(|e| u16_val(b, e, big)); - let rows = u32::from(get_u16((0x0028, 0x0010)).ok_or_else(|| bad("missing Rows (0028,0010)"))?); - let cols = u32::from(get_u16((0x0028, 0x0011)).ok_or_else(|| bad("missing Columns (0028,0011)"))?); - let samples = u32::from(get_u16((0x0028, 0x0002)).unwrap_or(1)); - let bits = get_u16((0x0028, 0x0100)).ok_or_else(|| bad("missing BitsAllocated (0028,0100)"))?; - let bits_stored = get_u16((0x0028, 0x0101)).unwrap_or(bits); - let high_bit = get_u16((0x0028, 0x0102)).unwrap_or(bits_stored.saturating_sub(1)); - if u32::from(high_bit) >= u32::from(bits) { - return Err(bad("HighBit is outside the allocated bits")); - } - let signed = get_u16((0x0028, 0x0103)).unwrap_or(0) == 1; - let planar = get_u16((0x0028, 0x0006)).unwrap_or(0); - let photometric = tags - .get(&(0x0028, 0x0004)) - .and_then(|e| b.get(e.start..e.start.checked_add(e.len)?)) - .map(|v| String::from_utf8_lossy(v).trim_end_matches(['\0', ' ']).to_string()) - .ok_or_else(|| bad("missing PhotometricInterpretation (0028,0004)"))?; - let pixel = tags.get(&(0x7FE0, 0x0010)).ok_or_else(|| CodecError::unsupported(F, "no pixel data (7FE0,0010)"))?; - if !matches!(bits, 8 | 16) || !matches!(bits_stored, 1..=16) { - return Err(CodecError::unsupported(F, format!("{bits}-bit allocated / {bits_stored}-bit stored samples"))); - } - let mono = matches!(photometric.as_str(), "MONOCHROME1" | "MONOCHROME2"); - let rgb = photometric == "RGB"; - let ybr = photometric == "YBR_FULL"; - if !(mono || rgb || ybr) { - return Err(CodecError::unsupported(F, format!("photometric interpretation {photometric}"))); - } - // Mono stores one sample; RGB and YBR_FULL store three. Any other count would index past the - // pixel data, so it is refused rather than misread. - let want_samples = if mono { 1 } else { 3 }; - if samples != want_samples { - return Err(CodecError::unsupported(F, format!("{samples} samples per pixel with {photometric}"))); - } - if ybr && bits != 8 { - return Err(CodecError::unsupported(F, format!("{bits}-bit {photometric} (8-bit only)"))); - } - let layout = if mono { ChannelLayout::Gray } else { ChannelLayout::Rgb }; - let out_sample = if bits == 8 { SampleType::U8 } else { SampleType::U16 }; - limits.check(cols, rows, layout, out_sample)?; - - let pixels = (cols as usize).checked_mul(rows as usize).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let n = pixels.checked_mul(samples as usize).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let bytes_per = if bits == 16 { 2usize } else { 1 }; - let need = n.checked_mul(bytes_per).ok_or_else(|| CodecError::LimitExceeded("pixel data too large".into()))?; - let data = b - .get(pixel.start..pixel.start.checked_add(need).ok_or_else(|| CodecError::LimitExceeded("pixel data too large".into()))?) - .ok_or_else(|| bad("pixel data is truncated"))?; - let out_channels = layout.channels(); - let out_len = - pixels.checked_mul(out_channels).and_then(|k| k.checked_mul(bytes_per)).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let mut out = Vec::new(); - out.try_reserve_exact(out_len).map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?; - // Raw sample of channel `ch` at pixel `p`, honouring the planar configuration. - let sample_at = |p: usize, ch: usize| -> Option { - let idx = if planar == 1 { ch.checked_mul(pixels)?.checked_add(p)? } else { p.checked_mul(samples as usize)?.checked_add(ch)? }; - let off = idx.checked_mul(bytes_per)?; - if bits == 16 { - let c = data.get(off..off.checked_add(2)?)?; - Some(if big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }.into()) - } else { - Some(u32::from(*data.get(off)?)) - } - }; - let stored_max = f64::from((1u32 << bits_stored) - 1); - // Extract the `bits_stored` samples (the least significant one at `high_bit`) and scale to - // [0, 1]; signed values are shifted up by half a range first. `high_bit` is 1-based here. - let shift = (u32::from(high_bit) + 1).saturating_sub(u32::from(bits_stored)); - let mask = (1u32 << bits_stored) - 1; - let half = 1u32 << (bits_stored - 1); - let norm = move |raw: u32| -> f64 { - let v = (raw >> shift) & mask; - // Signed: flip the sign bit to map [-2^(b-1), 2^(b-1)-1] onto [0, 2^b-1]. - let v = if signed { v ^ half } else { v }; - (f64::from(v) / stored_max).clamp(0.0, 1.0) - }; - let q = |x: f64| -> u16 { (x * 65535.0).round() as u16 }; - let push = |out: &mut Vec, x: f64| { - if bits == 8 { - out.push((x * 255.0).round() as u8); - } else { - out.extend_from_slice(&q(x).to_ne_bytes()); - } - }; - for p in 0..pixels { - let s = |ch: usize| sample_at(p, ch).ok_or_else(|| bad("pixel data is shorter than the image")); - if mono { - let x = norm(s(0)?); - push(&mut out, if photometric == "MONOCHROME1" { 1.0 - x } else { x }); - } else if rgb { - for ch in 0..3 { - push(&mut out, norm(s(ch)?)); - } - } else { - // YBR_FULL (8-bit): BT.601 full-range to RGB. - let y = f64::from(s(0)?); - let cb = f64::from(s(1)?) - 128.0; - let cr = f64::from(s(2)?) - 128.0; - let r = (y + 1.402 * cr).clamp(0.0, 255.0); - let g = (y - 0.344_136 * cb - 0.714_136 * cr).clamp(0.0, 255.0); - let bl = (y + 1.772 * cb).clamp(0.0, 255.0); - for v in [r, g, bl] { - push(&mut out, v / 255.0); - } - } - } - Image::from_raw(cols, rows, layout, out_sample, out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Build the file meta group (explicit VR little-endian), including the given extra - /// `(element, ascii)` pairs before the TransferSyntaxUID. - fn meta(b: &mut Vec, ts: &str, extra: &[(u16, &str)]) { - let ui = |e: u16, v: &str, b: &mut Vec| { - let mut s = v.as_bytes().to_vec(); - if s.len() % 2 == 1 { - s.push(0); - } - b.extend_from_slice(&0x0002u16.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - b.extend_from_slice(b"UI"); - b.extend_from_slice(&(s.len() as u16).to_le_bytes()); - b.extend_from_slice(&s); - }; - for (e, v) in extra { - ui(*e, v, b); - } - ui(0x0010, ts, b); - } - - fn us(b: &mut Vec, g: u16, e: u16, v: u16, explicit: bool) { - b.extend_from_slice(&g.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - if explicit { - b.extend_from_slice(b"US"); - b.extend_from_slice(&2u16.to_le_bytes()); - } else { - b.extend_from_slice(&2u32.to_le_bytes()); - } - b.extend_from_slice(&v.to_le_bytes()); - } - - fn cs(b: &mut Vec, g: u16, e: u16, v: &str, explicit: bool) { - let mut s = v.as_bytes().to_vec(); - if s.len() % 2 == 1 { - s.push(0); - } - b.extend_from_slice(&g.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - if explicit { - b.extend_from_slice(b"CS"); - b.extend_from_slice(&(s.len() as u16).to_le_bytes()); - } else { - b.extend_from_slice(&(s.len() as u32).to_le_bytes()); - } - b.extend_from_slice(&s); - } - - /// A DICOM with the given transfer syntax UID and data-set encoding. - #[allow(clippy::too_many_arguments)] - fn synth( - ts: &str, - explicit: bool, - big: bool, - planar: u16, - rows: u16, - cols: u16, - samples: u16, - bits: u16, - photometric: &str, - pixels: &[u8], - ) -> Vec { - let mut b = vec![0u8; 128]; - b.extend_from_slice(b"DICM"); - // One extra meta element before the syntax, so a reader that only looks at the last - // group-0002 element takes the wrong one. - meta(&mut b, ts, &[(0x0002, "1.2.840.10008.5.1.4.1.1.7")]); - let _ = big; - us(&mut b, 0x0028, 0x0010, rows, explicit); - us(&mut b, 0x0028, 0x0011, cols, explicit); - us(&mut b, 0x0028, 0x0002, samples, explicit); - us(&mut b, 0x0028, 0x0006, planar, explicit); - cs(&mut b, 0x0028, 0x0004, photometric, explicit); - us(&mut b, 0x0028, 0x0100, bits, explicit); - us(&mut b, 0x0028, 0x0101, bits, explicit); - us(&mut b, 0x0028, 0x0102, bits - 1, explicit); - us(&mut b, 0x0028, 0x0103, 0, explicit); - b.extend_from_slice(&0x7FE0u16.to_le_bytes()); - b.extend_from_slice(&0x0010u16.to_le_bytes()); - if explicit { - b.extend_from_slice(b"OB"); - b.extend_from_slice(&0u16.to_le_bytes()); - } - b.extend_from_slice(&(pixels.len() as u32).to_le_bytes()); - b.extend_from_slice(pixels); - b - } - - #[test] - fn decodes_8bit_monochrome() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 51, 102, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (2, 2, ChannelLayout::Gray, SampleType::U8)); - assert_eq!(img.data(), &[0, 51, 102, 255]); - } - - #[test] - fn decodes_16bit_monochrome_and_scales() { - let px: Vec = [0u16, 32768, 65535].iter().flat_map(|v| v.to_le_bytes()).collect(); - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 3, 1, 1, 16, "MONOCHROME2", &px); - let img = decode(&b, &Limits::default()).unwrap(); - let v = img.to_u16_samples().unwrap(); - assert_eq!(v[0], 0); - assert!((i32::from(v[1]) - 32768).abs() <= 1); - assert_eq!(v[2], 65535); - } - - #[test] - fn monochrome1_is_inverted() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 1, 1, 8, "MONOCHROME1", &[0, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[255, 0]); - } - - #[test] - fn decodes_rgb_interleaved_and_planar() { - // 2 pixels: (10,20,30) and (40,50,60). - let interleaved = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 2, 3, 8, "RGB", &[10, 20, 30, 40, 50, 60]); - let img = decode(&interleaved, &Limits::default()).unwrap(); - assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgb, &[10u8, 20, 30, 40, 50, 60][..])); - // Planar 0: R plane, then G, then B. - let planar = synth("1.2.840.10008.1.2.1", true, false, 1, 1, 2, 3, 8, "RGB", &[10, 40, 20, 50, 30, 60]); - let img = decode(&planar, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[10, 20, 30, 40, 50, 60]); - } - - #[test] - fn decodes_ybr_full_to_rgb() { - // White (Y=128, Cb=Cr=128) stays neutral grey. - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 3, 8, "YBR_FULL", &[128, 128, 128]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Rgb); - let d = img.data(); - assert!(d[0].abs_diff(d[1]) <= 1 && d[1].abs_diff(d[2]) <= 1, "{d:?}"); - } - - #[test] - fn decodes_implicit_vr() { - let b = synth("1.2.840.10008.1.2", false, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 51, 102, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Gray); - assert_eq!(img.data(), &[0, 51, 102, 255]); - } - - #[test] - fn skips_an_undefined_length_sequence_outside_the_pixel_data() { - // Insert an undefined-length SQ (0008,2218) with one item, then a defined-length one, - // before the pixel data: the reader must skip both and still decode the image. - let mut b = vec![0u8; 128]; - b.extend_from_slice(b"DICM"); - meta(&mut b, "1.2.840.10008.1.2.1", &[]); - for (g, e, v) in [ - (0x0028, 0x0010, 1u16), - (0x0028, 0x0011, 1), - (0x0028, 0x0002, 1), - (0x0028, 0x0100, 8), - (0x0028, 0x0101, 8), - (0x0028, 0x0102, 7), - (0x0028, 0x0103, 0), - ] { - us(&mut b, g, e, v, true); - } - cs(&mut b, 0x0028, 0x0004, "MONOCHROME2", true); - // Undefined-length sequence (0008,2211), one undefined-length item containing a nested - // defined-length sequence, then the delimiters. - b.extend_from_slice(&[0x08, 0x00, 0x11, 0x22, b'S', b'Q', 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF]); - b.extend_from_slice(&[0xFE, 0xFF, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF]); // item, undefined - b.extend_from_slice(&[0x08, 0x00, 0x55, 0x22, b'S', b'Q', 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 1, 2, 3, 4]); // nested, defined - b.extend_from_slice(&[0xFE, 0xFF, 0x0D, 0xE0, 0x00, 0x00, 0x00, 0x00]); // item delimitation - b.extend_from_slice(&[0xFE, 0xFF, 0xDD, 0xE0, 0x00, 0x00, 0x00, 0x00]); // sequence delimitation - // Pixel data (defined length). - b.extend_from_slice(&0x7FE0u16.to_le_bytes()); - b.extend_from_slice(&0x0010u16.to_le_bytes()); - b.extend_from_slice(b"OB"); - b.extend_from_slice(&0u16.to_le_bytes()); - b.extend_from_slice(&1u32.to_le_bytes()); - b.push(200); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[200]); - } - - #[test] - fn truncated_and_bad_is_error_not_panic() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 1, 2, 3]); - for cut in [0, 4, 128, 132, 140, b.len() - 1] { - assert!(decode(&b[..cut.min(b.len())], &Limits::default()).is_err(), "cut {cut}"); - } - assert!(decode(b"not dicom", &Limits::default()).is_err()); - } - - #[test] - fn high_bit_outside_the_allocated_bits_is_an_error_not_a_panic() { - let mut b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 1, 8, "MONOCHROME2", &[7]); - let tag = [0x28, 0x00, 0x02, 0x01, b'U', b'S', 0x02, 0x00]; - let at = b.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len(); - b[at..at + 2].copy_from_slice(&200u16.to_le_bytes()); - assert!(decode(&b, &Limits::default()).is_err()); - } - - #[test] - fn rejects_compressed_transfer_syntax() { - let mut b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 1, 8, "MONOCHROME2", &[0]); - let uncompressed = b"1.2.840.10008.1.2.1\0"; - let compressed = b"1.2.840.10008.1.2.4\0"; // same length, a compressed family - let at = b.windows(uncompressed.len()).position(|w| w == uncompressed).expect("transfer syntax in the fixture"); - b[at..at + compressed.len()].copy_from_slice(compressed); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + bridge::format(Format::Dicom, bytes, limits) } diff --git a/crates/raster-codecs/src/fits.rs b/crates/raster-codecs/src/fits.rs index 0d05c0fa18..5b82541c9c 100644 --- a/crates/raster-codecs/src/fits.rs +++ b/crates/raster-codecs/src/fits.rs @@ -1,857 +1,19 @@ -//! FITS (Flexible Image Transport System, FITS Standard 4.0), implemented here: the image in the -//! primary HDU, or the first `IMAGE` extension when the primary HDU holds no data. -//! -//! Reading: -//! -//! * `BITPIX` 8, 16, 32, 64, -32 and -64, with `BSCALE`/`BZERO` and integer `BLANK`. -//! * `NAXIS3 = 3` opens as RGB (the planes are R, G, B); any other plane count opens the first -//! plane as gray with [`crate::DecodeWarning::MorePages`]. -//! * Rows are stored bottom-to-top, as the standard's convention has it (Siril, DS9, Astropy), -//! unless `ROWORDER = 'TOP-DOWN'`. -//! * Physical values that fit (unsigned 8-bit, or integers in 0..=65535 such as a camera's -//! `BITPIX = 16`, `BZERO = 32768`) are kept exactly as U8/U16. Everything else becomes F32: -//! values up to 2 are taken as already normalised (Siril, PixInsight), larger ones are scaled by -//! 65535 when they fit in it (DeepSkyStacker, most stackers) and by the maximum otherwise. NaN -//! and blank pixels read as 0. -//! * The other header cards are kept as text: `KEY` → value (strings unquoted), `COMMENT` and -//! `HISTORY` by their text, `HIERARCH` keywords by their long name. Long strings continued -//! on `CONTINUE` cards are joined. -//! -//! Writing: gray or RGB, U8 (`BITPIX = 8`), U16 (`BITPIX = 16`, `BZERO = 32768`) or F32 -//! (`BITPIX = -32`, 0..1), bottom-to-top with `ROWORDER = 'BOTTOM-UP'`, plus the text cards -//! (strings longer than one card on `CONTINUE` cards). -//! Tile-compressed files (fpack `ZIMAGE` tables) are recognised and refused. +//! FITS compatibility facade; implementation lives in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use std::collections::HashMap; - -use crate::{ChannelLayout, CodecError, DecodeWarning, Image, Limits, SampleType}; - -const F: &str = "FITS"; -const BLOCK: usize = 2880; -const CARD: usize = 80; -/// Most HDUs walked looking for an image; FITS files from cameras and stackers hold a handful. -const MAX_HDUS: usize = 1000; - -/// Keywords that describe the data layout. They are written from the image, never copied from -/// (or kept as) text metadata: after decoding they no longer describe the pixels. -const STRUCTURAL: &[&str] = &[ - "SIMPLE", "BITPIX", "NAXIS", "EXTEND", "BZERO", "BSCALE", "BLANK", "END", "XTENSION", "PCOUNT", "GCOUNT", "ROWORDER", "CHECKSUM", "DATASUM", - "DATAMIN", "DATAMAX", "ZIMAGE", -]; - -fn err(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) +pub fn looks_like_fits(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Fits) } - -#[derive(Debug, Clone, PartialEq)] -enum Value { - /// A quoted string, unescaped, trailing blanks removed. - Str(String), - /// Anything else (number, logical, complex) as written. - Raw(String), -} - -#[derive(Debug, Clone)] -struct Card { - key: String, - /// `None` for commentary cards (`COMMENT`, `HISTORY`, blank keyword). - value: Option, - /// The text of a commentary card. - text: String, - /// A `HIERARCH` keyword (`key` holds its long name). - hierarch: bool, -} - -fn parse_value(field: &str) -> Value { - let t = field.trim_start(); - if let Some(rest) = t.strip_prefix('\'') { - let mut s = String::new(); - let mut chars = rest.chars().peekable(); - while let Some(c) = chars.next() { - if c == '\'' { - if chars.peek() == Some(&'\'') { - chars.next(); - s.push('\''); - } else { - break; - } - } else { - s.push(c); - } - } - Value::Str(s.trim_end().to_string()) - } else { - Value::Raw(t.split('/').next().unwrap_or("").trim().to_string()) - } -} - -fn parse_card(raw: &[u8]) -> Card { - // Header bytes are ASCII 32–126 by the standard; anything else is replaced, never trusted. - let s: String = raw.iter().map(|&b| if (32..=126).contains(&b) { b as char } else { '?' }).collect(); - let key_field = s.get(..8).unwrap_or(&s).trim_end().to_string(); - if key_field == "HIERARCH" { - let rest = s.get(9..).unwrap_or(""); - if let Some((k, v)) = rest.split_once('=') { - return Card { key: k.trim().to_string(), value: Some(parse_value(v)), text: String::new(), hierarch: true }; - } - } - if s.get(8..10) == Some("= ") { - let v = parse_value(s.get(10..).unwrap_or("")); - return Card { key: key_field, value: Some(v), text: String::new(), hierarch: false }; - } - Card { key: key_field, value: None, text: s.get(8..).unwrap_or("").trim_end().to_string(), hierarch: false } -} - -struct Header { - cards: Vec, - /// First-occurrence index of each non-HIERARCH keyword, so `get` is O(1). The card - /// count and the number of looked-up keywords (NAXIS1..NAXISn) are both file-controlled, - /// so a linear scan per lookup lets a crafted header multiply commentary cards by axis - /// count into quadratic work. - index: HashMap, - /// Offset of the data unit. - data_start: usize, -} - -impl Header { - fn get(&self, key: &str) -> Option<&Value> { - let c = &self.cards[*self.index.get(key)?]; - c.value.as_ref() - } - - fn int(&self, key: &str) -> Option { - match self.get(key)? { - Value::Raw(r) => r.parse::().ok().or_else(|| self.float(key).filter(|f| f.fract() == 0.0 && f.abs() < 9.0e15).map(|f| f as i64)), - Value::Str(_) => None, - } - } - - fn float(&self, key: &str) -> Option { - match self.get(key)? { - // Fortran-style `D` exponents are allowed in FITS. - Value::Raw(r) => r.replace(['D', 'd'], "E").parse::().ok().filter(|f| f.is_finite()), - Value::Str(_) => None, - } - } - - fn logical(&self, key: &str) -> bool { - matches!(self.get(key), Some(Value::Raw(r)) if r == "T") - } - - fn string(&self, key: &str) -> Option<&str> { - match self.get(key)? { - Value::Str(s) => Some(s.trim()), - Value::Raw(_) => None, - } - } -} - -fn parse_header(b: &[u8], start: usize) -> Result { - let mut cards = Vec::new(); - let mut pos = start; - loop { - let raw = b.get(pos..pos.checked_add(CARD).ok_or_else(|| err("header too long"))?).ok_or_else(|| err("header ends before END"))?; - pos += CARD; - if raw.starts_with(b"END") && raw.get(3..).is_some_and(|r| r.iter().all(|&c| c == b' ')) { - break; - } - let card = parse_card(raw); - // Long strings (FITS 4.0 section 4.2.1.2): a string ending in '&' goes on in the next - // `CONTINUE` record. An orphaned `CONTINUE` stays a card of its own (commentary). - if let Some(Card { value: Some(Value::Str(s)), .. }) = cards.last_mut() - && s.ends_with('&') - && card.key == "CONTINUE" - && card.text.starts_with(" ") - && let Value::Str(more) = parse_value(&card.text) - { - s.pop(); - s.push_str(&more); - continue; - } - cards.push(card); - } - let data_start = pos.div_ceil(BLOCK).checked_mul(BLOCK).ok_or_else(|| err("header too long"))?; - // Index each non-HIERARCH keyword to its first occurrence, matching the previous - // `find(|c| !c.hierarch && c.key == key)` lookup while making `get` O(1). - let mut index = HashMap::with_capacity(cards.len()); - for (i, c) in cards.iter().enumerate() { - if !c.hierarch { - index.entry(c.key.clone()).or_insert(i); - } - } - Ok(Header { cards, index, data_start }) -} - -/// The axis lengths (`NAXIS1`, `NAXIS2`, …). -fn axes(h: &Header) -> Result, CodecError> { - let n = h.int("NAXIS").ok_or_else(|| err("missing NAXIS"))?; - if !(0..=999).contains(&n) { - return Err(err(format!("invalid NAXIS {n}"))); - } - (1..=n) - .map(|i| h.int(&format!("NAXIS{i}")).and_then(|v| u64::try_from(v).ok()).ok_or_else(|| err(format!("missing or negative NAXIS{i}")))) - .collect() -} - -/// Bytes in the data unit (before padding to a block). -fn data_len(h: &Header, bitpix: i64) -> Result { - let ax = axes(h)?; - if ax.is_empty() { - return Ok(0); - } - let pcount = u64::try_from(h.int("PCOUNT").unwrap_or(0)).map_err(|_| err("negative PCOUNT"))?; - let gcount = u64::try_from(h.int("GCOUNT").unwrap_or(1)).map_err(|_| err("negative GCOUNT"))?; - let elems = ax.iter().try_fold(1u64, |a, &n| a.checked_mul(n)).ok_or_else(|| err("data size overflows"))?; - elems - .checked_add(pcount) - .and_then(|v| v.checked_mul(gcount)) - .and_then(|v| v.checked_mul(bitpix.unsigned_abs() / 8)) - .ok_or_else(|| err("data size overflows")) -} - -/// A primary header's first card, `SIMPLE =`. -pub fn looks_like_fits(b: &[u8]) -> bool { - b.starts_with(b"SIMPLE =") -} - -/// Inspect every HDU without decoding pixels: one gray plane or three RGB planes are retained, -/// while other cubes, image extensions, tables and other data-bearing HDUs cannot survive a flat save. -/// Incomplete or over-limit walks fail closed rather than treating an unchecked suffix as safe. pub fn has_additional_images(bytes: &[u8]) -> Result { - let mut start = 0; - let mut image_seen = false; - for index in 0..MAX_HDUS { - let h = parse_header(bytes, start)?; - if index == 0 && h.get("SIMPLE").is_none() { - return Err(err("missing SIMPLE")); - } - let ax = axes(&h)?; - let size = data_len(&h, h.int("BITPIX").unwrap_or(8))?; - let image_hdu = index == 0 || h.string("XTENSION") == Some("IMAGE"); - if h.logical("ZIMAGE") { - return Ok(true); - } - if !image_hdu && size > 0 { - return Ok(true); - } - // An image HDU with a zero axis has no data (FITS 4.0, NAXISn) and holds no image, like - // the empty primary: `find_image` skips it too. - if image_hdu && size > 0 && ax.len() >= 2 && ax[..2].iter().all(|n| *n > 0) { - let planes = ax.iter().skip(2).try_fold(1u64, |n, axis| n.checked_mul(*axis)).ok_or_else(|| err("plane count overflows"))?; - let retained = planes == 1 || (ax.get(2) == Some(&3) && planes == 3); - if image_seen || !retained || h.int("GCOUNT").unwrap_or(1) > 1 || h.int("PCOUNT").unwrap_or(0) > 0 { - return Ok(true); - } - image_seen = true; - } else if size > 0 { - return Ok(true); - } - let padded = size.div_ceil(BLOCK as u64).checked_mul(BLOCK as u64).ok_or_else(|| err("data size overflows"))?; - let next = usize::try_from(padded).ok().and_then(|size| h.data_start.checked_add(size)).ok_or_else(|| err("data size overflows"))?; - if next > bytes.len() { - return Err(err("truncated HDU data")); - } - if next == bytes.len() { - return Ok(false); - } - start = next; - } - Err(err("too many HDUs to inspect every source image")) + craft_image_codecs::has_unretained_source_data(bytes).map_err(bridge::from_shared_error) } - -/// Whether an HDU with these axes stores pixels: at least two axes and none of them zero (FITS 4.0, -/// NAXISn: a zero axis means no data follow the header). -fn holds_pixels(ax: &[u64]) -> bool { - ax.len() >= 2 && ax.iter().all(|n| *n > 0) -} - -/// Finds the image HDU: the primary one when it holds pixels, else the first `IMAGE` extension -/// that does. Returns its header and the primary header (for its descriptive cards). -fn find_image(b: &[u8]) -> Result<(Header, Option
), CodecError> { - let primary = parse_header(b, 0)?; - if primary.get("SIMPLE").is_none() { - return Err(err("missing SIMPLE")); - } - if holds_pixels(&axes(&primary)?) { - return Ok((primary, None)); - } - let mut compressed = false; - let mut cur_start = primary.data_start; - let mut cur_len = data_len(&primary, primary.int("BITPIX").unwrap_or(8))?; - for _ in 0..MAX_HDUS { - let next = usize::try_from(cur_len.div_ceil(BLOCK as u64).saturating_mul(BLOCK as u64)) - .ok() - .and_then(|l| cur_start.checked_add(l)) - .ok_or_else(|| err("data size overflows"))?; - if next >= b.len() { - break; - } - let h = parse_header(b, next)?; - let kind = h.string("XTENSION").unwrap_or("").to_string(); - if kind == "IMAGE" && holds_pixels(&axes(&h)?) { - return Ok((h, Some(primary))); - } - if kind == "BINTABLE" && h.logical("ZIMAGE") { - compressed = true; - } - cur_len = data_len(&h, h.int("BITPIX").unwrap_or(8))?; - cur_start = h.data_start; - } - if compressed { - return Err(CodecError::unsupported(F, "tile-compressed FITS (fpack) is not supported; decompress it with funpack first")); - } - Err(err("the file holds no image")) -} - pub fn decode(bytes: &[u8], limits: &Limits) -> Result { - let (h, primary) = find_image(bytes)?; - let bitpix = h.int("BITPIX").ok_or_else(|| err("missing BITPIX"))?; - if !matches!(bitpix, 8 | 16 | 32 | 64 | -32 | -64) { - return Err(err(format!("invalid BITPIX {bitpix}"))); - } - let ax = axes(&h)?; - let (Some(&w), Some(&hgt)) = (ax.first(), ax.get(1)) else { return Err(err("the image has fewer than two axes")) }; - let w = u32::try_from(w).map_err(|_| CodecError::LimitExceeded(format!("width {w}")))?; - let hgt = u32::try_from(hgt).map_err(|_| CodecError::LimitExceeded(format!("height {hgt}")))?; - let planes = ax.iter().skip(2).try_fold(1u64, |a, &n| a.checked_mul(n)).ok_or_else(|| err("too many planes"))?; - let (layout, nplanes) = if ax.get(2) == Some(&3) && planes == 3 { (ChannelLayout::Rgb, 3usize) } else { (ChannelLayout::Gray, 1) }; - - let bscale = h.float("BSCALE").unwrap_or(1.0); - let bzero = h.float("BZERO").unwrap_or(0.0); - let blank = if bitpix > 0 { h.int("BLANK") } else { None }; - let integral = bscale == 1.0 && bzero.fract() == 0.0; - let candidate = match bitpix { - 8 if integral && bzero == 0.0 => SampleType::U8, - 8 | 16 if integral => SampleType::U16, - _ => SampleType::F32, - }; - limits.check(w, hgt, layout, candidate)?; - - let bps = (bitpix.unsigned_abs() / 8) as usize; - let plane_len = (w as usize).checked_mul(hgt as usize).ok_or_else(|| CodecError::LimitExceeded(format!("{w}x{hgt} does not fit in memory")))?; - let n = plane_len.checked_mul(nplanes).ok_or_else(|| CodecError::LimitExceeded("image does not fit in memory".into()))?; - let need = n.checked_mul(bps).and_then(|l| l.checked_add(h.data_start)).ok_or_else(|| err("data size overflows"))?; - let data = bytes.get(h.data_start..need).ok_or_else(|| err("truncated data"))?; - - // Physical value of sample `i` (planar order); `None` for a blank or NaN pixel. - let physical = |i: usize| -> Option { - let s = data.get(i * bps..(i + 1) * bps)?; - let raw = match bitpix { - 8 => s.first().map(|&v| v as i64)?, - 16 => i16::from_be_bytes([s[0], s[1]]) as i64, - 32 => i32::from_be_bytes([s[0], s[1], s[2], s[3]]) as i64, - 64 => i64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]), - -32 => return Some(f32::from_be_bytes([s[0], s[1], s[2], s[3]]) as f64 * bscale + bzero).filter(|v| v.is_finite()), - _ => return Some(f64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) * bscale + bzero).filter(|v| v.is_finite()), - }; - if blank == Some(raw) { - return None; - } - Some(raw as f64 * bscale + bzero) - }; - - let top_down = h.string("ROWORDER").is_some_and(|r| r.eq_ignore_ascii_case("TOP-DOWN")); - let (wu, hu) = (w as usize, hgt as usize); - // Planar, bottom-up (by default) → interleaved, top-down. - let dest = |i: usize| -> usize { - let (p, rem) = (i / plane_len, i % plane_len); - let (y, x) = (rem / wu, rem % wu); - let y = if top_down { y } else { hu - 1 - y }; - (y * wu + x) * nplanes + p - }; - - let mut img = match candidate { - SampleType::U8 => { - let mut out = vec![0u8; n]; - for i in 0..n { - out[dest(i)] = physical(i).unwrap_or(0.0) as u8; - } - Image::from_u8(w, hgt, layout, out)? - } - _ => { - let mut out16 = if candidate == SampleType::U16 { Some(vec![0u16; n]) } else { None }; - if let Some(out) = out16.as_mut() { - for i in 0..n { - let v = physical(i).unwrap_or(0.0); - if !(0.0..=65535.0).contains(&v) { - // Signed data with negative values: fall back to float. - out16 = None; - break; - } - out[dest(i)] = v as u16; - } - } - match out16 { - Some(out) => Image::from_u16(w, hgt, layout, &out)?, - None => { - let max = (0..n).filter_map(physical).fold(0.0f64, f64::max); - let white = if max <= 2.0 { - 1.0 - } else if max <= 65535.0 { - 65535.0 - } else { - max - }; - let mut out = vec![0f32; n]; - for i in 0..n { - out[dest(i)] = (physical(i).unwrap_or(0.0) / white) as f32; - } - Image::from_f32(w, hgt, layout, &out)? - } - } - } - }; - - if planes > nplanes as u64 { - img.warnings.push(DecodeWarning::MorePages { total: u32::try_from(planes).ok() }); - } - let mut text = Vec::new(); - for c in primary.iter().flat_map(|p| p.cards.iter()).chain(h.cards.iter()) { - if !c.hierarch && (STRUCTURAL.contains(&c.key.as_str()) || is_naxis(&c.key)) { - continue; - } - let entry = match &c.value { - Some(Value::Str(s) | Value::Raw(s)) => (c.key.clone(), s.clone()), - None if c.key.is_empty() && c.text.trim().is_empty() => continue, - None => (if c.key.is_empty() { "COMMENT".to_string() } else { c.key.clone() }, c.text.trim().to_string()), - }; - text.push(entry); - } - img.text = text; - Ok(img) + bridge::format(Format::Fits, bytes, limits) } - -fn is_naxis(key: &str) -> bool { - key.strip_prefix("NAXIS").is_some_and(|d| d.chars().all(|c| c.is_ascii_digit())) -} - -/// A standard keyword: 1–8 characters from `A-Z 0-9 _ -`. -fn standard_key(key: &str) -> bool { - (1..=8).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_' || b == b'-') -} - -fn ascii(s: &str) -> String { - s.chars().map(|c| if (' '..='~').contains(&c) { c } else { '?' }).collect() -} - -/// A FITS literal (number or logical) that can be written unquoted. -fn literal(v: &str) -> bool { - v == "T" - || v == "F" - || (v.replace(['D', 'd'], "E").parse::().is_ok_and(|f| f.is_finite()) && v.bytes().all(|b| b"0123456789+-.EeDd".contains(&b))) -} - -fn quoted(v: &str, room: usize) -> String { - let mut s = String::from("'"); - for c in ascii(v).chars() { - let add = if c == '\'' { 2 } else { 1 }; - // Keep room for the closing quote. - if s.len() + add + 1 > room { - break; - } - s.push(c); - if c == '\'' { - s.push('\''); - } +pub fn encode(image: &Image) -> Result, CodecError> { + if !matches!(image.layout(), crate::ChannelLayout::Gray | crate::ChannelLayout::Rgb) { + return Err(CodecError::encode("FITS", format!("FITS cannot store {:?}", image.layout()))); } - // Strings are at least eight characters inside the quotes. - while s.len() < 9 { - s.push(' '); - } - s.push('\''); - s -} - -struct Writer { - out: Vec, -} - -impl Writer { - fn card(&mut self, text: &str) { - let mut c: Vec = ascii(text).into_bytes(); - c.truncate(CARD); - c.resize(CARD, b' '); - self.out.extend_from_slice(&c); - } - - fn value(&mut self, key: &str, v: &str) { - if literal(v) { - self.card(&format!("{key:<8}= {v:>20}")); - return; - } - // A string too long for one card goes on in `CONTINUE` cards, every piece but the last - // ending in '&' (FITS 4.0 section 4.2.1.2). A doubled quote is never split, and trailing - // blanks (not significant) are dropped so none are kept before an '&'. - let escaped = ascii(v).trim_end().replace('\'', "''"); - let mut rest = escaped.as_str(); - let mut head = format!("{key:<8}= "); - while rest.len() > CARD - 12 { - let cut = CARD - 13 - rest.get(..CARD - 13).unwrap_or("").bytes().rev().take_while(|&b| b == b'\'').count() % 2; - let (piece, tail) = rest.split_at_checked(cut).unwrap_or((rest, "")); - self.card(&format!("{head}'{piece}&'")); - head = "CONTINUE ".to_string(); - rest = tail; - } - self.card(&format!("{head}'{rest:<8}'")); - } - - fn commentary(&mut self, key: &str, text: &str) { - let chars: Vec = ascii(text).chars().collect(); - if chars.is_empty() { - self.card(key); - } - for chunk in chars.chunks(CARD - 8) { - self.card(&format!("{key:<8}{}", chunk.iter().collect::())); - } - } - - fn text(&mut self, key: &str, v: &str) { - let upper = key.to_ascii_uppercase(); - if matches!(upper.as_str(), "COMMENT" | "HISTORY") { - self.commentary(&upper, v); - } else if standard_key(key) { - // `CONTINUE` only ever carries a string's continuation, written by `value`. - if !STRUCTURAL.contains(&key) && !is_naxis(key) && key != "CONTINUE" { - self.value(key, v); - } - } else { - // Long or mixed-case names (`Description`, `Software`): the HIERARCH convention, - // when the card fits, else a comment. - let name = ascii(key); - let head = format!("HIERARCH {name} = "); - let fits_key = !name.contains('=') && !name.trim().is_empty(); - let body = if literal(v) { v.to_string() } else { quoted(v, CARD.saturating_sub(head.len())) }; - if fits_key && head.len() + body.len() <= CARD && (literal(v) || body.ends_with('\'')) && quoted_whole(v, &body) { - self.card(&format!("{head}{body}")); - } else { - self.commentary("COMMENT", &format!("{key} = {v}")); - } - } - } -} - -/// `body` holds all of `v` (it was not cut short to fit the card). -fn quoted_whole(v: &str, body: &str) -> bool { - literal(v) || body.trim_matches('\'').trim_end().replace("''", "'") == ascii(v).trim_end() -} - -/// Writes `img` (gray or RGB; 8-bit, 16-bit or float) as a single-HDU FITS file, with -/// `img.text` as header cards. -pub fn encode(img: &Image) -> Result, CodecError> { - let (w, h) = (img.width(), img.height()); - let layout = img.layout(); - let nc = match layout { - ChannelLayout::Gray => 1, - ChannelLayout::Rgb => 3, - l => return Err(CodecError::encode(F, format!("FITS cannot store {l:?}"))), - }; - let bitpix = match img.sample_type() { - SampleType::U8 => 8, - SampleType::U16 => 16, - SampleType::F32 => -32, - }; - let mut wr = Writer { out: Vec::new() }; - wr.value("SIMPLE", "T"); - wr.value("BITPIX", &bitpix.to_string()); - wr.value("NAXIS", if nc == 3 { "3" } else { "2" }); - wr.value("NAXIS1", &w.to_string()); - wr.value("NAXIS2", &h.to_string()); - if nc == 3 { - wr.value("NAXIS3", "3"); - } - if bitpix == 16 { - wr.value("BZERO", "32768"); - wr.value("BSCALE", "1"); - } - wr.value("ROWORDER", "BOTTOM-UP"); - for (k, v) in &img.text { - wr.text(k, v); - } - wr.card("END"); - let mut out = wr.out; - out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); - - // Planar, bottom row first. - let (wu, hu) = (w as usize, h as usize); - let idx = |p: usize, y: usize, x: usize| ((hu - 1 - y) * wu + x) * nc + p; - match bitpix { - 8 => { - let d = img.data(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - out.push(d[idx(p, y, x)]); - } - } - } - } - 16 => { - let d = img.to_u16_samples().unwrap_or_default(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - out.extend_from_slice(&((d[idx(p, y, x)] as i32 - 32768) as i16).to_be_bytes()); - } - } - } - } - _ => { - let d = img.to_f32_samples().unwrap_or_default(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - // 0..1 as documented: a value above 2 would make readers (ours too) - // take the data as ADU and scale it by 65535. NaN is written as 0. - let v = d[idx(p, y, x)]; - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - out.extend_from_slice(&v.to_be_bytes()); - } - } - } - } - } - out.resize(out.len().div_ceil(BLOCK) * BLOCK, 0); - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn header(cards: &[&str]) -> Vec { - let mut w = Writer { out: Vec::new() }; - for c in cards { - w.card(c); - } - w.card("END"); - let mut out = w.out; - out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); - out - } - - #[test] - fn continue_strings_decode() { - let mut b = header(&[ - "SIMPLE = T", - "BITPIX = 8", - "NAXIS = 2", - "NAXIS1 = 1", - "NAXIS2 = 1", - "OBJECT = 'aaa&'", - "CONTINUE 'bbb&' / a comment", - "CONTINUE '&'", - "CONTINUE ''", - "OBSERVER= 'R&'", - "COMMENT hi", - "CONTINUE 'orphan'", - ]); - b.push(0); - let img = decode(&b, &Limits::default()).unwrap(); - let text = [("OBJECT", "aaabbb"), ("OBSERVER", "R&"), ("COMMENT", "hi"), ("CONTINUE", "'orphan'")]; - assert_eq!(img.text, text.map(|(k, v)| (k.to_string(), v.to_string()))); - } - - #[test] - fn continue_strings_round_trip() { - for value in ["a".repeat(100), format!("{}' {}", "a".repeat(65), "b".repeat(100)), "'".repeat(100), "a".repeat(68)] { - let mut img = Image::from_u8(1, 1, ChannelLayout::Gray, vec![0]).unwrap(); - img.text = vec![("OBJECT".into(), value.clone()), ("CONTINUE".into(), "orphan".into())]; - let b = encode(&img).unwrap(); - assert!(!b.chunks(CARD).any(|c| c.starts_with(b"CONTINUE="))); - let decoded = decode(&b, &Limits::default()).unwrap(); - assert_eq!(decoded.text, vec![("OBJECT".into(), value)]); - } - } - - #[test] - fn camera_u16_with_bzero_reads_exactly_and_bottom_up() { - let mut b = header(&[ - "SIMPLE = T", - "BITPIX = 16", - "NAXIS = 2", - "NAXIS1 = 2", - "NAXIS2 = 2", - "BZERO = 32768", - "OBJECT = 'M 31 '", - "EXPTIME = 300.0 / seconds", - ]); - for v in [0u16, 1000, 40000, 65535] { - b.extend_from_slice(&((v as i32 - 32768) as i16).to_be_bytes()); - } - b.resize(b.len().div_ceil(BLOCK) * BLOCK, 0); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.sample_type(), SampleType::U16); - // The first stored row is the bottom one. - assert_eq!(img.to_u16_samples().unwrap(), vec![40000, 65535, 0, 1000]); - assert!(img.text.contains(&("OBJECT".into(), "M 31".into()))); - assert!(img.text.contains(&("EXPTIME".into(), "300.0".into()))); - assert!(!img.text.iter().any(|(k, _)| k == "BZERO" || k == "NAXIS1")); - } - - #[test] - fn roworder_top_down_is_honoured() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 2", "ROWORDER= 'TOP-DOWN'"]); - b.extend_from_slice(&[10, 20]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[10, 20]); - } - - #[test] - fn stacked_float_in_adu_is_scaled_by_65535() { - let mut b = header(&["SIMPLE = T", "BITPIX = -32", "NAXIS = 2", "NAXIS1 = 2", "NAXIS2 = 1"]); - for v in [65535.0f32, f32::NAN] { - b.extend_from_slice(&v.to_be_bytes()); - } - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.to_f32_samples().unwrap(), vec![1.0, 0.0]); - } - - #[test] - fn hdr_float_saves_clamped_and_reopens_as_saved() { - // One value above 2 used to make the reader scale everything by 65535 (all black). - let img = Image::from_f32(2, 1, ChannelLayout::Gray, &[0.5, 3.0]).unwrap(); - let bytes = encode(&img).unwrap(); - let back = decode(&bytes, &Limits::default()).unwrap().to_f32_samples().unwrap(); - assert!((back[0] - 0.5).abs() < 1e-6, "{back:?}"); - assert!((back[1] - 1.0).abs() < 1e-6, "{back:?}"); - } - - #[test] - fn signed_negative_data_falls_back_to_float() { - let mut b = header(&["SIMPLE = T", "BITPIX = 16", "NAXIS = 2", "NAXIS1 = 2", "NAXIS2 = 1"]); - for v in [-100i16, 1000] { - b.extend_from_slice(&v.to_be_bytes()); - } - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.sample_type(), SampleType::F32); - } - - #[test] - fn image_extension_after_empty_primary() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T", "TELESCOP= 'Seestar S50'"]); - b.extend(header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1", "PCOUNT = 0", "GCOUNT = 1"])); - b.push(42); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[42]); - assert!(img.text.contains(&("TELESCOP".into(), "Seestar S50".into()))); - } - - /// A zero axis (`NAXIS3 = 0`) means the HDU has no data: it is neither the opened image nor - /// an additional one that a flat save would discard. - #[test] - fn zero_axis_image_hdus_are_empty() { - let empty = |primary: bool| { - let first = if primary { "SIMPLE = T" } else { "XTENSION= 'IMAGE '" }; - header(&[first, "BITPIX = 8", "NAXIS = 3", "NAXIS1 = 1", "NAXIS2 = 1", "NAXIS3 = 0", "PCOUNT = 0", "GCOUNT = 1"]) - }; - let image = || { - let mut b = header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1", "PCOUNT = 0", "GCOUNT = 1"]); - b.push(42); - b.resize(b.len().div_ceil(BLOCK) * BLOCK, 0); - b - }; - let mut after_empty_primary = empty(true); - after_empty_primary.extend(image()); - let mut after_empty_extension = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T"]); - after_empty_extension.extend(empty(false)); - after_empty_extension.extend(image()); - let mut before_empty_extension = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T"]); - before_empty_extension.extend(image()); - before_empty_extension.extend(empty(false)); - for b in [&after_empty_primary, &after_empty_extension, &before_empty_extension] { - assert!(!has_additional_images(b).unwrap()); - assert_eq!(decode(b, &Limits::default()).unwrap().data(), &[42]); - } - // Only empty HDUs: nothing to open, nothing to lose. - assert!(!has_additional_images(&empty(true)).unwrap()); - assert!(decode(&empty(true), &Limits::default()).is_err()); - // A second non-empty image is still additional data. - let mut two = after_empty_primary.clone(); - two.extend(image()); - assert!(has_additional_images(&two).unwrap()); - } - - #[test] - fn fpack_is_refused_as_unsupported() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - b.extend(header(&["XTENSION= 'BINTABLE'", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 0", "NAXIS2 = 0", "ZIMAGE = T"])); - b.extend(header(&["XTENSION= 'BINTABLE'", "BITPIX = 8", "NAXIS = 1", "NAXIS1 = 0"])); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - - /// Hostile headers: absurd or negative axes, bad BITPIX, overflowing sizes, missing END, - /// a long chain of empty HDUs and declared data past the end all error, never panic or - /// allocate the declared size. - #[test] - fn hostile_headers_error_without_panicking() { - let base = ["SIMPLE = T", "BITPIX = 16"]; - let cases: &[&[&str]] = &[ - &["NAXIS = 2", "NAXIS1 = 4294967296", "NAXIS2 = 1"], - &["NAXIS = 2", "NAXIS1 = -5", "NAXIS2 = 1"], - &["NAXIS = 2", "NAXIS1 = 2000000", "NAXIS2 = 2000000"], - &["NAXIS = 3", "NAXIS1 = 65536", "NAXIS2 = 65536", "NAXIS3 = 9223372036854775807"], - &["NAXIS = 1000"], - &["NAXIS = -1"], - &["NAXIS = 2", "NAXIS1 = 0", "NAXIS2 = 0"], - &["NAXIS = 2", "NAXIS1 = 1.5D300", "NAXIS2 = 1"], - &["NAXIS = 2"], - &["NAXIS = 2", "NAXIS1 = 100", "NAXIS2 = 100"], - ]; - for extra in cases { - let cards: Vec<&str> = base.iter().chain(extra.iter()).copied().collect(); - let b = header(&cards); - assert!(decode(&b, &Limits::default()).is_err(), "{extra:?}"); - } - for bitpix in ["0", "7", "-16", "128", "'X'"] { - let card = format!("BITPIX = {bitpix}"); - let b = header(&["SIMPLE = T", &card, "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1"]); - assert!(decode(&b, &Limits::default()).is_err(), "BITPIX {bitpix}"); - } - // No END card: the header runs off the end of the file. - let mut w = Writer { out: Vec::new() }; - for c in ["SIMPLE = T", "BITPIX = 8", "NAXIS = 2"] { - w.card(c); - } - assert!(decode(&w.out, &Limits::default()).is_err()); - // An empty primary followed by many empty extensions: bounded walk, then "no image". - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - for _ in 0..(MAX_HDUS + 5) { - b.extend(header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 0"])); - } - assert!(decode(&b, &Limits::default()).is_err()); - // An extension whose declared data size overflows. - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - b.extend(header(&[ - "XTENSION= 'BINTABLE'", - "BITPIX = 64", - "NAXIS = 2", - "NAXIS1 = 9223372036854775807", - "NAXIS2 = 4", - "PCOUNT = 0", - "GCOUNT = 1", - ])); - assert!(decode(&b, &Limits::default()).is_err()); - } - - #[test] - fn extra_planes_warn() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 3", "NAXIS1 = 1", "NAXIS2 = 1", "NAXIS3 = 4"]); - b.extend_from_slice(&[1, 2, 3, 4]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Gray); - assert_eq!(img.warnings, vec![DecodeWarning::MorePages { total: Some(4) }]); - } - - #[test] - fn strings_with_quotes_and_hierarch_round_trip() { - let mut w = Writer { out: Vec::new() }; - w.text("OBSERVER", "O'Brien"); - w.text("Software", "craft 1.0"); - w.text("HISTORY", "stacked"); - let cards: Vec = w.out.chunks(CARD).map(parse_card).collect(); - assert_eq!(cards[0].value, Some(Value::Str("O'Brien".into()))); - assert!(cards[1].hierarch && cards[1].key == "Software"); - assert_eq!(cards[1].value, Some(Value::Str("craft 1.0".into()))); - assert_eq!((cards[2].key.as_str(), cards[2].text.as_str()), ("HISTORY", "stacked")); - } + bridge::encode(image, Format::Fits, &Default::default()) } diff --git a/crates/raster-codecs/src/iff.rs b/crates/raster-codecs/src/iff.rs index 087ae5046d..95e439a580 100644 --- a/crates/raster-codecs/src/iff.rs +++ b/crates/raster-codecs/src/iff.rs @@ -1,538 +1,16 @@ -//! Amiga IFF/ILBM reader and writer (EA "Interchange File Format", "InterLeaved BitMap" and the -//! chunky "PBM " variant). Written from the published IFF/ILBM layout: a `FORM` chunk of four-byte -//! chunks (`BMHD` bitmap header, `CMAP` palette, `CAMG` Amiga viewport mode, `BODY` pixel data). -//! -//! Read: 1–8 bitplanes with a palette (or a gray ramp when there is none) with masking 0/1/2, and -//! 24-bitplane "deep" ILBMs (8 planes each of red, green and blue, least significant bit first, -//! no palette) with masking 0/1, both stored (0) and ByteRun1/PackBits (1) compressed. Anything -//! else is a clear `Unsupported`/`Malformed` error, never a panic. -//! -//! Write: a 24-bitplane ILBM, ByteRun1 compressed one plane row at a time, with a mask plane -//! (masking 1) when the image has alpha. The mask plane is one bit per pixel: alpha of 128 or -//! more is opaque. +//! IFF/ILBM compatibility facade; implementation lives in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -const F: &str = "IFF"; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) +pub fn looks_like_iff(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Iff) } - -fn unsupported(msg: impl Into) -> CodecError { - CodecError::unsupported(F, msg) +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + bridge::format(Format::Iff, bytes, limits) } - -fn be32(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(4)?)?.try_into().ok()?; - Some(u32::from_be_bytes(s)) -} - -fn be16(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(2)?)?.try_into().ok()?; - Some(u16::from_be_bytes(s)) -} - -/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8. -pub fn looks_like_iff(b: &[u8]) -> bool { - b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM ")) -} - -/// Bitplanes of a "deep" ILBM: red, green and blue, 8 each, least significant bit first. -const DEEP_PLANES: u8 = 24; - -/// The bitmap header fields decoding needs. -struct Header { - width: u32, - height: u32, - planes: u8, - masking: u8, - compression: u8, - transparent: u16, - /// `PBM ` stores one palette index per byte, padded to even row lengths. - chunky: bool, -} - -/// One four-byte chunk's id and byte range. -struct Chunk<'a> { - id: [u8; 4], - data: &'a [u8], -} - -/// Walk the `FORM`'s chunks from offset 12 to `end` (the form length), stopping at the first -/// malformed length so a hostile file can't run past the buffer. -fn chunks(b: &[u8]) -> impl Iterator> { - let end = be32(b, 4).map_or(b.len(), |n| (n as usize).saturating_add(8).min(b.len())); - let mut pos = 12usize; - std::iter::from_fn(move || { - if pos + 8 > end { - return None; - } - let id = b.get(pos..pos + 4)?.try_into().ok()?; - let len = be32(b, pos + 4)? as usize; - let start = pos + 8; - let data = b.get(start..start.checked_add(len)?)?; - // Chunks are padded to an even length. - pos = start.checked_add(len)?.checked_add(len & 1)?; - Some(Chunk { id, data }) - }) -} - -fn parse_header(b: &[u8], chunky: bool) -> Result { - let bmhd = chunks(b).find(|c| &c.id == b"BMHD").ok_or_else(|| bad("no BMHD chunk"))?; - let d = bmhd.data; - if d.len() < 20 { - return Err(bad("BMHD chunk is too short")); +pub fn encode(image: &Image) -> Result, CodecError> { + if !matches!(image.layout(), crate::ChannelLayout::Rgb | crate::ChannelLayout::Rgba) || image.sample_type() != crate::SampleType::U8 { + return Err(CodecError::encode("IFF", "ILBM writer stores 8-bit RGB pixels with optional alpha")); } - let width = u32::from(be16(d, 0).ok_or_else(|| bad("BMHD width"))?); - let height = u32::from(be16(d, 2).ok_or_else(|| bad("BMHD height"))?); - let planes = *d.get(8).ok_or_else(|| bad("BMHD planes"))?; - let masking = *d.get(9).ok_or_else(|| bad("BMHD masking"))?; - let compression = *d.get(10).ok_or_else(|| bad("BMHD compression"))?; - if width == 0 || height == 0 { - return Err(bad("zero-sized bitmap")); - } - if !(1..=8).contains(&planes) && planes != DEEP_PLANES { - return Err(unsupported(format!("{planes} bitplanes (1–8 with a palette, or 24)"))); - } - if masking > 2 { - return Err(unsupported(format!("masking {masking}"))); - } - if planes == DEEP_PLANES && masking == 2 { - return Err(unsupported("a transparent color in a 24-bitplane ILBM")); - } - if compression > 1 { - return Err(unsupported(format!("compression {compression} (only stored and ByteRun1)"))); - } - if chunky && (planes != 8 || masking == 1) { - return Err(unsupported("PBM requires 8-bit indices without a mask plane")); - } - let transparent = be16(d, 12).ok_or_else(|| bad("BMHD transparent colour"))?; - Ok(Header { width, height, planes, masking, compression, transparent, chunky }) -} - -/// ByteRun1 / PackBits decode of one plane row into `out`; returns the bytes consumed. A `0x80` -/// control byte is a no-op, as the layout specifies. -fn unpack_byte_run1(src: &[u8], out: &mut [u8]) -> Result { - let (mut i, mut o) = (0usize, 0usize); - while o < out.len() { - let n = *src.get(i).ok_or_else(|| bad("truncated ByteRun1 data"))? as i8; - i += 1; - if n >= 0 { - let count = n as usize + 1; - let lit = src.get(i..i.checked_add(count).ok_or_else(|| bad("ByteRun1 overflow"))?).ok_or_else(|| bad("truncated ByteRun1 run"))?; - if count > out.len() - o { - return Err(bad("ByteRun1 run crosses the plane row")); - } - out[o..o + count].copy_from_slice(lit); - i += count; - o += count; - } else if n != -128 { - let count = (1 - n as i32) as usize; - let value = *src.get(i).ok_or_else(|| bad("truncated ByteRun1 repeat"))?; - i += 1; - if count > out.len() - o { - return Err(bad("ByteRun1 repeat crosses the plane row")); - } - out[o..o + count].fill(value); - o += count; - } - } - Ok(i) -} - -pub fn decode(b: &[u8], limits: &Limits) -> Result { - if !looks_like_iff(b) { - return Err(bad("not an IFF/ILBM file (no FORM ... ILBM)")); - } - let h = parse_header(b, b.get(8..12) == Some(b"PBM "))?; - if let Some(camg) = chunks(b).find(|c| &c.id == b"CAMG") { - let mode = be32(camg.data, 0).ok_or_else(|| bad("short CAMG chunk"))?; - if mode & (0x80 | 0x800) != 0 { - return Err(unsupported("EHB and HAM viewport modes")); - } - } - let layout = if h.masking == 0 { ChannelLayout::Rgb } else { ChannelLayout::Rgba }; - limits.check(h.width, h.height, layout, SampleType::U8)?; - - // Palette: three bytes per colour; missing entries read as black. - let cmap = chunks(b).find(|c| &c.id == b"CMAP").map(|c| c.data).filter(|p| !p.is_empty()); - let colors = 1usize << h.planes; - let palette = |idx: usize| -> [u8; 3] { - if let Some(p) = cmap { - p.get(idx * 3..idx * 3 + 3).map(|c| [c[0], c[1], c[2]]).unwrap_or([0; 3]) - } else { - let v = ((idx as u32 * 255) / (colors as u32 - 1).max(1)) as u8; - [v, v, v] - } - }; - - let body = chunks(b).find(|c| &c.id == b"BODY").map(|c| c.data).ok_or_else(|| bad("no BODY chunk"))?; - let (w, hh) = (h.width as usize, h.height as usize); - // Each plane row is stored as a whole number of 16-bit words. - let plane_row = if h.chunky { w.div_ceil(2) * 2 } else { w.div_ceil(16) * 2 }; - // A masking type 1 bitmap carries one extra (mask) plane per row. - let rows_planes: usize = if h.chunky { 1 } else { usize::from(h.planes) + usize::from(h.masking == 1) }; - - // Decode every stored plane row up front, then recombine. - let total_rows = hh.checked_mul(rows_planes).ok_or_else(|| CodecError::LimitExceeded("bitmap too large".into()))?; - let total_bytes = total_rows.checked_mul(plane_row).ok_or_else(|| CodecError::LimitExceeded("bitmap too large".into()))?; - if total_bytes as u64 > limits.max_alloc { - return Err(CodecError::LimitExceeded("bitmap storage exceeds max_alloc".into())); - } - Limits::check_plausible(total_bytes as u64, body.len(), if h.compression == 0 { 1 } else { 128 })?; - let mut stored = crate::alloc_zeroed::(total_bytes)?; - let mut cursor = 0usize; - for row in stored.chunks_mut(plane_row.max(1)).take(total_rows) { - match h.compression { - 0 => { - let src = - body.get(cursor..cursor.checked_add(plane_row).ok_or_else(|| bad("BODY overflow"))?).ok_or_else(|| bad("truncated BODY data"))?; - let n = row.len().min(src.len()); - row[..n].copy_from_slice(&src[..n]); - cursor += plane_row; - } - _ => { - let tail = body.get(cursor..).ok_or_else(|| bad("truncated BODY data"))?; - cursor += unpack_byte_run1(tail, row)?; - } - } - } - - let mut out = Vec::new(); - out.try_reserve_exact(w.saturating_mul(hh).saturating_mul(layout.channels())) - .map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?; - let planes = usize::from(h.planes); - for y in 0..hh { - for x in 0..w { - let index = if h.chunky { - usize::from(*stored.get(y * plane_row + x).ok_or_else(|| bad("PBM pixel outside BODY"))?) - } else { - (0..planes).filter(|&p| bit_at(&stored, (y * rows_planes + p) * plane_row, x)).fold(0usize, |acc, p| acc | (1 << p)) - }; - let c = if h.planes == DEEP_PLANES { [index as u8, (index >> 8) as u8, (index >> 16) as u8] } else { palette(index) }; - out.extend_from_slice(&c); - if h.masking != 0 { - let opaque = - if h.masking == 1 { bit_at(&stored, (y * rows_planes + planes) * plane_row, x) } else { index != usize::from(h.transparent) }; - out.push(if opaque { 255 } else { 0 }); - } - } - } - Image::from_u8(h.width, h.height, layout, out) -} - -/// The bit for pixel `x` of a stored plane row at `base` (bits run MSB-first). -fn bit_at(stored: &[u8], base: usize, x: usize) -> bool { - stored.get(base + x / 8).is_some_and(|byte| byte & (0x80 >> (x % 8)) != 0) -} - -/// ByteRun1 / PackBits encode of one plane row, appended to `out`: three or more equal bytes -/// become a repeat (at most 128), everything else literal runs (at most 128 bytes). -fn pack_byte_run1(row: &[u8], out: &mut Vec) { - let mut i = 0usize; - while let Some(&value) = row.get(i) { - let repeat = row[i..].iter().take(128).take_while(|&&b| b == value).count(); - if repeat >= 3 { - out.push((1 - repeat as i32) as i8 as u8); - out.push(value); - i += repeat; - continue; - } - let start = i; - while i < row.len() && i - start < 128 { - if row.get(i..i + 3).is_some_and(|r| r[0] == r[1] && r[1] == r[2]) { - break; - } - i += 1; - } - out.push((i - start - 1) as u8); - out.extend_from_slice(&row[start..i]); - } -} - -fn push_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<(), CodecError> { - let len = u32::try_from(data.len()).map_err(|_| CodecError::encode(F, "chunk too large for an IFF file (4 GiB)"))?; - out.extend_from_slice(id); - out.extend_from_slice(&len.to_be_bytes()); - out.extend_from_slice(data); - // Chunks are padded to an even length. - if data.len() % 2 == 1 { - out.push(0); - } - Ok(()) -} - -/// Writes a 24-bitplane `FORM ILBM`: `BMHD` then a ByteRun1-compressed `BODY`, each row stored as -/// the red, green and blue planes (least significant bit first) and, for RGBA, a mask plane. -pub fn encode(img: &Image) -> Result, CodecError> { - let enc = |msg: String| CodecError::encode(F, msg); - let masked = match img.layout() { - ChannelLayout::Rgb => false, - ChannelLayout::Rgba => true, - l => return Err(enc(format!("IFF/ILBM cannot store {l:?}"))), - }; - if img.sample_type() != SampleType::U8 { - return Err(enc(format!("IFF/ILBM cannot store {:?} samples", img.sample_type()))); - } - let (w, h) = (img.width(), img.height()); - let (Ok(w16), Ok(h16)) = (u16::try_from(w), u16::try_from(h)) else { - return Err(enc("IFF/ILBM stores at most 65535 × 65535 pixels".into())); - }; - let (w, ch) = (w as usize, img.layout().channels()); - let data = img.data(); - let row_len = w.checked_mul(ch).ok_or_else(|| enc("image too large".into()))?; - if data.len() != row_len.checked_mul(h as usize).ok_or_else(|| enc("image too large".into()))? { - return Err(enc("the image has the wrong number of samples".into())); - } - let planes = usize::from(DEEP_PLANES) + usize::from(masked); - let mut plane_row = vec![0u8; w.div_ceil(16) * 2]; - let mut body = Vec::new(); - for px in data.chunks_exact(row_len.max(1)) { - for plane in 0..planes { - plane_row.fill(0); - for (x, p) in px.chunks_exact(ch).enumerate() { - let on = if plane == usize::from(DEEP_PLANES) { p[3] >= 128 } else { (p[plane / 8] >> (plane % 8)) & 1 == 1 }; - if on { - plane_row[x / 8] |= 0x80 >> (x % 8); - } - } - pack_byte_run1(&plane_row, &mut body); - } - } - - let mut bmhd = Vec::with_capacity(20); - bmhd.extend_from_slice(&w16.to_be_bytes()); - bmhd.extend_from_slice(&h16.to_be_bytes()); - bmhd.extend_from_slice(&[0, 0, 0, 0]); // x/y origin - bmhd.push(DEEP_PLANES); - bmhd.push(u8::from(masked)); // masking: 1 = a mask plane follows the color planes - bmhd.push(1); // ByteRun1 - bmhd.push(0); // pad - bmhd.extend_from_slice(&[0, 0]); // transparent color (unused) - bmhd.extend_from_slice(&[1, 1]); // square pixels - bmhd.extend_from_slice(&w16.to_be_bytes()); // page size - bmhd.extend_from_slice(&h16.to_be_bytes()); - - let mut out = b"FORM".to_vec(); - out.extend_from_slice(&[0; 4]); // patched below - out.extend_from_slice(b"ILBM"); - push_chunk(&mut out, b"BMHD", &bmhd)?; - push_chunk(&mut out, b"BODY", &body)?; - let form_len = u32::try_from(out.len() - 8).map_err(|_| enc("image too large for an IFF file (4 GiB)".into()))?; - out[4..8].copy_from_slice(&form_len.to_be_bytes()); - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A `FORM ILBM` with a `BMHD`, `CMAP` and `BODY`. `planes` plane rows per row, - /// `compression` 0 (stored) or 1 (ByteRun1), MSB-first. - fn ilbm(w: u16, h: u16, planes: u8, palette: &[[u8; 3]], compression: u8, body: &[u8]) -> Vec { - let mut b = b"FORM".to_vec(); - b.extend_from_slice(&0u32.to_be_bytes()); // patched below - b.extend_from_slice(b"ILBM"); - // BMHD (20 bytes) - b.extend_from_slice(b"BMHD"); - b.extend_from_slice(&20u32.to_be_bytes()); - b.extend_from_slice(&w.to_be_bytes()); - b.extend_from_slice(&h.to_be_bytes()); - b.extend_from_slice(&[0, 0, 0, 0]); // x/y origin - b.push(planes); - b.push(0); // masking - b.push(compression); - b.push(0); // pad - b.extend_from_slice(&[0, 0]); // transparent colour - b.extend_from_slice(&[1, 1]); // aspect - b.extend_from_slice(&[0, 0, 0, 0]); // page size - // CMAP - b.extend_from_slice(b"CMAP"); - b.extend_from_slice(&((palette.len() * 3) as u32).to_be_bytes()); - for c in palette { - b.extend_from_slice(c); - } - if palette.len() % 2 == 1 { - b.push(0); - } - // BODY - b.extend_from_slice(b"BODY"); - b.extend_from_slice(&(body.len() as u32).to_be_bytes()); - b.extend_from_slice(body); - if body.len() % 2 == 1 { - b.push(0); - } - let size = (b.len() - 8) as u32; - b[4..8].copy_from_slice(&size.to_be_bytes()); - b - } - - #[test] - fn reads_a_stored_two_plane_bitmap() { - // 2×1, 2 planes: pixel 0 index 0 (plane bits 0,0), pixel 1 index 3 (bits 1,1). - // Plane 0 = 0b0100_0000, plane 1 = 0b0100_0000, each padded to 2 bytes. - let body = [0b0100_0000, 0, 0b0100_0000, 0]; - let pal = [[10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120]]; - let b = ilbm(2, 1, 2, &pal, 0, &body); - assert!(looks_like_iff(&b)); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); - assert_eq!(img.data(), &[10, 20, 30, 100, 110, 120]); - } - - #[test] - fn reads_byte_run1_compressed_rows() { - // Same image, ByteRun1: literal run of two bytes (0x01) then the two plane bytes each row. - let body = [0x01, 0b0100_0000, 0, 0x01, 0b0100_0000, 0]; - let pal = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [250, 251, 252]]; - let b = ilbm(2, 1, 2, &pal, 1, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[1, 2, 3, 250, 251, 252]); - } - - #[test] - fn no_palette_falls_back_to_a_grey_ramp() { - // 2×1, 1 plane, no CMAP: indices 0 and 1 → black and white. - let body = [0b0100_0000, 0]; - let b = ilbm(2, 1, 1, &[], 0, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[0, 0, 0, 255, 255, 255]); - } - - #[test] - fn pbm_reads_chunky_indices_with_odd_width_padding() { - let pal = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]; - for (compression, body) in [(0, vec![2, 0, 1, 255, 1, 2, 0, 255]), (1, vec![3, 2, 0, 1, 255, 3, 1, 2, 0, 255])] { - let mut b = ilbm(3, 2, 8, &pal, compression, &body); - b[8..12].copy_from_slice(b"PBM "); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[70, 80, 90, 10, 20, 30, 40, 50, 60, 40, 50, 60, 70, 80, 90, 10, 20, 30]); - } - } - - #[test] - fn transparency_uses_the_mask_plane_or_transparent_index() { - for masking in [1, 2] { - let mut b = ilbm(2, 1, 1, &[[10, 20, 30], [40, 50, 60]], 0, if masking == 1 { &[0x40, 0, 0x40, 0] } else { &[0x40, 0] }); - b[29] = masking; - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Rgba); - assert_eq!(img.data(), &[10, 20, 30, 0, 40, 50, 60, 255]); - } - let mut b = ilbm(2, 1, 8, &[[10, 20, 30], [40, 50, 60]], 0, &[0, 1]); - b[8..12].copy_from_slice(b"PBM "); - b[29] = 2; - b[32..34].copy_from_slice(&1u16.to_be_bytes()); - assert_eq!(decode(&b, &Limits::default()).unwrap().data(), &[10, 20, 30, 255, 40, 50, 60, 0]); - } - - #[test] - fn rejects_ham_and_ehb_instead_of_returning_wrong_colours() { - for mode in [0x80u32, 0x800] { - let mut b = ilbm(1, 1, 1, &[], 0, &[0, 0]); - b.extend_from_slice(b"CAMG"); - b.extend_from_slice(&4u32.to_be_bytes()); - b.extend_from_slice(&mode.to_be_bytes()); - let len = (b.len() - 8) as u32; - b[4..8].copy_from_slice(&len.to_be_bytes()); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - } - - #[test] - fn missing_palette_entries_are_black() { - let b = ilbm(1, 1, 2, &[[10, 20, 30]], 0, &[0x80, 0, 0x80, 0]); - assert_eq!(decode(&b, &Limits::default()).unwrap().data(), &[0, 0, 0]); - } - - #[test] - fn reads_a_stored_24_plane_bitmap() { - // 2×1: pixel 0 = (1, 0, 128), pixel 1 = (0, 255, 0). Each plane row is 2 bytes; red bit 0 - // has pixel 0 set, green bits 0–7 have pixel 1 set, blue bit 7 has pixel 0 set. - let mut body = Vec::new(); - for plane in 0..24 { - let byte = match plane { - 0 | 23 => 0x80, - 8..=15 => 0x40, - _ => 0, - }; - body.extend_from_slice(&[byte, 0]); - } - let b = ilbm(2, 1, 24, &[], 0, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); - assert_eq!(img.data(), &[1, 0, 128, 0, 255, 0]); - } - - #[test] - fn writes_24_plane_byte_run1_that_reads_back_exactly() { - // 37 pixels wide: three plane-row words, the last one partly padding. - let (w, h) = (37u32, 3u32); - let data: Vec = (0..w * h * 3).map(|i| (i * 7 % 256) as u8).collect(); - let img = Image::from_u8(w, h, ChannelLayout::Rgb, data.clone()).unwrap(); - let bytes = encode(&img).unwrap(); - assert!(looks_like_iff(&bytes)); - assert_eq!(be32(&bytes, 4).unwrap() as usize, bytes.len() - 8, "FORM length"); - let h = parse_header(&bytes, false).unwrap(); - assert_eq!((h.width, h.height, h.planes, h.masking, h.compression), (37, 3, 24, 0, 1)); - assert!(chunks(&bytes).all(|c| &c.id != b"CMAP"), "a deep ILBM has no palette"); - let back = decode(&bytes, &Limits::default()).unwrap(); - assert_eq!(back.layout(), ChannelLayout::Rgb); - assert_eq!(back.data(), &data[..]); - } - - #[test] - fn alpha_is_written_as_a_mask_plane() { - let data = [10, 20, 30, 0, 40, 50, 60, 127, 70, 80, 90, 128, 1, 2, 3, 255]; - let img = Image::from_u8(4, 1, ChannelLayout::Rgba, data.to_vec()).unwrap(); - let bytes = encode(&img).unwrap(); - assert_eq!(parse_header(&bytes, false).unwrap().masking, 1); - let back = decode(&bytes, &Limits::default()).unwrap(); - assert_eq!(back.layout(), ChannelLayout::Rgba); - assert_eq!(back.data(), &[10, 20, 30, 0, 40, 50, 60, 0, 70, 80, 90, 255, 1, 2, 3, 255]); - } - - #[test] - fn byte_run1_round_trips_runs_literals_and_long_rows() { - let mut rows: Vec> = vec![vec![], vec![5], vec![5, 5], vec![5, 5, 5], vec![1, 2, 2, 2, 3], vec![9; 300]]; - rows.push((0..300).map(|i| (i % 251) as u8).collect()); - rows.push([vec![1, 2], vec![7; 129], vec![3]].concat()); - for row in rows { - let mut packed = Vec::new(); - pack_byte_run1(&row, &mut packed); - let mut back = vec![0; row.len()]; - assert_eq!(unpack_byte_run1(&packed, &mut back).unwrap(), packed.len(), "{row:?}"); - assert_eq!(back, row); - } - // A long repeat packs into two-byte runs. - let mut packed = Vec::new(); - pack_byte_run1(&[0; 256], &mut packed); - assert_eq!(packed, [0x81, 0, 0x81, 0]); - } - - #[test] - fn rejects_what_ilbm_cannot_store() { - let gray = Image::from_u8(1, 1, ChannelLayout::Gray, vec![0]).unwrap(); - assert!(encode(&gray).is_err()); - let wide = Image::from_u8(65536, 1, ChannelLayout::Rgb, vec![0; 65536 * 3]).unwrap(); - assert!(encode(&wide).is_err()); - // A transparent color index has no meaning without a palette. - let mut b = ilbm(1, 1, 24, &[], 0, &[0; 48]); - b[29] = 2; - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - - #[test] - fn hostile_input_errors_not_panics() { - // Truncations of a valid file never panic. - let body = [0b0100_0000, 0, 0b0100_0000, 0]; - let full = ilbm(2, 1, 2, &[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], 0, &body); - for cut in [0, 4, 8, 12, 40, full.len() - 1] { - assert!(decode(&full[..cut.min(full.len())], &Limits::default()).is_err(), "cut {cut}"); - } - // Too many planes is unsupported. - let bad = ilbm(1, 1, 9, &[], 0, &[0, 0]); - assert!(matches!(decode(&bad, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } + bridge::encode(image, Format::Iff, &Default::default()) } diff --git a/crates/raster-codecs/src/lib.rs b/crates/raster-codecs/src/lib.rs index 5b335a30cb..7e705da998 100644 --- a/crates/raster-codecs/src/lib.rs +++ b/crates/raster-codecs/src/lib.rs @@ -18,10 +18,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod bridge; /// Common bounded decoding and PNG/JPEG encoding for common image formats. pub mod common; pub mod dds; -mod dds_bc; pub mod dicom; pub mod fits; pub mod iff; @@ -215,47 +215,32 @@ impl Limits { /// Validates declared dimensions for an output buffer of the given layout and sample type. pub fn check(&self, width: u32, height: u32, layout: ChannelLayout, sample: SampleType) -> Result<(), CodecError> { - if width == 0 || height == 0 { - return Err(CodecError::InvalidImage(format!("zero-sized image {width}x{height}"))); - } - if width > self.max_width || height > self.max_height { - return Err(CodecError::LimitExceeded(format!("dimensions {width}x{height} exceed max {}x{}", self.max_width, self.max_height))); - } - let pixels = width as u64 * height as u64; - if pixels > self.max_pixels { - return Err(CodecError::LimitExceeded(format!("{pixels} pixels exceed max {}", self.max_pixels))); - } - let bytes = pixels.saturating_mul((layout.channels() * sample.bytes()) as u64); - if bytes > self.max_alloc { - return Err(CodecError::LimitExceeded(format!("{bytes} bytes exceed max_alloc {}", self.max_alloc))); - } - if usize::try_from(bytes).is_err() { - return Err(CodecError::LimitExceeded(format!("{bytes} bytes do not fit in memory"))); - } - Ok(()) + let layout = match layout { + ChannelLayout::Gray => craft_image_codecs::ChannelLayout::Gray, + ChannelLayout::GrayA => craft_image_codecs::ChannelLayout::GrayA, + ChannelLayout::Rgb => craft_image_codecs::ChannelLayout::Rgb, + ChannelLayout::Rgba => craft_image_codecs::ChannelLayout::Rgba, + ChannelLayout::Cmyk => craft_image_codecs::ChannelLayout::Cmyk, + ChannelLayout::CmykA => craft_image_codecs::ChannelLayout::CmykA, + }; + let sample = match sample { + SampleType::U8 => craft_image_codecs::SampleType::U8, + SampleType::U16 => craft_image_codecs::SampleType::U16, + SampleType::F32 => craft_image_codecs::SampleType::F32, + }; + craft_image_codecs::Limits::new(self.max_width, self.max_height, self.max_pixels, self.max_alloc) + .check(width, height, layout, sample) + .map_err(crate::bridge::from_shared_error) } /// Decompression-bomb guard for formats that compress: refuses a file too small to hold /// `declared_bytes` of stored image data when the compression never beats `max_ratio`:1. /// Called before the output buffer is allocated. 1 MiB of slack leaves tiny images alone. - pub(crate) fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> { - let capacity = (file_len as u64).saturating_mul(max_ratio).saturating_add(1 << 20); - if declared_bytes > capacity { - return Err(CodecError::LimitExceeded(format!("a {file_len} byte file cannot hold {declared_bytes} bytes of image data"))); - } - Ok(()) + pub fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> { + craft_image_codecs::Limits::check_plausible(declared_bytes, file_len, max_ratio).map_err(crate::bridge::from_shared_error) } } -/// A zero-filled buffer of `len` elements, allocated fallibly: an allocation failure is -/// [`CodecError::LimitExceeded`] instead of an abort. -pub(crate) fn alloc_zeroed(len: usize) -> Result, CodecError> { - let mut v = Vec::new(); - v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")))?; - v.resize(len, T::default()); - Ok(v) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/raster-codecs/src/pcx.rs b/crates/raster-codecs/src/pcx.rs index 00117bcf1b..61c4765112 100644 --- a/crates/raster-codecs/src/pcx.rs +++ b/crates/raster-codecs/src/pcx.rs @@ -1,144 +1,13 @@ -//! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour -//! palettes, 8-bit three-plane RGB and four-plane RGBA. Read-only: modern saves should use PNG. +//! PCX compatibility facade; implementation and header probing live in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -const HEADER: usize = 128; - -fn bad(reason: impl std::fmt::Display) -> CodecError { - CodecError::malformed("PCX", reason) +pub fn looks_like_pcx(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Pcx) } -fn le16(b: &[u8], i: usize) -> u16 { - u16::from_le_bytes([b[i], b[i + 1]]) +pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> { + craft_image_codecs::pcx_dimensions(bytes) } - -/// PCX lacks a strong magic number. Require plausible complete header fields before -/// identifying it, rather than classifying every file starting with 0x0a as PCX. -pub fn looks_like_pcx(b: &[u8]) -> bool { - if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2..=5) || b[2] != 1 { - return false; - } - let bits = b[3]; - let planes = b[65]; - let stride = u32::from(le16(b, 66)); - let (x0, y0, x1, y1) = (le16(b, 4), le16(b, 6), le16(b, 8), le16(b, 10)); - if x1 < x0 || y1 < y0 || !matches!(bits, 1 | 2 | 4 | 8) || !(1..=4).contains(&planes) { - return false; - } - let width = u32::from(x1 - x0) + 1; - let min_stride = (width * u32::from(bits)).div_ceil(8); - stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3 | 4)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4) -} - -/// Read one compressed scanline, including all planes. RLE packets never cross a scanline. -fn read_row(b: &[u8], pos: &mut usize, out: &mut [u8]) -> Result<(), CodecError> { - let mut n = 0; - while n < out.len() { - let code = *b.get(*pos).ok_or_else(|| bad("truncated pixel RLE"))?; - *pos += 1; - let (count, value) = if code >= 0xc0 { - let count = usize::from(code & 0x3f); - let value = *b.get(*pos).ok_or_else(|| bad("truncated RLE packet"))?; - *pos += 1; - (count, value) - } else { - (1, code) - }; - if count == 0 || count > out.len() - n { - return Err(bad("RLE packet crosses a scanline or has zero length")); - } - out[n..n + count].fill(value); - n += count; - } - Ok(()) -} - -/// The pixel size a PCX header declares, without decoding; `None` when [`looks_like_pcx`] is false. -pub fn dimensions(b: &[u8]) -> Option<(u32, u32)> { - looks_like_pcx(b).then(|| (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1)) -} - -/// Decodes to 8-bit RGB, or RGBA for four 8-bit planes (red, green, blue, alpha). -pub fn decode(b: &[u8], limits: &Limits) -> Result { - let (w, h) = dimensions(b).ok_or_else(|| bad("invalid PCX header or unsupported pixel layout"))?; - let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66))); - let layout = if bits == 8 && planes == 4 { ChannelLayout::Rgba } else { ChannelLayout::Rgb }; - let ch = layout.channels(); - limits.check(w, h, layout, SampleType::U8)?; - let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?; - let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(ch)).ok_or_else(|| bad("pixel size overflow"))?; - // The last 769 bytes are the optional VGA palette for 8-bit indexed images. - let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c; - if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 { - return Err(bad("8-bit indexed PCX has no 256-colour palette")); - } - let image_end = if vga { b.len() - 769 } else { b.len() }; - // A 63-byte RLE packet takes 2 bytes; a trailing remainder of 1 byte below 0xC0 - // can be encoded as a 1-byte literal, while any larger remainder takes at least 2 bytes. - // Because RLE packets may span planes within a scanline (`row_len`), compute the - // minimum encoded bytes across the full scanline (`row_len`) and multiply by `h`. - // Reject inputs that cannot possibly contain all scanlines before allocating - // the decoded image buffer. - let min_packets = (row_len / 63) - .checked_mul(2) - .and_then(|n| { - n.checked_add(match row_len % 63 { - 0 => 0, - 1 => 1, - _ => 2, - }) - }) - .ok_or_else(|| bad("compressed row size overflow"))?; - let min_encoded = min_packets.checked_mul(h as usize).ok_or_else(|| bad("compressed image size overflow"))?; - let encoded_len = image_end.saturating_sub(HEADER); - if encoded_len < min_encoded { - return Err(bad("PCX pixel data is too short for the declared image")); - } - let mut row = vec![0u8; row_len]; - let mut pixels = Vec::new(); - pixels.try_reserve_exact(total).map_err(|_| bad("PCX pixel buffer is too large"))?; - pixels.resize(total, 0); - let mut p = HEADER; - let width = w as usize; - for y in 0..h as usize { - read_row(&b[..image_end], &mut p, &mut row)?; - for x in 0..width { - let at = (y * width + x) * ch; - let rgb = if bits == 8 && planes >= 3 { - if planes == 4 { - pixels[at + 3] = row[3 * stride + x]; - } - [row[x], row[stride + x], row[2 * stride + x]] - } else { - let index = if bits == 8 { - usize::from(row[x]) - } else { - let bit = x * bits; - let shift = 8 - bits - (bit % 8); - let mask = (1usize << bits) - 1; - (0..planes).fold(0usize, |v, plane| { - let sample = (usize::from(row[plane * stride + bit / 8]) >> shift) & mask; - v | sample << (plane * bits) - }) - }; - if vga { - let o = image_end + 1 + index * 3; - [b[o], b[o + 1], b[o + 2]] - } else if bits == 8 { - let g = index as u8; - [g, g, g] // palette-info 2: gray scale - } else { - let o = 16 + index * 3; - [b[o], b[o + 1], b[o + 2]] - } - }; - pixels[at..at + 3].copy_from_slice(&rgb); - } - } - let mut image = Image::from_u8(w, h, layout, pixels)?; - let (xdpi, ydpi) = (le16(b, 12), le16(b, 14)); - if xdpi > 0 && ydpi > 0 { - image.dpi = Some((f32::from(xdpi), f32::from(ydpi))); - } - Ok(image) +pub fn decode(bytes: &[u8], limits: &Limits) -> Result { + bridge::format(Format::Pcx, bytes, limits) } diff --git a/crates/raster-codecs/src/pnm.rs b/crates/raster-codecs/src/pnm.rs index 6ef1409023..338938700e 100644 --- a/crates/raster-codecs/src/pnm.rs +++ b/crates/raster-codecs/src/pnm.rs @@ -1,357 +1,18 @@ -//! Netpbm family, implemented here: P1–P6 (PBM/PGM/PPM, ASCII and binary), -//! P7 (PAM, including the common `CMYK`/`CMYK_ALPHA` tuple types) and PFM -//! (`PF` colour / `Pf` gray float). -//! -//! Writing picks the subtype from the image: float → PFM (gray/RGB), gray -//! → P5, RGB → P6, anything with alpha or CMYK → P7. +//! Netpbm compatibility facade; implementation and bounds live in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -const F: &str = "PNM"; - -fn err(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) +pub fn looks_like_pnm(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Pnm) } - -struct Reader<'a> { - b: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - fn skip_ws_and_comments(&mut self) { - while self.pos < self.b.len() { - let c = self.b[self.pos]; - if c == b'#' { - while self.pos < self.b.len() && self.b[self.pos] != b'\n' && self.b[self.pos] != b'\r' { - self.pos += 1; - } - } else if c.is_ascii_whitespace() { - self.pos += 1; - } else { - break; - } - } - } - - fn token(&mut self) -> Result<&'a [u8], CodecError> { - self.skip_ws_and_comments(); - let start = self.pos; - while self.pos < self.b.len() && !self.b[self.pos].is_ascii_whitespace() && self.b[self.pos] != b'#' { - self.pos += 1; - } - if start == self.pos { - return Err(err("unexpected end of header")); - } - Ok(&self.b[start..self.pos]) - } - - fn uint(&mut self) -> Result { - let t = self.token()?; - std::str::from_utf8(t).ok().and_then(|s| s.parse::().ok()).ok_or_else(|| err("invalid integer in header")) - } - - /// Consume the single whitespace byte that separates header and raster. - fn single_ws(&mut self) -> Result<(), CodecError> { - match self.b.get(self.pos) { - Some(c) if c.is_ascii_whitespace() => { - self.pos += 1; - Ok(()) - } - _ => Err(err("missing whitespace after header")), - } - } - - /// PAM ends its header with an LF-terminated line, unlike P4–P6's single separator. - fn pam_endhdr(&mut self) -> Result<(), CodecError> { - while let Some(&c) = self.b.get(self.pos) { - self.pos += 1; - if c == b'\n' { - // Stop at the first LF: whitespace and '#' after it are raster bytes. - return Ok(()); - } - if !c.is_ascii_whitespace() { - return Err(err("unexpected data after PAM ENDHDR")); - } - } - Err(err("unterminated PAM ENDHDR line")) - } - - fn rest(&self) -> &'a [u8] { - &self.b[self.pos.min(self.b.len())..] - } -} - -fn sample_for_maxval(maxval: u32) -> Result { - match maxval { - 1..=255 => Ok(SampleType::U8), - 256..=65535 => Ok(SampleType::U16), - _ => Err(err(format!("invalid maxval {maxval}"))), - } -} - -/// The decoded raster, built straight in the output representation. It is the only buffer sized -/// by the header, so `Limits::check` on the output budgets all of it: no wider scratch buffer -/// (such as one `u32` per sample) sits beside it. -struct Samples { - maxval: u32, - sample: SampleType, - bytes: Vec, -} - -impl Samples { - /// Reserve room for `cap` samples (callers bound `cap` by the file length where the header - /// alone could overstate it). - fn with_capacity(maxval: u32, cap: usize) -> Result { - let sample = sample_for_maxval(maxval)?; - let len = cap.checked_mul(sample.bytes()).ok_or_else(|| CodecError::LimitExceeded(format!("{cap} samples do not fit in memory")))?; - let mut bytes = Vec::new(); - bytes.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} bytes for the image")))?; - Ok(Samples { maxval, sample, bytes }) - } - - /// Append one raw value in `[0, maxval]`, rescaled to the full range of the output sample. - fn push(&mut self, v: u32) -> Result<(), CodecError> { - let m = self.maxval; - if v > m { - return Err(err("sample exceeds maxval")); - } - match (self.sample, m) { - (SampleType::U8, 255) => self.bytes.push(v as u8), - (SampleType::U8, m) => self.bytes.push(((v * 255 + m / 2) / m) as u8), - (_, 65535) => self.bytes.extend_from_slice(&(v as u16).to_ne_bytes()), - (_, m) => self.bytes.extend_from_slice(&(((v as u64 * 65535 + m as u64 / 2) / m as u64) as u16).to_ne_bytes()), - } - Ok(()) - } - - fn into_image(self, w: u32, h: u32, layout: ChannelLayout) -> Result { - Image::from_raw(w, h, layout, self.sample, self.bytes) - } -} - -/// `w × h × channels` samples. `Limits::none()` lets any header through, so the product is -/// checked here rather than trusted to the limits. -fn sample_count(w: u32, h: u32, channels: usize) -> Result { - (w as usize) - .checked_mul(h as usize) - .and_then(|p| p.checked_mul(channels)) - .ok_or_else(|| CodecError::LimitExceeded(format!("{w}x{h}x{channels} samples do not fit in memory"))) -} - -fn read_binary(data: &[u8], n: usize, maxval: u32) -> Result { - let mut out = Samples::with_capacity(maxval, n)?; - if maxval < 256 { - let Some(raw) = data.get(..n) else { - return Err(err("truncated raster")); - }; - for &v in raw { - out.push(v as u32)?; - } - } else { - let Some(raw) = n.checked_mul(2).and_then(|len| data.get(..len)) else { - return Err(err("truncated raster")); - }; - for c in raw.as_chunks::<2>().0 { - out.push(u16::from_be_bytes(*c) as u32)?; - } - } - Ok(out) -} - -/// `P1`..`P7`, `PF` or `Pf` followed by white space. -pub fn looks_like_pnm(b: &[u8]) -> bool { - matches!(b, [b'P', b'1'..=b'7' | b'F' | b'f', s, ..] if s.is_ascii_whitespace()) -} - pub fn decode(bytes: &[u8], limits: &Limits) -> Result { - if bytes.len() < 2 || bytes[0] != b'P' { - return Err(err("not a Netpbm file")); - } - let kind = bytes[1]; - let mut r = Reader { b: bytes, pos: 2 }; - match kind { - b'1' | b'4' => { - let (w, h) = (r.uint()?, r.uint()?); - limits.check(w, h, ChannelLayout::Gray, SampleType::U8)?; - let n = sample_count(w, h, 1)?; - let mut px; - if kind == b'4' { - r.single_ws()?; - let row = (w as usize).div_ceil(8); - let data = r.rest(); - if row.checked_mul(h as usize).is_none_or(|len| data.len() < len) { - return Err(err("truncated raster")); - } - px = Vec::with_capacity(n); - for y in 0..h as usize { - for x in 0..w as usize { - let bit = (data[y * row + x / 8] >> (7 - x % 8)) & 1; - px.push(if bit == 1 { 0 } else { 255 }); - } - } - } else { - // Each ASCII pixel takes at least a byte, so the file bounds the reservation. - px = Vec::with_capacity(n.min(r.rest().len())); - while px.len() < n { - r.skip_ws_and_comments(); - match r.b.get(r.pos) { - Some(b'0') => px.push(255), - Some(b'1') => px.push(0), - Some(_) => return Err(err("invalid PBM digit")), - None => return Err(err("truncated raster")), - } - r.pos += 1; - } - } - Image::from_u8(w, h, ChannelLayout::Gray, px) - } - b'2' | b'3' | b'5' | b'6' => { - let (w, h, maxval) = (r.uint()?, r.uint()?, r.uint()?); - let layout = if matches!(kind, b'2' | b'5') { ChannelLayout::Gray } else { ChannelLayout::Rgb }; - limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = sample_count(w, h, layout.channels())?; - let samples = if matches!(kind, b'5' | b'6') { - r.single_ws()?; - read_binary(r.rest(), n, maxval)? - } else { - // Each ASCII sample is a digit and a separator (the last may lack one), so the - // file, not the header, bounds the reservation. - let mut v = Samples::with_capacity(maxval, n.min(r.rest().len() / 2 + 1))?; - for _ in 0..n { - v.push(r.uint()?)?; - } - v - }; - samples.into_image(w, h, layout) - } - b'7' => decode_pam(&mut r, limits), - b'F' | b'f' => { - let layout = if kind == b'F' { ChannelLayout::Rgb } else { ChannelLayout::Gray }; - let (w, h) = (r.uint()?, r.uint()?); - let scale: f32 = std::str::from_utf8(r.token()?) - .ok() - .and_then(|s| s.parse().ok()) - .filter(|s: &f32| s.is_finite() && *s != 0.0) - .ok_or_else(|| err("invalid PFM scale"))?; - r.single_ws()?; - limits.check(w, h, layout, SampleType::F32)?; - let nc = layout.channels(); - let row = w as usize * nc; - let data = r.rest(); - if sample_count(w, h, nc)?.checked_mul(4).is_none_or(|len| data.len() < len) { - return Err(err("truncated raster")); - } - let le = scale < 0.0; - // Write native-endian bytes straight into the output buffer: a separate `Vec` - // would double the budgeted allocation. - let row_bytes = row * 4; - let mut out = vec![0u8; row_bytes * h as usize]; - for (y, src) in data.chunks_exact(row_bytes).take(h as usize).enumerate() { - // PFM rows are stored bottom-to-top. - let dst_start = (h as usize - 1 - y) * row_bytes; - let Some(dst) = out.get_mut(dst_start..dst_start + row_bytes) else { - return Err(err("truncated raster")); - }; - for (d, s) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let v = if le { f32::from_le_bytes(*s) } else { f32::from_be_bytes(*s) }; - *d = v.to_ne_bytes(); - } - } - Image::from_raw(w, h, layout, SampleType::F32, out) - } - _ => Err(err("unknown Netpbm subtype")), - } + bridge::format(Format::Pnm, bytes, limits) } - -fn decode_pam(r: &mut Reader<'_>, limits: &Limits) -> Result { - let (mut w, mut h, mut depth, mut maxval) = (None, None, None, None); - let mut tupltype = String::new(); - loop { - let tok = r.token()?; - match tok { - b"WIDTH" => w = Some(r.uint()?), - b"HEIGHT" => h = Some(r.uint()?), - b"DEPTH" => depth = Some(r.uint()?), - b"MAXVAL" => maxval = Some(r.uint()?), - b"TUPLTYPE" => { - let t = r.token()?; - if !tupltype.is_empty() { - tupltype.push(' '); - } - tupltype.push_str(std::str::from_utf8(t).map_err(|_| err("bad TUPLTYPE"))?); - } - b"ENDHDR" => break, - _ => return Err(err("unknown PAM header field")), - } +pub fn encode(image: &Image) -> Result, CodecError> { + // PFM has only gray and RGB tuples. Preserve this facade's contract that + // unsupported layouts are refused instead of silently dropping alpha. + if image.sample_type() == crate::SampleType::F32 && !matches!(image.layout(), crate::ChannelLayout::Gray | crate::ChannelLayout::Rgb) { + return Err(CodecError::encode("PNM", format!("PFM cannot store {:?}", image.layout()))); } - r.pam_endhdr()?; - let (w, h, depth, maxval) = match (w, h, depth, maxval) { - (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d), - _ => return Err(err("incomplete PAM header")), - }; - let layout = match (tupltype.as_str(), depth) { - ("BLACKANDWHITE" | "GRAYSCALE", 1) | ("", 1) => ChannelLayout::Gray, - ("BLACKANDWHITE_ALPHA" | "GRAYSCALE_ALPHA", 2) | ("", 2) => ChannelLayout::GrayA, - ("RGB", 3) | ("", 3) => ChannelLayout::Rgb, - ("RGB_ALPHA", 4) | ("", 4) => ChannelLayout::Rgba, - ("CMYK", 4) => ChannelLayout::Cmyk, - ("CMYK_ALPHA", 5) => ChannelLayout::CmykA, - (t, d) => { - return Err(CodecError::unsupported(F, format!("PAM tuple type {t:?} with depth {d}"))); - } - }; - limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = sample_count(w, h, layout.channels())?; - read_binary(r.rest(), n, maxval)?.into_image(w, h, layout) -} - -/// Writes `img` as PGM/PPM (gray, RGB), PAM (alpha, CMYK) or PFM (float gray, RGB). -pub fn encode(img: &Image) -> Result, CodecError> { - let (w, h) = (img.width(), img.height()); - let layout = img.layout(); - let mut out = Vec::new(); - match img.sample_type() { - SampleType::F32 => { - let tag = match layout { - ChannelLayout::Gray => "Pf", - ChannelLayout::Rgb => "PF", - l => return Err(CodecError::encode(F, format!("PFM cannot store {l:?}"))), - }; - out.extend_from_slice(format!("{tag}\n{w} {h}\n-1.0\n").as_bytes()); - let s = img.to_f32_samples().unwrap_or_default(); - let row = w as usize * layout.channels(); - for y in (0..h as usize).rev() { - for v in &s[y * row..(y + 1) * row] { - out.extend_from_slice(&v.to_le_bytes()); - } - } - } - sample @ (SampleType::U8 | SampleType::U16) => { - let maxval = if sample == SampleType::U8 { 255 } else { 65535 }; - match layout { - ChannelLayout::Gray => out.extend_from_slice(format!("P5\n{w} {h}\n{maxval}\n").as_bytes()), - ChannelLayout::Rgb => out.extend_from_slice(format!("P6\n{w} {h}\n{maxval}\n").as_bytes()), - l => { - let t = match l { - ChannelLayout::GrayA => "GRAYSCALE_ALPHA", - ChannelLayout::Rgba => "RGB_ALPHA", - ChannelLayout::Cmyk => "CMYK", - _ => "CMYK_ALPHA", - }; - out.extend_from_slice( - format!("P7\nWIDTH {w}\nHEIGHT {h}\nDEPTH {}\nMAXVAL {maxval}\nTUPLTYPE {t}\nENDHDR\n", l.channels()).as_bytes(), - ); - } - } - if sample == SampleType::U8 { - out.extend_from_slice(img.data()); - } else { - for v in img.to_u16_samples().unwrap_or_default() { - out.extend_from_slice(&v.to_be_bytes()); - } - } - } - } - Ok(out) + bridge::encode(image, Format::Pnm, &Default::default()) } diff --git a/crates/raster-codecs/src/xpm.rs b/crates/raster-codecs/src/xpm.rs index 05d93cd755..2d49a2d63a 100644 --- a/crates/raster-codecs/src/xpm.rs +++ b/crates/raster-codecs/src/xpm.rs @@ -1,243 +1,13 @@ -//! X PixMap reader for XPM2 plain-text icons and XPM3 C-source icon arrays. -//! Supports transparency (None), RGB hex at 4/8/16 bits per channel and -//! common X11 colour names. Does not execute C code. +//! XPM compatibility facade; implementation and color-name data live in craft-image-codecs. +use crate::{CodecError, Image, Limits, bridge}; +use craft_image_codecs::Format; -use std::collections::HashMap; - -mod x11_colors; - -use crate::{ChannelLayout, CodecError, Image, Limits, SampleType}; - -const MAX_SOURCE: usize = 256 << 20; -const MAX_COLOURS: usize = 65_536; -const MAX_CPP: usize = 8; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed("XPM", msg) -} - -/// Extract C string literals without treating quoted text or // in a string as a comment. -/// XPM uses one literal for the header, each palette entry and each row. -fn c_strings(bytes: &[u8]) -> Result>, CodecError> { - let mut lines = Vec::new(); - let mut i = 0usize; - while i < bytes.len() { - if bytes[i..].starts_with(b"/*") { - let tail = &bytes[i + 2..]; - let Some(end) = tail.windows(2).position(|p| p == b"*/") else { return Err(bad("unterminated C comment")) }; - i += end + 4; - } else if bytes[i..].starts_with(b"//") { - i += bytes[i..].iter().position(|&c| c == b'\n').unwrap_or(bytes.len() - i); - } else if bytes[i] == b'"' { - i += 1; - let mut s = Vec::new(); - let mut closed = false; - while i < bytes.len() { - let c = bytes[i]; - i += 1; - match c { - b'"' => { - closed = true; - break; - } - b'\\' => { - let next = *bytes.get(i).ok_or_else(|| bad("truncated C escape"))?; - i += 1; - s.push(match next { - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - b'0' => 0, - _ => next, // quoted backslash or quote - }); - } - _ => s.push(c), - } - } - if !closed { - return Err(bad("unterminated XPM string")); - } - lines.push(s); - } else { - i += 1; - } - } - Ok(lines) -} - -/// Extract XPM2's plain-text lines without trimming pixel rows: leading and -/// trailing spaces can be palette keys, and physical CRLF is not image data. -fn xpm2_lines(bytes: &[u8]) -> Result>, CodecError> { - let mut input = bytes.split(|&b| b == b'\n'); - let header = input.next().ok_or_else(|| bad("missing XPM2 marker"))?; - if header.strip_suffix(b"\r").unwrap_or(header) != b"! XPM2" { - return Err(bad("not an XPM2 image")); - } - let mut lines = Vec::new(); - for raw in input { - let line = raw.strip_suffix(b"\r").unwrap_or(raw); - // The header may be preceded by comments and blank lines. After the - // header, a leading '!' is allowed as a palette key or pixel value. - if lines.is_empty() && (line.is_empty() || line.starts_with(b"!")) { - continue; - } - lines.push(line.to_vec()); - } - Ok(lines) -} - -fn channel(hex: &str) -> Option { - let v = u32::from_str_radix(hex, 16).ok()?; - let max = (1u32 << (hex.len() * 4)) - 1; - Some(((v * 255 + max / 2) / max) as u8) -} - -fn named(name: &str) -> Option<[u8; 3]> { - let s = name.to_ascii_lowercase().replace([' ', '-', '_'], ""); - // XPM imports X11 names, whose RGB values differ from CSS for names - // such as gray, maroon and purple. Keep these exact rather than guessing. - if let Ok(index) = x11_colors::X11_COLORS.binary_search_by_key(&s.as_str(), |(name, _)| *name) { - return Some(x11_colors::X11_COLORS[index].1); - } - // Retain useful web color aliases not present in the X11 database. - Some(match s.as_str() { - "silver" => [192, 192, 192], - "olive" => [128, 128, 0], - "teal" => [0, 128, 128], - "fuchsia" => [255, 0, 255], - "navyblue" => [0, 0, 128], - _ => return None, - }) -} - -/// Look up an exact normalized X11 color name as RGB channels in `0..=1`. -/// -/// Names must contain 1–64 bytes of lowercase ASCII letters or digits. Unknown names, -/// unnormalized names and XPM-only aliases return `None`; this does not parse hex colors -/// or transparency. Values are the stored X11 bytes divided by 255, without CSS overrides -/// or color-space conversion. XPM decoding retains its own normalization and alias policy. pub fn x11_color_rgb(name: &str) -> Option<[f32; 3]> { - // Bound work on untrusted names before searching the shared table, without allocating. - if name.is_empty() || name.len() > 64 || !name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) { - return None; - } - let index = x11_colors::X11_COLORS.binary_search_by_key(&name, |(entry, _)| *entry).ok()?; - let (_, rgb) = x11_colors::X11_COLORS.get(index)?; - Some(rgb.map(|channel| f32::from(channel) / 255.0)) + craft_image_codecs::xpm_named_color_rgb(name) } - -fn color(name: &str) -> Option<[u8; 4]> { - if name.eq_ignore_ascii_case("none") { - return Some([0, 0, 0, 0]); - } - let rgb = if let Some(hex) = name.strip_prefix('#') { - // UTF-8 byte lengths can match a supported hex width while slicing would panic. - // `from_str_radix` would also take a leading `+`: accept hex digits only. - if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - let digits = match hex.len() { - 3 => 1, - 6 => 2, - 12 => 4, - _ => return None, - }; - let rgb = (0..3).map(|i| channel(&hex[i * digits..(i + 1) * digits])).collect::>>()?; - [rgb[0], rgb[1], rgb[2]] - } else { - named(name)? - }; - Some([rgb[0], rgb[1], rgb[2], 255]) +pub fn looks_like_xpm(bytes: &[u8]) -> bool { + craft_image_codecs::detect(bytes) == Some(Format::Xpm) } - -/// The XPM3 comment or the XPM2 first line. -pub fn looks_like_xpm(b: &[u8]) -> bool { - b.starts_with(b"/* XPM */") || b.starts_with(b"! XPM2\n") || b.starts_with(b"! XPM2\r\n") -} - pub fn decode(bytes: &[u8], limits: &Limits) -> Result { - if bytes.len() > MAX_SOURCE { - return Err(CodecError::LimitExceeded("XPM source exceeds 256 MiB".into())); - } - let lines = if bytes.starts_with(b"/* XPM */") { - c_strings(bytes)? - } else if bytes.starts_with(b"! XPM2\n") || bytes.starts_with(b"! XPM2\r\n") { - xpm2_lines(bytes)? - } else { - return Err(bad("not an XPM2/XPM3 image")); - }; - decode_lines(&lines, limits) -} - -fn decode_lines(lines: &[Vec], limits: &Limits) -> Result { - let header = lines.first().ok_or_else(|| bad("missing image header"))?; - let parts = std::str::from_utf8(header).map_err(|_| bad("non-UTF-8 XPM header"))?; - let mut parts = parts.split_ascii_whitespace(); - let number = |key: &str, s: Option<&str>| -> Result { - s.ok_or_else(|| bad(format!("missing {key}")))?.parse::().map_err(|_| bad(format!("invalid {key}"))) - }; - let width = number("width", parts.next())?; - let height = number("height", parts.next())?; - let colours = number("palette size", parts.next())?; - let cpp = number("chars per pixel", parts.next())?; - if width == 0 || height == 0 || colours == 0 || colours > MAX_COLOURS || !(1..=MAX_CPP).contains(&cpp) { - return Err(bad("invalid XPM dimensions, palette size or chars per pixel")); - } - let (w, h) = (u32::try_from(width).map_err(|_| bad("width overflow"))?, u32::try_from(height).map_err(|_| bad("height overflow"))?); - limits.check(w, h, ChannelLayout::Rgba, SampleType::U8)?; - let required = 1usize.checked_add(colours).and_then(|n| n.checked_add(height)).ok_or_else(|| bad("row count overflow"))?; - if lines.len() < required { - return Err(bad("truncated palette or image rows")); - } - let mut palette = HashMap::, [u8; 4]>::with_capacity(colours); - for line in &lines[1..1 + colours] { - if line.len() < cpp { - return Err(bad("truncated colour key")); - } - let fields = std::str::from_utf8(&line[cpp..]).map_err(|_| bad("invalid colour name"))?; - // XPM priority is colour, gray, four-level gray, then monochrome, - // regardless of the order of keys in the palette entry. - let terms: Vec<&str> = fields.split_ascii_whitespace().collect(); - let mut picked: Option<(u8, String)> = None; - let mut i = 0; - while i < terms.len() { - let priority = match terms[i] { - "c" => 4, - "g" => 3, - "g4" => 2, - "m" => 1, - _ => 0, // Symbolic names ('s') are not colour values. - }; - let start = i + 1; - i = start; - while i < terms.len() && !matches!(terms[i], "c" | "g" | "g4" | "m" | "s") { - i += 1; - } - if priority > 0 && i > start && picked.as_ref().is_none_or(|(current, _)| priority > *current) { - picked = Some((priority, terms[start..i].join(" "))); - } - } - let value = picked.as_ref().and_then(|(_, name)| color(name)).ok_or_else(|| bad("unsupported or missing XPM colour"))?; - if palette.insert(line[..cpp].to_vec(), value).is_some() { - return Err(bad("duplicate XPM palette key")); - } - } - let row_len = width.checked_mul(cpp).ok_or_else(|| bad("row byte count overflow"))?; - // Validate all source rows before reserving the decoded RGBA image. A malformed - // short row must not be able to make a large header-sized allocation first. - if lines[1 + colours..required].iter().any(|line| line.len() != row_len) { - return Err(bad("XPM row has the wrong width")); - } - let total = width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = Vec::new(); - pixels.try_reserve_exact(total).map_err(|_| bad("XPM pixel buffer is too large"))?; - pixels.resize(total, 0); - for (y, line) in lines[1 + colours..required].iter().enumerate() { - for x in 0..width { - let key = &line[x * cpp..(x + 1) * cpp]; - let rgba = palette.get(key).ok_or_else(|| bad("unknown palette key"))?; - pixels[(y * width + x) * 4..(y * width + x + 1) * 4].copy_from_slice(rgba); - } - } - Image::from_u8(w, h, ChannelLayout::Rgba, pixels) + bridge::format(Format::Xpm, bytes, limits) } diff --git a/crates/raster-codecs/src/xpm/x11_colors.rs b/crates/raster-codecs/src/xpm/x11_colors.rs deleted file mode 100644 index 31986999a8..0000000000 --- a/crates/raster-codecs/src/xpm/x11_colors.rs +++ /dev/null @@ -1,666 +0,0 @@ -//! X11 color-name database (X.Org rgb.txt) normalized to lowercase without -//! spaces, underscores, or hyphens. RGB values are *X11* values, not CSS values. -//! Source: -//! License: MIT (X.Org Foundation), see the upstream app/rgb COPYING file. -//! Aliases differing only in case or spaces have been collapsed. -//! Keep sorted: decoder uses binary search without allocation per candidate. - -pub(super) const X11_COLORS: &[(&str, [u8; 3])] = &[ - ("aliceblue", [240, 248, 255]), - ("antiquewhite", [250, 235, 215]), - ("antiquewhite1", [255, 239, 219]), - ("antiquewhite2", [238, 223, 204]), - ("antiquewhite3", [205, 192, 176]), - ("antiquewhite4", [139, 131, 120]), - ("aquamarine", [127, 255, 212]), - ("aquamarine1", [127, 255, 212]), - ("aquamarine2", [118, 238, 198]), - ("aquamarine3", [102, 205, 170]), - ("aquamarine4", [69, 139, 116]), - ("azure", [240, 255, 255]), - ("azure1", [240, 255, 255]), - ("azure2", [224, 238, 238]), - ("azure3", [193, 205, 205]), - ("azure4", [131, 139, 139]), - ("beige", [245, 245, 220]), - ("bisque", [255, 228, 196]), - ("bisque1", [255, 228, 196]), - ("bisque2", [238, 213, 183]), - ("bisque3", [205, 183, 158]), - ("bisque4", [139, 125, 107]), - ("black", [0, 0, 0]), - ("blanchedalmond", [255, 235, 205]), - ("blue", [0, 0, 255]), - ("blue1", [0, 0, 255]), - ("blue2", [0, 0, 238]), - ("blue3", [0, 0, 205]), - ("blue4", [0, 0, 139]), - ("blueviolet", [138, 43, 226]), - ("brown", [165, 42, 42]), - ("brown1", [255, 64, 64]), - ("brown2", [238, 59, 59]), - ("brown3", [205, 51, 51]), - ("brown4", [139, 35, 35]), - ("burlywood", [222, 184, 135]), - ("burlywood1", [255, 211, 155]), - ("burlywood2", [238, 197, 145]), - ("burlywood3", [205, 170, 125]), - ("burlywood4", [139, 115, 85]), - ("cadetblue", [95, 158, 160]), - ("cadetblue1", [152, 245, 255]), - ("cadetblue2", [142, 229, 238]), - ("cadetblue3", [122, 197, 205]), - ("cadetblue4", [83, 134, 139]), - ("chartreuse", [127, 255, 0]), - ("chartreuse1", [127, 255, 0]), - ("chartreuse2", [118, 238, 0]), - ("chartreuse3", [102, 205, 0]), - ("chartreuse4", [69, 139, 0]), - ("chocolate", [210, 105, 30]), - ("chocolate1", [255, 127, 36]), - ("chocolate2", [238, 118, 33]), - ("chocolate3", [205, 102, 29]), - ("chocolate4", [139, 69, 19]), - ("coral", [255, 127, 80]), - ("coral1", [255, 114, 86]), - ("coral2", [238, 106, 80]), - ("coral3", [205, 91, 69]), - ("coral4", [139, 62, 47]), - ("cornflowerblue", [100, 149, 237]), - ("cornsilk", [255, 248, 220]), - ("cornsilk1", [255, 248, 220]), - ("cornsilk2", [238, 232, 205]), - ("cornsilk3", [205, 200, 177]), - ("cornsilk4", [139, 136, 120]), - ("cyan", [0, 255, 255]), - ("cyan1", [0, 255, 255]), - ("cyan2", [0, 238, 238]), - ("cyan3", [0, 205, 205]), - ("cyan4", [0, 139, 139]), - ("darkblue", [0, 0, 139]), - ("darkcyan", [0, 139, 139]), - ("darkgoldenrod", [184, 134, 11]), - ("darkgoldenrod1", [255, 185, 15]), - ("darkgoldenrod2", [238, 173, 14]), - ("darkgoldenrod3", [205, 149, 12]), - ("darkgoldenrod4", [139, 101, 8]), - ("darkgray", [169, 169, 169]), - ("darkgreen", [0, 100, 0]), - ("darkgrey", [169, 169, 169]), - ("darkkhaki", [189, 183, 107]), - ("darkmagenta", [139, 0, 139]), - ("darkolivegreen", [85, 107, 47]), - ("darkolivegreen1", [202, 255, 112]), - ("darkolivegreen2", [188, 238, 104]), - ("darkolivegreen3", [162, 205, 90]), - ("darkolivegreen4", [110, 139, 61]), - ("darkorange", [255, 140, 0]), - ("darkorange1", [255, 127, 0]), - ("darkorange2", [238, 118, 0]), - ("darkorange3", [205, 102, 0]), - ("darkorange4", [139, 69, 0]), - ("darkorchid", [153, 50, 204]), - ("darkorchid1", [191, 62, 255]), - ("darkorchid2", [178, 58, 238]), - ("darkorchid3", [154, 50, 205]), - ("darkorchid4", [104, 34, 139]), - ("darkred", [139, 0, 0]), - ("darksalmon", [233, 150, 122]), - ("darkseagreen", [143, 188, 143]), - ("darkseagreen1", [193, 255, 193]), - ("darkseagreen2", [180, 238, 180]), - ("darkseagreen3", [155, 205, 155]), - ("darkseagreen4", [105, 139, 105]), - ("darkslateblue", [72, 61, 139]), - ("darkslategray", [47, 79, 79]), - ("darkslategray1", [151, 255, 255]), - ("darkslategray2", [141, 238, 238]), - ("darkslategray3", [121, 205, 205]), - ("darkslategray4", [82, 139, 139]), - ("darkslategrey", [47, 79, 79]), - ("darkturquoise", [0, 206, 209]), - ("darkviolet", [148, 0, 211]), - ("deeppink", [255, 20, 147]), - ("deeppink1", [255, 20, 147]), - ("deeppink2", [238, 18, 137]), - ("deeppink3", [205, 16, 118]), - ("deeppink4", [139, 10, 80]), - ("deepskyblue", [0, 191, 255]), - ("deepskyblue1", [0, 191, 255]), - ("deepskyblue2", [0, 178, 238]), - ("deepskyblue3", [0, 154, 205]), - ("deepskyblue4", [0, 104, 139]), - ("dimgray", [105, 105, 105]), - ("dimgrey", [105, 105, 105]), - ("dodgerblue", [30, 144, 255]), - ("dodgerblue1", [30, 144, 255]), - ("dodgerblue2", [28, 134, 238]), - ("dodgerblue3", [24, 116, 205]), - ("dodgerblue4", [16, 78, 139]), - ("firebrick", [178, 34, 34]), - ("firebrick1", [255, 48, 48]), - ("firebrick2", [238, 44, 44]), - ("firebrick3", [205, 38, 38]), - ("firebrick4", [139, 26, 26]), - ("floralwhite", [255, 250, 240]), - ("forestgreen", [34, 139, 34]), - ("gainsboro", [220, 220, 220]), - ("ghostwhite", [248, 248, 255]), - ("gold", [255, 215, 0]), - ("gold1", [255, 215, 0]), - ("gold2", [238, 201, 0]), - ("gold3", [205, 173, 0]), - ("gold4", [139, 117, 0]), - ("goldenrod", [218, 165, 32]), - ("goldenrod1", [255, 193, 37]), - ("goldenrod2", [238, 180, 34]), - ("goldenrod3", [205, 155, 29]), - ("goldenrod4", [139, 105, 20]), - ("gray", [190, 190, 190]), - ("gray0", [0, 0, 0]), - ("gray1", [3, 3, 3]), - ("gray10", [26, 26, 26]), - ("gray100", [255, 255, 255]), - ("gray11", [28, 28, 28]), - ("gray12", [31, 31, 31]), - ("gray13", [33, 33, 33]), - ("gray14", [36, 36, 36]), - ("gray15", [38, 38, 38]), - ("gray16", [41, 41, 41]), - ("gray17", [43, 43, 43]), - ("gray18", [46, 46, 46]), - ("gray19", [48, 48, 48]), - ("gray2", [5, 5, 5]), - ("gray20", [51, 51, 51]), - ("gray21", [54, 54, 54]), - ("gray22", [56, 56, 56]), - ("gray23", [59, 59, 59]), - ("gray24", [61, 61, 61]), - ("gray25", [64, 64, 64]), - ("gray26", [66, 66, 66]), - ("gray27", [69, 69, 69]), - ("gray28", [71, 71, 71]), - ("gray29", [74, 74, 74]), - ("gray3", [8, 8, 8]), - ("gray30", [77, 77, 77]), - ("gray31", [79, 79, 79]), - ("gray32", [82, 82, 82]), - ("gray33", [84, 84, 84]), - ("gray34", [87, 87, 87]), - ("gray35", [89, 89, 89]), - ("gray36", [92, 92, 92]), - ("gray37", [94, 94, 94]), - ("gray38", [97, 97, 97]), - ("gray39", [99, 99, 99]), - ("gray4", [10, 10, 10]), - ("gray40", [102, 102, 102]), - ("gray41", [105, 105, 105]), - ("gray42", [107, 107, 107]), - ("gray43", [110, 110, 110]), - ("gray44", [112, 112, 112]), - ("gray45", [115, 115, 115]), - ("gray46", [117, 117, 117]), - ("gray47", [120, 120, 120]), - ("gray48", [122, 122, 122]), - ("gray49", [125, 125, 125]), - ("gray5", [13, 13, 13]), - ("gray50", [127, 127, 127]), - ("gray51", [130, 130, 130]), - ("gray52", [133, 133, 133]), - ("gray53", [135, 135, 135]), - ("gray54", [138, 138, 138]), - ("gray55", [140, 140, 140]), - ("gray56", [143, 143, 143]), - ("gray57", [145, 145, 145]), - ("gray58", [148, 148, 148]), - ("gray59", [150, 150, 150]), - ("gray6", [15, 15, 15]), - ("gray60", [153, 153, 153]), - ("gray61", [156, 156, 156]), - ("gray62", [158, 158, 158]), - ("gray63", [161, 161, 161]), - ("gray64", [163, 163, 163]), - ("gray65", [166, 166, 166]), - ("gray66", [168, 168, 168]), - ("gray67", [171, 171, 171]), - ("gray68", [173, 173, 173]), - ("gray69", [176, 176, 176]), - ("gray7", [18, 18, 18]), - ("gray70", [179, 179, 179]), - ("gray71", [181, 181, 181]), - ("gray72", [184, 184, 184]), - ("gray73", [186, 186, 186]), - ("gray74", [189, 189, 189]), - ("gray75", [191, 191, 191]), - ("gray76", [194, 194, 194]), - ("gray77", [196, 196, 196]), - ("gray78", [199, 199, 199]), - ("gray79", [201, 201, 201]), - ("gray8", [20, 20, 20]), - ("gray80", [204, 204, 204]), - ("gray81", [207, 207, 207]), - ("gray82", [209, 209, 209]), - ("gray83", [212, 212, 212]), - ("gray84", [214, 214, 214]), - ("gray85", [217, 217, 217]), - ("gray86", [219, 219, 219]), - ("gray87", [222, 222, 222]), - ("gray88", [224, 224, 224]), - ("gray89", [227, 227, 227]), - ("gray9", [23, 23, 23]), - ("gray90", [229, 229, 229]), - ("gray91", [232, 232, 232]), - ("gray92", [235, 235, 235]), - ("gray93", [237, 237, 237]), - ("gray94", [240, 240, 240]), - ("gray95", [242, 242, 242]), - ("gray96", [245, 245, 245]), - ("gray97", [247, 247, 247]), - ("gray98", [250, 250, 250]), - ("gray99", [252, 252, 252]), - ("green", [0, 255, 0]), - ("green1", [0, 255, 0]), - ("green2", [0, 238, 0]), - ("green3", [0, 205, 0]), - ("green4", [0, 139, 0]), - ("greenyellow", [173, 255, 47]), - ("grey", [190, 190, 190]), - ("grey0", [0, 0, 0]), - ("grey1", [3, 3, 3]), - ("grey10", [26, 26, 26]), - ("grey100", [255, 255, 255]), - ("grey11", [28, 28, 28]), - ("grey12", [31, 31, 31]), - ("grey13", [33, 33, 33]), - ("grey14", [36, 36, 36]), - ("grey15", [38, 38, 38]), - ("grey16", [41, 41, 41]), - ("grey17", [43, 43, 43]), - ("grey18", [46, 46, 46]), - ("grey19", [48, 48, 48]), - ("grey2", [5, 5, 5]), - ("grey20", [51, 51, 51]), - ("grey21", [54, 54, 54]), - ("grey22", [56, 56, 56]), - ("grey23", [59, 59, 59]), - ("grey24", [61, 61, 61]), - ("grey25", [64, 64, 64]), - ("grey26", [66, 66, 66]), - ("grey27", [69, 69, 69]), - ("grey28", [71, 71, 71]), - ("grey29", [74, 74, 74]), - ("grey3", [8, 8, 8]), - ("grey30", [77, 77, 77]), - ("grey31", [79, 79, 79]), - ("grey32", [82, 82, 82]), - ("grey33", [84, 84, 84]), - ("grey34", [87, 87, 87]), - ("grey35", [89, 89, 89]), - ("grey36", [92, 92, 92]), - ("grey37", [94, 94, 94]), - ("grey38", [97, 97, 97]), - ("grey39", [99, 99, 99]), - ("grey4", [10, 10, 10]), - ("grey40", [102, 102, 102]), - ("grey41", [105, 105, 105]), - ("grey42", [107, 107, 107]), - ("grey43", [110, 110, 110]), - ("grey44", [112, 112, 112]), - ("grey45", [115, 115, 115]), - ("grey46", [117, 117, 117]), - ("grey47", [120, 120, 120]), - ("grey48", [122, 122, 122]), - ("grey49", [125, 125, 125]), - ("grey5", [13, 13, 13]), - ("grey50", [127, 127, 127]), - ("grey51", [130, 130, 130]), - ("grey52", [133, 133, 133]), - ("grey53", [135, 135, 135]), - ("grey54", [138, 138, 138]), - ("grey55", [140, 140, 140]), - ("grey56", [143, 143, 143]), - ("grey57", [145, 145, 145]), - ("grey58", [148, 148, 148]), - ("grey59", [150, 150, 150]), - ("grey6", [15, 15, 15]), - ("grey60", [153, 153, 153]), - ("grey61", [156, 156, 156]), - ("grey62", [158, 158, 158]), - ("grey63", [161, 161, 161]), - ("grey64", [163, 163, 163]), - ("grey65", [166, 166, 166]), - ("grey66", [168, 168, 168]), - ("grey67", [171, 171, 171]), - ("grey68", [173, 173, 173]), - ("grey69", [176, 176, 176]), - ("grey7", [18, 18, 18]), - ("grey70", [179, 179, 179]), - ("grey71", [181, 181, 181]), - ("grey72", [184, 184, 184]), - ("grey73", [186, 186, 186]), - ("grey74", [189, 189, 189]), - ("grey75", [191, 191, 191]), - ("grey76", [194, 194, 194]), - ("grey77", [196, 196, 196]), - ("grey78", [199, 199, 199]), - ("grey79", [201, 201, 201]), - ("grey8", [20, 20, 20]), - ("grey80", [204, 204, 204]), - ("grey81", [207, 207, 207]), - ("grey82", [209, 209, 209]), - ("grey83", [212, 212, 212]), - ("grey84", [214, 214, 214]), - ("grey85", [217, 217, 217]), - ("grey86", [219, 219, 219]), - ("grey87", [222, 222, 222]), - ("grey88", [224, 224, 224]), - ("grey89", [227, 227, 227]), - ("grey9", [23, 23, 23]), - ("grey90", [229, 229, 229]), - ("grey91", [232, 232, 232]), - ("grey92", [235, 235, 235]), - ("grey93", [237, 237, 237]), - ("grey94", [240, 240, 240]), - ("grey95", [242, 242, 242]), - ("grey96", [245, 245, 245]), - ("grey97", [247, 247, 247]), - ("grey98", [250, 250, 250]), - ("grey99", [252, 252, 252]), - ("honeydew", [240, 255, 240]), - ("honeydew1", [240, 255, 240]), - ("honeydew2", [224, 238, 224]), - ("honeydew3", [193, 205, 193]), - ("honeydew4", [131, 139, 131]), - ("hotpink", [255, 105, 180]), - ("hotpink1", [255, 110, 180]), - ("hotpink2", [238, 106, 167]), - ("hotpink3", [205, 96, 144]), - ("hotpink4", [139, 58, 98]), - ("indianred", [205, 92, 92]), - ("indianred1", [255, 106, 106]), - ("indianred2", [238, 99, 99]), - ("indianred3", [205, 85, 85]), - ("indianred4", [139, 58, 58]), - ("ivory", [255, 255, 240]), - ("ivory1", [255, 255, 240]), - ("ivory2", [238, 238, 224]), - ("ivory3", [205, 205, 193]), - ("ivory4", [139, 139, 131]), - ("khaki", [240, 230, 140]), - ("khaki1", [255, 246, 143]), - ("khaki2", [238, 230, 133]), - ("khaki3", [205, 198, 115]), - ("khaki4", [139, 134, 78]), - ("lavender", [230, 230, 250]), - ("lavenderblush", [255, 240, 245]), - ("lavenderblush1", [255, 240, 245]), - ("lavenderblush2", [238, 224, 229]), - ("lavenderblush3", [205, 193, 197]), - ("lavenderblush4", [139, 131, 134]), - ("lawngreen", [124, 252, 0]), - ("lemonchiffon", [255, 250, 205]), - ("lemonchiffon1", [255, 250, 205]), - ("lemonchiffon2", [238, 233, 191]), - ("lemonchiffon3", [205, 201, 165]), - ("lemonchiffon4", [139, 137, 112]), - ("lightblue", [173, 216, 230]), - ("lightblue1", [191, 239, 255]), - ("lightblue2", [178, 223, 238]), - ("lightblue3", [154, 192, 205]), - ("lightblue4", [104, 131, 139]), - ("lightcoral", [240, 128, 128]), - ("lightcyan", [224, 255, 255]), - ("lightcyan1", [224, 255, 255]), - ("lightcyan2", [209, 238, 238]), - ("lightcyan3", [180, 205, 205]), - ("lightcyan4", [122, 139, 139]), - ("lightgoldenrod", [238, 221, 130]), - ("lightgoldenrod1", [255, 236, 139]), - ("lightgoldenrod2", [238, 220, 130]), - ("lightgoldenrod3", [205, 190, 112]), - ("lightgoldenrod4", [139, 129, 76]), - ("lightgoldenrodyellow", [250, 250, 210]), - ("lightgray", [211, 211, 211]), - ("lightgreen", [144, 238, 144]), - ("lightgrey", [211, 211, 211]), - ("lightpink", [255, 182, 193]), - ("lightpink1", [255, 174, 185]), - ("lightpink2", [238, 162, 173]), - ("lightpink3", [205, 140, 149]), - ("lightpink4", [139, 95, 101]), - ("lightsalmon", [255, 160, 122]), - ("lightsalmon1", [255, 160, 122]), - ("lightsalmon2", [238, 149, 114]), - ("lightsalmon3", [205, 129, 98]), - ("lightsalmon4", [139, 87, 66]), - ("lightseagreen", [32, 178, 170]), - ("lightskyblue", [135, 206, 250]), - ("lightskyblue1", [176, 226, 255]), - ("lightskyblue2", [164, 211, 238]), - ("lightskyblue3", [141, 182, 205]), - ("lightskyblue4", [96, 123, 139]), - ("lightslateblue", [132, 112, 255]), - ("lightslategray", [119, 136, 153]), - ("lightslategrey", [119, 136, 153]), - ("lightsteelblue", [176, 196, 222]), - ("lightsteelblue1", [202, 225, 255]), - ("lightsteelblue2", [188, 210, 238]), - ("lightsteelblue3", [162, 181, 205]), - ("lightsteelblue4", [110, 123, 139]), - ("lightyellow", [255, 255, 224]), - ("lightyellow1", [255, 255, 224]), - ("lightyellow2", [238, 238, 209]), - ("lightyellow3", [205, 205, 180]), - ("lightyellow4", [139, 139, 122]), - ("limegreen", [50, 205, 50]), - ("linen", [250, 240, 230]), - ("magenta", [255, 0, 255]), - ("magenta1", [255, 0, 255]), - ("magenta2", [238, 0, 238]), - ("magenta3", [205, 0, 205]), - ("magenta4", [139, 0, 139]), - ("maroon", [176, 48, 96]), - ("maroon1", [255, 52, 179]), - ("maroon2", [238, 48, 167]), - ("maroon3", [205, 41, 144]), - ("maroon4", [139, 28, 98]), - ("mediumaquamarine", [102, 205, 170]), - ("mediumblue", [0, 0, 205]), - ("mediumorchid", [186, 85, 211]), - ("mediumorchid1", [224, 102, 255]), - ("mediumorchid2", [209, 95, 238]), - ("mediumorchid3", [180, 82, 205]), - ("mediumorchid4", [122, 55, 139]), - ("mediumpurple", [147, 112, 219]), - ("mediumpurple1", [171, 130, 255]), - ("mediumpurple2", [159, 121, 238]), - ("mediumpurple3", [137, 104, 205]), - ("mediumpurple4", [93, 71, 139]), - ("mediumseagreen", [60, 179, 113]), - ("mediumslateblue", [123, 104, 238]), - ("mediumspringgreen", [0, 250, 154]), - ("mediumturquoise", [72, 209, 204]), - ("mediumvioletred", [199, 21, 133]), - ("midnightblue", [25, 25, 112]), - ("mintcream", [245, 255, 250]), - ("mistyrose", [255, 228, 225]), - ("mistyrose1", [255, 228, 225]), - ("mistyrose2", [238, 213, 210]), - ("mistyrose3", [205, 183, 181]), - ("mistyrose4", [139, 125, 123]), - ("moccasin", [255, 228, 181]), - ("navajowhite", [255, 222, 173]), - ("navajowhite1", [255, 222, 173]), - ("navajowhite2", [238, 207, 161]), - ("navajowhite3", [205, 179, 139]), - ("navajowhite4", [139, 121, 94]), - ("navy", [0, 0, 128]), - ("navyblue", [0, 0, 128]), - ("oldlace", [253, 245, 230]), - ("olivedrab", [107, 142, 35]), - ("olivedrab1", [192, 255, 62]), - ("olivedrab2", [179, 238, 58]), - ("olivedrab3", [154, 205, 50]), - ("olivedrab4", [105, 139, 34]), - ("orange", [255, 165, 0]), - ("orange1", [255, 165, 0]), - ("orange2", [238, 154, 0]), - ("orange3", [205, 133, 0]), - ("orange4", [139, 90, 0]), - ("orangered", [255, 69, 0]), - ("orangered1", [255, 69, 0]), - ("orangered2", [238, 64, 0]), - ("orangered3", [205, 55, 0]), - ("orangered4", [139, 37, 0]), - ("orchid", [218, 112, 214]), - ("orchid1", [255, 131, 250]), - ("orchid2", [238, 122, 233]), - ("orchid3", [205, 105, 201]), - ("orchid4", [139, 71, 137]), - ("palegoldenrod", [238, 232, 170]), - ("palegreen", [152, 251, 152]), - ("palegreen1", [154, 255, 154]), - ("palegreen2", [144, 238, 144]), - ("palegreen3", [124, 205, 124]), - ("palegreen4", [84, 139, 84]), - ("paleturquoise", [175, 238, 238]), - ("paleturquoise1", [187, 255, 255]), - ("paleturquoise2", [174, 238, 238]), - ("paleturquoise3", [150, 205, 205]), - ("paleturquoise4", [102, 139, 139]), - ("palevioletred", [219, 112, 147]), - ("palevioletred1", [255, 130, 171]), - ("palevioletred2", [238, 121, 159]), - ("palevioletred3", [205, 104, 137]), - ("palevioletred4", [139, 71, 93]), - ("papayawhip", [255, 239, 213]), - ("peachpuff", [255, 218, 185]), - ("peachpuff1", [255, 218, 185]), - ("peachpuff2", [238, 203, 173]), - ("peachpuff3", [205, 175, 149]), - ("peachpuff4", [139, 119, 101]), - ("peru", [205, 133, 63]), - ("pink", [255, 192, 203]), - ("pink1", [255, 181, 197]), - ("pink2", [238, 169, 184]), - ("pink3", [205, 145, 158]), - ("pink4", [139, 99, 108]), - ("plum", [221, 160, 221]), - ("plum1", [255, 187, 255]), - ("plum2", [238, 174, 238]), - ("plum3", [205, 150, 205]), - ("plum4", [139, 102, 139]), - ("powderblue", [176, 224, 230]), - ("purple", [160, 32, 240]), - ("purple1", [155, 48, 255]), - ("purple2", [145, 44, 238]), - ("purple3", [125, 38, 205]), - ("purple4", [85, 26, 139]), - ("red", [255, 0, 0]), - ("red1", [255, 0, 0]), - ("red2", [238, 0, 0]), - ("red3", [205, 0, 0]), - ("red4", [139, 0, 0]), - ("rosybrown", [188, 143, 143]), - ("rosybrown1", [255, 193, 193]), - ("rosybrown2", [238, 180, 180]), - ("rosybrown3", [205, 155, 155]), - ("rosybrown4", [139, 105, 105]), - ("royalblue", [65, 105, 225]), - ("royalblue1", [72, 118, 255]), - ("royalblue2", [67, 110, 238]), - ("royalblue3", [58, 95, 205]), - ("royalblue4", [39, 64, 139]), - ("saddlebrown", [139, 69, 19]), - ("salmon", [250, 128, 114]), - ("salmon1", [255, 140, 105]), - ("salmon2", [238, 130, 98]), - ("salmon3", [205, 112, 84]), - ("salmon4", [139, 76, 57]), - ("sandybrown", [244, 164, 96]), - ("seagreen", [46, 139, 87]), - ("seagreen1", [84, 255, 159]), - ("seagreen2", [78, 238, 148]), - ("seagreen3", [67, 205, 128]), - ("seagreen4", [46, 139, 87]), - ("seashell", [255, 245, 238]), - ("seashell1", [255, 245, 238]), - ("seashell2", [238, 229, 222]), - ("seashell3", [205, 197, 191]), - ("seashell4", [139, 134, 130]), - ("sienna", [160, 82, 45]), - ("sienna1", [255, 130, 71]), - ("sienna2", [238, 121, 66]), - ("sienna3", [205, 104, 57]), - ("sienna4", [139, 71, 38]), - ("skyblue", [135, 206, 235]), - ("skyblue1", [135, 206, 255]), - ("skyblue2", [126, 192, 238]), - ("skyblue3", [108, 166, 205]), - ("skyblue4", [74, 112, 139]), - ("slateblue", [106, 90, 205]), - ("slateblue1", [131, 111, 255]), - ("slateblue2", [122, 103, 238]), - ("slateblue3", [105, 89, 205]), - ("slateblue4", [71, 60, 139]), - ("slategray", [112, 128, 144]), - ("slategray1", [198, 226, 255]), - ("slategray2", [185, 211, 238]), - ("slategray3", [159, 182, 205]), - ("slategray4", [108, 123, 139]), - ("slategrey", [112, 128, 144]), - ("snow", [255, 250, 250]), - ("snow1", [255, 250, 250]), - ("snow2", [238, 233, 233]), - ("snow3", [205, 201, 201]), - ("snow4", [139, 137, 137]), - ("springgreen", [0, 255, 127]), - ("springgreen1", [0, 255, 127]), - ("springgreen2", [0, 238, 118]), - ("springgreen3", [0, 205, 102]), - ("springgreen4", [0, 139, 69]), - ("steelblue", [70, 130, 180]), - ("steelblue1", [99, 184, 255]), - ("steelblue2", [92, 172, 238]), - ("steelblue3", [79, 148, 205]), - ("steelblue4", [54, 100, 139]), - ("tan", [210, 180, 140]), - ("tan1", [255, 165, 79]), - ("tan2", [238, 154, 73]), - ("tan3", [205, 133, 63]), - ("tan4", [139, 90, 43]), - ("thistle", [216, 191, 216]), - ("thistle1", [255, 225, 255]), - ("thistle2", [238, 210, 238]), - ("thistle3", [205, 181, 205]), - ("thistle4", [139, 123, 139]), - ("tomato", [255, 99, 71]), - ("tomato1", [255, 99, 71]), - ("tomato2", [238, 92, 66]), - ("tomato3", [205, 79, 57]), - ("tomato4", [139, 54, 38]), - ("turquoise", [64, 224, 208]), - ("turquoise1", [0, 245, 255]), - ("turquoise2", [0, 229, 238]), - ("turquoise3", [0, 197, 205]), - ("turquoise4", [0, 134, 139]), - ("violet", [238, 130, 238]), - ("violetred", [208, 32, 144]), - ("violetred1", [255, 62, 150]), - ("violetred2", [238, 58, 140]), - ("violetred3", [205, 50, 120]), - ("violetred4", [139, 34, 82]), - ("wheat", [245, 222, 179]), - ("wheat1", [255, 231, 186]), - ("wheat2", [238, 216, 174]), - ("wheat3", [205, 186, 150]), - ("wheat4", [139, 126, 102]), - ("white", [255, 255, 255]), - ("whitesmoke", [245, 245, 245]), - ("yellow", [255, 255, 0]), - ("yellow1", [255, 255, 0]), - ("yellow2", [238, 238, 0]), - ("yellow3", [205, 205, 0]), - ("yellow4", [139, 139, 0]), - ("yellowgreen", [154, 205, 50]), -]; diff --git a/crates/raster-codecs/tests/shared_contract.rs b/crates/raster-codecs/tests/shared_contract.rs new file mode 100644 index 0000000000..390242a650 --- /dev/null +++ b/crates/raster-codecs/tests/shared_contract.rs @@ -0,0 +1,46 @@ +//! The compatibility facade must retain its policy while sharing the codec implementation. +use craft_raster_codecs::{ChannelLayout, CodecError, Image, Limits, SampleType, dds, fits, iff, pnm, xpm}; + +#[test] +fn facade_refuses_conversions_the_generic_encoder_can_plan() { + for layout in [ChannelLayout::GrayA, ChannelLayout::Rgba, ChannelLayout::Cmyk, ChannelLayout::CmykA] { + let image = Image::from_f32(1, 1, layout, &vec![0.5; layout.channels()]).unwrap(); + assert!(matches!(pnm::encode(&image), Err(CodecError::Encode { .. }))); + assert!(matches!(fits::encode(&image), Err(CodecError::Encode { .. }))); + } + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Cmyk, ChannelLayout::CmykA] { + let image = Image::from_u8(1, 1, layout, vec![127; layout.channels()]).unwrap(); + for compression in [dds::DdsCompression::Bc1, dds::DdsCompression::Bc2, dds::DdsCompression::Bc3] { + assert!(matches!(dds::encode(&image, dds::DdsOptions { compression, mipmaps: false }), Err(CodecError::Encode { .. }))); + } + } + for layout in [ChannelLayout::Rgb, ChannelLayout::Rgba] { + let image = Image::from_u16(1, 1, layout, &vec![32768; layout.channels()]).unwrap(); + assert!(matches!(iff::encode(&image), Err(CodecError::Encode { .. }))); + assert!(matches!(dds::encode(&image, dds::DdsOptions::default()), Err(CodecError::Encode { .. }))); + } +} + +#[test] +fn fits_facade_keeps_metadata_samples_and_explicit_limits() { + let mut image = Image::from_u16(2, 1, ChannelLayout::Gray, &[0, 65535]).unwrap(); + image.text.push(("OBJECT".into(), "shared codec".into())); + let bytes = fits::encode(&image).unwrap(); + let decoded = fits::decode(&bytes, &Limits::default()).unwrap(); + assert_eq!(decoded.sample_type(), SampleType::U16); + assert_eq!(decoded.data(), image.data()); + assert!(decoded.text.contains(&("OBJECT".into(), "shared codec".into()))); + for limits in + [Limits { max_width: 1, ..Limits::default() }, Limits { max_pixels: 1, ..Limits::default() }, Limits { max_alloc: 3, ..Limits::default() }] + { + assert!(matches!(fits::decode(&bytes, &limits), Err(CodecError::LimitExceeded(_)))); + } +} + +#[test] +fn x11_table_lookup_does_not_adopt_xpm_aliases_or_normalization() { + assert_eq!(xpm::x11_color_rgb("red"), Some([1.0, 0.0, 0.0])); + for name in ["Red", "light blue", "light-blue", "light_blue", "none", "transparent", ""] { + assert_eq!(xpm::x11_color_rgb(name), None, "{name}"); + } +} diff --git a/crates/raw/src/arw.rs b/crates/raw/src/arw.rs index 639fc00327..1b25aacda1 100644 --- a/crates/raw/src/arw.rs +++ b/crates/raw/src/arw.rs @@ -629,6 +629,19 @@ fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> { .max_by_key(|i| i.u64(t::IMAGE_WIDTH).unwrap_or(0).saturating_mul(i.u64(t::IMAGE_LENGTH).unwrap_or(0))) } +fn valid_arw2_curve(curve: &[u64]) -> bool { + curve.len() == 4 && curve.iter().all(|&v| v <= 16383) && curve.windows(2).all(|v| (v[0] >> 2) < (v[1] >> 2)) +} + +fn declared_arw2_curve(raw: &Ifd, compression: u16, one_byte_per_sample: bool) -> Result>> { + let curve = raw.u64s(TONE_CURVE); + if compression == 32767 && one_byte_per_sample && curve.as_ref().is_some_and(|curve| !valid_arw2_curve(curve)) { + // Reordering or clamping malformed breakpoints fabricates a different transfer curve. + return Err(RawError::Unsupported("Sony ARW2 with an invalid tone curve".into())); + } + Ok(curve) +} + pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { let tiff = Tiff::parse(bytes)?; let ifd0 = tiff.ifds.first().ok_or_else(|| RawError::Corrupt("TIFF without IFDs".into()))?; @@ -645,6 +658,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result (RawData::U16(read_ycbcr_tiles(bytes, &info, raw, mode, limits)?), 14), @@ -720,13 +734,16 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result= (w * h * 2) as u64 { 14 } else { out_bits }; - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + let (cfa, assumed_cfa) = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { - Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } + (Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 }, false) } - _ => Cfa::bayer_static("RGGB"), + _ => (Cfa::bayer_static("RGGB"), true), }; - let default_black = if scale_bits >= 14 { 512.0 } else { 128.0 }; + let curve_black = (info.compression == 32767 && one_byte_per_sample) + .then(|| declared_curve.as_ref().and_then(|curve| code_curve(curve).get(256).copied()).map(f32::from)) + .flatten(); + let default_black = curve_black.unwrap_or(if scale_bits >= 14 { 512.0 } else { 128.0 }); // the decrypted SR2SubIFD, read once and only when a plain black level or white balance is missing let sr2_cell = std::cell::OnceCell::new(); let sr2 = || sr2_cell.get_or_init(|| crate::sr2::SubIfd::read(bytes, ifd0, tiff.order)).as_ref(); @@ -741,7 +758,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result (BlackLevel::uniform(default_black + YCBCR_OFFSET), crate::LevelSource::Fallback), _ => match (scale_bits >= 14).then(|| sr2().and_then(sr2_black)).flatten() { Some(b) => (BlackLevel::uniform(b), crate::LevelSource::Metadata), - None => (BlackLevel::uniform(default_black), crate::LevelSource::Fallback), + None => (BlackLevel::uniform(default_black), curve_black.map_or(crate::LevelSource::Fallback, |_| crate::LevelSource::Metadata)), }, }; // ARW6 samples are in 2 x 14-bit units, so the file's 14-bit levels double; without the tag the white is the @@ -842,6 +859,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Vec { + arw_with_strip_and_cfa(strip, None) + } + + fn arw_with_strip_and_cfa(strip: usize, cfa: Option<(Vec, Vec)>) -> Vec { use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value}; let mut raw = IfdBuilder::new(); raw.set(t::MAKE, Value::Ascii("SONY".into())); @@ -921,11 +945,37 @@ mod tests { raw.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![1])); raw.set(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])); raw.set(t::COMPRESSION, Value::Short(vec![32767])); + if let Some((dimensions, pattern)) = cfa { + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(dimensions)); + raw.set(t::CFA_PATTERN_EP, Value::Byte(pattern)); + } raw.set(TONE_CURVE, Value::Short(vec![8000, 10400, 12900, 14100])); raw.set_image(ImageData::Strips { rows_per_strip: 4, strips: vec![vec![0u8; strip]] }); TiffWriter::default().write(&[raw]).unwrap() } + #[test] + fn cfa_fallback_notices_follow_missing_malformed_and_valid_source_tags() { + for (tags, expected, assumed) in [ + (None, "RGGB", true), + (Some((vec![1, 4], vec![0, 1, 1, 2])), "RGGB", true), + (Some((vec![2, 2], vec![0, 1, 3, 2])), "RGGB", true), + (Some((vec![2, 2], vec![0, 1, 2])), "RGGB", true), + (Some((vec![2, 2], vec![1, 0, 2, 1])), "GRBG", false), + ] { + let file = arw_with_strip_and_cfa(32 * 4, tags); + let header = decode(&file, Mode::Header, &Limits::default()).unwrap(); + let full = decode(&file, Mode::Full, &Limits::default()).unwrap(); + assert_eq!(header.info(), full.info()); + for image in [&header, &full] { + assert_eq!(image.cfa.as_ref().unwrap().name(), expected); + assert_eq!(image.notices.assumed_cfa, assumed); + } + assert!(header.data.is_empty()); + assert_eq!(full.data.len(), 32 * 4); + } + } + /// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow. #[test] fn strip_byte_counts_past_u64_max_do_not_overflow() { @@ -1110,6 +1160,25 @@ mod tests { let _ = code_curve(&[60000, 1, 0, 0]); } + #[test] + fn arw2_rejects_non_increasing_declared_curve_in_header_and_full_decode() { + let valid = arw_with_strip(32 * 4); + assert!(crate::decode(&valid).is_ok()); + let mut damaged = valid.clone(); + let tiff = Tiff::parse(&damaged).unwrap(); + let curve = raw_ifd(&tiff).unwrap().get(TONE_CURVE).unwrap(); + let at = curve.offset as usize; + for (dst, value) in damaged[at..at + 8].as_chunks_mut::<2>().0.iter_mut().zip([9000u16, 8000, 12000, 13000]) { + dst.copy_from_slice(&value.to_le_bytes()); + } + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&damaged, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("curve"))); + let image = decode(&valid, mode, &Limits::default()).unwrap(); + assert_eq!(image.black.mean(), 512.0); + assert_eq!(image.level_sources.black, crate::LevelSource::Metadata, "the declared curve maps the black code"); + } + } + #[test] fn decipher_inverts_the_cube_substitution() { let mut seen = [false; 256]; diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs index ec98ea48eb..0253845826 100644 --- a/crates/raw/src/cr2.rs +++ b/crates/raw/src/cr2.rs @@ -10,8 +10,11 @@ //! - Colour filter layout: IFD#3 tag `0xc5e0` (`CR2CFAPattern` in the ExifTool EXIF tag-name docs): 1 = RGGB, //! 2 = BGGR, 3 = GBRG, 4 = GRBG, anchored at the top-left of the full decoded sensor (masked borders included). //! It differs by model (e.g. 3 on the 50D/60D/7D/550D/5D Mark II, 1 on the 40D/5D Mark III/6D/5DS R), so it is -//! read per file (no model table); files without the tag fall back to RGGB (storytold/lightcraft#85). The parity of the +//! read per file first. Without a known tag, observed model IDs provide the fallback; scene-derived +//! measurements are not authoritative enough to establish sensor phase. The parity of the //! `SensorInfo` borders does *not* predict it (RGGB files come with both even and odd top borders). +//! Header-only probes do not decode pixels for this fallback: without the tag their reported CFA +//! is assumed and can refine on full decode, as indicated by `RawNotices::assumed_cfa`. //! - `SensorInfo` (maker note `0x00e0`): sensor width/height and the left/top/right/bottom borders of the image //! area. Light already reaches some columns left of that border (EOS 6D: masked columns 0–70, border 84; 10–36 //! such columns on every corpus body), so the masked columns that give the black level are measured from the @@ -38,6 +41,7 @@ const SRAW_TYPE: u16 = 0xc6c5; /// `SRAW_TYPE` value of the YCbCr frames of sRAW / mRAW (IFD2's preview image carries 3). const SRAW_YCC: u32 = 4; const CR2_CFA_PATTERN: u16 = 0xc5e0; +const CANON_MODEL_ID: u16 = 0x0010; const SENSOR_INFO: u16 = 0x00e0; const COLOR_BALANCE: u16 = 0x4001; /// ShotInfo, whose value 7 is the white-balance setting. @@ -61,6 +65,13 @@ fn cfa_from_tag(v: Option) -> Option { Some(Cfa::bayer_static(name)) } +/// Fallback for files without CR2CFAPattern. Image content cannot establish sensor phase safely. +fn fallback_cfa(_data: &[u16], _width: usize, _area: Rect, _black: f32, _white: f32, model: Option) -> (Cfa, bool) { + // Observed CC0 raw.pixls.us captures: 5D II, 7D, 550D, 600D and 1200D. + let green_first = [0x8000_0218, 0x8000_0250, 0x8000_0270, 0x8000_0286, 0x8000_0327].into_iter().any(|id| model == Some(id)); + (Cfa::bayer_static(if green_first { "GBRG" } else { "RGGB" }), true) +} + /// The 16-bit words of a maker-note array. Canon writes `ColorData` as SHORT in most models, but as UNDEFINED /// bytes (count = byte length, e.g. 5120) in the PowerShot / EOS M models with ColorData versions -3 and -4; /// those bytes are the same 16-bit words in the maker note's byte order, so they are paired up, not read one by @@ -198,6 +209,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result { let total = (fw as u64) @@ -270,12 +282,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result= 2 => black_from_columns_sourced(&data, width, cols, active.y..active.y + active.height, active), _ => (BlackLevel::uniform(0.0), crate::LevelSource::Fallback), }; + let model = mn.as_ref().and_then(|m| m.ifd.u64(CANON_MODEL_ID)); + let (cfa, assumed_cfa) = match tagged_cfa { + Some(cfa) => (cfa, false), + None => { + let (cfa, guessed) = fallback_cfa(&data, width, active, black.mean(), white, model); + (cfa, guessed || mode == Mode::Header) + } + }; let img = RawImage { format: RawFormat::Cr2, width, @@ -298,6 +317,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let texture = ((x / 2 + y / 2) % 17) as u16; + if i % 97 == 0 { + return 13000; + } + 100 + if (y & 1) == red_row { + if x & 1 == 0 { 500 + texture } else { 1000 + texture } + } else if x & 1 == 0 { + 1000 + texture + } else { + 667 + texture + } + }) + .collect(); + for (left, top) in [(16, 4), (17, 4), (16, 5), (17, 5)] { + let area = Rect::new(left, top, w - left, h - top); + let (cfa, assumed) = fallback_cfa(&samples, w, area, 100.0, 4000.0, None); + assert_eq!(cfa.name(), "RGGB"); + assert!(assumed); + } + let mut bytes = synthetic_cr2_of(&samples, w, h, None, None); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // The explicit tag remains authoritative even when the observed sensor phase disagrees. + bytes[at + 8..at + 12].copy_from_slice(&4u32.to_le_bytes()); + let explicit = crate::decode(&bytes).unwrap(); + assert_eq!(explicit.cfa.as_ref().unwrap().name(), "GRBG"); + assert_eq!(explicit.info(), crate::probe_info(&bytes).unwrap()); + assert!(!explicit.notices.assumed_cfa); + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let full = crate::decode(&bytes).unwrap(); + assert_eq!(full.cfa.as_ref().unwrap().name(), "RGGB"); + assert!(full.notices.assumed_cfa); + let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); + assert!(header.notices.assumed_cfa); + assert!(matches!(header.data, RawData::U16(ref v) if v.is_empty())); + assert_eq!(full.data, RawData::U16(samples)); + } + } + + #[test] + fn inconclusive_cfa_measurement_keeps_observed_model_fallback_and_safe_geometry() { + let data = vec![512; 64 * 32]; + let area = Rect::new(0, 0, 64, 32); + assert_eq!(fallback_cfa(&data, 64, area, 512.0, 16000.0, Some(0x8000_0250)).0.name(), "GBRG"); + assert!(fallback_cfa(&data, 64, area, 512.0, 16000.0, Some(0x8000_0250)).1); + assert_eq!(fallback_cfa(&data, 64, area, 512.0, 16000.0, None).0.name(), "RGGB"); + assert!(fallback_cfa(&data, 64, area, 512.0, 16000.0, None).1); + let gradient: Vec = (0..192 * 96) + .map(|i| { + let (x, y) = (i % 192, i / 192); + if y % 2 == 0 { + if x % 2 == 0 { 500 } else { 1000 + 8 * x as u16 } + } else if x % 2 == 0 { + 1000 + 8 * x as u16 + } else { + 500 + } + }) + .collect(); + let (cfa, assumed) = fallback_cfa(&gradient, 192, Rect::new(0, 0, 192, 96), 0.0, 4000.0, None); + assert_eq!(cfa.name(), "RGGB"); + assert!(assumed); + let mut bytes = synthetic_cr2_of(&gradient, 192, 96, None, None); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // Exercise the decoder's missing-tag fallback, not the fixture's default CFA tag. + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let decoded = crate::decode(&bytes).unwrap(); + assert_eq!(decoded.cfa.as_ref().unwrap().name(), "RGGB"); + assert!(decoded.notices.assumed_cfa); + } + + #[test] + fn model_cfa_fallback_is_disclosed_in_header_and_full_decodes() { + // A single inline LONG maker-note entry needs no external offsets. + let mut note = Vec::new(); + note.extend_from_slice(&1u16.to_le_bytes()); + note.extend_from_slice(&CANON_MODEL_ID.to_le_bytes()); + note.extend_from_slice(&4u16.to_le_bytes()); + note.extend_from_slice(&1u32.to_le_bytes()); + note.extend_from_slice(&0x8000_0250u32.to_le_bytes()); + note.extend_from_slice(&0u32.to_le_bytes()); + let samples = vec![512u16; 64 * 32]; + let mut bytes = synthetic_cr2_of(&samples, 64, 32, None, Some(note)); + let marker = [0xe0, 0xc5, 4, 0, 1, 0, 0, 0]; + let at = bytes.windows(marker.len()).position(|b| b == marker).unwrap(); + // Remove only the CFA tag; the model ID and encoded samples stay intact. + bytes[at..at + 2].copy_from_slice(&0xc5dfu16.to_le_bytes()); + let header = decode(&bytes, Mode::Header, &Limits::default()).unwrap(); + let full = decode(&bytes, Mode::Full, &Limits::default()).unwrap(); + for image in [&header, &full] { + assert_eq!(image.cfa.as_ref().unwrap().name(), "GBRG"); + assert!(image.notices.assumed_cfa); + } + assert_eq!(header.info(), full.info()); + assert_eq!(full.data, RawData::U16(samples)); + assert!(header.data.is_empty()); + } + #[test] fn wb_probe() { let mut v = vec![0u64; 120]; diff --git a/crates/raw/src/cr2/sraw.rs b/crates/raw/src/cr2/sraw.rs index 7ad98906be..4b02881d25 100644 --- a/crates/raw/src/cr2/sraw.rs +++ b/crates/raw/src/cr2/sraw.rs @@ -393,6 +393,7 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode, limits: & camera: tiff.ifds.first().map(Camera::from_ifd0).unwrap_or_default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: Default::default(), level_sources: Default::default(), }; img.validate_for(mode)?; diff --git a/crates/raw/src/cr3.rs b/crates/raw/src/cr3.rs index 956446c6e2..14bec61325 100644 --- a/crates/raw/src/cr3.rs +++ b/crates/raw/src/cr3.rs @@ -274,6 +274,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Vec { + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(); + track_with_mapping(entry, offset, size, &mapping) + } + + fn track_with_mapping(entry: &[u8], offset: u64, size: u32, mapping: &[u8]) -> Vec { + track_with_table(entry, offset, size, b"stsc", mapping) + } + + fn track_with_table(entry: &[u8], offset: u64, size: u32, table: &[u8; 4], payload: &[u8]) -> Vec { let mut stsd = vec![0u8; 4]; stsd.extend(1u32.to_be_bytes()); stsd.extend(entry); @@ -413,7 +423,15 @@ mod tests { let mut co64 = vec![0u8; 4]; co64.extend(1u32.to_be_bytes()); co64.extend(offset.to_be_bytes()); - let tables = [box_bytes(b"stsd", &stsd), box_bytes(b"stsz", &stsz), box_bytes(b"co64", &co64)].concat(); + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(); + let offsets = if table == b"stco" { box_bytes(b"stco", payload) } else { box_bytes(b"co64", if table == b"co64" { payload } else { &co64 }) }; + let tables = [ + box_bytes(b"stsd", &stsd), + box_bytes(b"stsc", if table == b"stsc" { payload } else { &mapping }), + box_bytes(b"stsz", if table == b"stsz" { payload } else { &stsz }), + offsets, + ] + .concat(); box_bytes(b"trak", &box_bytes(b"mdia", &box_bytes(b"minf", &box_bytes(b"stbl", &tables)))) } @@ -636,6 +654,105 @@ mod tests { assert!(matches!(decode(&missing, Mode::Header, &Limits::default()), Err(RawError::Corrupt(_)))); } + /// Independently framed constant-value CRX: each 4x4 tile has four 2x2 + /// planes whose one-byte 0x1e entropy streams reconstruct sensor value8193. + fn flat_raw_track(tiles: u32) -> (Vec, Vec) { + let mut sample = Vec::new(); + let marker = |out: &mut Vec, code: u16, size: u32, flags: u32| { + out.extend(code.to_be_bytes()); + out.extend(8u16.to_be_bytes()); + out.extend(size.to_be_bytes()); + out.extend(flags.to_be_bytes()); + }; + for tile in 0..tiles { + marker(&mut sample, 0xff01, 4, tile << 16); + for plane in 0..4 { + marker(&mut sample, 0xff02, 1, (plane << 28) | 0x0800_0000); + marker(&mut sample, 0xff03, 1, 0x0020_0000); + } + } + let header_size = sample.len() as u32; + sample.extend(std::iter::repeat_n(0x1e, tiles as usize * 4)); + let mut coding = vec![0u8; 52]; + coding[..2].copy_from_slice(&0xff00u16.to_be_bytes()); + coding[2..4].copy_from_slice(&48u16.to_be_bytes()); + coding[4..6].copy_from_slice(&0x100u16.to_be_bytes()); + for (offset, value) in [(8, tiles * 4), (12, 4), (16, 4), (20, 4), (28, header_size)] { + coding[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); + } + coding[24] = 14; + coding[25] = 0x40; + let mut entry = vec![0u8; 82]; + entry[24..26].copy_from_slice(&((tiles * 4) as u16).to_be_bytes()); + entry[26..28].copy_from_slice(&4u16.to_be_bytes()); + entry.extend(box_bytes(b"CMP1", &coding)); + (box_bytes(b"CRAW", &entry), sample) + } + + #[test] + fn truncated_main_sample_mapping_cannot_silently_select_a_valid_reduced_raw() { + let mapping = [0u32, 1, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>(); + let (reduced_entry, reduced_sample) = flat_raw_track(1); + let (main_entry, main_sample) = flat_raw_track(2); + let main_offset = 4096 + reduced_sample.len(); + let file = |main_table: Option<(&[u8; 4], &[u8])>, main_first: bool| { + let reduced = track_with_mapping(&reduced_entry, 4096, reduced_sample.len() as u32, &mapping); + let tracks = if let Some((table, payload)) = main_table { + let main = track_with_table(&main_entry, main_offset as u64, main_sample.len() as u32, table, payload); + if main_first { [main, reduced].concat() } else { [reduced, main].concat() } + } else { + reduced + }; + let mut bytes = box_bytes(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(box_bytes(b"moov", &tracks)); + assert!(bytes.len() < 4096); + bytes.resize(4096, 0); + bytes.extend_from_slice(&reduced_sample); + bytes.extend_from_slice(&main_sample); + bytes + }; + let mut co64 = vec![0u8; 4]; + co64.extend(1u32.to_be_bytes()); + co64.extend((main_offset as u64).to_be_bytes()); + let valid_tables = [ + (b"stsc", mapping.clone()), + (b"stsz", [0u32, main_sample.len() as u32, 1].into_iter().flat_map(u32::to_be_bytes).collect()), + (b"co64", co64), + (b"stco", [0u32, 1, main_offset as u32].into_iter().flat_map(u32::to_be_bytes).collect()), + ]; + for mode in [Mode::Header, Mode::Full] { + // The smaller source is genuinely decodable, so dropping the larger + // track would return success rather than merely a different failure. + let reduced = decode(&file(None, false), mode, &Limits::default()).unwrap(); + assert_eq!((reduced.width, reduced.height), (4, 4)); + if mode == Mode::Full { + assert_eq!(reduced.data, RawData::U16(vec![8193; 16])); + } + for main_first in [false, true] { + for (table, payload) in &valid_tables { + let valid = decode(&file(Some((table, payload)), main_first), mode, &Limits::default()).unwrap(); + assert_eq!((valid.width, valid.height), (8, 4)); + if mode == Mode::Full { + assert_eq!(valid.data, RawData::U16(vec![8193; 32])); + } + for truncated in [vec![], vec![0; 4], vec![0, 0, 0, 0, 0, 0, 0, 1]] { + let bytes = file(Some((table, &truncated)), main_first); + let container = parse_cr3(&bytes).unwrap(); + assert_eq!(container.tracks.len(), 2, "mapping damage cannot erase the main track"); + let selected = main_track(&container.tracks).unwrap(); + assert!(matches!(selected.kind, Cr3TrackKind::Raw { width: 8, height: 4, .. })); + assert!(selected.data.is_none()); + assert!(selected.compression(&bytes).is_some()); + assert!( + matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Corrupt(message)) if message.contains("sample")), + "{mode:?}/{table:?}: main mapping damage cannot decode the reduced source" + ); + } + } + } + } + } + #[test] fn color_data_uses_versioned_as_shot_offsets() { for (version, wb_at, black_at, white_at) in @@ -712,6 +829,7 @@ mod tests { camera: Camera::default(), cinema: Default::default(), lens_metadata: Default::default(), + notices: Default::default(), level_sources: Default::default(), } } diff --git a/crates/raw/src/crw.rs b/crates/raw/src/crw.rs index 6909667516..b51c042613 100644 --- a/crates/raw/src/crw.rs +++ b/crates/raw/src/crw.rs @@ -65,6 +65,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, caller: &Limits) -> Result bool { if !raw.contains(t::AS_SHOT_NEUTRAL) && !tiff.ifds.first().is_some_and(|i| i.contains(t::AS_SHOT_NEUTRAL)) { return false; } - let Ok(info) = raw.image() else { return false }; + let Ok(info) = raw.image() else { + // Recognition must not turn a damaged, otherwise supported plain CFA + // image into an unsupported container. Let decode_as report its layout + // error; these tags alone never decompress or allocate pixel samples. + return raw.u16(t::COMPRESSION).unwrap_or(1) == t::compression::NONE + && raw.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1) == 1 + && (1..=16).contains(&raw.u16(t::BITS_PER_SAMPLE).unwrap_or(1)) + && raw.u16(t::SAMPLE_FORMAT).unwrap_or(1) != 3; + }; if info.samples_per_pixel != 1 || !(1..=16).contains(&info.bits()) || info.sample_format == 3 { return false; } @@ -274,8 +282,13 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let bits = info.bits() as u32; // DNG 1.4 stores lossy JPEG at 8 bits per sample: the tiles are 8-bit baseline JPEGs whatever the tag says, // and reading them as a deeper sample would put the picture at the bottom of its range - if info.compression == t::compression::LOSSY_JPEG && bits != 8 { - return Err(RawError::Unsupported(format!("lossy JPEG DNG with {bits}-bit samples (DNG allows only 8)"))); + if info.compression == t::compression::LOSSY_JPEG { + if bits != 8 { + return Err(RawError::Unsupported(format!("lossy JPEG DNG with {bits}-bit samples (DNG allows only 8)"))); + } + if !matches!(cpp, 1 | 3) { + return Err(RawError::Unsupported(format!("lossy JPEG DNG with {cpp} samples per pixel"))); + } } let mut data = read_image_in(mode, bytes, &info, tiff.order, Packing::Msb, limits)?; @@ -312,6 +325,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f // (a DOUBLE past `f32::MAX` casts to infinity, which would black the picture out: ignored like a zero one) let mut white: Vec = levels(t::WHITE_LEVEL).f64s(t::WHITE_LEVEL).unwrap_or_default().into_iter().map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0).collect(); + let white_source = if !white.is_empty() || table_max.is_some() { LevelSource::Metadata } else { LevelSource::Fallback }; if white.is_empty() { white = vec![default_white]; } @@ -333,7 +347,13 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f }; // (a FLOAT / DOUBLE tag can hold NaN or infinity: such a level reads as 0, in its place) let level = |v: f64| Some(v as f32).filter(|v| v.is_finite()).unwrap_or(0.0); - let mut values: Vec = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default().into_iter().map(level).collect(); + let declared_black = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default(); + let black_source = if !declared_black.is_empty() && declared_black.iter().all(|value| (*value as f32).is_finite()) { + LevelSource::Metadata + } else { + LevelSource::Fallback + }; + let mut values: Vec = declared_black.into_iter().map(level).collect(); // A TIFF that is not a DNG may state four black levels without `BlackLevelRepeatDim`: one per site of its 2 × 2 // CFA, row-major (PhotoCraft's reading of Hasselblad files). In a DNG the count has to match the repeat. let (br, bc) = if format != RawFormat::Dng && cpp == 1 && values.len() == 4 && !levels(t::BLACK_LEVEL).contains(t::BLACK_LEVEL_REPEAT_DIM) { @@ -364,7 +384,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f } _ => Rect::new(0, 0, full_w, full_h), }; - let crop = default_crop(raw, active_area); + let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); let (active_area, crop) = if (full_w, full_h) == (w, h) { (active_area, crop) } else { @@ -378,6 +398,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f (area, scale(crop).clipped(area.width, area.height)) }; + let mut assumed_cfa = false; let cfa = if info.photometric == photometric::CFA { if raw.u16(t::CFA_LAYOUT).unwrap_or(1) != 1 { return Err(RawError::Unsupported("non-rectangular CFA layout".into())); @@ -391,7 +412,10 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let assumed = [0u8, 1, 1, 2]; let pat = match raw.bytes(t::CFA_PATTERN_EP) { Some(p) => p, - None if format != RawFormat::Dng && (rows, cols) == (2, 2) => &assumed, + None if format != RawFormat::Dng && (rows, cols) == (2, 2) => { + assumed_cfa = true; + &assumed + } None => return Err(RawError::Corrupt("missing CFAPattern".into())), }; if pat.len() != rows * cols { @@ -422,6 +446,9 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let opcodes = crate::OpcodeLists { list1: opcode_list(t::OPCODE_LIST_1), list2: opcode_list(t::OPCODE_LIST_2), list3: opcode_list(t::OPCODE_LIST_3) }; + let color = color_data(ifd0, raw, tiff.order); + let gain_table_omitted = [raw, ifd0].iter().any(|ifd| ifd.contains(t::PROFILE_GAIN_TABLE_MAP) || ifd.contains(t::PROFILE_GAIN_TABLE_MAP_2)) + && color.profile.gain_table_map.is_none(); let img = RawImage { format, width: w, @@ -435,7 +462,7 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f active_area, crop, orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)), - color: color_data(ifd0, raw, tiff.order), + color, wb_multipliers: None, linearized, pixel_aspect: default_scale_aspect(raw.f64s(t::DEFAULT_SCALE).as_deref()), @@ -443,7 +470,8 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f camera: Camera::from_ifd0(ifd0), cinema: cinema_tags(ifd0, raw), lens_metadata: Default::default(), - level_sources: Default::default(), + level_sources: LevelSources { black: black_source, white: white_source }, + notices: RawNotices { default_crop_adjusted, gain_table_omitted, assumed_cfa }, }; img.validate_for(mode)?; Ok(img) @@ -472,33 +500,45 @@ fn cinema_tags(ifd0: &Ifd, raw: &Ifd) -> CinemaTags { } } -/// The default crop, relative to the active area. Each tag has its own default (DNG 1.7.1, `DefaultCropOrigin` -/// and `DefaultCropSize`): the origin (0, 0), the size the whole area, so a file with only a size crops from the -/// area's corner. A tag that is present must hold two finite, non-negative values, and the crop must start inside -/// the area and be at least one pixel each way; otherwise the crop is the whole active area. -fn default_crop(raw: &Ifd, active_area: Rect) -> Rect { +/// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent +/// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop +/// preserves the entire active image. Valid partly overlapping rectangles retain the +/// existing clipped-crop policy, with an explicit notice rather than silent adjustment. +fn default_crop(raw: &Ifd, active_area: Rect, full_width: usize, full_height: usize) -> (Rect, bool) { let whole = Rect::new(0, 0, active_area.width, active_area.height); - let pair = |tag: u16, default: [f64; 2]| -> Option<[f64; 2]> { - if !raw.contains(tag) { - return Some(default); - } - match raw.f64s(tag).as_deref() { - Some([a, b]) if a.is_finite() && b.is_finite() && *a >= 0.0 && *b >= 0.0 => Some([*a, *b]), - _ => None, - } - }; - let (Some([x, y]), Some([cw, ch])) = - (pair(t::DEFAULT_CROP_ORIGIN, [0.0, 0.0]), pair(t::DEFAULT_CROP_SIZE, [active_area.width as f64, active_area.height as f64])) - else { - return whole; - }; - if cw < 1.0 || ch < 1.0 { - return whole; + if !raw.contains(t::DEFAULT_CROP_ORIGIN) && !raw.contains(t::DEFAULT_CROP_SIZE) { + return (whole, false); } - // (`as usize` saturates, and `clipped` holds the origin to the area) - let crop = - Rect::new(x.round() as usize, y.round() as usize, cw.round() as usize, ch.round() as usize).clipped(active_area.width, active_area.height); - if crop.width == 0 || crop.height == 0 { whole } else { crop } + let pair = |tag: u16, default: [f64; 2]| -> Option<[usize; 2]> { + let values = if raw.contains(tag) { + match raw.f64s(tag).as_deref() { + Some([a, b]) => [*a, *b], + _ => return None, + } + } else { + default + }; + // Float-to-integer casts saturate. Refuse nonfinite/unrepresentable numbers before + // casting so a hostile origin cannot become a seemingly valid clipped rectangle. + if values.iter().any(|value| !value.is_finite() || value.round() >= usize::MAX as f64) { + return None; + } + if values.iter().any(|value| *value < 0.0) { + return None; + } + Some(values.map(|value| value.round() as usize)) + }; + let (Some([x, y]), Some([width, height])) = + (pair(t::DEFAULT_CROP_ORIGIN, [0.0, 0.0]), pair(t::DEFAULT_CROP_SIZE, [full_width as f64, full_height as f64])) + else { + return (whole, true); + }; + let requested = Rect::new(x, y, width, height); + let crop = requested.clipped(active_area.width, active_area.height); + if crop.width == 0 || crop.height == 0 { + return (whole, true); + } + (crop, crop != requested) } /// Pixel height over width from `DefaultScale` (horizontal, vertical): only a clear 1.5 to 4 ratio counts (the rows stretch; a wider-than-tall pixel is left alone). @@ -509,6 +549,9 @@ fn default_scale_aspect(scale: Option<&[f64]>) -> f32 { } } +#[cfg(test)] +mod compat_review_tests; + #[cfg(test)] mod tests { #[test] @@ -621,3 +664,7 @@ mod tests { assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err()); } } + +#[cfg(all(test, feature = "hasselblad"))] +#[path = "dng/probe_review_tests.rs"] +mod probe_review_tests; diff --git a/crates/raw/src/dng/compat_review_tests.rs b/crates/raw/src/dng/compat_review_tests.rs new file mode 100644 index 0000000000..48300cbf77 --- /dev/null +++ b/crates/raw/src/dng/compat_review_tests.rs @@ -0,0 +1,120 @@ +use super::*; +use craft_tiff::{Entry, IfdBuilder, ImageData, TiffWriter}; + +fn ifd(tags: Vec<(u16, Value)>) -> Ifd { + let mut entries: Vec<_> = tags.into_iter().map(|(tag, value)| Entry { tag, value, offset: 0 }).collect(); + entries.sort_by_key(|entry| entry.tag); + Ifd { entries, ..Default::default() } +} + +#[test] +fn optional_crop_adjustments_are_explicit_and_valid_clipping_is_preserved() { + let active = Rect::new(3, 2, 11, 8); + let whole = Rect::new(0, 0, 11, 8); + let clipped = ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![10, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]); + assert_eq!(default_crop(&clipped, active, 16, 12), (Rect::new(10, 0, 1, 4), true)); + assert_eq!(default_crop(&ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![1, 1]))]), active, 16, 12), (Rect::new(1, 1, 10, 7), true)); + for fields in [ + vec![(t::DEFAULT_CROP_SIZE, Value::Long(vec![4]))], + vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![0, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![0, 4]))], + ] { + assert_eq!(default_crop(&ifd(fields), active, 16, 12), (whole, true)); + } + assert_eq!(default_crop(&Ifd::default(), active, 16, 12), (whole, false)); + assert_eq!(default_crop(&ifd(vec![(t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), active, 16, 12), (Rect::new(0, 0, 5, 4), false)); + assert_eq!( + default_crop(&ifd(vec![(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![2, 1])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), active, 16, 12), + (Rect::new(2, 1, 5, 4), false) + ); +} + +#[test] +fn hostile_crop_coordinates_fall_back_explicitly_before_saturating_casts() { + for bad in [1e300, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + for tag in [t::DEFAULT_CROP_ORIGIN, t::DEFAULT_CROP_SIZE] { + let raw = ifd(vec![(tag, Value::Double(vec![bad, 1.]))]); + assert_eq!(default_crop(&raw, Rect::new(0, 0, 16, 12), 16, 12), (Rect::new(0, 0, 16, 12), true)); + } + } +} + +fn linear(extra: &[(u16, Value)]) -> Vec { + let mut raw = IfdBuilder::new(); + for (tag, value) in [ + (t::IMAGE_WIDTH, Value::Long(vec![8])), + (t::IMAGE_LENGTH, Value::Long(vec![6])), + (t::BITS_PER_SAMPLE, Value::Short(vec![16])), + (t::SAMPLES_PER_PIXEL, Value::Short(vec![1])), + (t::PHOTOMETRIC, Value::Short(vec![photometric::LINEAR_RAW])), + (t::COMPRESSION, Value::Short(vec![1])), + ] { + raw.set(tag, value); + } + for (tag, value) in extra { + raw.set(*tag, value.clone()); + } + raw.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![(0u16..48).flat_map(u16::to_le_bytes).collect()] }); + TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap() +} + +#[test] +fn dng_and_generic_cfa_tiff_report_actual_level_sources_instead_of_unknown() { + for format in [RawFormat::Dng, RawFormat::CfaTiff] { + let missing = decode_as(&linear(&[]), Mode::Full, format, &Limits::default()).unwrap(); + assert_eq!(missing.level_sources, LevelSources { black: LevelSource::Fallback, white: LevelSource::Fallback }); + let declared = decode_as( + &linear(&[(t::BLACK_LEVEL, Value::Short(vec![17])), (t::WHITE_LEVEL, Value::Short(vec![1000]))]), + Mode::Full, + format, + &Limits::default(), + ) + .unwrap(); + assert_eq!(declared.level_sources, LevelSources { black: LevelSource::Metadata, white: LevelSource::Metadata }); + assert_eq!(declared.black.values, vec![17.]); + assert_eq!(declared.white, vec![1000.]); + let invalid = decode_as( + &linear(&[(t::BLACK_LEVEL, Value::Double(vec![f64::NAN])), (t::WHITE_LEVEL, Value::Double(vec![f64::INFINITY]))]), + Mode::Full, + format, + &Limits::default(), + ) + .unwrap(); + assert_eq!(invalid.level_sources, LevelSources { black: LevelSource::Fallback, white: LevelSource::Fallback }); + } + let table = decode_as(&linear(&[(t::LINEARIZATION_TABLE, Value::Short(vec![0, 1000]))]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert_eq!(table.white, vec![1000.]); + assert_eq!(table.level_sources.white, LevelSource::Metadata); +} + +#[test] +fn decoded_notices_record_actual_crop_gain_table_and_cfa_decisions() { + let plain = decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert_eq!(plain.notices, RawNotices::default()); + let adjusted = decode_as( + &linear(&[(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![7, 0])), (t::DEFAULT_CROP_SIZE, Value::Long(vec![5, 4]))]), + Mode::Full, + RawFormat::Dng, + &Limits::default(), + ) + .unwrap(); + assert_eq!(adjusted.crop, Rect::new(7, 0, 1, 4)); + assert!(adjusted.notices.default_crop_adjusted); + let invalid_gain = + decode_as(&linear(&[(t::PROFILE_GAIN_TABLE_MAP, Value::Undefined(vec![0; 16]))]), Mode::Full, RawFormat::Dng, &Limits::default()).unwrap(); + assert!(invalid_gain.notices.gain_table_omitted); + assert!(invalid_gain.color.profile.gain_table_map.is_none()); + let assumed = + decode_as(&linear(&[(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA]))]), Mode::Full, RawFormat::CfaTiff, &Limits::default()).unwrap(); + assert!(assumed.notices.assumed_cfa); + assert_eq!(assumed.cfa.as_ref().unwrap().pattern, vec![0, 1, 1, 2]); + let tagged = decode_as( + &linear(&[(t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])), (t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]))]), + Mode::Full, + RawFormat::Dng, + &Limits::default(), + ) + .unwrap(); + assert!(!tagged.notices.assumed_cfa); + let limits = Limits { max_samples: 47, ..Default::default() }; + assert!(matches!(decode_as(&linear(&[]), Mode::Full, RawFormat::Dng, &limits), Err(RawError::Limit(_)))); +} diff --git a/crates/raw/src/dng/probe_review_tests.rs b/crates/raw/src/dng/probe_review_tests.rs new file mode 100644 index 0000000000..8e54e8db6c --- /dev/null +++ b/crates/raw/src/dng/probe_review_tests.rs @@ -0,0 +1,64 @@ +use super::*; +use craft_tiff::{IfdBuilder, ImageData, TiffWriter}; + +#[allow(clippy::unwrap_used)] // Test fixture construction must fail the test if its independent writer fails. +fn plain() -> Vec { + let mut raw = IfdBuilder::new(); + for (tag, value) in [ + (t::IMAGE_WIDTH, Value::Long(vec![2])), + (t::IMAGE_LENGTH, Value::Long(vec![2])), + (t::BITS_PER_SAMPLE, Value::Short(vec![16])), + (t::SAMPLES_PER_PIXEL, Value::Short(vec![1])), + (t::PHOTOMETRIC, Value::Short(vec![photometric::CFA])), + (t::COMPRESSION, Value::Short(vec![1])), + (t::AS_SHOT_NEUTRAL, Value::Rational(vec![(1, 2), (1, 1), (2, 3)])), + ] { + raw.set(tag, value); + } + raw.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![[17u16, 31, 53, 79].into_iter().flat_map(u16::to_le_bytes).collect()] }); + TiffWriter::new(ByteOrder::Little, false).write(&[raw]).unwrap() +} + +#[allow(clippy::unwrap_used)] // Only known tags in this module's synthetic TIFF are inspected. +fn entry(bytes: &[u8], tag: u16) -> usize { + let at = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let count = u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap()) as usize; + (0..count).map(|i| at + 2 + i * 12).find(|&i| u16::from_le_bytes(bytes[i..i + 2].try_into().unwrap()) == tag).unwrap() +} + +#[test] +fn plain_cfa_probe_keeps_malformed_geometry_and_tables_in_the_supported_decoder() { + let valid = plain(); + assert_eq!(crate::probe(&valid), Some(RawFormat::CfaTiff)); + let decoded = crate::decode(&valid).unwrap(); + assert_eq!(decoded.data, RawData::U16(vec![17, 31, 53, 79])); + for tag in [t::IMAGE_WIDTH, t::IMAGE_LENGTH] { + let mut damaged = valid.clone(); + let at = entry(&damaged, tag); + damaged[at + 8..at + 12].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(crate::probe(&damaged), Some(RawFormat::CfaTiff)); + assert!(matches!(crate::probe_info(&damaged), Err(RawError::Tiff(_))), "zero geometry remains malformed before pixel decode"); + assert!(matches!(crate::decode(&damaged), Err(RawError::Tiff(_)))); + } + let mut missing = valid.clone(); + let at = entry(&missing, t::STRIP_OFFSETS); + missing[at..at + 2].copy_from_slice(&0xf123u16.to_le_bytes()); + assert_eq!(crate::probe(&missing), Some(RawFormat::CfaTiff)); + assert!(matches!(crate::probe_info(&missing), Err(RawError::Tiff(_)))); + assert!(matches!(crate::decode(&missing), Err(RawError::Tiff(_)))); +} + +#[test] +fn plain_cfa_probe_does_not_claim_unknown_tiff_codings_or_missing_color_contracts() { + for tag in [t::AS_SHOT_NEUTRAL, t::COMPRESSION] { + let mut unknown = plain(); + let at = entry(&unknown, tag); + if tag == t::COMPRESSION { + unknown[at + 8..at + 10].copy_from_slice(&65000u16.to_le_bytes()); + } else { + unknown[at..at + 2].copy_from_slice(&0xf123u16.to_le_bytes()); + } + assert_eq!(crate::probe(&unknown), Some(RawFormat::OtherTiff)); + assert!(matches!(crate::decode(&unknown), Err(RawError::Unsupported(_)))); + } +} diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index d7f6cdeddf..8953f94ea3 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -462,6 +462,7 @@ mod tests { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: crate::RawNotices::default(), }; let opts = |tile: u32| DngWriteOptions { compression: DngCompression::Deflate { tile, half: false }, ..DngWriteOptions::default() }; let hostile = write_dng(&raw, &opts(u32::MAX)).expect("the clamped tile writes"); diff --git a/crates/raw/src/erf.rs b/crates/raw/src/erf.rs index 40190ca207..fcdfa43cd0 100644 --- a/crates/raw/src/erf.rs +++ b/crates/raw/src/erf.rs @@ -128,6 +128,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Result, } +/// Bounded diagnostics for decisions actually made by a raw decoder. An absent optional tag +/// does not itself set a notice; hosts can translate these flags into their own warning text +/// without inferring a fallback from missing metadata or retaining source-controlled strings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RawNotices { + /// Explicit default-crop metadata needed correction or a fallback to the active area. + pub default_crop_adjusted: bool, + /// A source profile gain table could not be used and was omitted from the decoded image. + pub gain_table_omitted: bool, + /// The CFA layout was selected by a decoder fallback instead of usable source metadata. + pub assumed_cfa: bool, +} + /// A decoded raw image. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RawImage { @@ -1041,6 +1055,9 @@ pub struct RawImage { /// measured levels are placeholders. #[serde(default)] pub level_sources: LevelSources, + /// Fixed-size decoder decisions, separate from ordinary missing optional metadata. + #[serde(default)] + pub notices: RawNotices, } impl RawImage { @@ -1173,3 +1190,21 @@ mod checked_arithmetic_tests { assert_eq!(Orientation::from_exif(9), Orientation::Normal); } } + +#[cfg(test)] +mod raw_notices_tests { + use super::*; + + #[test] + fn missing_notices_default_to_no_claims_and_explicit_flags_are_independent() { + type Error = serde::de::value::Error; + let empty = serde::de::value::MapDeserializer::<_, Error>::new(std::iter::empty::<(&str, bool)>()); + assert_eq!(RawNotices::deserialize(empty).unwrap(), RawNotices::default()); + let one = serde::de::value::MapDeserializer::<_, Error>::new([("assumed_cfa", true)].into_iter()); + let notices = RawNotices::deserialize(one).unwrap(); + let copied = notices; + assert_eq!(notices, copied); + assert_eq!(notices, RawNotices { assumed_cfa: true, default_crop_adjusted: false, gain_table_omitted: false }); + assert!(!std::mem::needs_drop::(), "decoder notices own no allocated strings"); + } +} diff --git a/crates/raw/src/mef.rs b/crates/raw/src/mef.rs index 5cd1fb705b..36ba18e0f6 100644 --- a/crates/raw/src/mef.rs +++ b/crates/raw/src/mef.rs @@ -128,6 +128,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Result Result BlackLevel { - repeat_rows: 2, - repeat_cols: 2, - values: [a, b, c, d].iter().map(|v| (**v * black_scale) as f32).collect(), - ..Default::default() + let (black, black_source) = match mn.as_ref().and_then(|m| m.ifd.f64s(BLACK_LEVEL)).as_deref() { + Some([a, b, c, d]) if [a, b, c, d].iter().all(|v| **v < 16384.0) => ( + BlackLevel { + repeat_rows: 2, + repeat_cols: 2, + values: [a, b, c, d].iter().map(|v| (**v * black_scale) as f32).collect(), + ..Default::default() + }, + crate::LevelSource::Metadata, + ), + _ => match nrw_black(mn.as_ref(), bits) { + Some(value) => (BlackLevel::uniform(value), crate::LevelSource::Metadata), + None => { + let (value, source) = be16_black(&info, bytes.len() as u64, mn.as_ref(), samples); + (BlackLevel::uniform(value), source) + } }, - _ => BlackLevel::uniform(nrw_black(mn.as_ref(), bits).unwrap_or_else(|| be16_black(&info, bytes.len() as u64, mn.as_ref(), samples))), }; let wb = mn .as_ref() .and_then(|m| m.ifd.f64s(WB_RB_LEVELS)) .filter(|v| v.len() >= 2 && v[0] > 0.1 && v[1] > 0.1 && v[0] < 10.0 && v[1] < 10.0) .map(|v| [v[0] as f32, 1.0, v[1] as f32]); - let cfa = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { + let (cfa, assumed_cfa) = match (raw.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), raw.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { - Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } + (Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 }, false) } - _ => Cfa::bayer_static("RGGB"), + _ => (Cfa::bayer_static("RGGB"), true), }; let model = ifd0.string(t::MODEL).unwrap_or_default(); let body = measured_body(&model, w, h, bits); let active_w = trailing_masked_columns(samples, w, bits); // the white level is measured from the whole image (or known for a measured body); the probe (no samples in its // result) takes the nominal one - let white = match (body.and_then(|b| b.white), mode) { - (Some(white), _) => white, - (None, Mode::Full) => white_from_data(samples, bits), - (None, Mode::Header) => ((1u32 << bits.clamp(1, 16)) - 1) as f32, + let (white, white_source) = match (body.and_then(|b| b.white), mode) { + (Some(white), _) => (white, crate::LevelSource::Fallback), + (None, Mode::Full) => white_from_data_sourced(samples, bits), + (None, Mode::Header) => (((1u32 << bits.clamp(1, 16)) - 1) as f32, crate::LevelSource::Fallback), }; let crop = match body { Some(&MeasuredBody { crop: (x, y, cw, ch), .. }) if x + cw <= active_w && y + ch <= h => Rect::new(x, y, cw, ch), @@ -329,7 +338,8 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Opt } let stride = strip / h; let tight = w.checked_mul(bits as usize)?.div_ceil(8); - let tight = if bits == 12 && w.is_multiple_of(2) || bits == 14 && w.is_multiple_of(4) { tight } else { return None }; + // Unmarked data must still match a measured complete-group layout: do not guess a packing for compressed + // data. An explicit packed maker mode permits a final partial group, byte-aligned independently on each row. + if !stated && !(bits == 12 && w.is_multiple_of(2) || bits == 14 && w.is_multiple_of(4)) { + return None; + } let padded = tight.checked_next_multiple_of(16)?; let lsb_ok = match bits { 12 => stride == tight || stride == padded, @@ -436,14 +450,14 @@ fn be16_layout(w: usize, h: usize, bits: u32, strip: u64) -> Option, samples: &[u16]) -> f32 { +fn be16_black(info: &ImageInfo, file_len: u64, mn: Option<&makernote::MakerNote>, samples: &[u16]) -> (f32, crate::LevelSource) { let has_table = mn.is_some_and(|m| m.ifd.bytes(LINEARIZATION_TABLE).is_some()); let single = matches!(info.chunks(file_len).as_slice(), [c] if be16_layout(info.width as usize, info.height as usize, info.bits() as u32, c.len).is_some()); if info.compression != t::compression::NIKON || has_table || info.samples_per_pixel != 1 || !single { - return 0.0; + return (0.0, crate::LevelSource::Fallback); } let darkest = samples.iter().copied().min().unwrap_or(0); - BE16_BLACK.min(f32::from(darkest)) + (BE16_BLACK.min(f32::from(darkest)), crate::LevelSource::Inferred) } /// Unpack a [`PackedLayout`] strip into `w * h` samples. Short input leaves the missing samples zero. @@ -524,7 +538,7 @@ fn compressed(bytes: &[u8], info: &ImageInfo, mn: Option<&makernote::MakerNote>, } /// A "compressed" strip of packed samples: the strip size must match a measured layout exactly. `stated` is set -/// when the maker note names the packed mode, which also allows 14-bit rows without padding. +/// when the maker note names the packed mode, which also allows partial groups and 14-bit rows without padding. fn packed(bytes: &[u8], info: &ImageInfo, rows: usize, stated: bool, limits: &Limits) -> Result { let (w, h) = (info.width as usize, info.height as usize); let bits = info.bits() as u32; @@ -663,6 +677,7 @@ fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: craft_tiff::ima cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: Default::default(), }; img.validate_for(mode)?; Ok(img) @@ -725,6 +740,21 @@ mod tests { TiffWriter::new(order, false).write(&[ifd0]).unwrap() } + #[test] + fn level_provenance_distinguishes_missing_black_from_recorded_black() { + let strip: Vec = [1000u16; 16].into_iter().flat_map(u16::to_be_bytes).collect(); + let fallback = nef(1, 12, vec![strip.clone()], 4, 4, 4); + let mut note = IfdBuilder::new(); + note.set(BLACK_LEVEL, Value::Short(vec![400; 4])); + let recorded = nef_with_note(1, 12, vec![strip], 4, 4, 4, Some(note)); + for mode in [Mode::Header, Mode::Full] { + let missing = decode(&fallback, mode, &Limits::default()).unwrap(); + assert_eq!((missing.black.mean(), missing.level_sources.black), (0.0, crate::LevelSource::Fallback)); + let stated = decode(&recorded, mode, &Limits::default()).unwrap(); + assert_eq!((stated.black.mean(), stated.level_sources.black), (100.0, crate::LevelSource::Metadata)); + } + } + /// A small uncompressed NEF with a real NikonNEFInfo TIFF block, without binary fixtures. fn nikon_distortion_file(model: &str, mode: u8) -> Vec { use crate::nef_lens::tests::{distortion_block, nef_info_blob, offset_block}; @@ -1527,4 +1557,95 @@ mod tests { } } } + + mod partial_row_tests { + use super::*; + + // Independent wire oracle: place each sample bit directly, leaving nonzero tail bits and padding. + fn image(data: &[u16], w: usize, bits: u32, padded: bool) -> Vec { + let tight = (w * bits as usize).div_ceil(8); + let stride = if padded { tight.next_multiple_of(16) } else { tight }; + let mut bytes = vec![0xA5; stride * (data.len() / w)]; + for (i, &sample) in data.iter().enumerate() { + for bit in 0..bits as usize { + let at = (i % w) * bits as usize + bit; + let byte = &mut bytes[(i / w) * stride + at / 8]; + *byte = (*byte & !(1 << (at % 8))) | (((sample >> bit) as u8 & 1) << (at % 8)); + } + } + bytes + } + + fn note(order: ByteOrder, modern: bool, mode: u16) -> IfdBuilder { + let mut n = IfdBuilder::new(); + if modern { + let mut record = b"01000400\0\0".to_vec(); + record.extend(if order == ByteOrder::Big { mode.to_be_bytes() } else { mode.to_le_bytes() }); + n.set(NEF_COMPRESSION_RECORD, Value::Undefined(record)); + } else { + n.set(NEF_COMPRESSION, Value::Short(vec![mode])); + } + n + } + + #[test] + fn declared_packed_partial_rows_preserve_every_sample() { + let h = 5; + for (bits, mode) in [(12u32, 6), (14, 10)] { + for w in [1, 3, 5, 22, 23] { + let data = samples(w * h, bits); + for padded in [false, true] { + let wire = image(&data, w, bits, padded); + if w == 22 && bits == 14 { + assert_eq!(wire.len() / h, if padded { 48 } else { 39 }); + } + for order in [ByteOrder::Big, ByteOrder::Little] { + for modern in [false, true] { + let file = nef_in( + order, + 34713, + bits as u16, + vec![wire.clone()], + w as u32, + h as u32, + h as u32, + Some(note(order, modern, mode)), + ); + let raw = crate::decode(&file).unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp), (w, h, 1)); + assert!(!raw.notices.assumed_cfa, "valid CFA tag is retained"); + let RawData::U16(got) = raw.data else { panic!("integer samples") }; + assert_eq!(got, data, "{bits}-bit width {w}, padded {padded}, {order:?}, modern {modern}"); + } + } + } + } + } + } + + #[test] + fn partial_rows_keep_mode_depth_and_strip_guards() { + let (w, h) = (22, 5); + let data = samples(w * h, 14); + for padded in [false, true] { + let wire = image(&data, w, 14, padded); + let file = |bytes, mode: Option| { + nef_with_note(34713, 14, vec![bytes], w as u32, h as u32, h as u32, mode.map(|m| note(ByteOrder::Big, false, m))) + }; + for mode in [None, Some(0), Some(6), Some(13), Some(14)] { + assert!(matches!(crate::decode(&file(wire.clone(), mode)), Err(RawError::Unsupported(_))), "mode {mode:?}"); + } + let good = file(wire.clone(), Some(10)); + assert!(crate::decode(&good).is_ok()); + let short = truncated_tail_strip(good, wire.len() - 1); + assert!(matches!(crate::decode(&short), Err(RawError::Corrupt(_)))); + for len in [wire.len() - 1, wire.len() + 1] { + assert!(matches!(crate::decode(&file(vec![0; len], Some(10))), Err(RawError::Unsupported(_)))); + } + } + for (w, h, bits) in [(0, 5, 14), (22, 0, 14), (22, 5, 13), (usize::MAX, 5, 14)] { + assert!(packed_layout(w, h, bits, u64::MAX, true).is_none()); + } + } + } } diff --git a/crates/raw/src/orf.rs b/crates/raw/src/orf.rs index ebfa28eb21..566e56fed4 100644 --- a/crates/raw/src/orf.rs +++ b/crates/raw/src/orf.rs @@ -207,6 +207,19 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; + // A partial TIFF directory is damage, not evidence of an unsupported compressed layout. + // Do not infer packing from an absent strip table or from clipped sensor bytes. + if info.compression == 1 + && (info.offsets.is_empty() + || info.offsets.len() != info.byte_counts.len() + || info + .offsets + .iter() + .zip(&info.byte_counts) + .any(|(&at, &len)| len == 0 || at.checked_add(len).is_none_or(|end| end > bytes.len() as u64))) + { + return Err(RawError::Corrupt("ORF strip table is missing or outside file".into())); + } let chunks = info.chunks(bytes.len() as u64); let total = chunks.iter().fold(0u64, |a, c| a.saturating_add(c.len)); let stated = cfa_from_exif(&tiff); @@ -302,6 +315,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Rect::new(0, 0, w, h), }; + let assumed_cfa = stated.is_none(); let cfa = stated.unwrap_or_else(|| cfa_from_data(samples, w, active)); let (black, black_source) = match ip.as_ref().and_then(|i| i.f64s(BLACK)).as_deref() { Some(v @ [_, _, _, _]) => { @@ -348,6 +362,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result = strip.as_chunks::<2>().0.iter().map(|word| u16::from_le_bytes(*word)).collect(); + for (tag, assumed, pattern) in [ + (None, true, "RGGB"), + (Some(&[2, 0, 2, 0, 0, 1][..]), true, "RGGB"), + (Some(&[2, 0, 2, 0, 0, 1, 1, 3][..]), true, "RGGB"), + (Some(BGGR), false, "BGGR"), + (Some(GRBG), false, "GRBG"), + ] { + let bytes = orf_with(w as u32, h as u32, 16, strip.clone(), tag); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!(image.cfa, Some(Cfa::bayer_static(pattern))); + assert_eq!(image.data, RawData::U16(expected.clone()), "word16 samples remain unchanged"); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }); + } + } + } + #[test] fn packed_12_bit_probe_agrees_with_decode() { let (w, h) = (16usize, 4usize); diff --git a/crates/raw/src/pef.rs b/crates/raw/src/pef.rs index a33750db5a..9dc3a89f1e 100644 --- a/crates/raw/src/pef.rs +++ b/crates/raw/src/pef.rs @@ -194,6 +194,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result r, None => dark_trimmed(samples, w, hgt, black_point.as_deref().map(|v| v.iter().sum::() / 4.0), white), }; + let mut assumed_cfa = false; let cfa = match (ifd0.u64s(t::CFA_REPEAT_PATTERN_DIM).as_deref(), ifd0.bytes(t::CFA_PATTERN_EP)) { (Some([2, 2]), Some(p)) if p.len() == 4 && p.iter().all(|&c| c <= 2) => { Cfa { width: 2, height: 2, pattern: p.to_vec(), origin_x: 0, origin_y: 0 } @@ -202,7 +203,10 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result cfa_from_exif(&tiff).unwrap_or_else(|| Cfa::bayer_static("BGGR")), + _ => cfa_from_exif(&tiff).unwrap_or_else(|| { + assumed_cfa = true; + Cfa::bayer_static("BGGR") + }), }; let black = match black_point.as_deref() { Some(v @ [_, _, _, _]) => { @@ -240,6 +244,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result = (0..16).map(|i| 100 + i * 7).collect(); + let valid_exif = &[2, 0, 2, 0, 1, 0, 2, 1][..]; + let invalid_exif = &[2, 0, 2, 0, 1, 0][..]; + for (primary, exif, assumed, pattern) in [ + (None, None, true, "BGGR"), + (Some([0, 1, 1, 3]), None, true, "BGGR"), + (None, Some(invalid_exif), true, "BGGR"), + (Some([0, 1, 1, 3]), Some(invalid_exif), true, "BGGR"), + (Some([0, 1, 1, 3]), Some(valid_exif), false, "GRBG"), + (None, Some(valid_exif), false, "GRBG"), + (Some([0, 1, 1, 2]), None, false, "RGGB"), + (Some([0, 1, 1, 2]), Some(valid_exif), false, "RGGB"), + ] { + let mut raw = IfdBuilder::new(); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![4])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![4])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![32803])); + raw.set(t::MAKE, Value::Ascii("PENTAX Corporation".into())); + if let Some(pattern) = primary { + raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + raw.set(t::CFA_PATTERN_EP, Value::Byte(pattern.to_vec())); + } + if let Some(pattern) = exif { + raw.set_child(t::EXIF_IFD, IfdBuilder::new().with(crate::EXIF_CFA_PATTERN, Value::Undefined(pattern.to_vec()))); + } + raw.set_image(ImageData::Strips { rows_per_strip: 4, strips: vec![expected.iter().flat_map(|value| value.to_be_bytes()).collect()] }); + let bytes = TiffWriter::new(ByteOrder::Big, false).write(&[raw]).unwrap(); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!(image.cfa, Some(Cfa::bayer_static(pattern))); + assert_eq!(image.data, RawData::U16(expected.clone())); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }); + } + } + } + /// A `w x h` big-endian 14-bit PEF of plain 16-bit words without area tags, whose maker note has only a /// BlackPoint of `black`, with `px(x, y)` as the samples. fn pef_with_black_point(w: usize, h: usize, black: u16, px: impl Fn(usize, usize) -> u16) -> Vec { diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 48fa4e4b14..bd66f58c89 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -643,9 +643,15 @@ fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> { /// A CR3's full-size JPEG track, when it holds a DCT JPEG. #[cfg(feature = "cr3")] fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> { - let full = craft_metadata::cr3::parse_cr3(bytes) - .and_then(|c| c.tracks.iter().find(|t| t.kind == craft_metadata::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data)); - full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j)) + let cr3 = craft_metadata::cr3::parse_cr3(bytes)?; + // An unusable preview track must not hide a later usable one. Share the marker budget + // across candidates so overlapping hostile track ranges cannot cause quadratic walks. + let mut work = CR3_MAX_WALK; + cr3.tracks.iter().filter(|t| t.kind == craft_metadata::cr3::Cr3TrackKind::Jpeg).find_map(|t| { + let (at, len) = t.data?; + let jpeg = bytes.get(at..at.checked_add(len)?)?; + first_frame_within(jpeg, &mut work).filter(|(m, _)| matches!(m, 0xc0..=0xc2)).map(|_| jpeg) + }) } /// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index 19018d9b1c..e04c8574f7 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -582,7 +582,19 @@ fn cr3_prefers_the_full_size_jpeg_track() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(&big); @@ -592,6 +604,48 @@ fn cr3_prefers_the_full_size_jpeg_track() { assert_eq!(embedded_preview(&file).unwrap(), small); } +#[cfg(feature = "cr3")] +#[test] +fn cr3_skips_bad_preview_tracks_but_never_uses_sensor_tracks_as_jpeg() { + let bx = |kind: &[u8; 4], body: &[u8]| -> Vec { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() }; + let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat()); + let track = |jpeg: bool, at: u64, len: u32| { + let mut entry = vec![0u8; 82]; + if jpeg { + entry.extend(bx(b"JPEG", &[0; 4])); + } + let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &entry)].concat()); + let stsz = full(b"stsz", &[len.to_be_bytes(), 1u32.to_be_bytes()].concat()); + let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); + bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>()), stsz, co64].concat(), + ), + ), + ), + ) + }; + let good = fake_jpeg(100); + for first in [track(true, u64::MAX, 32), track(true, 4096, 32)] { + let mut bytes = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(bx(b"moov", &[first, track(true, 4128, good.len() as u32)].concat())); + bytes.resize(4128, 0); + bytes.extend(&good); + assert_eq!(embedded_preview(&bytes).as_deref(), Some(good.as_slice())); + } + let mut bytes = bx(b"ftyp", b"crx \0\0\0\x01crx isom"); + bytes.extend(bx(b"moov", &track(false, 4096, good.len() as u32))); + bytes.resize(4096, 0); + bytes.extend(&good); + assert_eq!(embedded_preview(&bytes), None, "a sensor sample is not a rendered preview even if its bytes look like JPEG"); +} + #[cfg(feature = "cr3")] /// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`. fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec { @@ -608,7 +662,19 @@ fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(big); @@ -656,7 +722,19 @@ fn the_smallest_preview_covering_the_size_is_chosen() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); file.resize(at as usize, 0); file.extend_from_slice(&big); @@ -769,7 +847,19 @@ fn a_cr3_with_two_prvw_boxes_offers_both() { let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat()); let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat()); let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat()); - let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat())))); + let trak = bx( + b"trak", + &bx( + b"mdia", + &bx( + b"minf", + &bx( + b"stbl", + &[stsd, full(b"stsc", &[1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::>()), stsz, co64].concat(), + ), + ), + ), + ); file.extend(bx(b"moov", &trak)); // (the track in the media data, as a camera writes it, after a `free` box up to it) let pad = at as usize - 16 - file.len(); diff --git a/crates/raw/src/raf.rs b/crates/raw/src/raf.rs index f75fa160b8..a3e407454a 100644 --- a/crates/raw/src/raf.rs +++ b/crates/raw/src/raf.rs @@ -18,7 +18,10 @@ //! - CFA: the X-Trans layout record (36 bytes, 0 = R, 1 = G, 2 = B) is stored in reverse order and, reversed, //! is anchored at raw pixel (0, 0) — verified on X-Trans I and III samples by minimising the difference //! between horizontally / vertically adjacent "green" samples over all 72 orientations/phases, and by colour -//! renders. Bayer bodies (X-A series) use RGGB at (0, 0), verified by colour renders. +//! renders. Bayer FujiLayout (`0x0130`) gives the reversed 2×2 pattern in its low two bits +//! (0 = R, 1/3 = G, 2 = B); absent layout records retain the assumed RGGB fallback. +//! - RawExposureBias (`0x9650`) is a signed big-endian 16-bit fraction; its negative is the +//! baseline exposure used to restore the camera's dynamic-range exposure reduction. //! - Striped predictive compression is decoded by `rafc`; see `docs/raf-compression.md`. use crate::shared::white_from_data_sourced; @@ -87,7 +90,7 @@ fn pair(h: &Header, tag: u16) -> Option<(usize, usize)> { pub(crate) fn raw_ifd(raw: &[u8]) -> Result { let tiff = Tiff::parse(raw).map_err(|_| RawError::Unsupported("RAF without a raw IFD (older FinePix layout)".into()))?; let off = tiff.ifds.first().and_then(|i| i.u64(0xf000)).ok_or_else(|| RawError::Unsupported("RAF without a raw IFD".into()))?; - let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?; + let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, tiff.order, 0, false, &Default::default())?; Ok(ifd) } @@ -122,14 +125,42 @@ fn camera_name(b: &[u8]) -> String { String::from_utf8_lossy(name.get(..end).unwrap_or_default()).trim().to_string() } -/// The CFA: X-Trans from the (reversed) layout record, else RGGB. -fn cfa(h: &Header) -> Cfa { - match record(h, XTRANS_LAYOUT) { - Some(l) if l.len() == 36 && l.iter().all(|&c| c <= 2) => { - Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect(), origin_x: 0, origin_y: 0 } +/// Layout records are reversed and anchored at sensor (0, 0). FujiLayout's low +/// two bits encode Bayer colour; both 1 and 3 denote green. +fn cfa(h: &Header) -> Result { + if let Some(l) = record(h, XTRANS_LAYOUT) { + if l.len() != 36 || l.iter().any(|&c| c > 2) { + return Err(RawError::Unsupported("Fujifilm RAF with an unknown X-Trans layout".into())); } - _ => Cfa::bayer_static("RGGB"), + return Ok(Cfa { width: 6, height: 6, pattern: l.iter().rev().copied().collect(), origin_x: 0, origin_y: 0 }); } + let Some(l) = record(h, 0x0130) else { return Ok(Cfa::bayer_static("RGGB")) }; + let cfa = Cfa { width: 2, height: 2, pattern: l.iter().rev().map(|&c| if c & 3 == 3 { 1 } else { c & 3 }).collect(), origin_x: 0, origin_y: 0 }; + // Colour counts alone also accept adjacent green sites; the two greens + // must occupy opposite corners of the 2x2 Bayer repeat. + if l.len() != 4 || !matches!(cfa.pattern.as_slice(), [0, 1, 1, 2] | [2, 1, 1, 0] | [1, 0, 2, 1] | [1, 2, 0, 1]) { + return Err(RawError::Unsupported("Fujifilm RAF with an unknown Bayer layout".into())); + } + Ok(cfa) +} + +/// Fuji RawExposureBias is a signed big-endian 16-bit fraction, undone like +/// DNG BaselineExposure. Invalid or implausible metadata does not alter exposure. +fn baseline_exposure(h: &Header) -> f64 { + record(h, 0x9650) + .and_then(|d| { + let num = i16::from_be_bytes(d.get(..2)?.try_into().ok()?); + let den = i16::from_be_bytes(d.get(2..4)?.try_into().ok()?); + (den != 0).then(|| -f64::from(num) / f64::from(den)) + }) + .filter(|v| v.is_finite() && v.abs() <= 8.0) + .unwrap_or(0.0) +} + +/// The codec fixes the green-site geometry; exchanging the two non-green +/// planes only exchanges their colour labels, so RGGB and BGGR are both valid. +fn compressed_layout_supported(cfa: &Cfa) -> bool { + *cfa == Cfa::xtrans() || *cfa == Cfa::bayer_static("RGGB") || *cfa == Cfa::bayer_static("BGGR") } /// Unpack one row of `bits`-bit samples in Fujifilm's packing. `words32`: the raw IFD's `0xf006` flag is set, the @@ -137,7 +168,7 @@ fn cfa(h: &Header) -> Cfa { /// LSB-first bit stream, or (other depths) the same 32-bit words. pub(crate) fn unpack_row(src: &[u8], bits: u32, words32: bool, out: &mut [u16]) { match bits { - 16 => out.iter_mut().zip(src.as_chunks::<2>().0).for_each(|(o, c)| *o = u16::from_le_bytes([c[0], c[1]])), + 16 if !words32 => out.iter_mut().zip(src.as_chunks::<2>().0).for_each(|(o, c)| *o = u16::from_le_bytes([c[0], c[1]])), 12 if !words32 => unpack_lsb(src, 12, out), _ => unpack_words32_msb(src, ByteOrder::Little, bits, out), } @@ -171,7 +202,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result false, @@ -180,8 +211,13 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Result= (n as u64) * 2 { 16 } else { bits }; - let packed_row = w.checked_mul(store as usize).map(|n| n.div_ceil(8)).ok_or(RawError::Limit("RAF row too large"))?; + // An explicit packed-word flag wins over the size heuristic: padding in short + // packed rows can occupy as many bytes as unpacked 16-bit samples. + // Unflagged samples may use 16-bit words (e.g. 14-bit X-T20). + let store = if !words32 && len as u64 >= (n as u64) * 2 { 16 } else { bits }; + let row_bits = w.checked_mul(store as usize).ok_or(RawError::Limit("RAF row too large"))?; + // Word-packed rows store the high bits in the last little-endian word's final bytes. + // Reading only ceil(bits / 8) bytes would lose those samples, not just padding. + let packed_row = if words32 || (store != 16 && store != 12) { + row_bits.div_ceil(32).checked_mul(4).ok_or(RawError::Limit("RAF row too large"))? + } else { + row_bits.div_ceil(8) + }; let stride = match get(0xf005)?.unwrap_or(0) { 0 => packed_row, words => words.checked_mul(4).ok_or(RawError::Limit("RAF stride too large"))?.max(packed_row), @@ -206,7 +251,11 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Result Result = (0..w * h).map(|i| ((i * 977 + 101) % (1 << bits)) as u16).collect(); + // Independently place each sample bit into whole little-endian 32-bit row words. + let strip: Vec = px + .chunks(w as usize) + .flat_map(|row| { + let mut words = vec![0u32; (row.len() * bits as usize).div_ceil(32)]; + for (i, &sample) in row.iter().enumerate() { + for bit in 0..bits as usize { + let at = i * bits as usize + bit; + words[at / 32] |= u32::from((sample >> (bits as usize - 1 - bit)) & 1) << (31 - at % 32); + } + } + words.into_iter().flat_map(u32::to_le_bytes).collect::>() + }) + .collect(); + let bytes = raf_flagged(w, h, bits, strip, None, &[], flag); + assert_eq!(crate::decode(&bytes).unwrap().data, RawData::U16(px)); + assert!(crate::decode(&bytes[..bytes.len() - 1]).is_err()); + } + } + + #[test] + fn big_endian_words_and_bayer_layout_preserve_exact_sensor_values() { + use craft_tiff::{IfdBuilder, TiffWriter, Value}; + let (w, h) = (6u32, 4u32); + let px: Vec = (0..w * h).map(|i| (i * 977 + 123) as u16).collect(); + for order in [ByteOrder::Little, ByteOrder::Big] { + let build = |at| { + let mut sensor = IfdBuilder::new(); + for (tag, value) in [(0xf001, w), (0xf002, h), (0xf003, 16), (0xf007, at), (0xf008, w * h * 2)] { + sensor.set(tag, Value::Long(vec![value])); + } + let mut root = IfdBuilder::new(); + root.set_child(0xf000, sensor); + TiffWriter::new(order, false).write(&[root]).unwrap() + }; + let mut raw = build(build(0).len() as u32); + raw.extend(px.iter().flat_map(|v| if order == ByteOrder::Big { v.to_be_bytes() } else { v.to_le_bytes() })); + let mut bytes = raf(w, h, 16, vec![0; (w * h * 2) as usize], None, &[]); + let raw_at = be32(&bytes, 100).unwrap(); + bytes.truncate(raw_at); + bytes[104..108].copy_from_slice(&(raw.len() as u32).to_be_bytes()); + bytes.extend(raw); + // A four-site Bayer record is reversed in storage, just like the X-Trans record. + let dir_at = be32(&bytes, 92).unwrap(); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + records.extend_from_slice(&[0x01, 0x30, 0, 4, 0x08, 0x09, 0x0b, 0x0a]); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + let image = crate::decode(&bytes).unwrap(); + assert_eq!(image.data, RawData::U16(px.clone())); + assert_eq!(image.cfa.unwrap().name(), "BGGR"); + } + } + + #[test] + fn raw_exposure_bias_is_preserved_as_baseline_exposure_and_invalid_values_are_ignored() { + for (num, den, expected) in [(-72i16, 100i16, 0.72f64), (1, 0, 0.0), (32767, 1, 0.0)] { + let mut bytes = raf(6, 4, 16, pack(&[1000; 24], 16), None, &[]); + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + records.extend_from_slice(&[0x96, 0x50, 0, 4]); + records.extend(num.to_be_bytes()); + records.extend(den.to_be_bytes()); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + for mode in [Mode::Header, Mode::Full] { + assert!((decode(&bytes, mode, &Limits::default()).unwrap().color.baseline_exposure - expected).abs() < 1e-9); + } + } + } + + #[test] + fn invalid_declared_cfa_layouts_are_not_silently_replaced() { + for (tag, data) in [(0x0130, vec![8, 8, 10, 10]), (0x0130, vec![1, 2, 1, 0]), (0x0131, vec![3; 36])] { + let header = Header { jpeg: None, records: vec![(tag, data.as_slice())], raw: None }; + assert!(matches!(cfa(&header), Err(RawError::Unsupported(_)))); + } + } + + fn with_bayer_record(mut bytes: Vec, pattern: [u8; 4]) -> Vec { + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let count = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&count.to_be_bytes()); + records.extend_from_slice(&[0x01, 0x30, 0, 4]); + records.extend_from_slice(&pattern); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + bytes + } + + #[test] + fn non_bayer_geometry_is_rejected_in_header_and_full_modes() { + // Reversal gives RGBG: correct colour counts, but both greens in one column. + let bytes = with_bayer_record(raf(6, 4, 16, pack(&[1000; 24], 16), None, &[]), [1, 2, 1, 0]); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("Bayer layout"))); + } + } + + #[test] + fn all_four_bayer_geometries_preserve_the_stored_samples() { + let pixels: Vec = (0..24).map(|i| 123 + i * 977).collect(); + for (stored, expected) in [([2, 1, 1, 0], "RGGB"), ([0, 1, 1, 2], "BGGR"), ([1, 2, 0, 1], "GRBG"), ([1, 0, 2, 1], "GBRG")] { + let bytes = with_bayer_record(raf(6, 4, 16, pack(&pixels, 16), None, &[]), stored); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (6, 4)); + assert_eq!(image.cfa.as_ref().unwrap().name(), expected); + assert_eq!(image.data, RawData::U16(if mode == Mode::Full { pixels.clone() } else { Vec::new() })); + } + } + } + + #[test] + fn compressed_bayer_requires_the_layout_assumed_by_its_predictor() { + let strip = b"IS\x01\x00\x0e\0\x12\x06\0\x03\x0c\x03\0\x02\0\x03".to_vec(); + let mut bytes = raf(780, 18, 14, strip, None, &[]); + let (dir_at, raw_at) = (be32(&bytes, 92).unwrap(), be32(&bytes, 100).unwrap()); + let mut records = bytes[dir_at..raw_at].to_vec(); + let n = u32::from_be_bytes(records[..4].try_into().unwrap()) + 1; + records[..4].copy_from_slice(&n.to_be_bytes()); + // Reversed GRBG: a valid Bayer pattern, but not the RGGB order of this codec. + records.extend_from_slice(&[0x01, 0x30, 0, 4, 0x0b, 0x0a, 0x08, 0x09]); + bytes.splice(dir_at..raw_at, records.clone()); + bytes[96..100].copy_from_slice(&(records.len() as u32).to_be_bytes()); + bytes[100..104].copy_from_slice(&((raw_at + 8) as u32).to_be_bytes()); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&bytes, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("layout"))); + } + } + + #[test] + fn compressed_layout_accepts_both_red_blue_orders_without_accepting_wrong_green_phase() { + for name in ["RGGB", "BGGR"] { + assert!(compressed_layout_supported(&Cfa::bayer_static(name)), "{name}"); + } + for name in ["GRBG", "GBRG"] { + assert!(!compressed_layout_supported(&Cfa::bayer_static(name)), "{name}"); + } + let mut other = Cfa::xtrans(); + assert!(compressed_layout_supported(&other)); + other.pattern.swap(0, 2); + assert!(!compressed_layout_supported(&other)); + } + + #[test] + fn unknown_compressed_signature_is_unsupported_but_identified_stream_damage_is_corrupt() { + let header = b"IS\x01\x00\x0e\0\x12\x06\0\x03\x0c\x03\0\x02\0\x03".to_vec(); + let known = raf(780, 18, 14, header, None, &[]); + let raw_at = be32(&known, 100).unwrap(); + let strip_at = raw_at + raw_ifd(&known[raw_at..]).unwrap().u64(0xf007).unwrap() as usize; + let mut unknown = known.clone(); + unknown[strip_at..strip_at + 2].copy_from_slice(b"XX"); + for mode in [Mode::Header, Mode::Full] { + assert!(matches!(decode(&unknown, mode, &Limits::default()), Err(RawError::Unsupported(why)) if why.contains("signature"))); + assert!( + matches!(decode(&known, mode, &Limits::default()), Err(RawError::Corrupt(_))), + "identified but truncated IS stream must remain corrupt" + ); + } + } + /// Raw IFD flag `0xf006` selects the 32-bit-word packing at 12 bits; without it 12 bits are an LSB-first stream. #[test] fn flag_selects_word_packed_12_bit() { diff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rs index 9984ed9879..1dc1a885e2 100644 --- a/crates/raw/src/rw2.rs +++ b/crates/raw/src/rw2.rs @@ -615,11 +615,18 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Rect::new(0, 0, active.width, active.height), }; - if !data.is_empty() { + // Packed formats 2/5/7 are lossless sample containers: zero is an ordinary + // code, not evidence of a mapped-out photosite. The documented zero repair + // applies to the predictive format 4 and older word containers only. + if !data.is_empty() && matches!(encoding, Encoding::Words | Encoding::Blocks { kind: Block::Format4, .. }) { fill_defects(&mut data, w, active); } - let cfa = cfa(ifd0.u16(CFA_PATTERN).unwrap_or(1)); + let cfa_code = ifd0.u16(CFA_PATTERN); + // RGGB is still usable when metadata is absent or unknown, but callers + // must be able to distinguish that fallback from a recorded sensor phase. + let assumed_cfa = !matches!(cfa_code, Some(1..=4)); + let cfa = cfa(cfa_code.unwrap_or(1)); let read = BLACK_RGB.map(|tag| ifd0.f64(tag).filter(|v| v.is_finite() && *v >= 0.0)); let tags = read.map(|v| v.unwrap_or(0.0) as f32); let offset = match encoding { @@ -671,6 +678,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result = (0..72).map(|i| 17 + i * 113).collect(); + let payload = pack(&pixels, 14); + for (code, expected, assumed) in [ + (None, "RGGB", true), + (Some(0), "RGGB", true), + (Some(5), "RGGB", true), + (Some(u16::MAX), "RGGB", true), + (Some(1), "RGGB", false), + (Some(2), "GRBG", false), + (Some(3), "GBRG", false), + (Some(4), "BGGR", false), + ] { + let mut tags = vec![short(BITS, 14), short(RAW_FORMAT, 7)]; + if let Some(code) = code { + tags.push(short(CFA_PATTERN, code)); + } + let bytes = file(18, 4, &tags, &payload, &|off| vec![(RAW_OFFSET, Value::Long(vec![off]))]); + for mode in [Mode::Header, Mode::Full] { + let image = decode(&bytes, mode, &Limits::default()).unwrap(); + assert_eq!((image.width, image.height), (18, 4)); + assert_eq!(image.cfa.as_ref().unwrap().name(), expected, "code {code:?}"); + assert_eq!(image.notices, crate::RawNotices { assumed_cfa: assumed, ..Default::default() }, "code {code:?}, {mode:?}"); + assert_eq!(samples(&image), if mode == Mode::Full { pixels.as_slice() } else { &[] }); + } + } + } + + #[test] + fn lossless_packed_formats_preserve_zero_codes_inside_the_active_area() { + let (w, h) = (90usize, 12usize); + for (format, bits, rotated) in [(5u16, 12u32, true), (5, 14, true), (7, 14, false), (2, 12, false)] { + let mut px = vec![1000u16; w * h]; + px[5 * w + 20] = 0; + let payload = pack(&px, bits); + let bytes = rw2(w as u16, h as u16, bits as u16, format, 100, &if rotated { rotate(payload) } else { payload }); + assert_eq!(samples(&crate::decode(&bytes).unwrap()), px, "format {format}/{bits}"); + } + } + #[test] fn levels_crop_defects_and_cfa() { let (w, h) = (90usize, 60usize); let mut px: Vec = (0..w * h).map(|i| 300 + (i % 7) as u16).collect(); - // a saturation plateau sets the white level; zeros inside the active area are defects + // A saturation plateau sets the white level. In the older word container, + // isolated zeros inside the active area are documented mapped-out defects. px[10 * w..20 * w].fill(3900); px[30 * w + 40] = 0; px[1] = 0; // in the border: left alone - let mut tags = vec![short(CFA_PATTERN, 2), short(BITS, 12), short(RAW_FORMAT, 5)]; + let mut tags = vec![short(CFA_PATTERN, 2), short(BITS, 12), short(COMPRESSION, 34828)]; tags.extend([0x002f, 0x0030, 0x0031, 0x0032].iter().zip([12u16, 10, 52, 80]).map(|(&tag, v)| short(tag, v))); tags.extend(LINEARITY_LIMIT.map(|tag| short(tag, 2000))); // recorded limits are not used - let bytes = file(w as u16, h as u16, &tags, &rotate(pack(&px, 12)), &|off| vec![(RAW_OFFSET, Value::Long(vec![off]))]); + // Compression 34828 stores left-justified samples in little-endian u16 words. + let words: Vec = px.iter().flat_map(|&v| (v << 4).to_le_bytes()).collect(); + let bytes = file(w as u16, h as u16, &tags, &words, &|off| vec![(t::STRIP_OFFSETS, Value::Long(vec![off]))]); let r = crate::decode(&bytes).unwrap(); let d = samples(&r); assert_eq!(d[30 * w + 40], ((px[30 * w + 38] as u32 + px[30 * w + 42] as u32 + px[28 * w + 40] as u32 + px[32 * w + 40] as u32) / 4) as u16); diff --git a/crates/raw/src/srw.rs b/crates/raw/src/srw.rs index c78ef1f6fc..c9f9a0ce6b 100644 --- a/crates/raw/src/srw.rs +++ b/crates/raw/src/srw.rs @@ -192,6 +192,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result read_image(data, info, order, packing, limits), crate::Mode::Header => { check_image(data, info, limits)?; + check_uncompressed_chunks(data, info, &info.chunks(data.len() as u64), packing)?; // a lossless-JPEG layout the decoder rejects (subsampled components, e.g. Sony's // lossless M/S sizes) must fail here too, as the full decode will; likewise a JPEG XL // chunk whose headers don't match the IFD @@ -151,6 +152,7 @@ pub(crate) fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packin let bits = info.bits() as u32; let float = info.sample_format == 3; let chunks = info.chunks(data.len() as u64); + check_uncompressed_chunks(data, info, &chunks, packing)?; let planar = info.planar == 2 && cpp > 1; let ccpp = if planar { 1 } else { cpp }; // The chunks are decoded and copied into the output in groups whose combined nominal size stays within @@ -222,6 +224,26 @@ pub(crate) fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packin Ok(if float { RawData::F32(out_f32) } else { RawData::U16(out_u16) }) } +/// Framing precedes allocation even in header-only probes: missing source rows may not +/// be reported as a decodable image and later silently filled with zero samples. +fn check_uncompressed_chunks(data: &[u8], info: &ImageInfo, chunks: &[Chunk], packing: Packing) -> Result<()> { + if info.compression != comp::NONE { + return Ok(()); + } + let cpp = if info.planar == 2 { 1 } else { info.samples_per_pixel as usize }; + for chunk in chunks { + let src = chunk_bytes(data, chunk).ok_or_else(|| RawError::Corrupt("uncompressed chunk is outside the file".into()))?; + let (cw, _, vw, vh) = chunk_dims(info, chunk); + let row = packed_row_bytes(cw as u64 * cpp as u64, info.bits() as u32, packing, info.sample_format == 3); + let last = packed_row_bytes(vw as u64 * cpp as u64, info.bits() as u32, packing, info.sample_format == 3); + let need = row.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last); + if (src.len() as u64) < need { + return Err(RawError::Corrupt(format!("an uncompressed chunk has {} bytes, expected at least {need}", src.len()))); + } + } + Ok(()) +} + /// Bytes that `n` samples take in a row of an uncompressed or inflated chunk, laid out as /// [`unpack_chunk`] reads them: whole bytes or 16-bit words, or 32-bit words for `Words32Msb`. fn packed_row_bytes(n: u64, bits: u32, packing: Packing, float: bool) -> u64 { @@ -285,10 +307,12 @@ fn decode_chunk( } match info.compression { comp::NONE => { - // uncompressed: missing rows are filled with zeros, but a chunk holding a small fraction of what its - // samples need is no picture: refused before the nominal chunk is allocated (storytold/lightcraft#1512) - let need = (n as u64).saturating_mul(u64::from(bits)) / 8; - if (src.len() as u64).saturating_mul(64) < need { + // Require every visible sample. Nominal edge-tile padding may be absent, but + // missing image rows must not turn a truncated file into a zero-filled success. + let row_bytes = packed_row_bytes(cw as u64 * cpp as u64, bits, packing, float); + let last_row = packed_row_bytes(vw as u64 * cpp as u64, bits, packing, float); + let need = row_bytes.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last_row); + if (src.len() as u64) < need { return Err(RawError::Corrupt(format!("an uncompressed chunk of {n} samples has only {} bytes", src.len()))); } unpack_chunk(src, order, packing, cw, ch, cpp, bits, float, 1) @@ -314,13 +338,7 @@ fn decode_chunk( let mcu = |v: usize| v.div_ceil(32).saturating_mul(32); let tile_budget = mcu(cw).saturating_mul(mcu(ch)).saturating_mul(if cpp == 1 { 1 } else { 3 }).clamp(1, limits.max_lossy_tile_samples.max(1)); - let (px, jw, jh, jc) = lossy_jpeg(src, cpp, tile_budget)?; - // An edge tile's JPEG may be smaller than the nominal tile, but it has to cover the part of the tile - // inside the image: one that doesn't would leave a black region in a picture reported as decoded - // (PhotoCraft's and FilmCraft's readers refuse a JPEG smaller than its tile; this keeps the edge case). - if jw < vw || jh < vh { - return Err(RawError::Corrupt(format!("a lossy JPEG of {jw} × {jh} does not cover the {vw} × {vh} of its tile inside the image"))); - } + let (px, jw, jh, jc) = lossy_jpeg_with_tile(src, cpp, tile_budget, Some((cw, ch, vw, vh)))?; // the buffer holds the rows the decoded JPEG covers (the caller zero-fills the tile's // remainder and reads only rows it fills): a tile-many-larger decoded JPEG does not // get the nominal tile's full buffer (storytold/lightcraft#1517) @@ -408,9 +426,21 @@ const MAX_PADDING_FACTOR: usize = 32; #[cfg(feature = "dng")] const MAX_WRITER_TILE_SAMPLES: usize = 2048 * 2048; -#[cfg(feature = "dng")] +#[cfg(all(test, feature = "dng"))] /// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels). pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<(Vec, usize, usize, usize)> { + lossy_jpeg_with_tile(src, cpp, max_samples, None) +} + +/// Validate the actual frame before decode allocates its output. Edge tiles may store +/// a smaller frame covering all visible samples or bounded whole-MCU padding. +#[cfg(feature = "dng")] +fn lossy_jpeg_with_tile( + src: &[u8], + cpp: usize, + max_samples: usize, + tile: Option<(usize, usize, usize, usize)>, +) -> Result<(Vec, usize, usize, usize)> { use zune_core::bytestream::ZCursor; use zune_core::colorspace::ColorSpace; use zune_core::options::DecoderOptions; @@ -422,7 +452,27 @@ pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<( d.decode_headers().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; let info = d.info().ok_or_else(|| RawError::Corrupt("lossy JPEG tile without a header".into()))?; let (w, h) = (info.width as usize, info.height as usize); - let c = if cpp == 1 { 1 } else { 3 }; + if !matches!(cpp, 1 | 3) { + return Err(RawError::Unsupported(format!("lossy JPEG with {cpp} samples per pixel"))); + } + if usize::from(info.components) != cpp { + return Err(RawError::Corrupt(format!("lossy JPEG has {} components, expected {cpp}", info.components))); + } + if let Some((cw, ch, vw, vh)) = tile { + if w < vw || h < vh { + return Err(RawError::Corrupt(format!("a lossy JPEG of {w} x {h} does not cover the {vw} x {vh} of its tile inside the image"))); + } + // Writers can store a whole MCU around an edge tile. Keep the documented + // 32-pixel padding allowance without letting one tiny tile decode an arbitrary frame. + let mcu_extent = |value: usize| value.checked_add(31).map(|rounded| rounded / 32).and_then(|blocks| blocks.checked_mul(32)); + let (Some(max_w), Some(max_h)) = (mcu_extent(cw), mcu_extent(ch)) else { + return Err(RawError::Corrupt("lossy JPEG tile dimensions overflow MCU padding".into())); + }; + if w > max_w || h > max_h { + return Err(RawError::Corrupt(format!("a lossy JPEG of {w} x {h} exceeds its {max_w} x {max_h} MCU-padded tile dimensions"))); + } + } + let c = cpp; let out = w as u64 * h as u64 * c as u64; if w == 0 || h == 0 || out > max_samples as u64 { return Err(RawError::Corrupt(format!("a lossy JPEG of {w} × {h} × {c} would exceed the {max_samples} output samples allowed"))); @@ -519,6 +569,12 @@ fn unpack_chunk( } } else { undo_diff_u16(row, cpp * factor); + // Horizontal differences wrap in the declared sample precision, not in + // the u16 container used by the unpacker (TIFF 6.0 Predictor 2). + if bits < 16 { + let mask = ((1u32 << bits) - 1) as u16; + row.iter_mut().for_each(|sample| *sample &= mask); + } } } } @@ -982,3 +1038,6 @@ mod budget_tests { assert_eq!(decode_groups(&big.chunks(64), 1, 1 << 20), vec![0..1]); } } + +#[cfg(all(test, feature = "dng"))] +mod compat_review_tests; diff --git a/crates/raw/src/tiffraw/compat_review_tests.rs b/crates/raw/src/tiffraw/compat_review_tests.rs new file mode 100644 index 0000000000..ae5da8f2f0 --- /dev/null +++ b/crates/raw/src/tiffraw/compat_review_tests.rs @@ -0,0 +1,115 @@ +use super::*; +use craft_tiff::image::Layout; + +fn image(width: u32, height: u32, bits: u16, cpp: u16, compression: u16, len: usize) -> ImageInfo { + ImageInfo { + width, + height, + bits_per_sample: vec![bits; cpp as usize], + samples_per_pixel: cpp, + compression, + photometric: 34892, + planar: 1, + predictor: 1, + sample_format: 1, + new_subfile_type: 0, + layout: Layout::Strips { rows_per_strip: height }, + offsets: vec![0], + byte_counts: vec![len as u64], + } +} + +#[test] +fn truncated_uncompressed_rows_are_rejected_in_full_and_header_modes() { + for (bits, packing, float, bytes) in [ + (8, Packing::Msb, false, 8), + (12, Packing::Msb, false, 12), + (12, Packing::Word16, false, 16), + (16, Packing::Msb, false, 16), + (32, Packing::Msb, true, 32), + ] { + let data = vec![0u8; bytes]; + let mut info = image(4, 2, bits, 1, comp::NONE, bytes); + info.sample_format = if float { 3 } else { 1 }; + assert!(read_image_in(crate::Mode::Full, &data, &info, ByteOrder::Little, packing, &Limits::default()).is_ok()); + info.byte_counts[0] -= 1; + for mode in [crate::Mode::Full, crate::Mode::Header] { + assert!( + matches!(read_image_in(mode, &data[..bytes - 1], &info, ByteOrder::Little, packing, &Limits::default()), Err(RawError::Corrupt(message)) if message.contains("uncompressed chunk")), + "{bits}/{float}/{mode:?}" + ); + } + } +} + +#[test] +fn edge_padding_may_be_absent_but_visible_uncompressed_samples_must_all_exist() { + let data = vec![31u8; 16 * 7 + 8]; + let mut info = image(8, 8, 8, 1, comp::NONE, data.len()); + info.layout = Layout::Tiles { tile_width: 16, tile_height: 16 }; + let RawData::U16(values) = read_image(&data, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).unwrap() else { panic!("integer") }; + assert_eq!(values, vec![31; 64]); + info.byte_counts[0] -= 1; + assert!(read_image(&data[..data.len() - 1], &info, ByteOrder::Little, Packing::Msb, &Limits::default()).is_err()); +} + +#[test] +fn packed_predictor_two_wraps_at_declared_twelve_bits() { + // Samples [250, 10, 4090, 20]; differences modulo4096 are 0FA,F10,FF0,01A. + let packed = [0x0f, 0xaf, 0x10, 0xff, 0x00, 0x1a]; + let ChunkPx::U16(values) = unpack_chunk(&packed, ByteOrder::Little, Packing::Msb, 4, 1, 1, 12, false, 2).unwrap() else { panic!("integer") }; + assert_eq!(values, vec![250, 10, 4090, 20]); +} + +#[allow(clippy::unwrap_used)] // Test-only fixture encoder; failed construction must fail the test. +fn jpeg(cpp: usize, width: u16, height: u16) -> Vec { + let mut data = Vec::new(); + let color = if cpp == 1 { jpeg_encoder::ColorType::Luma } else { jpeg_encoder::ColorType::Rgb }; + jpeg_encoder::Encoder::new(&mut data, 100).encode(&vec![90; width as usize * height as usize * cpp], width, height, color).unwrap(); + data +} + +#[test] +fn baseline_jpeg_components_are_checked_before_forced_colorspace_conversion() { + for (actual, expected) in [(3, 1), (1, 3)] { + let data = jpeg(actual, 8, 8); + let error = lossy_jpeg(&data, expected, 1024).unwrap_err(); + assert!(matches!(error, RawError::Corrupt(message) if message.contains(&format!("{actual} components")))); + } + assert!(matches!(lossy_jpeg(&jpeg(3, 8, 8), 4, 1024), Err(RawError::Unsupported(message)) if message.contains("4 samples"))); + for cpp in [1, 3] { + assert_eq!(lossy_jpeg(&jpeg(cpp, 8, 8), cpp, 1024).unwrap().3, cpp); + } +} + +#[test] +fn jpeg_tile_geometry_and_limits_are_checked_at_the_header_with_valid_edge_controls() { + let data = jpeg(3, 8, 8); + assert!(lossy_jpeg_with_tile(&data, 3, 1024, Some((16, 16, 8, 8))).is_ok()); + assert!( + matches!(lossy_jpeg_with_tile(&data, 3, 1024, Some((16, 16, 9, 8))), Err(RawError::Corrupt(message)) if message.contains("does not cover")) + ); + assert!(matches!(lossy_jpeg_with_tile(&data, 3, 32, Some((16, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("would exceed"))); + // Mutate only SOF dimensions, retaining a valid header but no entropy for the claimed frame. + // The geometry error proves refusal precedes decode's short/corrupt entropy failure. + for (width, height) in [(33u16, 8u16), (8, 33), (256, 256)] { + let mut oversized = data.clone(); + let sof = oversized.windows(2).position(|bytes| bytes == [0xff, 0xc0]).unwrap(); + oversized[sof + 5..sof + 7].copy_from_slice(&height.to_be_bytes()); + oversized[sof + 7..sof + 9].copy_from_slice(&width.to_be_bytes()); + assert!( + matches!(lossy_jpeg_with_tile(&oversized, 3, 1 << 20, Some((16, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("exceeds its")) + ); + } + // A genuine full MCU remains valid even when only a 4x4 part of the nominal16 tile is visible. + let padded = jpeg(3, 32, 32); + assert!(lossy_jpeg_with_tile(&padded, 3, 32 * 32 * 3, Some((16, 16, 4, 4))).is_ok()); + assert!( + matches!(lossy_jpeg_with_tile(&data, 3, 1 << 20, Some((usize::MAX, 16, 8, 8))), Err(RawError::Corrupt(message)) if message.contains("overflow MCU padding")) + ); + let mut info = image(8, 8, 8, 3, comp::LOSSY_JPEG, data.len()); + info.layout = Layout::Tiles { tile_width: 16, tile_height: 16 }; + let RawData::U16(values) = read_image(&data, &info, ByteOrder::Little, Packing::Msb, &Limits::default()).unwrap() else { panic!("integer") }; + assert_eq!(values.len(), 8 * 8 * 3); + assert!(values.iter().all(|sample| (i32::from(*sample) - 90).abs() <= 3)); +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 3b7f4bc0aa..2169378624 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -64,6 +64,7 @@ fn synthetic(w: usize, h: usize, cfa: Option, cpp: usize) -> RawImage { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: craft_raw::RawNotices::default(), } } @@ -948,18 +949,31 @@ fn malformed_semantic_masks_are_skipped() { let mut zero = mask_ifd(2, 2, "zero size", vec![0; 4]); zero.set(t::IMAGE_WIDTH, Value::Long(vec![0])); ifd0.add_sub_ifd(zero); + // A 4x4 8-bit mask needs 16 visible samples; three bytes must not be + // accepted as a synthetic mask with thirteen zero-filled samples. let mut short = mask_ifd(4, 4, "short strip", vec![200; 3]); short.set(t::MASK_SUB_AREA, Value::Long(vec![u32::MAX, u32::MAX, u32::MAX, u32::MAX])); ifd0.add_sub_ifd(short); + let mut valid = mask_ifd(4, 2, "valid crop", vec![10, 20, 30, 40, 50, 60, 70, 255]); + valid.set(t::MASK_SUB_AREA, Value::Long(vec![1, 2, 8, 4])); + ifd0.add_sub_ifd(valid); let mut outside = mask_ifd(2, 2, "sub area too small", vec![255; 4]); outside.set(t::MASK_SUB_AREA, Value::Long(vec![3, 0, 2, 4])); ifd0.add_sub_ifd(outside); }); - assert_eq!(decode(&bytes).unwrap().cpp, 3); + let raw = decode(&bytes).unwrap(); + let baseline = decode(&profile_dng(ByteOrder::Little, |_| {})).unwrap(); + assert_eq!((raw.width, raw.height, raw.cpp), (8, 6, 3)); + assert_eq!(raw.data, baseline.data, "optional damaged masks must not change base image samples"); let masks = craft_raw::semantic_masks(&bytes); let names: Vec<&str> = masks.iter().map(|m| m.name.as_str()).collect(); - assert_eq!(names, ["short strip", "sub area too small"]); - assert!(masks.iter().all(|m| m.sub_area.is_none()), "sub areas the mask doesn't fit are ignored"); + assert_eq!(names, ["valid crop", "sub area too small"], "the truncated mask is omitted, and later usable masks survive"); + assert_eq!(masks[0].data, [10u16, 20, 30, 40, 50, 60, 70, 255].map(|sample| sample * 257)); + assert_eq!(masks[0].sub_area, Some(craft_raw::semantic::MaskSubArea { top: 1, left: 2, full_width: 8, full_height: 4 })); + assert!((masks[0].value_at(2.5, 1.5) - 10. / 255.).abs() < 1e-4); + assert_eq!(masks[0].value_at(1.5, 1.5), 0.); + assert!(masks[1].sub_area.is_none(), "the complete mask survives while a sub area it doesn't fit is ignored"); + assert_eq!(masks[1].data, vec![65535; 4]); for m in &masks { assert_eq!(m.data.len(), m.width * m.height); } diff --git a/crates/raw/tests/it/robust.rs b/crates/raw/tests/it/robust.rs index b2adb26e05..5ad1d1b32a 100644 --- a/crates/raw/tests/it/robust.rs +++ b/crates/raw/tests/it/robust.rs @@ -28,6 +28,7 @@ fn sample(comp: DngCompression) -> Vec { cinema: Default::default(), lens_metadata: Default::default(), level_sources: Default::default(), + notices: craft_raw::RawNotices::default(), }; craft_raw::write_dng(&raw, &DngWriteOptions { compression: comp, ..Default::default() }).unwrap() } diff --git a/crates/rtf/src/doc/export.rs b/crates/rtf/src/doc/export.rs index 69fab3d766..daa3afbda9 100644 --- a/crates/rtf/src/doc/export.rs +++ b/crates/rtf/src/doc/export.rs @@ -8,32 +8,27 @@ use crate::date::{date_words as rtf_date, iso_to_dttm}; // --------------------------------------------------------------------------------------------- // Export +use crate::write::{Interned, font_key}; pub use crate::{esc, esc_font}; pub(super) struct Tables { - pub(super) fonts: Vec, - pub(super) colors: Vec, + pub(super) fonts: Interned, + pub(super) colors: Interned, } impl Tables { + /// Tables whose font 0 is `base_font`, with no colours yet. + pub(super) fn new(base_font: String) -> Tables { + let mut t = Tables { fonts: Interned::new(), colors: Interned::new() }; + t.fonts.insert(font_key(&base_font), || base_font); + t + } pub(super) fn font(&mut self, name: &str) -> usize { - match self.fonts.iter().position(|f| f.eq_ignore_ascii_case(name)) { - Some(i) => i, - None => { - self.fonts.push(name.to_string()); - self.fonts.len() - 1 - } - } + self.fonts.insert(font_key(name), || name.to_string()) } /// Colour table index (1-based; 0 is "auto"). fn color(&mut self, c: Rgb) -> usize { - match self.colors.iter().position(|x| *x == c) { - Some(i) => i + 1, - None => { - self.colors.push(c); - self.colors.len() - } - } + self.colors.insert(c, || c) + 1 } } @@ -65,7 +60,7 @@ pub(super) struct Writer { /// List definitions: per list, the ordered flag per level. pub(super) lists: Vec<[bool; 9]>, /// Authors of tracked changes (`\revtbl` entries after "Unknown"), when the text has any. - pub(super) authors: Option>, + pub(super) authors: Option>, /// The character formatting the current paragraph's style gives its runs (heading bold and /// size, code font…): what a run's formatting without a direct value resolves to. pub(super) base: Fmt, @@ -306,18 +301,18 @@ impl Writer { /// `\revtbl` index of a tracked change's author (0 = "Unknown"). fn author(&mut self, a: &str) -> usize { - let authors = self.authors.get_or_insert_with(Vec::new); + let authors = self.authors.get_or_insert_with(Interned::new); let a = a.trim(); if a.is_empty() { return 0; } - match authors.iter().position(|x| x == a) { - Some(i) => i + 1, - None => { - authors.push(a.to_string()); - authors.len() - } - } + // A borrowed lookup first: most calls name an author already in the table, and need no + // `String` for the key. + let i = match authors.get(a) { + Some(i) => i, + None => authors.insert(a.to_string(), || a.to_string()), + }; + i + 1 } /// Control words of a tracked insertion and deletion (`\revised`, `\deleted`). @@ -858,15 +853,7 @@ pub fn export(doc: &Document) -> String { let doc = marked.as_ref().unwrap_or(doc); let flow = model::from_doc_tracked(doc); let base_font = doc.styles.default_chr.font.clone().unwrap_or_else(|| craft_wordmodel::styles::BODY_FONT.to_string()); - let mut w = Writer { - marks, - t: Tables { fonts: vec![base_font], colors: Vec::new() }, - lists: Vec::new(), - authors: None, - base: Fmt::default(), - sections: Vec::new(), - sect_i: 0, - }; + let mut w = Writer { marks, t: Tables::new(base_font), lists: Vec::new(), authors: None, base: Fmt::default(), sections: Vec::new(), sect_i: 0 }; let mut body = String::new(); // Every section starts with its own `\sectd`; `\sect` breaks only where there are several. let secs: Vec = doc.sections().into_iter().map(|(_, s)| s.clone()).collect(); @@ -882,12 +869,12 @@ pub fn export(doc: &Document) -> String { fn export_with(m: &Meta, w: &Writer, body: &str, sec: &craft_wordmodel::SectionProps) -> String { let mut out = String::from("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1\n{\\fonttbl"); - for (i, f) in w.t.fonts.iter().enumerate() { + for (i, f) in w.t.fonts.items.iter().enumerate() { let fam = if model::is_mono(f) { "\\fmodern" } else { "\\fswiss" }; out.push_str(&format!("{{\\f{i}{fam}\\fcharset0 {};}}", esc_font(f))); } out.push_str("}\n{\\colortbl;"); - for c in &w.t.colors { + for c in &w.t.colors.items { out.push_str(&format!("\\red{}\\green{}\\blue{};", c.0, c.1, c.2)); } out.push_str("}\n{\\*\\generator WordCraft;}\n{\\stylesheet{\\s0\\snext0 Normal;}"); @@ -916,7 +903,7 @@ fn export_with(m: &Meta, w: &Writer, body: &str, sec: &craft_wordmodel::SectionP } if let Some(authors) = &w.authors { out.push_str("{\\*\\revtbl {Unknown;}"); - for a in authors { + for a in &authors.items { out.push_str(&format!("{{{};}}", esc(&a.replace(';', ",")))); } out.push_str("}\n"); diff --git a/crates/rtf/src/doc/tests.rs b/crates/rtf/src/doc/tests.rs index 7c1075a86b..003b32872e 100644 --- a/crates/rtf/src/doc/tests.rs +++ b/crates/rtf/src/doc/tests.rs @@ -1168,7 +1168,7 @@ fn old_formatting_in_a_code_paragraph_has_the_code_font() { p.push_text("x", &Fmt { font: Some("Arial".into()), fmt_change: Some(Box::new(FmtChange { mark, old: Fmt::default() })), ..Default::default() }); let mut w = Writer { marks: Vec::new(), - t: Tables { fonts: vec!["Aptos".into()], colors: Vec::new() }, + t: Tables::new("Aptos".into()), lists: Vec::new(), authors: None, base: Fmt::default(), @@ -1181,6 +1181,39 @@ fn old_formatting_in_a_code_paragraph_has_the_code_font() { assert!(out.contains(&format!("{{\\*\\oldcprops \\f{mono}\\crauth1}}")), "{out}"); } +#[test] +fn many_distinct_fonts_colours_and_authors_take_constant_steps_each() { + use model::FmtChange; + // Each run has its own font, colour and tracked-change author. + let n = 3000; + let mut p = Para::default(); + for i in 0..n { + let mark = RevMark { author: format!("Author {i}"), date: String::new(), id: None }; + let color = Rgb((i >> 16) as u8, (i >> 8) as u8, i as u8); + let font: Arc = format!("Font {i}").into(); + p.push_text( + "x", + &Fmt { font: Some(font), color: Some(color), fmt_change: Some(Box::new(FmtChange { mark, old: Fmt::default() })), ..Default::default() }, + ); + } + let mut w = Writer { + marks: Vec::new(), + t: Tables::new("Aptos".into()), + lists: Vec::new(), + authors: None, + base: Fmt::default(), + sections: Vec::new(), + sect_i: 0, + }; + let mut out = String::new(); + let steps = crate::write::lookup_steps(|| w.para(&p, false, None, "\\par", &mut out)); + // One lookup each for the font and the colour, and two for a new author: the borrowed + // lookup, then the insert. + assert!(steps <= 4 * n, "{steps} steps for {n} runs"); + assert!(out.contains(&format!("\\f{n}\\cf{n}")), "the last run names the last font and colour"); + assert!(out.contains(&format!("\\crauth{n}")), "the last run names the last author"); +} + /// The text runs of `rtf`'s paragraphs, in order, with their formatting. fn text_runs(rtf: &[u8]) -> Vec<(String, Fmt)> { let f = parse(rtf).unwrap(); diff --git a/crates/rtf/src/write.rs b/crates/rtf/src/write.rs index 0b8f1dc8d1..9bd6c7b0c5 100644 --- a/crates/rtf/src/write.rs +++ b/crates/rtf/src/write.rs @@ -1,6 +1,10 @@ //! The model as RTF, and the escaping every RTF writer needs. +use std::borrow::Borrow; +use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::fmt::Write; +use std::hash::Hash; use crate::model::{Align, Block, COLUMN_BREAK, CharFmt, Document, LINE_BREAK, PAGE_BREAK, Para, VertAlign}; @@ -48,31 +52,94 @@ pub fn esc_font(name: &str) -> String { esc(&name.replace(char::is_control, "")).replace(';', "\\'3b") } +#[cfg(test)] +thread_local! { + /// Lookups the writers make in their font, colour and author tables, counted in tests: each + /// must take one step however long the table is, so a document with thousands of fonts or + /// colours is written in linear time. + static STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The lookup steps `f` takes (see [`STEPS`]). +#[cfg(test)] +pub(crate) fn lookup_steps(f: impl FnOnce()) -> usize { + STEPS.with(|s| s.set(0)); + f(); + STEPS.with(|s| s.get()) +} + +/// A table written in the order its entries were first used (`\fonttbl`, `\colortbl`, +/// `\revtbl`), with an index from each entry's key to its place, so that a lookup doesn't scan +/// the table: a document can use thousands of fonts or colours. +pub(crate) struct Interned { + pub(crate) items: Vec, + index: HashMap, +} + +impl Interned { + pub(crate) fn new() -> Self { + Interned { items: Vec::new(), index: HashMap::new() } + } + + /// The place of the entry with `key`. + pub(crate) fn get(&self, key: &Q) -> Option + where + K: Borrow, + { + #[cfg(test)] + STEPS.with(|s| s.set(s.get() + 1)); + self.index.get(key).copied() + } + + /// The place of the entry with `key`, adding `item()` at the end when there is none: one + /// lookup in the index either way. + pub(crate) fn insert(&mut self, key: K, item: impl FnOnce() -> T) -> usize { + #[cfg(test)] + STEPS.with(|s| s.set(s.get() + 1)); + match self.index.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + self.items.push(item()); + let i = self.items.len() - 1; + e.insert(i); + i + } + } + } +} + +/// A font table's key for `name`: RTF writers match font names without regard to ASCII case, +/// and the table keeps the first spelling. +pub(crate) fn font_key(name: &str) -> String { + name.to_ascii_lowercase() +} + /// The fonts and colours a document uses, in the order of their tables. Font 0 is the default /// font; colour 0 is the default (auto) colour, so the first real colour is `\cf1`. struct Tables { - fonts: Vec, - colors: Vec<[u8; 3]>, + fonts: Interned, + colors: Interned<[u8; 3], [u8; 3]>, } impl Tables { fn of(doc: &Document, default_font: &str) -> Tables { - let mut t = Tables { fonts: vec![default_font.to_string()], colors: Vec::new() }; + let mut t = Tables { fonts: Interned::new(), colors: Interned::new() }; + t.fonts.insert(font_key(default_font), || default_font.to_string()); for fmt in doc.paras().flat_map(|p| &p.runs).map(|r| &r.fmt) { - if let Some(f) = fmt.font.as_deref().filter(|f| t.font(f).is_none()) { - t.fonts.push(f.to_string()); + if let Some(f) = fmt.font.as_deref() { + t.fonts.insert(font_key(f), || f.to_string()); } - if let Some(c) = fmt.color.filter(|c| t.color(*c).is_none()) { - t.colors.push(c); + if let Some(c) = fmt.color { + t.colors.insert(c, || c); } } t } fn font(&self, name: &str) -> Option { - self.fonts.iter().position(|f| f.eq_ignore_ascii_case(name)) + self.fonts.get(font_key(name).as_str()) } fn color(&self, c: [u8; 3]) -> Option { - self.colors.iter().position(|k| *k == c).map(|i| i + 1) + self.colors.get(&c).map(|i| i + 1) } fn fmt_words(&self, f: &CharFmt) -> String { @@ -148,13 +215,13 @@ impl Tables { pub fn write(doc: &Document, default_font: &str) -> String { let t = Tables::of(doc, default_font); let mut o = String::from("{\\rtf1\\ansi\\ansicpg1252\\deff0\\uc1{\\fonttbl"); - for (i, f) in t.fonts.iter().enumerate() { + for (i, f) in t.fonts.items.iter().enumerate() { let _ = write!(o, "{{\\f{i}\\fnil {};}}", esc_font(f)); } o.push_str("}\n"); - if !t.colors.is_empty() { + if !t.colors.items.is_empty() { o.push_str("{\\colortbl;"); - for [r, g, b] in &t.colors { + for [r, g, b] in &t.colors.items { let _ = write!(o, "\\red{r}\\green{g}\\blue{b};"); } o.push_str("}\n"); @@ -196,3 +263,7 @@ pub fn write(doc: &Document, default_font: &str) -> String { o.push('}'); o } + +#[cfg(test)] +#[path = "write_tests.rs"] +mod tests; diff --git a/crates/rtf/src/write_tests.rs b/crates/rtf/src/write_tests.rs new file mode 100644 index 0000000000..ff208c88dc --- /dev/null +++ b/crates/rtf/src/write_tests.rs @@ -0,0 +1,38 @@ +use super::*; +use crate::model::Run; + +/// A paragraph of `n` runs, each in its own font and colour. +fn varied(n: usize) -> Document { + let runs = (0..n) + .map(|i| Run { + text: "x".into(), + fmt: CharFmt { font: Some(format!("Font {i}")), color: Some([(i >> 16) as u8, (i >> 8) as u8, i as u8]), ..CharFmt::default() }, + }) + .collect(); + Document { blocks: vec![Block::Para(Para { runs, ..Para::default() })], pictures_left_out: 0 } +} + +#[test] +fn many_distinct_fonts_and_colours_take_constant_steps_each() { + let n = 3000; + let doc = varied(n); + let mut out = String::new(); + let steps = lookup_steps(|| out = write(&doc, "Helvetica")); + // The default font, then two lookups per run to build the tables and two to write it. + assert!(steps <= 4 * n + 1, "{steps} steps for {n} runs"); + assert!(out.contains(&format!("{{\\f{n}\\fnil Font {};}}", n - 1)), "the last font has the last slot"); + assert!(out.contains(&format!("\\f{n}\\cf{n} x")), "the last run names the last font and colour"); +} + +#[test] +fn fonts_match_without_regard_to_ascii_case() { + let run = |font: &str| Run { text: "x".into(), fmt: CharFmt { font: Some(font.into()), ..CharFmt::default() } }; + let doc = Document { + blocks: vec![Block::Para(Para { runs: vec![run("Arial"), run("ARIAL"), run("helvetica")], ..Para::default() })], + pictures_left_out: 0, + }; + let out = write(&doc, "Helvetica"); + assert!(out.contains("{\\fonttbl{\\f0\\fnil Helvetica;}{\\f1\\fnil Arial;}}"), "{out}"); + // Both spellings of Arial are font 1; the default font's run names no font. + assert!(out.contains("{\\f1 x}{\\f1 x}x\\par"), "{out}"); +} diff --git a/crates/smime/Cargo.toml b/crates/smime/Cargo.toml new file mode 100644 index 0000000000..d2b53cabb8 --- /dev/null +++ b/crates/smime/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "craft-smime" +description = "S/MIME (RFC 8551): Digital signatures checked from CMS (RFC 5652) and X.509 (RFC 5280), no I/O" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-ber = { workspace = true } +serde = { workspace = true } +base64 = "0.23" +# RustCrypto: CMS, X.509, DER, SPKI, OID, RSA, P256, P384, SHA2. +cms = { version = "=0.3.0-rc.2", default-features = false } +x509-cert = { version = "0.3", default-features = false } +der = { version = "0.8", default-features = false, features = ["alloc", "oid"] } +spki = { version = "0.8", default-features = false, features = ["alloc"] } +const-oid = { version = "0.10", default-features = false, features = ["db"] } +# Match craft-pkcs7's RSA pin; parse PKCS #1 separately to avoid incompatible RC encoding APIs. +rsa = { version = "=0.10.0-rc.18", default-features = false } +pkcs1 = { version = "0.8", default-features = false, features = ["alloc"] } +p256 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] } +p384 = { version = "0.14", default-features = false, features = ["ecdsa", "alloc"] } +sha2 = { version = "0.11", default-features = false, features = ["oid"] } +# PKCS #12 file handling (RFC 7292 Appendix B): PBES2, triple-DES key derivation. +pkcs12 = { version = "=0.2.0-rc.0", default-features = false, features = ["kdf"] } +pbkdf2 = { version = "0.13", default-features = false, features = ["hmac"] } +hmac = { version = "0.13", default-features = false } +sha1 = { version = "0.11", default-features = false } +aes = { version = "0.9", default-features = false } +des = { version = "0.9", default-features = false } +cbc = { version = "0.2", default-features = false, features = ["block-padding"] } +zeroize = { version = "1", default-features = false, features = ["alloc"] } +# Error handling. +thiserror = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } +rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring"] } +ring = "0.17" diff --git a/crates/smime/src/algorithms.rs b/crates/smime/src/algorithms.rs new file mode 100644 index 0000000000..ba9837acd3 --- /dev/null +++ b/crates/smime/src/algorithms.rs @@ -0,0 +1,283 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! The algorithms a Digital signature or a certificate is checked with (RFC 8551 §2, RFC 5754, +//! RFC 4055, RFC 5480): SHA-2 digests, RSA (PKCS #1 v1.5 and PSS, 2048 bits or more) and ECDSA +//! on P-256 and P-384. MD5, SHA-1 and shorter RSA keys are no longer safe and are refused as +//! such; anything else is unknown. The primitives are RustCrypto's; this only names them. + +use const_oid::ObjectIdentifier; +use der::{Decode, Encode}; +use sha2::Digest; +use spki::{AlgorithmIdentifierOwned, SubjectPublicKeyInfoOwned}; + +/// Why a signature didn't check out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fault { + /// It doesn't match: what it covers was changed, or another key made it. + Invalid, + /// It uses an algorithm that's no longer safe (MD5, SHA-1, RSA under 2048 bits). + Weak, + /// It uses an algorithm that isn't known here. + Unknown, + /// The key or the signature can't be read, or they are of different kinds: nothing can be + /// said of what it covers. + Malformed, +} + +/// The least RSA modulus, in bits, that is safe enough (RFC 8551 §6). +pub const MIN_RSA_BITS: usize = 2048; +/// The largest RSA modulus checked, in bits: a longer key takes too long to be worth it. +pub const MAX_RSA_BITS: usize = 8192; + +const fn oid(s: &str) -> ObjectIdentifier { + ObjectIdentifier::new_unwrap(s) +} + +// Digests. +const MD5: ObjectIdentifier = oid("1.2.840.113549.2.5"); +const SHA1: ObjectIdentifier = oid("1.3.14.3.2.26"); +const SHA224: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.4"); +const SHA256: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.1"); +const SHA384: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.2"); +const SHA512: ObjectIdentifier = oid("2.16.840.1.101.3.4.2.3"); + +// RSA. +const RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.1"); +const MD2_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.2"); +const MD5_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.4"); +const SHA1_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.5"); +const PSS: ObjectIdentifier = oid("1.2.840.113549.1.1.10"); +const SHA256_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.11"); +const SHA384_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.12"); +const SHA512_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.13"); +const SHA224_RSA: ObjectIdentifier = oid("1.2.840.113549.1.1.14"); +const MGF1: ObjectIdentifier = oid("1.2.840.113549.1.1.8"); + +/// The bits of an RSA modulus written big-endian. +fn modulus_bits(modulus: &[u8]) -> usize { + let mut significant = modulus.iter().skip_while(|b| **b == 0); + let top = significant.next().copied().unwrap_or(0); + significant.count().saturating_mul(8).saturating_add(8usize.saturating_sub(top.leading_zeros() as usize)) +} + +/// What kind of key `key` is: RSA of so many bits, ECDSA on P-256 or P-384, or another. +pub(crate) fn key_kind(key: &SubjectPublicKeyInfoOwned) -> crate::pkcs12::KeyKind { + use crate::pkcs12::KeyKind; + if key.algorithm.oid == RSA { + return key + .subject_public_key + .as_bytes() + .and_then(|b| pkcs1::RsaPublicKey::>::from_der(b).ok()) + .map_or(KeyKind::Other, |k| KeyKind::Rsa { bits: modulus_bits(k.modulus.as_bytes()) }); + } + if key.algorithm.oid == EC_KEY { + return match key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::().ok()) { + Some(P256) => KeyKind::P256, + Some(P384) => KeyKind::P384, + _ => KeyKind::Other, + }; + } + KeyKind::Other +} + +/// What kind of private key a PKCS #8 `PrivateKeyInfo` holds, from its own algorithm identifier +/// (`algorithm`; for EC, its named `curve`, from the identifier's parameters or the key's own) +/// and, for RSA, its `modulus` (big-endian): never from a certificate that came with it. +pub(crate) fn private_key_kind(algorithm: ObjectIdentifier, curve: Option, modulus: Option<&[u8]>) -> crate::pkcs12::KeyKind { + use crate::pkcs12::KeyKind; + match (algorithm, curve, modulus) { + (RSA, _, Some(modulus)) => KeyKind::Rsa { bits: modulus_bits(modulus) }, + (EC_KEY, Some(P256), _) => KeyKind::P256, + (EC_KEY, Some(P384), _) => KeyKind::P384, + _ => KeyKind::Other, + } +} + +// ECDSA. +const EC_KEY: ObjectIdentifier = oid("1.2.840.10045.2.1"); +const SHA1_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.1"); +const SHA224_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.1"); +const SHA256_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.2"); +const SHA384_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.3"); +const SHA512_ECDSA: ObjectIdentifier = oid("1.2.840.10045.4.3.4"); +const P256: ObjectIdentifier = oid("1.2.840.10045.3.1.7"); +const P384: ObjectIdentifier = oid("1.3.132.0.34"); + +/// A digest algorithm that is safe to rely on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Hash { + Sha224, + Sha256, + Sha384, + Sha512, +} + +impl Hash { + /// The digest a CMS `digestAlgorithm` names. + pub fn of(algorithm: &AlgorithmIdentifierOwned) -> Result { + Hash::by_oid(algorithm.oid) + } + + fn by_oid(oid: ObjectIdentifier) -> Result { + match oid { + SHA224 => Ok(Hash::Sha224), + SHA256 => Ok(Hash::Sha256), + SHA384 => Ok(Hash::Sha384), + SHA512 => Ok(Hash::Sha512), + MD5 | SHA1 => Err(Fault::Weak), + _ => Err(Fault::Unknown), + } + } + + /// The digest of `data`. + pub fn digest(self, data: &[u8]) -> Vec { + match self { + Hash::Sha224 => sha2::Sha224::digest(data).to_vec(), + Hash::Sha256 => sha2::Sha256::digest(data).to_vec(), + Hash::Sha384 => sha2::Sha384::digest(data).to_vec(), + Hash::Sha512 => sha2::Sha512::digest(data).to_vec(), + } + } +} + +/// How a signature is made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Scheme { + Pkcs1(Hash), + Pss(Hash, usize), + Ecdsa(Hash), +} + +/// The scheme `algorithm` names; `digest` is the CMS signer's digest algorithm, for the names +/// that leave the hash to it (`rsaEncryption`, `id-ecPublicKey`), `None` for a certificate. +fn scheme(algorithm: &AlgorithmIdentifierOwned, digest: Option) -> Result { + match algorithm.oid { + RSA => digest.map(Scheme::Pkcs1).ok_or(Fault::Unknown), + SHA224_RSA => Ok(Scheme::Pkcs1(Hash::Sha224)), + SHA256_RSA => Ok(Scheme::Pkcs1(Hash::Sha256)), + SHA384_RSA => Ok(Scheme::Pkcs1(Hash::Sha384)), + SHA512_RSA => Ok(Scheme::Pkcs1(Hash::Sha512)), + MD2_RSA | MD5_RSA | SHA1_RSA | SHA1_ECDSA => Err(Fault::Weak), + PSS => pss(algorithm), + EC_KEY => digest.map(Scheme::Ecdsa).ok_or(Fault::Unknown), + SHA224_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha224)), + SHA256_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha256)), + SHA384_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha384)), + SHA512_ECDSA => Ok(Scheme::Ecdsa(Hash::Sha512)), + _ => Err(Fault::Unknown), + } +} + +/// RSASSA-PSS with its parameters (RFC 4055 §3.1): the hash, MGF1 with the same hash, and the +/// salt's length. Their defaults are SHA-1, which is no longer safe. +fn pss(algorithm: &AlgorithmIdentifierOwned) -> Result { + let params = algorithm.parameters.as_ref().ok_or(Fault::Weak)?; + let der = params.to_der().map_err(|_| Fault::Unknown)?; + let params = pkcs1::RsaPssParams::::from_der(&der).map_err(|_| Fault::Unknown)?; + let hash = Hash::by_oid(params.hash.oid)?; + if params.mask_gen.oid != MGF1 { + return Err(Fault::Unknown); + } + let mgf_hash = params.mask_gen.parameters.as_ref().map(|p| p.oid).ok_or(Fault::Weak)?; + if Hash::by_oid(mgf_hash)? != hash { + return Err(Fault::Unknown); + } + Ok(Scheme::Pss(hash, usize::from(params.salt_len))) +} + +/// Check `signature` over `data` with the key `key`, by `algorithm` (and `digest`, for a CMS +/// signer: see [`scheme`]). +pub fn verify( + key: &SubjectPublicKeyInfoOwned, + algorithm: &AlgorithmIdentifierOwned, + digest: Option, + data: &[u8], + signature: &[u8], +) -> Result<(), Fault> { + verify_hashed(key, algorithm, digest, &mut |hash| hash.digest(data), signature) +} + +/// [`verify`], with what was signed given by its digest: `hashed` gives it by each algorithm +/// (so that a long content is hashed once per algorithm however many keys are tried). +pub fn verify_hashed( + key: &SubjectPublicKeyInfoOwned, + algorithm: &AlgorithmIdentifierOwned, + digest: Option, + hashed: &mut dyn FnMut(Hash) -> Vec, + signature: &[u8], +) -> Result<(), Fault> { + // RFC 4055 3.3: an id-RSASSA-PSS SPKI restricts schemes and parameters. + // Those restrictions are not implemented here; do not treat it as rsaEncryption. + if key.algorithm.oid == PSS { + return Err(Fault::Unknown); + } + let scheme = scheme(algorithm, digest)?; + match scheme { + Scheme::Pkcs1(hash) | Scheme::Pss(hash, _) => { + if key.algorithm.oid != RSA { + return Err(Fault::Malformed); + } + let public = rsa_key(key)?; + let hashed = hashed(hash); + let checked = match scheme { + Scheme::Pss(_, salt) => match hash { + Hash::Sha224 => public.verify(rsa::pss::Pss::::new_with_salt(salt), &hashed, signature), + Hash::Sha256 => public.verify(rsa::pss::Pss::::new_with_salt(salt), &hashed, signature), + Hash::Sha384 => public.verify(rsa::pss::Pss::::new_with_salt(salt), &hashed, signature), + Hash::Sha512 => public.verify(rsa::pss::Pss::::new_with_salt(salt), &hashed, signature), + }, + _ => { + let padding = match hash { + Hash::Sha224 => rsa::Pkcs1v15Sign::new::(), + Hash::Sha256 => rsa::Pkcs1v15Sign::new::(), + Hash::Sha384 => rsa::Pkcs1v15Sign::new::(), + Hash::Sha512 => rsa::Pkcs1v15Sign::new::(), + }; + public.verify(padding, &hashed, signature) + } + }; + checked.map_err(|_| Fault::Invalid) + } + Scheme::Ecdsa(hash) => { + if key.algorithm.oid != EC_KEY { + return Err(Fault::Malformed); + } + let curve = key.algorithm.parameters.as_ref().and_then(|p| p.decode_as::().ok()).ok_or(Fault::Unknown)?; + let point = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?; + let hashed = hashed(hash); + use p256::ecdsa::signature::hazmat::PrehashVerifier; + match curve { + P256 => { + let key = p256::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?; + let sig = p256::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?; + key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid) + } + P384 => { + let key = p384::ecdsa::VerifyingKey::from_sec1_bytes(point).map_err(|_| Fault::Malformed)?; + let sig = p384::ecdsa::Signature::from_der(signature).map_err(|_| Fault::Malformed)?; + key.verify_prehash(&hashed, &sig).map_err(|_| Fault::Invalid) + } + _ => Err(Fault::Unknown), + } + } + } +} + +/// The RSA key of `key`: [`Fault::Weak`] under [`MIN_RSA_BITS`], [`Fault::Unknown`] past what +/// the library takes (8192 bits) or when it can't be read. +fn rsa_key(key: &SubjectPublicKeyInfoOwned) -> Result { + let bits = key.subject_public_key.as_bytes().ok_or(Fault::Unknown)?; + let pkcs1 = pkcs1::RsaPublicKey::>::from_der(bits).map_err(|_| Fault::Unknown)?; + let bits = modulus_bits(pkcs1.modulus.as_bytes()); + if bits < MIN_RSA_BITS { + return Err(Fault::Weak); + } + if bits > MAX_RSA_BITS { + return Err(Fault::Unknown); + } + rsa::RsaPublicKey::new( + rsa::BoxedUint::from_be_slice_vartime(pkcs1.modulus.as_bytes()), + rsa::BoxedUint::from_be_slice_vartime(pkcs1.public_exponent.as_bytes()), + ) + .map_err(|_| Fault::Unknown) +} diff --git a/crates/smime/src/cert.rs b/crates/smime/src/cert.rs new file mode 100644 index 0000000000..28968f27f2 --- /dev/null +++ b/crates/smime/src/cert.rs @@ -0,0 +1,448 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! An X.509 certificate (RFC 5280) as a Digital signature is checked with: its bytes, what it +//! says, and the few questions asked of it (who it names, for what, until when, who signed it). + +use crate::Timestamp; +use crate::digital_signature::{MAX_SIGNER_ADDRESSES, signer_text}; +use const_oid::ObjectIdentifier; +use der::{Decode, Encode}; +use x509_cert::Certificate; +use x509_cert::ext::pkix::constraints::name::GeneralSubtrees; +use x509_cert::ext::pkix::name::GeneralName; +use x509_cert::ext::pkix::{ + AuthorityKeyIdentifier, BasicConstraints, CertificatePolicies, ExtendedKeyUsage, KeyUsage, NameConstraints, SubjectAltName, SubjectKeyIdentifier, +}; + +use crate::algorithms::{self, Fault}; +use craft_ber as ber; + +/// The largest certificate read. +pub const MAX_CERT_BYTES: usize = 64 * 1024; + +const EMAIL_PROTECTION: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4"); +const ANY_EXTENDED_KEY_USAGE: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.37.0"); +const EMAIL_ADDRESS: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1"); + +/// The extensions whose meaning is known here (RFC 5280 §4.2): a certificate with any other +/// marked critical is refused (§6.1.4 (o)). Certificate policies are taken as any policy (no +/// policy is asked for, §6.1.1 (c)); the identifiers say nothing to check. +const KNOWN: [ObjectIdentifier; 8] = [ + ObjectIdentifier::new_unwrap("2.5.29.14"), // subject key identifier + ObjectIdentifier::new_unwrap("2.5.29.15"), // key usage + ObjectIdentifier::new_unwrap("2.5.29.17"), // subject alternative name + ObjectIdentifier::new_unwrap("2.5.29.19"), // basic constraints + ObjectIdentifier::new_unwrap("2.5.29.30"), // name constraints + ObjectIdentifier::new_unwrap("2.5.29.32"), // certificate policies + ObjectIdentifier::new_unwrap("2.5.29.35"), // authority key identifier + ObjectIdentifier::new_unwrap("2.5.29.37"), // extended key usage +]; + +/// The name constraints a certification authority puts on what it vouches for (RFC 5280 +/// §4.2.1.10), for the two kinds of name a mail certificate has: mail addresses and directory +/// names. The other kinds name nothing that is checked here. +#[derive(Clone, Debug, Default)] +pub struct Constraints { + pub permitted_mail: Option>, + pub excluded_mail: Vec, + pub permitted_dirs: Option>>>, + pub excluded_dirs: Vec>>, +} + +/// A directory identity represented as ordered DER relative names. +pub type DirectoryName = Vec>; + +/// A certificate: its DER, the body its issuer signed, and what it says. +#[derive(Clone, Debug)] +pub struct Cert { + der: Vec, + /// Where the to-be-signed body is in `der`. + tbs: std::ops::Range, + parsed: Certificate, + subject: Vec, + issuer: Vec, +} + +impl PartialEq for Cert { + fn eq(&self, other: &Self) -> bool { + self.der == other.der + } +} + +impl Cert { + /// The certificate `der` is, when it is one. + pub fn from_der(der: &[u8]) -> Option { + if der.len() > MAX_CERT_BYTES { + return None; + } + let (outer, rest) = ber::read(der)?; + if !rest.is_empty() { + return None; + } + let (tbs, _) = ber::read(outer.value)?; + let start = outer.whole.len().checked_sub(outer.value.len())?; + let end = start.checked_add(tbs.whole.len())?; + let parsed = Certificate::from_der(der).ok()?; + // RFC 5280 4.1.1.2: the outer and signed algorithm identifiers must agree. + if parsed.signature_algorithm() != parsed.tbs_certificate().signature() { + return None; + } + // A recognized extension that cannot be decoded is not an absent extension. + // In particular, never fall back to the subject identity after a malformed SAN. + let tbs = parsed.tbs_certificate(); + if tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + || tbs.get_extension::().is_err() + { + return None; + } + let subject = parsed.tbs_certificate().subject().to_der().ok()?; + let issuer = parsed.tbs_certificate().issuer().to_der().ok()?; + Some(Cert { der: der.to_vec(), tbs: start..end, parsed, subject, issuer }) + } + + pub fn der(&self) -> &[u8] { + &self.der + } + + fn tbs(&self) -> &[u8] { + self.der.get(self.tbs.clone()).unwrap_or_default() + } + + pub fn subject(&self) -> &[u8] { + &self.subject + } + + pub fn issuer(&self) -> &[u8] { + &self.issuer + } + + /// The serial number's bytes. + pub fn serial(&self) -> &[u8] { + self.parsed.tbs_certificate().serial_number().as_bytes() + } + + /// The subject key identifier, when it has one. + pub fn key_id(&self) -> Option> { + let (_, ski) = self.parsed.tbs_certificate().get_extension::().ok()??; + Some(ski.0.as_bytes().to_vec()) + } + + pub fn public_key(&self) -> &spki::SubjectPublicKeyInfoOwned { + self.parsed.tbs_certificate().subject_public_key_info() + } + + /// Its SHA-256 fingerprint: upper-case hexadecimal pairs with colons between. + pub fn fingerprint(&self) -> String { + algorithms::Hash::Sha256.digest(&self.der).iter().map(|b| format!("{b:02X}")).collect::>().join(":") + } + + /// From and until when it is valid, in seconds since 1970. + pub fn validity(&self) -> (Timestamp, Timestamp) { + let v = self.parsed.tbs_certificate().validity(); + let secs = |t: &x509_cert::time::Time| Timestamp::try_from(t.to_unix_duration().as_secs()).unwrap_or(Timestamp::MAX); + (secs(&v.not_before), secs(&v.not_after)) + } + + /// Whether it is valid at `now`. + pub fn valid_at(&self, now: Timestamp) -> bool { + let (from, until) = self.validity(); + from <= now && now <= until + } + + /// The name it is for: its common name, else its whole name. + pub fn name(&self) -> String { + name_of(self.parsed.tbs_certificate().subject()) + } + + /// The name of who issued it. + pub fn issuer_name(&self) -> String { + name_of(self.parsed.tbs_certificate().issuer()) + } + + /// The mail addresses it is for: its subject alternative names of that kind, and an + /// `emailAddress` in its subject (RFC 8551 §3.1), at most [`MAX_SIGNER_ADDRESSES`]. + pub fn addresses(&self) -> Vec { + let mut out = Vec::new(); + if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::() { + for name in san.0.iter() { + if let GeneralName::Rfc822Name(a) = name { + out.push(signer_text(a.as_str())); + } + } + } + for atv in self.parsed.tbs_certificate().subject().iter() { + if atv.oid == EMAIL_ADDRESS + && let Ok(a) = atv.value.decode_as::() + { + out.push(signer_text(a.as_str())); + } + } + out.retain(|a| !a.is_empty()); + out.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + out.truncate(MAX_SIGNER_ADDRESSES); + out + } + + /// The mail addresses it names, exactly as written (its alternative names of that kind and + /// the `emailAddress` in its subject), all of them: for comparing + /// and for name constraints, never for showing. The certificate byte cap bounds this list; display truncation + /// must not hide names from certification-authority constraints. + pub fn raw_addresses(&self) -> Vec { + let mut out = Vec::new(); + if let Ok(Some((_, san))) = self.parsed.tbs_certificate().get_extension::() { + out.extend(san.0.iter().filter_map(|n| match n { + GeneralName::Rfc822Name(a) => Some(a.as_str().to_string()), + _ => None, + })); + } + out.extend( + self.parsed + .tbs_certificate() + .subject() + .iter() + .filter(|atv| atv.oid == EMAIL_ADDRESS) + .filter_map(|atv| atv.value.decode_as::().ok()) + .map(|a| a.as_str().to_string()), + ); + out + } + + /// Whether it is for `address`: one of its addresses as written is that address, letter case + /// aside in plain ASCII (RFC 5280 §4.2.1.6, §7.5). An address with a space, a control or any + /// character past ASCII on either side never is. + pub fn is_for(&self, address: &str) -> bool { + printable(address) && self.raw_addresses().iter().any(|a| printable(a) && a.eq_ignore_ascii_case(address)) + } + + /// The address of its it is for `address` by ([`Cert::is_for`]), as it shows it. + pub fn address_for(&self, address: &str) -> Option { + printable(address).then(|| self.raw_addresses().into_iter().find(|a| printable(a) && a.eq_ignore_ascii_case(address))).flatten() + } + + /// Whether it carries an extension marked critical that isn't known here. + pub fn unknown_critical(&self) -> bool { + self.parsed.tbs_certificate().extensions().is_some_and(|exts| exts.iter().any(|e| e.critical && !KNOWN.contains(&e.extn_id))) + } + + /// Its path length constraint, when its basic constraints give one (unreadable: none + /// allowed below it). + pub fn path_len(&self) -> Option { + match self.parsed.tbs_certificate().get_extension::() { + Ok(Some((_, bc))) => bc.path_len_constraint, + Ok(None) => None, + Err(_) => Some(0), + } + } + + /// Whether, as a certification authority on a path, its extended key usage (when it has + /// one) lets it vouch for mail: email protection, or any use. + pub fn may_vouch_for_mail(&self) -> bool { + match self.parsed.tbs_certificate().get_extension::() { + Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE), + Ok(None) => true, + Err(_) => false, + } + } + + /// Whether it is a certification authority's by any sign (basic constraints say so, or its + /// key usage lets it sign certificates): never a mail signer's. + pub fn is_authority(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let ca = matches!(tbs.get_extension::(), Ok(Some((_, bc))) if bc.ca); + let signs = matches!(tbs.get_extension::(), Ok(Some((_, ku))) if ku.key_cert_sign()); + ca || signs + } + + /// The name constraints it puts on what it vouches for; `Err` when they can't be read or use + /// what RFC 5280 says mustn't be (a minimum or a maximum). + pub fn constraints(&self) -> Result, ()> { + let Some((_, nc)) = self.parsed.tbs_certificate().get_extension::().map_err(|_| ())? else { return Ok(None) }; + let mut c = Constraints::default(); + if let Some(permitted) = &nc.permitted_subtrees { + let (mail, dirs) = subtrees(permitted)?; + c.permitted_mail = mail; + c.permitted_dirs = dirs; + } + if let Some(excluded) = &nc.excluded_subtrees { + let (mail, dirs) = subtrees(excluded)?; + c.excluded_mail = mail.unwrap_or_default(); + c.excluded_dirs = dirs.unwrap_or_default(); + } + Ok(Some(c)) + } + + /// Every directory identity: the nonempty subject and every directoryName SAN. + pub fn directory_names(&self) -> Option> { + let rdns = |name: &x509_cert::name::Name| name.iter_rdn().map(|r| r.to_der().ok()).collect::>>(); + let mut names = Vec::new(); + let subject = rdns(self.parsed.tbs_certificate().subject())?; + if !subject.is_empty() { + names.push(subject); + } + if let Some((_, san)) = self.parsed.tbs_certificate().get_extension::().ok()? { + for name in &san.0 { + if let GeneralName::DirectoryName(name) = name { + names.push(rdns(name)?); + } + } + } + Some(names) + } + + /// Whether it may be a certification authority's: basic constraints say so, and its key + /// usage, when it has one, lets it sign certificates. + pub fn is_ca(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let ca = matches!(tbs.get_extension::(), Ok(Some((_, bc))) if bc.ca); + let signs = match tbs.get_extension::() { + Ok(Some((_, ku))) => ku.key_cert_sign(), + Ok(None) => true, + Err(_) => false, + }; + ca && signs + } + + /// Whether it is for signing mail (RFC 8551 §4.4): its key usage, when it has one, allows a + /// Digital signature or non-repudiation, and its extended key usage, when it has one, names + /// email protection (or any use). + pub fn for_email(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let usage = match tbs.get_extension::() { + Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation(), + Ok(None) => true, + Err(_) => false, + }; + let extended = match tbs.get_extension::() { + Ok(Some((_, eku))) => eku.0.iter().any(|o| *o == EMAIL_PROTECTION || *o == ANY_EXTENDED_KEY_USAGE), + Ok(None) => true, + Err(_) => false, + }; + usage && extended + } + + /// Whether it is for mail at all, to sign it or to encrypt it (RFC 8551 §4.4): its key usage, + /// when it has one, allows a Digital signature, non-repudiation, key encipherment or key + /// agreement, and its extended key usage, when it has one, names email protection (or any + /// use). What a Public key imported for an address must be. + pub fn for_mail(&self) -> bool { + let tbs = self.parsed.tbs_certificate(); + let usage = match tbs.get_extension::() { + Ok(Some((_, ku))) => ku.digital_signature() || ku.non_repudiation() || ku.key_encipherment() || ku.key_agreement(), + Ok(None) => true, + Err(_) => false, + }; + usage && self.may_vouch_for_mail() + } + + /// Whether it names itself as its issuer. + pub fn self_issued(&self) -> bool { + self.subject == self.issuer + } + + /// Whether `issuer`'s key made its signature. + pub fn signed_by(&self, issuer: &Cert) -> Result<(), Fault> { + let signature = self.parsed.signature().as_bytes().ok_or(Fault::Invalid)?; + algorithms::verify(issuer.public_key(), self.parsed.signature_algorithm(), None, self.tbs(), signature) + } +} + +/// Whether `address` has only the printable ASCII an address is compared in (and something). +pub(crate) fn printable(address: &str) -> bool { + !address.is_empty() && address.bytes().all(|b| (0x21..=0x7e).contains(&b)) +} + +/// The mail and directory names of `subtrees` (`None` of a kind: none of that kind given). +type Subtrees = (Option>, Option>>>); + +fn subtrees(subtrees: &GeneralSubtrees) -> Result { + let (mut mail, mut dirs): Subtrees = (None, None); + for s in subtrees.iter().take(64) { + if s.minimum != 0 || s.maximum.is_some() { + return Err(()); + } + match &s.base { + GeneralName::Rfc822Name(a) => mail.get_or_insert_with(Vec::new).push(a.as_str().to_string()), + GeneralName::DirectoryName(n) => dirs.get_or_insert_with(Vec::new).push(n.iter_rdn().filter_map(|r| r.to_der().ok()).collect()), + // RFC 5280 4.2.1.10: constraints cannot be treated as processed when + // this validator does not implement their name form. Fail closed. + _ => return Err(()), + } + } + if subtrees.len() > 64 { + return Err(()); + } + Ok((mail, dirs)) +} + +/// Whether the mail address `address` is within the constraint `base` (RFC 5280 §4.2.1.10): a +/// whole address, every address at one host, or (with a leading dot) every address at any host +/// under a domain. Letter case aside. +pub fn mail_within(address: &str, base: &str) -> bool { + let address = address.to_ascii_lowercase(); + let base = base.to_ascii_lowercase(); + if base.contains('@') { + return address == base; + } + let Some((_, host)) = address.rsplit_once('@') else { return false }; + if let Some(domain) = base.strip_prefix('.') { + return host.len() > domain.len() && host.ends_with(domain) && host.as_bytes().get(host.len() - domain.len() - 1) == Some(&b'.'); + } + host == base +} + +/// Whether the name `rdns` is within the directory name `base`: it begins with all of it, each +/// relative name compared using the supported ASCII subset of RFC 5280 §7.1. +/// Unsupported string types or non-ASCII values must fail closed in the caller. +pub fn dir_within(rdns: &[Vec], base: &[Vec]) -> bool { + rdns.len() >= base.len() && rdns.iter().zip(base).all(|(a, b)| matches!((rdn_key(a), rdn_key(b)), (Some(x), Some(y)) if x == y)) +} + +/// Whether every relative name is within the supported comparison profile. +pub fn directory_supported(rdns: &[Vec]) -> bool { + rdns.iter().all(|rdn| rdn_key(rdn).is_some()) +} + +fn rdn_key(der: &[u8]) -> Option)>> { + use der::Tag; + let rdn = x509_cert::name::RelativeDistinguishedName::from_der(der).ok()?; + let mut key: Vec<(String, Vec)> = rdn + .iter() + .map(|atv| { + let value = match der::Tagged::tag(&atv.value) { + Tag::PrintableString | Tag::Utf8String => { + let text = std::str::from_utf8(atv.value.value()).ok()?; + // RFC 5280 7.1 requires StringPrep for non-ASCII names. Until the + // complete profile is implemented, constrained chains fail closed. + if !text.is_ascii() { + return None; + } + let folded: Vec = text.split_whitespace().map(str::to_lowercase).collect(); + let mut v = b"s".to_vec(); + v.extend_from_slice(folded.join(" ").as_bytes()); + v + } + _ => return None, + }; + Some((atv.oid.to_string(), value)) + }) + .collect::>()?; + key.sort(); + Some(key) +} + +/// A name for people: its common name, else the whole of it as RFC 4514 writes it. +fn name_of(name: &x509_cert::name::Name) -> String { + if let Ok(Some(cn)) = name.common_name() { + let cn = signer_text(&cn.value()); + if !cn.is_empty() { + return cn; + } + } + signer_text(&name.to_string()) +} diff --git a/crates/smime/src/chain.rs b/crates/smime/src/chain.rs new file mode 100644 index 0000000000..81d52b71db --- /dev/null +++ b/crates/smime/src/chain.rs @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Whether a signer's certificate rests on a trust anchor (RFC 5280 §6, as S/MIME needs it): a +//! path from it through certification authorities' certificates that came with the message, to +//! a certificate the host trusts. Each link's signature is checked, and every certificate on the +//! path must be valid at the time of the check and keep its authorities' constraints. Bounded: a +//! path is at most [`MAX_PATH`] long, and the signatures checked come out of the message's +//! budget ([`crate::MAX_VERIFICATIONS`]). + +use std::collections::HashMap; + +use crate::Timestamp; +use crate::digital_signature::Why; + +use crate::algorithms::Fault; +use crate::cert::{Cert, Constraints, dir_within, directory_supported, mail_within}; + +/// The most certificates between a signer's and a trust anchor. +pub const MAX_PATH: usize = 6; +/// The most trust anchors kept. +pub const MAX_ANCHORS: usize = 4_000; + +/// The certificates the host trusts (the system's certification authorities, handed in: this +/// crate never reads a store of its own). +#[derive(Clone, Debug, Default)] +pub struct Anchors { + certs: Vec, + by_subject: HashMap, Vec>, +} + +impl Anchors { + /// Anchors from certificates in DER; one that isn't a certificate is left out, as is + /// everything past [`MAX_ANCHORS`]. + pub fn new(ders: I) -> Anchors + where + I: IntoIterator, + B: AsRef<[u8]>, + { + let mut anchors = Anchors::default(); + for der in ders { + if anchors.certs.len() >= MAX_ANCHORS { + break; + } + if let Some(cert) = Cert::from_der(der.as_ref()) { + anchors.by_subject.entry(cert.subject().to_vec()).or_default().push(anchors.certs.len()); + anchors.certs.push(cert); + } + } + anchors + } + + pub fn len(&self) -> usize { + self.certs.len() + } + + pub fn is_empty(&self) -> bool { + self.certs.is_empty() + } + + fn named(&self, subject: &[u8]) -> impl Iterator { + self.by_subject.get(subject).into_iter().flatten().filter_map(|i| self.certs.get(*i)) + } + + fn holds(&self, cert: &Cert) -> bool { + self.named(cert.subject()).any(|a| a == cert) + } +} + +/// Whether `leaf` rests on one of `anchors` through the certificates of `pool`, at `now`, +/// checking at most `budget` signatures (taken from it). Every path to an anchor is tried until +/// one holds (RFC 5280 §6.1): each certificate on it valid at `now`, none with a critical +/// extension not known here, each authority's path length and name constraints kept, and every +/// authority's extended key usage, when it has one, allowing mail. +/// +/// (Validity is checked at the time of the check, not the signing time the signer gives: that is +/// the signer's own word, and a certificate that ran out or was replaced since is said.) +pub fn trust(leaf: &Cert, pool: &[Cert], anchors: &Anchors, now: Timestamp, budget: &mut usize) -> Result<(), Why> { + let mut search = Search { leaf, pool, anchors, now, budget, weak: false, refused: None, ran_out: false }; + let mut path = Vec::new(); + if search.walk(leaf, &mut path) { + return Ok(()); + } + Err(match search.refused { + // (A path left untried may hold: no answer, rather than the first refusal's.) + _ if search.ran_out => Why::TooMuch, + Some(why) => why, + None if search.weak => Why::WeakAlgorithm, + None if leaf.self_issued() => Why::SelfSigned, + None => Why::UnknownIssuer, + }) +} + +struct Search<'a, 'b> { + leaf: &'a Cert, + pool: &'a [Cert], + anchors: &'a Anchors, + now: Timestamp, + budget: &'b mut usize, + /// A link was signed with an algorithm that's no longer safe. + weak: bool, + /// Why the first path found to an anchor didn't hold. + refused: Option, + /// The budget ran out before every path was tried. + ran_out: bool, +} + +impl<'a> Search<'a, '_> { + /// Whether `cert` rests on an anchor by a path that holds; `path` has the certificates above + /// the leaf so far, the anchor last once one is reached. + fn walk(&mut self, cert: &'a Cert, path: &mut Vec<&'a Cert>) -> bool { + // A certificate the host trusts itself ends the path, whether it holds or not. + if self.anchors.holds(cert) { + return self.holds(path); + } + for anchor in self.anchors.named(cert.issuer()) { + if self.signed(cert, anchor) { + path.push(anchor); + if self.holds(path) { + return true; + } + path.pop(); + } + } + if path.len() >= MAX_PATH { + return false; + } + for issuer in self.pool.iter().filter(|c| c.subject() == cert.issuer() && *c != cert && c.is_ca()) { + // (No certificate twice on a path.) + if path.contains(&issuer) || !self.signed(cert, issuer) { + continue; + } + path.push(issuer); + if self.walk(issuer, path) { + return true; + } + path.pop(); + } + false + } + + /// Whether the path from the leaf through `above` (the anchor last) holds; why not is kept. + fn holds(&mut self, above: &[&Cert]) -> bool { + let full: Vec<&Cert> = std::iter::once(self.leaf).chain(above.iter().copied()).collect(); + match judge(&full, self.now) { + Ok(()) => true, + Err(why) => { + self.refused.get_or_insert(why); + false + } + } + } + + fn signed(&mut self, cert: &Cert, by: &Cert) -> bool { + if *self.budget == 0 { + self.ran_out = true; + return false; + } + *self.budget -= 1; + match cert.signed_by(by) { + Ok(()) => true, + Err(Fault::Weak) => { + self.weak = true; + false + } + Err(_) => false, + } + } +} + +/// Whether the path `full` (the leaf first, the anchor last) holds at `now` (RFC 5280 §6.1). +pub(crate) fn judge(full: &[&Cert], now: Timestamp) -> Result<(), Why> { + if full.iter().any(|c| !c.valid_at(now)) { + return Err(Why::Expired); + } + // (The anchor is the host's to vouch for, extensions and all.) + let last = full.len().saturating_sub(1); + if full.iter().take(last).any(|c| c.unknown_critical()) { + return Err(Why::Constrained); + } + for (k, ca) in full.iter().enumerate().skip(1) { + if !ca.may_vouch_for_mail() { + return Err(Why::Constrained); + } + // The certificates below it that count: the leaf, and every authority's not issued by + // itself (§6.1.4 (l), §6.1.3 (b)). + let below: Vec<&Cert> = full.iter().take(k).enumerate().filter(|(j, c)| *j == 0 || !c.self_issued()).map(|(_, c)| *c).collect(); + if let Some(n) = ca.path_len() + && below.len().saturating_sub(1) > usize::from(n) + { + return Err(Why::Constrained); + } + let Ok(constraints) = ca.constraints() else { return Err(Why::Constrained) }; + if let Some(c) = constraints + && !below.iter().all(|cert| within(cert, &c)) + { + return Err(Why::Constrained); + } + } + Ok(()) +} + +/// Whether the names of `cert` are within `c`. +fn within(cert: &Cert, c: &Constraints) -> bool { + let mail = cert.raw_addresses(); + if let Some(permitted) = &c.permitted_mail + && !mail.iter().all(|a| permitted.iter().any(|p| mail_within(a, p))) + { + return false; + } + if mail.iter().any(|a| c.excluded_mail.iter().any(|e| mail_within(a, e))) { + return false; + } + // Unsupported normalization must not make an excluded subtree look different. + if c.permitted_dirs.is_none() && c.excluded_dirs.is_empty() { + return true; + } + let Some(names) = cert.directory_names() else { return false }; + if !names.iter().all(|name| directory_supported(name)) + || !c.excluded_dirs.iter().all(|name| directory_supported(name)) + || c.permitted_dirs.as_ref().is_some_and(|names| !names.iter().all(|name| directory_supported(name))) + { + return false; + } + names.iter().all(|rdns| { + if let Some(permitted) = &c.permitted_dirs + && !permitted.iter().any(|p| dir_within(rdns, p)) + { + return false; + } + !c.excluded_dirs.iter().any(|e| dir_within(rdns, e)) + }) +} diff --git a/crates/smime/src/digital_signature.rs b/crates/smime/src/digital_signature.rs new file mode 100644 index 0000000000..19bb572f7a --- /dev/null +++ b/crates/smime/src/digital_signature.rs @@ -0,0 +1,277 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! What checking a message's Digital signature found (#30), whichever format it is in: S/MIME +//! (`craft-smime`) or OpenPGP. One of four results ([`Verdict`]), why when it isn't the +//! first ([`Why`]), and what is known of who signed it ([`Signer`]). Worked out from the bytes the +//! message came as, in memory, and never written to the mailbox file: it is checked again when +//! the message is next looked at, against the trust and the clock of that moment. + +use serde::{Deserialize, Serialize}; + +use crate::Timestamp; + +/// The format of a Digital signature. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum SignatureFormat { + /// S/MIME (RFC 8551): CMS signed data and an X.509 certificate. + Smime, + /// OpenPGP (RFC 9580), as PGP/MIME (RFC 3156) or inline. + OpenPgp, +} + +impl SignatureFormat { + pub fn as_str(self) -> &'static str { + match self { + SignatureFormat::Smime => "smime", + SignatureFormat::OpenPgp => "openpgp", + } + } +} + +/// The four results a check has, best first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Verdict { + /// The Digital signature is valid, its signer is trusted, the signer's address is the + /// message's one From address (verified is for that signer and that address together, never + /// for a key alone), and what was signed is the whole message ([`Coverage::Whole`]). + Verified, + /// The Digital signature is valid, but its signer isn't verified ([`Why`] says how): an + /// unknown issuer, a certificate out of date or not for mail, an address that isn't the From + /// address, an OpenPGP key nobody marked verified. + NotVerified, + /// The message was changed after it was signed: what is shown isn't what was signed. + Changed, + /// The Digital signature can't be checked ([`Why`] says why): an algorithm that's no longer + /// safe or isn't known, no Public key, or a signature that can't be read. + Unchecked, +} + +impl Verdict { + /// Its name for an agent and a script: `verified`, `notVerified`, `changed`, `unchecked`. + pub fn as_str(self) -> &'static str { + match self { + Verdict::Verified => "verified", + Verdict::NotVerified => "notVerified", + Verdict::Changed => "changed", + Verdict::Unchecked => "unchecked", + } + } + + /// The better of two results ([`Verdict::Verified`] best): of several signers of one + /// message, the best one stands. + pub fn best(self, other: Verdict) -> Verdict { + self.min(other) + } +} + +/// Why a check found less than [`Verdict::Verified`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Why { + // Not verified. + /// The certificate wasn't issued by a certification authority this computer trusts. + UnknownIssuer, + /// The certificate signed itself, and isn't one this computer trusts. + SelfSigned, + /// The certificate, or one of those it rests on, is out of date (or not valid yet). + Expired, + /// The certificate isn't for signing mail (its key usage or extended key usage say so). + NotForEmail, + /// The certificate is for another address than the message's From address. + AddressMismatch, + /// An authority on the way to a trusted one doesn't allow the certificate to be used this + /// way: a name outside what it may vouch for, a path too long, a use it doesn't allow, or a + /// critical extension not known here (RFC 5280 §4.2, §6.1). + Constrained, + /// No certification authorities for mail could be read on this computer, so no signer can be + /// verified here. + NoAuthorities, + /// This computer's certification authorities haven't been read yet (they are read at start): + /// the check is made again when they are. + AuthoritiesNotRead, + /// An OpenPGP key that the owner hasn't marked Verified. + KeyNotVerified, + /// Only part of the message was signed (a wrapper such as a list's footer holds it), so + /// what is outside that part could say anything. + PartlySigned, + // Changed. + /// What was signed isn't what arrived. + Altered, + // Can't be checked. + /// It uses an algorithm that's no longer safe (MD5, SHA-1, a short RSA key). + WeakAlgorithm, + /// It uses an algorithm MailCraft doesn't know. + UnknownAlgorithm, + /// The signer's Public key (certificate) isn't in the message or kept here. + NoPublicKey, + /// The signer's OpenPGP key was revoked by its owner, for when the message was signed. + KeyRevoked, + /// The signer's OpenPGP key had expired when the message was signed. + KeyExpired, + /// The OpenPGP key that made it isn't one that may sign. + NotASigningKey, + /// The Digital signature itself has expired (it said until when it holds). + SignatureExpired, + /// The Digital signature can't be read. + Unreadable, + /// The bytes the message came as aren't here (it was read before they were kept): Check + /// again downloads them. + NoOriginal, + /// There is more to check than a message is allowed (many certificates, or many ways to a + /// trusted authority): it was stopped before an answer. + TooMuch, +} + +impl Why { + /// Its name for an agent and a script. + pub fn as_str(self) -> &'static str { + match self { + Why::UnknownIssuer => "unknownIssuer", + Why::SelfSigned => "selfSigned", + Why::Expired => "expired", + Why::NotForEmail => "notForEmail", + Why::AddressMismatch => "addressMismatch", + Why::Constrained => "constrained", + Why::NoAuthorities => "noAuthorities", + Why::AuthoritiesNotRead => "authoritiesNotRead", + Why::KeyNotVerified => "keyNotVerified", + Why::PartlySigned => "partlySigned", + Why::Altered => "altered", + Why::WeakAlgorithm => "weakAlgorithm", + Why::UnknownAlgorithm => "unknownAlgorithm", + Why::NoPublicKey => "noPublicKey", + Why::KeyRevoked => "keyRevoked", + Why::KeyExpired => "keyExpired", + Why::NotASigningKey => "notASigningKey", + Why::SignatureExpired => "signatureExpired", + Why::Unreadable => "unreadable", + Why::NoOriginal => "noOriginal", + Why::TooMuch => "tooMuch", + } + } + + /// The plain English of it, for an agent, a script and the log; the window says it in its + /// own language. + pub fn english(self) -> &'static str { + match self { + Why::UnknownIssuer => "the certificate wasn't issued by a certification authority this computer trusts", + Why::SelfSigned => "the certificate signed itself and isn't one this computer trusts", + Why::Expired => "the certificate is out of date", + Why::NotForEmail => "the certificate isn't for signing mail", + Why::AddressMismatch => "the certificate is for another address than the sender's", + Why::Constrained => "an authority on the way to a trusted one doesn't allow the certificate to be used this way", + Why::NoAuthorities => "no certification authorities for mail could be read on this computer, so no signer can be verified here", + Why::AuthoritiesNotRead => "this computer's certification authorities haven't been read yet", + Why::KeyNotVerified => "the signer's key hasn't been marked verified", + Why::PartlySigned => "only part of the message was signed; the rest could say anything", + Why::Altered => "the message was changed after it was signed", + Why::WeakAlgorithm => "it uses an algorithm that's no longer safe", + Why::UnknownAlgorithm => "it uses an algorithm MailCraft doesn't know", + Why::NoPublicKey => "the signer's Public key (certificate) isn't in the message or kept on this computer", + Why::KeyRevoked => "the signer's key was revoked by its owner", + Why::KeyExpired => "the signer's key had expired when the message was signed", + Why::NotASigningKey => "the key that made it isn't one that may sign", + Why::SignatureExpired => "the Digital signature has expired", + Why::Unreadable => "the Digital signature can't be read", + Why::NoOriginal => "the bytes the message came as aren't on this computer; Check again downloads them", + Why::TooMuch => "there is too much to check in this Digital signature", + } + } +} + +/// Who signed, as the certificate or key says: the signer's own words, data and never +/// instructions. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Signer { + /// The name in the certificate (its common name) or key, if any. + pub name: String, + /// The addresses in the certificate or key, as they are written there, at most + /// [`MAX_SIGNER_ADDRESSES`]. + pub addresses: Vec, + /// The SHA-256 fingerprint of the certificate (or the fingerprint of the OpenPGP key), in + /// upper-case hexadecimal pairs with colons between. + pub fingerprint: String, + /// Who issued the certificate (its common name, else its whole name). Empty for OpenPGP. + pub issuer: String, + /// From and until when the certificate is valid; 0 when it doesn't say. + pub not_before: Timestamp, + pub not_after: Timestamp, +} + +/// How much of the message the Digital signature covers. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Coverage { + /// The whole message body: the signed part is the message's top level (S/MIME's + /// `multipart/signed` or signed data, PGP/MIME's `multipart/signed`). + Whole, + /// Only a part of it: the signed part sits inside a wrapper whose other parts nobody signed + /// (or a format that can't tell). The safe default. + #[default] + Part, +} + +impl Coverage { + pub fn as_str(self) -> &'static str { + match self { + Coverage::Whole => "whole", + Coverage::Part => "part", + } + } +} + +/// The most addresses of a signer that are kept. +pub const MAX_SIGNER_ADDRESSES: usize = 16; +/// The most characters of a name, an issuer or an address that are kept. +pub const MAX_SIGNER_TEXT: usize = 256; + +/// What checking a message's Digital signature found. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DigitalSignature { + pub format: SignatureFormat, + pub verdict: Verdict, + /// Why it is less than verified; `None` when it is verified. + pub why: Option, + /// Who signed, when the signer's certificate or key was found. + pub signer: Option, + /// When the signer says they signed it (S/MIME's signing time): the signer's word, not + /// checked by anybody. + pub signed_at: Option, + /// Whether the certificate was checked against its issuer's list of revoked certificates. + /// Never yet (#30 R7): the details say "Revocation not checked". + pub revocation_checked: bool, + /// How much of the message was signed; set with [`DigitalSignature::covering`]. + #[serde(default)] + pub coverage: Coverage, +} + +impl DigitalSignature { + /// A result of `verdict` for `why`, with nothing known of the signer. + pub fn bare(format: SignatureFormat, verdict: Verdict, why: Why) -> DigitalSignature { + DigitalSignature { format, verdict, why: Some(why), signer: None, signed_at: None, revocation_checked: false, coverage: Coverage::Part } + } + + /// This result for a signature that covers `coverage` of the message: a valid signature by a + /// trusted signer over only part of it is [`Verdict::NotVerified`] ([`Why::PartlySigned`]), + /// never verified for the message. Either format's checker ends with it. + pub fn covering(mut self, coverage: Coverage) -> DigitalSignature { + self.coverage = coverage; + if coverage == Coverage::Part && self.verdict == Verdict::Verified { + self.verdict = Verdict::NotVerified; + self.why = Some(Why::PartlySigned); + } + self + } +} + +/// `text` (a name or address from a certificate) as a name coming in is kept +/// ([`crate::names::incoming`]): one line, without control or format characters (no +/// reordering by a bidirectional override, nothing hidden by a zero-width one), at most +/// [`MAX_SIGNER_TEXT`] characters. +pub fn signer_text(text: &str) -> String { + crate::names::incoming(text, MAX_SIGNER_TEXT).unwrap_or_default() +} diff --git a/crates/smime/src/import.rs b/crates/smime/src/import.rs new file mode 100644 index 0000000000..216cfaa923 --- /dev/null +++ b/crates/smime/src/import.rs @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Certificates read from a file the owner imports as Public keys (#30): DER or PEM, what each +//! one is for, and whether the file holds a private key instead (which is never a Public key +//! to import, and goes through File › Options › Security in the window). No I/O; the file is +//! hostile: sizes and counts are capped, and nothing here panics on any bytes. + +use crate::Timestamp; +use base64::Engine as _; +use craft_ber as ber; + +use crate::cert::{Cert, MAX_CERT_BYTES, printable}; + +/// The most certificates read from one file. +pub const MAX_IMPORT_CERTIFICATES: usize = 16; +/// The most addresses a certificate is kept for. +const MAX_ADDRESSES: usize = 16; + +/// What a certificate to import says of itself. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CertificateInfo { + /// The certificate, in DER. + pub der: Vec, + /// Its SHA-256 fingerprint, as a Digital signature's details have it. + pub fingerprint: String, + /// The mail addresses it is for (subject alternative names, and an `emailAddress` in its + /// subject), in lower case: plain ASCII only, as a signer's address is compared. + pub addresses: Vec, + /// Until when it is valid. + pub not_after: Timestamp, + /// Whether it is for mail ([`Cert::for_mail`]). + pub for_mail: bool, + /// Whether it is a certification authority's. + pub authority: bool, + /// Who it is for (its subject's common name, else its whole subject), cleaned. + pub name: String, + /// Who issued it (the issuer's common name, else its whole name), cleaned. + pub issuer: String, +} + +/// What the certificate `der` says of itself; `None` when it isn't one. +pub fn certificate_info(der: &[u8]) -> Option { + let cert = Cert::from_der(der)?; + let mut addresses: Vec = Vec::new(); + for a in cert.raw_addresses() { + let a = a.to_ascii_lowercase(); + if printable(&a) && a.contains('@') && !addresses.contains(&a) && addresses.len() < MAX_ADDRESSES { + addresses.push(a); + } + } + Some(CertificateInfo { + der: cert.der().to_vec(), + fingerprint: cert.fingerprint(), + addresses, + not_after: cert.validity().1, + for_mail: cert.for_mail(), + authority: cert.is_authority(), + name: cert.name(), + issuer: cert.issuer_name(), + }) +} + +/// The certificates in `bytes`: PEM `CERTIFICATE` blocks (as many as there are, at most +/// [`MAX_IMPORT_CERTIFICATES`]), else one certificate in DER (or BER). Empty when there is none. +pub fn certificates_in(bytes: &[u8]) -> Vec> { + let blocks = pem_blocks(bytes, "CERTIFICATE"); + if !blocks.is_empty() { + return blocks.into_iter().filter(|b| Cert::from_der(b).is_some()).take(MAX_IMPORT_CERTIFICATES).collect(); + } + if bytes.len() > MAX_CERT_BYTES { + return Vec::new(); + } + match ber::to_der(bytes) { + Some(der) if Cert::from_der(&der).is_some() => vec![der], + _ => Vec::new(), + } +} + +/// The decoded bodies of the PEM blocks labelled `label` in `bytes` (RFC 7468), each at most a +/// certificate's size, at most [`MAX_IMPORT_CERTIFICATES`]. +fn pem_blocks(bytes: &[u8], label: &str) -> Vec> { + let text = String::from_utf8_lossy(bytes); + let begin = format!("-----BEGIN {label}-----"); + let end = format!("-----END {label}-----"); + let mut out = Vec::new(); + let mut body: Option = None; + for line in text.lines() { + let line = line.trim(); + match body.as_mut() { + None if line == begin => body = Some(String::new()), + None => {} + Some(b) if line == end => { + if let Ok(der) = base64::engine::general_purpose::STANDARD.decode(b.as_bytes()) + && der.len() <= MAX_CERT_BYTES + { + out.push(der); + } + body = None; + if out.len() >= MAX_IMPORT_CERTIFICATES { + break; + } + } + Some(b) => { + // (A header line of RFC 1421's kind is no base64: such a block won't decode.) + if !append_pem_line(b, line) { + body = None; + } + } + } + } + out +} + +/// Whether `bytes` hold a private key in a form S/MIME's tools write: a PEM block of any kind of +/// `PRIVATE KEY` (PKCS #8, encrypted or not, PKCS #1, SEC 1, OpenSSH, OpenPGP's armour too), a +/// PKCS #12 file, or a PKCS #8, PKCS #1 or SEC 1 key in DER. +pub fn holds_private_key(bytes: &[u8]) -> bool { + let text = String::from_utf8_lossy(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default()); + if text.lines().any(|l| { + let l = l.trim(); + l.starts_with("-----BEGIN ") && l.contains("PRIVATE KEY") + }) { + return true; + } + if crate::pkcs12::looks_like(bytes) { + return true; + } + let Some(der) = ber::to_der(bytes.get(..bytes.len().min(crate::pkcs12::MAX_P12_LEN)).unwrap_or_default()) else { return false }; + let Some((outer, _)) = ber::read(&der) else { return false }; + if outer.tag != 0x30 { + return false; + } + let Some(fields) = ber::children(outer.value) else { return false }; + let tags: Vec = fields.iter().map(|f| f.tag).collect(); + let first_int = |v: &[u8]| fields.first().is_some_and(|f| f.tag == 0x02 && f.value == v); + // PKCS #8 PrivateKeyInfo / OneAsymmetricKey: version, algorithm, the key in an OCTET STRING. + let pkcs8 = matches!(tags.as_slice(), [0x02, 0x30, 0x04, ..]) && (first_int(&[0]) || first_int(&[1])); + // EncryptedPrivateKeyInfo: algorithm, the encrypted key. + let encrypted = matches!(tags.as_slice(), [0x30, 0x04]); + // PKCS #1 RSAPrivateKey: version 0 and eight INTEGERs. + let rsa = tags.len() >= 9 && tags.iter().take(9).all(|t| *t == 0x02) && first_int(&[0]); + // SEC 1 ECPrivateKey: version 1, the key in an OCTET STRING. + let ec = matches!(tags.as_slice(), [0x02, 0x04, ..]) && first_int(&[1]); + pkcs8 || encrypted || rsa || ec +} + +// Check the prospective length before allocation, including a single oversized line. +fn append_pem_line(body: &mut String, line: &str) -> bool { + if body.len().checked_add(line.len()).is_none_or(|len| len > MAX_CERT_BYTES.saturating_mul(2)) { + return false; + } + body.push_str(line); + true +} + +#[cfg(test)] +mod bounded_pem_tests { + use super::*; + + #[test] + fn oversized_pem_lines_are_refused_before_accumulation() { + let cap = MAX_CERT_BYTES * 2; + let mut body = String::new(); + assert!(!append_pem_line(&mut body, &"A".repeat(cap + 1))); + assert!(body.is_empty()); + assert!(append_pem_line(&mut body, &"A".repeat(cap - 1))); + assert!(append_pem_line(&mut body, "A")); + assert!(!append_pem_line(&mut body, "A")); + assert_eq!(body.len(), cap); + } +} diff --git a/crates/smime/src/import_tests.rs b/crates/smime/src/import_tests.rs new file mode 100644 index 0000000000..2865dcbf3d --- /dev/null +++ b/crates/smime/src/import_tests.rs @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Certificates read for import, and private keys told apart (#30). The certificates are those +//! of `pkcs12_tests` (synthetic `example.org` people under a test authority), and one made for a +//! web server with Bob's key. + +use base64::Engine as _; +use proptest::prelude::*; + +use crate::import::{certificate_info, certificates_in, holds_private_key}; +use crate::pkcs12_tests::{ALICE_PEM, CA_PEM, MODERN}; + +/// Bob's key, certified for `www.example.org` and for serving the web only. +pub(crate) const SERVER_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIICeTCCAWGgAwIBAgITBZjuab1kWRuw6iskHm6GfE5XsDANBgkqhkiG9w0BAQsF\nADAsMRgwFgYDVQQDDA9FeGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUw\nIBcNMjYxMTEwMjM1NzM0WhgPMjEyNjEwMTcyMzU3MzRaMBYxFDASBgNVBAMMC0Jv\nYiBFeGFtcGxlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEVMGX6KffvBxXYqhk\nGl7wd0hrcjrtj18zbj1rN23ToDZ6d+Iy3rQQZvU5gCfqoP/scGZ9K377DvfqOzR8\n8VGPoKNzMHEwGgYDVR0RBBMwEYIPd3d3LmV4YW1wbGUub3JnMBMGA1UdJQQMMAoG\nCCsGAQUFBwMBMB0GA1UdDgQWBBQNf+WUyk2rA7Ol2+DplbqCmjDuOTAfBgNVHSME\nGDAWgBQDV2BK6ZYA5LKhPQiiQ98tSGv7JjANBgkqhkiG9w0BAQsFAAOCAQEAUlZu\nif7xv5ZXlsWt0KX458+G2vekBcqdE3UD21hTvJ9tbCrnfIuXa9pigZsYUzqV5Xwt\npaXU+7JedPYNZs0qqk2nPw+VULsxBNhaKre5V+v4tdHxq16MTsAalT6GfeOtX8+G\nZ5CwUqqe5SW9kkUi0QnaR/BDZuTKIOKKBCJ4AEOmi9cbDWUQiKkQRR4mEQH7wAJM\nfBXlNb7YHRikSE/ZHAjsLKNwSEpOsKnKav8KxPy/moR+emB9AFIHAsGjmPTMNhdG\nQ5DrRP3eAtKBGCrFGOj+JSxXW4O2eqKGuMHy7fLrCD2st7qBv4Lm7lEw1SDsXAQ/\nx1BBQKVBaJYfE2pKOA==\n-----END CERTIFICATE-----\n"; + +#[test] +fn certificates_are_read_from_pem_and_der() { + let both = format!("{ALICE_PEM}{CA_PEM}"); + let read = certificates_in(both.as_bytes()); + assert_eq!(read.len(), 2); + assert_eq!(certificates_in(&read[0]), vec![read[0].clone()], "DER"); + assert!(certificates_in(b"no certificate").is_empty()); + assert!(certificates_in(b"").is_empty()); +} + +#[test] +fn what_a_certificate_is_for_is_told() { + let alice = certificate_info(&certificates_in(ALICE_PEM.as_bytes())[0]).unwrap(); + assert_eq!(alice.addresses, vec!["alice@example.org".to_string()], "its alternative name and its subject's address, once"); + assert!(alice.for_mail); + assert!(!alice.authority); + assert_eq!(alice.fingerprint, "10:33:B4:36:A1:40:16:60:4A:21:D5:BC:F3:B1:69:38:60:22:DF:01:85:71:8D:BC:F5:BB:63:4B:09:CB:AA:FC"); + assert!(alice.not_after > 4_000_000_000); + let server = certificate_info(&certificates_in(SERVER_PEM.as_bytes())[0]).unwrap(); + assert!(!server.for_mail, "for the web only"); + assert!(server.addresses.is_empty()); + let ca = certificate_info(&certificates_in(CA_PEM.as_bytes())[0]).unwrap(); + assert!(ca.authority); + assert!(certificate_info(b"junk").is_none()); +} + +#[test] +fn a_private_key_in_any_form_is_told() { + for label in ["PRIVATE KEY", "ENCRYPTED PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY", "OPENSSH PRIVATE KEY", "PGP PRIVATE KEY BLOCK"] { + let pem = format!("-----BEGIN {label}-----\nAAAA\n-----END {label}-----\n"); + assert!(holds_private_key(pem.as_bytes()), "{label}"); + } + assert!(holds_private_key(&base64::engine::general_purpose::STANDARD.decode(MODERN).unwrap()), "a PKCS #12 file"); + // PKCS #8: version 0, an algorithm, the key in an OCTET STRING. + let pkcs8 = [0x30, 0x0b, 0x02, 0x01, 0x00, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00]; + assert!(holds_private_key(&pkcs8)); + // EncryptedPrivateKeyInfo. + assert!(holds_private_key(&[0x30, 0x08, 0x30, 0x03, 0x06, 0x01, 0x2a, 0x04, 0x01, 0x00])); + // SEC 1: version 1, the key. + assert!(holds_private_key(&[0x30, 0x06, 0x02, 0x01, 0x01, 0x04, 0x01, 0x07])); + // PKCS #1: nine INTEGERs, the first 0. + let mut rsa = vec![0x30, 27]; + for _ in 0..9 { + rsa.extend_from_slice(&[0x02, 0x01, 0x00]); + } + assert!(holds_private_key(&rsa)); + for public in [ALICE_PEM.as_bytes(), &certificates_in(ALICE_PEM.as_bytes())[0], b"-----BEGIN PGP PUBLIC KEY BLOCK-----", b""] { + assert!(!holds_private_key(public)); + } +} + +proptest! { + #[test] + fn any_bytes_are_read_without_a_panic(bytes in proptest::collection::vec(any::(), 0..2048)) { + let _ = certificates_in(&bytes); + let _ = certificate_info(&bytes); + let _ = holds_private_key(&bytes); + } +} diff --git a/crates/smime/src/lib.rs b/crates/smime/src/lib.rs new file mode 100644 index 0000000000..d9b5343890 --- /dev/null +++ b/crates/smime/src/lib.rs @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! MailCraft's S/MIME (RFC 8551): Digital signatures checked (#30), written from the public +//! specifications (RFC 5652 for CMS, RFC 5280 for X.509, RFC 5754, RFC 4055 and RFC 5480 for +//! the algorithms). No I/O: the host hands in the certificates it trusts ([`Anchors`]), the +//! message's halves come from `mailcraft-mime`, and the result is +//! [`crate::digital_signature::DigitalSignature`], which OpenPGP shares. +//! +//! [`check`] reads the CMS SignedData of a detached or an opaque Digital signature, finds the +//! signer's certificate, compares the signer's digest with the message's, checks the signature +//! (RSA PKCS #1 v1.5 or PSS of 2048 bits or more, ECDSA on P-256 or P-384, over SHA-2), and then +//! whether the certificate rests on a trust anchor, is for signing mail and is for the From +//! address. MD5 and SHA-1 are no longer safe and are said to be. Revocation isn't checked. +//! +//! Directory-name constraints currently support ASCII PrintableString/UTF8String names. +//! Constrained chains requiring other string profiles are refused, not approximately matched. +//! Opaque CMS content is verified as exact octets; only detached transport text permits LF repair. +//! +//! Input is hostile: BER is turned into DER with nesting bounded, every length is checked +//! against what is there, the certificates, signers and the path to an anchor are capped, and +//! nothing here panics on any bytes. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![cfg_attr(not(test), deny(clippy::indexing_slicing))] + +/// Seconds since the Unix epoch, UTC. +pub type Timestamp = i64; + +mod algorithms; +mod cert; +mod chain; +pub mod digital_signature; +pub mod import; +mod names; +pub mod pkcs12; +mod verify; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod import_tests; +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod pkcs12_tests; +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests; + +pub use chain::{Anchors, MAX_ANCHORS}; +pub use verify::{Checked, Context, MAX_CERTS, MAX_SIGNERS, MAX_VERIFICATIONS, Signed, check}; + +/// The fingerprint and addresses of a certificate in DER, as a Digital signature's details show +/// them: `None` when it isn't one. +pub fn certificate_summary(der: &[u8]) -> Option<(String, Vec, crate::Timestamp)> { + let cert = cert::Cert::from_der(der)?; + Some((cert.fingerprint(), cert.addresses(), cert.validity().1)) +} diff --git a/crates/smime/src/names.rs b/crates/smime/src/names.rs new file mode 100644 index 0000000000..f0ad2bad55 --- /dev/null +++ b/crates/smime/src/names.rs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Bounded certificate display-name sanitization extracted from MailCraft. + +/// Whether `c` is one of Unicode's format characters (general category Cf, Unicode 17.0): the +/// soft hyphen, the Arabic number signs and end-of-ayah marks, the Syriac abbreviation mark, the +/// Arabic pound and piastre marks above, the Mongolian vowel separator, zero-width marks and +/// joiners, bidirectional marks, embeddings, overrides and isolates, the word joiner and +/// invisible operators, the deprecated shaping controls, the byte-order mark, interlinear +/// annotations, the Kaithi number signs, the Egyptian hieroglyph, shorthand and musical format +/// controls, and tags. +pub fn is_format(c: char) -> bool { + matches!( + c, + '\u{00ad}' + | '\u{0600}'..='\u{0605}' + | '\u{061c}' + | '\u{06dd}' + | '\u{070f}' + | '\u{0890}'..='\u{0891}' + | '\u{08e2}' + | '\u{180e}' + | '\u{200b}'..='\u{200f}' + | '\u{202a}'..='\u{202e}' + | '\u{2060}'..='\u{2064}' + | '\u{2066}'..='\u{206f}' + | '\u{feff}' + | '\u{fff9}'..='\u{fffb}' + | '\u{110bd}' + | '\u{110cd}' + | '\u{13430}'..='\u{1343f}' + | '\u{1bca0}'..='\u{1bca3}' + | '\u{1d173}'..='\u{1d17a}' + | '\u{e0001}' + | '\u{e0020}'..='\u{e007f}' + ) +} + +/// Whether `c` is the zero-width non-joiner or joiner (U+200C, U+200D): format characters that +/// are part of a word where they stand inside one. +pub fn is_joiner(c: char) -> bool { + matches!(c, '\u{200c}' | '\u{200d}') +} + +/// A name as it is kept: one line (a line break, a tab or any other white space parts words, and +/// words are parted by one space), without control characters or the characters Unicode marks as +/// showing nothing (a joiner inside a word and one variation selector after a character stay), +/// trimmed, at most `max` characters. `None` when nothing is left. +pub fn incoming(text: &str, max: usize) -> Option { + let (name, _) = clean(text, max); + (!name.is_empty()).then_some(name) +} + +/// Whether `c` is one of the rest of Unicode's default-ignorable code points +/// (`Default_Ignorable_Code_Point`, Unicode 17.0, less the format characters and the variation +/// selectors): the combining grapheme joiner, the Hangul fillers, the Khmer inherent vowels, and +/// the code points Unicode keeps for more characters that show nothing. +fn is_ignorable(c: char) -> bool { + matches!( + c, + '\u{034f}' + | '\u{115f}'..='\u{1160}' + | '\u{17b4}'..='\u{17b5}' + | '\u{2065}' + | '\u{3164}' + | '\u{ffa0}' + | '\u{fff0}'..='\u{fff8}' + | '\u{e0000}' + | '\u{e0002}'..='\u{e001f}' + | '\u{e0080}'..='\u{e00ff}' + | '\u{e01f0}'..='\u{e0fff}' + ) +} + +/// Whether `c` is a variation selector (`Variation_Selector`, Unicode 17.0): it picks how the +/// character before it is drawn. +fn is_selector(c: char) -> bool { + matches!(c, '\u{180b}'..='\u{180d}' | '\u{180f}' | '\u{fe00}'..='\u{fe0f}' | '\u{e0100}'..='\u{e01ef}') +} + +/// The braille pattern blank: a symbol to Unicode, and in braille the space between words. +const BRAILLE_BLANK: char = '\u{2800}'; + +/// `text` cleaned and cut to at most `max` characters, and whether something was left out for +/// the length. Nothing past it is read. +fn clean(text: &str, max: usize) -> (String, bool) { + let mut out = String::new(); + let mut count = 0usize; + // A space between words, and a joiner inside one, come only with the character after them. + let mut space = false; + let mut joiner: Option = None; + // Whether the last character written shows, so that a variation selector may follow it. + let mut selectable = false; + for c in text.chars() { + if is_joiner(c) { + if count > 0 && !space { + joiner = Some(c); + } + } else if c.is_whitespace() || c == BRAILLE_BLANK { + space = count > 0; + joiner = None; + } else if is_selector(c) { + if selectable && !space && joiner.is_none() { + if count >= max { + return (out, true); + } + out.push(c); + count = count.saturating_add(1); + selectable = false; + } + } else if !c.is_control() && !is_format(c) && !is_ignorable(c) { + let needed = 1 + usize::from(space) + usize::from(joiner.is_some()); + if count.saturating_add(needed) > max { + return (out, true); + } + if std::mem::take(&mut space) { + out.push(' '); + } + if let Some(j) = joiner.take() { + out.push(j); + } + out.push(c); + count = count.saturating_add(needed); + selectable = true; + } + } + (out, false) +} diff --git a/crates/smime/src/pkcs12.rs b/crates/smime/src/pkcs12.rs new file mode 100644 index 0000000000..753a26dfba --- /dev/null +++ b/crates/smime/src/pkcs12.rs @@ -0,0 +1,794 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! A PKCS #12 file (`.p12`, `.pfx`; RFC 7292) opened with its passphrase (#30 R13): the +//! certificate and private key an owner's IT department hands out, for the window to put in the +//! system's credential store. No I/O, and nothing kept: what is opened goes back to the caller, +//! the private key in memory that is wiped when it is let go of. +//! +//! The file is believed only when its MAC checks with the passphrase (RFC 7292 §5.1, the +//! password-integrity mode, HMAC with SHA-1 or SHA-2 keyed by the PKCS #12 key derivation of +//! Appendix B): a file without one, or with a public-key integrity mode, is refused, and a MAC +//! that doesn't check is a wrong passphrase. The bags may be encrypted with PBES2 (RFC 8018: +//! PBKDF2 with HMAC-SHA-1 or SHA-2, and AES-128/192/256-CBC or 3DES-CBC) or with the old +//! pbeWithSHAAnd3-KeyTripleDES-CBC (RFC 7292 Appendix C); RC2, RC4, two-key 3DES, DES and the +//! 40-bit schemes are no longer safe and are refused. +//! +//! The file is hostile: its size, the bags, their nesting and every iteration count (and their +//! sum) are capped, lengths are checked against what is there, and nothing here panics on any +//! bytes. The cryptography is RustCrypto's (`pkcs12`'s key derivation, `pbkdf2`, `hmac`, `sha1`, +//! `sha2`, `aes`, `des`, `cbc`); only the layout is read here. + +use aes::cipher::block_padding::Pkcs7; +use aes::cipher::{BlockModeDecrypt, KeyIvInit}; +use const_oid::ObjectIdentifier; +use craft_ber::{self as ber, Tlv}; +use der::Decode; +use hmac::{KeyInit, Mac}; +use zeroize::Zeroizing; + +/// The largest file opened (the window reads at most as much). +pub const MAX_P12_LEN: usize = 1 << 20; +/// The most bags read, in all. +pub const MAX_BAGS: usize = 64; +/// The most iterations one key derivation may ask for: past it the file is refused as +/// unreasonable rather than spent time on. +pub const MAX_ITERATIONS: u64 = 1_000_000; +/// The most iterations every key derivation of one file may ask for together. +const MAX_TOTAL_ITERATIONS: u64 = 8_000_000; +/// How deep safe-contents bags may nest in each other. +const MAX_NESTING: usize = 4; +/// The most certificates kept from one file. +const MAX_CERTIFICATES: usize = 32; + +const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"); +const ENCRYPTED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.6"); +const KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.1"); +const SHROUDED_KEY_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.2"); +const CERT_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.3"); +const SAFE_CONTENTS_BAG: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.10.1.6"); +const X509_CERTIFICATE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.22.1"); +const LOCAL_KEY_ID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.21"); + +const SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.26"); +const SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"); +const SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"); +const SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3"); + +const PBES2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13"); +const PBKDF2: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.12"); +const HMAC_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.7"); +const HMAC_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.9"); +const HMAC_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.10"); +const HMAC_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.11"); +const AES128_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.2"); +const AES192_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.22"); +const AES256_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.42"); +const DES_EDE3_CBC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.3.7"); +const SHA_3DES: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.12.1.3"); +/// The PKCS #12 schemes that are no longer safe (RC4, two-key 3DES, RC2), and PKCS #5 v1.5's +/// (DES and RC2 with MD2, MD5 or SHA-1). +const WEAK: [&str; 11] = [ + "1.2.840.113549.1.12.1.1", + "1.2.840.113549.1.12.1.2", + "1.2.840.113549.1.12.1.4", + "1.2.840.113549.1.12.1.5", + "1.2.840.113549.1.12.1.6", + "1.2.840.113549.1.5.1", + "1.2.840.113549.1.5.3", + "1.2.840.113549.1.5.4", + "1.2.840.113549.1.5.6", + "1.2.840.113549.1.5.10", + "1.2.840.113549.1.5.11", +]; + +/// Why a PKCS #12 file couldn't be opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Larger than any such file is. + #[error("the file is larger than a certificate file can be")] + TooLarge, + /// Not a PKCS #12 file, or a damaged one. + #[error("the file isn't a certificate file (.p12 or .pfx) that can be read")] + Unreadable, + /// It has no MAC with a passphrase: nothing vouches that it is as it was made. + #[error("the file isn't protected with a passphrase, so nothing vouches for it")] + NoMac, + /// The MAC doesn't check: the passphrase is wrong (or the file was changed). + #[error("the passphrase is wrong")] + WrongPassphrase, + /// It is encrypted with a scheme that is no longer safe (RC2, RC4, DES, 40-bit keys). + #[error("the file is encrypted in a way that is no longer safe (RC2, RC4, DES or 40-bit keys); export it again with AES")] + WeakEncryption, + /// It uses an algorithm this program doesn't know. + #[error("the file uses an algorithm MailCraft doesn't know")] + UnknownAlgorithm, + /// It asks for more iterations than any file needs, or more bags or nesting than there is room for. + #[error("the file asks for more work than a certificate file needs")] + Unreasonable, + /// It holds no private key, or more than one. + #[error("the file holds no private key, or more than one")] + NoPrivateKey, + /// It holds no certificate for its private key. + #[error("the file holds no certificate for its private key")] + NoCertificate, +} + +/// What a PKCS #12 file holds, opened. +pub struct Opened { + /// The certificate of the private key, in DER: the one whose public key is the key's, else + /// the one with the key's local key id. + pub certificate: Vec, + /// The other certificates (the authorities on the way to a trusted one), in DER. + pub others: Vec>, + /// The private key as PKCS #8 `PrivateKeyInfo` in DER, wiped when let go of. + pub private_key: Zeroizing>, + /// What kind of key the private key is, read from its own PKCS #8 algorithm identifier (and + /// curve): whether it may be used here. The certificate is of the same kind. + pub key_kind: KeyKind, + /// Whether the private key was encrypted in the file (a shrouded key bag, or a bag in an + /// encrypted safe), and not merely vouched for by the MAC: a key in a plain key bag of a + /// plain safe is in the file in clear. + pub key_encrypted: bool, +} + +/// What kind of key a certificate holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyKind { + /// RSA, with a modulus of so many bits. + Rsa { bits: usize }, + /// ECDSA on NIST P-256. + P256, + /// ECDSA on NIST P-384. + P384, + /// Any other. + Other, +} + +impl std::fmt::Debug for Opened { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Opened") + .field("certificate", &self.certificate.len()) + .field("others", &self.others.len()) + .field("private_key", &"[redacted]") + .field("key_kind", &self.key_kind) + .field("key_encrypted", &self.key_encrypted) + .finish() + } +} + +/// Whether `bytes` look like a PKCS #12 file (a version 3 PFX), without opening it: so that a +/// private key is never taken for a Public key to import. +pub fn looks_like(bytes: &[u8]) -> bool { + let Some(der) = ber::to_der(bytes.get(..bytes.len().min(MAX_P12_LEN)).unwrap_or_default()).map(Zeroizing::new) else { return false }; + let Some((pfx, _)) = ber::read(&der) else { return false }; + let Some(fields) = ber::children(pfx.value) else { return false }; + matches!(fields.as_slice(), [version, info, ..] if version.tag == 0x02 && version.value == [3] && info.tag == 0x30) +} + +/// Open the PKCS #12 file `p12` with `passphrase`. +pub fn open(p12: &[u8], passphrase: &str) -> Result { + if p12.len() > MAX_P12_LEN { + return Err(Error::TooLarge); + } + let der = Zeroizing::new(ber::to_der(p12).ok_or(Error::Unreadable)?); + let (pfx, rest) = ber::read(&der).ok_or(Error::Unreadable)?; + if pfx.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + let fields = ber::children(pfx.value).ok_or(Error::Unreadable)?; + let (version, auth_safe, mac) = match fields.as_slice() { + [v, a, m] => (v, a, Some(m)), + [v, a] => (v, a, None), + _ => return Err(Error::Unreadable), + }; + if version.tag != 0x02 || version.value != [3] { + return Err(Error::Unreadable); + } + let mut work = Work { iterations: 0, bags: 0 }; + // Only the password-integrity mode: the authenticated safe is data, and the MAC is over it. + let (content_type, content) = content_info(auth_safe)?; + if content_type != DATA { + return Err(Error::NoMac); + } + let safe = Zeroizing::new(octets(content)?); + let mac = mac.ok_or(Error::NoMac)?; + let legacy_password = check_mac(mac, &safe, passphrase, &mut work)?; + let safe = Zeroizing::new(ber::to_der(&safe).ok_or(Error::Unreadable)?); + let mut found = Found::default(); + let (list, rest) = ber::read(&safe).ok_or(Error::Unreadable)?; + if list.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + for info in ber::children(list.value).ok_or(Error::Unreadable)? { + let (kind, content) = content_info(&info)?; + let (contents, encrypted) = if kind == DATA { + (Zeroizing::new(octets(content)?), false) + } else if kind == ENCRYPTED_DATA { + (encrypted_data(content, passphrase, &legacy_password, &mut work)?, true) + } else { + // (Enveloped data, which needs a key of the owner's to open: not a file to import.) + return Err(Error::UnknownAlgorithm); + }; + safe_contents(&contents, Safe { passphrase, legacy_password: &legacy_password, encrypted, depth: 0 }, &mut work, &mut found)?; + } + found.finish() +} + +/// What opening costs so far. +struct Work { + iterations: u64, + bags: usize, +} + +impl Work { + /// Count a key derivation of `iterations`: refused past the caps. + fn derive(&mut self, iterations: u64) -> Result<(), Error> { + if iterations == 0 || iterations > MAX_ITERATIONS { + return Err(Error::Unreasonable); + } + self.iterations = self.iterations.saturating_add(iterations); + if self.iterations > MAX_TOTAL_ITERATIONS { Err(Error::Unreasonable) } else { Ok(()) } + } +} + +/// A private-key bag and whether it was encrypted. +struct KeyBag { + key: Zeroizing>, + encrypted: bool, +} + +/// The bags found. +#[derive(Default)] +struct Found { + /// Each private key and whether it was encrypted in the file. + keys: Vec, + certificates: Vec<(Vec, Option>)>, +} + +impl Found { + /// Pair only by verified public key, never by untrusted bag metadata. + fn finish(mut self) -> Result { + let KeyBag { key, encrypted: key_encrypted } = match self.keys.len() { + 1 => self.keys.pop().ok_or(Error::NoPrivateKey)?, + _ => return Err(Error::NoPrivateKey), + }; + let key_kind = private_key_kind(&key); + let kind_of = |c: &[u8]| crate::cert::Cert::from_der(c).map_or(KeyKind::Other, |c| crate::algorithms::key_kind(c.public_key())); + let public = public_of(&key); + let by_key = public.as_ref().and_then(|p| self.certificates.iter().position(|(c, _)| certificate_key(c).as_ref() == Some(p))); + // localKeyId is untrusted metadata, not proof of key ownership. + let at = by_key.ok_or(Error::NoCertificate)?; + let (certificate, _) = self.certificates.remove(at); + if kind_of(&certificate) != key_kind { + return Err(Error::NoCertificate); + } + Ok(Opened { certificate, others: self.certificates.into_iter().map(|(c, _)| c).collect(), private_key: key, key_kind, key_encrypted }) + } +} + +/// What kind of key a PKCS #8 `PrivateKeyInfo` is, by its own algorithm identifier: RSA by its +/// modulus, EC by its named curve (the identifier's parameters, else the `ECPrivateKey`'s own). +fn private_key_kind(pkcs8: &[u8]) -> KeyKind { + let read = || -> Option { + let (info, _) = ber::read(pkcs8)?; + let fields = ber::children(info.value)?; + let [_, alg, key, ..] = fields.as_slice() else { return None }; + if key.tag != 0x04 { + return None; + } + let (oid, params) = algorithm(alg).ok()?; + let (inner, _) = ber::read(key.value)?; + let parts = ber::children(inner.value)?; + let curve_of = |t: &Tlv<'_>| oid_of(t).ok(); + let curve = params.as_ref().and_then(curve_of).or_else(|| { + // ECPrivateKey (RFC 5915): [0] parameters, a named curve. + let explicit = parts.iter().find(|p| p.tag == 0xa0)?; + let (named, _) = ber::read(explicit.value)?; + curve_of(&named) + }); + // RSAPrivateKey (RFC 8017 A.1.2): version, modulus, … + let modulus = parts.get(1).filter(|n| n.tag == 0x02).map(|n| n.value); + Some(crate::algorithms::private_key_kind(oid, curve, modulus)) + }; + read().unwrap_or(KeyKind::Other) +} + +/// A ContentInfo's type and content (inside its `[0] EXPLICIT`). +fn content_info<'a>(info: &Tlv<'a>) -> Result<(ObjectIdentifier, Tlv<'a>), Error> { + if info.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(info.value).ok_or(Error::Unreadable)?; + let [oid, explicit] = fields.as_slice() else { return Err(Error::Unreadable) }; + if explicit.tag != 0xa0 { + return Err(Error::Unreadable); + } + let (content, rest) = ber::read(explicit.value).ok_or(Error::Unreadable)?; + if !rest.is_empty() { + return Err(Error::Unreadable); + } + Ok((oid_of(oid)?, content)) +} + +fn oid_of(tlv: &Tlv<'_>) -> Result { + if tlv.tag != 0x06 { + return Err(Error::Unreadable); + } + ObjectIdentifier::from_der(tlv.whole).map_err(|_| Error::Unreadable) +} + +/// An OCTET STRING's octets: in one piece, or (BER) in pieces under a constructed tag. +fn octets(tlv: Tlv<'_>) -> Result, Error> { + match tlv.tag { + 0x04 | 0x80 => Ok(tlv.value.to_vec()), + 0x24 | 0xa0 => { + let mut out = Vec::new(); + for piece in ber::children(tlv.value).ok_or(Error::Unreadable)? { + if piece.tag != 0x04 { + return Err(Error::Unreadable); + } + out.extend_from_slice(piece.value); + } + Ok(out) + } + _ => Err(Error::Unreadable), + } +} + +/// An INTEGER that fits, not negative. +fn uint(tlv: &Tlv<'_>) -> Result { + if tlv.tag != 0x02 || tlv.value.is_empty() || tlv.value.len() > 9 || tlv.value.first().is_some_and(|b| b & 0x80 != 0) { + return Err(Error::Unreasonable); + } + let digits = tlv.value.strip_prefix(&[0]).unwrap_or(tlv.value); + if digits.len() > 8 { + return Err(Error::Unreasonable); + } + Ok(digits.iter().fold(0u64, |acc, d| (acc << 8) | u64::from(*d))) +} + +/// An AlgorithmIdentifier: its OID and its parameters, if any. +fn algorithm<'a>(tlv: &Tlv<'a>) -> Result<(ObjectIdentifier, Option>), Error> { + if tlv.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(tlv.value).ok_or(Error::Unreadable)?; + match fields.as_slice() { + [oid] => Ok((oid_of(oid)?, None)), + [oid, params] => Ok((oid_of(oid)?, (params.tag != 0x05).then_some(*params))), + _ => Err(Error::Unreadable), + } +} + +/// The hashes a MAC or a key derivation is made with. +#[derive(Clone, Copy)] +enum Hash { + Sha1, + Sha256, + Sha384, + Sha512, +} + +impl Hash { + fn digest(oid: ObjectIdentifier) -> Result { + Ok(match oid { + SHA1 => Hash::Sha1, + SHA256 => Hash::Sha256, + SHA384 => Hash::Sha384, + SHA512 => Hash::Sha512, + _ => return Err(Error::UnknownAlgorithm), + }) + } + + fn hmac(oid: ObjectIdentifier) -> Result { + Ok(match oid { + HMAC_SHA1 => Hash::Sha1, + HMAC_SHA256 => Hash::Sha256, + HMAC_SHA384 => Hash::Sha384, + HMAC_SHA512 => Hash::Sha512, + _ => return Err(Error::UnknownAlgorithm), + }) + } + + fn len(self) -> usize { + match self { + Hash::Sha1 => 20, + Hash::Sha256 => 32, + Hash::Sha384 => 48, + Hash::Sha512 => 64, + } + } + + /// The PKCS #12 key derivation (RFC 7292 Appendix B.2) of `len` bytes for `purpose`. + fn pkcs12_kdf(self, password: &[u8], salt: &[u8], purpose: Purpose, iterations: u64, len: usize) -> Result>, Error> { + use pkcs12::kdf::{Pkcs12KeyType, derive_key}; + let id = match purpose { + Purpose::Key => Pkcs12KeyType::EncryptionKey, + Purpose::Iv => Pkcs12KeyType::Iv, + Purpose::Mac => Pkcs12KeyType::Mac, + }; + let rounds = i32::try_from(iterations).map_err(|_| Error::Unreasonable)?; + let out = match self { + Hash::Sha1 => derive_key::(password, salt, id, rounds, len), + Hash::Sha256 => derive_key::(password, salt, id, rounds, len), + Hash::Sha384 => derive_key::(password, salt, id, rounds, len), + Hash::Sha512 => derive_key::(password, salt, id, rounds, len), + }; + out.map(Zeroizing::new).map_err(|_| Error::Unreadable) + } + + /// Whether the HMAC of `data` under `key` is `tag`, in constant time. + fn hmac_checks(self, key: &[u8], data: &[u8], tag: &[u8]) -> bool { + fn check(key: &[u8], data: &[u8], tag: &[u8]) -> bool { + match ::new_from_slice(key) { + Ok(mut mac) => { + mac.update(data); + mac.verify_slice(tag).is_ok() + } + Err(_) => false, + } + } + match self { + Hash::Sha1 => check::>(key, data, tag), + Hash::Sha256 => check::>(key, data, tag), + Hash::Sha384 => check::>(key, data, tag), + Hash::Sha512 => check::>(key, data, tag), + } + } + + fn pbkdf2(self, password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) { + match self { + Hash::Sha1 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, out), + Hash::Sha256 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, out), + Hash::Sha384 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, out), + Hash::Sha512 => pbkdf2::pbkdf2_hmac::(password, salt, iterations, out), + } + } +} + +#[derive(Clone, Copy)] +enum Purpose { + Key, + Iv, + Mac, +} + +/// The passphrase as the PKCS #12 key derivation takes it (RFC 7292 Appendix B.1): a BMPString, +/// two bytes to a character, ended by two zero bytes. `None` for a character outside the BMP. +fn bmp(passphrase: &str) -> Option>> { + let mut out = Zeroizing::new(Vec::with_capacity(passphrase.len().saturating_mul(2).saturating_add(2))); + for c in passphrase.chars() { + let unit = u16::try_from(u32::from(c)).ok()?; + out.extend_from_slice(&unit.to_be_bytes()); + } + out.extend_from_slice(&[0, 0]); + Some(out) +} + +/// The forms of the passphrase a file may have been made with: the BMPString, and for an empty +/// one also nothing at all (which some writers use). +fn passwords(passphrase: &str) -> Vec>> { + let mut out: Vec>> = bmp(passphrase).into_iter().collect(); + if passphrase.is_empty() { + out.push(Zeroizing::new(Vec::new())); + } + out +} + +/// Check the file's MAC (RFC 7292 §5.1, Appendix B.4) over `safe`. +fn check_mac(mac: &Tlv<'_>, safe: &[u8], passphrase: &str, work: &mut Work) -> Result>, Error> { + if mac.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(mac.value).ok_or(Error::Unreadable)?; + let (digest_info, salt, iterations) = match fields.as_slice() { + [d, s] => (d, s, 1), + [d, s, i] => (d, s, uint(i)?), + _ => return Err(Error::Unreadable), + }; + if digest_info.tag != 0x30 || salt.tag != 0x04 { + return Err(Error::Unreadable); + } + let parts = ber::children(digest_info.value).ok_or(Error::Unreadable)?; + let [alg, digest] = parts.as_slice() else { return Err(Error::Unreadable) }; + if digest.tag != 0x04 { + return Err(Error::Unreadable); + } + let (oid, _) = algorithm(alg)?; + let hash = Hash::digest(oid)?; + if digest.value.len() != hash.len() { + return Err(Error::Unreadable); + } + for password in passwords(passphrase) { + work.derive(iterations)?; + let key = hash.pkcs12_kdf(&password, salt.value, Purpose::Mac, iterations, hash.len())?; + if hash.hmac_checks(&key, safe, digest.value) { + return Ok(password); + } + } + Err(Error::WrongPassphrase) +} + +/// The contents of an EncryptedData (RFC 5652 §8), decrypted. +fn encrypted_data(content: Tlv<'_>, passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result>, Error> { + if content.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(content.value).ok_or(Error::Unreadable)?; + let info = fields.get(1).ok_or(Error::Unreadable)?; + if info.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(info.value).ok_or(Error::Unreadable)?; + let [kind, alg, encrypted] = parts.as_slice() else { return Err(Error::Unreadable) }; + if oid_of(kind)? != DATA { + return Err(Error::Unreadable); + } + let ciphertext = octets(*encrypted)?; + decrypt(alg, &ciphertext, passphrase, legacy_password, work) +} + +/// `ciphertext` decrypted with the passphrase as the algorithm identifier `alg` says. +fn decrypt(alg: &Tlv<'_>, ciphertext: &[u8], passphrase: &str, legacy_password: &[u8], work: &mut Work) -> Result>, Error> { + let (oid, params) = algorithm(alg)?; + if WEAK.iter().any(|w| oid.to_string() == *w) { + return Err(Error::WeakEncryption); + } + let params = params.ok_or(Error::Unreadable)?; + if oid == SHA_3DES { + // RFC 7292 Appendix C: pkcs-12PbeParams, the key and IV from the PKCS #12 derivation. + let fields = ber::children(params.value).ok_or(Error::Unreadable)?; + let [salt, iterations] = fields.as_slice() else { return Err(Error::Unreadable) }; + if salt.tag != 0x04 { + return Err(Error::Unreadable); + } + let iterations = uint(iterations)?; + // Reuse the exact representation authenticated by the MAC, including empty bytes. + let password = legacy_password; + work.derive(iterations)?; + let key = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Key, iterations, 24)?; + work.derive(iterations)?; + let iv = Hash::Sha1.pkcs12_kdf(password, salt.value, Purpose::Iv, iterations, 8)?; + return cbc_decrypt::(&key, &iv, ciphertext); + } + if oid != PBES2 { + return Err(Error::UnknownAlgorithm); + } + let fields = ber::children(params.value).ok_or(Error::Unreadable)?; + let [kdf, scheme] = fields.as_slice() else { return Err(Error::Unreadable) }; + let (kdf_oid, kdf_params) = algorithm(kdf)?; + if kdf_oid != PBKDF2 { + return Err(Error::UnknownAlgorithm); + } + let kdf_fields = ber::children(kdf_params.ok_or(Error::Unreadable)?.value).ok_or(Error::Unreadable)?; + let mut kdf_fields = kdf_fields.iter(); + let salt = kdf_fields.next().filter(|s| s.tag == 0x04).ok_or(Error::UnknownAlgorithm)?; + let iterations = uint(kdf_fields.next().ok_or(Error::Unreadable)?)?; + let mut prf = Hash::Sha1; + let mut key_length: Option = None; + for field in kdf_fields { + match field.tag { + 0x02 if key_length.is_none() => key_length = Some(uint(field)?), + 0x30 => prf = Hash::hmac(algorithm(field)?.0)?, + _ => return Err(Error::Unreadable), + } + } + let (cipher, iv) = algorithm(scheme)?; + let iv = iv.filter(|v| v.tag == 0x04).ok_or(Error::Unreadable)?; + let size = match cipher { + AES128_CBC => 16, + AES192_CBC => 24, + AES256_CBC => 32, + DES_EDE3_CBC => 24, + _ => return Err(Error::UnknownAlgorithm), + }; + if key_length.is_some_and(|l| l != size as u64) { + return Err(Error::Unreadable); + } + work.derive(iterations)?; + let rounds = u32::try_from(iterations).map_err(|_| Error::Unreasonable)?; + let mut key = Zeroizing::new(vec![0u8; size]); + // (RFC 8018 takes the passphrase as octets: its UTF-8, as the writers do.) + prf.pbkdf2(passphrase.as_bytes(), salt.value, rounds, &mut key); + match cipher { + AES128_CBC => cbc_decrypt::(&key, iv.value, ciphertext), + AES192_CBC => cbc_decrypt::(&key, iv.value, ciphertext), + AES256_CBC => cbc_decrypt::(&key, iv.value, ciphertext), + _ => cbc_decrypt::(&key, iv.value, ciphertext), + } +} + +/// `ciphertext` decrypted in CBC mode with PKCS #7 padding. A wrong key shows as bad padding, +/// which is said as a wrong passphrase (the MAC has checked by then, so it seldom is). +fn cbc_decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result>, Error> +where + C: aes::cipher::BlockCipherDecrypt + aes::cipher::KeyInit, + cbc::Decryptor: KeyIvInit + BlockModeDecrypt, +{ + let decryptor = cbc::Decryptor::::new_from_slices(key, iv).map_err(|_| Error::Unreadable)?; + let mut buffer = Zeroizing::new(ciphertext.to_vec()); + let len = decryptor.decrypt_padded::(&mut buffer).map_err(|_| Error::WrongPassphrase)?.len(); + buffer.truncate(len); + Ok(buffer) +} + +/// Where a SafeContents is: the passphrase, whether it came out of an encrypted safe, and how +/// deep in other bags. +#[derive(Clone, Copy)] +struct Safe<'a> { + passphrase: &'a str, + legacy_password: &'a [u8], + encrypted: bool, + depth: usize, +} + +/// The bags of a SafeContents, into `found`. +fn safe_contents(bytes: &[u8], safe: Safe<'_>, work: &mut Work, found: &mut Found) -> Result<(), Error> { + let Safe { passphrase, legacy_password, encrypted, depth } = safe; + if depth > MAX_NESTING { + return Err(Error::Unreasonable); + } + let der = Zeroizing::new(ber::to_der(bytes).ok_or(Error::Unreadable)?); + let (list, rest) = ber::read(&der).ok_or(Error::Unreadable)?; + if list.tag != 0x30 || !rest.is_empty() { + return Err(Error::Unreadable); + } + for bag in ber::children(list.value).ok_or(Error::Unreadable)? { + work.bags = work.bags.saturating_add(1); + if work.bags > MAX_BAGS { + return Err(Error::Unreasonable); + } + if bag.tag != 0x30 { + return Err(Error::Unreadable); + } + let fields = ber::children(bag.value).ok_or(Error::Unreadable)?; + let (kind, value, attributes) = match fields.as_slice() { + [k, v] => (k, v, None), + [k, v, a] => (k, v, Some(a)), + _ => return Err(Error::Unreadable), + }; + if value.tag != 0xa0 { + return Err(Error::Unreadable); + } + let (value, rest) = ber::read(value.value).ok_or(Error::Unreadable)?; + if !rest.is_empty() { + return Err(Error::Unreadable); + } + let key_id = attributes.and_then(local_key_id); + match oid_of(kind)? { + KEY_BAG => found.keys.push(KeyBag { key: Zeroizing::new(value.whole.to_vec()), encrypted }), + SHROUDED_KEY_BAG => { + // EncryptedPrivateKeyInfo (RFC 5958 §3). + if value.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(value.value).ok_or(Error::Unreadable)?; + let [alg, data] = parts.as_slice() else { return Err(Error::Unreadable) }; + let ciphertext = octets(*data)?; + let key = decrypt(alg, &ciphertext, passphrase, legacy_password, work)?; + if ber::read(&key).is_none_or(|(k, rest)| k.tag != 0x30 || !rest.is_empty()) { + return Err(Error::WrongPassphrase); + } + found.keys.push(KeyBag { key, encrypted: true }); + } + CERT_BAG => { + if value.tag != 0x30 { + return Err(Error::Unreadable); + } + let parts = ber::children(value.value).ok_or(Error::Unreadable)?; + let [cert_kind, cert] = parts.as_slice() else { return Err(Error::Unreadable) }; + // (SDSI certificates are of no use for mail: left out.) + if oid_of(cert_kind)? != X509_CERTIFICATE || cert.tag != 0xa0 { + continue; + } + let (octet, _) = ber::read(cert.value).ok_or(Error::Unreadable)?; + let der = ber::to_der(&octets(octet)?).ok_or(Error::Unreadable)?; + if found.certificates.len() < MAX_CERTIFICATES && crate::cert::Cert::from_der(&der).is_some() { + found.certificates.push((der, key_id)); + } + } + SAFE_CONTENTS_BAG => safe_contents(value.whole, Safe { depth: depth.saturating_add(1), ..safe }, work, found)?, + // CRLs and secrets: of no use here. + _ => {} + } + } + Ok(()) +} + +/// A bag's localKeyId attribute (PKCS #9), when it has one. +fn local_key_id(attributes: &Tlv<'_>) -> Option> { + for attribute in ber::children(attributes.value)? { + let parts = ber::children(attribute.value)?; + let [oid, values] = parts.as_slice() else { continue }; + if oid_of(oid).ok()? == LOCAL_KEY_ID { + let (value, _) = ber::read(values.value)?; + return (value.tag == 0x04).then(|| value.value.to_vec()); + } + } + None +} + +/// What of a private key (PKCS #8) its certificate's public key must match: an RSA key's modulus +/// and exponent as `RSAPublicKey`, an EC key's public point derived from its scalar. +fn public_of(pkcs8: &[u8]) -> Option> { + let (info, _) = ber::read(pkcs8)?; + let fields = ber::children(info.value)?; + let [_, alg, key, ..] = fields.as_slice() else { return None }; + if key.tag != 0x04 { + return None; + } + let (oid, _) = algorithm(alg).ok()?; + let (inner, _) = ber::read(key.value)?; + let parts = ber::children(inner.value)?; + if oid.to_string() == "1.2.840.113549.1.1.1" { + // RSAPrivateKey (RFC 8017 A.1.2): version, modulus, publicExponent, … + let [_, n, e, ..] = parts.as_slice() else { return None }; + let mut body = n.whole.to_vec(); + body.extend_from_slice(e.whole); + return Some(rsa_public(&body)); + } + // RFC 5915 makes the public point optional. Derive it from the private scalar, + // and refuse an inconsistent supplied point rather than trusting bag metadata. + let scalar = parts.get(1).filter(|p| p.tag == 0x04)?.value; + let supplied = parts.iter().find(|p| p.tag == 0xa1).map(|p| { + let (bits, rest) = ber::read(p.value)?; + if !rest.is_empty() || bits.tag != 0x03 || bits.value.first() != Some(&0) { + return None; + } + bits.value.get(1..) + }); + use p256::elliptic_curve::sec1::ToSec1Point; + let point = match private_key_kind(pkcs8) { + KeyKind::P256 => { + let public = p256::SecretKey::from_slice(scalar).ok()?.public_key(); + if let Some(encoded) = supplied + && p256::PublicKey::from_sec1_bytes(encoded?).ok()? != public + { + return None; + } + public.to_sec1_point(false).as_bytes().to_vec() + } + KeyKind::P384 => { + let public = p384::SecretKey::from_slice(scalar).ok()?.public_key(); + if let Some(encoded) = supplied + && p384::PublicKey::from_sec1_bytes(encoded?).ok()? != public + { + return None; + } + public.to_sec1_point(false).as_bytes().to_vec() + } + _ => return None, + }; + let mut bits = vec![0]; + bits.extend(point); + Some(bits) +} + +/// `RSAPublicKey ::= SEQUENCE { modulus, publicExponent }` around `body`. +fn rsa_public(body: &[u8]) -> Vec { + let mut out = vec![0x30]; + let len = body.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect(); + out.push(0x80 | bytes.len() as u8); + out.extend(bytes); + } + out.extend_from_slice(body); + out +} + +/// A certificate's public key as [`public_of`] gives it: the subjectPublicKey's bits. +fn certificate_key(der: &[u8]) -> Option> { + let cert = crate::cert::Cert::from_der(der)?; + let spki = cert.public_key(); + let bits = spki.subject_public_key.as_bytes()?; + if spki.algorithm.oid.to_string() == "1.2.840.113549.1.1.1" { + return Some(bits.to_vec()); + } + // (An EC point: the BIT STRING's octets, after its unused-bits byte, as `public_of` gives.) + let mut with_unused = vec![0u8]; + with_unused.extend_from_slice(bits); + Some(with_unused) +} diff --git a/crates/smime/src/pkcs12_tests.rs b/crates/smime/src/pkcs12_tests.rs new file mode 100644 index 0000000000..1d640ecd74 --- /dev/null +++ b/crates/smime/src/pkcs12_tests.rs @@ -0,0 +1,568 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! PKCS #12 files opened (#30 R13). The files were made with OpenSSL 3 for synthetic +//! `example.org` people (an RSA key for Alice, a P-256 key for Bob, both under a test authority +//! made for these tests alone), with the passphrase `example-pass`: +//! `openssl pkcs12 -export` (PBES2, AES-256-CBC, HMAC-SHA-256), with `-keypbe PBE-SHA1-3DES +//! -certpbe PBE-SHA1-3DES -macalg sha1` (the old scheme), `-legacy` (RC2-40), `-nomac`, +//! `-keypbe AES-128-CBC -certpbe NONE -macalg sha512` (Bob's), `-passout pass:` (no passphrase) +//! and `-iter 2000000`. + +use base64::Engine as _; +use proptest::prelude::*; + +use crate::pkcs12::{Error, KeyKind, MAX_P12_LEN, looks_like, open}; + +const PASS: &str = "example-pass"; + +fn bytes(b64: &str) -> Vec { + base64::engine::general_purpose::STANDARD.decode(b64).unwrap() +} + +fn der(pem: &str) -> Vec { + crate::import::certificates_in(pem.as_bytes()).remove(0) +} + +#[test] +fn a_modern_file_opens_with_its_certificate_its_authority_and_its_key() { + let opened = open(&bytes(MODERN), PASS).unwrap(); + assert_eq!(opened.certificate, der(ALICE_PEM)); + assert_eq!(opened.others, vec![der(CA_PEM)]); + assert_eq!(opened.key_kind, KeyKind::Rsa { bits: 2048 }, "RSA keys aren't used here: the window is told"); + // PKCS #8 PrivateKeyInfo, RSA. + assert_eq!(opened.private_key.first(), Some(&0x30)); + assert!(opened.private_key.windows(9).any(|w| w == [0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01])); + // Never shown, even in a log. + let shown = format!("{opened:?}"); + assert!(shown.contains("redacted"), "{shown}"); + assert!(!shown.contains("48, 130"), "{shown}"); +} + +#[test] +fn the_old_triple_des_scheme_opens() { + let opened = open(&bytes(LEGACY), PASS).unwrap(); + assert_eq!(opened.certificate, der(ALICE_PEM)); + assert_eq!(opened.others.len(), 1); +} + +#[test] +fn an_ec_key_finds_its_certificate_by_its_public_key() { + let opened = open(&bytes(EC), PASS).unwrap(); + let info = crate::import::certificate_info(&opened.certificate).unwrap(); + assert_eq!(info.addresses, vec!["bob@example.org".to_string()]); + assert_eq!(opened.key_kind, KeyKind::P256); + assert!(opened.others.is_empty()); +} + +#[test] +fn a_file_with_no_passphrase_opens_with_none() { + assert!(open(&bytes(EMPTY), "").is_ok()); + assert_eq!(open(&bytes(EMPTY), PASS).err(), Some(Error::WrongPassphrase)); +} + +#[test] +fn a_wrong_passphrase_is_said_as_one() { + for file in [MODERN, LEGACY, EC] { + assert_eq!(open(&bytes(file), "wrong").err(), Some(Error::WrongPassphrase)); + } + // A passphrase with a character past the BMP can't be one a file was made with. + assert_eq!(open(&bytes(MODERN), "\u{1F600}").err(), Some(Error::WrongPassphrase)); +} + +#[test] +fn a_changed_file_fails_its_mac() { + let mut file = bytes(MODERN); + // The MAC's digest is near the end: change its last byte, then a byte of the content. + let last = file.len() - 30; + file[last] ^= 1; + assert_eq!(open(&file, PASS).err(), Some(Error::WrongPassphrase)); + let mut file = bytes(MODERN); + file[200] ^= 0x40; + assert!(open(&file, PASS).is_err()); +} + +#[test] +fn what_is_no_longer_safe_or_unvouched_for_is_refused() { + assert_eq!(open(&bytes(RC2), PASS).err(), Some(Error::WeakEncryption)); + assert_eq!(open(&bytes(NO_MAC), PASS).err(), Some(Error::NoMac)); + assert_eq!(open(&bytes(SLOW), PASS).err(), Some(Error::Unreasonable)); + assert_eq!(open(&vec![0x30; MAX_P12_LEN + 1], PASS).err(), Some(Error::TooLarge)); + assert_eq!(open(b"not a file", PASS).err(), Some(Error::Unreadable)); + assert_eq!(open(ALICE_PEM.as_bytes(), PASS).err(), Some(Error::Unreadable)); +} + +#[test] +fn a_pkcs12_file_is_told_from_a_certificate() { + for file in [MODERN, LEGACY, RC2, NO_MAC, EC] { + assert!(looks_like(&bytes(file))); + } + assert!(!looks_like(&der(ALICE_PEM))); + assert!(!looks_like(b"")); +} + +/// A DER element of `tag` around `content`. +fn tlv(tag: u8, content: &[u8]) -> Vec { + let mut out = vec![tag]; + let len = content.len(); + if len < 0x80 { + out.push(len as u8); + } else { + let bytes: Vec = len.to_be_bytes().into_iter().skip_while(|b| *b == 0).collect(); + out.push(0x80 | bytes.len() as u8); + out.extend(bytes); + } + out.extend_from_slice(content); + out +} + +fn seq(parts: &[Vec]) -> Vec { + tlv(0x30, &parts.concat()) +} + +fn oid(dotted: &str) -> Vec { + use der::Encode; + const_oid::ObjectIdentifier::new(dotted).unwrap().to_der().unwrap() +} + +/// A bag of `kind` holding `value`, with the local key id `id`. +fn bag(kind: &str, value: Vec, id: &[u8]) -> Vec { + let local_key_id = seq(&[oid("1.2.840.113549.1.9.21"), tlv(0x31, &tlv(0x04, id))]); + seq(&[oid(kind), tlv(0xa0, &value), tlv(0x31, &local_key_id)]) +} + +/// A PKCS #12 file of one plain safe (no encryption at all) holding `key` in a plain key bag +/// and `certificate`, both with the local key id `id`, under a SHA-256 MAC with [`PASS`]: what +/// `openssl pkcs12 -export -keypbe NONE -certpbe NONE` writes, and a file that pairs any key with +/// any certificate. +fn plain_p12(key: &[u8], certificate: &[u8], id: &[u8]) -> Vec { + use hmac::{KeyInit, Mac}; + let key_bag = bag("1.2.840.113549.1.12.10.1.1", key.to_vec(), id); + let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, certificate))]); + let cert_bag = bag("1.2.840.113549.1.12.10.1.3", cert, id); + let safe = seq(&[key_bag, cert_bag]); + let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]); + let auth_safe = seq(&[data(&safe)]); + let salt = b"example salt"; + let password: Vec = PASS.encode_utf16().flat_map(u16::to_be_bytes).chain([0, 0]).collect(); + let mac_key = pkcs12::kdf::derive_key::(&password, salt, pkcs12::kdf::Pkcs12KeyType::Mac, 2048, 32).unwrap(); + let mut mac = as KeyInit>::new_from_slice(&mac_key).unwrap(); + mac.update(&auth_safe); + let digest = mac.finalize().into_bytes(); + let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0x00]]); + let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]); + seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data]) +} + +/// The private keys of the fixtures, as PKCS #8. +fn rsa_key() -> Vec { + open(&bytes(MODERN), PASS).unwrap().private_key.to_vec() +} + +fn p256_key() -> Vec { + open(&bytes(EC), PASS).unwrap().private_key.to_vec() +} + +fn p256_certificate() -> Vec { + open(&bytes(EC), PASS).unwrap().certificate +} + +#[test] +fn the_kind_said_is_the_private_keys_own() { + // A P-256 key with its own certificate, in a plain safe: it opens, and is said to be in + // clear in the file. + let opened = open(&plain_p12(&p256_key(), &p256_certificate(), b"1"), PASS).unwrap(); + assert_eq!(opened.key_kind, KeyKind::P256); + assert!(!opened.key_encrypted, "a plain key bag in a plain safe"); + assert!(open(&bytes(EC), PASS).unwrap().key_encrypted); + assert!(open(&bytes(MODERN), PASS).unwrap().key_encrypted); + // An RSA key with a P-256 certificate sharing its local key id: no certificate is its. + assert_eq!(open(&plain_p12(&rsa_key(), &p256_certificate(), b"1"), PASS).err(), Some(Error::NoCertificate)); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn any_bytes_open_without_a_panic(junk in proptest::collection::vec(any::(), 0..1024)) { + let _ = open(&junk, PASS); + let _ = looks_like(&junk); + } + + #[test] + fn a_damaged_file_opens_without_a_panic(at in 0usize..4096, byte in any::()) { + static FILE: std::sync::LazyLock> = std::sync::LazyLock::new(|| bytes(EC)); + let mut file = FILE.clone(); + let len = file.len(); + if let Some(b) = file.get_mut(at % len) { + *b = byte; + } + let _ = open(&file, PASS); + } +} + +pub(crate) const MODERN: &str = "\ +MIIOEgIBAzCCDcAGCSqGSIb3DQEHAaCCDbEEgg2tMIINqTCCB/oGCSqGSIb3DQEHBqCCB+swggfnAgEAMIIH4AYJKoZIhvcNAQcB\ +MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDdm3fB+5srzOj3zg38HGApAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFl\ +AwQBKgQQvM0sSUpkFZIgMm8ugLNoeYCCB3DTS+ebN3ewVoyZqBEVHgql+fwsLs2Kg1+vsIpYO6KKjRTdBOZcc43YM0KcswLrG9Pn\ +Nk9h5L3j4iXV5F4pjDpsLB/myW9NveaGnVh/3fuiPbCuyGFZFnyO/R45vFcDkoyPsG/GKLWPZuHIUZ4ZypHj8YJm6hgZyzFzxjmx\ +lMogMrNxsne0FSFLS8bLT4Y6onx8ERTLqTRWjtl+HmVYOy7/st3MB50p6Gkl1JJLvPJc+y0XBqtV8KXnn1fFBPDtSjpFX2A1TRBW\ +lSDMEKm/YA2PO1daflSoJxRmyQXdyprI0jBd6oea7larA6PexvHX5en/3Vw5P02s49dxnJSGkuqhk1mKTJJTvdu/s3WBfvTBEmiV\ +sL67c31NmDsNTQ9FUQNZKSvEj3OLZ6752e/enf4dHZebvxXcYIHLndpGAVF+jvjYoZ68O+unm2jP8k94lkHgnwu+LYBBdEpfmntU\ +lfFN68RmuOyuIUQn8Xmpw5sEH4TDLTodI5BFLHb6+Rcz6tvTFZTUcaVTJfVP4O0ZaSy/vgDSBFN6X0LwHG+znHi+hkZr2gMhElRi\ +q2Ewx/iSOWVn6Iy+k1TE+qBc1tuOA1BvzaRlg712WWM5SyNTx25+1/6G1CW7xbbyz9AmQQacZ1PUXpqr9JD5e21OgYvldy9Tt38l\ +IY/Vk5aqpD4hScAv5Ncwr7aGuchhJ8AJLkBRT1SLpazhwzmbyoSYBlwEZ/WpY8hc35OsMLHI8jgR9BXBuUVrP0kM+kFBh5Cyb1F2\ +zRFDTAGKaRh7kVAd/GHPQ6t/FveBHp2ne9ADXXF3Nl1MqAXAuSBhZs2WTWTxOG2cy+4ocb1psFia3Y9abxjMksB23byqCt+ZX1mL\ +DXmfK0EUxq1K1twkJJEQnnMcp9lvEgc4uzggu8zICWsPRh/H1v0VlDp7PextlWotnf1TnTI8WgjcqT6JsDUmLEtwEufsSQtbHm26\ +vXbLBLdW0ZTG57FmqjkPXptnrxk+X9athIxcMaphL0HZIIId5zUqDBzw5hTCf9SUd6lNjkmK5h1qTBkOF3oUWCmxZc9kcCt54nKk\ +YvKjq602dWGxI9WQ41symceExKYXqfrsKKVLEofNPr6ObYyc6dgeM9Tq0D21XMr3L4Z0rpFUj7jPbS+0vJGtXFnOCfdkEBmR/00U\ +chFTsOEHQZ2lbsaZt0MSiN1kvfvOh22mdiM6Q6VPG5HCBTIpvgOoC5RvjRxVZzDl1HDgUuPG0cM8B+tnn2IVuyflnygwoTpHZtLQ\ +qfA6ZVFnJTfMFuXwzhRDk9yJafE33gyYCLpfewQ31ljE3x/CmXdA5kzSiwRizb+Z0LJZMGI6zh/iA5tKa4xWL7IpOXPex/xe9Lhh\ +cpVLk+ylN6GUeOOcHt1bYujRQuM4BmWnNVJ46Uf2ozUd72x3jystLTYDd9+JnNLfFrKMdkyIkm4/Hihyu0GMPm5YSfgFG2qQPY2l\ +GqPV8Xs09CrZM/X10Td+a4nBFVU9HwVzWX1H4cAJXwsjanojxX1J75LAbrRQBWozWgtpBavsG+1G55ygnG+4z5+P+JYnspzTxxG1\ +NgpE6ngq9aMjZ6AsiZM5rzX78LKjuWSzA9xfawnOukt2irF/j+cDIojJR9NdLiCgh1v9AckJzQQh96NFsQ9w8s2FGUurMMih/dln\ +onyw0m/8VHYx1HPoIgwhJgOvsIrwHjkxG6gS4cIJCRBWwj/93nYgyYEBkBD24g5hMrsNpHfgf9jvQZ5y/Sj/5jNf4n0GzQXnTQur\ +Mm9FuEb3VAIfU1tNYevZ/xdF66yQ9NApmUXvTiHlitvI9ndebAW8etiLAwBajsb6eBbI489cOzCvI/9hoouFns3wSFNVuHNRD2qg\ +Ujl6dNPyPnuzow6tQz4mFPRi/WMl3aSq3CWZ9kybYJXNIO/2vaN85a7bx3tueZaAs1Jm/HrHpiwYXDM2nFqXYWDyeAfq+xLfwsJ0\ +a/eJ7s74Vjibl9ANfe7Pkb0v00y4vFkMJ60Yk/3TuW6qqLrIjAqQ8Qh+aFH/IZ1wFdibZk9Hk3yFoCV1CgA5hGT4WouTkEV8Z7PT\ +gC/ipwbgOPXUEq33yfTFDFbmrk9PvbpjSWKA9Aw+7CPA9j22j0ciYvNGacHKdf5Qgmh1J5W6uC0Rz+WupFEKwkYqj7MM3zp92tKQ\ +DXIoutcAPmQOsqapR6POtbz9J62RZLZDSkiWfMSyRzNuoOZW8TvdH7Xi/y4FH3bMBDIbNrdDIzS9yxrTMBjv773Aoa+iCtATmcU5\ +dGu22y9IUJ95hALMMRRu01RvzyImR3RZLM3zXVpMrdirFPcQ0xV3zXsxquNMBTm7LEaZPO5iUIC8kaaOSxy6X3ETG2Dd74WuB3C9\ +Y+3Jrx55yUd8vdgflIxwv3JxBhS+rqMqNSmS6ho/4Yip7SVLtrGNPyDt267y+CH2kLGyhjIccH46k/o0P/V3Rj+3RKkI5zea1jRG\ +N4ZqezhlpJJOea/MFbDS/1hV+3EAzklYs++Pw9Xeywtr21GtzVgGnmNlZj7aaf0f6VA5xC+CBjCCBacGCSqGSIb3DQEHAaCCBZgE\ +ggWUMIIFkDCCBYwGCyqGSIb3DQEMCgECoIIFOTCCBTUwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEENj6DxvnJypnlOxD\ +B4pal5ICAggAMAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBDwjW/DvRppLgPgUc4+brTxBIIE0Gibr1mXoSTq1KNRphdw8u0Q\ +PJosufEujUHoGpnTeYPnkjjfilvFrwSVN4nB8A8hB/pth1NCPFAxGSkdIZtf8AImtCZ2DDXoX1G8210m3RdoI1G5zA3RXgefKDzT\ +vVh5iKTjqIorB/slrDkTd2vBdI6odSzii+2wwUMeF6pxZ4XDjc155HFpXA5zvwIEUPbKOG+Ah9khv9ZsB2ya11hfay3/w30q87uJ\ +74lOnkEMU00e5fkHu4V/oE/2dcHRvY76f0vqpxVgLpVVQRAn5IhXNEOiJ5wDIB86zf8Eg4eMuTgWoJaOux8vA7pSzOgNZrrOD4hM\ +hXHRclWmMZqXYgz3bTTU1VfTaqID6XKnPKjQymbzfsre0M3lixdq8EdylKIDWazMuIGo3sLnJV0to0UAmKWrzqBUdedAVcSdKjHe\ +HF/NJmtzzbiLXI5s7UuqBPOKvwMLWWCm1JN70SQBX+IEP8OU1d1TJghAn9kFq6gEq4uMB/L69T+r8LQLY6ralvGbDvCGfBqvmbqM\ +una2ZKdHJ9X/B8IQuP2ioraI8ToN11wywLwPwGgISrwyVpBwQQDmPjfxs2yfgDNqb+NxZAT1+MnW9Sibo8WN+R91QOJRCxgMQmdV\ +alJFZljUH0ZhvugvdLeguAElnATMF2R5r6JmprYJA/jqz3BUo/WkUnHsV0nAhps7d9oHRkQMRQ/oYwzONBfLDmEb6AkbqAYLGJHw\ +PDHQ1efrgZlo0GeokG224wDzz2OlFSrWqMX1RQ95aM7DI/vUAO1kKI58uVYXSDwg3a3VBzhrZLedkkPU5m8SM2sYJgtmi6rKHllO\ +XvTpOPXX+XohJr7Q7S0XFR9KoSHeH1q29E/aOT01Wp7Wfq19hhtAkJtd48vOoZmoE4DdSy1mVfGXouU5piS6a+HF9HIhEZbMvP2T\ +t5EAptK5KxaJQ5xj3ICJ8tfFmePZqMITIeQem4Dpem1rcwc3eh5A1tGLoGITFEWB1TDl5wl65hY3MZItmAAqabBwaHIPhThIEYxu\ +xlSSj9GE9Tuhq00sBLfBQnDULf0XYxInFnoWalvFNtmWLR+3njdwJ5r4bPGJrNhnpDqPEPlwCJ/nKzQf1DGb/0rc7Vx2VDfNYkvU\ +4u7+M4YQm7KIsWBVZbWjNHOOUoP5iU5OaAbfFNjW5zs5h9VJSh1Yrh5UGbFk8rfR+UF+GlEA2NQ0X16N4lPFGvQqJhDX3IgKVKhX\ +nhyV1HSkLn0qUnQH8oT9ZfqASUxN0uaTN3MYGZQTRB/vKwg3V6zxKtQD3PLqRWR1eFm8UYq3/3Sa1H+qYje5GsWXL+wbB1UXrnP8\ +O4v1/PJ759QDqCpEXSc/YUAxw2J7g54LJEUKFwvvTEprlP75LFnXaRx60kzi0RDzvOzbBDIdjYtiOCEgX2l6D0TWnYPVvqsy4cK7\ +wY0OND6oE5WS2WxSCGMsfgIuOWjQ4zNFRZpjwVwBPjSbgYLY0Lxt+k3/9i+QQVrurodJQeO12rk5hn32ihc71JyQfMH5b8i/bVGs\ ++7cJhmc+I56DJ6S/o+M5RxHFIH03iBwp6wxwz9zu67OFa+w89Aybp80TeqjAcMFoqqJoO5tBub83yT7///FLwF3TraZUkWm1Cqgz\ +F5qTXAqUVgAYo3XCHFEjMUAwGQYJKoZIhvcNAQkUMQweCgBhAGwAaQBjAGUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpT\ +GrG04AAzMEkwMTANBglghkgBZQMEAgEFAAQgGqUPhUzRMcaqds9vgTOSCbcRLzd3zWp/qA73DkTB8zsEEB9ajyrtEIfDiOZeZ+v5\ +L4kCAggA"; + +const LEGACY: &str = "\ +MIINQQIBAzCCDP8GCSqGSIb3DQEHAaCCDPAEggzsMIIM6DCCB58GCSqGSIb3DQEHBqCCB5AwggeMAgEAMIIHhQYJKoZIhvcNAQcB\ +MBwGCiqGSIb3DQEMAQMwDgQI0ywIdIL+wmUCAggAgIIHWCNIi5dNd/xDFZskzoB0TEfhZ7bZE/3+oz+hJ4aSPSKFQ12Dw77TkEio\ +FSJ3n2G8EimkuNz/d4JNhuo/kVHNQUBS6Fq//WcB1j7uQOO4M65Lz5nXcTCihxBqhVHamKWqYwnzAwkiYvjy+SLXcAS+JeXPieWX\ +BjTq2D8pSPZ2g18IalAPQFuF6wkN4K9ninrpz9IXhss5+05hgTj2xKZdj9zrU4HL3gZ5C9iAudsUDiMB9vA9ruvr7HrhLCW9ezWs\ +Vuav57JvSEXm1EGMhx0Xu5t6nf1AwgzKJ9+D3chvV4XvIV37ITvwoT5eCiAsHaCn1AJD8Q8R/26W9ypGOpuJfeXEtIyXcbybCkJ6\ +351XP0Wt87l1/i1JHsJHwgErfCASgrL2zkQGymIUxjdTtaE55kBgL9BJZvCjagI9uMw0rC5azJ8UwJwp+fsVnzYXzVsvCFK7cVR8\ +LLA0nQSiwu9E24U6/b7zn21WktBF3UFmLWsdCCEbvrrxZOmmGuwWikSF3Li4s5n2uNMJ9pJkm6qFqOvoie2048UOzcO4uuLbV+kb\ +KobV5BEo/EQQoiI66+Z7z7cK6nUjiEZNpeZKqaVnNunuJN2WvGlO4EqLykjj7vzVUU3XKHoKwpsaGalihbvKVcA939KvP4GYTyu0\ +N2UWQ9BUn/XLV+e/oHD2YLkclbYM6Xt5ZDf3RZ1mvDu8GVU8wCpL4TiYf7UA3Nc5k77O4fg9wy9cQgaM3gJwhTz4LmWJO4CgLaHY\ +Z1MoFgRghg6CWRgWrFuDwuB14FjkYsQSwCexd2KoZgbeCb2E9kVRHX9j16Y3fq4k1VzOlg70nSJr3xqhsKB4u7ahr0J3jdhIb6Xm\ +m2yknpFaOyVs9/6J8r7DYV0P1VjIAjhGfTlhQxh7Dzw/BDUrLeLbZAvzwDxZB7d2VeezGcwJz99QcyV3HC0G+rBUwyq6umUbE8cl\ +Lic0hZ1uXDiGraPSe5VZ/HCfIZCLPJfRn2of7B+QOORPiNQ869dj1Kpr59bcgu8D2hjU795TYSn4n34+5wUp3yF5mZ+DDlSEY/yZ\ +2De3QrZsEyRMrhHwDssDa2VQ4EVOeyx4KsSdfKKQDKsBoFk8cpu6Au4gw4j3/LVZZC6e7arqHwJae5vG9vuXa7TYulIQm81l8AGi\ +jV5EOWx6W7JZoiFpF506EISnDvjCjcSJ9xUPKoBoQpl0GjxPf66WakDMclKx5gsw3WTV5WNOsUHGqW7+fVS8+XdHTVzeniXprqKR\ +XXI7qQvTsgjeks300xfOXZczaBBM923HqKXzl2eR9gAJx/pcpqF330dL/KOOnJMsaXJNq20kD5ZPjjbQ+EjmEgb68QbbwSYNTg5Y\ +SCFtzrGuQ1XFAJ0e7tS6umNi2LSUOdPr1VlyXvm/03uf6Zm1JMHbmv61wia1dtyksUnO9FxrRbwpRSFT/5KBY7ZPZinbQpE2Rlxx\ +NTpu0fKCZOUokvgWHAI9brPEKgRrNdkiugRP9RvpY6UX6v82Lby14iPH+ehH9sP2NhY+vlL1qS91n9HY+HygWOcMP/PfN3HpAcZU\ +QnlZnsq4ZO+U5piY1NrKTTcnhzIGKx5ObQcDolaoczLZTFwSxyxiTlRcJyJllIR/ff+64/wNiTdYODI3rEJunEQAbf5kEPKD0Rqn\ +YRgZRtMEWk1ADKHHbjykFupIgP6dSncJ0oiH2Pq84KU0SrJspJ1gQfmywgGV0gGc8alLeifHqktPdU4OEVq4FKZzSAVyTh9o0BX9\ +KOfsbM8iRlDa2AYP+Qnfbm7wmOFThnseg5rJ4aA7jUgtlkLg9YhMOI0Uh/vIAUopr5sK1qiU/w0XykCbU0JD36qyVSFxCdSweB1E\ +rKBf1FZ5AF0pR9XgCadKBATY9vwaLxTBxTWPJwdxKSCbAOc2V3UD0yzWvxTgzL2sh3YPZFVvJJot1aYO2U+J0omYo3c86h0bYyrY\ +uCEESVoBz1Euzs912It5Z+2s4R/f2Xu6EGQHGSTFIzuRQlzuAlHyBPZhToLkclFegQapeXzyrJwOusUaGtGqkmJZoseZ/yTxGBhk\ +c9JXuTHTYnsCEiuKhyeFG1yGRDlf/AiCDN6zOBNMiXJGdpvKrcx+Efz8hdZ94CE4FUp2QRnyKDVBYKd+6fa4Cv+LsCF+Ohk8zCt0\ +FrniW0GMvjrjvRCZYADyS94LWIVm57Xggz9t+3OONOW0xpswJCNCNpwttxP/FYa3A63jYatywOj4343vOMyubLGWpeaNnAzPVMHb\ +Yb1Utx6Xhj4DMmfAK69E3cCHH06auio+bmJx7p23k5UCc+ifA9o4qW9HuZtqfRUhWc+qFycZAaENll2nMHKctlhxId5bZ+R3EzJp\ +a6doHHgwLA8/YJiCTmt68pXV9zHlMfGhv22E3RPBCJX94265+llB/juy1CdrfDzszoM8sE6ikJ0BCWbIOvDHmzHeOUpW9gq17/rC\ +bmAzZLsfD2fZW18+Ygzd86Ci+VgdB+4YtGDYUom0SIFlJn/QNGKFMIIFQQYJKoZIhvcNAQcBoIIFMgSCBS4wggUqMIIFJgYLKoZI\ +hvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECEwWX85zkiPsAgIIAASCBMijlMCuQ4vGtXt5aSh+gMYSRbErCCsU7YSQ\ +ShBrz2ELWaNE2tXKyICqb/+TD+9nLJFikT/x1wF2I4qtTq9TRLf3WhR7wQGN9vxbeAS8w+0V8iBBmDlesS8zE76m3hBbrnxpSjEh\ +Q4+IwKEFU33WwdEVTbSRQj0R3DhQN10QR/8hhRHpxZlEQY5S9u0eVrFH8vObMlj3HJCx1tUiTAEmDMeVIA2Yy3bnnbdE1z7PLyKt\ +peBvfCg/2nczZLW9DRUquGhZp9MwdbLvpkR7COgBDTZY5MBGU6SfDyPffBaNaHS9ZmTKeOIHR67ZYQ/tT/5IlA+NKmAoKmMTjmO6\ +GIv+uDLWJPZVwFPcNxDe0YHZWgFrxOHam1HFIDHacGzCjJ8kJgYK7qPT4UzW5658wZrPPayGUs7OdcBSlUXoUPwI6GzdgxtPh9DF\ +6CFbHqvuyOo/XFP7pENIcZ+Fgpk7ruB9dJGC1rMlbg9v2myYEDlvH7ydJMAQKWEF4Cosii6KO0Td+4HHz1RPXDzLT0vzdulg6pwP\ +BGEoHfcVfd0xUuJp+Rd0lO+SWIyrLNhQ9sNUowMLwuvIRJfOxWjZ/Hop21DEn1eJtweC2BOXKnxMRsdEVBmLMHPidc6bPi6djMds\ +xbYRz9rmQ0eaQFR87cvyUHQCSglO9uyLOnLFlmAehtWLev0AehRsexD5gaID5KReBXV7KNvPdTu0F8LvOCtNi2cf2eHwnJSWgKrN\ +QwHodyVhZ//pLe93tiGdASuvCrEXN7gdIREv0njRmRqxWUl8MKfLJn/XtpUrGNLnU4qFjxrKkvTo/k7Ax0A7DFAATyulan/NHnBq\ +iHF6ZuUL1jha7jMcyhq7J5zSqDSX/0LQqbaRHigZ8IsOXdV8gB4yCraG+fLm9H7PK3nIb9yIymu/eE/C2QWecIrfGSH7sem/q0ld\ +YXxOAwm12HtcJydR0iNzK0Ddty8heVqvZRoLe+G4aY899vk9Y+Lv/XP1kWQxp8sqFw2PWM4k8TCPdhlk76PgDlkmvtDg7Yl8usT0\ ++BDLRSxtebssQTkRZ+OZzHMuj3uvyDeB9xpicoqGLgU0Qqq5w6g1SXeqyJIiEf3z7dWWw+dXxb7vbDQYySMBaUEHvXFFSCwz31Ml\ +iQAmlDT+MBqLaQhsABTa/k47Pagov+X751QT4Hs3mr8khTUoqRpRZJmFol5GBpwk5GOTMYWHBdPfqoLoU8mEObQoHT7aOembQNaM\ +NOi3zpNeKZi9kNcmMCc8EMP9IuSqwpSdx7Vq0ZNK6dCUoGmod/PTVwk5rYKUdfenLoNS5HBZaawJa+0yXunNnbkHGU01AzR19d0Y\ +nrKczQxCwQz4tRi7cf2/d2xDWFgHbU6m5OH1BMaGZcW/d35zahiz0XXlvRNIN/3mxg2gi9BO+P5TLBi3iEHeQzOHJb4vmJlpcjXh\ +3nIPBZT2roWIKpb9THlzasf8OzTGphL+Ru0zBlNmeYeJhI5yF9lPj7yMDfRCo0jk39Yy1zcMQ7ZSIgXCVRzctJxdp5AsMLrqKQhp\ +eTUW7DQ1VFE2eCAPPNl2kMZ31tM/GKIUQbwnhgQspmjWbj9XwKlmRni6nWbh2/dp+7X/3e5cXS4fParNRcMZQmPt8Ka3IGTnS64x\ +JTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwOTAhMAkGBSsOAwIaBQAEFMhJrwJwP5rTOUpuyMctQhSu75vz\ +BBA5cgeI/EDEl/gkbG7WnPM4AgIIAA=="; + +const RC2: &str = "\ +MIIJyQIBAzCCCYcGCSqGSIb3DQEHAaCCCXgEggl0MIIJcDCCBCcGCSqGSIb3DQEHBqCCBBgwggQUAgEAMIIEDQYJKoZIhvcNAQcB\ +MBwGCiqGSIb3DQEMAQYwDgQImY9Bmh6uNp8CAggAgIID4BTIb8wbN9av/HdVdrKW3Eu2N6IjA8GZZS44fkQWSMGQsHJqxJcJ4iHt\ +UNgG/fZUum+iwyceHL8dHrncGvaajpeyXvt8mqY33UxAesW3wj4Cw9PZMRy+Alsr6vv9vWiimdesEebRST+Y+eQWeXBRs8whlGQE\ +5sVNNtrm5QUsMOUas2tiOTF53sh7leVPLIaPq5sDw96dY5lK3RtIhcoORW8bPm2jqxWu8H5kyBIiOW2dRha4kyB4J6T3zT4Yzo/1\ +AK6RFkqU/UFTyYI8SRwozUE7nWAhO6zts+tTcyyTVFz+gcpP58PEtuWBJcGdFaNKh4Vf9E2oHwxFmjPRYgflmqtRvwVh8J1pL2zG\ +9LtDAqRrMwdjfw/PZHWgvbdKeZdj0oVRai5YlHBkqgJxKed9hH+ULrCuZOWrRcBV3V0zOPKvgcacdT81reJWP/DCEoVqaqxYea4I\ +oZ7TNsv0GQOOAriJKhsKGLy5vYFT9AOxtEcyr44vrJHzhZAxQUiBRbdbo46qEADkRGgVPRcnqzgJyxA8KAwCPSGeHHETxSE8qzvC\ +FqWdwxudGsQ6uxVDsptPKtyIZUkqR4nG/Fm4ZC0VgXjHfwKmiiLN9nYVvQDO7Xaq7TOrmUog+ifUaFuEEtbC3gbH88OX3Wr1g6lY\ +CLynNHp2KeoL559uVWLZMiNAjkQ4GevsP13GZTu84a00Ldc+hIKS9wj+bjP/JHlzSu++SHY9psD2/os+olCwHLUENMV5ML2rj1Oe\ +wcg6/HJF0TPmaAnsIxYYk5AgKSgpIwBocwco3siw16tn/1h6utRTEalO6vmPmBcWYMq9K5SeiqQ/J9X7JHC6qdGgtuOSTzAUqGzT\ +vwpHtMkIv2ITjWqewArQaUNw5WHxa0ZhhukprsFUmnc1Y1X7g0ddpGLZ3Dwn46AMivgsC4iA3FmPjykKGvhMddIxkaxLglNDKePx\ +1hfsCLYdNPYMHeIyw2EnYojyG9Ux/s5Z3f2LPYuK3WSS8xtvAZFDtrmVotKsGNzJiUpWH9dCTzOiHPmnakpodOJSxqxP/OlGuQzh\ +eIRMh3e6YKc809R0DVkKa3xP1kBbHPrdP+C0B24QTLUflYOLxzNY3dJ5wCZ5jbD1ZugJava/GqoV83qQkJ1hejaTsSWEhcRxBISm\ +z8guUuMemu7D2zS9cX+bJ+8scqijFzIx1/4q3WWkLPAiugK9HJ06DPfkqnxVvL4oaAVOHDVHyGJtaRiBzLUpOlC+dSkkbls/mmuk\ +sxzoiMZcAWO1vC1G/7wJsyXzS5wUvIKPgsIk3mF9GE+3TBADfnpuu6jw+GqotP53MLwuMIIFQQYJKoZIhvcNAQcBoIIFMgSCBS4w\ +ggUqMIIFJgYLKoZIhvcNAQwKAQKgggTuMIIE6jAcBgoqhkiG9w0BDAEDMA4ECOqPrTHFEt4EAgIIAASCBMjL1Rzzem4ErP7OZ3gD\ +eqNEzUjFxA1QlPbjaeLka39JtgzcsBAyIyEIgou3TddDzffJqd6V4/08Ls9SmpngPGpYXP07q6Xl1eFjrwQ+jMathtFWSHCqGgnm\ +5D9+IFalz/7/rQv43vVTqG7Cw7VCSKr0ly1dZAvGRFEnP83Ffvny+spKpSpWUY8SsY16333jp3Afb/V5NyfsJETdghxi8d56lThi\ +sx4FtTAhKMNXSLenQOkgHnscBh0w7Kg2PNBHzSW7qHQDvr5oq8ZOqIe6B3M1Lxxv5nVzSZRgHbvyy7d9nUFiuGSPMVINffXF8Acc\ +zTIbpkuW5+pEpCGKOyOsrqE8VyTLMq5e7MRPsmqu/v6CUR8gfFUp0B4ovFmsDyWOARbtoWx5aK4bhJbKX9CI+F3dKaWL9d4VJnxk\ +cYZtRHIfbrPKEb5Kk6oO4V9KOdPaXfhXkeARhLFsAQ9qb6tX3w75qfEaAwAiAjUJVgFFVQ7ycL8qNUUAt+xVNYTrYa3qXDVlsfW9\ +e/ok+XvIAhOlHIc60ug7OUmxa2E9zyeaEptRVxl1rMWaV/s8ZAQZhNzvRtNWPXUCR/pMGGySbO6G3fperpZZcIJqQ5o3nifM7Vak\ +XFHIpESFfiCD+dcl/cMlc8hzVORVaGNIc0kX6nzpZXKzXEAawEYwCpEf9T2CtD345/lZzfOGgxMEnENZrqaJCNeTmPxcSFmWAkDe\ +GsG2E6E7wX1XpuIpLu42Ik14Vgwb4Z1n9myuLqxATbnkMljJsIigr8WcGUSUOnru5ZoHZzZWGZGvQ5H3RGmDE4tWJMF4ngzTeOU7\ ++lvfmdg3bdL/jIdamvWXBbqUdsvECX1tORGZHAyJSkCqxupHaaARrSwd5t6hzM4y+dgDK5FRsxofN9ulujTDQPoKa/GuQ8rfCSxW\ +02kL8aCtv1BsqitghPMOeBst0xAFLvOrbYO6BVJpZPb4SNR957M964DVbannOhnrxPU11bWsB7V0q5Bp5mHSYON1Tslwa0VR7JsL\ +IDSQdGvldj66GGEfu7TJGrIEypKAOF83iFW72NuIrkN9qBw4XAC7Bpe8F2gkpHqCRCq+BYktD4BSnNglERLh6QiAVdwqa9J1LlwS\ +G+Kkgr0wr8uTKX7IV6XCc1Y0ngC9e4sT019+LmolLUg2v/pLw9BX90BjRyopV5oo4sywEs0pQ+2814fbBqvhRLpMKSOh5mcKr0fK\ +eStOGl2varQ6xV3g7x4ZYxnQBy/XYTBDuHhEzpGDEMk/iH6xOlvYleeUW2XgeFzDQk6B+tlkbXeCvmGZB+u+cIYG5QbT4Ro/e2Tq\ +LbCjXs2WfpIKoO466vBipuVmabca+yZ8Hdb+3dAlAq857JM8uEbZ79cWmb7pf9kPJEOrZfJobWD9YtgkTFihDbkgc2gpVYITwI0r\ +dFkk/V+NGcNon/8hMVUW51vTw93bIR74YyhCMMdei7z43ReARvAn1hPRzCJLKDPO1Pg9+WzufeGlqCko5wM5sr/xNCADeaLu7ont\ +4mRk6qSRHew4oVsQaoNkxiR4OupMSyXg7QQCfuShv30GFKileLpdXPAs3k72PtAjBEax5H58Mewnz6VOsYV26+ASBeTazwXwC8mu\ +4VxlEwy0k26/WoYxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwOTAhMAkGBSsOAwIaBQAEFAc6BlZhfHcR\ +gqNVb4hRy9Y/isasBBAmnrhSYOIWt0AqY73UNFmQAgIIAA=="; + +const NO_MAC: &str = "\ +MIIJnQIBAzCCCZYGCSqGSIb3DQEHAaCCCYcEggmDMIIJfzCCA+sGCSqGSIb3DQEHAaCCA9wEggPYMIID1DCCA9AGCyqGSIb3DQEM\ +CgEDoIIDmDCCA5QGCiqGSIb3DQEJFgGgggOEBIIDgDCCA3wwggJkoAMCAQICEwWY7mm9ZFkbsOorJB5uhnxOV64wDQYJKoZIhvcN\ +AQELBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxlMCAXDTI2MTExMDIzNTczNFoYDzIxMjYx\ +MDE3MjM1NzM0WjA6MRYwFAYDVQQDDA1BbGljZSBFeGFtcGxlMSAwHgYJKoZIhvcNAQkBFhFhbGljZUBleGFtcGxlLm9yZzCCASIw\ +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMUK1lXyl11Wa8nm/71zx548b0LNAi/mAN4gqxEV1ykHT2rpfmLHOBe/9jzNtib4\ +xFOq6GyQEI5uhyRitnwsv2cyQ6Q4BMdXzlGd7kXhhX0CUnG/a54A99qu1Kwwn5bsxvv1viA0FtwENk/RZQfAAZIof5MlZxTmUimR\ +74/wfpSplA2tVr1l27JYkTlcwEE75oTGHngMVcL+somdViVwL8W8g0XmrSR+guSF4lLadxE1dIv0kiW5hNIU5eTcj/5X/SkGDgvt\ +u7K8sXGk5czTLgPdIztVhWNJUgBF7DW8IvI9bFuHBIqe+ua2vWNPDCnHvHarblzP8I8K5+9DUqdx1uMCAwEAAaOBhjCBgzAcBgNV\ +HREEFTATgRFhbGljZUBleGFtcGxlLm9yZzAOBgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwQwHQYDVR0OBBYEFM4K\ +BwgbSCFFH9KVBBwDlUFEN6DkMB8GA1UdIwQYMBaAFANXYErplgDksqE9CKJD3y1Ia/smMA0GCSqGSIb3DQEBCwUAA4IBAQB4ZaoH\ +YTiXV8YNiQDcC80L113hM18buMihpyRvWYvfa6IRebJhJDV09KmI1hDP1x8sp0eaMxrDeLIZZHs5gD5I6kdUmIsWGtE4Igo5UmJU\ +PrcYjcuE7VtmQ9tzwTBgFL4scwkfZbAa43+fZe/BqndyMs2CMxAKcMV7jzw/LbrLEI6BP0MXqQ/B9wj0VcwV0prs9MxlYDbTbS0F\ +r+A+tX+0VRE39IFKo59Xs7t/9IodTBpMxIWhVZ7Ukbh8NyhE2NRM/y6czTPsO9FCC/zPF2U523812v+fkc0CnGS62kEujmRD6VTl\ +P1eHQ049OEjzCU/WHYdL9VFFoWswb87G+Ae4MSUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpTGrG04AAzMIIFjAYJKoZI\ +hvcNAQcBoIIFfQSCBXkwggV1MIIFcQYLKoZIhvcNAQwKAQKgggU5MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ\ +plQrIjqtb1mmwuPxoJsREAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEECBNQ0E9PNp4Ldl4bt+M5zUEggTQAAIoW4KR\ +EhQManAkJRk+Qd7hNcuwIuKNAWevxRC/6fNNgWt3Sxn3dLs/NTuv29nSk9FSlnGMV8v6PyuRKWHPnlobZdQqJI+SRNsyAD1uRpFE\ +0t8bhpLbR+qiIuyiRNhujUnCyccs3PgQnbMnCgKYkL75Bnd0edHCRvtxu65T8cdaQZhpXqLJWwRi8lTT/xiN3Kn3krJ1J+6vnI73\ +WUQIK3PtQrGzpW+gHOeburYFHiYSDfUy1GF758R7Di//fsvd68i2RGNqFPygi3OU0uBu3eYlv0GwlbWHTRYc6dLTcalnHH0XKcBp\ +RElCVLl/phAmSiXAre4NvPkLCNlS8xfhhfOYr5bX1a9CE6TWxU4C0S6i4e1q7X7d78mD7boH2/SJ0VbufJJOoHfScReUgi3P5WKp\ +0lKvO0mPc/hlTvyq9oiYDLk0Gi0v26t7+prbuWkkAcD1HtQLwGIZjq3HyRcBT2hwx9B6VM0VS/4uSsxr6XwP2fvCI8tDLokBw+Ts\ +EAQbLR6Ozjz0eYuKnrnC4+/Pjn7TX1JvDGISZAbKNVsI6RrL/iZUbushmso78I/bg8cENE7ipGwTwYGMiZZ5+9oMKvymkowpOBr/\ +u78hppuWcJMCmty/5EtoEDVhImb6hPwJ7dY4k5ZEHl2tsweOgSEmlkzxh+dMPQPeYMc/+2VcxysDxNjW5jiaBbXVWS6XgKc/VJGu\ +29JHTN4KYdoQorWUuMBNAt0vLF+pJb/3KtgfHpZ4i6cJ28skain5RTSjXiL+RY1Q4zyKJgqgrCyMRvgXXUviEtjLIUrNdKsgPVP5\ +iV0vGkFB7/DNGn88DzEqoEGczdarU1dEsHN334swHGF6ZGdYXTfxeQu1rx5tgo1ObXcrrHYAmi6/3vufK1p/WMH2t+VzdJtR8Bjz\ +LxbCiEeaXAw8ZW3g9tClnYwdizcSq2tfmLBqhD57ydAjBjOKj8m3XwqPtk8rzedyZF9NDXPq7kqHIWX+RAtpyd/7HWHz44uj7fae\ +kYPyy1KsxMd+LlKc4BIHPmCnZ5Lk/uSvEVH9VuNoj87OQwHSdXTEQl5EA1kjeXXi7qA0OulEyVgiYwmIL8xwGDpRunC59TxYWFQU\ +KPA56IhG7jHq9owAMws5bv3XwpZAevik2RqBMoqitKSJiNUWeQZ3ILXVpvqjW6GNrFg9GRHqO3/bA3LIziboCohWLasMXywIhyaY\ +WnePvvvKouwkhLHjK5VJj71KHY3T91ULhmI/iDx0PdUgdcTH+pAX/Ogj6YG+vxnEUg1V/hZLsW5hFavvenj0iEzc+6qJyvKFpjBu\ +Rk/FBwebzYB/UJ016t9hDqyk27pnEbn8DHmsS4zCQ2IQHV0iiI1CVZALVf0yaZ4NDE/bkLBIiCUajUImzFvq/8YWYHN0RwbbtG/V\ +KJzAOHrot7pQlJy2cJyELhdbuNuPwEB/S86OwEsDIU4Ku5hF/c+WUdNKm646DsZM28EZlcq9jR+mK2x/prErV0jZcHrWaEF+n6FK\ +yEc1u/4obH2RCOK7mKQQIuTOc3JhEOcYAFjClm2OtcSanUccDT+yIBwiDkhLteXMH/GZ4VF0AXHWWD8uGZviUq5wunG9QVtlUQDz\ +Uvr4Oob6RK80S2zz3PCqwquX/vyuTIppXoYxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADM="; + +const EC: &str = "\ +MIIE1AIBAzCCBGIGCSqGSIb3DQEHAaCCBFMEggRPMIIESzCCAvoGCSqGSIb3DQEHAaCCAusEggLnMIIC4zCCAt8GCyqGSIb3DQEM\ +CgEDoIICpzCCAqMGCiqGSIb3DQEJFgGgggKTBIICjzCCAoswggFzoAMCAQICEwWY7mm9ZFkbsOorJB5uhnxOV68wDQYJKoZIhvcN\ +AQELBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxlMCAXDTI2MTExMDIzNTczNFoYDzIxMjYx\ +MDE3MjM1NzM0WjAWMRQwEgYDVQQDDAtCb2IgRXhhbXBsZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABFTBl+in37wcV2KoZBpe\ +8HdIa3I67Y9fM249azdt06A2enfiMt60EGb1OYAn6qD/7HBmfSt++w736js0fPFRj6CjgYQwgYEwGgYDVR0RBBMwEYEPYm9iQGV4\ +YW1wbGUub3JnMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDBDAdBgNVHQ4EFgQUDX/llMpNqwOzpdvg6ZW6gpow\ +7jkwHwYDVR0jBBgwFoAUA1dgSumWAOSyoT0IokPfLUhr+yYwDQYJKoZIhvcNAQELBQADggEBABUyJYbCAXO4DRftivaELtGfecBe\ +lAyblNSgoObqXGpjfDbP4GR628maNzFSCSNpT9GaBtY2nsHyqwbTBbrZcrbXrE8IXhyF+QfXW4KjQXd4zl/VDL79lv997I2ocl/G\ +RYq8jMPO22zCDkzJW/ihqgTw77YfuJy3TRG1KFDCYpt+N8jy+ua7E8nVCcjAUIGdyoEZFJmvznih0qh/gAZrHH1JF3dvgmml3R1E\ +DBY8ZueV7uMWcBGHKwc4x+qd8zhyfvKibwl5Xd/NhtBqclmgKTR2IoZA4tojridkfdzmnrB2acqkp/AEByd9E8axNymFFExtlSrE\ +N3rxIi94y3IQXgcxJTAjBgkqhkiG9w0BCRUxFgQUjInlR11rxzqXIkizr2OoL11D9JIwggFJBgkqhkiG9w0BBwGgggE6BIIBNjCC\ +ATIwggEuBgsqhkiG9w0BDAoBAqCB9zCB9DBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQqWdl82FHAGkVnnehJZkd3wIC\ +CAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEAQIEEJgmrQYD1UonngDfy0Jb2UUEgZA+uRWJCzYL7FxB1NaX04qn17h2kOUbLwAT\ +MC2Qj28y4C1jXfvwP2/jJ66n1CYMQ5jrOyp7b2kn1CF3jYyfvUcuy1eRX5re20d3MO3BvVyJLACAwfNrG3XQhPBiqhi238zukWbC\ +Ub4PuKJIQ/w7Ro4e77aBGzhH1WN2okRbfbKJNwGO8+oD40su43K6/Pyg2ssxJTAjBgkqhkiG9w0BCRUxFgQUjInlR11rxzqXIkiz\ +r2OoL11D9JIwaTBRMA0GCWCGSAFlAwQCAwUABEB4m6CI+/V15b2q/hZZfc/EPIUaI48ZKAFYhEF3kRVR2NvgJt69KYUM0148qW+S\ +ddMTgHUukfMFkYfvSNHlPoByBBCW3D8EXEwst+W0w1AVuNT1AgIIAA=="; + +const EMPTY: &str = "\ +MIIKZwIBAzCCChUGCSqGSIb3DQEHAaCCCgYEggoCMIIJ/jCCBGoGCSqGSIb3DQEHBqCCBFswggRXAgEAMIIEUAYJKoZIhvcNAQcB\ +MF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBDF87jePepeWTUT3j7S2+0SAgIIADAMBggqhkiG9w0CCQUAMB0GCWCGSAFl\ +AwQBKgQQMtr209mOOryP12JAnbtuGoCCA+ByOsav2ReVfVr96Z8DrUpT7Yk491/QW8XjxxzhgZjZ8Vomefv54s/bqm7gd3q9ygOl\ +VMeA0zyOAvdnjFcy65fdJgAsjfj7p8rR46PWk8LsbV5OGgaueG+hDuNNwydEswqCrAN6E66X3X4zADJTzTLU85bbFdMGmdZ86Oly\ +T4eXoQOO9Fc4Sxl6CDMYsSqXft1bdl9byBazMjSpZuvKu+B4OwJx/u7g8f88QoMzRwnai82y/Dn9+aqg4cPq9deK308Yaq7Q4hML\ +uNHfpwUYjbULLBSq4NAzh0brm0vhjcFGJdjKi/S1KkiSFG7+xCzTPU9SFJ7AU/hti1Pe7ibP37dFm4IiYYylkiwNAPQs3q/P6sBc\ +rBYOT6Dyg2e8sQlXvaLp3B/cOheP6vU2k6WbM/2RePREH4Amx2qVdrXvNEM+i1TXMZXdurelNAS7DaG0gyGhmwzeyxApH4QqwNdv\ +DkgkW+sUONsxgJntlBNKEOyiRxi1YYCCFPgtbRucQ6lUSUjnzRr6HiuYApEk71aW/PZAMVhGKnJuoye2K59abhCyH8kxdz/umFzd\ +PNOm5Bjf8oOTtrmYP7JpPcVrDbYOUtJnzhPZEcg+SE9p1gt/lx6GjvqE8+/tZKgSNtd99xFNMat32Qbn8HG75vu0xcq8aVrN17qJ\ +fn68gd2UfGDsNfNwVcIWlTxsMlWHDfCL4QN3af4oFG1phxdMGlID7ALLcnC5VHc2fBaxH4DXTP2mriGGR0NMoZaZTqwyk16gbW5S\ +5bK4AvANC+ej9+PjEEYoHCi5T5Pad7HhkRUHyyrqN/jc+idS8JIzQoSwIH6+PGaDjofhaxr7LtKODmQ3nIAcUMs7n5BqPdcC318H\ +G9NqJ6zvAsbImrWVVYUkGhvA4T3qFqZqUgEzCf0NmTpyb0FHkGwSsmHlMdqr/DhicpBE3TU8Z8NJZOyYplaVRqOc3dRIGuzLqg/1\ +32+qblfFnE/9XidGQepwCMumitELsptymiU1FwdRfLSQjIf6DVbHAy/37RtttDHTrHTK2W8EqCiSSCSHZ4G+ORgTt5jZAn4VQbnC\ +BdtBwky2Cf/afKJYTgmV8He2KJ2DTzRX2APCQ4WRxu5wgnXA+aB/RwJyaXW653X0zh34tuaWTgikN8fJaeqTXq1cSc++vyDGVCpN\ +V5igIWfeNi7bUab6+BaBLxyJ0pIlJtGE5CuVf1bS8vx9/NcA+lyLNKuRNZAC5roLuF+ZcoviCjiVqhVpi6vMo3LjGKxZ+Pc8zl+w\ +G4W28K7Af2ZifdxR9H+5Rqa0ZiGFJOaS7akFeWHuMIML0ghkLrp0C1oG1jCCBYwGCSqGSIb3DQEHAaCCBX0EggV5MIIFdTCCBXEG\ +CyqGSIb3DQEMCgECoIIFOTCCBTUwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEEBwwyhmnKSJx/KzrtErA4x0CAggAMAwG\ +CCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBDf4dc8FXT+aYODSe2aT2gyBIIE0PsozHos8DialF+NaxO4hOL1U8n9PytgmrFH7MmM\ +HMVc3ScUVcgyC94+ZQjBJ3JWOjDo/2k+aH4c3V2k85+mXutBQU+idGNz8gh1DjHKWri8oX6SaogwG0dIVTpgAkeSVApXI1Tdzb7d\ +wxazLFIlFveL2bRGMGPpspMLgF+079AsL8phJ+EtI7G8kONL+406KYqIBr0nsqXravDIIFppB1pX83UqsBEs5Mxgkqh2P/Z9PXyQ\ +1zBCTofzXnwDISsM9WgVZfLyOSchUaO+LXnfxNAsSzm40nBn6N/s3k//JYWzyGQHIK0i/0C09J8AbiS2sGQd2tdDoEYofqECeMRl\ +JdjTv0wmJUMJldjSStDKWVNPTGBiGElWaNmDfhJrTXqIcVvoQRJZHvjCTqaYNqj12Oise2Y4p+u39U7NIVr3P1NoxdV3btaKUczd\ +MtqML1dHQJ5/0KlZBR9KINVNu7XpQpcgEu/KaGEIn6JILvQs5ISjKNmahNsfoCpUGtfV3xF3JzwRYrT9dzL7mr9Mv3s7ArZ34n3m\ +AqrGBGX6gQieMzYAtEJqUxtoNDck3SUNlgbWGs6Z9LHLrnMcCxN+k9xeanj2xnfaXNzCEcjzECvFHSr+RTCR6J+3sLj8QcAN0Pel\ +BjJICGrNHyyo4SqbixYYYe3iRpKFedTEC8ydoVmmeR7MtpSNg9K7a9fbd8cRwb/xCbi2u5t3/kFKy4UAeGVme0Tq95gvGai4/5nV\ +WkjzyXT1BPrnUIszrp0UNTs8MP6oJ1ndvKD4odlAdpQU0Ctl/eqQ+om7kqmWkSFIjUrex+YUv03euMsmUIqu6CpgCCcPV+SKHmU3\ +LPnrGH+oVYU7bPYQJcPfvL0lgcWeDiTp7AHOTB/qxEQ0OgjFc+JjNrmDwhV8qgjvAHtXRJHhRseBEWJs61IHtZ0JMvap53WfIKEn\ +IF0EihMfU1G3ht01uH4mBbUelfItlS9NGrMT+fXIy/qCB8a00doLv6b2xx2s+TBj1F1tXRe47ozNtWKxmTQw3gFhHoXXdRFX+XNa\ +5H+Qm6uGagZp58JQ0ybeit3p1Ck0TO1jYRPeLW1CW06kHCHFsvoYebhGtd9WqNk9KygjVU2h9aCg+Z+8c+mZ3nqxHs0VPMMNGrGE\ +TyUS4TechVigtVMJmj/cJA1Mme4eVyl7W2bdSvZntX+y9VTFMAJk8IHyxN6gOwvHgh/YfmvZQw/6ziL4BwEDcSVzJIGBW6X6PxcN\ +4gQ5kZhfshXwUIEKRebtmo3fTKn8D2WhUVbu3nge1I2G46ol+F2eZMtQisgjbAAxbGLr5Slz4SxijMrVgo8QHXXQhwWU2eeyCrTF\ +PKBUVHQG9CzNGRHsMmEmYk6WTyozR5ma2epCTYRPhR8fUxHxdjDuc/5qEWjPBg8m0FPCo0KbIYuhpZQTl52QRH+0mMs61kQsadow\ +bGTs+NMLOk10piUoMTDjz7A5vJwI5cS4WYmWALpIOXCVwSMLs97yJDOmFj/gFx+vbyn6W9rciQljO93vnpt7BvSUG7RQNufkePDZ\ +3VazbEmFWY0kvdOJDCeUF+AfqiOde94mOY5MNQx377q2yuBH4RNTGgY99r7/dJVd1/okNuLtK9wulLxqnZuV/iUDoF/egG4Egisd\ +Z+MXMSUwIwYJKoZIhvcNAQkVMRYEFIVDIKpsK9ynC1lADgpTGrG04AAzMEkwMTANBglghkgBZQMEAgEFAAQgcAZkx5WYR7XZrovc\ +Pgmgw0IuEAIj4FjBS78Zv6IAsScEEIk50Yy2OM0LI60aLfWObdcCAggA"; + +const SLOW: &str = "\ +MIIKagIBAzCCChcGCSqGSIb3DQEHAaCCCggEggoEMIIKADCCBGsGCSqGSIb3DQEHBqCCBFwwggRYAgEAMIIEUQYJKoZIhvcNAQcB\ +MGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBB8ks0TJ1AMoB0niaJzWOWJAgMehIAwDAYIKoZIhvcNAgkFADAdBglghkgB\ +ZQMEASoEEIQXlt2LpA9dPLJrIQbhjeCAggPgg1hhBenojqTc4iWsTMD37yvBa3dFNQUUB/y9ZLKMbyTRIorQx2API8WUpRqTQJHi\ +ad8BJgN8eUzaOFQtfpeCqeq8g/el9aJ/wiVDdyPWn8bEIa7bKSZUvC5Ei4qun29hHuf0GsEf38TjUz+Vwv+d/VxAnlNQrANGnZ6U\ +qNU1VQSNPhllyJnJGKhOkiCyv+7zn8518laLYcTj+Q6dGl1dINstFS+ve8BFmYv9236f6TNpDPu4n94CyUit2N6Hqg0LAVW6I0ct\ +MXoo6+7x3n0YgRzHNqo7XjfiRY96g2xb3lUJWCaHN1deVgJ1loGLrZZY1AYlWLtvUENZKC+Kwd6YpZbPydB27OApQc2sVkJYjp8T\ +9GDZ86fdIkNlfrKint59TniWPI7IPvXww27v2SHl828ADvaTR2XcS82QOqqq5INMYYRN9Kg4rjzwV1oWmDWywh8vD7cEIbbXzsBj\ +UexF5kzrjpe+j5/VYdA1VYNaERd0RlJqSXuyVxlvCvPziLzeADOoPT1lbVuloxaRNHTkr68hedHXh9Qju2YNUo+P7IbS4HXC6Nh1\ +m+8bjrRzVlA/MsLBhuxkwDv58z7n2B4iLJpu93/ZkxxyMPJI5cMg6ikeNLTmFj7vTxSb8uj31L73CySnXSlhi1CkKHCeofM6cKP+\ +DgUh5f9Axl91e+MOaNpxxZ6rxVaYMmtuzruDeABCRp2AxdA9eo5J2ReC6eHwNwDwVaECI8V1/tfdzdTTbbOD1YuaQ5z2mQgUx+C1\ +mqfVXJgWTnkUgNuwoFgOUJGQfAWuOjcZIaXx7slg9r7xQwitHnc1pn8Lj1ZB5l1ixHxn09wZCoLGhYbgR0fPEp/VQY/RlQZifxnF\ +Nc9LP6U/+qq+VbRmJ+wn7D3vcJ5/IMfOwrzYHBE2PaJLizpMR83W4dPVcOBLyogMowjkPoMFgnDzDOdlxi4Q1yaobzsS6VvnuD4Q\ +R1ehKNDG/x97CzgsFiovUW8KZkXacq0GtOUC8nuUI3O9d+HqBAPejfuq5A51r2pmn005DUCim9AEXYMxibVVqQ/qq2j9YkbRZ0gL\ +7XPiI2fxgR5B8IoZ/vbIopoy5BNhzVMRTGxLSOLLg3Y9gpdxojWS6Vg7Y2rD10UhbjIaMXMnXm2jOQ8Wv3NE5WfHotkpDV1MEEiH\ +xKn0pFByBi+WGIz/fjb6+DZtQ1JqHZZxMTSSOQcC8Ctv+Nlyi8MOxgMXKmuppKFiQxfZxgs/BRGsSY26HlohzkajQSb8nvsnx4er\ +xStV6ylCfQN1miQu1WmBWMa55v2b6YPfq3COIMVWqp/M9vlcdULkgHj23uUwggWNBgkqhkiG9w0BBwGgggV+BIIFejCCBXYwggVy\ +BgsqhkiG9w0BDAoBAqCCBTowggU2MGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBAchZc1zQburwsAUAl9cukPAgMehIAw\ +DAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEG6e5jeQsIVVfYE1Xo/vFtEEggTQpHmb8WWB5X0x2w9LAUs2s9HJD6Sn+TXkOLAg\ +Kgar2eH64/QfaaLyapDTTU5utuJlLYLuse5MmqD2Z6/rzTSNkDidMqhWaORB1AJYuz75BU8l13E8B9oLbgnGeo93XAtAyD+sTQ8M\ +kjc+LyDWgakOLYPLXGO9gPWdMc7qrn2PS8LRpjR7i3TPIJRmIwAiddGr0dZW8uEJke7jFTGkDdyGkR0VF6EeHhYPKQBTVdtqN7wI\ +BugMxrqNbrQjpiZezs91HGcvQK7POy6FGkYtmvjgQuNOO4NEbtXNCG4V8XTud/PgO3i5OEQRioj9TaNWclgTsn5R6hNoULijFYJw\ +jOKAa9MqquQvYoKXE3YlW0AccgpiHBF465DO+TO36vc2Ocy58oCIzwxObK34nbNnHpmQ4fwXtf2u1a43FUROd5d2RN0gCOUrmqdK\ +uPMYABQLgqFtYxKtaNrTBt0sMjdhksW6ttREJiudv8P5Zgo8Lzjrjwp8PSO05Dux5IxOOgnRlG9nl34PysHl5domXrNfs54/iesS\ +f3WakBTSEs5Of4itSRub9cpkMWYlBJ1TmliNBJHibytBQTgGiw2nPIzGlSMDkMQ8TZGBt2LCW8KBKc/4gJHi+AEOS8p5mIk+9DTv\ +Vm1l+i8ljwELfWkFVeHZZ0MKnd4lJY743H4KKvZMT+zMw0OKg7c5Oag9QfXNyBKh2QmgimnM/5Zu1f6DDju0QqCSDov/1nPJ3tdj\ +imCzIh3UxvuM9crzic4qtsQMQz0tNPqZJ2id/icRv4cGNepKUawoS+AcpKDzuMaqAOFWMbSt7WRHONdLbyylZioZQlXu/TaA9Hcm\ +1JItzMDxFh4ZqW9D7MJPs50Zn/aRK3xV5ADuAKCg26WSt+9svgrZS3sG6bF2dVE8M6tV8qz6ljkRRiP5a5YfpmffP/mA//FuKsPH\ +8JoIURm0jLzDF2Cyj2Xk/0HJFSDkbfI4W5O6Fe62QA6hTDlOJjd7eGSCV52u3OUTNK13qMFr8ZdaGfdpMKxt2x7WEufoWbju7TtM\ +4a4bM0AoN2ob2iziC16E0GZQtqVy4is5U/yUs/nLkA1rGdvwwcubIiTaGuI4cmVeVnMqBEp6TFH6WOYSadWmfN2RzMe5gDNFGMJb\ +AUgA9xdwzKRO7C/9fox4PQ2EnVvX1NwzcexeuTE15c0ry3/N9J2CnCmaVZFHyicQYaTOKGPi4bX1ZGSblJwHoJPS+Wm8rfYBXwK6\ +hjmz1SKSt0Eh0e8oKwuM8RwJnAN13lScGT0AD668PaOgzSK3WfMDSJMRJhvzTRmpHc4/eOIa8MbG8rkNm434k7E/jujaWbMAAWCv\ +w2UnOzqmba9buKNE62tSffWE+45pO/9grKFk/X7r6W2U3ECc66iV+NcP+4oLLX4x/w3Oi62M0PaWilWgVgpMZCur3tUb1O9eap8y\ +kToB2qBP0mgYlKbwjka3i1eHoPt472W0+D/ov7PqOt+ZbQqZLFCmXh7MhvNf0K2HrycL7iSb1SSENg3AjLDzbKwQk0cjm4Y37l5x\ +JzLgdnICu18j20yHZzPn7iNUMhQZGn/miKChpNbjOfn5eOdxfHb2tuNhGXUxcIFPHc+llSAae5dNQOx9jdJGIa/FSoZogWVweM8L\ +70AvjLgxJTAjBgkqhkiG9w0BCRUxFgQUhUMgqmwr3KcLWUAOClMasbTgADMwSjAxMA0GCWCGSAFlAwQCAQUABCBSwdTuQqfx6oMN\ +oRpM+476CU35vPBZAg7uDRQ2W0rxuwQQlBfL7bD0DVRjC7ff7DCBfgIDHoSA"; + +pub(crate) const ALICE_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIDfDCCAmSgAwIBAgITBZjuab1kWRuw6iskHm6GfE5XrjANBgkqhkiG9w0BAQsF\nADAsMRgwFgYDVQQDDA9FeGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUw\nIBcNMjYxMTEwMjM1NzM0WhgPMjEyNjEwMTcyMzU3MzRaMDoxFjAUBgNVBAMMDUFs\naWNlIEV4YW1wbGUxIDAeBgkqhkiG9w0BCQEWEWFsaWNlQGV4YW1wbGUub3JnMIIB\nIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxQrWVfKXXVZryeb/vXPHnjxv\nQs0CL+YA3iCrERXXKQdPaul+Ysc4F7/2PM22JvjEU6robJAQjm6HJGK2fCy/ZzJD\npDgEx1fOUZ3uReGFfQJScb9rngD32q7UrDCfluzG+/W+IDQW3AQ2T9FlB8ABkih/\nkyVnFOZSKZHvj/B+lKmUDa1WvWXbsliROVzAQTvmhMYeeAxVwv6yiZ1WJXAvxbyD\nReatJH6C5IXiUtp3ETV0i/SSJbmE0hTl5NyP/lf9KQYOC+27sryxcaTlzNMuA90j\nO1WFY0lSAEXsNbwi8j1sW4cEip765ra9Y08MKce8dqtuXM/wjwrn70NSp3HW4wID\nAQABo4GGMIGDMBwGA1UdEQQVMBOBEWFsaWNlQGV4YW1wbGUub3JnMA4GA1UdDwEB\n/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDBDAdBgNVHQ4EFgQUzgoHCBtIIUUf\n0pUEHAOVQUQ3oOQwHwYDVR0jBBgwFoAUA1dgSumWAOSyoT0IokPfLUhr+yYwDQYJ\nKoZIhvcNAQELBQADggEBAHhlqgdhOJdXxg2JANwLzQvXXeEzXxu4yKGnJG9Zi99r\nohF5smEkNXT0qYjWEM/XHyynR5ozGsN4shlkezmAPkjqR1SYixYa0TgiCjlSYlQ+\ntxiNy4TtW2ZD23PBMGAUvixzCR9lsBrjf59l78Gqd3IyzYIzEApwxXuPPD8tussQ\njoE/QxepD8H3CPRVzBXSmuz0zGVgNtNtLQWv4D61f7RVETf0gUqjn1ezu3/0ih1M\nGkzEhaFVntSRuHw3KETY1Ez/LpzNM+w70UIL/M8XZTnbfzXa/5+RzQKcZLraQS6O\nZEPpVOU/V4dDTj04SPMJT9Ydh0v1UUWhazBvzsb4B7g=\n-----END CERTIFICATE-----\n"; + +pub(crate) const CA_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIDSzCCAjOgAwIBAgIUQiksTfPBn790EMSMwNs3Jn0jaiUwDQYJKoZIhvcNAQEL\nBQAwLDEYMBYGA1UEAwwPRXhhbXBsZSBUZXN0IENBMRAwDgYDVQQKDAdFeGFtcGxl\nMCAXDTI2MTExMDIzNTczNFoYDzIxMjYxMDE3MjM1NzM0WjAsMRgwFgYDVQQDDA9F\neGFtcGxlIFRlc3QgQ0ExEDAOBgNVBAoMB0V4YW1wbGUwggEiMA0GCSqGSIb3DQEB\nAQUAA4IBDwAwggEKAoIBAQCLZYmAht/KhFBvK9uNCHWCQ0viLErOUqeX1aXmT1gD\nK7pnO17kenetbfhEY1tBB8bvhkLYcW+A10RZslY/ZMJsf8PTHA+B+gZB5GdIDtAC\nASHTmiBJIr9bdJiD+eZ1hDNfSvXm2dlF7qEnaaUj+GoowKnyqkGQ4EbfFcVT1rJR\n09Gx1yu1Ti5gKG4/BoAZ9Q/Ho/TGKXhCOLbecWzFzFHMbwLU+oY5rVjibp/FVbwT\nC54cuuqmwS1z+t/ABBvIUv5cVZloWXcoe1Sw2KSN7IaGGM3ziCSDBM6RZiUsD/Fr\n6CkW5m2c+XPOSTwfHPz8h39bCITS0DbB86fXDy7kZQTTAgMBAAGjYzBhMB0GA1Ud\nDgQWBBQDV2BK6ZYA5LKhPQiiQ98tSGv7JjAfBgNVHSMEGDAWgBQDV2BK6ZYA5LKh\nPQiiQ98tSGv7JjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkq\nhkiG9w0BAQsFAAOCAQEAaT1BKjztiC5bgQ3hT0zRsqSLXlzGGRYAMC49eLPAAPvO\n6CL+ZPvNByZKTRy6pt+Tr06nbj7YH92z4xO601vILQBmBwwhsQNMotKDZ/Qedb8t\ng6maxc83l5rKOR/XHze6nIoFQR1uYWrvLT/JpwTZ9SfDk5pbMVCRyExACSAQL3NF\nS1boSb2RndOIHAcwKUF7uEYm+uoMbttCFcFZTcNcO1swL43/562cJ8w2AWwCBv4j\nz0Kcna6idZx/eTZxkHizZwMGzJL9Hzbvui0gPBu0RNAbBUTeJawC/1IOEFQq43Fj\nMxttmH5D5Ax3nffhFlrAH2IgjiHTI+IbzIzNR1J0Xw==\n-----END CERTIFICATE-----\n"; + +#[test] +fn matching_local_id_cannot_override_a_different_public_key() { + // Both are 2048-bit RSA, but the CA certificate does not belong to Alice's key. + let key = rsa_key(); + let alice = der(ALICE_PEM); + let other = der(CA_PEM); + let alice_key = crate::cert::Cert::from_der(&alice).unwrap(); + let other_key = crate::cert::Cert::from_der(&other).unwrap(); + assert_eq!(crate::algorithms::key_kind(alice_key.public_key()), crate::algorithms::key_kind(other_key.public_key())); + assert_ne!(alice_key.public_key(), other_key.public_key()); + assert!(open(&plain_p12(&key, &alice, b"same-id"), PASS).is_ok()); + assert_eq!(open(&plain_p12(&key, &other, b"same-id"), PASS).err(), Some(Error::NoCertificate)); +} + +#[test] +fn ec_key_pairing_is_derived_not_claimed_by_metadata() { + for algorithm in [&rcgen::PKCS_ECDSA_P256_SHA256, &rcgen::PKCS_ECDSA_P384_SHA384] { + let key = rcgen::KeyPair::generate_for(algorithm).unwrap(); + let other = rcgen::KeyPair::generate_for(algorithm).unwrap(); + let params = rcgen::CertificateParams::new(vec!["example.org".into()]).unwrap(); + let certificate = params.self_signed(&key).unwrap(); + let wrong = params.self_signed(&other).unwrap(); + let pkcs8 = key.serialize_der(); + let (info, _) = craft_ber::read(&pkcs8).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (inner, _) = craft_ber::read(fields[2].value).unwrap(); + let parts = craft_ber::children(inner.value).unwrap(); + let without_point: Vec> = parts.iter().filter(|p| p.tag != 0xa1).map(|p| p.whole.to_vec()).collect(); + let omitted = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&without_point))]); + assert!(open(&plain_p12(&omitted, certificate.der(), b"same-id"), PASS).is_ok()); + assert_eq!(open(&plain_p12(&omitted, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate)); + + let other_der = other.serialize_der(); + let (other_info, _) = craft_ber::read(&other_der).unwrap(); + let other_fields = craft_ber::children(other_info.value).unwrap(); + let (other_inner, _) = craft_ber::read(other_fields[2].value).unwrap(); + let other_parts = craft_ber::children(other_inner.value).unwrap(); + let point = other_parts.iter().find(|p| p.tag == 0xa1).unwrap(); + let mut forged_parts = without_point; + forged_parts.push(point.whole.to_vec()); + let forged = seq(&[fields[0].whole.to_vec(), fields[1].whole.to_vec(), tlv(0x04, &seq(&forged_parts))]); + assert_eq!(open(&plain_p12(&forged, wrong.der(), b"same-id"), PASS).err(), Some(Error::NoCertificate)); + } +} + +#[test] +fn legacy_decryption_uses_the_empty_password_representation_verified_by_the_mac() { + use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7}; + use hmac::{KeyInit, Mac}; + use pkcs12::kdf::{Pkcs12KeyType, derive_key}; + let salt = b"empty password fixture salt"; + let key = rsa_key(); + let certificate = der(ALICE_PEM); + for password in [b"".as_slice(), &[0, 0][..]] { + for encrypt_safe in [false, true] { + let encrypt = |plain: &[u8]| { + let key = derive_key::(password, salt, Pkcs12KeyType::EncryptionKey, 2048, 24).unwrap(); + let iv = derive_key::(password, salt, Pkcs12KeyType::Iv, 2048, 8).unwrap(); + let mut buffer = plain.to_vec(); + buffer.resize(plain.len() + 8, 0); + cbc::Encryptor::::new_from_slices(&key, &iv) + .unwrap() + .encrypt_padded::(&mut buffer, plain.len()) + .unwrap() + .to_vec() + }; + let algorithm = seq(&[oid("1.2.840.113549.1.12.1.3"), seq(&[tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])])]); + let key_bag = if encrypt_safe { + bag("1.2.840.113549.1.12.10.1.1", key.clone(), b"id") + } else { + bag("1.2.840.113549.1.12.10.1.2", seq(&[algorithm.clone(), tlv(0x04, &encrypt(&key))]), b"id") + }; + let cert = seq(&[oid("1.2.840.113549.1.9.22.1"), tlv(0xa0, &tlv(0x04, &certificate))]); + let safe = seq(&[key_bag, bag("1.2.840.113549.1.12.10.1.3", cert, b"id")]); + let data = |content: &[u8]| seq(&[oid("1.2.840.113549.1.7.1"), tlv(0xa0, &tlv(0x04, content))]); + let content = if encrypt_safe { + let encrypted_info = seq(&[oid("1.2.840.113549.1.7.1"), algorithm, tlv(0x80, &encrypt(&safe))]); + seq(&[oid("1.2.840.113549.1.7.6"), tlv(0xa0, &seq(&[tlv(0x02, &[0]), encrypted_info]))]) + } else { + data(&safe) + }; + let auth_safe = seq(&[content]); + let mac_key = derive_key::(password, salt, Pkcs12KeyType::Mac, 2048, 32).unwrap(); + let mut mac = as KeyInit>::new_from_slice(&mac_key).unwrap(); + mac.update(&auth_safe); + let digest = mac.finalize().into_bytes(); + let sha256 = seq(&[oid("2.16.840.1.101.3.4.2.1"), vec![0x05, 0]]); + let mac_data = seq(&[seq(&[sha256, tlv(0x04, &digest)]), tlv(0x04, salt), tlv(0x02, &[0x08, 0x00])]); + let p12 = seq(&[tlv(0x02, &[3]), data(&auth_safe), mac_data]); + let opened = open(&p12, "").unwrap(); + assert_eq!(&*opened.private_key, &key); + assert_eq!(opened.certificate, certificate); + assert!(opened.key_encrypted); + assert_eq!(open(&p12, "wrong").err(), Some(Error::WrongPassphrase)); + } + } +} diff --git a/crates/smime/src/tests.rs b/crates/smime/src/tests.rs new file mode 100644 index 0000000000..0b9c83948d --- /dev/null +++ b/crates/smime/src/tests.rs @@ -0,0 +1,1104 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Checking S/MIME Digital signatures (#30): fixed vectors signed with RFC 9216's example +//! certificate for Alice (by OpenSSL, `testdata/`), and certificates of example.org authorities +//! and signers made here; and never a panic on any bytes. + +use crate::digital_signature::{Coverage, Verdict, Why}; +use cms::cert::IssuerAndSerialNumber; +use cms::content_info::{CmsVersion, ContentInfo}; +use cms::signed_data::{CertificateSet, EncapsulatedContentInfo, SignedData, SignerIdentifier, SignerInfo, SignerInfos}; +use const_oid::ObjectIdentifier; +use der::asn1::{OctetString, SetOfVec}; +use der::{Any, Decode, Encode}; +use proptest::prelude::*; +use spki::AlgorithmIdentifierOwned; +use x509_cert::Certificate; +use x509_cert::attr::Attribute; + +use crate::{Anchors, Checked, Context, Signed, check}; + +const CA: &[u8] = include_bytes!("../testdata/ca.rsa.der"); +const ALICE: &[u8] = include_bytes!("../testdata/alice.sign.der"); +const DETACHED: &[u8] = include_bytes!("../testdata/detached.eml"); +const OPAQUE: &[u8] = include_bytes!("../testdata/opaque.eml"); +const OPAQUE_BER: &[u8] = include_bytes!("../testdata/opaque-ber.eml"); +const SHA1: &[u8] = include_bytes!("../testdata/sha1.eml"); +const NO_ATTRIBUTES: &[u8] = include_bytes!("../testdata/noattr.eml"); +const PSS: &[u8] = include_bytes!("../testdata/pss.eml"); +const NO_CERTS: &[u8] = include_bytes!("../testdata/nocerts.eml"); + +/// 2026-11-09, within the RFC 9216 certificates' years. +const NOW: i64 = 1_794_182_400; + +fn base64(text: &[u8]) -> Vec { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = Vec::new(); + let (mut acc, mut bits) = (0u32, 0u32); + for c in text { + let Some(v) = ALPHABET.iter().position(|a| a == c) else { continue }; + acc = (acc << 6) | v as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + out +} + +/// A message's body: what follows its first empty line. +fn body(message: &[u8]) -> &[u8] { + let at = message.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + &message[at + 4..] +} + +/// The two halves of a detached fixture: the signed part as it came, and the CMS. +fn halves(message: &[u8]) -> (Vec, Vec) { + let text = String::from_utf8_lossy(message); + let boundary = text.split("boundary=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); + let delimiter = format!("\r\n--{boundary}"); + let body = String::from_utf8_lossy(body(message)).into_owned(); + let pieces: Vec<&str> = body.split(delimiter.as_str()).collect(); + // pieces[0] is the preamble up to the first delimiter line; the content follows its CRLF. + let content = pieces[1].strip_prefix("\r\n").unwrap().as_bytes().to_vec(); + let signature_part = pieces[2].strip_prefix("\r\n").unwrap(); + (content, base64(body_of(signature_part.as_bytes()))) +} + +fn body_of(part: &[u8]) -> &[u8] { + let at = part.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + &part[at + 4..] +} + +fn anchors() -> Anchors { + Anchors::new([CA]) +} + +fn checked_detached(message: &[u8], anchors: &Anchors, from: &str, now: i64, known: &[&[u8]]) -> Checked { + let (content, signature) = halves(message); + check(Signed::Detached { content: &content, signature: &signature }, &Context { anchors, from, now, known, coverage: Coverage::Whole }).unwrap() +} + +fn checked_opaque(message: &[u8], anchors: &Anchors, from: &str) -> Checked { + let cms = base64(body(message)); + check(Signed::Opaque(&cms), &Context { anchors, from, now: NOW, known: &[], coverage: Coverage::Whole }).unwrap() +} + +#[test] +fn alices_detached_signature_is_verified() { + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + assert_eq!(c.signature.why, None); + let signer = c.signature.signer.clone().unwrap(); + assert_eq!(signer.name, "Alice Lovelace"); + assert_eq!(signer.addresses, vec!["alice@smime.example".to_string()]); + assert_eq!(signer.issuer, "Sample LAMPS RSA Certification Authority"); + assert_eq!(signer.fingerprint.len(), 32 * 3 - 1); + assert!(signer.not_before < NOW && NOW < signer.not_after); + assert!(c.signature.signed_at.is_some(), "OpenSSL gives a signing time"); + assert!(!c.signature.revocation_checked); + assert_eq!(c.certificate.as_deref(), Some(ALICE), "the certificate is worth keeping"); +} + +#[test] +fn the_address_is_compared_without_regard_to_case() { + let c = checked_detached(DETACHED, &anchors(), "Alice@SMIME.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn opaque_ber_pss_and_bare_signatures_are_verified() { + for message in [OPAQUE, OPAQUE_BER] { + let c = checked_opaque(message, &anchors(), "alice@smime.example"); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + } + for message in [NO_ATTRIBUTES, PSS] { + let c = checked_detached(message, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!(c.signature.verdict, Verdict::Verified, "{c:?}"); + } +} + +#[test] +fn sha1_is_no_longer_safe() { + let c = checked_detached(SHA1, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::WeakAlgorithm))); + assert_eq!(c.certificate, None); +} + +#[test] +fn a_signature_without_its_certificate_needs_one_kept_here() { + let c = checked_detached(NO_CERTS, &anchors(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::NoPublicKey))); + let c = checked_detached(NO_CERTS, &anchors(), "alice@smime.example", NOW, &[ALICE]); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn an_unknown_issuer_another_address_and_an_expired_certificate_are_not_verified() { + let c = checked_detached(DETACHED, &Anchors::default(), "alice@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::UnknownIssuer))); + assert_eq!(c.certificate, None, "only a certificate that is trusted and valid is kept (#30 review 7)"); + let c = checked_detached(DETACHED, &anchors(), "bob@smime.example", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::AddressMismatch))); + assert_eq!(c.certificate, None, "not kept for an address it isn't for"); + // 2060: past 2052. + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", 2_840_140_800, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::Expired))); + assert_eq!(c.certificate, None, "nor one out of date"); + let c = checked_detached(DETACHED, &anchors(), "alice@smime.example", NOW, &[]); + assert!(c.certificate.is_some(), "a trusted one, valid now, for the sender, is"); +} + +#[test] +fn a_change_after_signing_is_seen() { + let (mut content, signature) = halves(DETACHED); + let at = content.windows(7).position(|w| w == b"Tuesday").unwrap(); + content[at] = b'W'; + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Changed, Some(Why::Altered))); + // Opaque: the content inside the CMS. + let mut cms = base64(body(OPAQUE)); + let at = cms.windows(7).position(|w| w == b"Tuesday").unwrap(); + cms[at] = b'W'; + let c = + check(Signed::Opaque(&cms), &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); + // The signature itself. + let (content, mut signature) = halves(DETACHED); + let last = signature.len() - 1; + signature[last] ^= 1; + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); +} + +#[test] +fn content_in_lf_lines_is_checked_in_its_canonical_form() { + let (content, signature) = halves(DETACHED); + let lf: Vec = String::from_utf8_lossy(&content).replace("\r\n", "\n").into_bytes(); + let c = check( + Signed::Detached { content: &lf, signature: &signature }, + &Context { anchors: &anchors(), from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Verified); +} + +#[test] +fn enveloped_data_is_no_digital_signature_and_junk_is_unreadable() { + // ContentInfo { envelopedData, [0] { SEQUENCE {} } }. + let enveloped = [0x30, 0x0f, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x03, 0xa0, 0x02, 0x30, 0x00]; + let context = Context { anchors: &Anchors::default(), from: "a@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + assert_eq!(check(Signed::Opaque(&enveloped), &context), None); + let junk = check(Signed::Opaque(b"not a CMS"), &context).unwrap(); + assert_eq!((junk.signature.verdict, junk.signature.why), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +// ---- certificates made here ---- + +const SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"); +const ECDSA_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"); +const ECDSA_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3"); +const SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"); + +struct Made { + der: Vec, + key: rcgen::KeyPair, + params: rcgen::CertificateParams, +} + +fn params(name: &str) -> rcgen::CertificateParams { + let mut p = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + p.distinguished_name = rcgen::DistinguishedName::new(); + p.distinguished_name.push(rcgen::DnType::CommonName, name); + p.not_before = rcgen::date_time_ymd(2020, 1, 1); + p.not_after = rcgen::date_time_ymd(2050, 1, 1); + p +} + +fn ca_params(name: &str) -> rcgen::CertificateParams { + let mut p = params(name); + p.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + p.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign, rcgen::KeyUsagePurpose::CrlSign]; + p +} + +fn signer_params(name: &str, address: &str) -> rcgen::CertificateParams { + let mut p = params(name); + p.subject_alt_names = vec![rcgen::SanType::Rfc822Name(address.try_into().unwrap())]; + p.key_usages = vec![rcgen::KeyUsagePurpose::DigitalSignature]; + p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::EmailProtection]; + p +} + +fn key(alg: &'static rcgen::SignatureAlgorithm) -> rcgen::KeyPair { + rcgen::KeyPair::generate_for(alg).unwrap() +} + +fn root(name: &str) -> Made { + let key = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let params = ca_params(name); + let der = params.self_signed(&key).unwrap().der().to_vec(); + Made { der, key, params } +} + +fn issued(params: rcgen::CertificateParams, key: rcgen::KeyPair, by: &Made) -> Made { + let issuer = rcgen::Issuer::new(by.params.clone(), &by.key); + let der = params.signed_by(&key, &issuer).unwrap().der().to_vec(); + Made { der, key, params } +} + +/// A detached CMS SignedData over `content` by `signer`, carrying `certs`. +fn sign(content: &[u8], signer: &Made, certs: &[&Made], p384: bool) -> Vec { + sign_with(content, signer, certs, p384, |_| {}) +} + +/// [`sign`], with the signer's information changed by `tweak` after it is made. +fn sign_with(content: &[u8], signer: &Made, certs: &[&Made], p384: bool, tweak: impl Fn(&mut SignerInfo)) -> Vec { + sign_data_with(content, signer, certs, p384, tweak, |_| {}) +} + +/// [`sign_with`], with the SignedData changed by `tweak_data` too. +fn sign_data_with( + content: &[u8], + signer: &Made, + certs: &[&Made], + p384: bool, + tweak: impl Fn(&mut SignerInfo), + tweak_data: impl Fn(&mut SignedData), +) -> Vec { + let cert = Certificate::from_der(&signer.der).unwrap(); + let (digest_oid, sig_oid) = if p384 { (SHA384, ECDSA_SHA384) } else { (SHA256, ECDSA_SHA256) }; + let digest = if p384 { ring::digest::digest(&ring::digest::SHA384, content) } else { ring::digest::digest(&ring::digest::SHA256, content) }; + let attr = |oid: &str, value: Any| Attribute { oid: ObjectIdentifier::new_unwrap(oid), values: SetOfVec::try_from(vec![value]).unwrap() }; + let attrs: SetOfVec = SetOfVec::try_from(vec![ + attr("1.2.840.113549.1.9.3", Any::encode_from(&ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1")).unwrap()), + attr("1.2.840.113549.1.9.4", Any::encode_from(&OctetString::new(digest.as_ref().to_vec()).unwrap()).unwrap()), + ]) + .unwrap(); + let to_sign = attrs.to_der().unwrap(); + let alg = if p384 { &ring::signature::ECDSA_P384_SHA384_ASN1_SIGNING } else { &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING }; + let rng = ring::rand::SystemRandom::new(); + let pair = ring::signature::EcdsaKeyPair::from_pkcs8(alg, &signer.key.serialize_der(), &rng).unwrap(); + let signature = pair.sign(&rng, &to_sign).unwrap(); + let info = SignerInfo { + version: CmsVersion::V1, + sid: SignerIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber { + issuer: cert.tbs_certificate().issuer().clone(), + serial_number: cert.tbs_certificate().serial_number().clone(), + }), + digest_alg: AlgorithmIdentifierOwned { oid: digest_oid, parameters: None }, + signed_attrs: Some(attrs), + signature_algorithm: AlgorithmIdentifierOwned { oid: sig_oid, parameters: None }, + signature: OctetString::new(signature.as_ref().to_vec()).unwrap(), + unsigned_attrs: None, + }; + let mut info = info; + tweak(&mut info); + let set: Vec = + certs.iter().map(|c| cms::cert::CertificateChoices::Certificate(Certificate::from_der(&c.der).unwrap())).collect(); + let mut data = SignedData { + version: CmsVersion::V1, + digest_algorithms: SetOfVec::try_from(vec![AlgorithmIdentifierOwned { oid: digest_oid, parameters: None }]).unwrap(), + encap_content_info: EncapsulatedContentInfo { econtent_type: ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"), econtent: None }, + certificates: Some(CertificateSet::try_from(set).unwrap()), + crls: None, + signer_infos: SignerInfos::try_from(vec![info]).unwrap(), + }; + tweak_data(&mut data); + ContentInfo { content_type: ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2"), content: Any::encode_from(&data).unwrap() }.to_der().unwrap() +} + +fn verdict(cms: &[u8], content: &[u8], anchors: &Anchors, from: &str) -> (Verdict, Option) { + let c = check(Signed::Detached { content, signature: cms }, &Context { anchors, from, now: NOW, known: &[], coverage: Coverage::Whole }).unwrap(); + (c.signature.verdict, c.signature.why) +} + +const CONTENT: &[u8] = b"Content-Type: text/plain\r\n\r\nThe accounts are ready.\r\n"; + +#[test] +fn a_path_through_an_intermediate_authority_is_verified() { + let root = root("Example Root"); + let intermediate = issued(ca_params("Example Mail CA"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &intermediate); + let cms = sign(CONTENT, &ada, &[&ada, &intermediate], false); + let anchors = Anchors::new([&root.der]); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // Without the intermediate authority's certificate there is no path. + let alone = sign(CONTENT, &ada, &[&ada], false); + assert_eq!(verdict(&alone, CONTENT, &anchors, "ada@example.org"), (Verdict::NotVerified, Some(Why::UnknownIssuer))); + // A P-384 signer. + let grace = issued(signer_params("Grace", "grace@example.org"), key(&rcgen::PKCS_ECDSA_P384_SHA384), &intermediate); + let cms = sign(CONTENT, &grace, &[&grace, &intermediate], true); + assert_eq!(verdict(&cms, CONTENT, &anchors, "grace@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn a_certificate_not_for_mail_or_signed_by_itself_is_not_verified() { + let root = root("Example Root"); + let anchors = Anchors::new([&root.der]); + let mut web = signer_params("Web", "web@example.org"); + web.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]; + let web = issued(web, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &web, &[&web], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "web@example.org"), (Verdict::NotVerified, Some(Why::NotForEmail))); + let own_key = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let own_params = signer_params("Self", "self@example.org"); + let own = Made { der: own_params.self_signed(&own_key).unwrap().der().to_vec(), key: own_key, params: own_params }; + let cms = sign(CONTENT, &own, &[&own], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "self@example.org"), (Verdict::NotVerified, Some(Why::SelfSigned))); + // Unless the host trusts it itself. + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&own.der]), "self@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn an_expired_link_is_not_verified() { + let root = root("Example Root"); + let mut old = signer_params("Old", "old@example.org"); + old.not_after = rcgen::date_time_ymd(2021, 1, 1); + let old = issued(old, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &old, &[&old], false); + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&root.der]), "old@example.org"), (Verdict::NotVerified, Some(Why::Expired))); +} + +#[test] +fn a_certificate_from_another_authority_of_the_same_name_is_not_trusted() { + let real = root("Example Root"); + let fake = root("Example Root"); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &fake); + let cms = sign(CONTENT, &ada, &[&ada], false); + assert_eq!(verdict(&cms, CONTENT, &Anchors::new([&real.der]), "ada@example.org"), (Verdict::NotVerified, Some(Why::UnknownIssuer))); +} + +/// A certificate of the signer's issuer and serial number put in the message (anybody can put +/// one there) is not the signer's unless its key made the signature: it changes nothing. +#[test] +fn a_certificate_that_only_claims_the_signers_name_changes_nothing() { + let real = root("Example Root"); + let fake = root("Example Root"); + let serial = |mut p: rcgen::CertificateParams| { + p.serial_number = Some(rcgen::SerialNumber::from(vec![0x30, 0x01, 0x02])); + p + }; + let ada = issued(serial(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &real); + let impostor = issued(serial(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &fake); + let anchors = Anchors::new([&real.der]); + // The impostor first: the signer is still found, and verified. + let cms = sign(CONTENT, &ada, &[&impostor, &ada], false); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // Changed content is put down to the signer that fits, and named. + let changed = b"Content-Type: text/plain\r\n\r\nThe accounts are empty.\r\n"; + let c = check( + Signed::Detached { content: changed, signature: &cms }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Changed, Some(Why::Altered))); + let named = c.signature.signer.unwrap(); + assert_eq!(named.fingerprint, crate::cert::Cert::from_der(&ada.der).unwrap().fingerprint(), "the real signer, not the impostor"); + // With only the impostor's certificate, nobody is named as having signed it. + let alone = sign(CONTENT, &ada, &[&impostor], false); + let c = check( + Signed::Detached { content: CONTENT, signature: &alone }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Changed); + assert!(c.signature.signer.is_none()); + assert!(c.certificate.is_none(), "nothing of it is kept"); +} + +/// A signature that can't be read is "can't be checked", never "changed". +#[test] +fn a_malformed_signature_cant_be_checked() { + let root = root("Example Root"); + let ada = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let junk = sign_with(CONTENT, &ada, &[&ada], false, |info| info.signature = OctetString::new(vec![0xff; 12]).unwrap()); + assert_eq!(verdict(&junk, CONTENT, &Anchors::new([&root.der]), "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // An RSA signature algorithm for an elliptic-curve key: of different kinds. + let crossed = sign_with(CONTENT, &ada, &[&ada], false, |info| { + info.signature_algorithm = AlgorithmIdentifierOwned { oid: ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11"), parameters: None } + }); + assert_eq!(verdict(&crossed, CONTENT, &Anchors::new([&root.der]), "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +/// A valid signature by a trusted signer over only part of a message (a wrapper's first part) +/// is never verified for the message. +#[test] +fn a_signature_over_part_of_a_message_is_not_verified_for_it() { + let (content, signature) = halves(DETACHED); + let anchors = anchors(); + let c = check( + Signed::Detached { content: &content, signature: &signature }, + &Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Part }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::PartlySigned))); + assert_eq!(c.signature.coverage, Coverage::Part); + // A message from several people is nobody's alone: no address matches. + let c = checked_detached(DETACHED, &anchors, "", NOW, &[]); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::NotVerified, Some(Why::AddressMismatch))); +} + +// ---- #30 review: what a path must keep (RFC 5280 §4.2, §6.1) ---- + +/// An authority's certificate for `name` issued by `by`, changed by `change` first. +fn authority(name: &str, by: &Made, change: impl FnOnce(&mut rcgen::CertificateParams)) -> Made { + let mut p = ca_params(name); + change(&mut p); + issued(p, key(&rcgen::PKCS_ECDSA_P256_SHA256), by) +} + +fn signer_by(name: &str, address: &str, by: &Made) -> Made { + issued(signer_params(name, address), key(&rcgen::PKCS_ECDSA_P256_SHA256), by) +} + +/// The verdict for a message by `leaf` carrying `chain`, against `root`. +fn path_verdict(leaf: &Made, chain: &[&Made], root: &Made, from: &str) -> (Verdict, Option) { + let mut certs = vec![leaf]; + certs.extend_from_slice(chain); + let cms = sign(CONTENT, leaf, &certs, false); + verdict(&cms, CONTENT, &Anchors::new([&root.der]), from) +} + +#[test] +fn name_constraints_on_mail_addresses_are_kept() { + let root = root("Example Root"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("corp.example".into())], + excluded_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("ceo@corp.example".into())], + }) + }); + let inside = signer_by("Ada", "ada@corp.example", &corp); + assert_eq!(path_verdict(&inside, &[&corp], &root, "ada@corp.example"), (Verdict::Verified, None)); + let outside = signer_by("CEO", "ceo@bank.example", &corp); + assert_eq!(path_verdict(&outside, &[&corp], &root, "ceo@bank.example"), (Verdict::NotVerified, Some(Why::Constrained))); + let excluded = signer_by("CEO", "ceo@corp.example", &corp); + assert_eq!(path_verdict(&excluded, &[&corp], &root, "ceo@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + // A leading dot: any host under the domain, not the domain itself. + let sub = authority("Sub CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name(".corp.example".into())], + excluded_subtrees: vec![], + }) + }); + let mail = signer_by("Ada", "ada@mail.corp.example", &sub); + assert_eq!(path_verdict(&mail, &[&sub], &root, "ada@mail.corp.example"), (Verdict::Verified, None)); + let bare = signer_by("Ada", "ada@corp.example", &sub); + assert_eq!(path_verdict(&bare, &[&sub], &root, "ada@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + assert!(crate::cert::mail_within("Ada@Corp.Example", "corp.example")); + assert!(!crate::cert::mail_within("ada@evilcorp.example", ".corp.example")); +} + +#[test] +fn name_constraints_on_directory_names_are_kept() { + let root = root("Example Root"); + let mut corp_dn = rcgen::DistinguishedName::new(); + corp_dn.push(rcgen::DnType::OrganizationName, "Corp"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(corp_dn.clone())], + excluded_subtrees: vec![], + }) + }); + let mut inside = signer_params("Ada", "ada@corp.example"); + inside.distinguished_name = rcgen::DistinguishedName::new(); + inside.distinguished_name.push(rcgen::DnType::OrganizationName, "Corp"); + inside.distinguished_name.push(rcgen::DnType::CommonName, "Ada"); + let inside = issued(inside, key(&rcgen::PKCS_ECDSA_P256_SHA256), &corp); + assert_eq!(path_verdict(&inside, &[&corp], &root, "ada@corp.example"), (Verdict::Verified, None)); + let outside = signer_by("Mallory", "mallory@corp.example", &corp); + assert_eq!(path_verdict(&outside, &[&corp], &root, "mallory@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn an_excluded_directory_name_written_another_way_is_still_excluded() { + let root = root("Example Root"); + let mut rogue = rcgen::DistinguishedName::new(); + rogue.push(rcgen::DnType::OrganizationName, "Rogue Unit"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(rogue)] }) + }); + // The same name in another string type, case and spacing (RFC 5280 §7.1). + let mut dressed = signer_params("Mallory", "mallory@corp.example"); + dressed.distinguished_name = rcgen::DistinguishedName::new(); + dressed.distinguished_name.push(rcgen::DnType::OrganizationName, rcgen::DnValue::PrintableString(" ROGUE unit ".try_into().unwrap())); + dressed.distinguished_name.push(rcgen::DnType::CommonName, "Mallory"); + let dressed = issued(dressed, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&dressed, &[&ca], &root, "mallory@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); + let other = signer_by("Ada", "ada@corp.example", &ca); + assert_eq!(path_verdict(&other, &[&ca], &root, "ada@corp.example"), (Verdict::Verified, None)); +} + +#[test] +fn an_unknown_critical_extension_is_refused() { + let root = root("Example Root"); + let mut odd = signer_params("Ada", "ada@example.org"); + let mut ext = rcgen::CustomExtension::from_oid_content(&[1, 3, 6, 1, 4, 1, 99999, 1], vec![0x05, 0x00]); + ext.set_criticality(true); + odd.custom_extensions = vec![ext]; + let odd = issued(odd, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&odd, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + // On an authority on the way too. + let ca = authority("Odd CA", &root, |p| { + let mut ext = rcgen::CustomExtension::from_oid_content(&[1, 3, 6, 1, 4, 1, 99999, 2], vec![0x05, 0x00]); + ext.set_criticality(true); + p.custom_extensions = vec![ext]; + }); + let ada = signer_by("Ada", "ada@example.org", &ca); + assert_eq!(path_verdict(&ada, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn a_path_length_constraint_is_kept() { + let root = root("Example Root"); + let ca = authority("Mail CA", &root, |p| p.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Constrained(0))); + let rogue = authority("Rogue CA", &ca, |_| {}); + let leaf = signer_by("Ada", "ada@example.org", &rogue); + assert_eq!(path_verdict(&leaf, &[&rogue, &ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + // Directly below it, a signer is fine. + let direct = signer_by("Ada", "ada@example.org", &ca); + assert_eq!(path_verdict(&direct, &[&ca], &root, "ada@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn an_authority_not_for_mail_cant_vouch_for_a_mail_certificate() { + let root = root("Example Root"); + let web = authority("Web CA", &root, |p| p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth]); + let leaf = signer_by("Ada", "ada@example.org", &web); + assert_eq!(path_verdict(&leaf, &[&web], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + let mail = authority("Mail CA", &root, |p| p.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::EmailProtection]); + let leaf = signer_by("Ada", "ada@example.org", &mail); + assert_eq!(path_verdict(&leaf, &[&mail], &root, "ada@example.org"), (Verdict::Verified, None)); +} + +#[test] +fn another_path_is_tried_when_the_first_doesnt_hold() { + let root = root("Example Root"); + let shared = key(&rcgen::PKCS_ECDSA_P256_SHA256); + let again = || rcgen::KeyPair::try_from(shared.serialize_der().as_slice()).unwrap(); + // The same authority, its key and name, in two certificates: one ran out, one is current. + let mut old = ca_params("Mail CA"); + old.not_after = rcgen::date_time_ymd(2021, 1, 1); + let old = issued(old, again(), &root); + let current = issued(ca_params("Mail CA"), again(), &root); + let leaf = signer_by("Ada", "ada@example.org", ¤t); + assert_eq!(path_verdict(&leaf, &[&old, ¤t], &root, "ada@example.org"), (Verdict::Verified, None)); + assert_eq!(path_verdict(&leaf, &[&old], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Expired))); +} + +#[test] +fn the_search_for_a_path_keeps_to_its_budget() { + let root = root("Example Root"); + let a = authority("A CA", &root, |_| {}); + let b = authority("B CA", &a, |_| {}); + let leaf = signer_by("Ada", "ada@example.org", &b); + let pool: Vec = [&b, &a].iter().map(|m| crate::cert::Cert::from_der(&m.der).unwrap()).collect(); + let leaf = crate::cert::Cert::from_der(&leaf.der).unwrap(); + let anchors = Anchors::new([&root.der]); + let mut budget = 3; + assert_eq!(crate::chain::trust(&leaf, &pool, &anchors, NOW, &mut budget), Ok(())); + assert_eq!(budget, 0, "three links, three signatures"); + let mut budget = 2; + assert_eq!(crate::chain::trust(&leaf, &pool, &anchors, NOW, &mut budget), Err(Why::TooMuch), "stops when it runs out, and says so"); + assert_eq!(crate::MAX_VERIFICATIONS, 32); +} + +/// `cms` with its signers' information put in place of its own, in this order. +fn with_signers(cms: &[u8], infos: &[&[u8]]) -> Vec { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + let mut inner: Vec = parts[..parts.len() - 1].iter().flat_map(|p| p.whole.to_vec()).collect(); + inner.extend(tlv(0x31, &infos.concat())); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &tlv(0x30, &inner))); + tlv(0x30, &ci) +} + +/// The first signer's information in `cms`, as it is written. +fn first_signer(cms: &[u8]) -> Vec { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + craft_ber::children(parts.last().unwrap().value).unwrap()[0].whole.to_vec() +} + +/// The second try of a signature without signed attributes, over the content in its canonical +/// form, is a verification of its own, paid from the budget (#30 review 6). +#[test] +fn the_canonical_try_is_paid_from_the_budget() { + const LF: &[u8] = b"Content-Type: text/plain\n\nThe accounts are ready.\n"; + let root = root("Example Root"); + let mail = authority("Mail CA", &root, |_| {}); + let ada = signer_by("Ada", "ada@example.org", &mail); + // Without its signed attributes, the signature (made over them) fails as it came and in the + // canonical form alike. + let cms = sign_with(LF, &ada, &[&ada], false, |i| i.signed_attrs = None); + let anchors = Anchors::default(); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + let signed = Signed::Detached { content: LF, signature: &cms }; + let one = crate::verify::check_within(signed, &context, 1).unwrap(); + assert_eq!((one.signature.verdict, one.signature.why), (Verdict::Unchecked, Some(Why::TooMuch)), "one verification: no canonical try"); + let two = crate::verify::check_within(signed, &context, 2).unwrap(); + assert_eq!(two.signature.verdict, Verdict::Changed); +} + +/// A signer's name and issuer are shown without format characters: no bidirectional override +/// reorders them and no zero-width space hides in them (#30 review 6). +#[test] +fn a_certificates_names_lose_their_format_characters() { + let root = root("Example Root"); + let mail = authority("Mail\u{202e} CA\u{200b}", &root, |_| {}); + let ada = signer_by("Ada\u{202e}gpj.exe\u{200b}", "ada@example.org", &mail); + let cms = sign(CONTENT, &ada, &[&ada], false); + let anchors = Anchors::default(); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + let c = check(Signed::Detached { content: CONTENT, signature: &cms }, &context).unwrap(); + let signer = c.signature.signer.unwrap(); + assert_eq!(signer.name, "Adagpj.exe"); + assert!(signer.issuer.contains("Mail CA") && !signer.issuer.contains(['\u{202e}', '\u{200b}']), "{:?}", signer.issuer); +} + +#[test] +fn a_message_with_too_much_to_check_is_said_so() { + let root = root("Example Root"); + // Thirty authorities of the right name with the wrong keys come before the one that signed: + // the first signer's path takes all the budget, and the second signer is left with none. + let mut known: Vec = (0..30).map(|_| authority("Mail CA", &root, |_| {})).collect(); + let mail = authority("Mail CA", &root, |_| {}); + let ada = signer_by("Ada", "ada@example.org", &mail); + // A signer this computer trusts itself: no link to check, only its signature. + let trusted = issued(signer_params("Ada", "ada@example.org"), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + known.push(mail); + let first = sign(CONTENT, &ada, &[&ada], false); + let second = sign(CONTENT, &trusted, &[], false); + let cms = with_signers(&first, &[&first_signer(&first), &first_signer(&second)]); + let known: Vec<&[u8]> = known.iter().map(|m| m.der.as_slice()).chain([trusted.der.as_slice()]).collect(); + let anchors = Anchors::new([&root.der, &trusted.der]); + let c = check( + Signed::Detached { content: CONTENT, signature: &cms }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &known, coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Unchecked, Some(Why::TooMuch))); + // With the budget to spare, the trusted signer alone is verified. + let alone = with_signers(&first, &[&first_signer(&second)]); + let c = check( + Signed::Detached { content: CONTENT, signature: &alone }, + &Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &known, coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!((c.signature.verdict, c.signature.why), (Verdict::Verified, None)); +} + +#[test] +fn an_authoritys_certificate_never_signs_mail_and_the_matching_address_is_said() { + let root = root("Example Root"); + let mut ca_signer = signer_params("Ada", "ada@example.org"); + ca_signer.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + let ca_signer = issued(ca_signer, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&ca_signer, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::NotForEmail))); + let mut two = signer_params("Ada", "other@example.org"); + two.subject_alt_names.push(rcgen::SanType::Rfc822Name("ada@example.org".try_into().unwrap())); + let two = issued(two, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign(CONTENT, &two, &[&two], false); + let anchors = Anchors::new([&root.der]); + let c = check( + Signed::Detached { content: CONTENT, signature: &cms }, + &Context { anchors: &anchors, from: "ADA@example.org", now: NOW, known: &[], coverage: Coverage::Whole }, + ) + .unwrap(); + assert_eq!(c.signature.verdict, Verdict::Verified); + assert_eq!(c.signature.signer.unwrap().addresses.first().map(String::as_str), Some("ada@example.org")); +} + +#[test] +fn an_address_is_compared_as_it_is_written() { + let root = root("Example Root"); + let mut spaced = signer_params("Ada", "ada@example.org"); + spaced.subject_alt_names = vec![rcgen::SanType::Rfc822Name("ada@example.org ".try_into().unwrap())]; + let spaced = issued(spaced, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert_eq!(path_verdict(&spaced, &[], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::AddressMismatch))); + let ada = crate::cert::Cert::from_der(&signer_by("Ada", "ada@example.org", &root).der).unwrap(); + assert!(ada.is_for("ADA@EXAMPLE.ORG")); + assert!(!ada.is_for("ada@example.org\n")); + assert!(!ada.is_for("")); +} + +// ---- #30 review: SignedData read strictly ---- + +/// A DER element of `tag` holding `content`. +fn tlv(tag: u8, content: &[u8]) -> Vec { + let mut out = vec![tag]; + let n = content.len(); + if n < 0x80 { + out.push(n as u8); + } else if n < 0x100 { + out.extend([0x81, n as u8]); + } else { + out.extend([0x82, (n >> 8) as u8, n as u8]); + } + out.extend_from_slice(content); + out +} + +/// `cms` with `extra` put into its SignedData just before the signers. +fn smuggled(cms: &[u8], extra: &[u8]) -> Vec { + let (info, _) = craft_ber::read(cms).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let parts = craft_ber::children(sd.value).unwrap(); + let mut inner = Vec::new(); + for (i, p) in parts.iter().enumerate() { + if i == parts.len() - 1 { + inner.extend_from_slice(extra); + } + inner.extend_from_slice(p.whole); + } + let sd = tlv(0x30, &inner); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &sd)); + tlv(0x30, &ci) +} + +#[test] +fn signed_data_with_anything_else_in_it_cant_be_checked() { + let root = root("Example Root"); + let ada = signer_by("Ada", "ada@example.org", &root); + let cms = sign(CONTENT, &ada, &[&ada], false); + let anchors = Anchors::new([&root.der]); + assert_eq!(verdict(&cms, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + // A field smuggled in, an OCTET STRING with other content, is refused, not passed over. + let forged = smuggled(&cms, &tlv(0x04, b"

Wire 10000 EUR to Mallory

")); + assert_eq!(verdict(&forged, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // And after the signers, where nothing may follow. + let signers = first_signer(&cms); + let mut after = with_signers(&cms, &[&signers]); + assert_eq!(verdict(&after, CONTENT, &anchors, "ada@example.org"), (Verdict::Verified, None)); + after = { + let (info, _) = craft_ber::read(&after).unwrap(); + let fields = craft_ber::children(info.value).unwrap(); + let (sd, _) = craft_ber::read(fields[1].value).unwrap(); + let mut inner = sd.value.to_vec(); + inner.extend(tlv(0x04, b"after")); + let mut ci = fields[0].whole.to_vec(); + ci.extend(tlv(0xa0, &tlv(0x30, &inner))); + tlv(0x30, &ci) + }; + assert_eq!(verdict(&after, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // A version that isn't one, and a detached signature that carries content too. + let versioned = sign_data_with(CONTENT, &ada, &[&ada], false, |_| {}, |d| d.version = CmsVersion::V2); + assert_eq!(verdict(&versioned, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + let carrying = sign_data_with( + CONTENT, + &ada, + &[&ada], + false, + |_| {}, + |d| d.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(b"other".to_vec()).unwrap()).unwrap()), + ); + assert_eq!(verdict(&carrying, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); + // What mail signs is id-data. + let other_type = sign_data_with( + CONTENT, + &ada, + &[&ada], + false, + |_| {}, + |d| d.encap_content_info.econtent_type = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.16.1.4"), + ); + assert_eq!(verdict(&other_type, CONTENT, &anchors, "ada@example.org"), (Verdict::Unchecked, Some(Why::Unreadable))); +} + +#[test] +fn an_opaque_signatures_content_is_given_for_showing() { + let cms = base64(body(OPAQUE)); + let content = craft_ber::signed_content(&cms).unwrap(); + assert!(String::from_utf8_lossy(&content).contains("Hello Bob"), "the signed MIME entity"); + let ber = base64(body(OPAQUE_BER)); + assert_eq!(craft_ber::signed_content(&ber), Some(content)); + let (_, detached) = halves(DETACHED); + assert_eq!(craft_ber::signed_content(&detached), None); +} + +#[test] +fn the_ber_reader_keeps_der_as_it_is_and_joins_pieces() { + assert_eq!(craft_ber::to_der(CA).as_deref(), Some(CA)); + // SEQUENCE (indefinite) { OCTET STRING in pieces "ab" "c" }. + let ber = [0x30, 0x80, 0x24, 0x80, 0x04, 0x02, b'a', b'b', 0x04, 0x01, b'c', 0x00, 0x00, 0x00, 0x00]; + assert_eq!(craft_ber::to_der(&ber), Some(vec![0x30, 0x05, 0x04, 0x03, b'a', b'b', b'c'])); + // A definite length inside, written longer than it need be (a certificate's, say, which its + // signature covers), is kept as it was written. + let ber = [0x30, 0x80, 0x30, 0x81, 0x03, 0x02, 0x01, 0x05, 0x00, 0x00]; + assert_eq!(craft_ber::to_der(&ber), Some(vec![0x30, 0x06, 0x30, 0x81, 0x03, 0x02, 0x01, 0x05])); + // Nesting past the bound is refused, not followed. + let deep: Vec = std::iter::repeat_n([0x30u8, 0x80], 200).flatten().chain(std::iter::repeat_n(0u8, 400)).collect(); + assert_eq!(craft_ber::to_der(&deep), None); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn any_bytes_never_panic(bytes in proptest::collection::vec(any::(), 0..4096)) { + let anchors = Anchors::new([CA]); + let context = Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[&bytes], coverage: Coverage::Whole }; + let _ = check(Signed::Opaque(&bytes), &context); + let _ = check(Signed::Detached { content: b"x", signature: &bytes }, &context); + let _ = craft_ber::to_der(&bytes); + let _ = Anchors::new([&bytes]); + } + + #[test] + fn a_damaged_cms_never_panics(flip in 0usize..3000, byte in any::(), cut in 0usize..3000) { + let mut cms = base64(body(OPAQUE_BER)); + if let Some(b) = cms.get_mut(flip) { + *b = byte; + } + cms.truncate(cut); + let anchors = Anchors::new([CA]); + let context = Context { anchors: &anchors, from: "alice@smime.example", now: NOW, known: &[], coverage: Coverage::Whole }; + let _ = check(Signed::Opaque(&cms), &context); + let (content, signature) = halves(DETACHED); + let mut signature = signature; + if let Some(b) = signature.get_mut(flip) { + *b = byte; + } + let _ = check(Signed::Detached { content: &content, signature: &signature }, &context); + } +} + +#[test] +fn certificate_rejects_mismatched_outer_signature_algorithm() { + assert!(crate::cert::Cert::from_der(CA).is_some()); + let (outer, _) = craft_ber::read(CA).unwrap(); + let fields = craft_ber::children(outer.value).unwrap(); + let (algorithm, _) = craft_ber::read(fields[1].value).unwrap(); + assert_eq!(algorithm.tag, 0x06); + let offset = CA.len() - outer.value.len() + fields[0].whole.len() + fields[1].whole.len() - fields[1].value.len() + algorithm.whole.len() - 1; + let mut changed = CA.to_vec(); + changed[offset] ^= 1; + // The mutation remains a syntactically valid certificate: rejection must come from + // algorithm agreement, not a DER decoding error. Without that guard Cert accepts it. + let decoded = Certificate::from_der(&changed).unwrap(); + assert_ne!(decoded.signature_algorithm(), decoded.tbs_certificate().signature()); + assert!(crate::cert::Cert::from_der(&changed).is_none()); +} + +#[test] +fn shared_result_preserves_partial_coverage_and_name_bounds() { + use crate::digital_signature::{DigitalSignature, MAX_SIGNER_TEXT, SignatureFormat, signer_text}; + let signature = DigitalSignature::bare(SignatureFormat::Smime, Verdict::Verified, Why::PartlySigned).covering(Coverage::Part); + assert_eq!(signature.verdict, Verdict::NotVerified); + assert_eq!(signature.why, Some(Why::PartlySigned)); + assert_eq!(signer_text("Alice\u{202e}\u{200b}\nBob"), "Alice Bob"); + assert_eq!(signer_text(&"A".repeat(1000)).chars().count(), MAX_SIGNER_TEXT); +} + +#[test] +fn name_constraints_cover_addresses_beyond_the_display_limit() { + let root = root("Example Root"); + let corp = authority("Corp CA", &root, |p| { + p.name_constraints = Some(rcgen::NameConstraints { + permitted_subtrees: vec![rcgen::GeneralSubtree::Rfc822Name("corp.example".into())], + excluded_subtrees: vec![], + }); + }); + let mut params = signer_params("Many names", "ada@corp.example"); + for n in 1..crate::digital_signature::MAX_SIGNER_ADDRESSES { + params.subject_alt_names.push(rcgen::SanType::Rfc822Name(format!("alias{n}@corp.example").try_into().unwrap())); + } + params.subject_alt_names.push(rcgen::SanType::Rfc822Name("ceo@bank.example".try_into().unwrap())); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &corp); + assert_eq!(path_verdict(&signer, &[&corp], &root, "ada@corp.example"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn pss_restricted_public_keys_are_not_treated_as_unrestricted_rsa() { + use crate::algorithms::{Fault, Hash}; + let certificate = crate::cert::Cert::from_der(ALICE).unwrap(); + for message in [NO_ATTRIBUTES, PSS] { + let (content, cms) = halves(message); + let info = SignerInfo::from_der(&first_signer(&cms)).unwrap(); + let signed = info.signed_attrs.as_ref().map(|a| a.to_der().unwrap()).unwrap_or(content); + let hash = Hash::of(&info.digest_alg).unwrap(); + let mut key = certificate.public_key().clone(); + assert_eq!(crate::algorithms::verify(&key, &info.signature_algorithm, Some(hash), &signed, info.signature.as_bytes()), Ok(())); + key.algorithm.oid = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10"); + // An empty PSS parameter sequence restricts the key to SHA-1 defaults, not + // the SHA-256 signature above. PKCS#1 v1.5 is never allowed for a PSS key. + key.algorithm.parameters = Some(Any::from_der(&[0x30, 0]).unwrap()); + assert_eq!(crate::algorithms::verify(&key, &info.signature_algorithm, Some(hash), &signed, info.signature.as_bytes()), Err(Fault::Unknown)); + } +} + +#[test] +fn malformed_critical_san_is_not_an_absent_identity() { + let root = root("Example Root"); + let mut params = signer_params("Ada", "ada@example.org"); + params.subject_alt_names.clear(); + params + .distinguished_name + .push(rcgen::DnType::CustomDnType(vec![1, 2, 840, 113549, 1, 9, 1]), rcgen::DnValue::Ia5String("ada@example.org".try_into().unwrap())); + let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], vec![0x05, 0]); + san.set_criticality(true); + params.custom_extensions.push(san); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + assert!(Certificate::from_der(&signer.der).is_ok(), "outer certificate is valid DER"); + assert!(crate::cert::Cert::from_der(&signer.der).is_none()); + assert_ne!(path_verdict(&signer, &[], &root, "ada@example.org").0, Verdict::Verified); +} + +#[test] +fn excluded_directory_san_is_checked_even_with_empty_subject() { + let root = root("Example Root"); + let mut rogue = rcgen::DistinguishedName::new(); + rogue.push(rcgen::DnType::OrganizationName, "Rogue"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(rogue)] }); + }); + let directory: x509_cert::name::Name = "O=Rogue".parse().unwrap(); + for empty_subject in [false, true] { + let mut params = signer_params("Ada", "ada@example.org"); + if empty_subject { + params.distinguished_name = rcgen::DistinguishedName::new(); + } + params.subject_alt_names.clear(); + let mut names = tlv(0x81, b"ada@example.org"); + names.extend(tlv(0xa4, &directory.to_der().unwrap())); + let mut san = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], tlv(0x30, &names)); + san.set_criticality(true); + params.custom_extensions.push(san); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + } +} + +#[test] +fn unsupported_unicode_directory_normalization_fails_closed() { + let root = root("Example Root"); + let mut excluded = rcgen::DistinguishedName::new(); + excluded.push(rcgen::DnType::OrganizationName, "STRASSE"); + let ca = authority("Corp CA", &root, |p| { + p.name_constraints = + Some(rcgen::NameConstraints { permitted_subtrees: vec![], excluded_subtrees: vec![rcgen::GeneralSubtree::DirectoryName(excluded)] }); + }); + let mut params = signer_params("Ada", "ada@example.org"); + params.distinguished_name = rcgen::DistinguishedName::new(); + params.distinguished_name.push(rcgen::DnType::OrganizationName, "Straße"); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); +} + +#[test] +fn opaque_binary_content_is_verified_as_exact_octets_with_or_without_attributes() { + const BINARY: &[u8] = b"Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\nA\r\nB"; + const CHANGED: &[u8] = b"Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\nA\nB"; + let root = root("Example Root"); + let signer = signer_by("Ada", "ada@example.org", &root); + let anchors = Anchors::new([&root.der]); + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known: &[], coverage: Coverage::Whole }; + for bare in [false, true] { + let cms = sign_data_with( + BINARY, + &signer, + &[&signer], + false, + |info| { + if bare { + let rng = ring::rand::SystemRandom::new(); + let pair = ring::signature::EcdsaKeyPair::from_pkcs8( + &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, + &signer.key.serialize_der(), + &rng, + ) + .unwrap(); + info.signed_attrs = None; + info.signature = OctetString::new(pair.sign(&rng, BINARY).unwrap().as_ref().to_vec()).unwrap(); + } + }, + |data| data.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(BINARY.to_vec()).unwrap()).unwrap()), + ); + assert_eq!(check(Signed::Opaque(&cms), &context).unwrap().signature.verdict, Verdict::Verified); + let info = ContentInfo::from_der(&cms).unwrap(); + let mut data = info.content.decode_as::().unwrap(); + data.encap_content_info.econtent = Some(Any::encode_from(&OctetString::new(CHANGED.to_vec()).unwrap()).unwrap()); + let changed = ContentInfo { content_type: info.content_type, content: Any::encode_from(&data).unwrap() }.to_der().unwrap(); + assert_eq!(craft_ber::signed_content(&changed).unwrap(), CHANGED); + assert_eq!(check(Signed::Opaque(&changed), &context).unwrap().signature.verdict, Verdict::Changed); + } +} + +#[test] +fn unsupported_name_constraints_fail_closed_for_dns_ip_and_uri() { + // Critical excludedSubtrees for each unsupported form, alongside valid email identity. + for (tag, excluded, presented) in [ + (0x82, b"blocked.example".as_slice(), b"blocked.example".as_slice()), + (0x87, &[192, 0, 2, 0, 255, 255, 255, 0][..], &[192, 0, 2, 1][..]), + (0x86, b"blocked.example".as_slice(), b"https://blocked.example/path".as_slice()), + ] { + let root = root("Root"); + let ca = authority("Constrained CA", &root, |params| { + let subtree = tlv(0x30, &tlv(tag, excluded)); + let mut extension = rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 30], tlv(0x30, &tlv(0xa1, &subtree))); + extension.set_criticality(true); + params.custom_extensions.push(extension); + }); + let mut params = signer_params("Ada", "ada@example.org"); + params.subject_alt_names.clear(); + let mut names = tlv(0x81, b"ada@example.org"); + names.extend(tlv(tag, presented)); + params.custom_extensions.push(rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 17], tlv(0x30, &names))); + let signer = issued(params, key(&rcgen::PKCS_ECDSA_P256_SHA256), &ca); + assert_eq!(path_verdict(&signer, &[&ca], &root, "ada@example.org"), (Verdict::NotVerified, Some(Why::Constrained))); + } +} + +#[test] +fn later_matching_certificates_are_checked_for_trust_usage_and_address() { + let root = root("Renewal Root"); + let id = b"same-key-after-renewal"; + let with_id = |mut params: rcgen::CertificateParams| { + params.custom_extensions.push(rcgen::CustomExtension::from_oid_content(&[2, 5, 29, 14], tlv(0x04, id))); + params + }; + let current = issued(with_id(signer_params("Ada", "ada@example.org")), key(&rcgen::PKCS_ECDSA_P256_SHA256), &root); + let cms = sign_with(CONTENT, ¤t, &[], false, |info| { + info.version = CmsVersion::V3; + info.sid = SignerIdentifier::SubjectKeyIdentifier(x509_cert::ext::pkix::SubjectKeyIdentifier(OctetString::new(id.to_vec()).unwrap())); + }); + let anchors = Anchors::new([&root.der]); + for kind in 0..3 { + let mut params = signer_params("Ada", "ada@example.org"); + match kind { + 0 => params.not_after = rcgen::date_time_ymd(2021, 1, 1), + 1 => params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ServerAuth], + _ => params.subject_alt_names = vec![rcgen::SanType::Rfc822Name("other@example.org".try_into().unwrap())], + } + let issuer = rcgen::Issuer::new(root.params.clone(), &root.key); + let first = with_id(params).signed_by(¤t.key, &issuer).unwrap(); + let known: &[&[u8]] = &[first.der().as_ref(), ¤t.der]; + let context = Context { anchors: &anchors, from: "ada@example.org", now: NOW, known, coverage: Coverage::Whole }; + let checked = check(Signed::Detached { content: CONTENT, signature: &cms }, &context).unwrap(); + assert_eq!((checked.signature.verdict, checked.signature.why), (Verdict::Verified, None)); + assert_eq!(checked.certificate.as_deref(), Some(current.der.as_slice())); + // A later trusted certificate never excuses changed signed content. + let changed = check(Signed::Detached { content: b"changed", signature: &cms }, &context).unwrap(); + assert_eq!(changed.signature.verdict, Verdict::Changed); + } +} diff --git a/crates/smime/src/verify.rs b/crates/smime/src/verify.rs new file mode 100644 index 0000000000..c2f9af0846 --- /dev/null +++ b/crates/smime/src/verify.rs @@ -0,0 +1,478 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! Checking CMS SignedData (RFC 5652 §5) as S/MIME carries it (RFC 8551 §3.5): the signer's +//! digest of what was signed, their signature over it, and whether their certificate is trusted +//! and for the message's sender. + +use crate::Timestamp; +use crate::digital_signature::{Coverage, DigitalSignature, SignatureFormat, Signer, Verdict, Why}; +use cms::signed_data::{EncapsulatedContentInfo, SignerIdentifier, SignerInfo}; +use const_oid::ObjectIdentifier; +use der::asn1::OctetString; +use der::{Decode, Encode}; + +use crate::algorithms::{self, Fault, Hash}; +use crate::cert::Cert; +use crate::chain::{self, Anchors}; +use craft_ber::{self as ber, Tlv}; + +/// The most certificates read from one message. +pub const MAX_CERTS: usize = 32; +/// The most signers of one message that are checked. +pub const MAX_SIGNERS: usize = 8; +/// The most signatures checked for one message, its signers' and their certificates' together +/// (#30): an RSA key of 8192 bits takes a while, and a message may carry many. +pub const MAX_VERIFICATIONS: usize = 32; +/// The most certificates tried for one signer: those that its identifier names (the message +/// may carry several of one name; only the one whose key made the signature is the signer's). +pub const MAX_CANDIDATES: usize = 4; + +const SIGNED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2"); +const DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.1"); +const CONTENT_TYPE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.3"); +const MESSAGE_DIGEST: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.4"); +const SIGNING_TIME: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.5"); + +/// What a check is made against. +#[derive(Clone, Copy, Debug)] +pub struct Context<'a> { + /// The certificates the host trusts. + pub anchors: &'a Anchors, + /// The message's From address. + pub from: &'a str, + /// The time of the check, seconds since 1970. + pub now: Timestamp, + /// Certificates kept for the sender already, in DER: a message that doesn't carry its + /// signer's certificate may be checked with one of them. + pub known: &'a [&'a [u8]], + /// How much of the message the signed part is: the whole of it only when it is the + /// message's top level. A part is never verified for the message. + pub coverage: Coverage, +} + +/// A Digitally signed message's two halves. +#[derive(Clone, Copy, Debug)] +pub enum Signed<'a> { + /// `multipart/signed`: the signed part as it came (its MIME header and body) and the + /// signature part's bytes (the CMS SignedData, decoded from base64). + Detached { content: &'a [u8], signature: &'a [u8] }, + /// `application/pkcs7-mime; smime-type=signed-data`: the CMS SignedData holding what was + /// signed (decoded from base64). + Opaque(&'a [u8]), +} + +/// What a check found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Checked { + pub signature: DigitalSignature, + /// The signer's certificate, in DER, when the signature over the message is the signer's + /// and the certificate is for the From address: worth keeping for that address (#30 R9). + pub certificate: Option>, +} + +/// Check `signed` against `context`. `None` when the CMS isn't SignedData at all (an Encrypted +/// message's enveloped data, say): not a Digital signature. Never fails otherwise: what can't be +/// read is [`Verdict::Unchecked`]. +pub fn check(signed: Signed<'_>, context: &Context<'_>) -> Option { + check_within(signed, context, MAX_VERIFICATIONS) +} + +/// [`check`] with at most `verifications` signatures checked (for the tests, which spend a +/// smaller budget). +pub(crate) fn check_within(signed: Signed<'_>, context: &Context<'_>, verifications: usize) -> Option { + let blob = match signed { + Signed::Detached { signature, .. } => signature, + Signed::Opaque(blob) => blob, + }; + let unreadable = || Some(unchecked(Why::Unreadable)); + let Some(der) = ber::to_der(blob) else { return unreadable() }; + let Some(parts) = content_info(&der) else { return unreadable() }; + if parts.content_type != SIGNED_DATA { + return None; + } + let Some(data) = signed_data(parts.content) else { return unreadable() }; + let Ok(eci) = EncapsulatedContentInfo::from_der(data.encap.whole) else { return unreadable() }; + // What mail signs is MIME, id-data (RFC 8551 §3.5); a detached signature carries none of it + // and an opaque one all of it. + if eci.econtent_type != DATA { + return unreadable(); + } + let content: &[u8] = match (signed, econtent(&data.encap)) { + (Signed::Detached { content, .. }, None) if eci.econtent.is_none() => content, + (Signed::Opaque(_), Some(c)) => c, + _ => return unreadable(), + }; + let mut pool: Vec = data.certificates.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c.whole)).collect(); + pool.extend(context.known.iter().take(MAX_CERTS).filter_map(|c| Cert::from_der(c))); + let mut digests = Digests::new(content, matches!(signed, Signed::Detached { .. })); + let mut budget = verifications; + let mut best: Option = None; + for signer in data.signers.iter().take(MAX_SIGNERS) { + let found = one_signer(signer, &eci, &mut digests, &pool, context, &mut budget); + best = Some(match best { + Some(b) if b.signature.verdict <= found.signature.verdict => b, + _ => found, + }); + } + best.or_else(unreadable).map(|mut c| { + c.signature = c.signature.covering(context.coverage); + c + }) +} + +/// What was signed and its digests, each worked out once (#30: a long message isn't hashed +/// again for every signer and key tried), as it came and in its canonical form. +struct Digests<'a> { + content: &'a [u8], + allow_transport_normalization: bool, + /// The content with lone LFs made CRLF, when it has any: worked out at its first use. + canonical: Option>>, + plain: Vec<(Hash, Vec)>, + crlf: Vec<(Hash, Vec)>, +} + +impl<'a> Digests<'a> { + fn new(content: &'a [u8], allow_transport_normalization: bool) -> Self { + Digests { content, allow_transport_normalization, canonical: None, plain: Vec::new(), crlf: Vec::new() } + } + + fn of(&mut self, hash: Hash) -> Vec { + if let Some((_, d)) = self.plain.iter().find(|(h, _)| *h == hash) { + return d.clone(); + } + let d = hash.digest(self.content); + self.plain.push((hash, d.clone())); + d + } + + /// The digest of the canonical form; `None` when the content has no lone LF (it is its own). + fn of_canonical(&mut self, hash: Hash) -> Option> { + // Encapsulated content is already the exact signed octet sequence. Rewriting + // binary payload newlines would authenticate different bytes than we expose. + if !self.allow_transport_normalization { + return None; + } + if let Some((_, d)) = self.crlf.iter().find(|(h, _)| *h == hash) { + return Some(d.clone()); + } + let content = self.content; + let canonical = self.canonical.get_or_insert_with(|| canonical(content)).as_ref()?; + let d = hash.digest(canonical); + self.crlf.push((hash, d.clone())); + Some(d) + } + + /// Whether `said` is the digest of the content as it came or in its canonical form. + fn matches(&mut self, hash: Hash, said: &[u8]) -> bool { + self.of(hash) == said || self.of_canonical(hash).is_some_and(|d| d == said) + } +} + +fn unchecked(why: Why) -> Checked { + Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Unchecked, why), certificate: None } +} + +struct ContentInfoParts<'a> { + content_type: ObjectIdentifier, + content: &'a [u8], +} + +/// ContentInfo: its type, and the value inside its `[0] EXPLICIT`. +fn content_info(der: &[u8]) -> Option> { + let (outer, rest) = ber::read(der)?; + if outer.tag != 0x30 || !rest.is_empty() { + return None; + } + let fields = ber::children(outer.value)?; + let [oid, explicit] = fields.as_slice() else { return None }; + if oid.tag != 0x06 || explicit.tag != 0xa0 { + return None; + } + let content_type = ObjectIdentifier::from_der(oid.whole).ok()?; + Some(ContentInfoParts { content_type, content: explicit.value }) +} + +/// SignedData's parts as they came, so that signatures are checked over the bytes the signer +/// wrote: what is inside, the certificates, and the signers. +struct SignedDataParts<'a> { + encap: Tlv<'a>, + certificates: Vec>, + signers: Vec>, +} + +/// SignedData read strictly (RFC 5652 §5.1): its version one of those defined, its digest +/// algorithms a SET of algorithm identifiers, encapContentInfo, the certificates and the +/// revocation lists when they are there, in that order, and the signers last: nothing else, and +/// nothing after. +fn signed_data(content: &[u8]) -> Option> { + let (outer, rest) = ber::read(content)?; + if outer.tag != 0x30 || !rest.is_empty() { + return None; + } + let fields = ber::children(outer.value)?; + let mut fields = fields.into_iter(); + let version = fields.next().filter(|f| f.tag == 0x02)?; + if !matches!(version.value, [1] | [3] | [4] | [5]) { + return None; + } + let digests = fields.next().filter(|f| f.tag == 0x31)?; + for d in ber::children(digests.value)? { + spki::AlgorithmIdentifierOwned::from_der(d.whole).ok()?; + } + let encap = fields.next().filter(|f| f.tag == 0x30)?; + let mut next = fields.next()?; + let mut certificates = Vec::new(); + if next.tag == 0xa0 { + // (Other kinds of certificate, [0]..[3] IMPLICIT, are left out; they are never a path.) + certificates = ber::children(next.value)?.into_iter().filter(|c| c.tag == 0x30).collect(); + next = fields.next()?; + } + if next.tag == 0xa1 { + next = fields.next()?; + } + if next.tag != 0x31 || fields.next().is_some() { + return None; + } + Some(SignedDataParts { encap, certificates, signers: ber::children(next.value)? }) +} + +/// The OCTET STRING inside encapContentInfo's `[0] EXPLICIT eContent`, when there is one (and +/// nothing else is there). +fn econtent<'a>(encap: &Tlv<'a>) -> Option<&'a [u8]> { + let fields = ber::children(encap.value)?; + let explicit = fields.get(1).filter(|f| f.tag == 0xa0)?; + let (octets, rest) = ber::read(explicit.value)?; + (octets.tag == 0x04 && rest.is_empty()).then_some(octets.value) +} + +/// The value of the signed attribute `oid`, in DER (its one value), when there is one. +fn attribute(info: &SignerInfo, oid: ObjectIdentifier) -> Option> { + let attrs = info.signed_attrs.as_ref()?; + let attr = attrs.iter().find(|a| a.oid == oid)?; + if attr.values.len() != 1 { + return None; + } + attr.values.iter().next()?.to_der().ok() +} + +/// The bytes a signer with signed attributes signed (RFC 5652 §5.4): the attributes as they came, +/// with their `[0] IMPLICIT` tag made the SET OF's. +fn signed_attributes(raw: &Tlv<'_>) -> Option> { + let fields = ber::children(raw.value)?; + let attrs = fields.iter().find(|f| f.tag == 0xa0)?; + let mut out = attrs.whole.to_vec(); + *out.first_mut()? = 0x31; + Some(out) +} + +/// `content` with every lone LF made CRLF (RFC 8551 §3.1.1's canonical form), when it has one. +fn canonical(content: &[u8]) -> Option> { + let mut lone = false; + let mut out = Vec::with_capacity(content.len().saturating_add(content.len() / 32)); + let mut previous = 0u8; + for &b in content { + if b == b'\n' && previous != b'\r' { + out.push(b'\r'); + lone = true; + } + out.push(b); + previous = b; + } + lone.then_some(out) +} + +fn one_signer( + raw: &Tlv<'_>, + eci: &EncapsulatedContentInfo, + digests: &mut Digests<'_>, + pool: &[Cert], + context: &Context<'_>, + budget: &mut usize, +) -> Checked { + let Ok(info) = SignerInfo::from_der(raw.whole) else { return unchecked(Why::Unreadable) }; + let hash = match Hash::of(&info.digest_alg) { + Ok(hash) => hash, + Err(fault) => return unchecked(why_not(fault)), + }; + let candidates = signer_certs(&info.sid, pool); + if candidates.is_empty() { + return unchecked(Why::NoPublicKey); + } + let signature = info.signature.as_bytes(); + // What the signer's key signed: the signed attributes (which hold the content's digest), or + // without them the content itself, as it came or in its canonical form. + let attributes = match &info.signed_attrs { + Some(_) => match signed_attributes(raw) { + Some(bytes) => Some(bytes), + None => return unchecked(Why::Unreadable), + }, + None => None, + }; + // The signer is the certificate whose key made the signature, of those its identifier names: + // another one of the same name (any can be put in a message) makes no difference. + let mut fault: Option = None; + let mut signer: Option<(&Cert, Result<(), Why>)> = None; + let mut ran_out = false; + for cert in candidates { + let Some(left) = budget.checked_sub(1) else { + ran_out = true; + break; + }; + *budget = left; + let verified = match &attributes { + Some(bytes) => algorithms::verify(cert.public_key(), &info.signature_algorithm, Some(hash), bytes, signature), + None => { + let plain = algorithms::verify_hashed(cert.public_key(), &info.signature_algorithm, Some(hash), &mut |h| digests.of(h), signature); + // (Signed in its canonical form, perhaps: another verification, from the budget.) + if plain == Err(Fault::Invalid) && digests.of_canonical(hash).is_some() { + let Some(left) = budget.checked_sub(1) else { + ran_out = true; + break; + }; + *budget = left; + algorithms::verify_hashed( + cert.public_key(), + &info.signature_algorithm, + Some(hash), + &mut |h| digests.of_canonical(h).unwrap_or_default(), + signature, + ) + } else { + plain + } + } + }; + match verified { + Ok(()) => { + // Matching keys can occur in expired or renewed certificates. A valid + // signature alone does not select the certificate we can trust for mail. + let for_email = cert.for_email() && !cert.is_authority(); + let trust = chain::trust(cert, pool, context.anchors, context.now, budget) + .and_then(|()| for_email.then_some(()).ok_or(Why::NotForEmail)) + .and_then(|()| if cert.is_for(context.from) { Ok(()) } else { Err(Why::AddressMismatch) }); + if trust.is_ok() { + signer = Some((cert, trust)); + break; + } + if signer.is_none() { + signer = Some((cert, trust)); + } + if trust == Err(Why::TooMuch) { + ran_out = true; + break; + } + } + // (Of several faults, what says most: an algorithm, then a malformed key, then no + // match.) + Err(f) => fault = Some(fault.map_or(f, |g| worse(g, f))), + } + } + let Some((cert, mut trust)) = signer else { + return match fault { + // (A certificate not tried may have made it: no answer.) + _ if ran_out => unchecked(Why::TooMuch), + // No key it names made it: changed after signing, or never signed by any of them; + // nobody is named, since none of them fits. + Some(Fault::Invalid) | None => { + Checked { signature: DigitalSignature::bare(SignatureFormat::Smime, Verdict::Changed, Why::Altered), certificate: None } + } + Some(f) => unchecked(why_not(f)), + }; + }; + let result = |verdict: Verdict, why: Option| Checked { + signature: DigitalSignature { + format: SignatureFormat::Smime, + verdict, + why, + signer: Some(signer_of(cert)), + signed_at: signing_time(&info), + revocation_checked: false, + // (`check` says, from where in the message the signed part sat.) + coverage: Coverage::Part, + }, + certificate: None, + }; + if attributes.is_some() { + // The attributes are the signer's own words now: what they say of the content holds. + let Some(said_type) = attribute(&info, CONTENT_TYPE).and_then(|d| ObjectIdentifier::from_der(&d).ok()) else { + return unchecked(Why::Unreadable); + }; + let Some(said_digest) = attribute(&info, MESSAGE_DIGEST).and_then(|d| OctetString::from_der(&d).ok()) else { + return unchecked(Why::Unreadable); + }; + if said_type != eci.econtent_type || !digests.matches(hash, said_digest.as_bytes()) { + return result(Verdict::Changed, Some(Why::Altered)); + } + } + // A candidate left untried may be acceptable. Do not report the first + // refusal as definitive when the shared verification budget was exhausted. + if ran_out { + trust = Err(Why::TooMuch); + } + let mut r = match trust { + Ok(()) => result(Verdict::Verified, None), + Err(Why::TooMuch) => result(Verdict::Unchecked, Some(Why::TooMuch)), + // (An algorithm that's no longer safe on the way to a trust anchor: the certificate can't + // be relied on, but the message is as it was signed.) + Err(why) => result(Verdict::NotVerified, Some(why)), + }; + // Kept for the sender only when it is trusted, valid now and theirs: it is what mail to them + // will be encrypted with. + if trust.is_ok() { + r.certificate = Some(cert.der().to_vec()); + } + // The signer's address that is the sender's comes first: it is the one said. + if let (Some(address), Some(signer)) = (cert.address_for(context.from), r.signature.signer.as_mut()) { + let shown = crate::digital_signature::signer_text(&address); + signer.addresses.retain(|a| !a.eq_ignore_ascii_case(&shown)); + signer.addresses.insert(0, shown); + } + r +} + +/// Of two faults, the one that says most of why a signature can't be relied on. +fn worse(a: Fault, b: Fault) -> Fault { + let rank = |f: Fault| match f { + Fault::Weak => 0, + Fault::Unknown => 1, + Fault::Malformed => 2, + Fault::Invalid => 3, + }; + if rank(b) < rank(a) { b } else { a } +} + +fn why_not(fault: Fault) -> Why { + match fault { + Fault::Weak => Why::WeakAlgorithm, + Fault::Unknown => Why::UnknownAlgorithm, + Fault::Invalid => Why::Altered, + Fault::Malformed => Why::Unreadable, + } +} + +/// The certificates in `pool` that `sid` names, at most [`MAX_CANDIDATES`]. +fn signer_certs<'a>(sid: &SignerIdentifier, pool: &'a [Cert]) -> Vec<&'a Cert> { + match sid { + SignerIdentifier::IssuerAndSerialNumber(isn) => { + let Ok(issuer) = isn.issuer.to_der() else { return Vec::new() }; + let serial = isn.serial_number.as_bytes(); + pool.iter().filter(|c| c.issuer() == issuer.as_slice() && c.serial() == serial).take(MAX_CANDIDATES).collect() + } + SignerIdentifier::SubjectKeyIdentifier(ski) => { + let id = ski.0.as_bytes(); + pool.iter().filter(|c| c.key_id().as_deref() == Some(id)).take(MAX_CANDIDATES).collect() + } + } +} + +fn signer_of(cert: &Cert) -> Signer { + let (not_before, not_after) = cert.validity(); + Signer { name: cert.name(), addresses: cert.addresses(), fingerprint: cert.fingerprint(), issuer: cert.issuer_name(), not_before, not_after } +} + +/// The signing time the signer gives (RFC 5652 §11.3): their word, unchecked. +fn signing_time(info: &SignerInfo) -> Option { + let der = attribute(info, SIGNING_TIME)?; + let time = x509_cert::time::Time::from_der(&der).ok()?; + Timestamp::try_from(time.to_unix_duration().as_secs()).ok() +} diff --git a/crates/smime/testdata/README.md b/crates/smime/testdata/README.md new file mode 100644 index 0000000000..9200f2cc11 --- /dev/null +++ b/crates/smime/testdata/README.md @@ -0,0 +1,7 @@ +# S/MIME test vectors + +Restored from `UCS-Care-Group/mailcraft` commit +`240d1d42fe394cf3274402b180663ba9b43ca180`, `crates/smime/testdata`. +The source test suite identifies these as RFC 9216 example certificates and +OpenSSL-generated message vectors. These are public examples, not user mail or keys. +Source attribution: MailCraft contributors, MIT OR Apache-2.0. diff --git a/crates/smime/testdata/alice.sign.der b/crates/smime/testdata/alice.sign.der new file mode 100644 index 0000000000..9bff7d1b32 Binary files /dev/null and b/crates/smime/testdata/alice.sign.der differ diff --git a/crates/smime/testdata/ca.rsa.der b/crates/smime/testdata/ca.rsa.der new file mode 100644 index 0000000000..193b9ab9fc Binary files /dev/null and b/crates/smime/testdata/ca.rsa.der differ diff --git a/crates/smime/testdata/detached.eml b/crates/smime/testdata/detached.eml new file mode 100644 index 0000000000..51e8d32041 --- /dev/null +++ b/crates/smime/testdata/detached.eml @@ -0,0 +1,60 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Signed minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----011A3E8D1DC66D3261BBFB3EB4674ACD" + +This is an S/MIME signed message + +------011A3E8D1DC66D3261BBFB3EB4674ACD +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------011A3E8D1DC66D3261BBFB3EB4674ACD +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGiQYJKoZIhvcNAQcCoIIGejCCBnYCAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggJ8MIICeAIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCAaCB5DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB +MBwGCSqGSIb3DQEJBTEPFw0yNjExMDkxMjA5NTBaMC8GCSqGSIb3DQEJBDEiBCCl +3jtcr1bjeDRcGd4HoRLXWhkBqvOm0Ywlw7H6AYF2pzB5BgkqhkiG9w0BCQ8xbDBq +MAsGCWCGSAFlAwQBKjALBglghkgBZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3 +DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggq +hkiG9w0DAgIBKDANBgkqhkiG9w0BAQEFAASCAQCda8b7o1a3/12TBKbRDLoAW5sm +1MBd1j0huWs+wTdj6G3q0cOAPJ2OxZuNfZnUwce+CNAWsKyNyPXIm9k997yW837b +e//lUIXPh8b12hUM6te298xvNqCdNNA0Y3/ihNZvb0fbl4nJfu0X+QMo2VqcFI6w +cSRBcbMB1/pB47AZF1qOR1+WlvxWTfJ1gHRMvpgtmd5NwNx96jM4i8yMxa4zoXmW +ROlOHYcNSDpVkkuhH+m60zxk52vOdTmOdg6CY+rFcMrgY6R2qZu/sfQrWAFiKOYl +CSgqvp/pPEty15Kt8inC+DYrIDNdlLg9A1RPpV+H4XxTSgRiEPTFbPKdOjG/ + +------011A3E8D1DC66D3261BBFB3EB4674ACD-- + diff --git a/crates/smime/testdata/noattr.eml b/crates/smime/testdata/noattr.eml new file mode 100644 index 0000000000..0a5d7dad19 --- /dev/null +++ b/crates/smime/testdata/noattr.eml @@ -0,0 +1,56 @@ +To: bob@smime.example +From: alice@smime.example +Subject: No attributes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----9D215F381F61DA9DBEC8E6CEAF3E2E88" + +This is an S/MIME signed message + +------9D215F381F61DA9DBEC8E6CEAF3E2E88 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------9D215F381F61DA9DBEC8E6CEAF3E2E88 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIFogYJKoZIhvcNAQcCoIIFkzCCBY8CAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggGVMIIBkQIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCATANBgkqhkiG9w0BAQEFAASCAQB424lCX+hFmHkC +NtPDglt4jFneZge6fSFGI898+4Ve5+SehVpM2pmyugnk9NvpiEqI9ywInDENgbPc +lDxTkNSWoFRMAvexvyK91CLZ6E8oRur8unC6ZMMxcnpqbJqgJgW9BR4j8Q2octPv +IFwERtqcsNLuDx9kUh+MR6Z66rELQAesXzOiWMhqDwJKmQxNZqVu4k+BQqLmyHbK +BRS6uDN54Xgs7tHdFKhewEwoMLA+PEOTCpLcFRzWydywlxTJMMivqmEdvPC4R8pA +8XKDYA4k++6y9wjiq4e1Uc/+Ex/n6CgcJZNAo2qS8u0wIGfBL9xW9qEOnAI8wZPp +IoaGX1Qa + +------9D215F381F61DA9DBEC8E6CEAF3E2E88-- + diff --git a/crates/smime/testdata/nocerts.eml b/crates/smime/testdata/nocerts.eml new file mode 100644 index 0000000000..69741fc90e --- /dev/null +++ b/crates/smime/testdata/nocerts.eml @@ -0,0 +1,40 @@ +To: bob@smime.example +From: alice@smime.example +Subject: No certificate +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-256"; boundary="----C714793EB4AEA5E36741725AF174BFC1" + +This is an S/MIME signed message + +------C714793EB4AEA5E36741725AF174BFC1 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------C714793EB4AEA5E36741725AF174BFC1 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIICsgYJKoZIhvcNAQcCoIICozCCAp8CAQExDTALBglghkgBZQMEAgEwCwYJKoZI +hvcNAQcBMYICfDCCAngCAQEwbDBVMQ0wCwYDVQQKEwRJRVRGMREwDwYDVQQLEwhM +QU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBTIFJTQSBDZXJ0aWZpY2F0aW9u +IEF1dGhvcml0eQITN0EFee11f0Kpolw69Phqzpqp1zALBglghkgBZQMEAgGggeQw +GAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMjYxMTA5 +MTIwOTUxWjAvBgkqhkiG9w0BCQQxIgQgpd47XK9W43g0XBneB6ES11oZAarzptGM +JcOx+gGBdqcweQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZIAWUD +BAEWMAsGCWCGSAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYI +KoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcNAQEB +BQAEggEAnQNd8e5Phn1idVWgZqoGUqKXZQF2ojmQ9duGv5gAIzTmOpI6l4WaKj4t +T2EFa8cwQaIVhFz9ZKshEPSDep9y7IukzVi379CuHRonelJ9rwPQhkX7KLJVfnmh +AFc5XH9AdVxHPvpnP59ZankXO6MvzVO9kYKQdflZC8gv5Bl7Sh+FpS/0VGPEXNH+ +tkRGeX2jo5YY5Xsj2gGTBbiZQ07urn+dcETJxeGI+cLa5tkg3YBeLKthGEMekv9t +JakkfMsvpMW5m4TsiOz0A8gBrk5zP5YWEU+h+jKvSlQXyYcGbU04+Ir+y0HSa2ob +KUozlJlOmmhYzeok0wAsFf+V6qipCg== + +------C714793EB4AEA5E36741725AF174BFC1-- + diff --git a/crates/smime/testdata/opaque-ber.eml b/crates/smime/testdata/opaque-ber.eml new file mode 100644 index 0000000000..e6b1717492 --- /dev/null +++ b/crates/smime/testdata/opaque-ber.eml @@ -0,0 +1,47 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Opaque minutes +MIME-Version: 1.0 +Content-Disposition: attachment; filename="smime.p7m" +Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m" +Content-Transfer-Encoding: base64 + +MIAGCSqGSIb3DQEHAqCAMIACAQExDTALBglghkgBZQMEAgEwgAYJKoZIhvcNAQcB +oIAkgAR1Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PXVzLWFzY2lp +DQoNCkhlbGxvIEJvYiwNCg0KVGhlIG1pbnV0ZXMgb2YgVHVlc2RheSBhcmUgYXR0 +YWNoZWQgaW4gc3Bpcml0Lg0KDQpBbGljZQ0KAAAAAAAAoIID0zCCA88wggK3oAMC +AQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJKoZIhvcNAQENBQAwVTENMAsGA1UE +ChMESUVURjERMA8GA1UECxMITEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1Q +UyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwIBcNMTkxMTIwMDY1NDE4WhgP +MjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBT +IFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFjZTCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2KNI05Hwr+E3wP6XTvyi6WWyTgBK9 +LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0FpfgyC7OxsVcF7q4WHWZWleYXFKl +QHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOLPgPEwjTtdg0VQQ6Wz+CRQ/YbHPKa +w7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkLcLNau5LZDQUdsGV+SAo3nBdWCRYV ++I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iDz3X0zEoj0fqXgq4SWcC0nsG1lyyX +t1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bCSzsCAwEAAaOBrzCBrDAMBgNVHRMB +Af8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUDAgEwATAeBgNVHREEFzAVgRNhbGlj +ZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoGCCsGAQUFBwMEMA4GA1UdDwEB/wQE +AwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64papAQ0yBmZnMwHwYDVR0jBBgwFoAU +kTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZIhvcNAQENBQADggEBAHOJojanzqmg +aSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2iLNwYyTneuK6AChwKfnNvOFb8lV1 +iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4OHhyI0qNuz5oShNaACSioQ23WxHG +Vy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl0Z/wvXMt9cG6jbMvcdH4z0IOvg6m +rYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+fX5ODxh52MbNRYXTus2ZPRPM8JXN +QC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyybQYjfrgg4DRvw9Ksk22OH4ConlB8f +7R7s1LM2cSYxggJ8MIICeAIBATBsMFUxDTALBgNVBAoTBElFVEYxETAPBgNVBAsT +CExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUgTEFNUFMgUlNBIENlcnRpZmljYXRp +b24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0+GrOmqnXMAsGCWCGSAFlAwQCAaCB +5DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0yNjEx +MDkxMjA5NTFaMC8GCSqGSIb3DQEJBDEiBCCl3jtcr1bjeDRcGd4HoRLXWhkBqvOm +0Ywlw7H6AYF2pzB5BgkqhkiG9w0BCQ8xbDBqMAsGCWCGSAFlAwQBKjALBglghkgB +ZQMEARYwCwYJYIZIAWUDBAECMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDAN +BggqhkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0B +AQEFAASCAQCdA13x7k+GfWJ1VaBmqgZSopdlAXaiOZD124a/mAAjNOY6kjqXhZoq +Pi1PYQVrxzBBohWEXP1kqyEQ9IN6n3Lsi6TNWLfv0K4dGid6Un2vA9CGRfsoslV+ +eaEAVzlcf0B1XEc++mc/n1lqeRc7oy/NU72RgpB1+VkLyC/kGXtKH4WlL/RUY8Rc +0f62REZ5faOjlhjleyPaAZMFuJlDTu6uf51wRMnF4Yj5wtrm2SDdgF4sq2EYQx6S +/20lqSR8yy+kxbmbhOyI7PQDyAGuTnM/lhYRT6H6Mq9KVBfJhwZtTTj4iv7LQdJr +ahspSjOUmU6aaFjN6iTTACwV/5XqqKkKAAAAAAAA + diff --git a/crates/smime/testdata/opaque.eml b/crates/smime/testdata/opaque.eml new file mode 100644 index 0000000000..226af352b7 --- /dev/null +++ b/crates/smime/testdata/opaque.eml @@ -0,0 +1,47 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Opaque minutes +MIME-Version: 1.0 +Content-Disposition: attachment; filename="smime.p7m" +Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m" +Content-Transfer-Encoding: base64 + +MIIHAwYJKoZIhvcNAQcCoIIG9DCCBvACAQExDTALBglghkgBZQMEAgEwgYQGCSqG +SIb3DQEHAaB3BHVDb250ZW50LVR5cGU6IHRleHQvcGxhaW47IGNoYXJzZXQ9dXMt +YXNjaWkNCg0KSGVsbG8gQm9iLA0KDQpUaGUgbWludXRlcyBvZiBUdWVzZGF5IGFy +ZSBhdHRhY2hlZCBpbiBzcGlyaXQuDQoNCkFsaWNlDQqgggPTMIIDzzCCAregAwIB +AgITN0EFee11f0Kpolw69Phqzpqp1zANBgkqhkiG9w0BAQ0FADBVMQ0wCwYDVQQK +EwRJRVRGMREwDwYDVQQLEwhMQU1QUyBXRzExMC8GA1UEAxMoU2FtcGxlIExBTVBT +IFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAgFw0xOTExMjAwNjU0MThaGA8y +MDUyMDkyNzA2NTQxOFowOzENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMg +V0cxFzAVBgNVBAMTDkFsaWNlIExvdmVsYWNlMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAtPSJ6Fg4Fj5Nmn9PkrYo0jTkfCv4TfA/pdO/KLpZbJOAEr0s +I7AjaO7B1GuMUFJeSTulamNfCwDcDkY63PQWl+DILs7GxVwXurhYdZlaV5hcUqVA +ckPvedDBc/3rz4D/esFfs+E7QMFtmd+K04s+A8TCNO12DRVBDpbP4JFD9hsc8prD +tpGmFk7rd0q8gqnhxBW2RZAeLqzJOMayCQtws1q7ktkNBR2wZX5ICjecF1YJFhX4 +jrnHwp/iELGqqaNXd3/Y0pG7QFecN7836IPPdfTMSiPR+peCrhJZwLSewbWXLJe3 +VMvbvQjoBMpEYlaJBUIKkO1zQ1Pq90njlsJLOwIDAQABo4GvMIGsMAwGA1UdEwEB +/wQCMAAwFwYDVR0gBBAwDjAMBgpghkgBZQMCATABMB4GA1UdEQQXMBWBE2FsaWNl +QHNtaW1lLmV4YW1wbGUwEwYDVR0lBAwwCgYIKwYBBQUHAwQwDgYDVR0PAQH/BAQD +AgbAMB0GA1UdDgQWBBS79syyLR0GEhyXrilqkBDTIGZmczAfBgNVHSMEGDAWgBSR +MI58BxcMp/EJKGU2GmccaHb0WTANBgkqhkiG9w0BAQ0FAAOCAQEAc4miNqfOqaBp +I3f+CpJDhxtuZ2P9HjQEQ+v6BdP7GKJ19naIs3BjJOd64roAKHAp+c284VvyVXWJ +99FMX8q2ZUQMxH+xh6oAfzcozmnd6XaVWHg4eHIjSo27PmhKE1oAJKKhDbdbEcZX +L2+x1V+duGymWtaD01DZZukKYr7agyHahiXRn/C9cy31wbqNsy9x0fjPQg6+Dqat +iQpMz9EIae6aCHHBhOiPU7IPkazgPYgkLD59fk4PGHnYxs1FhdO6zZk9E8zwlc1A +LgZa/iSbczisqckN3qGehD2s16jMhwFXLJtBiN+uCDgNG/D0qyTbY4fgKieUHx/t +HuzUszZxJjGCAnwwggJ4AgEBMGwwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMI +TEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkCEzdBBXntdX9CqaJcOvT4as6aqdcwCwYJYIZIAWUDBAIBoIHk +MBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTI2MTEw +OTEyMDk1MVowLwYJKoZIhvcNAQkEMSIEIKXeO1yvVuN4NFwZ3gehEtdaGQGq86bR +jCXDsfoBgXanMHkGCSqGSIb3DQEJDzFsMGowCwYJYIZIAWUDBAEqMAsGCWCGSAFl +AwQBFjALBglghkgBZQMEAQIwCgYIKoZIhvcNAwcwDgYIKoZIhvcNAwICAgCAMA0G +CCqGSIb3DQMCAgFAMAcGBSsOAwIHMA0GCCqGSIb3DQMCAgEoMA0GCSqGSIb3DQEB +AQUABIIBAJ0DXfHuT4Z9YnVVoGaqBlKil2UBdqI5kPXbhr+YACM05jqSOpeFmio+ +LU9hBWvHMEGiFYRc/WSrIRD0g3qfcuyLpM1Yt+/Qrh0aJ3pSfa8D0IZF+yiyVX55 +oQBXOVx/QHVcRz76Zz+fWWp5FzujL81TvZGCkHX5WQvIL+QZe0ofhaUv9FRjxFzR +/rZERnl9o6OWGOV7I9oBkwW4mUNO7q5/nXBEycXhiPnC2ubZIN2AXiyrYRhDHpL/ +bSWpJHzLL6TFuZuE7Ijs9APIAa5Ocz+WFhFPofoyr0pUF8mHBm1NOPiK/stB0mtq +GylKM5SZTppoWM3qJNMALBX/leqoqQo= + diff --git a/crates/smime/testdata/pss.eml b/crates/smime/testdata/pss.eml new file mode 100644 index 0000000000..1fa054da52 --- /dev/null +++ b/crates/smime/testdata/pss.eml @@ -0,0 +1,62 @@ +To: bob@smime.example +From: alice@smime.example +Subject: PSS minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha-384"; boundary="----E33A7E587DACB5F6484402726C200129" + +This is an S/MIME signed message + +------E33A7E587DACB5F6484402726C200129 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------E33A7E587DACB5F6484402726C200129 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGzQYJKoZIhvcNAQcCoIIGvjCCBroCAQExDTALBglghkgBZQMEAgIwCwYJKoZI +hvcNAQcBoIID0zCCA88wggK3oAMCAQICEzdBBXntdX9CqaJcOvT4as6aqdcwDQYJ +KoZIhvcNAQENBQAwVTENMAsGA1UEChMESUVURjERMA8GA1UECxMITEFNUFMgV0cx +MTAvBgNVBAMTKFNhbXBsZSBMQU1QUyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwIBcNMTkxMTIwMDY1NDE4WhgPMjA1MjA5MjcwNjU0MThaMDsxDTALBgNVBAoT +BElFVEYxETAPBgNVBAsTCExBTVBTIFdHMRcwFQYDVQQDEw5BbGljZSBMb3ZlbGFj +ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALT0iehYOBY+TZp/T5K2 +KNI05Hwr+E3wP6XTvyi6WWyTgBK9LCOwI2juwdRrjFBSXkk7pWpjXwsA3A5GOtz0 +FpfgyC7OxsVcF7q4WHWZWleYXFKlQHJD73nQwXP968+A/3rBX7PhO0DBbZnfitOL +PgPEwjTtdg0VQQ6Wz+CRQ/YbHPKaw7aRphZO63dKvIKp4cQVtkWQHi6syTjGsgkL +cLNau5LZDQUdsGV+SAo3nBdWCRYV+I65x8Kf4hCxqqmjV3d/2NKRu0BXnDe/N+iD +z3X0zEoj0fqXgq4SWcC0nsG1lyyXt1TL270I6ATKRGJWiQVCCpDtc0NT6vdJ45bC +SzsCAwEAAaOBrzCBrDAMBgNVHRMBAf8EAjAAMBcGA1UdIAQQMA4wDAYKYIZIAWUD +AgEwATAeBgNVHREEFzAVgRNhbGljZUBzbWltZS5leGFtcGxlMBMGA1UdJQQMMAoG +CCsGAQUFBwMEMA4GA1UdDwEB/wQEAwIGwDAdBgNVHQ4EFgQUu/bMsi0dBhIcl64p +apAQ0yBmZnMwHwYDVR0jBBgwFoAUkTCOfAcXDKfxCShlNhpnHGh29FkwDQYJKoZI +hvcNAQENBQADggEBAHOJojanzqmgaSN3/gqSQ4cbbmdj/R40BEPr+gXT+xiidfZ2 +iLNwYyTneuK6AChwKfnNvOFb8lV1iffRTF/KtmVEDMR/sYeqAH83KM5p3el2lVh4 +OHhyI0qNuz5oShNaACSioQ23WxHGVy9vsdVfnbhsplrWg9NQ2WbpCmK+2oMh2oYl +0Z/wvXMt9cG6jbMvcdH4z0IOvg6mrYkKTM/RCGnumghxwYToj1OyD5Gs4D2IJCw+ +fX5ODxh52MbNRYXTus2ZPRPM8JXNQC4GWv4km3M4rKnJDd6hnoQ9rNeozIcBVyyb +QYjfrgg4DRvw9Ksk22OH4ConlB8f7R7s1LM2cSYxggLAMIICvAIBATBsMFUxDTAL +BgNVBAoTBElFVEYxETAPBgNVBAsTCExBTVBTIFdHMTEwLwYDVQQDEyhTYW1wbGUg +TEFNUFMgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5AhM3QQV57XV/QqmiXDr0 ++GrOmqnXMAsGCWCGSAFlAwQCAqCB9DAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB +MBwGCSqGSIb3DQEJBTEPFw0yNjExMDkxMjA5NTFaMD8GCSqGSIb3DQEJBDEyBDD4 +2qGCADijATcenlkhPijI4rlMODPEVAYYj23MDi+U5OoGk43dPeqaLE2/OuP3d9Ew +eQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZIAWUDBAEWMAsGCWCG +SAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAwDQYIKoZIhvcNAwIC +AUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwQQYJKoZIhvcNAQEKMDSgDzANBglg +hkgBZQMEAgIFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgIFAKIDAgEwBIIB +AFYJfuEecetLuIAZBdhyppBpqzeF9JN9RuGyi7qmrUFFU8xSyNh8/NFFE7UJ91Eo ++/zbQkuz0lfak8NSA1dw+qr2LnmnvpjD7LelEDJawTWJwzFnAVQaW7PaduLBwxZU +WmJRV6h4UZ1YEh8XEjpCqeUHTfqSiEyCaw0XOct6UoPOZQ64/7ytBOwrMUdMZNO5 +upqKR/NZSTwG91Izy78ORpW97ckbFcsklPOedHypUuecJTK5gzMEh2w5TGYZGRNs +x2kz6OqzzdhMUdT9DG84PGmZDTrp+Gw8lBWCUJs/1AMYm8ZKx/eSJwasJpeGaFUS +gPrYtiiA1mEl+vujBbhlwSo= + +------E33A7E587DACB5F6484402726C200129-- + diff --git a/crates/smime/testdata/sha1.eml b/crates/smime/testdata/sha1.eml new file mode 100644 index 0000000000..3a25ad9414 --- /dev/null +++ b/crates/smime/testdata/sha1.eml @@ -0,0 +1,60 @@ +To: bob@smime.example +From: alice@smime.example +Subject: Old minutes +MIME-Version: 1.0 +Content-Type: multipart/signed; protocol="application/pkcs7-signature"; micalg="sha1"; boundary="----C0EDEE0A5F012496F372EFC5533B6179" + +This is an S/MIME signed message + +------C0EDEE0A5F012496F372EFC5533B6179 +Content-Type: text/plain; charset=us-ascii + +Hello Bob, + +The minutes of Tuesday are attached in spirit. + +Alice + +------C0EDEE0A5F012496F372EFC5533B6179 +Content-Type: application/pkcs7-signature; name="smime.p7s" +Content-Transfer-Encoding: base64 +Content-Disposition: attachment; filename="smime.p7s" + +MIIGdQYJKoZIhvcNAQcCoIIGZjCCBmICAQExCTAHBgUrDgMCGjALBgkqhkiG9w0B +BwGgggPTMIIDzzCCAregAwIBAgITN0EFee11f0Kpolw69Phqzpqp1zANBgkqhkiG +9w0BAQ0FADBVMQ0wCwYDVQQKEwRJRVRGMREwDwYDVQQLEwhMQU1QUyBXRzExMC8G +A1UEAxMoU2FtcGxlIExBTVBTIFJTQSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAg +Fw0xOTExMjAwNjU0MThaGA8yMDUyMDkyNzA2NTQxOFowOzENMAsGA1UEChMESUVU +RjERMA8GA1UECxMITEFNUFMgV0cxFzAVBgNVBAMTDkFsaWNlIExvdmVsYWNlMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtPSJ6Fg4Fj5Nmn9PkrYo0jTk +fCv4TfA/pdO/KLpZbJOAEr0sI7AjaO7B1GuMUFJeSTulamNfCwDcDkY63PQWl+DI +Ls7GxVwXurhYdZlaV5hcUqVAckPvedDBc/3rz4D/esFfs+E7QMFtmd+K04s+A8TC +NO12DRVBDpbP4JFD9hsc8prDtpGmFk7rd0q8gqnhxBW2RZAeLqzJOMayCQtws1q7 +ktkNBR2wZX5ICjecF1YJFhX4jrnHwp/iELGqqaNXd3/Y0pG7QFecN7836IPPdfTM +SiPR+peCrhJZwLSewbWXLJe3VMvbvQjoBMpEYlaJBUIKkO1zQ1Pq90njlsJLOwID +AQABo4GvMIGsMAwGA1UdEwEB/wQCMAAwFwYDVR0gBBAwDjAMBgpghkgBZQMCATAB +MB4GA1UdEQQXMBWBE2FsaWNlQHNtaW1lLmV4YW1wbGUwEwYDVR0lBAwwCgYIKwYB +BQUHAwQwDgYDVR0PAQH/BAQDAgbAMB0GA1UdDgQWBBS79syyLR0GEhyXrilqkBDT +IGZmczAfBgNVHSMEGDAWgBSRMI58BxcMp/EJKGU2GmccaHb0WTANBgkqhkiG9w0B +AQ0FAAOCAQEAc4miNqfOqaBpI3f+CpJDhxtuZ2P9HjQEQ+v6BdP7GKJ19naIs3Bj +JOd64roAKHAp+c284VvyVXWJ99FMX8q2ZUQMxH+xh6oAfzcozmnd6XaVWHg4eHIj +So27PmhKE1oAJKKhDbdbEcZXL2+x1V+duGymWtaD01DZZukKYr7agyHahiXRn/C9 +cy31wbqNsy9x0fjPQg6+DqatiQpMz9EIae6aCHHBhOiPU7IPkazgPYgkLD59fk4P +GHnYxs1FhdO6zZk9E8zwlc1ALgZa/iSbczisqckN3qGehD2s16jMhwFXLJtBiN+u +CDgNG/D0qyTbY4fgKieUHx/tHuzUszZxJjGCAmwwggJoAgEBMGwwVTENMAsGA1UE +ChMESUVURjERMA8GA1UECxMITEFNUFMgV0cxMTAvBgNVBAMTKFNhbXBsZSBMQU1Q +UyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkCEzdBBXntdX9CqaJcOvT4as6a +qdcwBwYFKw4DAhqggdgwGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG +9w0BCQUxDxcNMjYxMTA5MTIwOTUxWjAjBgkqhkiG9w0BCQQxFgQU7fMLLzqCEOLs +sYLIvwK6bSUQpwQweQYJKoZIhvcNAQkPMWwwajALBglghkgBZQMEASowCwYJYIZI +AWUDBAEWMAsGCWCGSAFlAwQBAjAKBggqhkiG9w0DBzAOBggqhkiG9w0DAgICAIAw +DQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwDQYJKoZIhvcN +AQEBBQAEggEApwr9S+87L4Z+UZdVtuNmWH0eLmERMX6KTQ+zrlDxpXCq0ZPFkB7E +UijWdUoaWHOuwQbQac1tAoC9jP5cdpI9S3BB4QySECdzDOg6djzEnFEYrqddCKGY +nQswbRP/+mTMzN+lxO4kYjiHfb34egKPjgBiX6kUCpoxEZeV6joAtFRgBnkbUL4H +B2R+aiYiJt5jO1kB5beMf/gSFoIaycOf3EuTifNpPm2LsNGuEFZ72CRl2aHs2njc +O6XSZr8kODvUsPKJlXeqtThamr7Iy3NRvxQjDPFiW6i3TW9eo1/1LKSpDjjP8qet +p+iNds1neRoqaaDEkLifdykzuBLA0Sig8Q== + +------C0EDEE0A5F012496F372EFC5533B6179-- + diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index c3912696dd..3615a719cf 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -27,9 +27,11 @@ usvg = { version = "=0.48.1", default-features = false, optional = true } # so callers that only need bounded SVG text/tree parsing do not pull in raster backends. resvg = { version = "=0.48.1", default-features = false, features = ["text", "raster-images"], optional = true } +data-url = { version = "0.3.2", optional = true } + [features] # `craft_svg::tree`: usvg behind the bounded entry point. -tree = ["dep:usvg"] +tree = ["dep:usvg", "dep:data-url"] # Text converted to paths (needs a font database in the options). tree-text = ["tree", "usvg/text"] # The system's fonts in `usvg::fontdb`. diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 9cb004d896..cb33137b81 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -302,6 +302,7 @@ struct Used { raster_limit: AtomicUsize, invalid_svg: AtomicUsize, svg_limit: AtomicUsize, + svg_resource_limit: AtomicUsize, } /// What resolving one drawing's embedded images used or refused. @@ -323,6 +324,10 @@ pub struct ImageUsage { pub invalid_svg_images: usize, /// Embedded SVG data refused by byte or nesting limits. pub svg_limit_images: usize, + /// Subset of `svg_limit_images` refused by unpacked byte or embedded-document-chain limits. + /// XML/tree-depth omissions and invalid or corrupt data do not set this counter. Consumers + /// can reject resource overruns while still allowing an optional, over-deep child to be omitted. + pub svg_resource_limit_images: usize, } /// A data-URL resolver and the accounting for the one drawing it serves. @@ -350,6 +355,7 @@ impl ImageResolver { raster_limit: AtomicUsize::new(0), invalid_svg: AtomicUsize::new(0), svg_limit: AtomicUsize::new(0), + svg_resource_limit: AtomicUsize::new(0), }), } } @@ -365,6 +371,16 @@ impl ImageResolver { self.used.xml_depth.store(depth, Ordering::Relaxed); } + /// Account for malformed image data URLs before usvg discards them without calling + /// its image resolver. Call once for the outer document, before `parse_text`. + /// Nested SVGs are checked automatically. The scan shares the normal XML limits and + /// streaming-validates URL encoding without allocating another decoded image buffer. + pub fn check_document(&self, svg: &str) -> Result<(), Error> { + let xml = checked(svg, &self.limits)?; + account_invalid_data_urls(&xml, &self.used); + Ok(()) + } + /// Snapshot accounting after parsing has finished. pub fn usage(&self) -> ImageUsage { ImageUsage { @@ -376,6 +392,28 @@ impl ImageResolver { raster_limit_images: self.used.raster_limit.load(Ordering::Relaxed), invalid_svg_images: self.used.invalid_svg.load(Ordering::Relaxed), svg_limit_images: self.used.svg_limit.load(Ordering::Relaxed), + svg_resource_limit_images: self.used.svg_resource_limit.load(Ordering::Relaxed), + } + } +} + +// usvg's data-URL decoder returns before resolve_data for invalid base64. Count +// these omissions separately, including feImage, without reading linked resources. +fn account_invalid_data_urls(xml: &roxmltree::Document<'_>, used: &Used) { + for node in xml.descendants().filter(|n| n.is_element() && matches!(n.tag_name().name(), "image" | "feImage")) { + let href = node.attribute(("http://www.w3.org/1999/xlink", "href")).or_else(|| node.attribute("href")); + let Some(href) = href else { continue }; + let url = match data_url::DataUrl::process(href) { + Ok(url) => url, + // Use the parser's normalized scheme recognition, including whitespace. + Err(data_url::DataUrlError::NoComma) => { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); + continue; + } + Err(data_url::DataUrlError::NotADataUrl) => continue, + }; + if url.decode(|_| Ok::<(), std::convert::Infallible>(())).is_err() { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); } } } @@ -425,6 +463,24 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc>, format: craft_ } } drop(seen); + // A valid header is not proof of valid pixels. resvg can silently omit a damaged + // image later; decode now under explicit limits so omission accounting is honest. + let decode_limits = craft_image_codecs::Limits::new(width, height, pixels, limits.embedded_raster_pixels.saturating_mul(8)); + let options = craft_image_codecs::DecodeOptions { limits: decode_limits, keep_orientation: true }; + if let Err(error) = craft_image_codecs::decode_as_with(format, &data, &options) { + // No tree retains this allocation on failure. Forget its address before it + // can be reused, but keep the pixel charge for the decode work already spent. + used.raster_data.lock().unwrap_or_else(PoisonError::into_inner).remove(&pointer); + match error { + craft_image_codecs::CodecError::LimitExceeded(_) => { + used.raster_limit.fetch_add(1, Ordering::Relaxed); + } + _ => { + used.invalid_raster.fetch_add(1, Ordering::Relaxed); + } + } + return None; + } Some(match format { craft_image_codecs::Format::Png => usvg::ImageKind::PNG(data), craft_image_codecs::Format::Jpeg => usvg::ImageKind::JPEG(data), @@ -438,6 +494,7 @@ fn raster_image(used: &Used, limits: &Limits, data: Arc>, format: craft_ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<'_>) -> Option { if used.depth.load(Ordering::Relaxed) >= limits.embedded_depth { used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); return None; } let left = limits.embedded_bytes.saturating_sub(used.bytes.load(Ordering::Relaxed)); @@ -445,15 +502,37 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' Ok(text) => text, // What a refused document unpacked before it was refused was work too: it uses up what // is left, so the next image can't repeat it. - Err(_) => { + Err(error) => { used.bytes.fetch_add(left, Ordering::Relaxed); used.svg_limit.fetch_add(1, Ordering::Relaxed); + if matches!(error, svgz::Error::TooLarge(_)) { + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + } return None; } }; + // The raw/inflated bytes can fit while UTF-16/Latin-1 decoding expands + // beyond the aggregate allowance. A refusal consumes the remaining work. + if text.len() > left { + used.bytes.fetch_add(left, Ordering::Relaxed); + used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + return None; + } used.bytes.fetch_add(text.len(), Ordering::Relaxed); let xml = match checked(&text, limits) { Ok(xml) => xml, + // Decoding UTF-16 or Latin-1 can exceed the text cap after the + // raw/inflated bytes fitted. This is a resource refusal, not invalid XML. + Err(Error::Text(svgz::Error::TooLarge(_))) => { + used.svg_limit.fetch_add(1, Ordering::Relaxed); + used.svg_resource_limit.fetch_add(1, Ordering::Relaxed); + return None; + } + Err(Error::TooDeep(_)) => { + used.svg_limit.fetch_add(1, Ordering::Relaxed); + return None; + } Err(_) => { used.invalid_svg.fetch_add(1, Ordering::Relaxed); return None; @@ -471,6 +550,7 @@ fn embedded(used: &Used, limits: &Limits, data: &[u8], options: &usvg::Options<' let previous_depth = used.xml_depth.swap(total_depth, Ordering::Relaxed); let depth = used.depth.fetch_add(1, Ordering::Relaxed).saturating_add(1); used.svg_depth.fetch_max(depth, Ordering::Relaxed); + account_invalid_data_urls(&xml, used); let tree = usvg::Tree::from_xmltree(&xml, options); used.xml_depth.store(previous_depth, Ordering::Relaxed); used.depth.fetch_sub(1, Ordering::Relaxed); diff --git a/crates/svg/src/tree/tests.rs b/crates/svg/src/tree/tests.rs index 59b42dacc0..103c0fe7c2 100644 --- a/crates/svg/src/tree/tests.rs +++ b/crates/svg/src/tree/tests.rs @@ -245,6 +245,195 @@ fn embedded_svgs_are_read_within_their_budgets() { assert_eq!(found(&svg(r#""#), shallow()), [false; 0]); } +mod resource_limit_usage { + use super::*; + + fn data_image(bytes: &[u8]) -> String { + let encoded: String = bytes.iter().map(|byte| format!("%{byte:02X}")).collect(); + format!(r#""#) + } + + fn packed(text: &str, gzip: bool) -> Vec { + if gzip { svgz::compress(text.as_bytes()) } else { text.as_bytes().to_vec() } + } + + /// The outer document has its own generous text allowance, so tiny resolver limits + /// test the public embedded admission contract rather than rejecting the outer XML. + fn resolved(text: &str, limits: Limits, outer_depth: usize) -> (Vec, ImageUsage) { + let resolver = ImageResolver::new(limits); + resolver.set_document_depth(outer_depth); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse(text.as_bytes(), &shallow(), &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn expanding_encoded_children() -> Vec<(&'static str, Vec)> { + let latin = + format!("{}", svg(&format!("{}", "é".repeat(100)))); + let latin = latin.chars().map(|c| u8::try_from(u32::from(c)).unwrap()).collect(); + let wide = svg(&format!("{}", "ࠀ".repeat(400))); + let mut little = vec![0xff, 0xfe]; + little.extend(wide.encode_utf16().flat_map(u16::to_le_bytes)); + let mut big = vec![0xfe, 0xff]; + big.extend(wide.encode_utf16().flat_map(u16::to_be_bytes)); + vec![("Latin-1", latin), ("UTF-16LE", little), ("UTF-16BE", big)] + } + + #[test] + fn decoded_text_expansion_is_a_resource_refusal_for_plain_and_gzip_children() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let cap = raw.len(); + assert!(decoded.len() > cap, "{encoding} fixture must expand after inflation"); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, cap).unwrap().len(), cap, "raw bytes fit exactly"); + assert_eq!(svgz::text(&data, cap).unwrap().len(), decoded.len(), "decoding itself succeeds"); + let limits = Limits { bytes: cap, embedded_bytes: decoded.len(), ..shallow() }; + assert!(matches!(checked(&decoded, &limits), Err(Error::Text(svgz::Error::TooLarge(n))) if n == cap)); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "spent decoded work remains charged"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len(), "a refused sibling cannot repeat exhausted work"); + } + } + } + + #[test] + fn decoded_text_expansion_respects_aggregate_bytes_even_when_each_child_fits() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + let limits = Limits { bytes: decoded.len(), embedded_bytes: raw.len(), ..shallow() }; + assert!(decoded.len() > limits.embedded_bytes); + checked(&decoded, &limits).unwrap(); // The independent per-image cap allows this complete XML. + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + assert_eq!(svgz::inflate(&data, limits.embedded_bytes).unwrap().len(), raw.len()); + let image = data_image(&data); + let (found, usage) = resolved(&svg(&image), limits, 1); + assert!(found.is_empty(), "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (1, 1, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "refusal consumes exactly the remaining allowance"); + let (found, usage) = resolved(&svg(&format!("{image}{image}")), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (2, 2, 0)); + assert_eq!(usage.embedded_svg_bytes, limits.embedded_bytes, "a later child cannot repeat exhausted work"); + let (found, usage) = resolved(&svg(&image), Limits { embedded_bytes: decoded.len(), ..limits }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + } + } + } + + #[test] + fn decoded_text_expansion_at_the_cap_is_valid_and_malformed_xml_stays_invalid() { + for (encoding, raw) in expanding_encoded_children() { + let decoded = svgz::decode(&raw).unwrap(); + for gzip in [false, true] { + let data = if gzip { svgz::compress(&raw) } else { raw.clone() }; + let limits = Limits { bytes: decoded.len(), embedded_bytes: decoded.len(), ..shallow() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert_eq!(found, [true], "{encoding}, gzip {gzip}"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 0)); + assert_eq!(usage.embedded_svg_bytes, decoded.len()); + // Preserve the declared/BOM encoding when making the XML malformed; + // re-encoding Latin-1 text as UTF-8 would test a second expansion instead. + let closing_bytes = if encoding == "Latin-1" { 6 } else { 12 }; + let malformed = &raw[..raw.len() - closing_bytes]; + let data = if gzip { svgz::compress(malformed) } else { malformed.to_vec() }; + let (found, usage) = resolved(&svg(&data_image(&data)), limits, 1); + assert!(found.is_empty()); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images, usage.invalid_svg_images), (0, 0, 1)); + } + } + } + + #[test] + fn embedded_chain_caps_are_explicit_resource_refusals_for_plain_and_gzip_children() { + for gzip in [false, true] { + let inner = svg(""); + let middle = svg(&data_image(&packed(&inner, gzip))); + let outer = svg(&data_image(&packed(&middle, gzip))); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 1, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_depth, 1); + assert_eq!(usage.svg_limit_images, 1, "strict consumers still see the existing limit flag"); + assert_eq!(usage.svg_resource_limit_images, 1, "a chain cap must not become a successful partial bounded preview"); + let (found, usage) = resolved(&outer, Limits { embedded_depth: 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn embedded_per_image_byte_caps_are_resource_refusals_for_plain_and_gzip_children() { + let inner = svg(""); + for gzip in [false, true] { + let outer = svg(&data_image(&packed(&inner, gzip))); + let (_, usage) = resolved(&outer, Limits { bytes: inner.len() - 1, embedded_bytes: inner.len() * 3, ..shallow() }, 1); + assert_eq!(usage.embedded_svg_count, 0); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { bytes: inner.len(), ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn aggregate_embedded_bytes_are_resource_refusals_even_when_each_child_fits() { + let inner = svg(""); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{image}{image}")); + let cap = inner.len() * 2 - 1; + let (found, usage) = resolved(&outer, Limits { embedded_bytes: cap, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!(usage.embedded_svg_bytes, cap, "a refused child still spends the remaining work allowance"); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (1, 1)); + let (found, usage) = resolved(&outer, Limits { embedded_bytes: inner.len() * 2, ..shallow() }, 1); + assert_eq!(found, [true, true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn combined_xml_depth_omissions_remain_distinct_from_resource_refusals() { + let inner = svg(""); + for gzip in [false, true] { + let image = data_image(&packed(&inner, gzip)); + let outer = svg(&format!("{}{}{}", "".repeat(4), image, "".repeat(4))); + let (found, usage) = resolved(&outer, Limits { tree_depth: 6, ..shallow() }, 5); + assert!(found.is_empty()); + assert_eq!(usage.svg_limit_images, 1, "strict consumers must continue to reject this omission"); + assert_eq!(usage.svg_resource_limit_images, 0, "non-strict consumers may omit this child without disguising a byte/chain overrun"); + let (found, usage) = resolved(&svg(&image), Limits { tree_depth: 6, ..shallow() }, 1); + assert_eq!(found, [true]); + assert_eq!((usage.svg_limit_images, usage.svg_resource_limit_images), (0, 0)); + } + } + + #[test] + fn invalid_and_corrupt_children_do_not_claim_a_resource_limit() { + let mut corrupt = svgz::compress(svg("").as_bytes()); + let crc = corrupt.len() - 8; + corrupt[crc] ^= 1; + for data in [b"not XML".to_vec(), corrupt] { + let (found, usage) = resolved(&svg(&data_image(&data)), shallow(), 1); + assert!(found.is_empty()); + assert!(usage.invalid_svg_images > 0 || usage.svg_limit_images > 0, "strict consumers still observe unreadable content"); + assert_eq!(usage.svg_resource_limit_images, 0); + } + } +} + mod draw_checks { use super::*; @@ -303,3 +492,95 @@ mod draw_checks { assert!(!refusal.memory && refusal.message.contains("clip-paths"), "{refusal:?}"); } } + +mod invalid_image_accounting { + use super::*; + + fn usage(body: &str, limits: Limits) -> (Vec, ImageUsage) { + let text = svg(body); + let resolver = ImageResolver::new(limits); + resolver.check_document(&text).unwrap(); + let options = usvg::Options { image_href_resolver: resolver.resolver(), ..Default::default() }; + let tree = parse_text(&text, &limits, &options).unwrap(); + let mut found = Vec::new(); + images(tree.root(), &mut found); + (found, resolver.usage()) + } + + fn png() -> Vec { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType, encode}; + let image = Image::new(1, 1, ChannelLayout::Rgba, SampleType::U8).unwrap(); + encode(&image, Format::Png, &EncodeOptions::default()).unwrap() + } + + fn image(data: &[u8]) -> String { + let encoded: String = data.iter().map(|b| format!("%{b:02X}")).collect(); + format!(r#""#) + } + + #[test] + fn malformed_base64_is_counted_before_usvg_discards_it() { + let bad = r#""#; + let (found, report) = usage(bad, shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&embed(&svg(bad)), shallow()); + assert_eq!(found, [true]); + assert_eq!(report.invalid_raster_images, 1); + } + + #[test] + fn malformed_data_url_without_comma_is_counted() { + for href in ["data:image/png;base64", " data:image/png;base64", "da ta:image/png;base64", "da ta:image/png;base64"] { + let bad = format!(r#""#); + let (found, report) = usage(&bad, shallow()); + assert!(found.is_empty(), "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + let (found, report) = usage(&embed(&svg(&bad)), shallow()); + assert_eq!(found, [true], "{href}"); + assert_eq!(report.invalid_raster_images, 1, "{href}"); + } + } + + #[test] + fn failed_decode_forgets_address_but_preserves_spent_budget() { + let valid = png(); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let invalid = Arc::new(valid[..idat + 4].to_vec()); + let pointer = Arc::as_ptr(&invalid) as usize; + let limits = Limits { embedded_raster_pixels: 3, ..shallow() }; + let resolver = ImageResolver::new(limits); + let used = &resolver.used; + let format = craft_image_codecs::Format::Png; + assert!(raster_image(used, &limits, invalid, format).is_none()); + assert!(!used.raster_data.lock().unwrap().contains(&pointer)); + assert_eq!(resolver.usage().raster_pixels, 1); + let first_data = Arc::new(valid.clone()); + let first = raster_image(used, &limits, first_data.clone(), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let repeated = raster_image(used, &limits, first_data, format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 2); + let second = raster_image(used, &limits, Arc::new(valid.clone()), format).unwrap(); + assert_eq!(resolver.usage().raster_pixels, 3); + assert!(raster_image(used, &limits, Arc::new(valid), format).is_none()); + assert_eq!(resolver.usage().raster_limit_images, 1); + drop((first, repeated, second)); + } + + #[test] + fn corrupt_pixels_do_not_pass_a_valid_header_probe() { + let valid = png(); + let (found, report) = usage(&image(&valid), shallow()); + assert_eq!(found, [false]); + assert_eq!(report.invalid_raster_images, 0); + let idat = valid.windows(4).position(|b| b == b"IDAT").unwrap(); + let corrupt = &valid[..idat + 4]; + assert_eq!(craft_image_codecs::probe_allocation_size(corrupt).unwrap(), (1, 1)); + let (found, report) = usage(&image(corrupt), shallow()); + assert!(found.is_empty()); + assert_eq!(report.invalid_raster_images, 1); + let (found, report) = usage(&image(&valid), Limits { embedded_raster_pixels: 0, ..shallow() }); + assert!(found.is_empty()); + assert_eq!(report.raster_limit_images, 1); + } +} diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index 469a4f8fa4..66cb1d6a09 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -86,18 +86,36 @@ impl Attribute { pub fn translate_scale(x: f64, y: f64, scale_x: f64, scale_y: f64) -> Self { Self { name: "transform".into(), value: Value::TranslateScale { x, y, scale_x, scale_y } } } + /// A translate/scale transform with three decimal places for positions and four for scales. + pub fn translate_scale_fixed(x: f64, y: f64, scale_x: f64, scale_y: f64) -> Self { + Self::text("transform", format!("translate({} {}) scale({} {})", num(x, 3), num(y, 3), num(scale_x, 4), num(scale_y, 4))) + } } impl Scene { /// Serialize the scene as an SVG 1.1 document. pub fn write(&self) -> String { + self.write_impl(false) + } + + /// Serialize the root viewBox with three decimal places for stable fixed-width output. + pub fn write_fixed_view_box(&self) -> String { + self.write_impl(true) + } + + fn write_impl(&self, fixed: bool) -> String { let mut writer = SvgWriter::new(); + let view_box = if fixed { + format!("{} {} {} {}", num(self.view_box[0], 3), num(self.view_box[1], 3), num(self.view_box[2], 3), num(self.view_box[3], 3)) + } else { + view_box_data(self.view_box) + }; writer .root() .attr("version", "1.1") .attr("width", format!("{}mm", num(self.width_mm, 3))) .attr("height", format!("{}mm", num(self.height_mm, 3))) - .attr("viewBox", view_box_data(self.view_box)) + .attr("viewBox", view_box) .open(); write_elements(&mut writer, &self.elements, 1); writer.line(0); @@ -307,6 +325,14 @@ mod tests { p } + #[test] + fn scene_can_keep_fixed_view_box_without_changing_default_output() { + let scene = Scene { width_mm: 100.0, height_mm: 150.0, view_box: [0.0, 0.0, 100.0, 150.0], elements: vec![] }; + assert!(scene.write().contains("viewBox=\"0 0 100 150\"")); + assert!(scene.write_fixed_view_box().contains("viewBox=\"0.000 0.000 100.000 150.000\"")); + assert_eq!(Attribute::translate_scale_fixed(6.0, 46.0, 0.5, -0.5).value, Value::Text("translate(6.000 46.000) scale(0.5000 -0.5000)".into())); + } + #[test] fn numbers_have_fixed_decimals_and_are_never_non_finite() { assert_eq!(num(1.5, 3).to_string(), "1.500"); diff --git a/crates/tcraft/Cargo.toml b/crates/tcraft/Cargo.toml new file mode 100644 index 0000000000..3ce35abfb0 --- /dev/null +++ b/crates/tcraft/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-tcraft" +description = "Streaming binary payloads of TextureCraft project archives" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-zip = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/tcraft/README.md b/crates/tcraft/README.md new file mode 100644 index 0000000000..e5831ef98b --- /dev/null +++ b/crates/tcraft/README.md @@ -0,0 +1,14 @@ +# craft-tcraft + +Streaming neutral `TCTX` binary payloads used inside TextureCraft `.tcraft` projects. Sparse +paint data stores 64×64 tiles of little-endian `u16` components; baked maps store dense +little-endian `f32` values. This crate does not yet define the project JSON schema or ZIP +envelope and does not depend on TextureCraft's app types. + +`read_tiles` validates the expected dimensions and components, bounds tile count, rejects +out-of-range and repeated tile positions, and delivers one owned tile at a time. `read_baked` +validates dimensions and declared length and decodes in bounded chunks. Both consume the same +caller-owned `craft_zip::Budget` used for the surrounding project and reject trailing data. +`write_tiles` and `write_baked` stream their bodies rather than copying an entire image; a caller +must discard an incomplete output if a write fails. Limits and ownership rules beyond this +binary format remain with the project reader. diff --git a/crates/tcraft/src/lib.rs b/crates/tcraft/src/lib.rs new file mode 100644 index 0000000000..d7af3e8a6d --- /dev/null +++ b/crates/tcraft/src/lib.rs @@ -0,0 +1,428 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Streaming `TCTX` tile and baked-map payloads in TextureCraft `.tcraft` archives. +//! +//! This codec handles the neutral binary payload, not the application's project model or ZIP +//! envelope. Reads use a caller-owned budget shared with other archive entries. No reader opens +//! a file or reserves memory based on a claimed payload before checking it. + +use std::collections::{BTreeMap, HashSet}; +use std::io::{self, Read, Write}; + +use craft_zip::Budget; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub const TILE_SIDE: u32 = 64; +pub const TILE_AREA: usize = 64 * 64; +pub const HEADER_BYTES: u64 = 24; +pub const VERSION: u32 = 1; +const MAGIC: &[u8; 4] = b"TCTX"; +const CHUNK: usize = 1 << 16; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid TCTX payload: {0}")] + Invalid(String), + #[error("TCTX version {0} is newer than supported")] + NewerVersion(u32), + #[error("TCTX budget: {0}")] + Budget(#[from] craft_zip::Exceeded), + #[error("TCTX limit: {0}")] + Limit(String), + #[error("TCTX I/O: {0}")] + Io(#[from] io::Error), +} + +/// Neutral top-level project schema. Nested app-domain values and unknown fields remain JSON +/// so they round-trip without requiring TextureCraft's in-memory model. +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct ProjectDocument { + pub format_version: u32, + pub name: String, + pub mesh: String, + pub normal_format: Value, + pub texture_sets: Vec, + pub layers: BTreeMap, + pub next_id: u64, + pub display: Value, + #[serde(default)] + pub cameras: Vec, + #[serde(flatten)] + pub extra: BTreeMap, +} + +impl Serialize for ProjectDocument { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::{Error as _, SerializeMap as _}; + const RESERVED: &[&str] = &["format_version", "name", "mesh", "normal_format", "texture_sets", "layers", "next_id", "display", "cameras"]; + if self.extra.keys().any(|key| RESERVED.contains(&key.as_str())) { + return Err(S::Error::custom("an extra project field duplicates a known field")); + } + let mut map = serializer.serialize_map(Some(9 + self.extra.len()))?; + map.serialize_entry("format_version", &self.format_version)?; + map.serialize_entry("name", &self.name)?; + map.serialize_entry("mesh", &self.mesh)?; + map.serialize_entry("normal_format", &self.normal_format)?; + map.serialize_entry("texture_sets", &self.texture_sets)?; + map.serialize_entry("layers", &self.layers)?; + map.serialize_entry("next_id", &self.next_id)?; + map.serialize_entry("display", &self.display)?; + map.serialize_entry("cameras", &self.cameras)?; + for (key, value) in &self.extra { + map.serialize_entry(key, value)?; + } + map.end() + } +} + +/// Read only the version before an application applies its own recovery policy. Serde's +/// structured parse rejects a duplicate or invalid version field, like the project reader. +pub fn project_version(bytes: &[u8]) -> Result { + #[derive(Deserialize)] + struct Version { + format_version: u32, + } + Ok(serde_json::from_slice::(bytes)?.format_version) +} + +/// Width, height and number of components expected by the enclosing project schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Layout { + pub width: u32, + pub height: u32, + pub components: usize, +} + +#[derive(Clone, Copy, Debug)] +struct Header { + layout: Layout, + count: u32, +} + +fn charge(budget: &mut Budget, n: u64) -> Result<(), Error> { + budget.charge(n).map_err(Error::from) +} + +fn read_header(reader: &mut (impl Read + ?Sized), budget: &mut Budget) -> Result { + charge(budget, HEADER_BYTES)?; + let mut bytes = [0u8; HEADER_BYTES as usize]; + reader.read_exact(&mut bytes)?; + if bytes.get(..4) != Some(MAGIC.as_slice()) { + return Err(Error::Invalid("bad magic".into())); + } + let word = |i: usize| bytes.get(i * 4..i * 4 + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).unwrap_or(0); + let version = word(1); + if version > VERSION { + return Err(Error::NewerVersion(version)); + } + Ok(Header { layout: Layout { width: word(2), height: word(3), components: word(4) as usize }, count: word(5) }) +} + +fn write_header(writer: &mut (impl Write + ?Sized), layout: Layout, count: u32) -> Result<(), Error> { + let components = u32::try_from(layout.components).map_err(|_| Error::Limit("too many components".into()))?; + writer.write_all(MAGIC)?; + for value in [VERSION, layout.width, layout.height, components, count] { + writer.write_all(&value.to_le_bytes())?; + } + Ok(()) +} + +fn expect_end(reader: &mut (impl Read + ?Sized)) -> Result<(), Error> { + let mut byte = [0u8; 1]; + if reader.read(&mut byte)? != 0 { + return Err(Error::Invalid("trailing data".into())); + } + Ok(()) +} + +fn tile_dimensions(layout: Layout) -> Result<(u32, u32, usize), Error> { + if layout.width == 0 || layout.height == 0 || layout.components == 0 { + return Err(Error::Invalid("empty tile layout".into())); + } + let x = layout.width.div_ceil(TILE_SIDE); + let y = layout.height.div_ceil(TILE_SIDE); + let bytes = TILE_AREA.checked_mul(layout.components).and_then(|n| n.checked_mul(2)).ok_or_else(|| Error::Limit("tile is too large".into()))?; + Ok((x, y, bytes)) +} + +/// Decode tiles one at a time, transferring each tile to the callback. +/// Positions and duplicate tiles are checked before delivery; the entry must end exactly. +pub fn read_tiles( + reader: &mut (impl Read + ?Sized), + expected: Layout, + max_texels: u64, + budget: &mut Budget, + mut tile: impl FnMut(u32, u32, Vec) -> Result<(), Error>, +) -> Result<(), Error> { + let header = read_header(reader, budget)?; + let texels = u64::from(expected.width) * u64::from(expected.height); + if texels == 0 || texels > max_texels { + return Err(Error::Limit("tile image exceeds its texel limit".into())); + } + if header.layout != expected { + return Err(Error::Invalid("tile layout differs from the project".into())); + } + let (tiles_x, tiles_y, bytes_per_tile) = tile_dimensions(expected)?; + if u64::from(header.count) > u64::from(tiles_x) * u64::from(tiles_y) { + return Err(Error::Invalid("more tiles than the image holds".into())); + } + let mut bytes = Vec::new(); + let mut seen = HashSet::new(); + for _ in 0..header.count { + let payload = u64::try_from(bytes_per_tile).map_err(|_| Error::Limit("tile is too large".into()))?.saturating_add(8); + charge(budget, payload)?; + if bytes.is_empty() { + bytes.try_reserve_exact(bytes_per_tile).map_err(|_| Error::Limit("tile allocation failed".into()))?; + bytes.resize(bytes_per_tile, 0); + } + let mut pos = [0u8; 8]; + reader.read_exact(&mut pos)?; + let x = u32::from_le_bytes([pos[0], pos[1], pos[2], pos[3]]); + let y = u32::from_le_bytes([pos[4], pos[5], pos[6], pos[7]]); + if x >= tiles_x || y >= tiles_y || seen.contains(&(x, y)) { + return Err(Error::Invalid(format!("bad or repeated tile ({x}, {y})"))); + } + seen.try_reserve(1).map_err(|_| Error::Limit("tile index allocation failed".into()))?; + seen.insert((x, y)); + reader.read_exact(&mut bytes)?; + let mut values = Vec::new(); + values.try_reserve_exact(bytes_per_tile / 2).map_err(|_| Error::Limit("tile allocation failed".into()))?; + values.extend(bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b))); + tile(x, y, values)?; + } + expect_end(reader) +} + +/// Write tiles in caller order, without buffering the image. A failure may leave a partial +/// entry; callers writing a project should discard the incomplete output. +pub fn write_tiles<'a>( + writer: &mut (impl Write + ?Sized), + layout: Layout, + count: u32, + tiles: impl IntoIterator, +) -> Result<(), Error> { + let (tiles_x, tiles_y, bytes_per_tile) = tile_dimensions(layout)?; + if u64::from(count) > u64::from(tiles_x) * u64::from(tiles_y) { + return Err(Error::Invalid("more tiles than the image holds".into())); + } + write_header(writer, layout, count)?; + let mut seen = HashSet::new(); + let mut bytes = Vec::new(); + let mut written = 0u32; + for (x, y, values) in tiles { + if written >= count || x >= tiles_x || y >= tiles_y || seen.contains(&(x, y)) || values.len() != bytes_per_tile / 2 { + return Err(Error::Invalid("bad, repeated or incorrectly sized tile".into())); + } + seen.try_reserve(1).map_err(|_| Error::Limit("tile index allocation failed".into()))?; + seen.insert((x, y)); + if bytes.is_empty() { + bytes.try_reserve_exact(bytes_per_tile).map_err(|_| Error::Limit("tile allocation failed".into()))?; + } + bytes.clear(); + bytes.extend(values.iter().flat_map(|v| v.to_le_bytes())); + writer.write_all(&x.to_le_bytes())?; + writer.write_all(&y.to_le_bytes())?; + writer.write_all(&bytes)?; + written += 1; + } + if written != count { + return Err(Error::Invalid("tile count differs from its data".into())); + } + Ok(()) +} + +/// Read a dense f32 map, validating declared size and charging its shared budget first. +pub fn read_baked( + reader: &mut (impl Read + ?Sized), + declared_bytes: u64, + components: usize, + max_texels: u64, + budget: &mut Budget, +) -> Result<(Layout, Vec), Error> { + let header = read_header(reader, budget)?; + let layout = header.layout; + let texels = u64::from(layout.width) * u64::from(layout.height); + if texels == 0 || texels > max_texels || layout.components != components || components == 0 { + return Err(Error::Invalid("bad baked-map dimensions or components".into())); + } + let count = texels.checked_mul(components as u64).ok_or_else(|| Error::Limit("too many map values".into()))?; + let payload = count.checked_mul(4).ok_or_else(|| Error::Limit("map is too large".into()))?; + if declared_bytes != HEADER_BYTES.checked_add(payload).ok_or_else(|| Error::Limit("map is too large".into()))? { + return Err(Error::Invalid(format!("{declared_bytes} bytes for a {}×{}×{} map", layout.width, layout.height, layout.components))); + } + charge(budget, payload)?; + let count = usize::try_from(count).map_err(|_| Error::Limit("too many map values".into()))?; + let mut values = Vec::new(); + let chunk_bytes = CHUNK.min(count) * 4; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(chunk_bytes).map_err(|_| Error::Limit("map chunk allocation failed".into()))?; + bytes.resize(chunk_bytes, 0); + while values.len() < count { + let n = CHUNK.min(count - values.len()); + let chunk = bytes.get_mut(..n * 4).ok_or_else(|| Error::Invalid("bad map chunk".into()))?; + reader.read_exact(chunk)?; + values.try_reserve(n).map_err(|_| Error::Limit("map allocation failed".into()))?; + values.extend(chunk.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + } + expect_end(reader)?; + Ok((layout, values)) +} + +/// Write a dense f32 map in bounded chunks without constructing a second copy of its payload. +pub fn write_baked(writer: &mut (impl Write + ?Sized), layout: Layout, values: &[f32]) -> Result<(), Error> { + let count = u64::from(layout.width).checked_mul(u64::from(layout.height)).and_then(|n| n.checked_mul(layout.components as u64)); + if layout.width == 0 || layout.height == 0 || layout.components == 0 || count != Some(values.len() as u64) { + return Err(Error::Invalid("map dimensions differ from its data".into())); + } + write_header(writer, layout, 0)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(CHUNK * 4).map_err(|_| Error::Limit("map chunk allocation failed".into()))?; + for chunk in values.chunks(CHUNK) { + bytes.clear(); + bytes.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); + writer.write_all(&bytes)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn header(layout: Layout, count: u32) -> Vec { + let mut bytes = Vec::new(); + write_header(&mut bytes, layout, count).unwrap(); + bytes + } + + #[test] + fn project_schema_keeps_nested_and_future_fields() { + let json = serde_json::json!({ + "format_version": 2, "name": "Stone", "mesh": "mesh.obj", "normal_format": "openGl", + "texture_sets": [{"name": "main", "futureSet": {"keep": true}}], + "layers": {"1": {"kind": "paint", "futureLayer": [1, 2]}}, "next_id": 2, + "display": {"futureDisplay": 4}, "mesh_file": "source.obj", "futureProject": [3] + }); + let bytes = serde_json::to_vec(&json).unwrap(); + assert_eq!(project_version(&bytes).unwrap(), 2); + let document: ProjectDocument = serde_json::from_slice(&bytes).unwrap(); + let mut expected = json; + expected["cameras"] = serde_json::json!([]); + assert_eq!(serde_json::to_value(&document).unwrap(), expected); + let mut duplicate = document; + duplicate.extra.insert("mesh".into(), serde_json::json!("other.obj")); + assert!(serde_json::to_vec(&duplicate).is_err()); + assert!(project_version(br#"{"format_version":1,"format_version":2}"#).is_err()); + assert!(project_version(br#"{"format_version":-1}"#).is_err()); + } + + #[test] + fn baked_map_matches_the_native_little_endian_wire_layout() { + let layout = Layout { width: 2, height: 1, components: 1 }; + let mut expected = b"TCTX".to_vec(); + for value in [1u32, 2, 1, 1, 0] { + expected.extend_from_slice(&value.to_le_bytes()); + } + expected.extend_from_slice(&1.0f32.to_le_bytes()); + expected.extend_from_slice(&(-0.5f32).to_le_bytes()); + let mut actual = Vec::new(); + write_baked(&mut actual, layout, &[1.0, -0.5]).unwrap(); + assert_eq!(actual, expected); + let (decoded, values) = read_baked(&mut Cursor::new(&expected), expected.len() as u64, 1, 2, &mut Budget::new("project", 32)).unwrap(); + assert_eq!(decoded, layout); + assert_eq!(values, [1.0, -0.5]); + expected[4..8].copy_from_slice(&2u32.to_le_bytes()); + assert!(matches!(read_baked(&mut Cursor::new(&expected), 32, 1, 2, &mut Budget::new("project", 32)), Err(Error::NewerVersion(2)))); + } + + #[test] + fn dense_maps_round_trip_bit_exactly_in_bounded_chunks() { + let layout = Layout { width: 300, height: 300, components: 1 }; + let mut values = vec![0.25; 90_000]; + values[123] = f32::from_bits(0x7fc0_1234); + let mut bytes = Vec::new(); + write_baked(&mut bytes, layout, &values).unwrap(); + let mut budget = Budget::new("project", bytes.len() as u64); + let (decoded_layout, decoded) = read_baked(&mut Cursor::new(&bytes), bytes.len() as u64, 1, 100_000, &mut budget).unwrap(); + assert_eq!(decoded_layout, layout); + assert!(decoded.iter().zip(values.iter()).all(|(a, b)| a.to_bits() == b.to_bits())); + assert_eq!(budget.remaining(), 0); + } + + #[test] + fn dense_maps_refuse_false_lengths_limits_and_trailing_data() { + let layout = Layout { width: 2, height: 2, components: 1 }; + let mut bytes = Vec::new(); + write_baked(&mut bytes, layout, &[1.0; 4]).unwrap(); + let mut budget = Budget::new("project", 100); + assert!(read_baked(&mut Cursor::new(&bytes), 999, 1, 4, &mut budget).is_err()); + let mut budget = Budget::new("project", 39); + assert!(matches!(read_baked(&mut Cursor::new(&bytes), 40, 1, 4, &mut budget), Err(Error::Budget(_)))); + let mut extra = bytes.clone(); + extra.push(0); + let mut budget = Budget::new("project", 100); + assert!(read_baked(&mut Cursor::new(extra), 40, 1, 4, &mut budget).is_err()); + } + + #[test] + fn hostile_headers_and_tiles_are_rejected_without_trusting_counts() { + let layout = Layout { width: 64, height: 64, components: 1 }; + assert!(matches!( + read_tiles(&mut Cursor::new(header(layout, 0)), layout, 4095, &mut Budget::new("project", 100), |_, _, _| Ok(())), + Err(Error::Limit(_)) + )); + let mut bad_magic = header(layout, 0); + bad_magic[0] = b'X'; + assert!(read_tiles(&mut Cursor::new(bad_magic), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + assert!(read_tiles(&mut Cursor::new(header(layout, 2)), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + let other = Layout { width: 65, ..layout }; + assert!(read_tiles(&mut Cursor::new(header(layout, 0)), other, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + let mut outside = header(layout, 1); + outside.extend_from_slice(&1u32.to_le_bytes()); + outside.extend_from_slice(&0u32.to_le_bytes()); + assert!(read_tiles(&mut Cursor::new(outside), layout, u64::MAX, &mut Budget::new("project", 10_000), |_, _, _| Ok(())).is_err()); + let mut truncated = header(layout, 1); + truncated.extend_from_slice(&[0; 8]); + assert!(read_tiles(&mut Cursor::new(truncated), layout, u64::MAX, &mut Budget::new("project", 10_000), |_, _, _| Ok(())).is_err()); + let mut extra = header(layout, 0); + extra.push(1); + assert!(read_tiles(&mut Cursor::new(extra), layout, u64::MAX, &mut Budget::new("project", 100), |_, _, _| Ok(())).is_err()); + } + + #[test] + fn sparse_tiles_stream_and_reject_duplicates_and_short_budget() { + let layout = Layout { width: 128, height: 64, components: 1 }; + let mut bytes = header(layout, 2); + for x in [0u32, 1] { + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..TILE_AREA { + bytes.extend_from_slice(&(x as u16 + 1).to_le_bytes()); + } + } + let first = vec![1u16; TILE_AREA]; + let second = vec![2u16; TILE_AREA]; + let mut written = Vec::new(); + write_tiles(&mut written, layout, 2, [(0, 0, first.as_slice()), (1, 0, second.as_slice())]).unwrap(); + assert_eq!(written, bytes, "the streamed writer keeps the native wire layout"); + assert!(write_tiles(&mut Vec::new(), layout, 2, [(0, 0, first.as_slice())]).is_err()); + let mut seen = Vec::new(); + let mut budget = Budget::new("project", bytes.len() as u64); + read_tiles(&mut Cursor::new(&bytes), layout, u64::MAX, &mut budget, |x, y, tile| { + seen.push((x, y, tile.first().copied())); + Ok(()) + }) + .unwrap(); + assert_eq!(seen, [(0, 0, Some(1)), (1, 0, Some(2))]); + let mut duplicate = bytes.clone(); + let second = HEADER_BYTES as usize + 8 + TILE_AREA * 2; + duplicate[second..second + 4].copy_from_slice(&0u32.to_le_bytes()); + assert!(read_tiles(&mut Cursor::new(duplicate), layout, u64::MAX, &mut Budget::new("project", u64::MAX), |_, _, _| Ok(())).is_err()); + assert!(matches!( + read_tiles(&mut Cursor::new(bytes), layout, u64::MAX, &mut Budget::new("project", HEADER_BYTES), |_, _, _| Ok(())), + Err(Error::Budget(_)) + )); + } +} diff --git a/crates/timeline/src/fcpxml.rs b/crates/timeline/src/fcpxml.rs index 198574718f..4a255ba430 100644 --- a/crates/timeline/src/fcpxml.rs +++ b/crates/timeline/src/fcpxml.rs @@ -125,6 +125,16 @@ struct Asset { has_audio: bool, } +// Bound semantic resource chains separately from XML syntax: flat media resources can +// reference one another without adding any XML nesting. +const MAX_MEDIA_DEPTH: usize = 64; +const MAX_XML_DEPTH: usize = 128; +// Retrying truncated resources is useful at shallower depths, but must remain bounded. +const MAX_REIMPORTS: usize = 4096; +// A hostile document may reference the same large cached graph repeatedly. Bound total +// reachability work, not just one walk, and refuse reuse when safety cannot be established. +const MAX_CACHE_EDGES: usize = 1_000_000; + struct Imp<'a, 'c, 'r> { b: Builder<'c>, opts: &'a ImportOptions<'a>, @@ -135,6 +145,13 @@ struct Imp<'a, 'c, 'r> { media_nodes: HashMap>, media_items: HashMap, media_active: HashSet, + depth_hits: usize, + // Depths at which a cached resource was truncated. A retry may improve neither limit + // at the expense of the other, and reuses the same item so earlier references stay valid. + media_truncated_at: HashMap, + reimports_left: usize, + cache_edges_left: usize, + depth: usize, effects: HashMap, } @@ -186,6 +203,11 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Result { if let Some(s) = child(c, "sequence") { let name = c.attribute("name").unwrap_or("Project"); - let id = imp.sequence(s, name, Some(bin)); + let id = imp.sequence(s, name, Some(bin), None); imp.b.top.push(id); } } @@ -244,7 +266,7 @@ pub fn import(text: &str, opts: &ImportOptions, report: &mut Report) -> Result Imp<'a, '_, '_> { Some(a) } + /// A rebuilt item retains its ID. A cached ancestor that already points to it must + /// not be inserted underneath it, even when the resource names are not directly active. + fn cache_reaches_active(&mut self, root: ItemId) -> bool { + let active: HashSet = self.media_active.iter().filter_map(|id| self.media_items.get(id).copied()).collect(); + if active.is_empty() { + return false; + } + let mut seen = HashSet::from([root]); + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + if active.contains(&id) { + return true; + } + let Some(seq) = self.b.p.sequence(id) else { continue }; + for item in seq.all_tracks().flat_map(|track| &track.items) { + if self.cache_edges_left == 0 { + return true; + } + self.cache_edges_left -= 1; + if active.contains(&item.item) { + return true; + } + if seen.insert(item.item) { + pending.push(item.item); + } + } + } + false + } + /// Nested sequence from a `` resource. fn media(&mut self, id: &str) -> Option { - if let Some(i) = self.media_items.get(id) { - return Some(*i); - } - let n = *self.media_nodes.get(id)?; - let s = child(n, "sequence")?; - if !self.media_active.insert(id.into()) { + // Check before the cache: a truncated resource may already have an item while it + // is being rebuilt, but a back-edge must never turn that item into a self-cycle. + if self.media_active.contains(id) { self.report.warn(format!("recursive FCPXML media resource {id:?} ignored")); return None; } + let depth = self.media_active.len(); + let mut again = None; + if let Some(i) = self.media_items.get(id).copied() { + // Imported with a nested one cut off: import it again (into the same item) where that + // one now fits. + let shallower = self + .media_truncated_at + .get(id) + .is_some_and(|&(media, xml)| depth <= media && self.depth <= xml && (depth < media || self.depth < xml)) + && !self.media_active.contains(id); + if !shallower || self.reimports_left == 0 { + if self.cache_reaches_active(i) { + self.depth_hits += 1; + self.report.warn(format!( + "FCPXML cached media {id:?} could form a recursive graph or exceeds the cache traversal budget; imported as a gap" + )); + return None; + } + return Some(i); + } + self.reimports_left -= 1; + again = Some(i); + } + let n = *self.media_nodes.get(id)?; + let s = child(n, "sequence")?; + // The active set is the current nesting chain: a long acyclic chain of compound clips + // would otherwise recurse once per resource. + if depth >= MAX_MEDIA_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("FCPXML media resource {id:?} is nested too deeply; imported as a gap")); + return None; + } + self.media_active.insert(id.into()); // Mark the resource before descending: a compound clip can reference itself through a // ref-clip before a completed sequence is available to cache. let name = n.attribute("name").unwrap_or("Compound Clip").to_string(); - let item = self.sequence(s, &name, None); + let hits_before = self.depth_hits; + let item = self.sequence(s, &name, None, again); self.media_active.remove(id); self.media_items.insert(id.into(), item); + if self.depth_hits > hits_before { + self.media_truncated_at.insert(id.into(), (depth, self.depth)); + } else { + self.media_truncated_at.remove(id); + } Some(item) } - fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option) -> ItemId { + fn sequence(&mut self, s: Node<'a>, name: &str, bin: Option, reuse: Option) -> ItemId { let (rate, w, h) = s.attribute("format").and_then(|f| self.formats.get(f)).copied().unwrap_or((FrameRate::default(), 1920, 1080)); let df = s.attribute("tcFormat") == Some("DF"); let mut settings = settings_for(rate, w, h, df); if let Some(sr) = s.attribute("audioRate").and_then(parse_audio_rate) { settings.sample_rate = sr; } - let id = self.b.reserve_sequence(name, settings.clone(), bin); + let id = reuse.unwrap_or_else(|| self.b.reserve_sequence(name, settings.clone(), bin)); let mut seq = empty_sequence(settings); let tc_start = attr_time(s, "tcStart").unwrap_or(Tick::ZERO); seq.start_timecode = rate.frame_at(tc_start); @@ -353,7 +441,19 @@ impl<'a> Imp<'a, '_, '_> { /// Lay out a storyline. `origin` maps the storyline's offsets to timeline time /// (`timeline = origin + offset`). `lane` is the storyline's lane (0 = primary). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn storyline(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("XML storylines are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + return; + } + self.depth += 1; + self.storyline_inner(seq, ctx, spine, origin, lane, primary); + self.depth -= 1; + } + + fn storyline_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, spine: Node<'a>, origin: Tick, lane: i32, primary: bool) { // (timeline start, timeline end, video clip on this storyline's track) let mut laid: Vec<(Tick, Tick, Option)> = Vec::new(); let mut transitions: Vec<(usize, Node)> = Vec::new(); @@ -421,7 +521,20 @@ impl<'a> Imp<'a, '_, '_> { } /// Lay out one storyline element at timeline time `t0`. Returns (timeline end, video clip). + /// Refuses nesting past [`MAX_XML_DEPTH`]. fn element(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option) { + if self.depth >= MAX_XML_DEPTH { + self.depth_hits += 1; + self.report.warn(format!("XML elements are nested too deeply (more than {MAX_XML_DEPTH}); deeper clips were skipped")); + return (t0, None); + } + self.depth += 1; + let out = self.element_inner(seq, ctx, el, t0, lane, primary); + self.depth -= 1; + out + } + + fn element_inner(&mut self, seq: &mut Sequence, ctx: &Ctx, el: Node<'a>, t0: Tick, lane: i32, primary: bool) -> (Tick, Option) { let tag = el.name(); let dur = attr_time(el, "duration").unwrap_or(Tick::ZERO); let local_start = attr_time(el, "start").unwrap_or(Tick::ZERO); diff --git a/crates/timeline/tests/it/fcpxml.rs b/crates/timeline/tests/it/fcpxml.rs index 59baf660f1..65dc6827b2 100644 --- a/crates/timeline/tests/it/fcpxml.rs +++ b/crates/timeline/tests/it/fcpxml.rs @@ -503,3 +503,114 @@ fn relative_media_urls_are_percent_decoded() { let boats = &p.sequence(only_seq(&imp)).unwrap().video_tracks[0].items[1]; assert_eq!(media_key(p, boats.item), "/proj/media/boats b.mov"); } + +// Parity regressions from FilmCraft e6df318 (including #4799), adapted to the neutral model. +#[test] +fn media_cut_off_by_the_depth_limit_is_complete_when_reached_higher_up() { + // m0 … m64 nest one inside the next. Project A reaches m63 at the depth limit, so m64 is left + // out of it; project B refers to m63 directly, where m64 fits, and must not get the cut-off copy. + let mut media = String::new(); + for i in 0..64 { + media.push_str(&format!( + r#""#, + i + 1 + )); + } + media.push_str(r#""#); + let xml = format!( + r#"{media} + + + + "# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("nested too deeply"), "{rep:?}"); + let m63 = imp.project.items.values().find(|i| i.name == "M63").and_then(|i| imp.project.sequence(i.id)).unwrap(); + assert_eq!(m63.video_tracks[0].items.len(), 1, "M63 keeps its nested M64"); +} + +#[test] +fn media_cut_off_by_xml_layout_is_complete_when_revisited_at_the_same_media_depth() { + // Both references have media-chain depth zero, but the first is reached through connected + // clips. Its resource must not remain cached as complete after the XML-layout guard fires. + for depth in [125, 126] { + let nested = format!( + "{}{}", + "".repeat(depth), + "".repeat(depth) + ); + let xml = format!( + r#" + + + + + + + {nested} + + + + "# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("XML") && rep.mentions("nested"), "{rep:?}"); + let m0 = imp.project.items.values().find(|i| i.name == "M0").and_then(|i| imp.project.sequence(i.id)).unwrap(); + assert_eq!(m0.video_tracks[0].items.len(), 1, "M0 keeps its nested M1 after the shallower revisit"); + } +} + +#[test] +fn flat_resource_chain_is_bounded_even_when_xml_is_shallow() { + let mut media = String::new(); + for i in 0..512 { + media.push_str(&format!( + r#""#, + i + 1 + )); + } + let xml = format!( + r#"{media}"# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("nested too deeply"), "{rep:?}"); + assert!(imp.project.items.len() <= 65, "the flat resource graph is not expanded beyond the semantic limit"); +} + +#[test] +fn shallower_retry_does_not_link_a_cached_ancestor_back_to_the_rebuilt_item() { + let mut media = String::new(); + for i in 0..64 { + media.push_str(&format!( + r#""#, + (i + 1) % 64 + )); + } + let xml = format!( + r#"{media} + + "# + ); + let (imp, rep) = import(xml.as_bytes(), Format::Fcpxml, None).unwrap(); + assert!(rep.mentions("cached media"), "{rep:?}"); + // Check the final graph, not just the resource-name recursion stack during import. + fn visit(p: &Project, id: ItemId, active: &mut std::collections::HashSet, done: &mut std::collections::HashSet) { + if done.contains(&id) { + return; + } + assert!(active.insert(id), "cached media introduced a cycle at {id:?}"); + if let Some(seq) = p.sequence(id) { + for item in seq.all_tracks().flat_map(|track| &track.items) { + visit(p, item.item, active, done); + } + } + active.remove(&id); + done.insert(id); + } + let mut active = std::collections::HashSet::new(); + let mut done = std::collections::HashSet::new(); + for id in imp.project.items.keys() { + visit(&imp.project, *id, &mut active, &mut done); + } +} diff --git a/crates/ui/src/combo/tests.rs b/crates/ui/src/combo/tests.rs index 90e1afb15c..fbef2413ab 100644 --- a/crates/ui/src/combo/tests.rs +++ b/crates/ui/src/combo/tests.rs @@ -170,6 +170,7 @@ fn scene(ui: &mut egui::Ui, ours: bool) { } fn render(ours: bool, hover: Option<&str>, open: Option<&str>) -> image::RgbaImage { + let _gpu = crate::gpu_test_lock(); // Two of the combo boxes have no label: the scene compares looks, not names. let mut h = Harness::builder().with_size(egui::vec2(480.0, 700.0)).with_accessibility_check(false).build_ui(move |ui| scene(ui, ours)); h.run(); diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index e5a2d06c23..bbdd912ac2 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -27,3 +27,14 @@ pub mod text; pub mod theme; pub use combo::ComboBox; + +/// Lets one unit test at a time hold a wgpu renderer. Each renderer creates its own Vulkan instance +/// and device. When one test uses its device while a test on another thread creates or destroys +/// one, the Vulkan loader now and then crashes the test binary with SIGSEGV. Take the lock before +/// building the harness (`let _gpu = crate::gpu_test_lock();`), so it is released after the harness +/// is dropped. A test that failed while holding it does not block the others. +#[cfg(test)] +pub(crate) fn gpu_test_lock() -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/crates/ui/src/tabs/dialog.rs b/crates/ui/src/tabs/dialog.rs index 292cbb4cf2..e4820b042a 100644 --- a/crates/ui/src/tabs/dialog.rs +++ b/crates/ui/src/tabs/dialog.rs @@ -123,6 +123,7 @@ mod tests { #[test] fn selected_tab_erases_a_baseline_centered_on_its_bottom_edge() { + let _gpu = crate::gpu_test_lock(); let mut h = egui_kittest::Harness::builder().with_size(Vec2::new(120.0, 80.0)).wgpu().build_ui(|ui| { ui.painter().rect_filled(ui.max_rect(), 0.0, Color32::WHITE); let rect = Rect::from_min_size(egui::pos2(10.0, 10.0), Vec2::new(100.0, 26.0)); diff --git a/crates/ui/tests/visual_regression.rs b/crates/ui/tests/visual_regression.rs index 532c9dfc71..87edb8b4f8 100644 --- a/crates/ui/tests/visual_regression.rs +++ b/crates/ui/tests/visual_regression.rs @@ -9,6 +9,7 @@ mod fixtures; use std::path::PathBuf; +use std::sync::{Mutex, MutexGuard, PoisonError}; use egui::{Color32, Context, Event, FullOutput, Modifiers, PointerButton, Pos2, RawInput, Rect, Response, TextureId, Ui}; use egui_kittest::{TestRenderer, wgpu::WgpuTestRenderer}; @@ -28,6 +29,17 @@ struct Capture { meshes: Option>, } +/// Lets one test at a time hold a wgpu renderer. Each renderer creates its own Vulkan instance and +/// device. When one test uses its device while a test on another thread creates or destroys one, +/// the Vulkan loader now and then crashes the test binary with SIGSEGV. +static GPU_LOCK: Mutex<()> = Mutex::new(()); + +/// Take this before creating a renderer (`let _gpu = gpu_lock();`), so it is released after the +/// renderer is dropped. A test that failed while holding it does not block the others. +fn gpu_lock() -> MutexGuard<'static, ()> { + GPU_LOCK.lock().unwrap_or_else(PoisonError::into_inner) +} + fn context(theme: Theme, scale: f32) -> Context { let ctx = Context::default(); ctx.set_theme(theme.egui()); @@ -184,6 +196,7 @@ impl Artifacts { #[test] fn rendered_controls_match_independent_reference_pixels_and_meshes() { + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("controls"); let mut count = 0; @@ -213,6 +226,7 @@ fn rendered_controls_match_independent_reference_pixels_and_meshes() { #[test] fn visual_comparisons_detect_color_spacing_and_stroke_mutations() { + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("negative-controls"); let mut count = 0; @@ -241,6 +255,7 @@ fn toolbar_fitting_matches_literal_group_and_overflow_positions() { use craft_ui::layout::fit_toolbar; use egui::{Align, Layout, Stroke, StrokeKind, UiBuilder, pos2, vec2}; + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("toolbar"); let mut count = 0; @@ -295,6 +310,7 @@ fn widget_palette_renders_all_five_states_with_existing_borders_and_expansion() use craft_ui::theme::WidgetPalette; use egui::{CornerRadius, Stroke, StrokeKind, pos2, vec2}; + let _gpu = gpu_lock(); let mut renderer = WgpuTestRenderer::new(); let mut artifacts = Artifacts::new("widget-palette"); for theme in [Theme::Light, Theme::Dark] { diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index 5356db4fa0..a20f466ce1 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -157,9 +157,11 @@ const CARGO_CACHE_MARKER: &str = "CACHEDIR.TAG"; /// `build.build-dir` set, `.rustc_info.json` and those subdirectories live elsewhere and the /// profile directory has only Cargo's `.cargo-lock` file, which is accepted too. /// `CACHEDIR.TAG` alone isn't Cargo-specific (the same signature marks any cache directory), so -/// it only corroborates that profile layout. +/// it only corroborates that profile layout. Extracted nextest archives retain their +/// `nextest/binaries-metadata.json` inventory rather than Cargo cache files; those are +/// also build trees, even when the archive is unpacked outside its original target directory. fn is_development_build(exe: &Path, opted_in: bool) -> bool { - !opted_in && exe.ancestors().skip(1).any(is_cargo_build_dir) + !opted_in && exe.ancestors().skip(1).any(|dir| is_cargo_build_dir(dir) || is_nextest_binary(dir, exe)) } /// Whether `dir` is a Cargo target root (by its rustc-info cache marker) or a profile output @@ -182,6 +184,35 @@ fn is_cargo_build_dir(dir: &Path) -> bool { profile_parent.parent().is_some_and(|root| root.join(CARGO_CACHE_MARKER).is_file()) } +// An archive inventory identifies only its listed binaries, not every installation below +// its extraction directory. Bound the metadata read and refuse symlink markers. +fn is_nextest_binary(root: &Path, exe: &Path) -> bool { + use std::io::Read; + const LIMIT: u64 = 1024 * 1024; + let marker = root.join("nextest/binaries-metadata.json"); + let Ok(metadata) = std::fs::symlink_metadata(&marker) else { return false }; + if !metadata.file_type().is_file() || metadata.len() > LIMIT { + return false; + } + let Ok(file) = std::fs::File::open(&marker) else { return false }; + let mut bytes = Vec::new(); + if file.take(LIMIT + 1).read_to_end(&mut bytes).is_err() || bytes.len() as u64 > LIMIT { + return false; + } + let Ok(inventory) = serde_json::from_slice::(&bytes) else { return false }; + let Some(build) = inventory.get("rust-build-meta") else { return false }; + let Some(target) = build.get("target-directory").and_then(|v| v.as_str()) else { return false }; + let original = build.get("build-directory").and_then(|v| v.as_str()).unwrap_or(target); + let Some(binaries) = inventory.get("rust-binaries").and_then(|v| v.as_object()) else { return false }; + binaries.values().any(|binary| { + let Some(path) = binary.get("binary-path").and_then(|v| v.as_str()) else { return false }; + let Ok(relative) = Path::new(path).strip_prefix(original) else { return false }; + !relative.as_os_str().is_empty() + && relative.components().all(|part| matches!(part, std::path::Component::Normal(_))) + && root.join(relative) == exe + }) +} + /// Whether this installed copy can update itself. [`release_installs`] says whether a given /// release has a file to update it from. pub fn is_self_updating(app: &App) -> bool { @@ -3786,6 +3817,42 @@ mod tests { } } + #[test] + fn nextest_archive_binaries_do_not_update_themselves() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("relocated-artifacts"); + let exe = root.join("debug/build/artcraft-launcher-native/hash/out/artcraft_launcher_native-hash"); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, "ELF").unwrap(); + let metadata = root.join("nextest/binaries-metadata.json"); + std::fs::create_dir_all(metadata.parent().unwrap()).unwrap(); + // Names alone are not evidence of a Cargo build tree. + assert!(!is_development_build(&exe, false)); + std::fs::write(&metadata, "{}").unwrap(); + assert!(!is_development_build(&exe, false), "empty inventory is not evidence"); + let inventory = serde_json::json!({ + "rust-build-meta": {"target-directory": "/original/target"}, + "rust-binaries": {"launcher": {"binary-path": "/original/target/debug/build/artcraft-launcher-native/hash/out/artcraft_launcher_native-hash"}} + }); + std::fs::write(&metadata, inventory.to_string()).unwrap(); + assert!(is_development_build(&exe, false)); + assert_eq!(current_at(&crate::suite::LAUNCHER, &exe, false), None); + assert!(!is_development_build(&exe, true), "explicit developer opt-in remains available"); + let installed = root.join("bin/artcraft-launcher"); + assert!(!is_development_build(&installed, false), "an unlisted descendant installation is not a test binary"); + std::fs::remove_file(&metadata).unwrap(); + std::fs::create_dir(&metadata).unwrap(); + assert!(!is_development_build(&exe, false), "metadata must be a file"); + #[cfg(unix)] + { + std::fs::remove_dir(&metadata).unwrap(); + let external = dir.path().join("inventory.json"); + std::fs::write(&external, inventory.to_string()).unwrap(); + std::os::unix::fs::symlink(external, &metadata).unwrap(); + assert!(!is_development_build(&exe, false), "symlink inventory is not evidence"); + } + } + /// A Cargo build tree is not recognised by names: an installed copy in a folder literally /// called `target` stays an installed copy. #[test] diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index e5bbf1c94a..c3ebfd7221 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -52,6 +52,8 @@ vp9-encode = ["craft-media/isobmff"] av1 = ["av1-decode", "av1-encode"] av1-decode = [] av1-encode = ["craft-media/isobmff"] +# Tiled AV1 fallback for frames that exceed the clean-room encoder's single-tile limits. +av1-large-encode = ["av1-encode", "dep:rav1e"] # Decode and encode across worker threads (rayon) in the codecs that support it. threads = ["dep:rayon"] @@ -60,6 +62,9 @@ craft-media = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true, optional = true } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rav1e = { version = "0.8", default-features = false, optional = true } + [dev-dependencies] craft-media-testkit = { workspace = true } # The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test. diff --git a/crates/video/README.md b/crates/video/README.md index 74b8c64140..248e922b3b 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -21,11 +21,11 @@ No codec feature is on by default. | `dnx` | [`dnx`](src/dnx/README.md) | Avid DNxHD / DNxHR (SMPTE ST 2019-1 VC-3): decoder and encoder | | `apv` | [`apv`](src/apv/README.md) | APV (Advanced Professional Video, RFC 9924): decoder (`apv-decode` alone) and encoder (`apv-encode` alone) | | `vp8` | `vp8` | VP8 (RFC 6386): decoder | -| `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I and P pictures (`mpeg2-encode`, which also turns on the decoder) | +| `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I, P and B pictures (`mpeg2-encode`, which also turns on the decoder) | | `mpeg4` | [`mpeg4`](src/mpeg4/README.md) | MPEG-4 Part 2 video (ISO/IEC 14496-2, the Xvid/DivX format): Simple profile encoder (`mpeg4-encode`) | | `prores` | `prores` | Apple ProRes (SMPTE RDD 36): decoder and encoder | | `h264` | [`h264`](src/h264/decode/README.md) | ITU-T H.264 / AVC: decoder (`h264-decode` alone) and encoder (`h264-encode` alone) | | `hevc` | [`hevc`](src/hevc/decode/README.md) | ITU-T H.265 / HEVC: decoder (`hevc-decode` alone) and encoder (`hevc-encode` alone) | | `vp9` | [`vp9`](src/vp9/decode/README.md) | VP9: decoder (`vp9-decode` alone) and encoder (`vp9-encode` alone) | -| `av1` | [`av1`](src/av1/decode/README.md) | AV1 (AOMedia Video 1): decoder (`av1-decode` alone) and encoder (`av1-encode` alone) | +| `av1` | [`av1`](src/av1/decode/README.md) | AV1 (AOMedia Video 1): decoder (`av1-decode` alone) and clean-room encoder (`av1-encode`); tiled rav1e fallback for large frames (`av1-large-encode`) | | `threads` | — | Multi-threaded slice/row parallelism via `rayon` | diff --git a/crates/video/src/av1/encode/README.md b/crates/video/src/av1/encode/README.md index aa16047062..0fd60c50fd 100644 --- a/crates/video/src/av1/encode/README.md +++ b/crates/video/src/av1/encode/README.md @@ -3,6 +3,16 @@ Clean-room, pure-Rust AV1 encoder for MP4 / WebM export (layer L0, `std` only, no `unsafe`, builds for `wasm32-unknown-unknown`). +## Large frame fallback + +The optional `av1-large-encode` feature exposes `LargeEncoder`, a tiled rav1e-backed encoder for +8-bit 4:2:0 frames up to 8192 samples per side. Use it when the clean-room `Encoder`'s one-tile +limits (4096 samples per side and 2304 superblocks) would reject the frame. It supports constant +quantizer rate control. `push` returns packets available so far, which can be empty while frames +are buffered; `finish` returns delayed packets. Each packet includes its input frame number for +matching durations. The fallback is native only; the clean-room encoder remains available without +the feature and supports 8- and 10-bit input. + ## What is implemented - **Stream**: Main profile (`seq_profile` 0), 4:2:0, 8 or 10 bit, the configured colour description (BT.709 by default), diff --git a/crates/video/src/av1/encode/large.rs b/crates/video/src/av1/encode/large.rs new file mode 100644 index 0000000000..8ed26d52b4 --- /dev/null +++ b/crates/video/src/av1/encode/large.rs @@ -0,0 +1,269 @@ +//! Tiled AV1 encoding for frames outside the clean-room encoder's single-tile limits. + +use super::{EncoderConfig, Error, Frame, Packet, RateControl}; +use rav1e::prelude::{ + ChromaSampling, ColorDescription, ColorPrimaries, Config, Context, EncoderConfig as Rav1eConfig, FrameParameters, FrameType, FrameTypeOverride, + MatrixCoefficients, PixelRange, Rational, TransferCharacteristics, +}; + +/// Tiled AV1 encoder used when a frame is too large for [`super::Encoder`]. +pub struct LargeEncoder { + ctx: Context, + width: usize, + height: usize, + seq_header: Option>, + finished: bool, +} + +/// An encoded frame and the number of the input frame it represents. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BufferedPacket { + pub input_frame_number: u64, + pub packet: Packet, +} + +impl LargeEncoder { + /// Creates a tiled 8-bit 4:2:0 encoder for dimensions up to 8192 samples per side. + pub fn new(cfg: &EncoderConfig) -> Result { + Self::with_speed(cfg, 6) + } + + /// Creates the tiled encoder with a rav1e speed preset from 1 (slower) to 10 (faster). + pub fn with_speed(cfg: &EncoderConfig, speed: u8) -> Result { + if cfg.width < 16 || cfg.height < 16 || cfg.width > 8192 || cfg.height > 8192 { + return Err(Error::InvalidConfig("large AV1 frame dimensions must be 16..=8192".into())); + } + if cfg.bit_depth != 8 || cfg.fps_num == 0 || cfg.fps_den == 0 { + return Err(Error::InvalidConfig("large AV1 encoding requires 8-bit input and a valid frame rate".into())); + } + let RateControl::ConstantQ(quality) = cfg.rate else { + return Err(Error::InvalidConfig("large AV1 encoding currently supports constant quantizer rate control".into())); + }; + let mut ec = Rav1eConfig::with_speed_preset(speed.clamp(1, 10)); + ec.width = cfg.width as usize; + ec.height = cfg.height as usize; + ec.time_base = Rational::new(u64::from(cfg.fps_den), u64::from(cfg.fps_num)); + ec.bit_depth = 8; + ec.chroma_sampling = ChromaSampling::Cs420; + ec.pixel_range = if cfg.full_range { PixelRange::Full } else { PixelRange::Limited }; + ec.color_description = Some(ColorDescription { + color_primaries: ColorPrimaries::BT709, + transfer_characteristics: TransferCharacteristics::BT709, + matrix_coefficients: MatrixCoefficients::BT709, + }); + ec.low_latency = true; + ec.quantizer = quality.max(1) as usize; + ec.min_quantizer = ec.quantizer.min(255) as u8; + ec.min_key_frame_interval = 1; + ec.max_key_frame_interval = cfg.keyint.clamp(1, 120) as u64; + ec.tiles = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(2, 16); + let ctx = Config::new().with_encoder_config(ec).new_context().map_err(|e| Error::InvalidConfig(format!("rav1e: {e}")))?; + Ok(Self { ctx, width: cfg.width as usize, height: cfg.height as usize, seq_header: None, finished: false }) + } + + fn submit(&mut self, frame: &Frame<'_>, force_key: bool) -> Result<(), Error> { + if self.finished { + return Err(Error::InvalidFrame("AV1 encoder was already finished".into())); + } + if frame.y_stride < self.width + || frame.uv_stride < self.width / 2 + || frame.y.len() < frame.y_stride.saturating_mul(self.height) + || frame.u.len() < frame.uv_stride.saturating_mul(self.height / 2) + || frame.v.len() < frame.uv_stride.saturating_mul(self.height / 2) + { + return Err(Error::InvalidFrame("plane dimensions or strides do not match the configured frame".into())); + } + let mut input = self.ctx.new_frame(); + copy_plane(&mut input.planes[0], frame.y, frame.y_stride, self.width, self.height)?; + copy_plane(&mut input.planes[1], frame.u, frame.uv_stride, self.width / 2, self.height / 2)?; + copy_plane(&mut input.planes[2], frame.v, frame.uv_stride, self.width / 2, self.height / 2)?; + let params = + FrameParameters { frame_type_override: if force_key { FrameTypeOverride::Key } else { FrameTypeOverride::No }, ..Default::default() }; + self.ctx.send_frame((input, params)).map_err(|e| Error::InvalidFrame(format!("rav1e: {e}")))?; + Ok(()) + } + + fn packet(&mut self, packet: rav1e::prelude::Packet) -> Result { + let (data, seq) = sample_data(&packet.data)?; + if self.seq_header.is_none() { + self.seq_header = seq; + } + Ok(BufferedPacket { input_frame_number: packet.input_frameno, packet: Packet { data, keyframe: packet.frame_type == FrameType::KEY } }) + } + + fn drain(&mut self) -> Result, Error> { + let mut packets = Vec::new(); + loop { + match self.ctx.receive_packet() { + Ok(packet) => packets.push(self.packet(packet)?), + Err(rav1e::prelude::EncoderStatus::Encoded) => {} + Err(rav1e::prelude::EncoderStatus::NeedMoreData) if !self.finished => return Ok(packets), + Err(rav1e::prelude::EncoderStatus::LimitReached) if self.finished => return Ok(packets), + Err(e) => return Err(Error::InvalidFrame(format!("rav1e: {e}"))), + } + } + } + + /// Submit a frame and return all packets available now, which may be empty while the encoder + /// buffers input. Call [`Self::finish`] after the last frame to retrieve delayed packets. + pub fn push(&mut self, frame: &Frame<'_>, force_key: bool) -> Result, Error> { + self.submit(frame, force_key)?; + self.drain() + } + + /// Finish the stream and return its remaining packets. Repeated calls return no packets. + pub fn finish(&mut self) -> Result, Error> { + if !self.finished { + self.ctx.send_frame(None).map_err(|e| Error::InvalidFrame(format!("rav1e: {e}")))?; + self.finished = true; + } + self.drain() + } + + /// Encodes one frame if a packet is immediately available. The input is accepted even if + /// rav1e needs more frames and this returns an error; new callers should use [`Self::push`]. + pub fn encode_with_key(&mut self, frame: &Frame<'_>, force_key: bool) -> Result { + self.submit(frame, force_key)?; + loop { + match self.ctx.receive_packet() { + Ok(packet) => { + return Ok(self.packet(packet)?.packet); + } + Err(rav1e::prelude::EncoderStatus::Encoded) => continue, + Err(rav1e::prelude::EncoderStatus::NeedMoreData | rav1e::prelude::EncoderStatus::LimitReached) => { + return Err(Error::InvalidFrame("rav1e did not emit a low-latency frame".into())); + } + Err(e) => return Err(Error::InvalidFrame(format!("rav1e: {e}"))), + } + } + } + + /// Returns the AV1 configuration record after the first frame has been encoded. + pub fn av1c(&self) -> Option> { + self.seq_header.as_ref().map(|obu| { + let mut config = vec![0x81, 31, 0x0c, 0]; + config.extend_from_slice(obu); + config + }) + } +} + +fn copy_plane(plane: &mut rav1e::prelude::Plane, source: &[u16], stride: usize, width: usize, height: usize) -> Result<(), Error> { + let mut packed = Vec::with_capacity(width * height); + for row in 0..height { + let start = row * stride; + let pixels = &source[start..start + width]; + if pixels.iter().any(|&value| value > u8::MAX as u16) { + return Err(Error::InvalidFrame("8-bit AV1 samples must be in 0..=255".into())); + } + packed.extend(pixels.iter().map(|&value| value as u8)); + } + plane.copy_from_raw_u8(&packed, width, 1); + Ok(()) +} + +fn sample_data(data: &[u8]) -> Result<(Vec, Option>), Error> { + let mut pos = 0usize; + let mut sample = Vec::with_capacity(data.len()); + let mut sequence = None; + while pos < data.len() { + let start = pos; + let header = data[pos]; + if header & 0x80 != 0 { + return Err(Error::InvalidFrame("rav1e emitted an invalid OBU".into())); + } + let kind = (header >> 3) & 0x0f; + pos += 1 + usize::from(header & 0x04 != 0); + let end = if header & 0x02 != 0 { + let mut size = 0usize; + let mut shift = 0usize; + loop { + let byte = *data.get(pos).ok_or_else(|| Error::InvalidFrame("truncated OBU size".into()))?; + pos += 1; + size |= usize::from(byte & 0x7f).checked_shl(shift as u32).ok_or_else(|| Error::InvalidFrame("OBU size overflow".into()))?; + if byte & 0x80 == 0 { + break; + } + shift += 7; + if shift >= usize::BITS as usize { + return Err(Error::InvalidFrame("OBU size overflow".into())); + } + } + pos.checked_add(size).filter(|end| *end <= data.len()).ok_or_else(|| Error::InvalidFrame("OBU exceeds packet bounds".into()))? + } else { + data.len() + }; + if kind == 1 && sequence.is_none() { + sequence = Some(data[start..end].to_vec()); + } + if kind != 2 && kind != 15 { + sample.extend_from_slice(&data[start..end]); + } + pos = end; + } + Ok((sample, sequence)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buffered_frames_are_returned_with_input_numbers_and_finish_drains() { + let cfg = EncoderConfig::new(64, 48, 24, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + assert!(encoder.av1c().is_none()); + let y = vec![96; 64 * 48]; + let uv = vec![128; 32 * 24]; + let frame = Frame { y: &y, u: &uv, v: &uv, y_stride: 64, uv_stride: 32 }; + let mut packets = Vec::new(); + for i in 0..4 { + packets.extend(encoder.push(&frame, i == 2).unwrap()); + } + packets.extend(encoder.finish().unwrap()); + assert_eq!(packets.iter().map(|p| p.input_frame_number).collect::>(), [0, 1, 2, 3]); + assert!(packets[0].packet.keyframe); + assert!(packets[2].packet.keyframe, "requested key frame"); + assert!(encoder.av1c().is_some()); + #[cfg(feature = "av1-decode")] + { + let mut decoder = crate::av1::decode::Decoder::with_threads(1); + let mut frames = Vec::new(); + for packet in &packets { + frames.extend(decoder.decode(&packet.packet.data).unwrap()); + } + frames.extend(decoder.flush_result().unwrap()); + assert_eq!(frames.len(), 4); + assert!(frames.iter().all(|frame| (frame.width, frame.height) == (64, 48))); + } + assert!(encoder.finish().unwrap().is_empty()); + assert!(encoder.push(&frame, false).is_err()); + } + + #[test] + fn a_large_frame_can_be_flushed_even_when_the_first_push_is_buffered() { + let cfg = EncoderConfig::new(4112, 16, 30, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + let y = vec![64; 4112 * 16]; + let uv = vec![128; 2056 * 8]; + let frame = Frame { y: &y, u: &uv, v: &uv, y_stride: 4112, uv_stride: 2056 }; + let mut packets = encoder.push(&frame, false).unwrap(); + packets.extend(encoder.finish().unwrap()); + assert_eq!(packets.len(), 1); + assert_eq!(packets[0].input_frame_number, 0); + assert!(packets[0].packet.keyframe); + assert!(!packets[0].packet.data.is_empty()); + assert!(encoder.av1c().is_some()); + } + + #[test] + fn invalid_frame_is_not_queued_and_empty_stream_finishes() { + let cfg = EncoderConfig::new(64, 48, 24, 1); + let mut encoder = LargeEncoder::with_speed(&cfg, 10).unwrap(); + let short = [0; 1]; + let frame = Frame { y: &short, u: &short, v: &short, y_stride: 64, uv_stride: 32 }; + assert!(encoder.push(&frame, false).is_err()); + assert!(encoder.finish().unwrap().is_empty()); + assert!(encoder.av1c().is_none()); + } +} diff --git a/crates/video/src/av1/encode/mod.rs b/crates/video/src/av1/encode/mod.rs index 10e88d0ada..d6632a94dc 100644 --- a/crates/video/src/av1/encode/mod.rs +++ b/crates/video/src/av1/encode/mod.rs @@ -20,6 +20,11 @@ mod tables; mod transform; mod writer; +#[cfg(all(feature = "av1-large-encode", not(target_arch = "wasm32")))] +mod large; +#[cfg(all(feature = "av1-large-encode", not(target_arch = "wasm32")))] +pub use large::{BufferedPacket, LargeEncoder}; + use bitw::obu; use craft_media::bitstream::BitWriter; use craft_media::isobmff::Av1Config; diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index d9723a81da..0d8625bbd9 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -8,7 +8,7 @@ //! | `dnx` | [`dnx`] | Avid DNxHD / DNxHR (SMPTE ST 2019-1): decoder and encoder | //! | `apv` | [`apv`] | APV (RFC 9924): decoder (`apv-decode`) and encoder (`apv-encode`) | //! | `vp8` | [`vp8`] | VP8 (RFC 6386): decoder (`vp8-decode`) and key-frame encoder (`vp8-encode`) | -//! | `mpeg2` | [`mpeg2`] | MPEG-2 video (ITU-T H.262) and MPEG-1 video: decoder (`mpeg2-decode`) and MPEG-2 I/P encoder (`mpeg2-encode`) | +//! | `mpeg2` | [`mpeg2`] | MPEG-2 video (ITU-T H.262) and MPEG-1 video: decoder (`mpeg2-decode`) and MPEG-2 I/P/B encoder (`mpeg2-encode`) | //! | `mpeg4` | [`mpeg4`] | MPEG-4 Part 2 video (ISO/IEC 14496-2, Xvid/DivX): Simple profile encoder (`mpeg4-encode`) | //! | `prores` | [`prores`] | Apple ProRes (SMPTE RDD 36): decoder and encoder | //! | `h264` | [`h264`] | ITU-T H.264 / AVC: decoder (`h264-decode`) and encoder (`h264-encode`) | diff --git a/crates/video/src/mpeg2/README.md b/crates/video/src/mpeg2/README.md index b68dc800b8..069fd67bdb 100644 --- a/crates/video/src/mpeg2/README.md +++ b/crates/video/src/mpeg2/README.md @@ -1,7 +1,7 @@ # MPEG-2 and MPEG-1 video decoder, MPEG-2 encoder (`craft_video::mpeg2`, features `mpeg2-decode`, `mpeg2-encode`) -Clean-room MPEG-2 video and MPEG-1 video decoder, and the first step of an MPEG-2 video encoder -(I and P pictures, see "Encoder"), in pure Rust. Depends only on +Clean-room MPEG-2 video and MPEG-1 video decoder, and the first steps of an MPEG-2 video encoder +(I, P and B pictures, see "Encoder"), in pure Rust. Depends only on `thiserror` and (optional, feature `threads`) `rayon`. Builds for `wasm32-unknown-unknown`; no `unsafe`. No GPL/LGPL code (FFmpeg, libmpeg2, libavcodec) was consulted; FFmpeg is used only as an external fixture generator and test oracle. @@ -77,8 +77,8 @@ the synthetic-stream tests confirmed against FFmpeg: ## Encoder (feature `mpeg2-encode`) -The encoder is the first step of MPEG-2 encoding in this crate, tracked in -storytold/craft-libs#1133. It writes valid MPEG-2 elementary streams, but not yet DVD or +The encoder is built in steps, tracked in storytold/craft-libs#1133: I and P pictures came in +#1136, B pictures in the second step. It writes valid MPEG-2 elementary streams, but not yet DVD or broadcast deliverables: those need the later steps listed below. ```rust @@ -86,13 +86,15 @@ use craft_video::mpeg2::{Encoder, EncoderConfig, RateControl, YuvFrame}; let mut cfg = EncoderConfig::new(720, 576, 25, 1); cfg.rate = RateControl::Abr { kbps: 6000 }; // or RateControl::Quantiser(1..=31) -cfg.gop_size = 12; // one I picture, then P pictures +cfg.gop_size = 12; // pictures from one I picture to the next +cfg.b_pictures = 2; // I B B P B B P ...; 0 for I and P only +cfg.closed_gop = true; // or open GOPs let mut enc = Encoder::new(cfg)?; for (i, f) in frames.iter().enumerate() { let frame = YuvFrame { y: &f.y, cb: &f.cb, cr: &f.cr, y_stride: 720, c_stride: 360 }; for p in enc.encode(&frame, i as i64)? { /* p.data, p.pts, p.dts, p.keyframe, p.picture_type */ } } -for p in enc.flush() { /* none yet: no B pictures */ } +for p in enc.flush() { /* the pictures held for reordering */ } es.extend_from_slice(enc.end_of_sequence()); ``` @@ -101,9 +103,18 @@ What it does: - Main Profile (4:2:0) at Low, Main, High-1440 and High Level, and 4:2:2 Profile at Main and High Level. The lowest level that holds the size, frame rate and (average) bitrate is chosen; sizes beyond High Level are refused. Any even picture size; edges are padded by repetition. -- Progressive frame pictures, I and P, in closed GOPs. Every GOP starts with a sequence header, - sequence extension and GOP header (with a time code), so every I picture is a random access - point. Packets come out in decoding order, which equals display order without B pictures. +- Progressive frame pictures, I, P and B. Every GOP starts with a sequence header, sequence + extension and GOP header (with a time code), so every I picture is a random access point. +- B pictures (0-4 between anchors) and reordering: pictures go in in display order and packets + come out in decoding order; a B picture is held until the anchor after it is coded, and + `flush` codes the last held picture as a P picture. With B pictures, `dts` is the presentation + times in decoding order one picture interval earlier, so presentation times must step evenly. + A single picture flushed before a second one gets `dts = pts - 1`. With average bitrate, a + GOP that `flush` cuts short gives back the budget of the pictures it did not get. + `low_delay` is set only without B pictures. +- GOPs are closed or open. The B pictures shown before a GOP's I picture (coded after it) predict + backward only in a closed GOP, and from the previous GOP's last anchor too in an open one. + temporal_reference counts display order from the GOP's first picture. - Forward DCT on the transpose of the decoder's IDCT basis; intra quantisation with a small dead zone, non-intra quantisation by truncation; default or custom quantiser matrices (sequence header); linear or non-linear quantiser scale; intra DC precision 8-10 bits; @@ -112,9 +123,14 @@ What it does: predictor, the previous picture's vectors), then half-sample refinement; cost SAD + λ·bits. Each macroblock is coded intra, motion-compensated with or without residual, "no MC" with residual, or skipped. The search range sets f_code (1-4). +- B pictures: a search per direction (candidates include the P picture's vectors scaled to the + B picture's distance), then forward, backward, interpolated or the skip prediction (the + previous macroblock's directions with the predictors), whichever costs least, or intra. + Interpolated predictions are averaged in the decoder's order. - Adaptive quantisation by macroblock activity (Test Model 5 §5.2.3). -- Rate control: a constant quantiser, or single-pass average bitrate with Test Model 5's - target bit allocation at picture level. Streams are signalled as variable bitrate +- Rate control: a constant quantiser (B pictures at 1.25 times it), or single-pass average + bitrate with Test Model 5's target bit allocation at picture level (B pictures weighted by + K_b = 1.4). Streams are signalled as variable bitrate (`vbv_delay` 0xFFFF, the level's maximum bitrate and VBV size in the sequence header); the VBV buffer is not modelled. - The reconstruction uses the decoder's own dequantisation, mismatch control, IDCT and motion @@ -122,7 +138,7 @@ What it does: - Slices (one per macroblock row) are coded in parallel on rayon with `threads`; the stream is identical either way. -Later steps (#1133): B pictures and reordering; CBR and VBR with a VBV guarantee; DVD presets +Later steps (#1133): CBR and VBR with a VBV guarantee; DVD presets (sizes, aspect, GOP length, 9.8 Mb/s, 23.976 soft telecine); interlaced coding (field/frame DCT, field prediction, alternate scan) and 4:2:2 High Level CBR for XDCAM HD422. MPEG-2 essence in the MXF writer and a program stream muxer belong to `craft-media`. @@ -191,9 +207,15 @@ fell to 77–150 fps). These are lower bounds. rate control converges on its target. `encode/tests.rs`: our decoder outputs exactly the encoder's reconstruction (intra only, a 30-picture P GOP, 4:2:2, linear and non-linear quantisers, quantisers 1 and 31, DC precision 8 and 10, custom matrices, odd macroblock counts, - average bitrate); quality and size follow the quantiser; repeated pictures skip; levels and - aspect in the sequence header; bad configurations and short or inconsistent planes are refused. -- `tests/mpeg2/encode.rs`: FFmpeg decodes our streams of `testsrc2` (CIF and 576-line 4:2:2) - without errors and within the decoder suite's tolerance of our reconstruction, ffprobe reports - the profile, level, pixel format and I/P picture types, and average bitrate lands within 10 % of - 800 and 2500 kbit/s targets. + average bitrate, each with and without B pictures; 1-4 B pictures with closed and open GOPs, + GOP lengths that are and are not multiples of the anchor distance, and streams that end inside + a group of B pictures); decoding order, decoding times and temporal_reference; a closed GOP + decodes from its I picture with its leading B pictures and an open one without them; B pictures + are smaller than P pictures; uneven presentation times are refused with B pictures; quality and + size follow the quantiser; repeated pictures skip; levels and aspect in the sequence header; + bad configurations and short or inconsistent planes are refused. +- `tests/mpeg2/encode.rs`: FFmpeg decodes our streams of `testsrc2` (CIF and 576-line 4:2:2; + without B pictures, with 2 and 4, closed and open GOPs) without errors and within the decoder + suite's tolerance of our reconstruction, ffprobe reports the profile, level, pixel format and + picture types in display order, and average bitrate lands within 10 % of 800 and 2500 kbit/s + targets. diff --git a/crates/video/src/mpeg2/encode/mod.rs b/crates/video/src/mpeg2/encode/mod.rs index fcd1bd8d1b..af32b271da 100644 --- a/crates/video/src/mpeg2/encode/mod.rs +++ b/crates/video/src/mpeg2/encode/mod.rs @@ -1,9 +1,9 @@ //! MPEG-2 video encoder (ITU-T H.262 | ISO/IEC 13818-2), feature `mpeg2-encode`. //! -//! This is the first step of MPEG-2 encoding in this crate (storytold/craft-libs#1133): I and P -//! pictures, progressive frame pictures, 4:2:0 (Main Profile) and 4:2:2 (4:2:2 Profile), closed -//! GOPs, constant quantiser or single-pass average bitrate. B pictures, a VBV guarantee, -//! interlaced coding and DVD / broadcast presets come later. +//! MPEG-2 encoding in this crate is built in steps (storytold/craft-libs#1133). So far: I, P and B +//! pictures, progressive frame pictures, 4:2:0 (Main Profile) and 4:2:2 (4:2:2 Profile), closed or +//! open GOPs, constant quantiser or single-pass average bitrate. A VBV guarantee, interlaced +//! coding and DVD / broadcast presets come later. //! //! ```no_run //! use craft_video::mpeg2::encode::{Encoder, EncoderConfig, RateControl, YuvFrame}; @@ -36,6 +36,8 @@ mod transform; #[cfg(test)] mod tests; +use std::collections::VecDeque; + use crate::mpeg2::ChromaFormat; use crate::mpeg2::headers::{DEFAULT_INTRA, PictureType, SCAN}; use crate::mpeg2::mc::Frame; @@ -50,6 +52,10 @@ pub enum EncodeError { Config(String), #[error("bad input frame: {0}")] BadFrame(String), + /// With B pictures, presentation times must increase by a constant step (the decoding times + /// are the presentation times one step earlier). + #[error("bad presentation time: {0}")] + BadTimestamp(String), } /// aspect_ratio_information (H.262 Table 6-3). @@ -97,8 +103,15 @@ pub struct EncoderConfig { /// 4:2:0 (Main Profile) or 4:2:2 (4:2:2 Profile). pub chroma: ChromaFormat, pub aspect: AspectRatio, - /// Pictures per GOP: one I picture, then P pictures. 1 codes every picture as I. 1..=1023. + /// Pictures from one I picture to the next (display order). 1 codes every picture as I. + /// 1..=1023, and at most 1024 with `b_pictures` added. pub gop_size: u32, + /// B pictures between two anchor (I or P) pictures, 0..=4. 0 gives I and P pictures only and a + /// low-delay stream (no reordering). + pub b_pictures: u32, + /// Closed GOPs: the B pictures shown before a GOP's I picture predict from it alone, so the + /// GOP decodes on its own. Open GOPs let them predict from the previous GOP too. + pub closed_gop: bool, pub rate: RateControl, /// q_scale_type: the non-linear quantiser scale (finer steps at low quantisers). pub nonlinear_quant: bool, @@ -125,6 +138,8 @@ impl EncoderConfig { chroma: ChromaFormat::Yuv420, aspect: AspectRatio::Square, gop_size: 12, + b_pictures: 2, + closed_gop: true, rate: RateControl::Quantiser(4), nonlinear_quant: true, adaptive_quant: true, @@ -155,9 +170,12 @@ pub struct Packet { /// the picture. pub data: Vec, pub pts: i64, - /// Decoding timestamp; equal to `pts` while there are no B pictures. + /// Decoding timestamp: `pts` without B pictures; with them, the presentation times in + /// decoding order one picture interval earlier, so `dts <= pts`. A stream of one picture has + /// no interval: its `dts` is `pts - 1`. pub dts: i64, - /// An I picture starting a closed GOP (random access point). + /// An I picture (random access point; in an open GOP the B pictures after it in decoding + /// order also need the previous GOP). pub keyframe: bool, pub picture_type: PictureType, /// Average quantiser_scale of the picture's macroblocks. @@ -260,6 +278,13 @@ fn validate(cfg: &EncoderConfig) -> Result<(), EncodeError> { if !(1..=1023).contains(&cfg.gop_size) { return bad(format!("GOP size {} (1..=1023)", cfg.gop_size)); } + if cfg.b_pictures > 4 { + return bad(format!("{} B pictures between anchors (0..=4)", cfg.b_pictures)); + } + // temporal_reference (10 bits) counts a GOP's leading B pictures too + if cfg.gop_size + cfg.b_pictures > 1024 { + return bad(format!("GOP size {} with {} B pictures: more than 1024 pictures to number", cfg.gop_size, cfg.b_pictures)); + } match cfg.rate { RateControl::Quantiser(q) if !(1..=31).contains(&q) => return bad(format!("quantiser_scale_code {q} (1..=31)")), RateControl::Abr { kbps: 0 } => return bad("bitrate 0".into()), @@ -284,6 +309,26 @@ fn put_matrix(w: &mut BitWriter, m: &[u8; 64]) { } } +/// A source picture waiting for the anchor after it (a B picture). +struct Held { + src: Frame, + pts: i64, + /// Display index. + n: u64, +} + +/// A coded picture before rate control and timestamps. +struct Coded { + packet: Packet, + recon: Frame, + mvs: Vec<[i32; 2]>, + avg_q: f64, +} + +/// Quantiser ratio of B to P pictures with a constant quantiser (TM5 uses 1.4 for its rate +/// allocation; a constant quantiser keeps B pictures a little closer to the anchors). +const B_QUANT_FACTOR: f64 = 1.25; + /// A stateful encoder. Feed pictures in display order; packets come out in decoding order. pub struct Encoder { cfg: EncoderConfig, @@ -297,16 +342,32 @@ pub struct Encoder { inter_matrix: [u8; 64], /// Sequence header and sequence extension, sent before every GOP. seq_header: Vec, - /// The reconstruction of the previous picture. - reference: Option, - prev_mvs: Vec<[i32; 2]>, - /// Pictures coded so far. + /// The reconstructions of the last two anchor pictures and their display indices: `latest` + /// is the backward reference of the B pictures held, and the forward reference of the next + /// P picture. + older: Option<(Frame, u64)>, + latest: Option<(Frame, u64)>, + /// Forward vectors of the latest anchor when it is a P picture (search candidates). + anchor_mvs: Vec<[i32; 2]>, + /// B pictures waiting for their backward reference. + held: Vec, + /// Display index of the next picture. count: u64, - /// Position of the next picture in its GOP. - gop_pos: u32, + /// Display indices of the current GOP's I picture and of its first picture in display order + /// (a leading B picture in front of the I picture, or the I picture). + gop_start: u64, + gop_first: u64, + /// The current GOP is closed: its leading B pictures predict backward only. + gop_closed: bool, + /// Presentation times not yet given to a coded picture as its decoding time, in input order. + display_pts: VecDeque, + last_pts: Option, + pts_step: Option, + /// Packets waiting for the presentation time step (the decoding time offset). + out: Vec, rc: Option, recon_capture: bool, - recon: Vec, + recon: Vec<(u64, ReconFrame)>, } impl Encoder { @@ -330,10 +391,18 @@ impl Encoder { intra_matrix: cfg.intra_matrix.unwrap_or(DEFAULT_INTRA), inter_matrix: cfg.non_intra_matrix.unwrap_or([16; 64]), seq_header: Vec::new(), - reference: None, - prev_mvs: Vec::new(), + older: None, + latest: None, + anchor_mvs: Vec::new(), + held: Vec::new(), count: 0, - gop_pos: 0, + gop_start: 0, + gop_first: 0, + gop_closed: true, + display_pts: VecDeque::new(), + last_pts: None, + pts_step: None, + out: Vec::new(), rc, recon_capture: false, recon: Vec::new(), @@ -367,13 +436,32 @@ impl Encoder { self.recon_capture = on; } + /// The reconstructions captured so far, in display order. pub fn take_recon(&mut self) -> Vec { - std::mem::take(&mut self.recon) + let mut r = std::mem::take(&mut self.recon); + r.sort_by_key(|(n, _)| *n); + r.into_iter().map(|(_, f)| f).collect() } - /// Pictures held for reordering (none yet: there are no B pictures). + /// Code the pictures held for reordering (the last of them becomes a P picture) and return + /// every packet not yet returned. The next picture starts a new GOP. pub fn flush(&mut self) -> Vec { - Vec::new() + let mut out = Vec::new(); + if let Some(last) = self.held.pop() { + self.code_anchor(last, PictureType::P, &mut out); + } + // the GOP ends here: its budget covered `gop_size` pictures, so take back the share of + // those that never came, or every flushed GOP would raise the bitrate of the next + if self.latest.is_some() { + let missing = u64::from(self.cfg.gop_size).saturating_sub(self.count - self.gop_start); + if let Some(rc) = self.rc.as_mut() { + rc.end_gop(missing as u32); + } + } + self.older = None; + self.latest = None; + self.anchor_mvs.clear(); + self.release(out, true) } fn sequence_header_bytes(&self) -> Vec { @@ -406,16 +494,15 @@ impl Encoder { w.put((bit_rate >> 18) as u32 & 0xFFF, 12); w.bit(true); // marker_bit w.put((vbv >> 10) as u32 & 0xFF, 8); - w.bit(true); // low_delay: no B pictures + w.bit(c.b_pictures == 0); // low_delay: no B pictures, no reordering w.put(0, 2); // frame_rate_extension_n w.put(0, 5); // frame_rate_extension_d w.finish() } - /// group_of_pictures_header with the time code of picture `self.count`. - fn gop_header(&self, w: &mut BitWriter) { + /// group_of_pictures_header with the time code of display picture `n`. + fn gop_header(&self, w: &mut BitWriter, n: u64, closed: bool) { let fps = u64::from(self.cfg.fps_num.div_ceil(self.cfg.fps_den)).max(1); - let n = self.count; let secs = n / fps; w.start_code(0xB8); w.bit(false); // drop_frame_flag @@ -424,24 +511,40 @@ impl Encoder { w.bit(true); // marker_bit w.put((secs % 60) as u32, 6); w.put((n % fps) as u32, 6); - w.bit(true); // closed_gop + w.bit(closed); // closed_gop w.bit(false); // broken_link } - fn picture_header(&self, w: &mut BitWriter, intra: bool) { + fn picture_header(&self, w: &mut BitWriter, ptype: PictureType, temporal_reference: u64) { w.start_code(0x00); - w.put(self.gop_pos & 0x3FF, 10); // temporal_reference: display order within the GOP - w.put(if intra { 1 } else { 2 }, 3); + w.put((temporal_reference & 0x3FF) as u32, 10); // display order within the GOP + w.put( + match ptype { + PictureType::P => 2, + PictureType::B => 3, + _ => 1, + }, + 3, + ); w.put(0xFFFF, 16); // vbv_delay: variable bitrate - if !intra { - w.bit(false); // full_pel_forward_vector - w.put(7, 3); // forward_f_code (MPEG-2: in the extension) + for dir in [PictureType::P, PictureType::B] { + if ptype == dir || ptype == PictureType::B { + // full_pel_{forward,backward}_vector and {forward,backward}_f_code: MPEG-2 + // carries them in the extension + w.bit(false); + w.put(7, 3); + } } w.bit(false); // extra_bit_picture w.start_code(0xB5); w.put(8, 4); // picture coding extension - let fc = if intra { 15 } else { u32::from(self.f_code) }; - for v in [fc, fc, 15, 15] { + let fc = u32::from(self.f_code); + let f_codes = match ptype { + PictureType::P => [fc, fc, 15, 15], + PictureType::B => [fc; 4], + _ => [15; 4], + }; + for v in f_codes { w.put(v, 4); } w.put(u32::from(self.cfg.intra_dc_bits - 8), 2); @@ -502,28 +605,113 @@ impl Encoder { acts.iter().map(|&a| qcode_for(nl, base * (2.0 * a + avg) / (a + 2.0 * avg))).collect() } - /// Encode one picture. Returns the packets that became ready (one per picture for now). + /// With B pictures, presentation times must step by a constant amount, and the decoding + /// times (one step earlier) must fit in an `i64`. Checked before any state changes. + fn check_pts(&self, pts: i64) -> Result, EncodeError> { + if self.cfg.b_pictures == 0 { + return Ok(None); + } + let no_dts = |pts: i64, step: i64| EncodeError::BadTimestamp(format!("{pts}: no decoding time {step} earlier")); + let Some(last) = self.last_pts else { + // flushed before a second picture, this one decodes at `pts - 1` (see `release`) + return if pts == i64::MIN { Err(no_dts(pts, 1)) } else { Ok(None) }; + }; + let step = pts.checked_sub(last).filter(|&d| d > 0).ok_or_else(|| EncodeError::BadTimestamp(format!("{pts} after {last}")))?; + match self.pts_step { + Some(s) if s != step => Err(EncodeError::BadTimestamp(format!("{pts} after {last}: step {step}, earlier {s}"))), + // the earliest decoding time is the earlier picture's time less the step + None if last.checked_sub(step).is_none() => Err(no_dts(last, step)), + _ => Ok(Some(step)), + } + } + + /// Encode one picture (display order). Returns the packets that became ready, in decoding + /// order: with B pictures, a B picture is held until the anchor after it is coded. pub fn encode(&mut self, frame: &YuvFrame, pts: i64) -> Result, EncodeError> { let src = self.load(frame)?; - let reference = if self.gop_pos == 0 { None } else { self.reference.take() }; - let intra = reference.is_none(); + if let Some(step) = self.check_pts(pts)? { + self.pts_step = Some(step); + } + self.last_pts = Some(pts); + let n = self.count; + self.count += 1; + self.display_pts.push_back(pts); + let held = Held { src, pts, n }; + let mut out = Vec::new(); + let m = u64::from(self.cfg.b_pictures) + 1; + if self.latest.is_none() || n - self.gop_start >= u64::from(self.cfg.gop_size) { + self.code_anchor(held, PictureType::I, &mut out); + } else if (n - self.gop_start).is_multiple_of(m) { + self.code_anchor(held, PictureType::P, &mut out); + } else { + self.held.push(held); + } + Ok(self.release(out, false)) + } + + /// Code an anchor picture, then the B pictures held in front of it. + fn code_anchor(&mut self, h: Held, ptype: PictureType, out: &mut Vec) { + let intra = ptype == PictureType::I; if intra { - self.gop_pos = 0; + self.gop_start = h.n; + self.gop_first = self.held.first().map_or(h.n, |b| b.n); + self.gop_closed = self.cfg.closed_gop || self.held.is_empty(); + let n = u64::from(self.cfg.gop_size); + let m = u64::from(self.cfg.b_pictures) + 1; + let np = (n - 1) / m; if let Some(rc) = self.rc.as_mut() { - rc.start_gop(self.cfg.gop_size); + rc.start_gop(np as u32, (n - 1 - np) as u32); } } + let fwd = if intra { None } else { self.latest.as_ref().map(|r| &r.0) }; + let cand: &[[i32; 2]] = if intra { &[] } else { &self.anchor_mvs }; + let c = self.code_picture(&h, ptype, (fwd, None), [cand, &[]]); + let (recon, mvs) = self.finish(c, h.n, out); + self.older = self.latest.take(); + self.latest = Some((recon, h.n)); + self.anchor_mvs = if intra { Vec::new() } else { mvs }; + for b in std::mem::take(&mut self.held) { + self.code_b(b, out); + } + } + + /// Code a B picture between the two latest anchors. The leading B pictures of a closed GOP + /// (shown before its I picture) predict backward only. + fn code_b(&mut self, b: Held, out: &mut Vec) { + let Some((bwd, bn)) = self.latest.as_ref() else { return }; + let leading = b.n < self.gop_start; + let fwd = self.older.as_ref().filter(|_| !(leading && self.gop_closed)); + // search candidates: the latest anchor's vectors (which span the two anchors) scaled to + // this picture's distance from each + let span = self.older.as_ref().map_or(1, |o| bn.saturating_sub(o.1).max(1)) as i64; + let scaled = |d: i64| -> Vec<[i32; 2]> { + self.anchor_mvs.iter().map(|v| [(i64::from(v[0]) * d / span) as i32, (i64::from(v[1]) * d / span) as i32]).collect() + }; + let cf = fwd.map_or(Vec::new(), |f| scaled(b.n as i64 - f.1 as i64)); + let cb = scaled(b.n as i64 - *bn as i64); + let c = self.code_picture(&b, PictureType::B, (fwd.map(|f| &f.0), Some(bwd)), [&cf, &cb]); + self.finish(c, b.n, out); + } + + /// Code one picture with the given references and search candidates. + fn code_picture(&self, h: &Held, ptype: PictureType, (fwd, bwd): (Option<&Frame>, Option<&Frame>), cand: [&[[i32; 2]]; 2]) -> Coded { let base = match (&self.rc, self.cfg.rate) { - (Some(rc), _) => rc.qscale(intra), - (None, RateControl::Quantiser(q)) => f64::from(qscale(self.cfg.nonlinear_quant, q)), + (Some(rc), _) => rc.qscale(ptype), + (None, RateControl::Quantiser(q)) => { + let qs = f64::from(qscale(self.cfg.nonlinear_quant, q)); + if ptype == PictureType::B { qs * B_QUANT_FACTOR } else { qs } + } (None, _) => 8.0, }; - let mb_qcode = self.mb_quant(&src, base); + let src = &h.src; + let mb_qcode = self.mb_quant(src, base); let mut recon = Frame::new(src.w, src.h, src.cw, src.ch); let ctx = PicCtx { - src: &src, - reference: reference.as_ref(), - prev_mvs: &self.prev_mvs, + ptype, + src, + fwd, + bwd, + cand, mb_w: self.mb_w, shx: self.shx, shy: self.shy, @@ -536,11 +724,12 @@ impl Encoder { mb_qcode: &mb_qcode, }; let rows = encode_rows(&ctx, &mut recon, self.cfg.threads); + let intra = ptype == PictureType::I; let mut w = BitWriter::new(); if intra { - self.gop_header(&mut w); + self.gop_header(&mut w, self.gop_first, self.gop_closed); } - self.picture_header(&mut w, intra); + self.picture_header(&mut w, ptype, h.n - self.gop_first); let mut data = if intra { self.seq_header.clone() } else { Vec::new() }; data.extend_from_slice(&w.finish()); let mut qsum = 0u64; @@ -551,18 +740,47 @@ impl Encoder { mvs.extend_from_slice(&r.mvs); } let avg_q = qsum as f64 / (self.mb_w * self.mb_h).max(1) as f64; + let packet = Packet { data, pts: h.pts, dts: h.pts, keyframe: intra, picture_type: ptype, quantiser_scale: avg_q as f32 }; + Coded { packet, recon, mvs, avg_q } + } + + /// Account for a coded picture (display index `n`): rate control, its decoding time, the + /// reconstruction capture. Returns the reconstruction and the picture's vectors. + fn finish(&mut self, c: Coded, n: u64, out: &mut Vec) -> (Frame, Vec<[i32; 2]>) { + let Coded { mut packet, recon, mvs, avg_q } = c; if let Some(rc) = self.rc.as_mut() { - rc.update(intra, data.len() as u64 * 8, avg_q); + rc.update(packet.picture_type, packet.data.len() as u64 * 8, avg_q); } + // the k-th coded picture decodes at the k-th presentation time (less the offset that + // `release` subtracts); one time is queued per input picture + packet.dts = self.display_pts.pop_front().unwrap_or(packet.pts); if self.recon_capture { - self.recon.push(self.crop(&recon)); + self.recon.push((n, self.crop(&recon))); } - self.reference = Some(recon); - self.prev_mvs = mvs; - self.count += 1; - self.gop_pos = (self.gop_pos + 1) % self.cfg.gop_size; - let picture_type = if intra { PictureType::I } else { PictureType::P }; - Ok(vec![Packet { data, pts, dts: pts, keyframe: intra, picture_type, quantiser_scale: avg_q as f32 }]) + out.push(packet); + (recon, mvs) + } + + /// Hand out packets once their decoding times are known: with B pictures they are the + /// presentation times one step earlier, so packets wait for the second picture's time. + fn release(&mut self, out: Vec, flushing: bool) -> Vec { + self.out.extend(out); + if self.cfg.b_pictures == 0 { + return std::mem::take(&mut self.out); + } + if self.pts_step.is_none() && !flushing { + return Vec::new(); + } + // A lone picture flushed before a second one set the step decodes one unit early, the + // smallest step there is: if encoding goes on, the next picture decodes at this one's + // presentation time whatever the step turns out to be, and that must be later. + let off = self.pts_step.unwrap_or(1); + let mut res = std::mem::take(&mut self.out); + for p in &mut res { + // `check_pts` refused the times this would not fit for + p.dts = p.dts.saturating_sub(off); + } + res } fn crop(&self, f: &Frame) -> ReconFrame { diff --git a/crates/video/src/mpeg2/encode/motion.rs b/crates/video/src/mpeg2/encode/motion.rs index a7bedc80be..8242faafe3 100644 --- a/crates/video/src/mpeg2/encode/motion.rs +++ b/crates/video/src/mpeg2/encode/motion.rs @@ -47,7 +47,7 @@ impl Search<'_> { } /// A half-sample vector the bitstream can carry whose prediction stays inside the reference. - fn valid(&self, mv: [i32; 2]) -> bool { + pub(crate) fn valid(&self, mv: [i32; 2]) -> bool { let f = 1i32 << self.f_code.saturating_sub(1); let (ox, oy) = self.origin(); let size = [self.reference.w as i32, self.reference.h as i32]; @@ -58,7 +58,8 @@ impl Search<'_> { }) } - fn mv_cost(&self, mv: [i32; 2]) -> u32 { + /// λ·(bits of `mv` against the predictor). + pub(crate) fn mv_cost(&self, mv: [i32; 2]) -> u32 { let t = enc_tables(); let bits: u32 = (0..2).map(|c| t.motion_bits(wrap_delta(mv[c], self.pmv[c], self.f_code), self.f_code)).sum(); self.lambda * bits diff --git a/crates/video/src/mpeg2/encode/picture.rs b/crates/video/src/mpeg2/encode/picture.rs index e7bb84b7e5..0be5dbafd5 100644 --- a/crates/video/src/mpeg2/encode/picture.rs +++ b/crates/video/src/mpeg2/encode/picture.rs @@ -1,11 +1,11 @@ //! Slices and macroblocks of one frame picture (H.262 §6.2.4-§6.2.6), with a reconstruction //! that matches the decoder exactly. One slice per macroblock row; slices only depend on the -//! reference picture, so rows can be coded in parallel. +//! reference pictures, so rows can be coded in parallel. -use crate::mpeg2::headers::SCAN; +use crate::mpeg2::headers::{PictureType, SCAN}; use crate::mpeg2::mc::{Block, Frame, predict}; use crate::mpeg2::slice::NON_LINEAR_Q; -use crate::mpeg2::vlc::{MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT}; +use crate::mpeg2::vlc::{MB_BWD, MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT}; use super::bitwriter::BitWriter; use super::motion::Search; @@ -35,12 +35,17 @@ pub(crate) fn qcode_for(nonlinear: bool, qs: f64) -> u8 { /// What every slice of one picture shares (read-only). pub(crate) struct PicCtx<'a> { + /// I, P or B. + pub ptype: PictureType, /// The padded source picture. pub src: &'a Frame, - /// The reconstructed previous picture (P pictures); `None` codes an I picture. - pub reference: Option<&'a Frame>, - /// Vectors of the previous picture (motion search candidates), one per macroblock. - pub prev_mvs: &'a [[i32; 2]], + /// The reconstructed reference pictures: forward (P and B pictures) and backward (B + /// pictures). A B picture without a forward reference (the leading B pictures of a closed + /// GOP) predicts backward only. + pub fwd: Option<&'a Frame>, + pub bwd: Option<&'a Frame>, + /// Motion search candidates per macroblock, forward and backward (empty: none). + pub cand: [&'a [[i32; 2]]; 2], pub mb_w: usize, pub shx: u32, pub shy: u32, @@ -166,11 +171,22 @@ impl MbPix { struct SliceSt { qcode: u8, dc: [i32; 3], - pmv: [i32; 2], + /// Motion vector predictors, forward and backward. + pmv: [[i32; 2]; 2], /// Skipped macroblocks not yet covered by an address increment. skipped: usize, - /// The vector of the macroblock to the left (motion search candidate). - left_mv: [i32; 2], + /// The vectors of the macroblock to the left (motion search candidates). + left_mv: [[i32; 2]; 2], + /// Prediction directions (`MB_FWD` / `MB_BWD`) of the previous macroblock, or `MB_INTRA`: + /// a skipped macroblock in a B picture repeats them. + last_dirs: i16, +} + +/// A B macroblock's prediction: its directions and a vector per direction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct BPred { + dirs: i16, + mvs: [[i32; 2]; 2], } /// One macroblock being coded. @@ -188,7 +204,7 @@ pub(crate) fn encode_row(ctx: &PicCtx, row: usize, out: &mut RowPlanes) -> RowOu let q0 = ctx.mb_qcode.get(row * ctx.mb_w).copied().unwrap_or(1); w.put(u32::from(q0), 5); w.bit(false); // extra_bit_slice - let mut st = SliceSt { qcode: q0, dc: [ctx.dc_reset(); 3], pmv: [0; 2], skipped: 0, left_mv: [0; 2] }; + let mut st = SliceSt { qcode: q0, dc: [ctx.dc_reset(); 3], pmv: [[0; 2]; 2], skipped: 0, left_mv: [[0; 2]; 2], last_dirs: MB_INTRA }; let mut ro = RowOut { bytes: Vec::new(), mvs: vec![[0; 2]; ctx.mb_w], stats: RowStats::default() }; for mbx in 0..ctx.mb_w { macroblock(ctx, &mut st, &mut w, (mbx, row), out, &mut ro); @@ -205,31 +221,105 @@ fn macroblock(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, (mbx, mby): (us let qs = qscale(ctx.nonlinear, qcode); ro.stats.qsum += qs as u64; let planes = (ctx.src.w, ctx.src.cw); - let Some(reference) = ctx.reference else { - intra_mb(ctx, st, w, &mb).put(out, mbx, ctx.cmb(), planes); - ro.stats.intra += 1; - return; + let lambda = ((qs * 3 + 4) / 8).max(1) as u32; + let rec = match (ctx.ptype, ctx.fwd) { + (PictureType::P, Some(reference)) => { + let search = Search { reference, src: &src.y, mbx, mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[0], lambda }; + let found = search.run(&candidates(ctx, st, addr, 0)); + if intra_cost(&src.y).saturating_add(INTRA_BIAS) < found.sad { + None + } else { + let (rec, skipped) = inter_mb(ctx, st, w, &mb, reference, found.mv); + ro.stats.skipped += skipped as u32; + ro.mvs[mbx] = found.mv; + st.left_mv[0] = found.mv; + Some(rec) + } + } + (PictureType::B, _) if ctx.bwd.is_some() => b_decision(ctx, st, &mb, lambda).map(|pred| { + let (rec, skipped) = b_mb(ctx, st, w, &mb, pred); + ro.stats.skipped += skipped as u32; + st.left_mv = pred.mvs; + rec + }), + _ => None, }; - let mut candidates = vec![st.left_mv, st.pmv]; + let rec = rec.unwrap_or_else(|| { + ro.stats.intra += 1; + st.left_mv = [[0; 2]; 2]; + intra_mb(ctx, st, w, &mb) + }); + rec.put(out, mbx, ctx.cmb(), planes); +} + +/// Motion search candidates for direction `s` of macroblock `addr`: the left neighbour's vector, +/// the predictor, and the co-located and neighbouring candidates of the picture. +fn candidates(ctx: &PicCtx, st: &SliceSt, addr: usize, s: usize) -> Vec<[i32; 2]> { + let mut c = vec![st.left_mv[s], st.pmv[s]]; for a in [Some(addr), addr.checked_sub(ctx.mb_w), Some(addr + 1), Some(addr + ctx.mb_w)].into_iter().flatten() { - if let Some(&v) = ctx.prev_mvs.get(a) { - candidates.push(v); + if let Some(&v) = ctx.cand[s].get(a) { + c.push(v); } } - let lambda = ((qs * 3 + 4) / 8).max(1) as u32; - let search = Search { reference, src: &src.y, mbx, mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv, lambda }; - let found = search.run(&candidates); - if intra_cost(&src.y).saturating_add(INTRA_BIAS) < found.sad { - intra_mb(ctx, st, w, &mb).put(out, mbx, ctx.cmb(), planes); - ro.stats.intra += 1; - st.left_mv = [0; 2]; - return; + c +} + +/// Luma SAD of a prediction against the source. +fn sad(a: &[u8; 256], b: &[u8; 256]) -> u32 { + a.iter().zip(b).map(|(x, y)| u32::from(x.abs_diff(*y))).sum() +} + +/// Choose a B macroblock's prediction: forward, backward or interpolated, from a motion search +/// per direction, or the skip prediction (the previous macroblock's directions with the +/// predictors). `None`: code it intra. +fn b_decision(ctx: &PicCtx, st: &SliceSt, mb: &MbIn, lambda: u32) -> Option { + let addr = mb.mby * ctx.mb_w + mb.mbx; + let mut found = [None, None]; + for (s, r) in [ctx.fwd, ctx.bwd].into_iter().enumerate() { + if let Some(reference) = r { + let search = + Search { reference, src: &mb.src.y, mbx: mb.mbx, mby: mb.mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[s], lambda }; + let f = search.run(&candidates(ctx, st, addr, s)); + found[s] = Some((f.mv, f.sad, search.mv_cost(f.mv))); + } } - let (rec, skipped) = inter_mb(ctx, st, w, &mb, reference, found.mv); - rec.put(out, mbx, ctx.cmb(), planes); - ro.stats.skipped += skipped as u32; - ro.mvs[mbx] = found.mv; - st.left_mv = found.mv; + let mut best: Option<(BPred, u32)> = None; + let mut consider = |pred: BPred, cost: u32| { + if best.is_none_or(|(_, c)| cost < c) { + best = Some((pred, cost)); + } + }; + for (s, dir) in [(0, MB_FWD), (1, MB_BWD)] { + if let Some((mv, sad, bits)) = found[s] { + let mut mvs = [[0; 2]; 2]; + mvs[s] = mv; + consider(BPred { dirs: dir, mvs }, sad.saturating_add(bits)); + } + } + if let (Some((f, _, bits_f)), Some((b, _, bits_b))) = (found[0], found[1]) { + let pred = BPred { dirs: MB_FWD | MB_BWD, mvs: [f, b] }; + let p = predict_b(ctx, pred, mb.mbx, mb.mby); + consider(pred, sad(&p.y, &mb.src.y).saturating_add(bits_f).saturating_add(bits_b)); + } + // the skip prediction costs no vector bits; the predictors came from the macroblock to the + // left, so they must be checked to stay inside the reference from here + let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; + if !edge && st.last_dirs & MB_INTRA == 0 && st.last_dirs != 0 { + let pred = BPred { dirs: st.last_dirs, mvs: st.pmv }; + let usable = [(0, MB_FWD, ctx.fwd), (1, MB_BWD, ctx.bwd)].into_iter().all(|(s, dir, r)| { + st.last_dirs & dir == 0 + || r.is_some_and(|reference| { + let search = + Search { reference, src: &mb.src.y, mbx: mb.mbx, mby: mb.mby, f_code: ctx.f_code, range: ctx.search, pmv: st.pmv[s], lambda }; + search.valid(st.pmv[s]) + }) + }); + if usable { + consider(pred, sad(&predict_b(ctx, pred, mb.mbx, mb.mby).y, &mb.src.y)); + } + } + let (pred, cost) = best?; + (intra_cost(&mb.src.y).saturating_add(INTRA_BIAS) >= cost).then_some(pred) } /// Σ |sample − block mean| over the four luma blocks: the cost of coding them intra. @@ -270,8 +360,12 @@ fn put_coefficients(w: &mut BitWriter, t: &EncTables, levels: &[i32; 64], table: t.dct_eob[table].put(w); } -fn put_mb_type(w: &mut BitWriter, t: &EncTables, predicted: bool, flags: i16) { - let table = if predicted { &t.mbtype_p } else { &t.mbtype_i }; +fn put_mb_type(w: &mut BitWriter, t: &EncTables, ptype: PictureType, flags: i16) { + let table = match ptype { + PictureType::P => &t.mbtype_p, + PictureType::B => &t.mbtype_b, + _ => &t.mbtype_i, + }; if let Some(c) = table.get(flags as usize).copied().flatten() { c.put(w); } @@ -283,12 +377,13 @@ fn intra_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn) -> MbP let quant = mb.qcode != st.qcode; put_increment(w, t, st.skipped + 1); st.skipped = 0; - put_mb_type(w, t, ctx.reference.is_some(), if quant { MB_INTRA | MB_QUANT } else { MB_INTRA }); + put_mb_type(w, t, ctx.ptype, if quant { MB_INTRA | MB_QUANT } else { MB_INTRA }); if quant { w.put(u32::from(mb.qcode), 5); st.qcode = mb.qcode; } - st.pmv = [0; 2]; + st.pmv = [[0; 2]; 2]; + st.last_dirs = MB_INTRA; let qs = qscale(ctx.nonlinear, st.qcode); let dc_mult = 8 >> ctx.dc_prec; let dc_max = (1 << (8 + ctx.dc_prec)) - 1; @@ -321,28 +416,16 @@ fn intra_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn) -> MbP /// whether it was skipped. fn inter_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, reference: &Frame, mv: [i32; 2]) -> (MbPix, bool) { let t = enc_tables(); - let mut rec = predict_mb(ctx, reference, mv, mb.mbx, mb.mby); + let mut rec = predict_mb(ctx, Some(reference), mv, mb.mbx, mb.mby); let qs = qscale(ctx.nonlinear, mb.qcode); - let (cbw, _) = ctx.cmb(); - let n = ctx.blocks(); - let mut levels = [[0i32; 64]; 8]; - let mut cbp = 0u32; - for i in 0..n { - let (s, p) = (mb.src.block(i, cbw), rec.block(i, cbw)); - let f = fdct(&std::array::from_fn(|k| s[k] - p[k])); - for pos in 0..64 { - levels[i][pos] = quant_inter(f[pos], ctx.inter_matrix[pos], qs); - } - if levels[i].iter().any(|&l| l != 0) { - cbp |= 1 << (n - 1 - i); - } - } + let (levels, cbp) = residual(ctx, mb, &rec, qs); st.dc = [ctx.dc_reset(); 3]; + st.last_dirs = MB_FWD; // the first and last macroblock of a slice are always coded let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; if mv == [0, 0] && cbp == 0 && !edge { st.skipped += 1; - st.pmv = [0; 2]; + st.pmv = [[0; 2]; 2]; return (rec, true); } put_increment(w, t, st.skipped + 1); @@ -358,44 +441,140 @@ fn inter_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, refere if quant { flags |= MB_QUANT; } - put_mb_type(w, t, true, flags); + put_mb_type(w, t, PictureType::P, flags); if quant { w.put(u32::from(mb.qcode), 5); st.qcode = mb.qcode; } if flags & MB_FWD != 0 { for c in 0..2 { - t.put_motion(w, wrap_delta(mv[c], st.pmv[c], ctx.f_code), ctx.f_code); + t.put_motion(w, wrap_delta(mv[c], st.pmv[0][c], ctx.f_code), ctx.f_code); } - st.pmv = mv; + st.pmv[0] = mv; } else { - st.pmv = [0; 2]; // "No MC" resets the predictors - } - if cbp != 0 { - if n == 8 { - t.cbp[(cbp >> 2) as usize].put(w); - w.put(cbp & 3, 2); - } else { - t.cbp[cbp as usize].put(w); - } - for i in 0..n { - if cbp & (1 << (n - 1 - i)) != 0 { - put_coefficients(w, t, &levels[i], 0, 0); - rec.store(i, cbw, &reconstruct(&levels[i], ctx.inter_matrix, qs, false, 0), true); - } - } + st.pmv = [[0; 2]; 2]; // "No MC" resets the predictors } + put_residual(ctx, w, &levels, cbp, &mut rec, qs); (rec, false) } -/// The frame prediction of a macroblock from `f` with vector `mv`, formed as the decoder forms -/// it (§7.6.4: chroma vectors are the luma ones halved towards zero). -fn predict_mb(ctx: &PicCtx, f: &Frame, mv: [i32; 2], mbx: usize, mby: usize) -> MbPix { - let (cbw, cbh) = ctx.cmb(); +/// Quantised residual of every block of `mb` against `pred`, and the coded_block_pattern. +fn residual(ctx: &PicCtx, mb: &MbIn, pred: &MbPix, qs: i32) -> ([[i32; 64]; 8], u32) { + let (cbw, _) = ctx.cmb(); + let n = ctx.blocks(); + let mut levels = [[0i32; 64]; 8]; + let mut cbp = 0u32; + for i in 0..n { + let (s, p) = (mb.src.block(i, cbw), pred.block(i, cbw)); + let f = fdct(&std::array::from_fn(|k| s[k] - p[k])); + for pos in 0..64 { + levels[i][pos] = quant_inter(f[pos], ctx.inter_matrix[pos], qs); + } + if levels[i].iter().any(|&l| l != 0) { + cbp |= 1 << (n - 1 - i); + } + } + (levels, cbp) +} + +/// Write coded_block_pattern and the coded blocks, adding their reconstruction to `rec`. +fn put_residual(ctx: &PicCtx, w: &mut BitWriter, levels: &[[i32; 64]; 8], cbp: u32, rec: &mut MbPix, qs: i32) { + if cbp == 0 { + return; + } + let t = enc_tables(); + let (cbw, _) = ctx.cmb(); + let n = ctx.blocks(); + if n == 8 { + t.cbp[(cbp >> 2) as usize].put(w); + w.put(cbp & 3, 2); + } else { + t.cbp[cbp as usize].put(w); + } + for i in 0..n { + if cbp & (1 << (n - 1 - i)) != 0 { + put_coefficients(w, t, &levels[i], 0, 0); + rec.store(i, cbw, &reconstruct(&levels[i], ctx.inter_matrix, qs, false, 0), true); + } + } +} + +/// Code a B macroblock with prediction `pred` (or skip it); returns its reconstruction and +/// whether it was skipped. +fn b_mb(ctx: &PicCtx, st: &mut SliceSt, w: &mut BitWriter, mb: &MbIn, pred: BPred) -> (MbPix, bool) { + let t = enc_tables(); + let mut rec = predict_b(ctx, pred, mb.mbx, mb.mby); + let qs = qscale(ctx.nonlinear, mb.qcode); + let (levels, cbp) = residual(ctx, mb, &rec, qs); + st.dc = [ctx.dc_reset(); 3]; + // a skipped B macroblock repeats the previous one's directions with the predictors as its + // vectors (§7.6.6.3); the first and last macroblock of a slice are always coded + let edge = mb.mbx == 0 || mb.mbx + 1 == ctx.mb_w; + let same = |s: usize, dir: i16| pred.dirs & dir == 0 || pred.mvs[s] == st.pmv[s]; + if cbp == 0 && !edge && st.last_dirs & MB_INTRA == 0 && pred.dirs == st.last_dirs && same(0, MB_FWD) && same(1, MB_BWD) { + st.skipped += 1; + return (rec, true); + } + put_increment(w, t, st.skipped + 1); + st.skipped = 0; + let quant = cbp != 0 && mb.qcode != st.qcode; + let mut flags = pred.dirs; + if cbp != 0 { + flags |= MB_PATTERN; + } + if quant { + flags |= MB_QUANT; + } + put_mb_type(w, t, PictureType::B, flags); + if quant { + w.put(u32::from(mb.qcode), 5); + st.qcode = mb.qcode; + } + for (s, dir) in [(0, MB_FWD), (1, MB_BWD)] { + if pred.dirs & dir != 0 { + for c in 0..2 { + t.put_motion(w, wrap_delta(pred.mvs[s][c], st.pmv[s][c], ctx.f_code), ctx.f_code); + } + st.pmv[s] = pred.mvs[s]; + } + } + st.last_dirs = pred.dirs; + put_residual(ctx, w, &levels, cbp, &mut rec, qs); + (rec, false) +} + +/// The prediction of a B macroblock: forward, backward, or the average of both, formed in the +/// decoder's order (forward first, then the backward prediction averaged in). +fn predict_b(ctx: &PicCtx, pred: BPred, mbx: usize, mby: usize) -> MbPix { let mut p = MbPix { y: [0; 256], c: [[0; 256]; 2] }; + let mut avg = false; + for (s, dir, r) in [(0, MB_FWD, ctx.fwd), (1, MB_BWD, ctx.bwd)] { + if pred.dirs & dir != 0 { + if let Some(f) = r { + predict_into(ctx, &mut p, f, pred.mvs[s], (mbx, mby), avg); + } + avg = true; + } + } + p +} + +/// The frame prediction of a macroblock from `f` with vector `mv` (gray without a reference). +fn predict_mb(ctx: &PicCtx, f: Option<&Frame>, mv: [i32; 2], mbx: usize, mby: usize) -> MbPix { + let mut p = MbPix { y: [128; 256], c: [[128; 256]; 2] }; + if let Some(f) = f { + predict_into(ctx, &mut p, f, mv, (mbx, mby), false); + } + p +} + +/// Form the frame prediction from `f` with vector `mv` into `p`, or average it with what `p` +/// holds, as the decoder forms it (§7.6.4: chroma vectors are the luma ones halved towards zero). +fn predict_into(ctx: &PicCtx, p: &mut MbPix, f: &Frame, mv: [i32; 2], (mbx, mby): (usize, usize), avg: bool) { + let (cbw, cbh) = ctx.cmb(); let blk = Block { x: (mbx * 16) as i32 + (mv[0] >> 1), y: (mby * 16) as i32 + (mv[1] >> 1), hx: mv[0] & 1 != 0, hy: mv[1] & 1 != 0, bw: 16, bh: 16 }; - predict(&mut p.y, 0, 16, f.plane(0, None), blk, false); + predict(&mut p.y, 0, 16, f.plane(0, None), blk, avg); let cmv = [if ctx.shx == 1 { mv[0] / 2 } else { mv[0] }, if ctx.shy == 1 { mv[1] / 2 } else { mv[1] }]; let cb = Block { x: (mbx * cbw) as i32 + (cmv[0] >> 1), @@ -406,7 +585,48 @@ fn predict_mb(ctx: &PicCtx, f: &Frame, mv: [i32; 2], mbx: usize, mby: usize) -> bh: cbh, }; for c in 0..2 { - predict(&mut p.c[c], 0, cbw, f.plane(1 + c, None), cb, false); + predict(&mut p.c[c], 0, cbw, f.plane(1 + c, None), cb, avg); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_skip_prediction_never_leaves_the_reference() { + // three macroblocks across; the left neighbour's forward vector (+17 samples) fits its + // own position but points past the right edge from the middle macroblock + let mut f = Frame::new(48, 16, 24, 8); + for (i, v) in f.planes[0].iter_mut().enumerate() { + *v = ((i % 48) * 5 + (i / 48) * 11) as u8; + } + let ctx = PicCtx { + ptype: PictureType::B, + src: &f, + fwd: Some(&f), + bwd: Some(&f), + cand: [&[], &[]], + mb_w: 3, + shx: 1, + shy: 1, + intra_matrix: &crate::mpeg2::headers::DEFAULT_INTRA, + inter_matrix: &[16; 64], + nonlinear: true, + dc_prec: 1, + f_code: 3, + search: 31, + mb_qcode: &[4; 3], + }; + let bad = BPred { dirs: MB_FWD, mvs: [[34, 0], [0, 0]] }; + // the bitstream can carry the vector (f_code 3: -64..64): only the position rules it out + let at = |mbx| Search { reference: &f, src: &[0; 256], mbx, mby: 0, f_code: ctx.f_code, range: ctx.search, pmv: bad.mvs[0], lambda: 1 }; + assert!(at(0).valid(bad.mvs[0]) && !at(1).valid(bad.mvs[0])); + // a source that the out-of-range (edge-clamped) prediction would match exactly + let src = predict_b(&ctx, bad, 1, 0); + let st = SliceSt { qcode: 4, dc: [256; 3], pmv: bad.mvs, skipped: 0, left_mv: bad.mvs, last_dirs: MB_FWD }; + let mb = MbIn { src: &src, mbx: 1, mby: 0, qcode: 4 }; + let pred = b_decision(&ctx, &st, &mb, 1); + assert_ne!(pred, Some(bad)); } - p } diff --git a/crates/video/src/mpeg2/encode/rate.rs b/crates/video/src/mpeg2/encode/rate.rs index 65c23efc3e..96c6f2aa18 100644 --- a/crates/video/src/mpeg2/encode/rate.rs +++ b/crates/video/src/mpeg2/encode/rate.rs @@ -1,18 +1,26 @@ //! Single-pass average bitrate control at picture level, after the target bit allocation of the //! MPEG-2 Test Model 5: each picture type keeps a complexity `X = bits · average quantiser`, the -//! bits left for the GOP are shared out by complexity, and a picture's quantiser is `X / target`. -//! There is no VBV model: the average converges on the target, single pictures may not. +//! bits left for the GOP are shared out by complexity (B pictures weighted down by `KB`), and a +//! picture's quantiser is `X / target`. There is no VBV model: the average converges on the +//! target, single pictures may not. + +use crate::mpeg2::headers::PictureType; + +/// TM5's quantiser ratio of B to P pictures (K_b / K_p). +const KB: f64 = 1.4; pub(crate) struct RateCtl { bps: f64, fps: f64, - /// Complexity of I and P pictures. + /// Complexity of I, P and B pictures. xi: f64, xp: f64, + xb: f64, /// Bits left for the current GOP (carries over between GOPs). remaining: f64, - /// P pictures left in the current GOP. + /// P and B pictures left in the current GOP. np: u32, + nb: u32, /// Range of quantiser_scale values. q_min: f64, q_max: f64, @@ -21,34 +29,60 @@ pub(crate) struct RateCtl { impl RateCtl { pub fn new(bps: f64, fps: f64, q_range: (f64, f64)) -> Self { // TM5's starting complexities - Self { bps, fps, xi: 160.0 * bps / 115.0, xp: 60.0 * bps / 115.0, remaining: 0.0, np: 0, q_min: q_range.0, q_max: q_range.1 } + Self { + bps, + fps, + xi: 160.0 * bps / 115.0, + xp: 60.0 * bps / 115.0, + xb: 42.0 * bps / 115.0, + remaining: 0.0, + np: 0, + nb: 0, + q_min: q_range.0, + q_max: q_range.1, + } } - /// A GOP of `pictures` pictures (one I, the rest P) starts. - pub fn start_gop(&mut self, pictures: u32) { - self.remaining += self.bps * f64::from(pictures) / self.fps; - self.np = pictures.saturating_sub(1); + /// A GOP of one I, `np` P and `nb` B pictures starts. + pub fn start_gop(&mut self, np: u32, nb: u32) { + self.remaining += self.bps * f64::from(1 + np + nb) / self.fps; + self.np = np; + self.nb = nb; } - /// quantiser_scale for the next picture. - pub fn qscale(&self, intra: bool) -> f64 { + /// The GOP ends `missing` pictures short of what `start_gop` budgeted (the encoder was + /// flushed): their bits are not carried into the next GOP. + pub fn end_gop(&mut self, missing: u32) { + self.remaining -= self.bps * f64::from(missing) / self.fps; + self.np = 0; + self.nb = 0; + } + + /// quantiser_scale for the next picture of type `ptype`. + pub fn qscale(&self, ptype: PictureType) -> f64 { let floor = self.bps / (8.0 * self.fps); - let (target, x) = if intra { - (self.remaining / (1.0 + f64::from(self.np) * self.xp / self.xi), self.xi) - } else { - (self.remaining / f64::from(self.np.max(1)), self.xp) + let (np, nb) = (f64::from(self.np), f64::from(self.nb)); + let (target, x) = match ptype { + PictureType::I => (self.remaining / (1.0 + np * self.xp / self.xi + nb * self.xb / (self.xi * KB)), self.xi), + PictureType::B => (self.remaining / (nb.max(1.0) + np * KB * self.xp / self.xb), self.xb), + _ => (self.remaining / (np.max(1.0) + nb * self.xb / (KB * self.xp)), self.xp), }; (x / target.max(floor)).clamp(self.q_min, self.q_max) } - /// The picture used `bits` at average quantiser_scale `avg_q`. - pub fn update(&mut self, intra: bool, bits: u64, avg_q: f64) { - let x = bits as f64 * avg_q; - if intra { - self.xi = x.max(1.0); - } else { - self.xp = x.max(1.0); - self.np = self.np.saturating_sub(1); + /// A picture of type `ptype` used `bits` at average quantiser_scale `avg_q`. + pub fn update(&mut self, ptype: PictureType, bits: u64, avg_q: f64) { + let x = (bits as f64 * avg_q).max(1.0); + match ptype { + PictureType::I => self.xi = x, + PictureType::B => { + self.xb = x; + self.nb = self.nb.saturating_sub(1); + } + _ => { + self.xp = x; + self.np = self.np.saturating_sub(1); + } } self.remaining -= bits as f64; } @@ -58,18 +92,26 @@ impl RateCtl { mod tests { use super::*; - /// A picture whose size is `complexity / q` (the model the controller assumes). - fn run(complexity_i: f64, complexity_p: f64, bps: f64, gops: u32) -> f64 { + /// A picture whose size is `complexity / q` (the model the controller assumes), in GOPs of + /// 12 pictures with `b` B pictures between anchors. + fn run(c: [f64; 3], b: usize, bps: f64, gops: u32) -> f64 { let fps = 25.0; + let types: Vec = (0..12) + .map(|k| match k { + 0 => PictureType::I, + k if k % (b + 1) == 0 => PictureType::P, + _ => PictureType::B, + }) + .collect(); + let np = types.iter().filter(|&&t| t == PictureType::P).count() as u32; let mut rc = RateCtl::new(bps, fps, (1.0, 112.0)); let mut total = 0.0; for _ in 0..gops { - rc.start_gop(12); - for k in 0..12 { - let intra = k == 0; - let q = rc.qscale(intra); - let bits = (if intra { complexity_i } else { complexity_p }) / q; - rc.update(intra, bits as u64, q); + rc.start_gop(np, 11 - np); + for &t in &types { + let q = rc.qscale(t); + let bits = c[t as usize] / q; + rc.update(t, bits as u64, q); total += bits; } } @@ -79,24 +121,40 @@ mod tests { #[test] fn converges_on_the_target() { // complexities whose target quantiser is inside the allowed range - for (ci, cp) in [(4e7, 1e7), (8e7, 2e6), (1e7, 9e6)] { - let got = run(ci, cp, 4e6, 20); - assert!((got / 4e6 - 1.0).abs() < 0.03, "{ci} {cp}: {got}"); + for (c, b) in [([4e7, 1e7, 7e6], 0), ([8e7, 2e6, 1e6], 0), ([1e7, 9e6, 8e6], 0), ([4e7, 1e7, 7e6], 2), ([6e7, 2e7, 5e6], 1)] { + let got = run(c, b, 4e6, 20); + assert!((got / 4e6 - 1.0).abs() < 0.03, "{c:?} b {b}: {got}"); } } + #[test] + fn a_gop_cut_short_gives_its_budget_back() { + let mut rc = RateCtl::new(4e6, 25.0, (1.0, 112.0)); + for _ in 0..20 { + // a GOP of 12 that ends after its I picture and two P pictures + rc.start_gop(11, 0); + for t in [PictureType::I, PictureType::P, PictureType::P] { + let q = rc.qscale(t); + rc.update(t, (1e7 / q) as u64, q); + } + rc.end_gop(9); + } + // what is left is the three pictures' rounding, not nine pictures' budget per GOP + assert!(rc.remaining.abs() < 3.0 * 4e6 / 25.0, "{}", rc.remaining); + } + #[test] fn the_quantiser_stays_in_range() { let mut rc = RateCtl::new(1e6, 25.0, (2.0, 62.0)); - rc.start_gop(2); + rc.start_gop(1, 0); // a picture far larger than its budget pushes the next quantiser to the top - rc.update(true, 50_000_000, 10.0); - rc.start_gop(2); - assert_eq!(rc.qscale(true), 62.0); + rc.update(PictureType::I, 50_000_000, 10.0); + rc.start_gop(1, 0); + assert_eq!(rc.qscale(PictureType::I), 62.0); // and a tiny one to the bottom let mut rc = RateCtl::new(1e6, 25.0, (2.0, 62.0)); - rc.start_gop(2); - rc.update(true, 10, 2.0); - assert_eq!(rc.qscale(true), 2.0); + rc.start_gop(1, 0); + rc.update(PictureType::I, 10, 2.0); + assert_eq!(rc.qscale(PictureType::I), 2.0); } } diff --git a/crates/video/src/mpeg2/encode/tables.rs b/crates/video/src/mpeg2/encode/tables.rs index b79dd92eaa..e239294500 100644 --- a/crates/video/src/mpeg2/encode/tables.rs +++ b/crates/video/src/mpeg2/encode/tables.rs @@ -4,7 +4,7 @@ use std::sync::OnceLock; use crate::mpeg2::vlc::{ - CBP, DC_CHROMA, DC_LUMA, DCT_EOB, DCT_ESCAPE, DCT_ONE, DCT_ZERO, DCT_ZERO_LONG, MBA, MBA_ESCAPE, MBTYPE_I, MBTYPE_P, MOTION, dct_table, + CBP, DC_CHROMA, DC_LUMA, DCT_EOB, DCT_ESCAPE, DCT_ONE, DCT_ZERO, DCT_ZERO_LONG, MBA, MBA_ESCAPE, MBTYPE_B, MBTYPE_I, MBTYPE_P, MOTION, dct_table, parse_code, }; @@ -38,9 +38,10 @@ pub(crate) struct EncTables { /// macroblock_address_increment 1..=33 (index 0 unused) and the escape. pub mba: [Code; 34], pub mba_escape: Code, - /// macroblock_type by flags: I pictures, P pictures (index: flags, 0..32). + /// macroblock_type by flags: I, P and B pictures (index: flags, 0..32). pub mbtype_i: [Option; 32], pub mbtype_p: [Option; 32], + pub mbtype_b: [Option; 32], /// coded_block_pattern_420 (the first six blocks). pub cbp: [Code; 64], /// motion_code -16..=16 at index code + 16. @@ -105,6 +106,7 @@ pub(crate) fn enc_tables() -> &'static EncTables { mba_escape, mbtype_i: mb_types(MBTYPE_I), mbtype_p: mb_types(MBTYPE_P), + mbtype_b: mb_types(MBTYPE_B), cbp: by_value(CBP, 0), motion: by_value(MOTION, 16), dc_luma: by_value(DC_LUMA, 0), @@ -185,11 +187,25 @@ mod tests { use super::*; use crate::mpeg2::bits::Bits; use crate::mpeg2::slice::wrap_vector; - use crate::mpeg2::vlc::{MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT, rl, tables}; + use crate::mpeg2::vlc::{MB_BWD, MB_FWD, MB_INTRA, MB_PATTERN, MB_QUANT, rl, tables}; - /// Macroblock types the encoder sends (frame pictures, frame prediction, no B pictures). + /// Macroblock types the encoder sends in P pictures (frame pictures, frame prediction). const ENC_MB_TYPES: [i16; 7] = [MB_INTRA, MB_INTRA | MB_QUANT, MB_FWD | MB_PATTERN, MB_PATTERN, MB_FWD, MB_QUANT | MB_FWD | MB_PATTERN, MB_QUANT | MB_PATTERN]; + /// And in B pictures: every combination of directions, with and without a residual. + const ENC_MB_TYPES_B: [i16; 11] = [ + MB_INTRA, + MB_INTRA | MB_QUANT, + MB_FWD, + MB_BWD, + MB_FWD | MB_BWD, + MB_FWD | MB_PATTERN, + MB_BWD | MB_PATTERN, + MB_FWD | MB_BWD | MB_PATTERN, + MB_QUANT | MB_FWD | MB_PATTERN, + MB_QUANT | MB_BWD | MB_PATTERN, + MB_QUANT | MB_FWD | MB_BWD | MB_PATTERN, + ]; #[test] fn every_code_decodes_to_its_value() { @@ -223,6 +239,9 @@ mod tests { } check(t.mbtype_p[f as usize].unwrap_or_default(), &d.mbtype[1], f); } + for f in ENC_MB_TYPES_B { + check(t.mbtype_b[f as usize].unwrap_or_default(), &d.mbtype[2], f); + } for (k, vlc) in [&d.dct_zero, &d.dct_one].into_iter().enumerate() { for run in 0..=MAX_RUN { for level in 1..=MAX_LEVEL { diff --git a/crates/video/src/mpeg2/encode/tests.rs b/crates/video/src/mpeg2/encode/tests.rs index 5352161b3c..01aac2b32c 100644 --- a/crates/video/src/mpeg2/encode/tests.rs +++ b/crates/video/src/mpeg2/encode/tests.rs @@ -3,7 +3,7 @@ //! comparison is in `tests/mpeg2/encode.rs`. use super::*; -use crate::mpeg2::{Decoder, access_units, probe}; +use crate::mpeg2::{Decoder, probe}; /// A moving, textured test sequence: a gradient with a sharp pattern drifting by a fraction of a /// sample per picture, and a block moving across it. @@ -54,16 +54,21 @@ fn encode(cfg: EncoderConfig, frames: usize) -> (Vec, Vec, Vec

Vec { +/// Decode packets (each tagged with its presentation time); returns the pictures in display +/// order. +fn decode(packets: &[Packet]) -> Vec { let mut d = Decoder::new(); let mut out = Vec::new(); - for (i, r) in access_units(es).into_iter().enumerate() { - out.extend(d.decode(&es[r], i as i64).unwrap()); + for p in packets { + out.extend(d.decode(&p.data, p.pts).unwrap()); } out.extend(d.flush()); assert_eq!(d.errors(), 0, "decoder errors: {:?}", d.last_error()); @@ -71,9 +76,11 @@ fn decode(es: &[u8]) -> Vec { } fn assert_decodes_to_recon(name: &str, cfg: EncoderConfig, frames: usize) -> Vec { - let (es, recon, packets) = encode(cfg, frames); - let pics = decode(&es); + let (_, recon, packets) = encode(cfg, frames); + assert!(packets.windows(2).all(|w| w[0].dts < w[1].dts) && packets.iter().all(|p| p.dts <= p.pts), "{name}: decoding times"); + let pics = decode(&packets); assert_eq!(pics.len(), frames, "{name}: picture count"); + assert_eq!(recon.len(), frames, "{name}: reconstruction count"); for (i, (p, r)) in pics.iter().zip(&recon).enumerate() { assert_eq!(p.pts, i as i64, "{name}: display order"); for (plane, (a, b)) in [("Y", (&p.y, &r.y)), ("Cb", (&p.cb, &r.cb)), ("Cr", (&p.cr, &r.cr))] { @@ -101,6 +108,7 @@ fn intra_only_decodes_to_the_reconstruction() { fn long_p_gop_does_not_drift() { let mut cfg = EncoderConfig::new(96, 64, 25, 1); cfg.gop_size = 30; + cfg.b_pictures = 0; let packets = assert_decodes_to_recon("long gop", cfg, 30); assert_eq!(packets.iter().filter(|p| p.keyframe).count(), 1); assert!(packets[1..].iter().all(|p| p.picture_type == PictureType::P)); @@ -127,7 +135,201 @@ fn every_coding_option_decodes_to_the_reconstruction() { ("422 odd size", EncoderConfig { width: 70, height: 30, chroma: ChromaFormat::Yuv422, ..base.clone() }), ]; for (name, cfg) in cases { - assert_decodes_to_recon(name, cfg, 8); + assert_decodes_to_recon(name, cfg.clone(), 8); + assert_decodes_to_recon(name, EncoderConfig { b_pictures: 0, ..cfg }, 8); + } +} + +#[test] +fn b_pictures_decode_to_the_reconstruction() { + let base = EncoderConfig::new(96, 64, 25, 1); + for b in 1..=4 { + for closed in [true, false] { + for (gop, frames) in [(12, 30), (7, 17), (2, 6), (1, 4), (15, 16)] { + let name = format!("b {b} closed {closed} gop {gop} frames {frames}"); + let cfg = EncoderConfig { b_pictures: b, closed_gop: closed, gop_size: gop, ..base.clone() }; + let packets = assert_decodes_to_recon(&name, cfg, frames); + if gop > 1 { + assert!(packets.iter().any(|p| p.picture_type == PictureType::B), "{name}: no B pictures"); + } + } + } + } + let cases = [ + ("422", EncoderConfig { chroma: ChromaFormat::Yuv422, ..base.clone() }), + ("abr", EncoderConfig { rate: RateControl::Abr { kbps: 400 }, ..base.clone() }), + ("odd size", EncoderConfig { width: 50, height: 34, ..base.clone() }), + ("small range", EncoderConfig { search_range: 2, ..base.clone() }), + ("linear coarse", EncoderConfig { nonlinear_quant: false, rate: RateControl::Quantiser(25), ..base.clone() }), + ]; + for (name, cfg) in cases { + assert_decodes_to_recon(name, cfg, 14); + } +} + +#[test] +fn pictures_are_reordered_into_decoding_order() { + let cfg = EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(64, 48, 25, 1) }; + let (_, _, packets) = encode(cfg, 15); + let order: Vec<(PictureType, i64)> = packets.iter().map(|p| (p.picture_type, p.pts)).collect(); + use PictureType::{B, I, P}; + #[rustfmt::skip] + let want = [(I, 0), (P, 3), (B, 1), (B, 2), (P, 6), (B, 4), (B, 5), (P, 9), (B, 7), (B, 8), + // B10 and B11 lead the second GOP; at the end the last held picture becomes a P picture + (I, 12), (B, 10), (B, 11), (P, 14), (B, 13)]; + assert_eq!(order, want); + // decoding times: the presentation times in order, one interval early + let dts: Vec = packets.iter().map(|p| p.dts).collect(); + assert_eq!(dts, (-1..14).collect::>()); + // temporal_reference counts display order from each GOP's first picture + let pics = decode(&packets); + let tr: Vec = pics.iter().map(|p| p.temporal_reference).collect(); + assert_eq!(tr, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]); +} + +#[test] +fn a_closed_gop_decodes_on_its_own() { + for closed in [true, false] { + let cfg = EncoderConfig { gop_size: 6, b_pictures: 2, closed_gop: closed, ..EncoderConfig::new(64, 48, 25, 1) }; + let (_, recon, packets) = encode(cfg, 12); + // start decoding at the second GOP's I picture (display 6): B4 and B5 lead it + let at = packets.iter().position(|p| p.pts == 6).unwrap(); + assert!(packets[at].keyframe); + let mut d = Decoder::new(); + let mut pics = Vec::new(); + for p in &packets[at..] { + pics.extend(d.decode(&p.data, p.pts).unwrap()); + } + pics.extend(d.flush()); + let shown: Vec = pics.iter().map(|p| p.pts).collect(); + if closed { + assert_eq!(shown, (4..12).collect::>()); + for p in &pics { + assert_eq!(p.y, recon[p.pts as usize].y, "closed GOP: picture {}", p.pts); + } + } else { + // the leading B pictures need the previous GOP's last P picture + assert_eq!(shown, (6..12).collect::>()); + } + } +} + +#[test] +fn b_pictures_are_smaller_than_p_pictures() { + let cfg = EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(128, 96, 25, 1) }; + let (_, _, packets) = encode(cfg, 12); + let avg = |t: PictureType| { + let s: Vec = packets.iter().filter(|p| p.picture_type == t).map(|p| p.data.len()).collect(); + s.iter().sum::() as f64 / s.len().max(1) as f64 + }; + let (p, b) = (avg(PictureType::P), avg(PictureType::B)); + assert!(b * 1.5 < p, "P {p:.0} bytes, B {b:.0} bytes"); + // static content: the B pictures skip every macroblock but the first and last of a slice + let mut enc = Encoder::new(EncoderConfig { gop_size: 12, b_pictures: 2, ..EncoderConfig::new(128, 64, 25, 1) }).unwrap(); + let (y, cb, cr) = scene(128, 64, 64, 32, 0); + let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: 128, c_stride: 64 }; + let mut packets = Vec::new(); + for t in 0..7 { + packets.extend(enc.encode(&f, t).unwrap()); + } + let i = packets[0].data.len(); + let bs: Vec<&Packet> = packets.iter().filter(|p| p.picture_type == PictureType::B).collect(); + assert_eq!(bs.len(), 4); + for p in bs { + // a picture header, four slice headers and eight edge macroblocks + assert!(p.data.len() < 64, "static B picture {} of {} bytes (I {i})", p.pts, p.data.len()); + } +} + +#[test] +fn presentation_times_must_step_evenly_with_b_pictures() { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // the I picture waits for the second time, which sets the step + assert!(enc.encode(&f, 10).unwrap().is_empty()); + let mut packets = enc.encode(&f, 12).unwrap(); + for bad in [12, 11, 15] { + assert!(matches!(enc.encode(&f, bad), Err(EncodeError::BadTimestamp(_))), "{bad}"); + } + packets.extend(enc.encode(&f, 14).unwrap()); + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::>(), [(10, 8), (14, 10), (12, 12)]); + // without B pictures any increasing (or not) times pass through + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); + for pts in [5, 3, 9] { + let p = enc.encode(&f, pts).unwrap().remove(0); + assert_eq!((p.pts, p.dts), (pts, pts)); + } +} + +#[test] +fn decoding_times_increase_after_a_lone_picture_is_flushed() { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // one picture, flushed before a second sets the step: it decodes one unit early + assert!(enc.encode(&f, 100).unwrap().is_empty()); + let mut packets = enc.flush(); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::>(), [(100, 99)]); + // encoding goes on: the next picture decodes at the first one's presentation time + for pts in [105, 110] { + packets.extend(enc.encode(&f, pts).unwrap()); + } + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| (p.pts, p.dts)).collect::>(), [(100, 99), (105, 100), (110, 105)]); + assert!(packets[1].keyframe); +} + +#[test] +fn presentation_times_without_a_decoding_time_are_refused() { + let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); + let f = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; + // the decoding times are one step earlier: they must fit in an i64 + for (first, second) in [(i64::MIN + 1, i64::MIN + 3), (i64::MIN + 5, i64::MIN + 20)] { + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + assert!(matches!(enc.encode(&f, i64::MIN), Err(EncodeError::BadTimestamp(_)))); + assert!(enc.encode(&f, first).unwrap().is_empty()); + assert!(matches!(enc.encode(&f, second), Err(EncodeError::BadTimestamp(_))), "{second} after {first}"); + // a refused time leaves the encoder usable + assert_eq!(enc.flush().iter().map(|p| (p.pts, p.dts)).collect::>(), [(first, first - 1)]); + } + // the lowest times that have one + let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let mut packets = enc.encode(&f, i64::MIN + 1).unwrap(); + packets.extend(enc.encode(&f, i64::MIN + 2).unwrap()); + packets.extend(enc.flush()); + assert_eq!(packets.iter().map(|p| p.dts).collect::>(), [i64::MIN, i64::MIN + 1]); + // without B pictures every time passes through + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); + assert_eq!(enc.encode(&f, i64::MIN).unwrap()[0].dts, i64::MIN); +} + +/// Average bitrate (bit/s) of the scene coded in groups of `group` pictures, flushed after each. +fn flushed_bitrate(cfg: EncoderConfig, group: usize, groups: usize) -> f64 { + let (w, h) = (cfg.width as usize, cfg.height as usize); + let fps = f64::from(cfg.fps_num) / f64::from(cfg.fps_den); + let mut enc = Encoder::new(cfg).unwrap(); + let mut bytes = 0; + for t in 0..group * groups { + let (y, cb, cr) = scene(w, h, w / 2, h / 2, t); + let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: w, c_stride: w / 2 }; + bytes += enc.encode(&f, t as i64).unwrap().iter().map(|p| p.data.len()).sum::(); + if (t + 1) % group == 0 { + bytes += enc.flush().iter().map(|p| p.data.len()).sum::(); + } + } + bytes as f64 * 8.0 * fps / (group * groups) as f64 +} + +#[test] +fn flushing_short_gops_keeps_the_average_bitrate() { + // every flush ends a GOP of 12 after 4 pictures: the 8 that never came must not leave their + // bits to the next GOP + for b in [0, 2] { + let cfg = EncoderConfig { gop_size: 12, b_pictures: b, rate: RateControl::Abr { kbps: 600 }, ..EncoderConfig::new(176, 144, 25, 1) }; + let got = flushed_bitrate(cfg, 4, 15); + assert!((got / 600e3 - 1.0).abs() < 0.15, "b {b}: {got:.0} bit/s for 600000"); } } @@ -161,7 +363,7 @@ fn quality_follows_the_quantiser() { #[test] fn p_pictures_are_smaller_and_static_content_skips() { - let cfg = EncoderConfig { gop_size: 8, ..EncoderConfig::new(128, 64, 25, 1) }; + let cfg = EncoderConfig { gop_size: 8, b_pictures: 0, ..EncoderConfig::new(128, 64, 25, 1) }; let mut enc = Encoder::new(cfg).unwrap(); let (y, cb, cr) = scene(128, 64, 64, 32, 0); let f = YuvFrame { y: &y, cb: &cb, cr: &cr, y_stride: 128, c_stride: 64 }; @@ -191,7 +393,7 @@ fn the_sequence_header_describes_the_stream() { let enc = Encoder::new(cfg).unwrap(); assert_eq!(enc.profile_and_level(), pli, "{name}"); let info = probe(enc.sequence_header()).unwrap(); - assert_eq!((info.width, info.height, info.mpeg2, info.progressive_sequence, info.low_delay), (w, h, true, true, true)); + assert_eq!((info.width, info.height, info.mpeg2, info.progressive_sequence, info.low_delay), (w, h, true, true, false)); assert_eq!(info.codec_name(), format!("MPEG-2 Video ({name})")); assert_eq!(aspect, AspectRatio::Square); assert_eq!(info.sar, (1, 1)); @@ -199,6 +401,9 @@ fn the_sequence_header_describes_the_stream() { let enc = Encoder::new(EncoderConfig { aspect: AspectRatio::Dar16x9, ..EncoderConfig::new(720, 576, 30000, 1001) }).unwrap(); let info = probe(enc.sequence_header()).unwrap(); assert_eq!((info.dar, info.frame_rate), (Some((16, 9)), Some((30000, 1001)))); + // without B pictures the stream is low delay + let enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(720, 576, 25, 1) }).unwrap(); + assert!(probe(enc.sequence_header()).unwrap().low_delay); } #[test] @@ -214,6 +419,8 @@ fn bad_configurations_are_refused() { EncoderConfig { fps_den: 0, ..ok.clone() }, EncoderConfig { gop_size: 0, ..ok.clone() }, EncoderConfig { gop_size: 1024, ..ok.clone() }, + EncoderConfig { b_pictures: 5, ..ok.clone() }, + EncoderConfig { gop_size: 1023, b_pictures: 2, ..ok.clone() }, EncoderConfig { rate: RateControl::Quantiser(0), ..ok.clone() }, EncoderConfig { rate: RateControl::Quantiser(32), ..ok.clone() }, EncoderConfig { rate: RateControl::Abr { kbps: 0 }, ..ok.clone() }, @@ -231,7 +438,7 @@ fn bad_configurations_are_refused() { #[test] fn short_or_inconsistent_planes_are_refused() { - let mut enc = Encoder::new(EncoderConfig::new(32, 32, 25, 1)).unwrap(); + let mut enc = Encoder::new(EncoderConfig { b_pictures: 0, ..EncoderConfig::new(32, 32, 25, 1) }).unwrap(); let (y, c) = (vec![0u8; 32 * 32], vec![0u8; 16 * 16]); let ok = YuvFrame { y: &y, cb: &c, cr: &c, y_stride: 32, c_stride: 16 }; assert!(enc.encode(&ok, 0).is_ok()); diff --git a/crates/video/src/mpeg2/mod.rs b/crates/video/src/mpeg2/mod.rs index ae2bb1682d..4fd59dced1 100644 --- a/crates/video/src/mpeg2/mod.rs +++ b/crates/video/src/mpeg2/mod.rs @@ -1,5 +1,5 @@ //! Clean-room MPEG-2 video (ITU-T H.262 | ISO/IEC 13818-2) and MPEG-1 video (ISO/IEC 11172-2) -//! decoder, and the start of an MPEG-2 encoder ([`encode`], feature `mpeg2-encode`: I and P +//! decoder, and the start of an MPEG-2 encoder ([`encode`], feature `mpeg2-encode`: I, P and B //! pictures). //! //! - Main Profile at Low/Main/High-1440/High Level, 4:2:2 Profile (XDCAM HD422, IMX / D-10), diff --git a/crates/video/tests/mpeg2/encode.rs b/crates/video/tests/mpeg2/encode.rs index 5cb2377dcc..122fe2d716 100644 --- a/crates/video/tests/mpeg2/encode.rs +++ b/crates/video/tests/mpeg2/encode.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use craft_video::mpeg2::{ChromaFormat, Encoder, EncoderConfig, RateControl, ReconFrame, YuvFrame}; +use craft_video::mpeg2::{ChromaFormat, Encoder, EncoderConfig, Packet, RateControl, ReconFrame, YuvFrame}; use crate::common::{Stats, fixture_dir, pix_fmt_of}; use crate::oracle::{MAX_DIFFERING, MIN_PSNR, TOL_MAX}; @@ -39,24 +39,22 @@ fn sizes(cfg: &EncoderConfig) -> (usize, usize, usize) { (w * h, w / 2 * ch, w / 2) } -/// Encode `raw` frames; returns the elementary stream and the reconstruction. -fn encode(cfg: &EncoderConfig, raw: &[u8]) -> (Vec, Vec) { +/// Encode `raw` frames; returns the elementary stream, the reconstruction (display order) and +/// the packets (decoding order). +fn encode(cfg: &EncoderConfig, raw: &[u8]) -> (Vec, Vec, Vec) { let (ys, cs, cw) = sizes(cfg); let fsize = ys + 2 * cs; let mut enc = Encoder::new(cfg.clone()).expect("config"); enc.set_recon_capture(true); - let mut es = Vec::new(); + let mut packets = Vec::new(); for (i, f) in raw.chunks_exact(fsize).enumerate() { let frame = YuvFrame { y: &f[..ys], cb: &f[ys..ys + cs], cr: &f[ys + cs..], y_stride: cfg.width as usize, c_stride: cw }; - for p in enc.encode(&frame, i as i64).expect("encode") { - es.extend_from_slice(&p.data); - } - } - for p in enc.flush() { - es.extend_from_slice(&p.data); + packets.extend(enc.encode(&frame, i as i64).expect("encode")); } + packets.extend(enc.flush()); + let mut es: Vec = packets.iter().flat_map(|p| p.data.iter().copied()).collect(); es.extend_from_slice(enc.end_of_sequence()); - (es, enc.take_recon()) + (es, enc.take_recon(), packets) } /// ffmpeg's decode of `file`, failing on any decoding error. @@ -121,10 +119,11 @@ fn check(ff: &Path, c: &Case) -> (Vec, f64) { let raw = source(ff, c.cfg.width, c.cfg.height, c.frames, pix_fmt); let (ys, cs, _) = sizes(&c.cfg); let fsize = ys + 2 * cs; - let (es, recon) = encode(&c.cfg, &raw); + let (es, recon, packets) = encode(&c.cfg, &raw); let path = write(c.name, &es); let decoded = ffmpeg_decode(ff, &path, pix_fmt); assert_eq!(decoded.len(), c.frames * fsize, "{}: ffmpeg's frame count", c.name); + assert_eq!(recon.len(), c.frames, "{}: reconstruction count", c.name); let mut all = Stats::default(); for (i, (r, f)) in recon.iter().zip(decoded.chunks_exact(fsize)).enumerate() { let mut s = Stats::default(); @@ -139,15 +138,21 @@ fn check(ff: &Path, c: &Case) -> (Vec, f64) { assert!(quality >= c.min_psnr, "{}: luma PSNR {quality:.2} dB against the source", c.name); if let Some((stream, types)) = ffprobe(&path) { assert_eq!(stream, c.probe, "{}: ffprobe", c.name); - let gop = c.cfg.gop_size as usize; - let want: Vec<&str> = (0..c.frames).map(|i| if i % gop == 0 { "I" } else { "P" }).collect(); + // ffprobe lists the pictures in display order + let mut shown: Vec<&Packet> = packets.iter().collect(); + shown.sort_by_key(|p| p.pts); + let want: Vec = shown.iter().map(|p| format!("{:?}", p.picture_type)).collect(); assert_eq!(types, want, "{}: picture types", c.name); } + let count = |t: &str| packets.iter().filter(|p| format!("{:?}", p.picture_type) == t).count(); let kbps = es.len() as f64 * 8.0 * 25.0 / c.frames as f64 / 1000.0; println!( - "{}: {} frames, {kbps:.0} kbit/s, luma PSNR {quality:.2} dB, max diff to ffmpeg {}, {:.3}% differ", + "{}: {} frames ({} I, {} P, {} B), {kbps:.0} kbit/s, luma PSNR {quality:.2} dB, max diff to ffmpeg {}, {:.3}% differ", c.name, c.frames, + count("I"), + count("P"), + count("B"), all.max, 100.0 * all.diff as f64 / all.n as f64 ); @@ -160,6 +165,21 @@ fn ffmpeg_decodes_our_streams() { let cif = EncoderConfig { gop_size: 12, ..EncoderConfig::new(352, 288, 25, 1) }; let cases = [ Case { name: "cif_q4", cfg: cif.clone(), frames: 25, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 36.0 }, + Case { name: "cif_ip", cfg: EncoderConfig { b_pictures: 0, ..cif.clone() }, frames: 25, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 36.0 }, + Case { + name: "cif_open_gop", + cfg: EncoderConfig { closed_gop: false, gop_size: 15, ..cif.clone() }, + frames: 31, + probe: "mpeg2video,Main,10,yuv420p", + min_psnr: 35.0, + }, + Case { + name: "cif_b4", + cfg: EncoderConfig { b_pictures: 4, gop_size: 10, ..cif.clone() }, + frames: 23, + probe: "mpeg2video,Main,10,yuv420p", + min_psnr: 34.0, + }, Case { name: "cif_intra", cfg: EncoderConfig { gop_size: 1, rate: RateControl::Quantiser(8), ..cif.clone() }, @@ -191,10 +211,14 @@ fn ffmpeg_decodes_our_streams() { #[test] fn average_bitrate_reaches_its_target() { let Some(ff) = craft_media_testkit::ffmpeg_or_skip("mpeg2 encoder bitrate") else { return }; - for kbps in [800u32, 2500] { + for (kbps, b) in [(800u32, 2), (2500, 2), (800, 0)] { let c = Case { - name: if kbps == 800 { "cif_abr_800" } else { "cif_abr_2500" }, - cfg: EncoderConfig { rate: RateControl::Abr { kbps }, gop_size: 12, ..EncoderConfig::new(352, 288, 25, 1) }, + name: match (kbps, b) { + (800, 0) => "cif_abr_800_ip", + (800, _) => "cif_abr_800", + _ => "cif_abr_2500", + }, + cfg: EncoderConfig { rate: RateControl::Abr { kbps }, gop_size: 12, b_pictures: b, ..EncoderConfig::new(352, 288, 25, 1) }, frames: 72, probe: "mpeg2video,Main,10,yuv420p", min_psnr: 26.0, diff --git a/crates/webp/src/anim.rs b/crates/webp/src/anim.rs index 3c6df1a644..7d63c75b70 100644 --- a/crates/webp/src/anim.rs +++ b/crates/webp/src/anim.rs @@ -56,48 +56,8 @@ pub fn animation(width: u32, height: u32, frames: &[AnimFrame], opts: &AnimOptio if frames.is_empty() { return Err(Error::Encode("an animation needs a frame")); } - let mut anmf = Vec::new(); - let mut any_alpha = opts.alpha; - for f in frames { - if f.width == 0 || f.height == 0 || f.x % 2 != 0 || f.y % 2 != 0 { - return Err(Error::Encode("a frame is empty or not at an even position")); - } - if f.x.checked_add(f.width).is_none_or(|r| r > width) || f.y.checked_add(f.height).is_none_or(|b| b > height) { - return Err(Error::Encode("a frame reaches past the canvas")); - } - if f.duration_ms >= 1 << 24 { - return Err(Error::Encode("a frame duration is 2^24 ms or more")); - } - let mut body = Vec::new(); - u24(&mut body, f.x / 2); - u24(&mut body, f.y / 2); - u24(&mut body, f.width - 1); - u24(&mut body, f.height - 1); - u24(&mut body, f.duration_ms); - // Bit 1: do not blend; bit 0: dispose to the background. - body.push(u8::from(!f.blend) << 1 | u8::from(f.dispose_to_background)); - match f.payload { - Payload::Lossy { vp8, alpha } => { - if f.width > MAX_VP8_DIMENSION || f.height > MAX_VP8_DIMENSION { - return Err(Error::Encode("a lossy frame is at most 16383 pixels a side")); - } - if let Some(a) = alpha { - if a.len() as u64 != u64::from(f.width) * u64::from(f.height) { - return Err(Error::Encode("an alpha plane does not match its frame")); - } - any_alpha = true; - let mut alph = Vec::with_capacity(a.len() + 1); - // Header byte: no pre-processing, no filtering, no compression. - alph.push(0); - alph.extend_from_slice(a); - chunk(&mut body, b"ALPH", &alph)?; - } - chunk(&mut body, b"VP8 ", vp8)?; - } - Payload::Lossless { vp8l } => chunk(&mut body, b"VP8L", vp8l)?, - } - chunk(&mut anmf, b"ANMF", &body)?; - } + // Determine the header flag before writing, without retaining another full animation. + let any_alpha = opts.alpha || frames.iter().any(|f| matches!(f.payload, Payload::Lossy { alpha: Some(_), .. })); let mut body = b"WEBP".to_vec(); let flags = [(opts.icc.is_some(), 0x20u8), (any_alpha, 0x10), (opts.exif.is_some(), 0x08), (opts.xmp.is_some(), 0x04), (true, 0x02)] .iter() @@ -113,7 +73,46 @@ pub fn animation(width: u32, height: u32, frames: &[AnimFrame], opts: &AnimOptio let mut anim = opts.background_bgra.to_vec(); anim.extend_from_slice(&opts.loop_count.to_le_bytes()); chunk(&mut body, b"ANIM", &anim)?; - body.extend_from_slice(&anmf); + + for f in frames { + if f.width == 0 || f.height == 0 || f.x % 2 != 0 || f.y % 2 != 0 { + return Err(Error::Encode("a frame is empty or not at an even position")); + } + if f.x.checked_add(f.width).is_none_or(|r| r > width) || f.y.checked_add(f.height).is_none_or(|b| b > height) { + return Err(Error::Encode("a frame reaches past the canvas")); + } + if f.duration_ms >= 1 << 24 { + return Err(Error::Encode("a frame duration is 2^24 ms or more")); + } + let mut frame_body = Vec::new(); + u24(&mut frame_body, f.x / 2); + u24(&mut frame_body, f.y / 2); + u24(&mut frame_body, f.width - 1); + u24(&mut frame_body, f.height - 1); + u24(&mut frame_body, f.duration_ms); + // Bit 1: do not blend; bit 0: dispose to the background. + frame_body.push(u8::from(!f.blend) << 1 | u8::from(f.dispose_to_background)); + match f.payload { + Payload::Lossy { vp8, alpha } => { + if f.width > MAX_VP8_DIMENSION || f.height > MAX_VP8_DIMENSION { + return Err(Error::Encode("a lossy frame is at most 16383 pixels a side")); + } + if let Some(a) = alpha { + if a.len() as u64 != u64::from(f.width) * u64::from(f.height) { + return Err(Error::Encode("an alpha plane does not match its frame")); + } + let mut alph = Vec::with_capacity(a.len() + 1); + // Header byte: no pre-processing, no filtering, no compression. + alph.push(0); + alph.extend_from_slice(a); + chunk(&mut frame_body, b"ALPH", &alph)?; + } + chunk(&mut frame_body, b"VP8 ", vp8)?; + } + Payload::Lossless { vp8l } => chunk(&mut frame_body, b"VP8L", vp8l)?, + } + chunk(&mut body, b"ANMF", &frame_body)?; + } if let Some(exif) = opts.exif { chunk(&mut body, b"EXIF", exif)?; } @@ -231,6 +230,23 @@ mod tests { assert_eq!(&file[anim + 8..anim + 14], &[1, 2, 3, 4, 0, 0]); } + #[test] + fn lossy_container_keeps_alpha_payload_padding_and_xmp() { + // Container-only fixture: the writer must not reinterpret an encoder's VP8 bytes. + let vp8 = [11, 22, 33]; + let alpha = [128]; + let f = frame(Payload::Lossy { vp8: &vp8, alpha: Some(&alpha) }, 0, 0, 1, 1, 17); + let file = animation(1, 1, &[f], &AnimOptions { xmp: Some(b"xmp"), ..Default::default() }).unwrap(); + let info = scan(&file, 10).unwrap(); + assert!(info.alpha && info.complete); + assert_eq!(info.frames[0].duration_ms, 17); + let at = file.windows(4).position(|c| c == b"ANMF").unwrap(); + let payload = at + 8 + 16; + assert_eq!(&file[payload..payload + 10], &[b'A', b'L', b'P', b'H', 2, 0, 0, 0, 0, 128]); + assert_eq!(&file[payload + 10..payload + 22], &[b'V', b'P', b'8', b' ', 3, 0, 0, 0, 11, 22, 33, 0]); + assert_eq!(&file[file.len() - 12..], &[b'X', b'M', b'P', b' ', 3, 0, 0, 0, b'x', b'm', b'p', 0]); + } + #[test] fn what_does_not_fit_is_refused() { let px = vp8l(2, 2, [0; 4]); diff --git a/crates/webp/src/lib.rs b/crates/webp/src/lib.rs index 82f0a20033..a24dfc6566 100644 --- a/crates/webp/src/lib.rs +++ b/crates/webp/src/lib.rs @@ -17,6 +17,7 @@ //! Input is treated as hostile: every read is bounds-checked, chunk sizes are checked against the //! file, and the number of frames recorded is capped by the caller. +pub mod anim; #[cfg(feature = "frames")] pub mod frames; #[cfg(test)] diff --git a/crates/webp/tests/animation_public.rs b/crates/webp/tests/animation_public.rs new file mode 100644 index 0000000000..9106f1a798 --- /dev/null +++ b/crates/webp/tests/animation_public.rs @@ -0,0 +1,6 @@ +//! Guard the public module wiring: the implementation must be usable by consumers. +#[test] +fn public_animation_api_refuses_empty_movies() { + let result = craft_webp::anim::animation(1, 1, &[], &craft_webp::anim::AnimOptions::default()); + assert!(result.is_err()); +} diff --git a/crates/xfl/Cargo.toml b/crates/xfl/Cargo.toml index ddf2b3a362..9c8a40e3cb 100644 --- a/crates/xfl/Cargo.toml +++ b/crates/xfl/Cargo.toml @@ -11,5 +11,6 @@ repository.workspace = true workspace = true [dependencies] +craft-xml = { workspace = true } miniz_oxide = "0.8" thiserror = { workspace = true } diff --git a/crates/xfl/src/document.rs b/crates/xfl/src/document.rs new file mode 100644 index 0000000000..ec749189a8 --- /dev/null +++ b/crates/xfl/src/document.rs @@ -0,0 +1,844 @@ +//! Neutral views of the native XFL document schema. +//! +//! This layer recognizes the document, stage, scene, layer and keyframe fields defined by XFL. +//! It does not construct a consumer's animation model. More detailed payloads remain available +//! through [`Document::root`] for the application adapter. +use crate::shape::XflElement; +use craft_xml::{Doctype, El, Error as XmlError, Limits, Local, Options, Pat, UnknownEntity}; +use std::borrow::Cow; + +/// Maximum bytes of XML in one XFL document or library item. +pub const MAX_XML_BYTES: usize = 256 * 1024 * 1024; +/// Maximum depth accepted by AniCraft's existing XFL XML adapter (root depth is one). +pub const MAX_XML_DEPTH: usize = 257; +/// Maximum XFL document elements accepted by the existing adapter. +pub const MAX_XML_ELEMENTS: usize = 4_000_000; + +/// An XFL `DOMDocument.xml` tree plus typed, zero-copy views over its native structure. +#[derive(Clone, Debug)] +pub struct Document { + root: El, +} + +/// Stage metadata stored on the root `DOMDocument` element. +#[derive(Clone, Copy, Debug)] +pub struct Stage<'a> { + pub width: Option, + pub height: Option, + pub frame_rate: Option, + pub background_color: Option<&'a str>, +} + +/// The script-language version and document class selected by an XFL `PublishSettings.xml`. +/// Values stay in their native string form so each consumer can apply its own domain rules. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PublishSettings<'a> { + pub action_script_version: Option>, + pub document_class: Option>, +} + +/// Bounds used when projecting native schema fields into a compact model. +#[derive(Clone, Copy, Debug)] +pub struct ModelLimits { + pub max_timelines: usize, + pub max_layers_per_timeline: usize, +} + +/// Compact XFL metadata that does not retain or duplicate the parsed XML tree. +#[derive(Clone, Debug, PartialEq)] +pub struct DocumentModel { + pub stage: StageModel, + pub timelines: Vec, + /// Present for a library `DOMSymbolItem`; absent for normal `DOMDocument` files. + pub symbol_timeline: Option, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct StageModel { + pub width: Option, + pub height: Option, + pub frame_rate: Option, + pub has_background_color: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TimelineModel { + pub layers: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum LayerType { + #[default] + Normal, + Folder, + Guide, + Mask, + Other, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LayerModel { + pub layer_type: LayerType, + pub parent_layer_index: Option, + pub visible: Option, + pub locked: Option, + pub outline: Option, + pub height_multiplier: Option, + pub frames: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TweenType { + Motion, + Shape, + MotionObject, + #[default] + Other, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct FrameModel { + pub index: Option, + pub duration: Option, + pub is_comment: bool, + pub tween_type: TweenType, +} + +/// A timeline (`DOMTimeline`) listed under `DOMDocument/timelines`. +#[derive(Debug)] +pub struct Timeline<'a, E: XflElement = El> { + element: &'a E, +} + +impl Copy for Timeline<'_, E> {} + +impl Clone for Timeline<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +/// A native `DOMLayer` element. +#[derive(Debug)] +pub struct Layer<'a, E: XflElement = El> { + element: &'a E, +} + +impl Copy for Layer<'_, E> {} + +impl Clone for Layer<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +/// A native `DOMFrame` element. +#[derive(Debug)] +pub struct Frame<'a, E: XflElement = El> { + element: &'a E, +} + +/// An `Include` entry in the document's `` library list. +#[derive(Debug)] +pub struct SymbolInclude<'a, E: XflElement = El> { + element: &'a E, +} + +/// A folder entry in the document's `` library list. +#[derive(Debug)] +pub struct LibraryFolder<'a, E: XflElement = El> { + element: &'a E, +} + +/// Native metadata stored on a library `DOMSymbolItem`. +#[derive(Debug)] +pub struct SymbolItem<'a, E: XflElement = El> { + element: &'a E, +} + +impl Copy for Frame<'_, E> {} + +impl Clone for Frame<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for SymbolInclude<'_, E> {} + +impl Clone for SymbolInclude<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for LibraryFolder<'_, E> {} + +impl Clone for LibraryFolder<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for SymbolItem<'_, E> {} + +impl Clone for SymbolItem<'_, E> { + fn clone(&self) -> Self { + *self + } +} + +fn attr_last<'a>(element: &'a impl XflElement, name: &str) -> Option<&'a str> { + element.attr(name) +} + +fn number_f32(element: &impl XflElement, name: &str) -> Option { + attr_last(element, name).and_then(|value| value.trim().parse::().ok()).filter(|value| value.is_finite()) +} + +fn number_u32(element: &impl XflElement, name: &str) -> Option { + attr_last(element, name).and_then(|value| value.trim().parse::().ok()) +} + +fn boolean(element: &impl XflElement, name: &str) -> Option { + attr_last(element, name).map(|value| value.trim() == "true") +} + +fn trimmed_text<'a>(element: &'a El) -> Option> { + match element.text() { + Cow::Borrowed(text) => { + let trimmed = text.trim(); + (!trimmed.is_empty()).then_some(Cow::Borrowed(trimmed)) + } + Cow::Owned(text) => { + let trimmed = text.trim(); + (!trimmed.is_empty()).then(|| Cow::Owned(trimmed.to_string())) + } + } +} + +impl Document { + /// Parse XFL XML with AniCraft's existing size, depth, element, attribute, entity, doctype + /// and malformed-end-tag behavior. The shared XML parser owns byte parsing; this crate owns + /// the XFL-specific limits and schema views. + pub fn parse(bytes: &[u8]) -> Result { + let defaults = Limits::DEFAULT; + let limits = Limits { + max_input: MAX_XML_BYTES, + max_depth: MAX_XML_DEPTH, + max_nodes: MAX_XML_ELEMENTS.saturating_mul(2).saturating_add(1), + max_elements: MAX_XML_ELEMENTS, + max_attrs: defaults.max_attrs, + max_attrs_total: defaults.max_attrs_total, + }; + let options = + Options { limits, strict_end_tags: true, unknown_entity: UnknownEntity::Literal, doctype: Doctype::Ignore, ..Options::default() }; + Ok(Self { root: options.parse(bytes)? }) + } + + /// The lossless XML tree used by consumer adapters for schema details this view does not + /// interpret. Text and child order come directly from `craft-xml`. + pub fn root(&self) -> &El { + &self.root + } + + /// The root's local element name (normally `DOMDocument`). + pub fn root_name(&self) -> &str { + &self.root.name + } + + /// Reads the current publish profile, falling back to the first profile and then the root. + /// This is also used for `PublishSettings.xml` files, whose schema is separate from the main + /// `DOMDocument` tree. + pub fn publish_settings(&self) -> PublishSettings<'_> { + let profile = self + .root + .elements() + .find(|element| Local("flash_profile").matches(&element.name) && boolean(*element, "current") == Some(true)) + .or_else(|| self.root.elements().find(|element| Local("flash_profile").matches(&element.name))) + .unwrap_or(&self.root); + let properties = profile.child(Local("PublishFlashProperties")).unwrap_or(profile); + let value = |name: &str| properties.child(Local(name)).and_then(trimmed_text); + PublishSettings { action_script_version: value("ActionScriptVersion"), document_class: value("DocumentClass") } + } + + /// The XFL stage metadata, applying finite-number checks but leaving product defaults and + /// clamping to the consumer. + pub fn stage(&self) -> Stage<'_> { + Stage { + width: number_f32(&self.root, "width"), + height: number_f32(&self.root, "height"), + frame_rate: number_f32(&self.root, "frameRate"), + background_color: attr_last(&self.root, "backgroundColor"), + } + } + + /// Timelines in document order. Non-`DOMTimeline` extension nodes are skipped. + pub fn timelines(&self) -> impl Iterator> { + self.root + .child(Local("timelines")) + .into_iter() + .flat_map(El::elements) + .filter(|element| Local("DOMTimeline").matches(&element.name)) + .map(|element| Timeline { element }) + } + + /// The timeline nested under `DOMSymbolItem/timeline`, if this is library symbol XML. + pub fn symbol_timeline(&self) -> Option> { + self.root.child(Local("timeline"))?.child(Local("DOMTimeline")).map(|element| Timeline { element }) + } + + /// Projects bounded schema metadata and returns the XML tree by ownership. Consumers can + /// convert that tree into their compatibility representation without keeping two full trees + /// alive during import. + pub fn into_parts(self, limits: ModelLimits) -> (DocumentModel, El) { + let stage = StageModel { + width: number_f32(&self.root, "width"), + height: number_f32(&self.root, "height"), + frame_rate: number_f32(&self.root, "frameRate"), + has_background_color: attr_last(&self.root, "backgroundColor").is_some(), + }; + let timelines = self.timelines().take(limits.max_timelines).map(|timeline| timeline.into_model(limits.max_layers_per_timeline)).collect(); + let symbol_timeline = self.symbol_timeline().map(|timeline| timeline.into_model(limits.max_layers_per_timeline)); + (DocumentModel { stage, timelines, symbol_timeline }, self.root) + } +} + +impl<'a, E: XflElement> Timeline<'a, E> { + /// Creates a borrowed XFL timeline view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + /// Raw timeline XML for application-specific payload conversion. + pub fn element(self) -> &'a E { + self.element + } + + /// Layers in native order. Non-`DOMLayer` extension nodes are skipped. + pub fn layers(self) -> impl Iterator> { + self.element + .child("layers") + .into_iter() + .flat_map(|element| element.elements()) + .filter(|element| element.local_name() == "DOMLayer") + .map(|element| Layer { element }) + } + + fn into_model(self, max_layers: usize) -> TimelineModel { + TimelineModel { layers: self.layers().take(max_layers).map(Layer::into_model).collect() } + } +} + +impl<'a, E: XflElement> Layer<'a, E> { + /// Creates a borrowed XFL layer view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn layer_type(self) -> Option<&'a str> { + attr_last(self.element, "layerType") + } + + pub fn parent_layer_index(self) -> Option { + number_u32(self.element, "parentLayerIndex") + } + + pub fn visible(self) -> Option { + boolean(self.element, "visible") + } + + pub fn locked(self) -> Option { + boolean(self.element, "locked") + } + + pub fn outline(self) -> Option { + boolean(self.element, "outline") + } + + pub fn color(self) -> Option<&'a str> { + attr_last(self.element, "color") + } + + pub fn height_multiplier(self) -> Option { + number_u32(self.element, "heightMultiplier") + } + + /// Frames in native order. Non-`DOMFrame` extension nodes are skipped. + pub fn element(self) -> &'a E { + self.element + } + + pub fn frames(self) -> impl Iterator> { + self.element + .child("frames") + .into_iter() + .flat_map(|element| element.elements()) + .filter(|element| element.local_name() == "DOMFrame") + .map(|element| Frame { element }) + } + + fn into_model(self) -> LayerModel { + let layer_type = match attr_last(self.element, "layerType") { + Some("folder") => LayerType::Folder, + Some("guide") => LayerType::Guide, + Some("mask") => LayerType::Mask, + Some("normal") | None => LayerType::Normal, + Some(_) => LayerType::Other, + }; + LayerModel { + layer_type, + parent_layer_index: number_u32(self.element, "parentLayerIndex"), + visible: boolean(self.element, "visible"), + locked: boolean(self.element, "locked"), + outline: boolean(self.element, "outline"), + height_multiplier: number_u32(self.element, "heightMultiplier"), + frames: self.frames().map(Frame::into_model).collect(), + } + } +} + +impl<'a, E: XflElement> Frame<'a, E> { + /// Creates a borrowed XFL frame view over a consumer's compatible XML element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn index(self) -> Option { + number_u32(self.element, "index") + } + + pub fn duration(self) -> Option { + number_u32(self.element, "duration") + } + + pub fn label_type(self) -> Option<&'a str> { + attr_last(self.element, "labelType") + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn tween_type(self) -> Option<&'a str> { + attr_last(self.element, "tweenType") + } + + /// Raw frame XML for application-specific shape, action, sound and tween conversion. + pub fn element(self) -> &'a E { + self.element + } + + fn into_model(self) -> FrameModel { + let tween_type = match attr_last(self.element, "tweenType") { + Some("motion") => TweenType::Motion, + Some("shape") => TweenType::Shape, + Some("motion object") => TweenType::MotionObject, + _ => TweenType::Other, + }; + FrameModel { + index: number_u32(self.element, "index"), + duration: number_u32(self.element, "duration"), + is_comment: attr_last(self.element, "labelType").is_some_and(|value| value.trim() == "comment"), + tween_type, + } + } +} + +impl<'a, E: XflElement> SymbolInclude<'a, E> { + /// Creates a borrowed view over a native `Include` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The package-relative library XML path from `href`, kept in native string form. + pub fn href(self) -> Option<&'a str> { + attr_last(self.element, "href") + } + + /// The source element for application-specific path resolution. + pub fn element(self) -> &'a E { + self.element + } +} + +impl<'a, E: XflElement> LibraryFolder<'a, E> { + /// Creates a borrowed view over a native `DOMFolderItem` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The folder path from `name`, kept in native string form. + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + /// The source element for application-specific path validation. + pub fn element(self) -> &'a E { + self.element + } +} + +impl<'a, E: XflElement> SymbolItem<'a, E> { + /// Creates a borrowed view over a native `DOMSymbolItem` element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + pub fn name(self) -> Option<&'a str> { + attr_last(self.element, "name") + } + + pub fn symbol_type(self) -> Option<&'a str> { + attr_last(self.element, "symbolType") + } + + pub fn linkage_export_for_action_script(self) -> Option<&'a str> { + attr_last(self.element, "linkageExportForAS") + } + + pub fn linkage_class_name(self) -> Option<&'a str> { + attr_last(self.element, "linkageClassName") + } + + pub fn linkage_identifier(self) -> Option<&'a str> { + attr_last(self.element, "linkageIdentifier") + } + + pub fn linkage_base_class(self) -> Option<&'a str> { + attr_last(self.element, "linkageBaseClass") + } + + /// Whether the symbol declares any native 9-slice scale-grid attribute, even if malformed. + pub fn has_scale_grid(self) -> bool { + ["scaleGridLeft", "scaleGridRight", "scaleGridTop", "scaleGridBottom"].iter().any(|name| attr_last(self.element, name).is_some()) + } + + pub fn scale_grid_left(self) -> Option { + number_f32(self.element, "scaleGridLeft") + } + + pub fn scale_grid_right(self) -> Option { + number_f32(self.element, "scaleGridRight") + } + + pub fn scale_grid_top(self) -> Option { + number_f32(self.element, "scaleGridTop") + } + + pub fn scale_grid_bottom(self) -> Option { + number_f32(self.element, "scaleGridBottom") + } + + /// The symbol's optional timeline wrapper, for the consumer to map into its own model. + pub fn timeline(self) -> Option<&'a E> { + self.element.child("timeline") + } + + /// The source element for application-specific symbol validation and mapping. + pub fn element(self) -> &'a E { + self.element + } +} + +/// Symbol library entries in source order, skipping non-`Include` extension nodes. +pub fn symbol_includes<'a, E: XflElement>(root: &'a E) -> impl Iterator> + 'a { + root.child("symbols").into_iter().flat_map(XflElement::elements).filter(|element| element.local_name() == "Include").map(SymbolInclude::new) +} + +/// Library folders in source order, skipping non-`DOMFolderItem` extension nodes. +pub fn library_folders<'a, E: XflElement>(root: &'a E) -> impl Iterator> + 'a { + root.child("folders").into_iter().flat_map(XflElement::elements).filter(|element| element.local_name() == "DOMFolderItem").map(LibraryFolder::new) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_stage_scene_layer_and_frame_schema_without_building_an_app_model() { + let bytes = br##"]> + + + + + + + + + + +"##; + let document = Document::parse(bytes).unwrap(); + assert_eq!(document.root_name(), "DOMDocument"); + let stage = document.stage(); + assert_eq!((stage.width, stage.height, stage.frame_rate), (Some(640.0), Some(480.0), Some(29.97))); + assert_eq!(stage.background_color, Some("#123456")); + let mut timelines = document.timelines(); + let timeline = timelines.next().unwrap(); + assert_eq!(timeline.name(), Some("Scene &custom;"), "declared entities stay literal"); + assert!(timelines.next().is_none()); + let mut layers = timeline.layers(); + let layer = layers.next().unwrap(); + assert_eq!(layer.name(), Some("Background")); + assert_eq!(layer.layer_type(), Some("normal")); + assert_eq!(layer.parent_layer_index(), Some(0)); + assert_eq!((layer.visible(), layer.locked(), layer.outline()), (Some(false), Some(true), Some(true))); + assert_eq!(layer.color(), Some("#abcdef")); + assert_eq!(layer.height_multiplier(), Some(2)); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(4), Some(3))); + assert_eq!((frame.name(), frame.label_type(), frame.tween_type()), (Some("Intro"), Some("name"), Some("motion"))); + assert_eq!(frame.element().child("elements").unwrap().child("Shape").unwrap().name, "Shape"); + } + + #[test] + fn borrowed_timeline_views_accept_compatible_element_adapters() { + #[derive(Debug)] + struct AppElement { + name: String, + attributes: Vec<(String, String)>, + children: Vec, + } + + impl XflElement for AppElement { + type Elements<'a> = std::slice::Iter<'a, Self>; + + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attributes.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + + fn elements(&self) -> Self::Elements<'_> { + self.children.iter() + } + + fn text_content(&self) -> Cow<'_, str> { + Cow::Borrowed("") + } + } + + fn element(name: &str, attributes: &[(&str, &str)], children: Vec) -> AppElement { + AppElement { + name: name.to_string(), + attributes: attributes.iter().map(|(key, value)| ((*key).to_string(), (*value).to_string())).collect(), + children, + } + } + + let root = element( + "x:DOMDocument", + &[], + vec![element( + "x:timelines", + &[], + vec![element( + "x:DOMTimeline", + &[("name", "Old"), ("name", "Scene")], + vec![element( + "x:layers", + &[], + vec![element( + "x:DOMLayer", + &[("name", "Old"), ("name", "Layer"), ("color", "#abcdef"), ("visible", "false")], + vec![element( + "x:frames", + &[], + vec![element( + "x:DOMFrame", + &[ + ("index", "999"), + ("index", "3"), + ("duration", "2"), + ("name", "Intro"), + ("labelType", "name"), + ("tweenType", "motion"), + ], + vec![], + )], + )], + )], + )], + )], + )], + ); + let timeline_element = root.child("timelines").unwrap().child("DOMTimeline").unwrap(); + let timeline = Timeline::new(timeline_element); + assert_eq!(timeline.name(), Some("Scene")); + let layer = timeline.layers().next().unwrap(); + assert_eq!(layer.name(), Some("Layer")); + assert_eq!(layer.color(), Some("#abcdef")); + assert_eq!(layer.visible(), Some(false)); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(3), Some(2))); + assert_eq!((frame.name(), frame.label_type(), frame.tween_type()), (Some("Intro"), Some("name"), Some("motion"))); + } + + #[test] + fn uses_last_duplicate_attribute_like_the_legacy_xfl_adapter() { + let document = Document::parse(br##""##).unwrap(); + assert_eq!(document.stage().width, Some(2.0)); + } + + #[test] + fn preserves_lenient_doctype_entities_and_strict_end_tag_behavior() { + let document = Document::parse(br##"tail"##).unwrap(); + assert_eq!(document.stage().width, None); + assert!(Document::parse(b"").is_err()); + } + + #[test] + fn applies_the_existing_xfl_depth_and_attribute_budgets() { + let too_deep = format!("{}{}", "".repeat(MAX_XML_DEPTH + 1), "".repeat(MAX_XML_DEPTH + 1)); + assert!(matches!(Document::parse(too_deep.as_bytes()), Err(XmlError::TooDeep(_)))); + + let mut too_many_attrs = String::from(""); + assert!(matches!(Document::parse(too_many_attrs.as_bytes()), Err(XmlError::TooManyAttrs(_)))); + } + + #[test] + fn projects_neutral_schema_fields_and_returns_the_xml_tree_by_move() { + let document = Document::parse( + br##""##, + ) + .unwrap(); + let (model, root) = document.into_parts(ModelLimits { max_timelines: 1, max_layers_per_timeline: 1 }); + assert_eq!(model.stage, StageModel { width: Some(640.0), height: None, frame_rate: None, has_background_color: true }); + assert_eq!(model.timelines.len(), 1); + let layer = &model.timelines[0].layers[0]; + assert_eq!(layer.layer_type, LayerType::Mask); + assert_eq!(layer.visible, Some(false)); + assert_eq!(layer.frames[0], FrameModel { index: Some(7), duration: Some(2), is_comment: true, tween_type: TweenType::Shape }); + assert_eq!(root.attr("width"), Some("640")); + assert_eq!(root.child("timelines").unwrap().child("DOMTimeline").unwrap().attr("name"), Some("Scene")); + } + + #[test] + fn projects_symbol_timeline_under_the_native_symbol_wrapper() { + let document = Document::parse(b"").unwrap(); + let (model, _) = document.into_parts(ModelLimits { max_timelines: 10, max_layers_per_timeline: 10 }); + assert!(model.timelines.is_empty()); + assert_eq!(model.symbol_timeline.unwrap().layers[0].frames[0].index, Some(1)); + } + + #[test] + fn recognizes_prefixed_xfl_timeline_elements_by_local_name() { + let document = Document::parse( + b"", + ) + .unwrap(); + { + let mut timelines = document.timelines(); + let timeline = timelines.next().unwrap(); + assert!(timelines.next().is_none()); + let mut layers = timeline.layers(); + let layer = layers.next().unwrap(); + assert!(layers.next().is_none()); + let frame = layer.frames().next().unwrap(); + assert_eq!((frame.index(), frame.duration()), (Some(4), Some(2))); + } + let (model, _) = document.into_parts(ModelLimits { max_timelines: 1, max_layers_per_timeline: 1 }); + assert_eq!(model.timelines[0].layers[0].frames[0].index, Some(4)); + + let symbol = + Document::parse(b"").unwrap(); + assert!(symbol.symbol_timeline().is_some()); + } + + #[test] + fn reads_prefixed_publish_settings_children_by_local_name() { + let document = Document::parse( + b"3com.example.Main", + ) + .unwrap(); + let settings = document.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("com.example.Main")); + } + + #[test] + fn selects_current_publish_profile_and_uses_native_value_strings() { + let document = Document::parse( + br#"2OldClass 3 com.example.Main "#, + ) + .unwrap(); + let settings = document.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("com.example.Main")); + } + + #[test] + fn publish_settings_fall_back_to_first_profile_then_root() { + let first = Document::parse( + br#"23"#, + ) + .unwrap(); + assert_eq!(first.publish_settings().action_script_version.as_deref(), Some("2")); + + let root = Document::parse( + br#" 3 RootClass"#, + ) + .unwrap(); + let settings = root.publish_settings(); + assert_eq!(settings.action_script_version.as_deref(), Some("3")); + assert_eq!(settings.document_class.as_deref(), Some("RootClass")); + } + + #[test] + fn reads_symbol_library_entries_and_native_symbol_metadata() { + let document = Document::parse( + br#""#, + ) + .unwrap(); + let includes: Vec<_> = symbol_includes(document.root()).map(SymbolInclude::href).collect(); + assert_eq!(includes, [Some("LIBRARY/Shape.xml"), Some("LIBRARY/Button.xml")]); + let include = symbol_includes(document.root()).next().unwrap(); + assert_eq!(include.element().local_name(), "Include"); + let folders: Vec<_> = library_folders(document.root()).map(LibraryFolder::name).collect(); + assert_eq!(folders, [Some("Characters/Hero")]); + let folder = library_folders(document.root()).next().unwrap(); + assert_eq!(folder.element().local_name(), "DOMFolderItem"); + + let symbol = Document::parse( + br#""#, + ) + .unwrap(); + let item = SymbolItem::new(symbol.root()); + assert_eq!(item.element().local_name(), "DOMSymbolItem"); + assert_eq!(item.name(), Some("Characters/Final"), "the last duplicate attribute wins"); + assert_eq!(item.symbol_type(), Some("graphic")); + assert_eq!(item.linkage_export_for_action_script(), Some("true")); + assert_eq!(item.linkage_class_name(), Some("example.Hero")); + assert_eq!(item.linkage_identifier(), Some("legacy.Hero")); + assert_eq!(item.linkage_base_class(), Some("flash.display.MovieClip")); + assert_eq!( + (item.scale_grid_left(), item.scale_grid_right(), item.scale_grid_top(), item.scale_grid_bottom()), + (Some(10.0), Some(90.0), Some(5.0), Some(75.0)) + ); + assert!(item.has_scale_grid()); + assert!(item.timeline().is_some()); + + let malformed = Document::parse(br#""#).unwrap(); + let malformed = SymbolItem::new(malformed.root()); + assert!(malformed.has_scale_grid(), "attribute presence remains observable when its value is malformed"); + assert_eq!(malformed.scale_grid_left(), None); + + let absent = Document::parse(b"").unwrap(); + assert!(!SymbolItem::new(absent.root()).has_scale_grid()); + } +} diff --git a/crates/xfl/src/filters.rs b/crates/xfl/src/filters.rs new file mode 100644 index 0000000000..ef29a3707f --- /dev/null +++ b/crates/xfl/src/filters.rs @@ -0,0 +1,239 @@ +//! Borrowed views of native XFL filter records. +//! +//! This module parses the wire-level filter names, fields, and gradient-ramp entries. Consumers +//! remain responsible for mapping those values into their own rendering/filter models. + +use crate::shape::{self, Color, XflElement, boolean, integer, number}; + +/// Native filter variants understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterKind { + Blur, + DropShadow, + Glow, + AdjustColor, + Bevel, + GradientGlow, + GradientBevel, +} + +/// Bevel/glow placement recorded by the native `type` attribute. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FilterSide { + Inner, + Outer, + Full, +} + +/// The native `` list on an element, preserving source order and unknown records. +#[derive(Clone, Copy, Debug)] +pub struct FilterList<'a, E: XflElement> { + wrapper: Option<&'a E>, +} + +impl<'a, E: XflElement> FilterList<'a, E> { + pub fn new(element: &'a E) -> Self { + Self { wrapper: element.child("filters") } + } + + pub fn iter(&self) -> impl Iterator> + 'a { + let wrapper = self.wrapper; + wrapper.into_iter().flat_map(XflElement::elements).map(|element| Filter { element }) + } +} + +/// One native filter record. Unknown records are retained so the consumer can report/skip them. +#[derive(Clone, Copy, Debug)] +pub struct Filter<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Filter<'a, E> { + pub fn kind(&self) -> Option { + match self.element.local_name() { + "BlurFilter" => Some(FilterKind::Blur), + "DropShadowFilter" => Some(FilterKind::DropShadow), + "GlowFilter" => Some(FilterKind::Glow), + "AdjustColorFilter" => Some(FilterKind::AdjustColor), + "BevelFilter" => Some(FilterKind::Bevel), + "GradientGlowFilter" => Some(FilterKind::GradientGlow), + "GradientBevelFilter" => Some(FilterKind::GradientBevel), + _ => None, + } + } + + /// XFL treats filters as enabled unless explicitly set to false. + pub fn enabled(&self) -> bool { + boolean(self.element, "enabled") != Some(false) + } + + /// Quality is a native integer in the range 1 through 3, defaulting to 1. + pub fn quality(&self) -> u8 { + integer(self.element, "quality").unwrap_or(1).clamp(1, 3) as u8 + } + + pub fn blur_x(&self) -> Option { + number(self.element, "blurX") + } + + pub fn blur_y(&self) -> Option { + number(self.element, "blurY") + } + + pub fn strength(&self) -> Option { + number(self.element, "strength") + } + + pub fn angle(&self) -> Option { + number(self.element, "angle") + } + + pub fn distance(&self) -> Option { + number(self.element, "distance") + } + + pub fn brightness(&self) -> Option { + number(self.element, "brightness") + } + + pub fn contrast(&self) -> Option { + number(self.element, "contrast") + } + + pub fn saturation(&self) -> Option { + number(self.element, "saturation") + } + + pub fn hue(&self) -> Option { + number(self.element, "hue") + } + + pub fn inner(&self) -> Option { + boolean(self.element, "inner") + } + + pub fn knockout(&self) -> Option { + boolean(self.element, "knockout") + } + + pub fn hide_object(&self) -> Option { + boolean(self.element, "hideObject") + } + + pub fn side(&self) -> Option { + match self.element.attr("type").map(str::trim) { + Some("inner") => Some(FilterSide::Inner), + Some("outer") => Some(FilterSide::Outer), + Some("full") => Some(FilterSide::Full), + _ => None, + } + } + + pub fn color(&self) -> Color { + shape::color(self.element, "color", "alpha") + } + + pub fn shadow_color(&self) -> Color { + shape::color(self.element, "shadowColor", "shadowAlpha") + } + + /// Explicit highlight color, absent when the native attribute is missing so consumers can + /// apply the format-specific white highlight default. + pub fn highlight_color(&self) -> Option { + self.element.attr("highlightColor").map(|_| shape::color(self.element, "highlightColor", "highlightAlpha")) + } + + pub fn highlight_alpha(&self) -> Option { + number(self.element, "highlightAlpha") + } + + /// Native gradient entries, either direct children or one wrapper level below the filter. + pub fn ramp_entries(&self) -> impl Iterator> + 'a { + self.element + .elements() + .flat_map(|child| std::iter::once(child).chain(child.elements())) + .filter(|entry| entry.local_name() == "GradientEntry") + .map(|element| RampEntry { element }) + } +} + +/// One XFL gradient-ramp entry. +#[derive(Clone, Copy, Debug)] +pub struct RampEntry<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> RampEntry<'a, E> { + pub fn ratio(&self) -> Option { + number(self.element, "ratio") + } + + pub fn color(&self) -> Color { + shape::color(self.element, "color", "alpha") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn recognizes_filter_kinds_and_preserves_unknown_entries_and_order() { + let root = parse(br##""##); + let filters: Vec<_> = FilterList::new(&root).iter().collect(); + assert_eq!(filters.len(), 4); + assert_eq!(filters[0].kind(), Some(FilterKind::Blur)); + assert_eq!(filters[1].kind(), Some(FilterKind::Glow)); + assert!(!filters[1].enabled()); + assert_eq!(filters[2].kind(), None); + assert_eq!(filters[3].kind(), Some(FilterKind::GradientBevel)); + } + + #[test] + fn reads_native_filter_values_colors_and_gradient_entries_in_order() { + let root = parse( + br##""##, + ); + let filters: Vec<_> = FilterList::new(&root).iter().collect(); + let shadow = &filters[0]; + assert_eq!(shadow.quality(), 3); + assert_eq!( + (shadow.blur_x(), shadow.blur_y(), shadow.strength(), shadow.angle(), shadow.distance()), + (Some(7.5), Some(8.0), Some(1.25), Some(45.0), Some(4.0)) + ); + assert_eq!(shadow.color(), Color { rgb: 0x123456, alpha: 0.5 }); + assert_eq!(shadow.inner(), Some(true)); + assert_eq!(shadow.knockout(), Some(false)); + assert_eq!(shadow.hide_object(), Some(true)); + + let bevel = &filters[1]; + assert_eq!(bevel.side(), Some(FilterSide::Full)); + assert_eq!(bevel.shadow_color(), Color { rgb: 0x010203, alpha: 0.25 }); + assert_eq!(bevel.highlight_color(), Some(Color { rgb: 0xaabbcc, alpha: 0.75 })); + + let ramp: Vec<_> = filters[2].ramp_entries().collect(); + assert_eq!(ramp.iter().map(RampEntry::ratio).collect::>(), [Some(255.0), Some(64.0)]); + assert_eq!(ramp[0].color(), Color { rgb: 0xff0000, alpha: 1.0 }); + } + + #[test] + fn absent_lists_are_empty_and_values_use_shared_wire_validation() { + let root = parse(b""); + assert_eq!(FilterList::new(&root).iter().count(), 0); + + let root = parse(br##""##); + let filter = FilterList::new(&root).iter().next(); + assert_eq!(filter.map(|filter| filter.kind()), None); + let parent = + parse(br##""##); + let filter = FilterList::new(&parent).iter().next().expect("filter entry"); + assert_eq!(filter.kind(), Some(FilterKind::Blur)); + assert_eq!(filter.quality(), 1); + assert_eq!(filter.blur_x(), None); + assert!(!filter.enabled()); + } +} diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 83fdad40be..fbcb3ecc2b 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -23,8 +23,24 @@ use std::cell::Cell; use std::collections::HashMap; +/// Neutral views of the XFL document, timeline, layer and frame schema. +pub mod document; /// XFL's edge-attribute grammar, independent of any consuming application's geometry types. pub mod edges; +/// Borrowed views of native XFL filter records. +pub mod filters; +/// Borrowed views of native XFL media library records. +pub mod media; +/// Borrowed views of native XFL shape and style elements. +pub mod shape; +/// Borrowed views of native XFL shape-hint records. +pub mod shape_hints; +/// Borrowed views of native XFL frame-sound and envelope records. +pub mod sound; +/// Borrowed views of native XFL text-field and text-run schema. +pub mod text; +/// Borrowed views of native XFL tween and custom-ease records. +pub mod tween; /// Largest single entry inflated (bytes). pub const MAX_ENTRY: usize = 256 * 1024 * 1024; @@ -87,6 +103,19 @@ pub struct Archive<'a> { budget: Cell, } +/// The package root selected from an XFL archive's `DOMDocument.xml` paths. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum XflPackageRoot<'a> { + /// A document XML file is directly at the archive root. + Document, + /// The sole eligible top-level folder containing a document. + Folder(&'a str), + /// No document path was found. + Missing, + /// More than one eligible top-level folder contains a document, sorted by name. + Multiple(Vec<&'a str>), +} + const END: u32 = 0x0605_4b50; const END64: u32 = 0x0606_4b50; const LOCATOR64: u32 = 0x0706_4b50; @@ -527,6 +556,25 @@ impl<'a> Archive<'a> { self.entries.keys().map(String::as_str) } + /// Selects the package root from XFL document paths. A root-level document takes precedence; + /// otherwise only a single-level folder is eligible, with macOS metadata excluded. + pub fn xfl_package_root(&self) -> XflPackageRoot<'_> { + if self.entries.contains_key("DOMDocument.xml") { + return XflPackageRoot::Document; + } + let mut folders: Vec<&str> = self + .names() + .filter_map(|name| name.strip_suffix("/DOMDocument.xml")) + .filter(|folder| !folder.contains('/') && *folder != "__MACOSX") + .collect(); + folders.sort_unstable(); + match folders.as_slice() { + [] => XflPackageRoot::Missing, + [folder] => XflPackageRoot::Folder(folder), + _ => XflPackageRoot::Multiple(folders), + } + } + /// How many files and folder entries the archive lists. pub fn counts(&self) -> (usize, usize) { (self.entries.len(), self.folders) diff --git a/crates/xfl/src/media.rs b/crates/xfl/src/media.rs new file mode 100644 index 0000000000..a501e78880 --- /dev/null +++ b/crates/xfl/src/media.rs @@ -0,0 +1,190 @@ +//! Borrowed views of XFL's bitmap, sound, and video library-item records. +//! +//! These views expose native XFL metadata and archive member names. Decoding those bytes and +//! mapping the records into an application's media model remain consumer responsibilities. + +use crate::shape::XflElement; + +/// Archive member named by a library item's native `href` attribute. +pub fn library_member(href: &str) -> String { + format!("LIBRARY/{href}") +} + +/// Archive member named by an XFL item's native `*DataHRef` attribute. +pub fn data_member(href: &str) -> String { + format!("bin/{href}") +} + +/// A packaged `./...` external video source, normalized to ZIP's slash separators. +pub fn packaged_external_member(path: &str) -> Option { + path.strip_prefix("./").map(|path| path.replace('\\', "/")) +} + +/// Media library records in an XFL document, in source order. +#[derive(Clone, Copy, Debug)] +pub struct Catalog<'a, E: XflElement> { + media: Option<&'a E>, +} + +impl<'a, E: XflElement> Catalog<'a, E> { + pub fn new(document: &'a E) -> Self { + Self { media: document.child("media") } + } + + pub fn bitmaps(&self) -> impl Iterator> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMBitmapItem")).map(|element| Bitmap { element }) + } + + pub fn sounds(&self) -> impl Iterator> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMSoundItem")).map(|element| Sound { element }) + } + + pub fn videos(&self) -> impl Iterator> + 'a { + let media = self.media; + media.into_iter().flat_map(|media| media.elements_named("DOMVideoItem")).map(|element| Video { element }) + } +} + +/// Native bitmap library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Bitmap<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Bitmap<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("bitmapDataHRef") + } + + pub fn allow_smoothing(&self) -> Option { + self.element.attr("allowSmoothing").map(|value| value.trim() == "true") + } +} + +/// Native sound library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Sound<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Sound<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("soundDataHRef") + } +} + +/// Native video library metadata. +#[derive(Clone, Copy, Debug)] +pub struct Video<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Video<'a, E> { + pub fn name(&self) -> Option<&'a str> { + self.element.attr("name") + } + + pub fn href(&self) -> Option<&'a str> { + self.element.attr("href") + } + + pub fn external_path(&self) -> Option<&'a str> { + self.element.attr("sourceExternalFilepath") + } + + pub fn data_href(&self) -> Option<&'a str> { + self.element.attr("videoDataHRef") + } + + pub fn length(&self) -> Option { + number(self.element, "length") + } + + pub fn frame_count(&self) -> Option { + number(self.element, "frameCount") + } + + pub fn frames_per_second(&self) -> Option { + number(self.element, "fps") + } +} + +fn number(element: &impl XflElement, name: &str) -> Option { + element.attr(name)?.trim().parse::().ok().filter(|value| value.is_finite()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::Options::default().parse(source).unwrap() + } + + #[test] + fn reads_native_media_metadata_in_order_and_ignores_other_records() { + let root = parse( + br#" + + + + + + "#, + ); + let catalog = Catalog::new(&root); + let bitmaps: Vec<_> = catalog.bitmaps().collect(); + assert_eq!(bitmaps.len(), 2); + assert_eq!(bitmaps[0].name(), Some("folder/a")); + assert_eq!(bitmaps[0].href(), Some("a.png")); + assert_eq!(bitmaps[0].data_href(), Some("Bitmap 1")); + assert_eq!(bitmaps[0].allow_smoothing(), Some(false)); + assert_eq!( + catalog.sounds().next().map(|item| (item.name(), item.href(), item.data_href())), + Some((Some("s"), Some("s.wav"), Some("Sound 1"))) + ); + let video = catalog.videos().next().expect("video record"); + assert_eq!(video.external_path(), Some("./LIBRARY/v.flv")); + assert_eq!(video.data_href(), Some("Video 1")); + assert_eq!(video.length(), Some(3.5)); + assert_eq!(video.frame_count(), Some(70.0)); + assert_eq!(video.frames_per_second(), Some(20.0)); + } + + #[test] + fn missing_or_invalid_media_metadata_stays_optional() { + let root = parse(br#""#); + let video = Catalog::new(&root).videos().next().expect("video record"); + assert_eq!(video.name(), Some("v")); + assert_eq!(video.length(), None); + assert_eq!(video.frames_per_second(), None); + let empty = parse(b""); + assert_eq!(Catalog::new(&empty).bitmaps().count(), 0); + } + + #[test] + fn native_media_references_resolve_to_the_legacy_archive_members() { + assert_eq!(library_member("folder/a.png"), "LIBRARY/folder/a.png"); + assert_eq!(data_member("Bitmap 1"), "bin/Bitmap 1"); + assert_eq!(packaged_external_member("./LIBRARY\\v.flv").as_deref(), Some("LIBRARY/v.flv")); + assert_eq!(packaged_external_member("/outside/v.flv"), None); + } +} diff --git a/crates/xfl/src/shape.rs b/crates/xfl/src/shape.rs new file mode 100644 index 0000000000..173359a524 --- /dev/null +++ b/crates/xfl/src/shape.rs @@ -0,0 +1,675 @@ +//! Borrowed views of native XFL shape and style elements. +//! +//! These views recognize XFL's element names and attribute grammar without depending on an +//! application's geometry, paint, or animation types. They work with `craft_xml::El` and with +//! compatible borrowed element adapters implemented by consumers. + +use crate::edges::{self, Segment}; +use std::borrow::Cow; + +/// An element source used by the borrowed XFL schema views. +/// +/// Consumers with an existing XML facade can implement this small interface and use the same +/// XFL parser without converting or reparsing their tree. Attribute lookup must return the last +/// occurrence when an XML document repeats an attribute, matching the native XFL reader's +/// historical behavior. +pub trait XflElement { + /// Iterator type for direct child elements. + type Elements<'a>: Iterator + where + Self: 'a; + + /// The element's local name, with any namespace prefix removed. + fn local_name(&self) -> &str; + + /// The last attribute with this exact name. + fn attr(&self, name: &str) -> Option<&str>; + + /// Direct child elements in document order. + fn elements(&self) -> Self::Elements<'_>; + + /// This element's direct character data, with XML references resolved. + fn text_content(&self) -> Cow<'_, str>; + + /// The first direct child whose local name matches. + fn child(&self, name: &str) -> Option<&Self> { + self.elements().find(|element| element.local_name() == name) + } + + /// Direct children whose local name matches, in document order. + fn elements_named<'a>(&'a self, name: &'a str) -> impl Iterator + 'a { + self.elements().filter(move |element| element.local_name() == name) + } +} + +/// Direct child elements of `craft_xml::El`, used by its `XflElement` implementation. +pub struct XmlElements<'a> { + nodes: std::slice::Iter<'a, craft_xml::Node>, +} + +impl<'a> Iterator for XmlElements<'a> { + type Item = &'a craft_xml::El; + + fn next(&mut self) -> Option { + self.nodes.find_map(|node| match node { + craft_xml::Node::El(element) => Some(element), + _ => None, + }) + } +} + +impl XflElement for craft_xml::El { + type Elements<'a> = XmlElements<'a>; + + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + + fn attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + + fn elements(&self) -> Self::Elements<'_> { + XmlElements { nodes: self.children.iter() } + } + + fn text_content(&self) -> Cow<'_, str> { + self.text() + } +} + +/// XFL matrix coefficients, in the native units stored in XML. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix { + pub a: f32, + pub b: f32, + pub c: f32, + pub d: f32, + pub tx: f32, + pub ty: f32, +} + +/// A color encoded by an XFL color attribute and its optional alpha attribute. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Color { + pub rgb: u32, + pub alpha: f32, +} + +/// A native XFL instance color record (``). +/// +/// The view parses the authored tint, brightness, channel multipliers and offsets but does not +/// choose a consumer's color-effect style or clamp values into an application's model. Offsets +/// remain in XFL's native 0–255 scale. Invalid or non-finite channel multipliers use 1, and +/// invalid or non-finite offsets use 0, matching the historical AniCraft importer. +#[derive(Clone, Copy, Debug)] +pub struct NativeColorEffect<'a, E: XflElement> { + element: &'a E, +} + +impl Matrix { + /// The matrix used when an XFL element omits its transform. + pub const IDENTITY: Matrix = Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 }; +} + +impl<'a, E: XflElement> NativeColorEffect<'a, E> { + /// Views a native XFL `Color` element without converting it to an application's model. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// The native tint amount, when authored. + pub fn tint_multiplier(&self) -> Option { + number(self.element, "tintMultiplier") + } + + /// The native tint color. Missing or malformed color values use black as other XFL colors do. + pub fn tint_color(&self) -> Color { + color(self.element, "tintColor", "__none") + } + + /// The native brightness value, when authored. + pub fn brightness(&self) -> Option { + number(self.element, "brightness") + } + + /// Red, green, blue, and alpha multipliers, with identity defaults for absent or invalid data. + pub fn multipliers(&self) -> [f32; 4] { + ["redMultiplier", "greenMultiplier", "blueMultiplier", "alphaMultiplier"].map(|name| number(self.element, name).unwrap_or(1.0)) + } + + /// Red, green, blue, and alpha offsets in XFL's native 0–255 scale. + pub fn offsets(&self) -> [f32; 4] { + ["redOffset", "greenOffset", "blueOffset", "alphaOffset"].map(|name| number(self.element, name).unwrap_or(0.0)) + } +} + +pub(crate) fn number(element: &impl XflElement, name: &str) -> Option { + element.attr(name)?.trim().parse::().ok().filter(|value| value.is_finite()) +} + +pub(crate) fn integer(element: &impl XflElement, name: &str) -> Option { + element.attr(name)?.trim().parse::().ok() +} + +pub(crate) fn boolean(element: &impl XflElement, name: &str) -> Option { + element.attr(name).map(|value| value.trim() == "true") +} + +/// Parses XFL's hexadecimal color and alpha attributes. Missing or malformed colors use black; +/// missing, malformed, or non-finite alpha uses full opacity, matching the legacy importer. +pub fn color(element: &impl XflElement, color_attribute: &str, alpha_attribute: &str) -> Color { + color_from_attributes(element.attr(color_attribute), element.attr(alpha_attribute)) +} + +/// Parses native color and alpha strings after a consumer has read them from its own element +/// adapter. This keeps wire-value interpretation shared even when an application already has a +/// borrowed schema view for the containing element. +pub fn color_from_attributes(color: Option<&str>, alpha: Option<&str>) -> Color { + let rgb = color.and_then(|value| u32::from_str_radix(value.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0); + let alpha = alpha.and_then(|value| value.trim().parse::().ok()).filter(|value| value.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0); + Color { rgb, alpha } +} + +/// Reads the native `` transform. +/// +/// Each absent, malformed, or non-finite coefficient uses its identity default independently. +/// This preserves the prior AniCraft reader's `Element::f32` behavior, including retaining other +/// valid coefficients when one coefficient is invalid. +pub fn matrix(element: &impl XflElement) -> Matrix { + let Some(matrix) = element.child("matrix").and_then(|wrapper| wrapper.child("Matrix")) else { + return Matrix::IDENTITY; + }; + Matrix { + a: number(matrix, "a").unwrap_or(1.0), + b: number(matrix, "b").unwrap_or(0.0), + c: number(matrix, "c").unwrap_or(0.0), + d: number(matrix, "d").unwrap_or(1.0), + tx: number(matrix, "tx").unwrap_or(0.0), + ty: number(matrix, "ty").unwrap_or(0.0), + } +} + +/// A native `DOMShape` or drawing shape and its XFL style tables. +#[derive(Clone, Copy, Debug)] +pub struct Shape<'a, E: XflElement> { + element: &'a E, +} + +/// Kind of native drawable primitive stored in XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PrimitiveKind { + Rectangle, + Oval, +} + +/// Native rectangle or oval object, including its native style definitions. +#[derive(Clone, Copy, Debug)] +pub struct Primitive<'a, E: XflElement> { + element: &'a E, + kind: PrimitiveKind, +} + +impl<'a, E: XflElement> Primitive<'a, E> { + /// Views a supported native primitive by its local element name. + pub fn new(element: &'a E) -> Option { + let kind = match element.local_name() { + "DOMRectangleObject" => PrimitiveKind::Rectangle, + "DOMOvalObject" => PrimitiveKind::Oval, + _ => return None, + }; + Some(Self { element, kind }) + } + + pub fn kind(&self) -> PrimitiveKind { + self.kind + } + + pub fn x(&self) -> Option { + number(self.element, "x") + } + + pub fn y(&self) -> Option { + number(self.element, "y") + } + + pub fn width(&self) -> Option { + number(self.element, "objectWidth") + } + + pub fn height(&self) -> Option { + number(self.element, "objectHeight") + } + + pub fn top_left_radius(&self) -> Option { + number(self.element, "topLeftRadius") + } + + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + pub fn fill(&self) -> Option> { + self.element.child("fill")?.elements().next().map(|element| Fill { element }) + } + + pub fn stroke(&self) -> Option> { + self.element.child("stroke")?.elements().next().map(|element| Stroke { element }) + } +} + +impl<'a, E: XflElement> Shape<'a, E> { + /// Views an element as an XFL shape when its local name is `DOMShape`. + pub fn new(element: &'a E) -> Option { + (element.local_name() == "DOMShape").then_some(Self { element }) + } + + /// Native shape transform. + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + /// Whether Animate stores the shape as a drawing object. + pub fn is_drawing_object(&self) -> Option { + boolean(self.element, "isDrawingObject") + } + + /// Fill styles, preserving their native order and index values. + pub fn fills(&self) -> impl Iterator> + '_ { + self.element.child("fills").into_iter().flat_map(|table| table.elements()).map(|element| FillStyle { element }) + } + + /// Stroke styles, preserving their native order and index values. + pub fn strokes(&self) -> impl Iterator> + '_ { + self.element.child("strokes").into_iter().flat_map(|table| table.elements()).map(|element| StrokeStyle { element }) + } + + /// Native edge records, preserving malformed and unknown data for consumer policy. + pub fn edges(&self) -> impl Iterator> + '_ { + self.element.child("edges").into_iter().flat_map(|table| table.elements_named("Edge")).map(|element| Edge { element }) + } +} + +/// A native `FillStyle` entry. +#[derive(Clone, Copy, Debug)] +pub struct FillStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> FillStyle<'a, E> { + pub fn index(&self) -> Option { + integer(self.element, "index") + } + + /// The first native definition element inside this table entry. + pub fn definition(&self) -> Option> { + self.element.elements().next().map(|element| Fill { element }) + } +} + +/// Native fill definitions understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FillKind { + SolidColor, + LinearGradient, + RadialGradient, + Bitmap, + Other, +} + +/// A native XFL fill definition. +#[derive(Clone, Copy, Debug)] +pub struct Fill<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Fill<'a, E> { + /// Views any native fill-definition element, including fills nested in primitives or strokes. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// Underlying native definition element for consumers that map it into application types. + pub fn element(&self) -> &'a E { + self.element + } + + pub fn kind(&self) -> FillKind { + match self.element.local_name() { + "SolidColor" => FillKind::SolidColor, + "LinearGradient" => FillKind::LinearGradient, + "RadialGradient" => FillKind::RadialGradient, + "BitmapFill" => FillKind::Bitmap, + _ => FillKind::Other, + } + } + + pub fn color(&self) -> Option<&str> { + self.element.attr("color") + } + + pub fn color_value(&self) -> Color { + color(self.element, "color", "alpha") + } + + pub fn alpha(&self) -> Option { + number(self.element, "alpha") + } + + pub fn matrix(&self) -> Matrix { + matrix(self.element) + } + + pub fn spread_method(&self) -> Option<&str> { + self.element.attr("spreadMethod") + } + + pub fn interpolation_method(&self) -> Option<&str> { + self.element.attr("interpolationMethod") + } + + pub fn focal_point_ratio(&self) -> Option { + number(self.element, "focalPointRatio") + } + + pub fn bitmap_path(&self) -> Option<&str> { + self.element.attr("bitmapPath") + } + + pub fn bitmap_is_clipped(&self) -> Option { + boolean(self.element, "bitmapIsClipped") + } + + /// Gradient entries, preserving source order and raw native ratios. + pub fn gradient_entries(&self) -> impl Iterator> + '_ { + self.element.elements_named("GradientEntry").map(|element| GradientEntry { element }) + } +} + +/// A native gradient ramp entry. +#[derive(Clone, Copy, Debug)] +pub struct GradientEntry<'a, E: XflElement> { + element: &'a E, +} + +impl GradientEntry<'_, E> { + pub fn ratio(&self) -> Option { + number(self.element, "ratio") + } + + pub fn color(&self) -> Option<&str> { + self.element.attr("color") + } + + pub fn color_value(&self) -> Color { + color(self.element, "color", "alpha") + } + + pub fn alpha(&self) -> Option { + number(self.element, "alpha") + } +} + +/// Native stroke definitions understood by XFL. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StrokeKind { + Solid, + Dashed, + Dotted, + Ragged, + Stipple, + Hatched, + Other, +} + +/// A native `StrokeStyle` table entry. +#[derive(Clone, Copy, Debug)] +pub struct StrokeStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> StrokeStyle<'a, E> { + pub fn index(&self) -> Option { + integer(self.element, "index") + } + + /// The first native definition element inside this table entry. + pub fn definition(&self) -> Option> { + self.element.elements().next().map(|element| Stroke { element }) + } +} + +/// A native XFL stroke definition. +#[derive(Clone, Copy, Debug)] +pub struct Stroke<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> Stroke<'a, E> { + /// Views a native stroke-definition element. + pub fn new(element: &'a E) -> Self { + Self { element } + } + + /// Underlying native definition element for consumers that map it into application types. + pub fn element(&self) -> &'a E { + self.element + } + + pub fn kind(&self) -> StrokeKind { + match self.element.local_name() { + "SolidStroke" => StrokeKind::Solid, + "DashedStroke" => StrokeKind::Dashed, + "DottedStroke" => StrokeKind::Dotted, + "RaggedStroke" => StrokeKind::Ragged, + "StippleStroke" => StrokeKind::Stipple, + "HatchedStroke" => StrokeKind::Hatched, + _ => StrokeKind::Other, + } + } + + pub fn weight(&self) -> Option { + number(self.element, "weight") + } + + pub fn caps(&self) -> Option<&str> { + self.element.attr("caps") + } + + pub fn joints(&self) -> Option<&str> { + self.element.attr("joints") + } + + pub fn miter_limit(&self) -> Option { + number(self.element, "miterLimit") + } + + pub fn dash1(&self) -> Option { + number(self.element, "dash1") + } + + pub fn dash2(&self) -> Option { + number(self.element, "dash2") + } + + pub fn dot_space(&self) -> Option { + number(self.element, "dotSpace") + } + + /// The first fill definition nested in the stroke. + pub fn fill(&self) -> Option> { + self.element.child("fill")?.elements().next().map(|element| Fill { element }) + } +} + +/// A native `` record and its style indices. +#[derive(Clone, Copy, Debug)] +pub struct Edge<'a, E: XflElement> { + element: &'a E, +} + +impl Edge<'_, E> { + pub fn fill_style0(&self) -> Option { + integer(self.element, "fillStyle0") + } + + pub fn fill_style1(&self) -> Option { + integer(self.element, "fillStyle1") + } + + pub fn stroke_style(&self) -> Option { + integer(self.element, "strokeStyle") + } + + pub fn encoded_segments(&self) -> Option<&str> { + self.element.attr("edges") + } + + /// Parsed XFL path segments, using the shared bounded edge grammar. + pub fn segments(&self) -> Vec { + self.encoded_segments().map(edges::parse_edge_segments).unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::Options::default().parse(source).unwrap() + } + + #[test] + fn reads_prefixed_shape_fill_stroke_and_edge_schema() { + let root = parse(br##" + + + + + + + "##); + + let shape = Shape::new(&root).unwrap(); + assert_eq!(shape.matrix(), Matrix { a: 2.0, b: 0.0, c: 0.0, d: 1.0, tx: 12.0, ty: 0.0 }); + assert_eq!(shape.is_drawing_object(), Some(false)); + let fills: Vec<_> = shape.fills().collect(); + assert_eq!(fills.iter().map(FillStyle::index).collect::>(), [Some(1), Some(2)]); + let gradient = fills[0].definition().unwrap(); + assert_eq!(gradient.kind(), FillKind::LinearGradient); + assert_eq!(gradient.spread_method(), Some("reflect")); + assert_eq!(gradient.interpolation_method(), Some("linearRGB")); + assert_eq!(gradient.gradient_entries().map(|entry| entry.ratio()).collect::>(), [Some(0.0), Some(255.0)]); + let bitmap = fills[1].definition().unwrap(); + assert_eq!(bitmap.kind(), FillKind::Bitmap); + assert_eq!(bitmap.bitmap_path(), Some("Library/a.png")); + assert_eq!(bitmap.bitmap_is_clipped(), Some(true)); + + let stroke_style = shape.strokes().next().unwrap(); + let stroke = stroke_style.definition().unwrap(); + assert_eq!(stroke.kind(), StrokeKind::Dashed); + assert_eq!(stroke.weight(), Some(2.0)); + assert_eq!((stroke.dash1(), stroke.dash2()), (Some(8.0), Some(3.0))); + assert_eq!(stroke.fill().unwrap().color(), Some("#abcdef")); + let color = stroke.fill().unwrap().color_value(); + assert_eq!(color, Color { rgb: 0xabcdef, alpha: 1.0 }); + + let edge = shape.edges().next().unwrap(); + assert_eq!((edge.fill_style0(), edge.fill_style1(), edge.stroke_style()), (Some(2), Some(1), Some(3))); + assert_eq!(edge.segments().len(), 1); + } + + #[test] + fn duplicate_attributes_use_last_value_and_invalid_numbers_are_absent() { + let root = parse(b""); + let shape = Shape::new(&root).unwrap(); + assert_eq!(shape.is_drawing_object(), Some(true)); + assert_eq!(shape.matrix(), Matrix { tx: 12.0, ..Matrix::IDENTITY }); + let fill = shape.fills().next().unwrap(); + assert_eq!(fill.index(), Some(4)); + let fill = fill.definition().unwrap(); + assert_eq!(fill.alpha(), None); + assert_eq!(fill.color_value(), Color { rgb: 0, alpha: 1.0 }); + } + + #[test] + fn color_attribute_values_keep_native_defaults_and_clamping() { + assert_eq!(color_from_attributes(Some(" #123456 "), Some("0.4")), Color { rgb: 0x123456, alpha: 0.4 }); + assert_eq!(color_from_attributes(Some("invalid"), Some("NaN")), Color { rgb: 0, alpha: 1.0 }); + assert_eq!(color_from_attributes(Some("#abcdef"), Some("2")), Color { rgb: 0xabcdef, alpha: 1.0 }); + assert_eq!(color_from_attributes(None, Some("-1")), Color { rgb: 0, alpha: 0.0 }); + } + + #[test] + fn style_table_views_keep_the_legacy_first_child_and_index_behavior() { + let root = parse(b""); + let shape = Shape::new(&root).unwrap(); + let fill_style = shape.fills().next().unwrap(); + assert_eq!(fill_style.index(), Some(5)); + assert_eq!(fill_style.definition().map(|fill| fill.kind()), Some(FillKind::SolidColor)); + let stroke_style = shape.strokes().next().unwrap(); + assert_eq!(stroke_style.index(), Some(6)); + assert_eq!(stroke_style.definition().map(|stroke| stroke.kind()), Some(StrokeKind::Solid)); + } + + #[test] + fn an_application_element_adapter_can_use_the_same_views() { + #[derive(Debug)] + struct AppElement { + name: String, + attrs: Vec<(String, String)>, + children: Vec, + } + impl XflElement for AppElement { + type Elements<'a> = std::slice::Iter<'a, AppElement>; + fn local_name(&self) -> &str { + self.name.rsplit(':').next().unwrap_or(&self.name) + } + fn attr(&self, name: &str) -> Option<&str> { + self.attrs.iter().rev().find(|(key, _)| key == name).map(|(_, value)| value.as_str()) + } + fn elements(&self) -> Self::Elements<'_> { + self.children.iter() + } + fn text_content(&self) -> Cow<'_, str> { + Cow::Borrowed("") + } + } + let app = AppElement { name: "x:DOMShape".into(), attrs: vec![("isDrawingObject".into(), "true".into())], children: Vec::new() }; + assert_eq!(Shape::new(&app).unwrap().is_drawing_object(), Some(true)); + } + + #[test] + fn reads_native_rectangle_and_oval_geometry_and_styles() { + let root = parse(br##""##); + let primitive = Primitive::new(&root).unwrap(); + assert_eq!(primitive.kind(), PrimitiveKind::Rectangle); + assert_eq!( + (primitive.x(), primitive.y(), primitive.width(), primitive.height(), primitive.top_left_radius()), + (Some(-2.0), Some(3.0), Some(20.0), Some(10.0), Some(4.0)) + ); + assert_eq!(primitive.matrix().tx, 7.0); + assert_eq!(primitive.fill().unwrap().kind(), FillKind::SolidColor); + assert_eq!(primitive.stroke().unwrap().kind(), StrokeKind::Dashed); + + let oval = parse(b""); + assert_eq!(Primitive::new(&oval).unwrap().kind(), PrimitiveKind::Oval); + assert!(Primitive::new(&parse(b"")).is_none()); + } + + #[test] + fn native_color_effect_keeps_xfl_values_and_safe_channel_defaults() { + let element = parse( + br##""##, + ); + let effect = NativeColorEffect::new(&element); + + assert_eq!(effect.tint_multiplier(), Some(0.25)); + assert_eq!(effect.tint_color(), Color { rgb: 0x123456, alpha: 1.0 }); + assert_eq!(effect.brightness(), Some(-0.4)); + assert_eq!(effect.multipliers(), [1.0, -2.0, 0.5, 0.5]); + assert_eq!(effect.offsets(), [255.0, -255.0, 0.0, 0.25]); + } +} diff --git a/crates/xfl/src/shape_hints.rs b/crates/xfl/src/shape_hints.rs new file mode 100644 index 0000000000..681e0c5a95 --- /dev/null +++ b/crates/xfl/src/shape_hints.rs @@ -0,0 +1,119 @@ +//! Borrowed views of native XFL shape-hint records. +//! +//! These parse the native point encodings and hint ordering. Snapping points onto consumer +//! geometry and pairing start/end keyframes remain application responsibilities. + +use crate::shape::{XflElement, integer, number}; + +/// A native XFL point in document coordinates. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Point { + pub x: f32, + pub y: f32, +} + +/// The optional `` wrapper on a keyframe. +#[derive(Clone, Copy, Debug)] +pub struct ShapeHints<'a, E: XflElement> { + wrapper: Option<&'a E>, +} + +impl<'a, E: XflElement> ShapeHints<'a, E> { + pub fn new(keyframe: &'a E) -> Self { + Self { wrapper: keyframe.child("shapeHints") } + } + + pub fn is_empty(&self) -> bool { + self.wrapper.is_none_or(|wrapper| wrapper.elements().next().is_none()) + } + + /// Records in source order; unrecognized child names are retained because the legacy reader + /// interpreted their point and ordering attributes too. + pub fn iter(&self) -> impl Iterator> + 'a { + let wrapper = self.wrapper; + wrapper.into_iter().flat_map(XflElement::elements).map(|element| ShapeHint { element }) + } +} + +/// One native shape-hint record. +#[derive(Clone, Copy, Debug)] +pub struct ShapeHint<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> ShapeHint<'a, E> { + /// Native numeric order, or its single-letter `name` fallback (`a` is zero). + pub fn index(&self) -> Option { + integer(self.element, "index").map(|value| value as usize).or_else(|| self.element.attr("name").and_then(letter_index)) + } + + /// The keyframe's point, in either joined or separate native coordinate attributes. + pub fn start_point(&self) -> Option { + read_point(self.element, "startPoint", "startX", "startY").or_else(|| read_point(self.element, "point", "x", "y")) + } + + /// The next keyframe's point, when the record contains one. + pub fn end_point(&self) -> Option { + read_point(self.element, "endPoint", "endX", "endY") + } +} + +fn letter_index(name: &str) -> Option { + let [byte] = name.as_bytes() else { return None }; + match byte.to_ascii_lowercase() { + b'a'..=b'z' => Some((byte.to_ascii_lowercase() - b'a') as usize), + _ => None, + } +} + +fn read_point(element: &impl XflElement, joined: &str, x: &str, y: &str) -> Option { + let point = match element.attr(joined) { + Some(value) => { + let mut values = value.split([',', ' ']).filter(|part| !part.trim().is_empty()).map(|part| part.trim().parse::().ok()); + Point { x: values.next()??, y: values.next()?? } + } + None => Point { x: number(element, x)?, y: number(element, y)? }, + }; + (point.x.is_finite() && point.y.is_finite()).then_some(point) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_joined_and_split_native_points_in_source_order() { + let keyframe = parse(br#""#); + let hints = ShapeHints::new(&keyframe); + assert!(!hints.is_empty()); + let records: Vec<_> = hints.iter().collect(); + assert_eq!(records[0].index(), Some(1)); + assert_eq!(records[0].start_point(), Some(Point { x: 12.5, y: -2.0 })); + assert_eq!(records[0].end_point(), Some(Point { x: 30.0, y: 40.0 })); + assert_eq!(records[1].index(), Some(0)); + assert_eq!(records[1].start_point(), Some(Point { x: 1.0, y: 2.0 })); + assert_eq!(records[1].end_point(), Some(Point { x: 3.0, y: 4.0 })); + } + + #[test] + fn malformed_joined_values_fall_back_to_the_other_native_point_field() { + let keyframe = parse(br#""#); + let hint = ShapeHints::new(&keyframe).iter().next().expect("hint record"); + assert_eq!(hint.index(), Some(25)); + assert_eq!(hint.start_point(), Some(Point { x: 7.0, y: 8.0 })); + assert_eq!(hint.end_point(), None); + } + + #[test] + fn missing_lists_and_non_letter_names_remain_optional() { + let keyframe = parse(b""); + assert!(ShapeHints::new(&keyframe).is_empty()); + let keyframe = parse(br#""#); + let hint = ShapeHints::new(&keyframe).iter().next().expect("hint record"); + assert_eq!(hint.index(), None); + } +} diff --git a/crates/xfl/src/sound.rs b/crates/xfl/src/sound.rs new file mode 100644 index 0000000000..408b000f14 --- /dev/null +++ b/crates/xfl/src/sound.rs @@ -0,0 +1,136 @@ +//! Borrowed views of native XFL frame-sound and envelope records. +//! +//! These parse the frame fields, effect-name spelling, and envelope wire values. Resolving sound +//! library items and mapping effects/envelopes into a consumer's audio model remain application +//! responsibilities. + +use crate::shape::{XflElement, integer, number}; + +/// Native frame-sound synchronization mode. Unknown values use Animate's event behavior. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SyncMode { + Start, + Stop, + Stream, + #[default] + Event, +} + +/// A native sound instruction stored on a `DOMFrame`. +#[derive(Clone, Copy, Debug)] +pub struct FrameSound<'a, E: XflElement> { + frame: &'a E, +} + +impl<'a, E: XflElement> FrameSound<'a, E> { + pub fn new(frame: &'a E) -> Self { + Self { frame } + } + + pub fn name(&self) -> Option<&'a str> { + self.frame.attr("soundName") + } + + pub fn sync_mode(&self) -> SyncMode { + match self.frame.attr("soundSync").map(str::trim) { + Some("start") => SyncMode::Start, + Some("stop") => SyncMode::Stop, + Some("stream") => SyncMode::Stream, + _ => SyncMode::Event, + } + } + + pub fn looping(&self) -> bool { + self.frame.attr("soundLoopMode").map(str::trim) == Some("loop") + } + + pub fn repeat(&self) -> Option { + integer(self.frame, "soundLoop") + } + + pub fn has_in_point(&self) -> bool { + self.frame.attr("inPoint44").is_some() + } + + pub fn has_out_point(&self) -> bool { + self.frame.attr("outPoint44").is_some() + } + + /// The effect menu label normalized to lowercase ASCII letters and digits, matching the + /// legacy reader's recognition of labels such as `Fade Left to Right`. + pub fn effect_key(&self) -> String { + self.frame + .attr("soundEffect") + .unwrap_or("") + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|character| character.to_ascii_lowercase()) + .collect() + } + + pub fn envelope_points(&self) -> impl Iterator> + 'a { + self.frame + .child("SoundEnvelope") + .into_iter() + .flat_map(|envelope| envelope.elements_named("SoundEnvelopePoint")) + .map(|element| EnvelopePoint { element }) + } +} + +/// One native `SoundEnvelopePoint` record. Levels are raw SWF/XFL integer units. +#[derive(Clone, Copy, Debug)] +pub struct EnvelopePoint<'a, E: XflElement> { + element: &'a E, +} + +impl EnvelopePoint<'_, E> { + pub fn mark44(&self) -> Option { + number(self.element, "mark44") + } + + pub fn level0(&self) -> Option { + number(self.element, "level0") + } + + pub fn level1(&self) -> Option { + number(self.element, "level1") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_frame_sound_modes_repeat_trim_and_effect_name() { + let frame = parse(br#""#); + let sound = FrameSound::new(&frame); + assert_eq!(sound.name(), Some("Music")); + assert_eq!(sound.sync_mode(), SyncMode::Stream); + assert!(sound.looping()); + assert_eq!(sound.repeat(), Some(12)); + assert!(sound.has_in_point()); + assert!(sound.has_out_point()); + assert_eq!(sound.effect_key(), "fadelefttoright"); + } + + #[test] + fn defaults_and_envelope_records_keep_native_optional_values() { + let frame = parse(br#""#); + let sound = FrameSound::new(&frame); + assert_eq!(sound.sync_mode(), SyncMode::Event); + assert!(!sound.looping()); + assert_eq!(sound.repeat(), None); + assert!(!sound.has_in_point()); + assert!(!sound.has_out_point()); + assert_eq!(sound.effect_key(), "custom"); + let points: Vec<_> = sound.envelope_points().collect(); + assert_eq!(points.len(), 2); + assert_eq!((points[0].mark44(), points[0].level0(), points[0].level1()), (Some(44100.0), Some(32768.0), None)); + assert_eq!((points[1].mark44(), points[1].level0(), points[1].level1()), (None, Some(0.0), None)); + } +} diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index ee4b2cf337..5ae0713ba0 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -28,6 +28,32 @@ fn reads_stored_and_deflated_entries() { assert_eq!(a.read("missing").unwrap(), None); } +#[test] +fn xfl_package_root_prefers_root_then_selects_one_top_level_folder() { + let root = zip(&[("DOMDocument.xml", b"", true), ("Walk/DOMDocument.xml", b"", true)]); + let archive = Archive::open(&root).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Document); + + let folder = zip(&[("Walk/DOMDocument.xml", b"", true), ("Walk/LIBRARY/Clip.xml", b"", true)]); + let archive = Archive::open(&folder).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Folder("Walk")); +} + +#[test] +fn xfl_package_root_reports_sorted_candidates_and_ignores_metadata_and_nested_paths() { + let multiple = zip(&[ + ("Zebra/DOMDocument.xml", b"", true), + ("Apple/DOMDocument.xml", b"", true), + ("__MACOSX/DOMDocument.xml", b"not a project", true), + ]); + let archive = Archive::open(&multiple).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Multiple(vec!["Apple", "Zebra"])); + + let nested = zip(&[("One/Two/DOMDocument.xml", b"", true), ("__MACOSX/One/DOMDocument.xml", b"metadata", true)]); + let archive = Archive::open(&nested).unwrap(); + assert_eq!(archive.xfl_package_root(), XflPackageRoot::Missing); +} + #[test] fn the_checksum_matches_the_published_check_value() { assert_eq!(crc32(b"123456789"), 0xCBF4_3926); diff --git a/crates/xfl/src/text.rs b/crates/xfl/src/text.rs new file mode 100644 index 0000000000..8d883fc0c2 --- /dev/null +++ b/crates/xfl/src/text.rs @@ -0,0 +1,273 @@ +//! Borrowed views of native XFL text-field, run and style records. +//! +//! The views expose format attributes and direct text only. Text layout, font selection, +//! unsupported-style reporting and conversion into an application's text model stay with the +//! consumer. + +use crate::shape::{self, Color, XflElement}; +use std::borrow::Cow; + +/// A native static, dynamic or input text field. +#[derive(Clone, Copy, Debug)] +pub struct TextField<'a, E: XflElement> { + element: &'a E, + kind: TextFieldKind, +} + +/// Kind of native XFL text field. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextFieldKind { + Static, + Dynamic, + Input, +} + +impl<'a, E: XflElement> TextField<'a, E> { + /// Views a recognized XFL text field. + pub fn new(element: &'a E) -> Option { + let kind = match element.local_name() { + "DOMStaticText" => TextFieldKind::Static, + "DOMDynamicText" => TextFieldKind::Dynamic, + "DOMInputText" => TextFieldKind::Input, + _ => return None, + }; + Some(Self { element, kind }) + } + + pub fn kind(&self) -> TextFieldKind { + self.kind + } + + /// Native field orientation (`horizontal`, `vertical`, etc.). + pub fn orientation(&self) -> Option<&'a str> { + self.element.attr("orientation") + } + + /// Native `autoExpand` flag, if present and parseable. + pub fn auto_expand(&self) -> Option { + boolean(self.element, "autoExpand") + } + + pub fn width(&self) -> Option { + number(self.element, "width") + } + + pub fn height(&self) -> Option { + number(self.element, "height") + } + + pub fn left(&self) -> Option { + number(self.element, "left") + } + + pub fn top(&self) -> Option { + number(self.element, "top") + } + + pub fn line_type(&self) -> Option<&'a str> { + self.element.attr("lineType") + } + + pub fn border(&self) -> Option { + boolean(self.element, "border") + } + + pub fn is_selectable(&self) -> Option { + boolean(self.element, "isSelectable") + } + + pub fn render_as_html(&self) -> Option { + boolean(self.element, "renderAsHTML") + } + + pub fn max_characters(&self) -> Option { + number(self.element, "maxCharacters") + } + + pub fn variable_name(&self) -> Option<&'a str> { + self.element.attr("variableName") + } + + /// Whether the native field has any filter records, which consumers may need to report as + /// unsupported while keeping the field. + pub fn has_filters(&self) -> bool { + self.element.child("filters").is_some_and(|wrapper| wrapper.elements().next().is_some()) + } + + /// Text runs in document order. Non-`DOMTextRun` children are ignored. + pub fn runs(&self) -> impl Iterator> + 'a { + self.element.child("textRuns").into_iter().flat_map(|wrapper| wrapper.elements_named("DOMTextRun")).map(|element| TextRun { element }) + } + + /// Number of element records inside the native `` wrapper, including unknown + /// records. This lets consumers retain their prior malformed-record and resource-limit + /// policy while parsing recognized runs through [`Self::runs`]. + pub fn run_entries_count(&self) -> usize { + self.element.child("textRuns").map_or(0, |wrapper| wrapper.elements().count()) + } +} + +/// One native text run and its optional style record. +#[derive(Clone, Copy, Debug)] +pub struct TextRun<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> TextRun<'a, E> { + /// Direct character data of this run's `` element. + pub fn characters(&self) -> Cow<'a, str> { + self.element.child("characters").map_or(Cow::Borrowed(""), XflElement::text_content) + } + + /// The native text attributes nested under ``. + pub fn style(&self) -> Option> { + self.element.child("textAttrs").and_then(|wrapper| wrapper.child("DOMTextAttrs")).map(|element| TextStyle { element }) + } +} + +/// Native `DOMTextAttrs` fields. Values are parsed from the wire schema but not laid out or +/// normalized for any application. +#[derive(Clone, Copy, Debug)] +pub struct TextStyle<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> TextStyle<'a, E> { + pub fn face(&self) -> Option<&'a str> { + self.element.attr("face") + } + + pub fn size(&self) -> Option { + number(self.element, "size") + } + + pub fn bold(&self) -> Option { + boolean(self.element, "bold") + } + + pub fn italic(&self) -> Option { + boolean(self.element, "italic") + } + + pub fn fill_color(&self) -> Option<&'a str> { + self.element.attr("fillColor") + } + + /// Parsed native fill color and alpha, with XFL's black/full-opacity defaults. + pub fn color(&self) -> Color { + shape::color(self.element, "fillColor", "alpha") + } + + pub fn alpha(&self) -> Option { + number(self.element, "alpha") + } + + pub fn alignment(&self) -> Option<&'a str> { + self.element.attr("alignment") + } + + pub fn indent(&self) -> Option { + number(self.element, "indent") + } + + pub fn character_position(&self) -> Option<&'a str> { + self.element.attr("characterPosition") + } + + pub fn letter_spacing(&self) -> Option { + number(self.element, "letterSpacing") + } + + pub fn line_spacing(&self) -> Option { + number(self.element, "lineSpacing") + } + + pub fn left_margin(&self) -> Option { + number(self.element, "leftMargin") + } + + pub fn right_margin(&self) -> Option { + number(self.element, "rightMargin") + } +} + +fn number(element: &impl XflElement, name: &str) -> Option { + element.attr(name)?.trim().parse::().ok().filter(|value| value.is_finite()) +} + +fn boolean(element: &impl XflElement, name: &str) -> Option { + element.attr(name).map(|value| value.trim() == "true") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_prefixed_text_fields_runs_and_native_style_values() { + let root = parse( + br##"one & two"##, + ); + let field = TextField::new(&root).expect("dynamic text field"); + assert_eq!(field.kind(), TextFieldKind::Dynamic); + assert_eq!(field.orientation(), Some("horizontal")); + assert_eq!(field.auto_expand(), Some(true)); + assert_eq!((field.width(), field.height(), field.left(), field.top()), (Some(320.0), Some(40.0), Some(12.0), Some(3.0))); + assert_eq!(field.line_type(), Some("multiline")); + assert_eq!(field.border(), Some(true)); + assert_eq!(field.is_selectable(), Some(false)); + assert_eq!(field.render_as_html(), Some(false)); + assert_eq!(field.max_characters(), Some(45.0)); + assert_eq!(field.variable_name(), Some("message")); + assert!(field.has_filters()); + + let mut runs = field.runs(); + let first = runs.next().expect("first run"); + assert_eq!(first.characters(), "one & two"); + let style = first.style().expect("text style"); + assert_eq!(style.face(), Some("Arial")); + assert_eq!(style.size(), Some(24.0)); + assert_eq!(style.bold(), Some(true)); + assert_eq!(style.italic(), Some(false)); + assert_eq!(style.fill_color(), Some("#123456")); + assert_eq!(style.alpha(), Some(0.5)); + assert_eq!(style.alignment(), Some("center")); + assert_eq!(style.indent(), Some(3.0)); + assert_eq!(style.character_position(), Some("superscript")); + assert_eq!(style.letter_spacing(), Some(1.25)); + assert_eq!(style.line_spacing(), Some(2.0)); + assert_eq!(style.left_margin(), Some(4.0)); + assert_eq!(style.right_margin(), Some(5.0)); + + let second = runs.next().expect("second run"); + assert_eq!(second.characters(), "third"); + assert!(second.style().is_none()); + assert!(runs.next().is_none()); + } + + #[test] + fn recognizes_all_native_field_kinds_and_ignores_non_text_elements() { + for (name, expected) in + [("DOMStaticText", TextFieldKind::Static), ("DOMDynamicText", TextFieldKind::Dynamic), ("DOMInputText", TextFieldKind::Input)] + { + let xml = format!("<{name}/>"); + let root = craft_xml::parse(xml.as_bytes()).expect("test XML"); + assert_eq!(TextField::new(&root).map(|field| field.kind()), Some(expected)); + } + let root = parse(b""); + assert!(TextField::new(&root).is_none()); + } + + #[test] + fn malformed_and_non_finite_numbers_remain_absent() { + let root = parse(b""); + let field = TextField::new(&root).expect("text field"); + let style = field.runs().next().and_then(|run| run.style()).expect("style"); + assert_eq!(style.size(), None); + assert_eq!(style.letter_spacing(), None); + } +} diff --git a/crates/xfl/src/tween.rs b/crates/xfl/src/tween.rs new file mode 100644 index 0000000000..a894d5c295 --- /dev/null +++ b/crates/xfl/src/tween.rs @@ -0,0 +1,117 @@ +//! Borrowed views of native XFL frame-tween and custom-ease records. +//! +//! This parses the native attributes and point lists. Interpreting easing curves and applying +//! them to an application's timeline model remain consumer responsibilities. + +use crate::shape::{XflElement, boolean, number}; + +/// Native motion/shape tween settings on a `DOMFrame`. +#[derive(Clone, Copy, Debug)] +pub struct FrameTween<'a, E: XflElement> { + frame: &'a E, +} + +impl<'a, E: XflElement> FrameTween<'a, E> { + pub fn new(frame: &'a E) -> Self { + Self { frame } + } + + /// The classic slider value, when present and finite. + pub fn acceleration(&self) -> Option { + number(self.frame, "acceleration") + } + + pub fn has_custom_ease(&self) -> Option { + boolean(self.frame, "hasCustomEase") + } + + /// Animate's default is a single curve unless this is explicitly false. + pub fn use_single_ease_curve(&self) -> Option { + boolean(self.frame, "useSingleEaseCurve") + } + + pub fn orient_to_path(&self) -> Option { + boolean(self.frame, "motionTweenOrientToPath") + } + + /// Raw native rotation setting; interpretation stays in the consuming application. + pub fn rotate(&self) -> Option<&'a str> { + self.frame.attr("motionTweenRotate") + } + + /// Custom ease curves in source order; unknown tween entries are skipped. + pub fn custom_eases(&self) -> impl Iterator> + 'a { + self.frame.child("tweens").into_iter().flat_map(|wrapper| wrapper.elements_named("CustomEase")).map(|element| CustomEase { element }) + } +} + +/// A native custom-ease curve. +#[derive(Clone, Copy, Debug)] +pub struct CustomEase<'a, E: XflElement> { + element: &'a E, +} + +impl<'a, E: XflElement> CustomEase<'a, E> { + /// The property-group name, defaulting to `all` in XFL. + pub fn target(&self) -> &'a str { + self.element.attr("target").map(str::trim).unwrap_or("all") + } + + pub fn points(&self) -> impl Iterator> + 'a { + self.element.elements_named("Point").map(|element| EasePoint { element }) + } +} + +/// One native custom-ease point. +#[derive(Clone, Copy, Debug)] +pub struct EasePoint<'a, E: XflElement> { + element: &'a E, +} + +impl EasePoint<'_, E> { + pub fn x(&self) -> Option { + number(self.element, "x") + } + + pub fn y(&self) -> Option { + number(self.element, "y") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(source: &[u8]) -> craft_xml::El { + craft_xml::parse(source).expect("well-formed test XML") + } + + #[test] + fn reads_frame_tween_settings_and_custom_eases_in_order() { + let frame = parse( + br#""#, + ); + let tween = FrameTween::new(&frame); + assert_eq!(tween.acceleration(), Some(-45.0)); + assert_eq!(tween.has_custom_ease(), Some(true)); + assert_eq!(tween.use_single_ease_curve(), Some(false)); + assert_eq!(tween.orient_to_path(), Some(true)); + assert_eq!(tween.rotate(), Some("clockwise")); + let curves: Vec<_> = tween.custom_eases().collect(); + assert_eq!(curves.len(), 2); + assert_eq!(curves[0].target(), "position"); + assert_eq!(curves[0].points().map(|point| (point.x(), point.y())).collect::>(), [(Some(0.0), Some(0.0)), (Some(0.5), Some(0.25))]); + assert_eq!(curves[1].target(), "all"); + assert_eq!(curves[1].points().next().map(|point| (point.x(), point.y())), Some((Some(1.0), Some(1.0)))); + } + + #[test] + fn absent_and_malformed_values_remain_optional() { + let frame = parse(br#""#); + let tween = FrameTween::new(&frame); + assert_eq!(tween.acceleration(), None); + assert_eq!(tween.has_custom_ease(), Some(false)); + assert_eq!(tween.use_single_ease_curve(), Some(false)); + assert!(tween.custom_eases().next().is_none()); + } +} diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md index 3d3808ad3c..b8669288e2 100644 --- a/crates/xlsx/README.md +++ b/crates/xlsx/README.md @@ -83,9 +83,17 @@ for new pictures (`vm = i + 1`) and the `XLDAPR` dynamic-array metadata (`cm = 1 The parts this crate writes use the transitional namespaces; a strict file's kept parts stay as they were. A binary workbook is not written. -A binary workbook gives the same `Workbook`, strings, rows and merged cells, with saved values -only: its formulas are token streams that are not decoded, and its styles are not read (each -cell keeps its format index). +A binary workbook gives the same `Workbook`, strings, rows and merged cells. Its styles are not +read (each cell keeps its format index). Its cell formulas are decoded from their tokens into the +text an `.xlsx` file holds (`_xlfn.` and `_xlpm.` names as written, apart from the four +ISO/IEC 29500 functions `.xlsx` names bare, no implicit `@`, the spaces and line breaks typed in +the formula, numbers as Excel spells them), with +`FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell +metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the +file keeps the tokens once. A formula whose decoding needs something the reader does not read +keeps only its saved result, with a warning saying why: user defined names, table references, +other workbooks, Python code stored outside the cell, data tables. The XLSB function table +(`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from `craft-xls`'s. ## Hostile input @@ -94,8 +102,11 @@ cell keeps its format index). string and what is left of a part, not a sheet's length. - `Limits.binary_records`, `binary_cells`, `binary_text`: a binary workbook, over all its parts (40 million records, 4 million cells and as many shared strings, 256 MiB of text, as - `craft-xls` allows). Fixed caps: 1024 sheets, 100,000 merged ranges per sheet, 64 nested - extension blocks. + `craft-xls` allows). `binary_formula_text`: decoded formula text over the workbook (128 MiB); + past it, formulas keep their saved results. A formula's tokens are bounded at 16 KB, its + nesting at 256 levels and its array constants at 65,536 values in all, each charged before + it is held; once the formula text allowance is spent, no formula is decoded. Fixed caps: 1024 + sheets, 100,000 merged ranges per sheet, 64 nested extension blocks. - Cells and rows outside the 1,048,576 × 16,384 grid are dropped and counted. SpreadsheetML is read leniently: a damaged optional part is a warning, a damaged worksheet keeps diff --git a/crates/xlsx/src/lib.rs b/crates/xlsx/src/lib.rs index b0771d366d..5a64ae0abc 100644 --- a/crates/xlsx/src/lib.rs +++ b/crates/xlsx/src/lib.rs @@ -145,6 +145,10 @@ pub struct Limits { pub binary_cells: usize, /// Bytes of decoded text (shared and inline strings) in a binary workbook, over all its parts. pub binary_text: usize, + /// Bytes of decoded formula text in a binary workbook, over all its sheets. A cell formula + /// may hold 16 KB of tokens, so without a total a million cells of long formulas would cost + /// gigabytes; past it, formulas keep their saved results (the file still opens). + pub binary_formula_text: usize, } impl Default for Limits { @@ -156,6 +160,7 @@ impl Default for Limits { binary_records: 40_000_000, binary_cells: 4_000_000, binary_text: 256 << 20, + binary_formula_text: 128 << 20, } } } diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index e06619e27a..d43a15a8c9 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -29,6 +29,9 @@ pub struct Package<'a> { binary: Option, workbook_rels: Option, budget: xlsb::Budget, + /// What a binary workbook's formulas refer to, once its workbook part is read: `Some(None)` + /// when that couldn't be read (every formula keeps its saved result). + binary_links: Option>, /// Shared strings in a binary workbook, once counted: a cell's index is checked against it. binary_strings: Option, } @@ -67,6 +70,7 @@ impl<'a> Package<'a> { binary, workbook_rels: None, budget: xlsb::Budget::default(), + binary_links: None, binary_strings: None, }) } @@ -145,7 +149,9 @@ impl<'a> Package<'a> { if self.binary.is_some() { let bytes = self.required(&self.workbook_part.clone())?; let rels = self.workbook_rels()?; - return xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings); + let (wb, links) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; + self.binary_links = Some(links); + return Ok(wb); } let options = self.xml_options(); let root = match self.opc.read_xml(&self.workbook_part, &options)? { @@ -240,8 +246,13 @@ impl<'a> Package<'a> { Some(n) => n, None => self.shared_strings()?.len(), }; + // Formulas name sheets and functions through the workbook part. + if self.binary_links.is_none() { + self.workbook()?; + } let bytes = self.required(&part)?; - let mut sheet = xlsb::worksheet(&bytes, strings, &self.limits, &self.budget, &mut self.warnings, &mut each)?; + let links = self.binary_links.as_ref().and_then(Option::as_ref); + let mut sheet = xlsb::worksheet(&bytes, strings, links, &self.limits, &self.budget, &mut self.warnings, &mut each)?; sheet.part = part; return Ok(sheet); } diff --git a/crates/xlsx/src/sheet.rs b/crates/xlsx/src/sheet.rs index 243430f8ef..2691764d5c 100644 --- a/crates/xlsx/src/sheet.rs +++ b/crates/xlsx/src/sheet.rs @@ -113,8 +113,10 @@ pub enum FormulaKind { #[derive(Clone, Debug, Default, PartialEq)] pub struct CellFormula { pub kind: FormulaKind, - /// The formula as the file spells it (`_xlfn.` prefixes and all), trimmed. Empty for a - /// cell that shares the formula of its group's first cell. + /// The formula as the file spells it (`_xlfn.` prefixes and all), trimmed. In `.xlsx`, empty + /// for a cell that shares the formula of its group's first cell. A binary workbook (`.xlsb`) + /// stores a shared formula's tokens once, so every cell of the group gets its own text, + /// decoded at the cell. pub text: String, /// `si`: the shared formula group. pub shared_index: Option, diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index dbff61dd7b..b3f94b5fa8 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -1,16 +1,24 @@ //! Binary workbooks ([MS-XLSB]): the workbook part, shared strings and worksheet cells, from -//! their records. Saved values only: formulas are token streams that are not decoded, and -//! styles are not read. A record that does not parse fails the read. +//! their records. Cell formulas are decoded from their tokens ([`formula`]) into the text an +//! `.xlsx` file holds; one that can't be keeps only its saved result, with a warning saying why. +//! Styles are not read. A record that does not parse fails the read. +mod expr; +mod formula; +mod ftab; + +use std::collections::HashMap; use std::sync::Arc; use craft_opc::{ContentTypes, Rels}; use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS, Range, Visibility}; -use crate::sheet::{Cell, CellValue, Row, SheetPart}; +use crate::sheet::{Cell, CellFormula, CellValue, FormulaKind, Row, SheetPart}; use crate::strings::StringItem; use crate::workbook::{SheetEntry, SheetKind, Workbook}; use crate::{Error, Limits, Warnings}; +pub(crate) use formula::Links; +use formula::{Book, Mode, Name, Xti}; pub(crate) const MAIN: &str = "application/vnd.ms-excel.main"; const BINARY_MAIN: &str = "application/vnd.ms-excel.sheet.binary.macroEnabled.main"; @@ -18,8 +26,14 @@ pub(crate) const WORKSHEET: &str = "application/vnd.ms-excel.worksheet"; pub(crate) const STRINGS: &str = "application/vnd.ms-excel.sharedStrings"; /// Most sheets in the workbook. const MAX_SHEETS: usize = 1024; +/// Supporting links (this workbook, add-ins, other workbooks) read at most; past it, formulas +/// keep their saved results. +const MAX_BOOKS: usize = 65_536; /// Most merged ranges in one worksheet. const MAX_MERGES: usize = 100_000; +/// Defined names (Excel's hidden ones for newer functions included) read at most; past it, the +/// workbook's formulas keep their saved results. +const MAX_NAMES: usize = 65_536; pub(crate) fn invalid(msg: impl Into) -> Error { Error::Invalid(format!("XLSB: {}", msg.into())) @@ -41,9 +55,26 @@ pub(crate) struct Budget { cells: std::cell::Cell, text: std::cell::Cell, records: std::cell::Cell, + formula_text: std::cell::Cell, } impl Budget { + /// Charges a decoded formula's text if it fits [`Limits::binary_formula_text`]; a formula + /// that doesn't keeps its saved result. + /// Whether formula text of `len` bytes would still fit, without charging it. + fn formula_text_fits(&self, len: usize, limits: &Limits) -> bool { + self.formula_text.get().saturating_add(len) <= limits.binary_formula_text + } + + fn try_formula_text(&self, len: usize, limits: &Limits) -> bool { + let total = self.formula_text.get().saturating_add(len); + let fits = total <= limits.binary_formula_text; + if fits { + self.formula_text.set(total); + } + fits + } + fn text(&self, len: usize, limits: &Limits) -> Result<(), Error> { self.text.set(self.text.get().saturating_add(len)); if self.text.get() > limits.binary_text { @@ -95,6 +126,9 @@ impl<'a> Bytes<'a> { fn u32(&mut self) -> Result { Ok(u32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("truncated u32"))?)) } + fn i32(&mut self) -> Result { + Ok(i32::from_le_bytes(self.take(4)?.try_into().map_err(|_| invalid("truncated i32"))?)) + } fn f64(&mut self) -> Result { let n = f64::from_le_bytes(self.take(8)?.try_into().map_err(|_| invalid("truncated number"))?); @@ -222,12 +256,24 @@ impl<'a, 'l> Records<'a, 'l> { } /// The workbook part: BrtBeginBook, BrtWbProp, the BrtBundleSh list. -pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budget, warnings: &mut Warnings) -> Result { +/// The workbook part, and the tables its formulas refer to ([`Links`]): `None` when those can't +/// be read, so that the workbook still opens, with every formula kept as its saved result. +pub(crate) fn workbook( + bytes: &[u8], + rels: &Rels, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Result<(Workbook, Option), Error> { let mut records = Records::new(bytes, limits, budget); records.first(131, warnings)?; let mut wb = Workbook::default(); + let mut links = Some(Links::default()); let mut bundle = false; let mut bundle_seen = false; + // Every BrtBundleSh counts toward the cap, a skipped module sheet too: each keeps a place + // in the sheet links. + let mut bundle_count = 0usize; while let Some((id, payload)) = records.next(warnings)? { let mut b = Bytes::new(payload); match id { @@ -239,7 +285,17 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if wb.sheets.is_empty() { return Err(invalid("no supported worksheets")); } - return Ok(wb); + if links.is_none() { + warnings.warn("XLSB: the workbook's sheet links or names could not be read; formulas keep their saved results"); + } + return Ok((wb, links)); + } + 39 | 355 | 357 | 358 | 362 | 667 => { + if let Some(l) = links.as_mut() + && link_record(id, payload, l).is_err() + { + links = None; + } } 143 => { if bundle_seen { @@ -266,9 +322,10 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if !bundle { return Err(invalid("worksheet outside the worksheet list")); } - if wb.sheets.len() >= MAX_SHEETS { + if bundle_count >= MAX_SHEETS { return Err(Error::TooLarge(format!("XLSB exceeds {MAX_SHEETS} sheets"))); } + bundle_count += 1; let visibility = match b.u32()? { 0 => Visibility::Visible, 1 => Visibility::Hidden, @@ -287,6 +344,10 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg return Err(invalid("worksheet relationship is null")); } warnings.warn("XLSB module sheets were skipped"); + // Formulas name sheets by their place in this list, skipped sheets included. + if let Some(l) = links.as_mut() { + l.sheets.push(None); + } continue; }; let rel = rels.by_id(&rel_id).ok_or_else(|| invalid("worksheet relationship is missing"))?; @@ -297,6 +358,11 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg if let SheetKind::Other(_) = kind { return Err(invalid("unknown sheet relationship type")); } + // Only worksheets and macro sheets have cells a formula can refer to (a macro's + // name refers to its macro sheet: `Macro1!$A$1`). + if let Some(l) = links.as_mut() { + l.sheets.push(matches!(kind, SheetKind::Worksheet | SheetKind::Macrosheet).then(|| name.clone())); + } wb.sheets.push(SheetEntry { name, sheet_id, visibility, rel_id, kind, part: Some(rel.target.clone()) }); } _ => {} @@ -305,6 +371,51 @@ pub(crate) fn workbook(bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budg Err(invalid("missing workbook end record")) } +/// A supporting link (`BrtSupSelf`, `BrtSupSame`, `BrtSupAddin`, `BrtSupBookSrc`), the sheet links +/// (`BrtExternSheet`) or a defined name (`BrtName`), added to `links`. +fn link_record(id: u16, payload: &[u8], links: &mut Links) -> Result<(), Error> { + let mut b = Bytes::new(payload); + if matches!(id, 355 | 357 | 358 | 667) && links.books.len() >= MAX_BOOKS { + return Err(invalid("too many supporting links")); + } + match id { + 357 | 358 | 667 => { + b.finish()?; + links.books.push(match id { + 357 => Book::This, + 358 => Book::Same, + _ => Book::Addin, + }); + } + 355 => links.books.push(Book::External), + 362 => { + // [MS-XLSB] 2.4.672: cXti "MUST be less than 65536" (PtgRef3d's ixti is 16 bits). + let count = b.u32()?; + if count >= 65_536 || !links.xti.is_empty() { + return Err(invalid("invalid sheet link list")); + } + for _ in 0..count { + let book = b.u32()?; + let (first, last) = (b.i32()?, b.i32()?); + links.xti.push(Xti { book, first, last }); + } + b.finish()?; + } + _ => { + // BrtName ([MS-XLSB] 2.4.718): flags, chKey, itab, then the name; the formula and the + // rest aren't needed to call a function or tell a name from one. + if links.names.len() >= MAX_NAMES { + return Err(invalid("too many defined names")); + } + let flags = b.u32()?; + b.take(5)?; + let text = b.text(255)?; + links.names.push(Name { text, future: flags & (1 << 17) != 0 }); + } + } + Ok(()) +} + /// A `RichStr`: the text; formatting and phonetic runs are skipped. fn rich_string(b: &mut Bytes<'_>) -> Result { let flags = b.u8()?; @@ -395,17 +506,208 @@ fn boolean(b: &mut Bytes<'_>) -> Result { } } -/// The formula after a cell's saved result: checked for framing, not decoded. -fn skip_formula(b: &mut Bytes<'_>) -> Result<(), Error> { +/// The `grbitFlags` and `CellParsedFormula` after a formula cell's value: its tokens (`rgce`) +/// and their extra data (`rgcb`). The flags' only bit, `fAlwaysCalc`, is the calculator's to know. +fn cell_formula<'a>(b: &mut Bytes<'a>) -> Result<(&'a [u8], &'a [u8]), Error> { b.take(2)?; let cce = b.u32()?; if !(1..=16384).contains(&cce) { return Err(invalid("invalid formula token length")); } - b.take(cce as usize)?; + let rgce = b.take(cce as usize)?; let extra = b.u32()?; - b.take(extra as usize)?; - Ok(()) + let rgcb = b.take(extra as usize)?; + Ok((rgce, rgcb)) +} + +/// A formula's text, or `None` (with a warning saying why) for one that keeps its saved result: +/// the workbook's links couldn't be read, the tokens can't be decoded, or the formula text +/// allowance is spent. +fn decode_formula( + rgce: &[u8], + rgcb: &[u8], + mode: Mode, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Option { + let links = links?; + // Once the allowance is spent no formula fits it, so none is decoded only to be dropped. + if !budget.formula_text_fits(1, limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + let text = match formula::decode(rgce, rgcb, links, mode) { + Ok(e) => expr::print(&e), + Err(formula::Unsupported(why)) => { + kept(warnings, why); + return None; + } + }; + if !budget.try_formula_text(text.len(), limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + Some(text) +} + +/// Warns, once per reason, that formulas were kept as their saved results. +fn kept(warnings: &mut Warnings, why: &str) { + warnings.warn(format!("XLSB: some formulas were kept as their saved results ({why})")); +} + +/// A `BrtShrFmla`: the cells it may cover, its tokens, its first cell's text length (what a copy +/// is expected to cost) and the group's index (`si`). The tokens are borrowed from the worksheet +/// part, which outlives the sheet's read: a record can be up to 256 MiB, and copying every +/// shared formula's would cost as much again as the part. +#[derive(Clone, Copy)] +struct SharedFormula<'a> { + range: Range, + rgce: &'a [u8], + rgcb: &'a [u8], + len: usize, + si: u32, +} + +/// A formula cell whose tokens are only `PtgExp`: part of a shared or array formula. +enum Part { + /// The first cell: its formula is the `BrtShrFmla` or `BrtArrFmla` record that follows. + First, + /// Another cell of the formula whose first cell is this. + Of(CellRef), +} + +/// `PtgExp` ([MS-XLSB] 2.5.98.40) with its `PtgExtraCol`: the first cell of the shared or array +/// formula this cell belongs to. BIFF12 keeps only the row in the token and the column in rgcb. +fn part_of(rgce: &[u8], rgcb: &[u8], at: CellRef) -> Option> { + let (&ptg, row) = rgce.split_first()?; + if ptg != 0x01 { + return None; + } + let (Ok(row), Ok(col)) = (<[u8; 4]>::try_from(row), <[u8; 4]>::try_from(rgcb)) else { + return Some(Err("malformed shared or array formula references")); + }; + let first = CellRef::new(u32::from_le_bytes(row), u32::from_le_bytes(col)); + Some(Ok(if first == at { Part::First } else { Part::Of(first) })) +} + +/// One sheet's shared and array formulas, by first cell, as the reader meets them. `None` when +/// the formula keeps its values (so its other cells keep theirs). +#[derive(Default)] +struct RangeFormulas<'a> { + shared: HashMap>>, + arrays: HashMap>, +} + +impl<'a> RangeFormulas<'a> { + /// The formula of another cell `at` of the shared or array formula starting at `first`. A + /// shared formula's copy is decoded from the shared tokens at its own cell, as [MS-XLSB] + /// defines it (relative offsets wrap around the grid), and checked like any formula: its text + /// may be longer than the first cell's. That length estimates its cost, and a copy that can't + /// fit isn't decoded at all, so a long formula shared by a million cells stops costing once + /// the allowance is spent. An array formula's other cells have none, as in `.xlsx`. + fn follower( + &mut self, + at: CellRef, + first: CellRef, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, + ) -> Option { + if let Some(shared) = self.shared.get(&first) { + let sh = (*shared)?; + if !sh.range.contains(at) { + kept(warnings, "malformed shared or array formula references"); + return None; + } + if !budget.formula_text_fits(sh.len, limits) { + kept(warnings, "more formula text than the limits allow"); + return None; + } + let Some(text) = decode_formula(sh.rgce, sh.rgcb, Mode::Shared(at), links, limits, budget, warnings) else { + // A copy that was decoded but kept as its value charged nothing: one past the + // allowance (it may be longer than the first cell's estimate) or one that can't be + // decoded. The group's later copies would fail the same way, so they keep their + // values without being decoded: a group costs at most one wasted decode. + self.shared.insert(first, None); + return None; + }; + return Some(CellFormula { kind: FormulaKind::Shared, text, shared_index: Some(sh.si), ..CellFormula::default() }); + } + match self.arrays.get(&first) { + Some(Some(range)) if range.contains(at) => {} + Some(Some(_)) => kept(warnings, "malformed shared or array formula references"), + Some(None) => {} + None => kept(warnings, "a shared or array formula that is missing from the file"), + } + None + } + + /// `BrtShrFmla` (427) or `BrtArrFmla` (426) right after the first cell `first` of its range: + /// the formula that cell keeps, recorded for the range's other cells. A record that can't be + /// read leaves the whole range as values; it never fails the file, as these records were + /// skipped before formulas were read. + #[allow(clippy::too_many_arguments)] + fn range_formula( + &mut self, + id: u16, + payload: &'a [u8], + first: CellRef, + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, + ) -> Option { + let read = |b: &mut Bytes<'a>| -> Result<(Range, &'a [u8], &'a [u8]), Error> { + let (r0, r1, c0, c1) = (b.u32()?, b.u32()?, b.u32()?, b.u32()?); + if id == 426 { + b.u8()?; // Only fAlwaysCalc, the calculator's to know. + } + let cce = b.u32()?; + if !(1..=16384).contains(&cce) { + return Err(invalid("invalid formula token length")); + } + let rgce = b.take(cce as usize)?; + let cb = b.u32()?; + let rgcb = b.take(cb as usize)?; + if r0 > r1 || c0 > c1 || r1 >= MAX_ROWS || c1 >= MAX_COLS { + return Err(invalid("invalid formula range")); + } + let range = Range::new(CellRef::new(r0, c0), CellRef::new(r1, c1)); + // An array formula's first cell is its range's top-left one. A shared formula's is the + // first cell that uses it, which need not be: the top-left cell may not share it. + let start_ok = if id == 427 { range.contains(first) } else { range.first == first }; + if !start_ok { + return Err(invalid("invalid formula range")); + } + Ok((range, rgce, rgcb)) + }; + let mut b = Bytes::new(payload); + let Ok((range, rgce, rgcb)) = read(&mut b).and_then(|r| b.finish().map(|()| r)) else { + kept(warnings, "malformed shared or array formulas"); + self.shared.insert(first, None); + self.arrays.insert(first, None); + return None; + }; + if id == 427 { + let text = decode_formula(rgce, rgcb, Mode::Shared(first), links, limits, budget, warnings); + let si = u32::try_from(self.shared.len()).unwrap_or(u32::MAX); + let shared = text.as_ref().map(|t| SharedFormula { range, rgce, rgcb, len: t.len(), si }); + self.shared.insert(first, shared); + return text.map(|text| CellFormula { + kind: FormulaKind::Shared, + text, + shared_index: Some(si), + range: Some(range), + ..CellFormula::default() + }); + } + let text = decode_formula(rgce, rgcb, Mode::Cell, links, limits, budget, warnings); + self.arrays.insert(first, text.as_ref().map(|_| range)); + text.map(|text| CellFormula { kind: FormulaKind::Array, text, range: Some(range), ..CellFormula::default() }) + } } fn value(id: u16, b: &mut Bytes<'_>, strings: usize, limits: &Limits, budget: &Budget) -> Result { @@ -442,16 +744,16 @@ fn value(id: u16, b: &mut Bytes<'_>, strings: usize, limits: &Limits, budget: &B } _ => return Err(invalid("unsupported cell record")), }; - if (8..=11).contains(&id) { - skip_formula(b)?; - } Ok(value) } /// A worksheet part: rows (BrtRowHdr) and cells inside BrtBeginSheetData, merged cells after. +/// Formulas refer to the workbook's `links`; with none, each keeps its saved result. +#[allow(clippy::too_many_arguments)] pub(crate) fn worksheet( bytes: &[u8], strings: usize, + links: Option<&Links>, limits: &Limits, budget: &Budget, warnings: &mut Warnings, @@ -464,9 +766,41 @@ pub(crate) fn worksheet( let mut data_seen = false; let mut row: Option = None; let mut col = None; + // BrtCellMeta applies to the cell record that follows it (a dynamic-array formula), as `cm` + // does in `.xlsx`: a one-based index into the metadata part's cell metadata. Excel may write + // the cell's BrtValueMeta (a rich value, such as a spill error) in between. + let mut meta: Option = None; + let mut ranges = RangeFormulas::default(); + // The first cell of a shared or array formula, waiting for the record holding the formula. + let mut first: Option = None; while let Some((id, payload)) = records.next(warnings)? { let mut b = Bytes::new(payload); + let cell_metadata = if id == 50 { meta } else { meta.take() }; + if let Some(at) = first.take() { + if matches!(id, 426 | 427) { + let f = ranges.range_formula(id, payload, at, links, limits, budget, warnings); + if let Some(cell) = row.as_mut().and_then(|r| r.cells.last_mut()).filter(|c| c.at == at) { + // A dynamic array's cell metadata describes its formula: with none kept, the + // cell is a value, and `cm` on it would mark a formula that isn't there. + if f.is_none() { + cell.cell_metadata = None; + } + cell.formula = f; + } + continue; + } + // No formula record: the cell stays a value, so its formula's cell metadata goes too. + if let Some(cell) = row.as_mut().and_then(|r| r.cells.last_mut()).filter(|c| c.at == at) { + cell.cell_metadata = None; + } + kept(warnings, "a shared or array formula that is missing from the file"); + } match id { + 49 => { + let icmb = b.i32()?; + b.finish()?; + meta = u32::try_from(icmb).ok().filter(|&i| i >= 1); + } 130 => { if data || !data_seen { return Err(invalid("incomplete worksheet data")); @@ -525,15 +859,44 @@ pub(crate) fn worksheet( } let style = b.u32()?; let value = value(id, &mut b, strings, limits, budget)?; - b.finish()?; + let at = CellRef::new(current.index, c); + let formula = if (8..=11).contains(&id) { + let (rgce, rgcb) = cell_formula(&mut b)?; + b.finish()?; + match part_of(rgce, rgcb, at) { + None => decode_formula(rgce, rgcb, Mode::Cell, links, limits, budget, warnings) + .map(|text| CellFormula { text, ..CellFormula::default() }), + Some(Ok(Part::First)) => { + first = links.map(|_| at); + None + } + Some(Ok(Part::Of(start))) if links.is_some() => ranges.follower(at, start, links, limits, budget, warnings), + Some(Ok(Part::Of(_))) => None, + Some(Err(why)) => { + kept(warnings, why); + None + } + } + } else { + b.finish()?; + None + }; if value != CellValue::Empty { budget.cell(limits)?; } + // A formula record's cell metadata describes its formula (a dynamic array), so a + // formula kept as its value drops it; the first cell of a shared or array formula + // keeps it until its formula record is read. Other cells keep theirs as the file + // has it. + let formula_kept = !(8..=11).contains(&id) || formula.is_some() || first == Some(at); + let cell_metadata = cell_metadata.filter(|_| formula_kept); current.cells.push(Cell { - at: CellRef::new(current.index, c), + at, style: style & 0x00FF_FFFF, phonetic: style & 0x0100_0000 != 0, value, + formula, + cell_metadata, ..Cell::default() }); col = Some(c); diff --git a/crates/xlsx/src/xlsb/expr.rs b/crates/xlsx/src/xlsb/expr.rs new file mode 100644 index 0000000000..197644a333 --- /dev/null +++ b/crates/xlsx/src/xlsb/expr.rs @@ -0,0 +1,377 @@ +//! The expression tree an XLSB formula decodes to, and its A1 formula text (without `=`), in the +//! file's spelling (`_xlfn.` and `_xlpm.` names as written). A copy of craft-xls's: the two +//! readers follow separate specifications, and can share one tree when both settle. + +use std::fmt::Write; +use std::sync::Arc; + +use craft_sheet::{CellError, push_col, quote_sheet, sheet_needs_quotes}; + +/// One end of a reference, with `$` anchors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Anchor { + pub row: u32, + pub col: u32, + pub row_abs: bool, + pub col_abs: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum RefKind { + Cell(Anchor), + Range(Anchor, Anchor), + /// Whole rows `3:5` as (row, absolute) pairs. + Rows(u32, bool, u32, bool), + /// Whole columns `A:C`. + Cols(u32, bool, u32, bool), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SheetSel { + /// Unqualified: the formula's own sheet. + Current, + Named(String), + /// 3-D span `Sheet1:Sheet3`. + Span(String, String), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Reference { + pub sheet: SheetSel, + pub kind: RefKind, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum UnOp { + Neg, + Plus, + Percent, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BinOp { + Add, + Sub, + Mul, + Div, + Pow, + Concat, + Eq, + Ne, + Lt, + Gt, + Le, + Ge, + /// `:` between two references. + Range, + /// `,` inside parentheses. + Union, + /// A space between two references. + Intersect, +} + +impl BinOp { + /// How tightly the operator binds, as formula text is read: `:` 90, space 85, `,` 80, `^` 50, + /// `*` `/` 40, `+` `-` 30, `&` 20, comparisons 10. + pub(crate) fn precedence(self) -> u8 { + match self { + BinOp::Range => 90, + BinOp::Intersect => 85, + BinOp::Union => 80, + BinOp::Pow => 50, + BinOp::Mul | BinOp::Div => 40, + BinOp::Add | BinOp::Sub => 30, + BinOp::Concat => 20, + BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => 10, + } + } + + fn symbol(self) -> &'static str { + match self { + BinOp::Add => "+", + BinOp::Sub => "-", + BinOp::Mul => "*", + BinOp::Div => "/", + BinOp::Pow => "^", + BinOp::Concat => "&", + BinOp::Eq => "=", + BinOp::Ne => "<>", + BinOp::Lt => "<", + BinOp::Gt => ">", + BinOp::Le => "<=", + BinOp::Ge => ">=", + BinOp::Range => ":", + BinOp::Union => ",", + BinOp::Intersect => " ", + } + } +} + +/// A formula's syntax tree. The decoder bounds its depth, so printing and dropping it recurse +/// safely. +#[derive(Debug, PartialEq)] +pub(crate) enum Expr { + Number(f64), + Text(Arc), + Bool(bool), + Error(CellError), + /// Array constant `{1,2;3,4}` (rows of literals). + Array(Vec>), + Ref(Reference), + /// A defined name. + Name(String), + /// Spaces and line breaks typed before and after an expression (`PtgAttrSpace`), which + /// `.xlsx` formula text keeps. + Spaced(String, Box, String), + Unary(UnOp, Box), + Binary(BinOp, Box, Box), + Call(String, Vec), + /// An omitted argument. + Missing, + Paren(Box), +} + +fn push_anchor(s: &mut String, a: &Anchor) { + if a.col_abs { + s.push('$'); + } + push_col(s, a.col); + if a.row_abs { + s.push('$'); + } + let _ = write!(s, "{}", u64::from(a.row) + 1); +} + +fn push_reference(s: &mut String, r: &Reference) { + match &r.sheet { + SheetSel::Current => {} + SheetSel::Named(n) => { + s.push_str("e_sheet(n)); + s.push('!'); + } + SheetSel::Span(a, b) => { + let joined = format!("{a}:{b}"); + if sheet_needs_quotes(a) || sheet_needs_quotes(b) { + let _ = write!(s, "'{}'!", joined.replace('\'', "''")); + } else { + let _ = write!(s, "{joined}!"); + } + } + } + let dollar = |abs: bool| if abs { "$" } else { "" }; + match &r.kind { + RefKind::Cell(a) => push_anchor(s, a), + RefKind::Range(a, b) => { + push_anchor(s, a); + s.push(':'); + push_anchor(s, b); + } + RefKind::Rows(r0, a0, r1, a1) => { + let _ = write!(s, "{}{}:{}{}", dollar(*a0), u64::from(*r0) + 1, dollar(*a1), u64::from(*r1) + 1); + } + RefKind::Cols(c0, a0, c1, a1) => { + s.push_str(dollar(*a0)); + push_col(s, *c0); + s.push(':'); + s.push_str(dollar(*a1)); + push_col(s, *c1); + } + } +} + +/// Removes trailing zeros (and a trailing point) from a decimal string. +fn trim_decimal(s: &str) -> String { + if s.contains('.') { + let t = s.trim_end_matches('0').trim_end_matches('.'); + if t == "-0" { "0".into() } else { t.to_string() } + } else { + s.to_string() + } +} + +/// Scientific text like `1.23456789012346E+15` with up to `sig` significant digits. +fn sci_text(n: f64, sig: usize) -> String { + let s = format!("{:.*e}", sig.saturating_sub(1), n); + let Some((mant, exp)) = s.split_once('e') else { return s }; + let mant = trim_decimal(mant); + let e: i32 = exp.parse().unwrap_or(0); + format!("{}E{}{:02}", mant, if e < 0 { '-' } else { '+' }, e.abs()) +} + +/// A number as Excel spells it in a formula: rounded to 15 significant digits, written out in +/// full (`100000000000000000000`, `0.0000000000000000001`) when that takes at most 21 characters +/// without the sign, and scientific (`1E+21`, `1.5E-19`, `1.23456789012345E-06`) when it would +/// take more. +pub(crate) fn number_to_text(n: f64) -> String { + if n == 0.0 || !n.is_finite() { + return "0".into(); + } + let s = format!("{:.14e}", n.abs()); + let Some((mant, exp)) = s.split_once('e') else { return s }; + let Ok(e) = exp.parse::() else { return s }; + let digits: String = mant.chars().filter(char::is_ascii_digit).collect(); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let k = digits.len() as i32; + let plain_len = if e >= 0 { (e + 1).max(k + i32::from(k > e + 1)) } else { 1 - e + k }; + if plain_len > 21 { + return sci_text(n, 15); + } + let sign = if n < 0.0 { "-" } else { "" }; + let plain = if e >= 0 { + let int = (e + 1) as usize; + if digits.len() <= int { format!("{digits}{}", "0".repeat(int - digits.len())) } else { format!("{}.{}", &digits[..int], &digits[int..]) } + } else { + format!("0.{}{digits}", "0".repeat((-e - 1) as usize)) + }; + format!("{sign}{plain}") +} + +fn number(n: f64) -> String { + let text = number_to_text(n); + // 15 significant digits can round past f64::MAX, which no longer parses. + if text.parse::().is_ok_and(f64::is_finite) { + return text; + } + let exact = format!("{n:E}"); + match exact.split_once('E') { + Some((m, e)) if !e.starts_with('-') => format!("{m}E+{e}"), + _ => exact, + } +} + +/// Splits a sheet-qualified name at its last `!` outside brackets. +fn sheet_split(n: &str) -> Option<(&str, &str)> { + let mut depth = 0usize; + let mut escaped = false; + let mut at = None; + for (i, c) in n.char_indices() { + if escaped { + escaped = false; + continue; + } + match c { + '\'' if depth > 0 => escaped = true, + '[' => depth = depth.saturating_add(1), + ']' => depth = depth.saturating_sub(1), + '!' if depth == 0 => at = Some(i), + _ => {} + } + } + at.and_then(|i| Some((n.get(..i)?, n.get(i + 1..)?))) +} + +/// Prints an expression in A1 notation, trimmed as the `.xlsx` reader trims formula text. +pub(crate) fn print(e: &Expr) -> String { + let mut s = String::new(); + write_expr(&mut s, e); + match s.trim() { + t if t.len() == s.len() => s, + t => t.to_string(), + } +} + +fn write_args(s: &mut String, args: &[Expr], sep: char) { + for (i, a) in args.iter().enumerate() { + if i > 0 { + s.push(sep); + } + write_expr(s, a); + } +} + +fn write_expr(s: &mut String, e: &Expr) { + match e { + Expr::Number(n) => s.push_str(&number(*n)), + Expr::Text(t) => { + s.push('"'); + s.push_str(&t.replace('"', "\"\"")); + s.push('"'); + } + Expr::Bool(b) => s.push_str(if *b { "TRUE" } else { "FALSE" }), + Expr::Error(err) => s.push_str(err.as_str()), + Expr::Array(rows) => { + s.push('{'); + for (ri, row) in rows.iter().enumerate() { + if ri > 0 { + s.push(';'); + } + write_args(s, row, ','); + } + s.push('}'); + } + Expr::Ref(r) => push_reference(s, r), + Expr::Name(n) => match sheet_split(n) { + // A sheet-qualified name holds the bare sheet name (`My Sheet!Total`): quote it so it parses back. + Some((sheet, name)) => { + s.push_str("e_sheet(sheet)); + s.push('!'); + s.push_str(name); + } + None => s.push_str(n), + }, + Expr::Unary(UnOp::Neg, x) => { + s.push('-'); + write_expr(s, x); + } + Expr::Unary(UnOp::Plus, x) => { + s.push('+'); + write_expr(s, x); + } + Expr::Unary(UnOp::Percent, x) => { + write_expr(s, x); + s.push('%'); + } + Expr::Binary(op, a, b) => { + write_expr(s, a); + s.push_str(op.symbol()); + write_expr(s, b); + } + Expr::Call(name, args) => { + s.push_str(name); + s.push('('); + write_args(s, args, ','); + s.push(')'); + } + Expr::Missing => {} + Expr::Paren(x) => { + s.push('('); + write_expr(s, x); + s.push(')'); + } + Expr::Spaced(before, x, after) => { + s.push_str(before); + write_expr(s, x); + s.push_str(after); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_print_with_fifteen_significant_digits() { + assert_eq!(number_to_text(1.0), "1"); + assert_eq!(number_to_text(-2.5), "-2.5"); + assert_eq!(number_to_text(0.1 + 0.2), "0.3"); + assert_eq!(number_to_text(123456789012345.0), "123456789012345"); + // Written out in full up to 21 characters, as Excel writes them in .xlsx. + assert_eq!(number_to_text(1e15), "1000000000000000"); + assert_eq!(number_to_text(1234567890123456.0), "1234567890123460"); + assert_eq!(number_to_text(-1e20), "-100000000000000000000"); + assert_eq!(number_to_text(1e21), "1E+21"); + assert_eq!(number_to_text(1.5e21), "1.5E+21"); + assert_eq!(number_to_text(0.0001), "0.0001"); + assert_eq!(number_to_text(1e-10), "0.0000000001"); + assert_eq!(number_to_text(1e-19), "0.0000000000000000001"); + assert_eq!(number_to_text(1e-20), "1E-20"); + assert_eq!(number_to_text(1.5e-19), "1.5E-19"); + assert_eq!(number_to_text(1.23456789012345e-5), "0.0000123456789012345"); + assert_eq!(number_to_text(1.23456789012345e-6), "1.23456789012345E-06"); + assert_eq!(number_to_text(1234567890.12345), "1234567890.12345"); + assert_eq!(number_to_text(1e100), "1E+100"); + assert!(number(f64::MAX).parse::().is_ok_and(f64::is_finite)); + } +} diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs new file mode 100644 index 0000000000..a7293c0df2 --- /dev/null +++ b/crates/xlsx/src/xlsb/formula.rs @@ -0,0 +1,771 @@ +//! BIFF12 parsed formulas ([MS-XLSB] 2.2.2, 2.5.98): reverse-Polish `Ptg` tokens back to an +//! expression tree, for cell formulas. The tokens are BIFF8's, but nearly every operand differs +//! (32-bit rows, 14-bit columns, UTF-16 strings, its own array-constant codes, newer functions +//! called through hidden names), so this is its own decoder, with its own function table +//! ([`super::ftab`]) and its own copies of craft-xls's depth guards and limits. Anything outside the +//! token set it knows is reported as unsupported, and the caller keeps the cell's cached value. +//! So is a formula that needs something the reader doesn't read: a user's defined name (XLSB +//! names are not read yet) or Python code stored outside the cell. +//! +//! Names keep their file spelling (`_xlfn.CONCAT`, `_xlpm.x`), as `.xlsx` formula text has them. + +use std::sync::Arc; + +use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS}; + +use super::expr::{Anchor, BinOp, Expr, RefKind, Reference, SheetSel, UnOp}; +use super::ftab::function; + +/// Formula token bytes decoded at most (a cell formula holds at most 16,384). +pub(super) const MAX_RGCE: usize = 16 * 1024; +/// Values in one formula's array constants at most, all of them together: each array is charged +/// before its values are held, so a formula of many arrays can't hold more than this. +const MAX_ARRAY: usize = 65_536; + +/// Why a formula could not be turned back into text. +#[derive(Debug, PartialEq)] +pub(super) struct Unsupported(pub &'static str); + +/// Expression nesting at most: deeper trees would overflow the stack when printed or dropped (a +/// hostile file can chain thousands of PtgParen tokens). +const MAX_DEPTH: usize = 256; + +/// Operand stack entries: an expression and its nesting depth. +type Stack = Vec<(Expr, usize)>; + +/// Pops an operand, recording its depth in `kids` (the deepest operand this token consumed). +fn pop(stack: &mut Stack, kids: &mut usize) -> Result { + let (e, d) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + *kids = (*kids).max(d); + Ok(e) +} + +fn pop_n(stack: &mut Stack, n: usize, kids: &mut usize) -> Result, Unsupported> { + let at = stack.len().checked_sub(n).ok_or(Unsupported("malformed formula (argument missing)"))?; + let popped = stack.split_off(at); + *kids = popped.iter().map(|(_, d)| *d).fold(*kids, usize::max); + Ok(popped.into_iter().map(|(e, _)| e).collect()) +} + +/// Pushes the result of a token one level above the operands it consumed (two for one with the +/// spacing typed around it, which prints as a level of its own). +fn push(stack: &mut Stack, kids: usize, e: Expr) -> Result<(), Unsupported> { + let depth = kids.saturating_add(1).saturating_add(usize::from(matches!(e, Expr::Spaced(..)))); + if depth > MAX_DEPTH { + return Err(Unsupported("formula nested too deeply")); + } + stack.push((e, depth)); + Ok(()) +} + +/// Spaces and line breaks typed in the formula (`PtgAttrSpace`, [MS-XLSB] 2.5.98.32), waiting +/// for the token they belong to. Excel writes the attribute just before that token: spaces +/// before an operand, an operator's symbol or a function call go in `before`; those before a +/// parenthesis's `(`, or before the `)` of a parenthesis or a call, in `open` and `close`. +#[derive(Default)] +struct Spacing { + before: String, + open: String, + close: String, +} + +/// `e` with `ws` typed before it. +fn spaced_before(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(ws + &b, x, a), + e => Expr::Spaced(ws, Box::new(e), String::new()), + } +} + +/// `e` with `ws` typed after it. +fn spaced_after(e: Expr, ws: String) -> Expr { + match e { + _ if ws.is_empty() => e, + Expr::Spaced(b, x, a) => Expr::Spaced(b, x, a + &ws), + e => Expr::Spaced(String::new(), Box::new(e), ws), + } +} + +/// A call's arguments with the spacing typed before its `)`: after the last argument, or alone +/// between the parentheses (`PI( )`). +fn close_args(mut args: Vec, ws: String) -> Vec { + if ws.is_empty() { + return args; + } + match args.pop() { + Some(last) => args.push(spaced_after(last, ws)), + None => args.push(Expr::Spaced(String::new(), Box::new(Expr::Missing), ws)), + } + args +} + +/// An error constant's code ([MS-XLSB] 2.5.98.21, `BErr`). +fn error_code(code: u8) -> Option { + Some(match code { + 0x00 => CellError::Null, + 0x07 => CellError::Div0, + 0x0F => CellError::Value, + 0x17 => CellError::Ref, + 0x1D => CellError::Name, + 0x24 => CellError::Num, + 0x2A => CellError::NA, + 0x2B => CellError::GettingData, + _ => return None, + }) +} + +/// A supporting link record ([MS-XLSB] 2.2.7.3), in the order of the workbook's externals block. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Book { + /// `BrtSupSelf`: this workbook. + This, + /// `BrtSupSame`: the caller's sheet (macro sheets and names only). + Same, + /// `BrtSupAddin`: add-in functions. + Addin, + /// `BrtSupBookSrc`: another workbook, DDE or OLE. Never followed. + External, +} + +/// Xti ([MS-XLSB] 2.5.173): a supporting link and a range of its sheets. +#[derive(Clone, Copy, Debug)] +pub(super) struct Xti { + pub book: u32, + pub first: i32, + pub last: i32, +} + +/// A `BrtName` as far as cell formulas need it. +#[derive(Clone, Debug)] +pub(super) struct Name { + /// The name as written (`_xlfn.CONCAT`, `_xlpm.x`, `Rate`). + pub text: String, + /// `fFutureFunction`: a hidden name standing for a function newer than the file format. + pub future: bool, +} + +/// Workbook-level tables formulas refer to. +#[derive(Default)] +pub(crate) struct Links { + /// Every sheet's name in `BrtBundleSh` order, `None` for the sheets that hold no cells (chart, + /// dialog and module sheets). + pub(super) sheets: Vec>, + /// Every `BrtName`, in order: `PtgName` indexes them from 1. + pub(super) names: Vec, + pub(super) books: Vec, + pub(super) xti: Vec, +} + +/// Whether a name stands for a LET parameter (`_xlpm.x`), which only the formula itself defines. +fn is_param(name: &str) -> bool { + name.get(..6).is_some_and(|p| p.eq_ignore_ascii_case("_xlpm.")) +} + +impl Links { + /// The sheets a 3-D reference names, or `None` for a deleted sheet (the reference is `#REF!`). + fn sheet_sel(&self, ixti: u16) -> Result, Unsupported> { + let x = self.xti.get(usize::from(ixti)).ok_or(Unsupported("reference to a missing sheet link"))?; + match usize::try_from(x.book).ok().and_then(|b| self.books.get(b)) { + Some(Book::This) => {} + Some(Book::External) => return Err(Unsupported("references to other workbooks (external links)")), + Some(_) => return Err(Unsupported("references through add-in or same-sheet links")), + None => return Err(Unsupported("reference to a missing workbook link")), + } + // -1: "the first sheet in the reference cannot be found" (a deleted sheet). + if x.first == -1 || x.last == -1 { + return Ok(None); + } + // -2 (the whole workbook) is for names, not cell references. + let (Ok(first), Ok(last)) = (usize::try_from(x.first), usize::try_from(x.last)) else { + return Err(Unsupported("reference to a missing sheet")); + }; + // A span is spelled by its ends. A sheet between them with no cells (a chart sheet) adds + // nothing to it, and `.xlsx` spells the span the same; an end with no cells can't be named. + let span = self.sheets.get(first..=last).filter(|s| !s.is_empty()).ok_or(Unsupported("reference to a missing sheet"))?; + let (Some(Some(a)), Some(Some(b))) = (span.first(), span.last()) else { + return Err(Unsupported("references to sheets with no cells")); + }; + Ok(Some(if first == last { SheetSel::Named(a.clone()) } else { SheetSel::Span(a.clone(), b.clone()) })) + } +} + +struct Bytes<'a> { + b: &'a [u8], + pos: usize, +} + +const TRUNC: Unsupported = Unsupported("truncated formula"); + +impl Bytes<'_> { + fn take(&mut self, n: usize) -> Result<&[u8], Unsupported> { + let s = self.b.get(self.pos..self.pos.checked_add(n).ok_or(TRUNC)?).ok_or(TRUNC)?; + self.pos += n; + Ok(s) + } + fn u8(&mut self) -> Result { + self.take(1)?.first().copied().ok_or(TRUNC) + } + fn u16(&mut self) -> Result { + let s: [u8; 2] = self.take(2)?.try_into().map_err(|_| TRUNC)?; + Ok(u16::from_le_bytes(s)) + } + fn u32(&mut self) -> Result { + let s: [u8; 4] = self.take(4)?.try_into().map_err(|_| TRUNC)?; + Ok(u32::from_le_bytes(s)) + } + fn f64(&mut self) -> Result { + let s: [u8; 8] = self.take(8)?.try_into().map_err(|_| TRUNC)?; + let n = f64::from_le_bytes(s); + if !n.is_finite() { + return Err(Unsupported("invalid number constant")); + } + Ok(n) + } + /// `cch` UTF-16 code units; unpaired surrogates are refused, not replaced. + fn chars(&mut self, cch: usize) -> Result { + let units = self.take(cch.checked_mul(2).ok_or(TRUNC)?)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)); + char::decode_utf16(units).collect::>().map_err(|_| Unsupported("invalid text constant")) + } +} + +/// The last row and column of the grid: a range from 0 to these is a whole column or row. +const LAST_ROW: u32 = MAX_ROWS - 1; +const LAST_COL: u32 = MAX_COLS - 1; + +/// Where a formula lives: a cell formula's references hold coordinates; a shared formula's +/// relative tokens (`PtgRefN`, `PtgAreaN`) hold offsets from the shared formula's first cell. +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Mode { + Cell, + Shared(CellRef), +} + +/// RgceLoc ([MS-XLSB] 2.5.98.91): a row and a `ColRelShort` (14-bit column, then the +/// column-relative and row-relative flags). In a cell formula the coordinates are absolute +/// whatever the flags say; the flags only decide where `$` goes. +fn anchor(row: u32, col: u16) -> Result { + let c = u32::from(col & 0x3FFF); + if row > LAST_ROW || c > LAST_COL { + return Err(Unsupported("reference outside the grid")); + } + Ok(Anchor { row, col: c, row_abs: col & 0x8000 == 0, col_abs: col & 0x4000 == 0 }) +} + +/// RgceLocRel ([MS-XLSB] 2.5.98.92), in a shared formula: a relative row or column is an offset +/// from `base`, wrapping around the grid (1,048,576 rows, 16,384 columns), as Excel adds them. +/// An absolute one is a coordinate. +fn relative_anchor(row: u32, col: u16, base: CellRef) -> Result { + let (row_rel, col_rel) = (col & 0x8000 != 0, col & 0x4000 != 0); + let r = if row_rel { base.row.wrapping_add(row) % MAX_ROWS } else { row }; + let c = if col_rel { (base.col + u32::from(col & 0x3FFF)) % MAX_COLS } else { u32::from(col & 0x3FFF) }; + anchor(r, (c as u16) | (col & 0xC000)) +} + +fn loc(row: u32, col: u16, mode: Mode) -> Result { + match mode { + Mode::Cell => anchor(row, col), + Mode::Shared(base) => relative_anchor(row, col, base), + } +} + +/// RgceArea: a range spanning every row (or column) is a whole-column (row) reference. +fn area(r0: u32, r1: u32, c0: u16, c1: u16) -> Result { + area_of(anchor(r0, c0)?, anchor(r1, c1)?) +} + +fn area_of(a: Anchor, b: Anchor) -> Result { + Ok(if a.row == 0 && b.row == LAST_ROW { + RefKind::Cols(a.col, a.col_abs, b.col, b.col_abs) + } else if a.col == 0 && b.col == LAST_COL { + RefKind::Rows(a.row, a.row_abs, b.row, b.row_abs) + } else { + RefKind::Range(a, b) + }) +} + +fn reference(sheet: Option, kind: RefKind) -> Expr { + match sheet { + Some(sheet) => Expr::Ref(Reference { sheet, kind }), + None => Expr::Error(CellError::Ref), + } +} + +/// Decodes a formula's `rgce` (tokens) with its `rgcb` (extra data for array constants and +/// cached areas). Returns the expression, with names in their file spelling, or why it can't be +/// represented. A shared formula's tokens are decoded once for each of its cells +/// (`Mode::Shared` with that cell), whose relative references are offsets from it. +pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Result { + if rgce.len() > MAX_RGCE { + return Err(Unsupported("formula too long")); + } + let mut t = Bytes { b: rgce, pos: 0 }; + let mut extra = Bytes { b: rgcb, pos: 0 }; + let mut stack: Stack = Vec::new(); + let mut array_values = MAX_ARRAY; + let mut ws = Spacing::default(); + while t.pos < rgce.len() { + let ptg = t.u8()?; + let mut kids = 0usize; + // Operand classes (reference / value / array) share one token number. + let id = if ptg & 0x60 != 0 { 0x20 | (ptg & 0x1F) } else { ptg }; + // An operand (a constant, reference or name) takes the spacing typed before it; operators, + // calls and parentheses place theirs below, and attribute and cache tokens take none. + let operand = !matches!(id, 0x03..=0x15 | 0x19 | 0x21 | 0x22 | 0x26..=0x29); + let height = stack.len(); + match id { + 0x03..=0x11 => { + let op = match id { + 0x03 => BinOp::Add, + 0x04 => BinOp::Sub, + 0x05 => BinOp::Mul, + 0x06 => BinOp::Div, + 0x07 => BinOp::Pow, + 0x08 => BinOp::Concat, + 0x09 => BinOp::Lt, + 0x0A => BinOp::Le, + 0x0B => BinOp::Eq, + 0x0C => BinOp::Ge, + 0x0D => BinOp::Gt, + 0x0E => BinOp::Ne, + 0x0F => BinOp::Intersect, + 0x10 => BinOp::Union, + _ => BinOp::Range, + }; + let b = pop(&mut stack, &mut kids)?; + let a = pop(&mut stack, &mut kids)?; + // Spacing before the operator's symbol follows the left operand. + let before = std::mem::take(&mut ws.before); + kids = kids.saturating_add(usize::from(!before.is_empty())); + let a = spaced_after(a, before); + push(&mut stack, kids, Expr::Binary(op, Box::new(a), Box::new(b)))?; + } + 0x12..=0x14 => { + let op = match id { + 0x12 => UnOp::Plus, + 0x13 => UnOp::Neg, + _ => UnOp::Percent, + }; + let x = pop(&mut stack, &mut kids)?; + // A sign's spacing comes before it; `%`'s before its symbol, after the operand. + let before = std::mem::take(&mut ws.before); + let e = if op == UnOp::Percent { + kids = kids.saturating_add(usize::from(!before.is_empty())); + Expr::Unary(op, Box::new(spaced_after(x, before))) + } else { + spaced_before(Expr::Unary(op, Box::new(x)), before) + }; + push(&mut stack, kids, e)?; + } + 0x15 => { + let x = pop(&mut stack, &mut kids)?; + let close = std::mem::take(&mut ws.close); + kids = kids.saturating_add(usize::from(!close.is_empty())); + let x = spaced_after(x, close); + let before = std::mem::take(&mut ws.open) + &std::mem::take(&mut ws.before); + push(&mut stack, kids, spaced_before(Expr::Paren(Box::new(x)), before))?; + } + 0x16 => push(&mut stack, kids, Expr::Missing)?, + // PtgStr: cch (u16, at most 255) and always UTF-16, unlike BIFF8. + 0x17 => { + let cch = usize::from(t.u16()?); + if cch > 255 { + return Err(Unsupported("text constant too long")); + } + push(&mut stack, kids, Expr::Text(Arc::from(t.chars(cch)?)))?; + } + 0x19 => { + let kind = t.u8()?; + if kind & 0x04 != 0 { + // PtgAttrChoose: jump table of cOffset + 1 entries. + let n = usize::from(t.u16()?) + 1; + t.take(n * 2)?; + } else { + let data = t.take(2)?; + if kind & 0x40 != 0 { + // PtgAttrSpace / PtgAttrSpaceSemi: PtgAttrSpaceType's `type` and `cch`. + let (kind, n) = (data.first().copied().unwrap_or(0), data.get(1).copied().unwrap_or(0)); + let text = if matches!(kind, 1 | 3 | 5) { "\n" } else { " " }.repeat(usize::from(n)); + match kind { + 0 | 1 | 6 => ws.before.push_str(&text), + 2 | 3 => ws.open.push_str(&text), + 4 | 5 => ws.close.push_str(&text), + _ => return Err(Unsupported("unknown spacing in a formula")), + } + } + } + if kind & 0x10 != 0 { + // PtgAttrSum: SUM of the single operand. + let x = pop(&mut stack, &mut kids)?; + let args = close_args(vec![x], std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call("SUM".into(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + // Semi (volatile), If, Goto, Baxcel: no effect on the expression. + } + 0x1C => { + let e = t.u8()?; + push(&mut stack, kids, Expr::Error(error_code(e).ok_or(Unsupported("unknown error constant"))?))?; + } + 0x1D => push(&mut stack, kids, Expr::Bool(t.u8()? != 0))?, + 0x1E => push(&mut stack, kids, Expr::Number(f64::from(t.u16()?)))?, + 0x1F => { + let n = t.f64()?; + push(&mut stack, kids, Expr::Number(n))?; + } + 0x20 => { + // PtgArray: 14 unused bytes (Excel leaves junk in them); the values are in rgcb. + t.take(14)?; + push(&mut stack, kids, array_constant(&mut extra, &mut array_values)?)?; + } + 0x21 => { + let iftab = t.u16()?; + let (name, args) = function(iftab).ok_or(Unsupported("unknown function"))?; + let n = usize::try_from(args).map_err(|_| Unsupported("unknown function argument count"))?; + let args = close_args(pop_n(&mut stack, n, &mut kids)?, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + 0x22 => { + let n = usize::from(t.u8()?); + let tab = t.u16()?; + if tab & 0x8000 != 0 { + return Err(Unsupported("macro sheet commands")); + } + let mut args = pop_n(&mut stack, n, &mut kids)?; + if tab & 0x7FFF == 0x00FF { + // A function called by name (a newer function, add-in or LAMBDA): the name + // comes first, as a PtgName to a hidden `_xlfn.` name for a newer function. + if args.is_empty() { + return Err(Unsupported("malformed function call")); + } + // Spacing typed after the `(` comes before the name's token: it belongs to the + // first argument. + let (lead, first) = match args.remove(0) { + Expr::Spaced(before, x, _) => (before, *x), + e => (String::new(), e), + }; + let name = match first { + Expr::Name(n) => n, + _ => return Err(Unsupported("function call through an expression")), + }; + if let Some(a) = args.first_mut() { + *a = spaced_before(std::mem::replace(a, Expr::Missing), lead); + } + // `PY(index, …)` runs a script stored elsewhere in the package, which this + // import doesn't read. `PY("code", …)` carries its code and becomes a Python cell. + let py = name.rsplit('.').next().is_some_and(|n| n.eq_ignore_ascii_case("PY")); + if py && !args.first().is_some_and(literal_text) { + return Err(Unsupported("Python code stored outside the cell")); + } + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(bare_function(name), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } else { + let (name, _) = function(tab & 0x7FFF).ok_or(Unsupported("unknown function"))?; + let args = close_args(args, std::mem::take(&mut ws.close)); + let call = spaced_before(Expr::Call(name.to_string(), args), std::mem::take(&mut ws.before)); + push(&mut stack, kids.saturating_add(1), call)?; + } + } + 0x23 => { + // PtgName: a 1-based index into every BrtName, hidden ones included. + let i = usize::try_from(t.u32()?).ok().and_then(|i| i.checked_sub(1)); + let name = i.and_then(|i| links.names.get(i)).ok_or(Unsupported("reference to a missing defined name"))?; + // Defined names are not imported from XLSB yet: a cell using one would calculate + // to #NAME?, so it keeps its saved result. Newer functions and LET parameters are + // hidden names that the formula text itself defines. + if !name.future && !is_param(&name.text) { + return Err(Unsupported("defined names")); + } + push(&mut stack, kids, Expr::Name(name.text.clone()))?; + } + 0x24 => { + let (r, c) = (t.u32()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Cell(anchor(r, c)?) }))?; + } + 0x25 => { + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: area(r0, r1, c0, c1)? }))?; + } + 0x26 => { + // PtgMemArea: a cache of the sub-expression that follows. Its rgcb entry + // (PtgExtraMem) is a count and 16 bytes per cached area: skip both. + t.take(6)?; + let n = usize::try_from(extra.u32()?).map_err(|_| TRUNC)?; + extra.take(n.checked_mul(16).ok_or(TRUNC)?)?; + } + // PtgMemErr, PtgMemNoMem: 6 bytes; PtgMemFunc: 2. The sub-expression follows them. + 0x27 | 0x28 => { + t.take(6)?; + } + 0x29 => { + t.take(2)?; + } + 0x2A => { + t.take(6)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x2B => { + t.take(12)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x39 => return Err(Unsupported("names in other workbooks or on other sheets")), + 0x3A => { + let ixti = t.u16()?; + let (r, c) = (t.u32()?, t.u16()?); + let kind = RefKind::Cell(anchor(r, c)?); + push(&mut stack, kids, reference(links.sheet_sel(ixti)?, kind))?; + } + 0x3B => { + let ixti = t.u16()?; + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + let kind = area(r0, r1, c0, c1)?; + push(&mut stack, kids, reference(links.sheet_sel(ixti)?, kind))?; + } + 0x3C | 0x3D => { + let ixti = t.u16()?; + t.take(if id == 0x3C { 6 } else { 12 })?; + // The sheet link must still be one the reader follows: an external #REF! stays cached. + links.sheet_sel(ixti)?; + push(&mut stack, kids, Expr::Error(CellError::Ref))?; + } + 0x01 => return Err(Unsupported("the shared or array formula form")), + 0x02 => return Err(Unsupported("what-if data tables")), + 0x18 => return Err(Unsupported("structured table references")), + 0x2C => { + let Mode::Shared(_) = mode else { return Err(Unsupported("relative references in a cell formula")) }; + let (r, c) = (t.u32()?, t.u16()?); + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind: RefKind::Cell(loc(r, c, mode)?) }))?; + } + 0x2D => { + let Mode::Shared(_) = mode else { return Err(Unsupported("relative references in a cell formula")) }; + let (r0, r1, c0, c1) = (t.u32()?, t.u32()?, t.u16()?, t.u16()?); + let kind = area_of(loc(r0, c0, mode)?, loc(r1, c1, mode)?)?; + push(&mut stack, kids, Expr::Ref(Reference { sheet: SheetSel::Current, kind }))?; + } + _ => return Err(Unsupported("unknown formula token")), + } + if operand && !ws.before.is_empty() && stack.len() == height + 1 { + let (e, depth) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + push(&mut stack, depth, spaced_before(e, std::mem::take(&mut ws.before)))?; + } + if stack.len() > MAX_RGCE { + return Err(Unsupported("formula too complex")); + } + } + let (e, _) = stack.pop().ok_or(Unsupported("malformed formula (operand missing)"))?; + if !stack.is_empty() { + return Err(Unsupported("malformed formula (unused operands)")); + } + Ok(grouped(e, false)) +} + +/// The name a function called through a hidden name is written with in `.xlsx`: that name +/// (`_xlfn.CONCAT`), except for the four ISO/IEC 29500 functions, which `.xlsx` names without the +/// prefix though `.xlsb` calls them as it calls newer functions. +fn bare_function(name: String) -> String { + const ISO: [&str; 4] = ["ISO.CEILING", "ECMA.CEILING", "NETWORKDAYS.INTL", "WORKDAY.INTL"]; + match name.get(..6).filter(|p| p.eq_ignore_ascii_case("_xlfn.")).and(name.get(6..)) { + Some(bare) if ISO.iter().any(|f| f.eq_ignore_ascii_case(bare)) => bare.to_string(), + _ => name, + } +} + +/// Text written out in the formula: a string, or strings joined with `&` (how Python code +/// longer than a string constant is written). +fn literal_text(e: &Expr) -> bool { + match e { + Expr::Text(_) => true, + Expr::Spaced(_, x, _) => literal_text(x), + Expr::Binary(BinOp::Concat, a, b) => literal_text(a) && literal_text(b), + _ => false, + } +} + +/// How many strings a [`literal_text`] chain joins, or `None` for anything else. It accepts +/// what [`literal_text`] does, typed spacing included, so a chain the Python check accepts is +/// one that is written flat. +fn literal_texts(e: &Expr) -> Option { + match e { + Expr::Text(_) => Some(1), + Expr::Spaced(_, x, _) => literal_texts(x), + Expr::Binary(BinOp::Concat, a, b) => literal_texts(a)?.checked_add(literal_texts(b)?), + _ => None, + } +} + +/// How tightly an expression binds when printed, as the formula parser reads it: binary +/// operators by [`BinOp::precedence`], prefix `+`/`-` at 60 and `%` at 70 (`-2^2` is `(-2)^2`); +/// anything else is one operand. +fn binding(e: &Expr) -> u8 { + match e { + Expr::Binary(op, ..) => op.precedence(), + Expr::Unary(UnOp::Neg | UnOp::Plus, _) => 60, + Expr::Unary(UnOp::Percent, _) => 70, + Expr::Spaced(_, x, _) => binding(x), + _ => u8::MAX, + } +} + +/// The strings of a [`literal_text`] chain, left to right. Spacing typed around a part of the +/// chain stays with that part's first and last strings, where it is written. +fn flatten_texts(e: Expr, out: &mut Vec) { + match e { + Expr::Binary(BinOp::Concat, a, b) => { + flatten_texts(*a, out); + flatten_texts(*b, out); + } + Expr::Spaced(before, x, after) if matches!(*x, Expr::Binary(BinOp::Concat, ..)) => { + let start = out.len(); + flatten_texts(*x, out); + if let Some(first) = out.get_mut(start) { + *first = spaced_before(std::mem::replace(first, Expr::Missing), before); + } + if let Some(last) = out.last_mut() { + *last = spaced_after(std::mem::replace(last, Expr::Missing), after); + } + } + text => out.push(text), + } +} + +fn paren(e: Expr) -> Expr { + Expr::Paren(Box::new(e)) +} + +/// The tree with the parentheses its text needs to mean the same. Tokens are reverse Polish, so +/// grouping lives in their order: Excel adds `PtgParen` wherever its text has parentheses, but +/// `1 2 + 3 *` (another writer's, or a crafted file's) would print as `1+2*3`. Binary operators +/// are left-associative; a union in a function's arguments needs parentheses of its own. +/// Recursion follows the decoded tree, which `push` bounds at `MAX_DEPTH` levels. +fn grouped(e: Expr, in_args: bool) -> Expr { + match e { + // Strings joined with `&` are written as one flat chain, however their tokens nest: `&` + // is associative, and `PY("…"&"…")` is read as Python code only in that form. The chain + // nests one level per string, so it is made only up to `MAX_DEPTH` strings, the bound + // `push` keeps on the decoded tree (Excel's 8,192 characters hold at most about 33 + // full-length constants). A longer one prints as its tokens nest, with the parentheses + // that needs: a balanced tree of thousands of strings is only a few levels deep, and + // printing or dropping a chain of thousands would recurse past the stack. + e @ Expr::Binary(BinOp::Concat, ..) if literal_texts(&e).is_some_and(|n| n <= MAX_DEPTH) => { + let mut texts = vec![]; + flatten_texts(e, &mut texts); + let mut texts = texts.into_iter(); + let first = texts.next().unwrap_or(Expr::Missing); + texts.fold(first, |a, b| Expr::Binary(BinOp::Concat, Box::new(a), Box::new(b))) + } + Expr::Binary(op, a, b) => { + let (a, b) = (grouped(*a, in_args), grouped(*b, in_args)); + let a = if binding(&a) < op.precedence() { paren(a) } else { a }; + let b = if binding(&b) <= op.precedence() { paren(b) } else { b }; + let e = Expr::Binary(op, Box::new(a), Box::new(b)); + if in_args && op == BinOp::Union { paren(e) } else { e } + } + Expr::Unary(op, x) => { + let x = grouped(*x, in_args); + // Each of `+`, `-` and `%` takes an operand that binds at least as tightly as a sign. The + // parser reads `-1%` as `-(1%)`, Excel's tokens as `(-1)%`: the same value, so a sign + // under `%` keeps Excel's spelling. + let needs = binding(&x) < 60; + Expr::Unary(op, Box::new(if needs { paren(x) } else { x })) + } + Expr::Paren(x) => paren(grouped(*x, false)), + Expr::Spaced(before, x, after) => Expr::Spaced(before, Box::new(grouped(*x, in_args)), after), + Expr::Call(name, args) => Expr::Call(name, args.into_iter().map(|a| grouped(a, true)).collect()), + other => other, + } +} + +/// PtgExtraArray ([MS-XLSB] 2.5.98.41): row and column counts, then `SerAr` values in row-major +/// order. The type codes are not BIFF8's: 0x00 is a number here, not a missing value. +fn array_constant(b: &mut Bytes<'_>, left: &mut usize) -> Result { + let rows = usize::try_from(b.u32()?).map_err(|_| TRUNC)?; + let cols = usize::try_from(b.u32()?).map_err(|_| TRUNC)?; + let values = rows.saturating_mul(cols); + if values == 0 { + return Err(Unsupported("empty array constant")); + } + // Charged before the rows are allocated, against what the formula's arrays may hold in all. + *left = left.checked_sub(values).ok_or(Unsupported("array constants too large"))?; + let mut out = Vec::with_capacity(rows); + for _ in 0..rows { + let mut row = Vec::with_capacity(cols); + for _ in 0..cols { + row.push(match b.u8()? { + 0x00 => Expr::Number(b.f64()?), + 0x01 => { + let cch = usize::from(b.u16()?); + if cch > 255 { + return Err(Unsupported("text constant too long")); + } + Expr::Text(Arc::from(b.chars(cch)?)) + } + 0x02 => Expr::Bool(b.u8()? != 0), + 0x04 => { + let e = b.u8()?; + b.take(3)?; + Expr::Error(error_code(e).ok_or(Unsupported("unknown error constant"))?) + } + _ => return Err(Unsupported("unknown array constant value")), + }); + } + out.push(row); + } + Ok(Expr::Array(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Postfix tokens for `n` empty strings joined by `&` as a balanced tree. + fn balanced_strings(n: usize, out: &mut Vec) { + if n == 1 { + out.extend([0x17, 0, 0]); + } else { + balanced_strings(n / 2, out); + balanced_strings(n - n / 2, out); + out.push(0x08); + } + } + + #[test] + fn a_spaced_part_of_a_string_chain_is_written_flat() { + // `"x"`, then `"="` typed with a space before it joined to `"1"`, then joined: the tokens + // nest to the right, and the space is on the inner chain. Written flat, as Python code + // must be, with the space where it was typed. + let s = |c: u8| [0x17, 1, 0, c, 0]; + let rgce = [&s(b'x')[..], &[0x19, 0x40, 0, 1], &s(b'=')[..], &s(b'1')[..], &[0x08, 0x08]].concat(); + let e = decode(&rgce, &[], &Links::default(), Mode::Cell).unwrap(); + assert_eq!(super::super::expr::print(&e), "\"x\"& \"=\"&\"1\""); + assert!(literal_text(&e) && literal_texts(&e) == Some(3)); + } + + #[test] + fn a_long_chain_of_strings_stays_within_the_depth_bound() { + // 4,096 strings and 4,095 `&` fill 16,383 token bytes, 13 levels deep as written. Made + // into one flat chain they would be 4,096 levels deep, past what printing and dropping + // the tree may recurse; on a small stack that overflows. They print as written instead. + let mut rgce = vec![]; + balanced_strings(4096, &mut rgce); + assert!(rgce.len() <= MAX_RGCE); + let text = std::thread::Builder::new() + .stack_size(256 * 1024) + .spawn(move || { + let e = decode(&rgce, &[], &Links::default(), Mode::Cell).unwrap(); + let text = super::super::expr::print(&e); + drop(e); + text + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(text.matches("\"\"").count(), 4096); + // A short chain, such as Python code split into constants, is still one flat chain. + let mut short = vec![]; + balanced_strings(4, &mut short); + let e = decode(&short, &[], &Links::default(), Mode::Cell).unwrap(); + assert_eq!(super::super::expr::print(&e), "\"\"&\"\"&\"\"&\"\""); + } +} diff --git a/crates/xlsx/src/xlsb/ftab.rs b/crates/xlsx/src/xlsb/ftab.rs new file mode 100644 index 0000000000..efd6e44264 --- /dev/null +++ b/crates/xlsx/src/xlsb/ftab.rs @@ -0,0 +1,521 @@ +//! The XLSB function table ([MS-XLSB] 2.5.98.10, `Ftab`): the functions a `PtgFunc` or +//! `PtgFuncVar` token calls by number. Up to 379 (0x17B) it is the table of [MS-XLS] 2.5.198.17, +//! which craft-xls also carries. The entries from 380 (0x17C) on are the rest of the XLSB table: +//! XLSB files call these functions by number, where `.xls` files call them by name. Kept apart from +//! craft-xls's copy: the two formats follow separate specifications. +//! +//! One entry is not in the specification's table: 468 (0x1D4) is CONVERT. The table has no row +//! for it, but its grammar lists `convert-params` among the fixed-argument functions, and Excel +//! writes `=CONVERT(1,"m","ft")` in `.xlsb` as a `PtgFunc` calling 0x1D4. + +/// (iftab, name, fixed argument count or -1 when the function takes a variable number of +/// arguments), sorted by number. +const FTAB: &[(u16, &str, i8)] = &[ + (0, "COUNT", -1), + (1, "IF", -1), + (2, "ISNA", 1), + (3, "ISERROR", 1), + (4, "SUM", -1), + (5, "AVERAGE", -1), + (6, "MIN", -1), + (7, "MAX", -1), + (8, "ROW", -1), + (9, "COLUMN", -1), + (10, "NA", 0), + (11, "NPV", -1), + (12, "STDEV", -1), + (13, "DOLLAR", -1), + (14, "FIXED", -1), + (15, "SIN", 1), + (16, "COS", 1), + (17, "TAN", 1), + (18, "ATAN", 1), + (19, "PI", 0), + (20, "SQRT", 1), + (21, "EXP", 1), + (22, "LN", 1), + (23, "LOG10", 1), + (24, "ABS", 1), + (25, "INT", 1), + (26, "SIGN", 1), + (27, "ROUND", 2), + (28, "LOOKUP", -1), + (29, "INDEX", -1), + (30, "REPT", 2), + (31, "MID", 3), + (32, "LEN", 1), + (33, "VALUE", 1), + (34, "TRUE", 0), + (35, "FALSE", 0), + (36, "AND", -1), + (37, "OR", -1), + (38, "NOT", 1), + (39, "MOD", 2), + (40, "DCOUNT", 3), + (41, "DSUM", 3), + (42, "DAVERAGE", 3), + (43, "DMIN", 3), + (44, "DMAX", 3), + (45, "DSTDEV", 3), + (46, "VAR", -1), + (47, "DVAR", 3), + (48, "TEXT", 2), + (49, "LINEST", -1), + (50, "TREND", -1), + (51, "LOGEST", -1), + (52, "GROWTH", -1), + (53, "GOTO", 1), + (54, "HALT", -1), + (55, "RETURN", -1), + (56, "PV", -1), + (57, "FV", -1), + (58, "NPER", -1), + (59, "PMT", -1), + (60, "RATE", -1), + (61, "MIRR", 3), + (62, "IRR", -1), + (63, "RAND", 0), + (64, "MATCH", -1), + (65, "DATE", 3), + (66, "TIME", 3), + (67, "DAY", 1), + (68, "MONTH", 1), + (69, "YEAR", 1), + (70, "WEEKDAY", -1), + (71, "HOUR", 1), + (72, "MINUTE", 1), + (73, "SECOND", 1), + (74, "NOW", 0), + (75, "AREAS", 1), + (76, "ROWS", 1), + (77, "COLUMNS", 1), + (78, "OFFSET", -1), + (79, "ABSREF", 2), + (80, "RELREF", 2), + (81, "ARGUMENT", -1), + (82, "SEARCH", -1), + (83, "TRANSPOSE", 1), + (84, "ERROR", -1), + (85, "STEP", 0), + (86, "TYPE", 1), + (87, "ECHO", -1), + (88, "SET.NAME", -1), + (89, "CALLER", 0), + (90, "DEREF", 1), + (91, "WINDOWS", -1), + (92, "SERIES", -1), + (93, "DOCUMENTS", -1), + (94, "ACTIVE.CELL", 0), + (95, "SELECTION", 0), + (96, "RESULT", -1), + (97, "ATAN2", 2), + (98, "ASIN", 1), + (99, "ACOS", 1), + (100, "CHOOSE", -1), + (101, "HLOOKUP", -1), + (102, "VLOOKUP", -1), + (103, "LINKS", -1), + (104, "INPUT", -1), + (105, "ISREF", 1), + (106, "GET.FORMULA", 1), + (107, "GET.NAME", -1), + (108, "SET.VALUE", 2), + (109, "LOG", -1), + (110, "EXEC", -1), + (111, "CHAR", 1), + (112, "LOWER", 1), + (113, "UPPER", 1), + (114, "PROPER", 1), + (115, "LEFT", -1), + (116, "RIGHT", -1), + (117, "EXACT", 2), + (118, "TRIM", 1), + (119, "REPLACE", 4), + (120, "SUBSTITUTE", -1), + (121, "CODE", 1), + (122, "NAMES", -1), + (123, "DIRECTORY", -1), + (124, "FIND", -1), + (125, "CELL", -1), + (126, "ISERR", 1), + (127, "ISTEXT", 1), + (128, "ISNUMBER", 1), + (129, "ISBLANK", 1), + (130, "T", 1), + (131, "N", 1), + (132, "FOPEN", -1), + (133, "FCLOSE", 1), + (134, "FSIZE", 1), + (135, "FREADLN", 1), + (136, "FREAD", 2), + (137, "FWRITELN", 2), + (138, "FWRITE", 2), + (139, "FPOS", -1), + (140, "DATEVALUE", 1), + (141, "TIMEVALUE", 1), + (142, "SLN", 3), + (143, "SYD", 4), + (144, "DDB", -1), + (145, "GET.DEF", -1), + (146, "REFTEXT", -1), + (147, "TEXTREF", -1), + (148, "INDIRECT", -1), + (149, "REGISTER", -1), + (150, "CALL", -1), + (151, "ADD.BAR", -1), + (152, "ADD.MENU", -1), + (153, "ADD.COMMAND", -1), + (154, "ENABLE.COMMAND", -1), + (155, "CHECK.COMMAND", -1), + (156, "RENAME.COMMAND", -1), + (157, "SHOW.BAR", -1), + (158, "DELETE.MENU", -1), + (159, "DELETE.COMMAND", -1), + (160, "GET.CHART.ITEM", -1), + (161, "DIALOG.BOX", 1), + (162, "CLEAN", 1), + (163, "MDETERM", 1), + (164, "MINVERSE", 1), + (165, "MMULT", 2), + (166, "FILES", -1), + (167, "IPMT", -1), + (168, "PPMT", -1), + (169, "COUNTA", -1), + (170, "CANCEL.KEY", -1), + (171, "FOR", -1), + (172, "WHILE", 1), + (173, "BREAK", 0), + (174, "NEXT", 0), + (175, "INITIATE", 2), + (176, "REQUEST", 2), + (177, "POKE", 3), + (178, "EXECUTE", 2), + (179, "TERMINATE", 1), + (180, "RESTART", -1), + (181, "HELP", -1), + (182, "GET.BAR", -1), + (183, "PRODUCT", -1), + (184, "FACT", 1), + (185, "GET.CELL", -1), + (186, "GET.WORKSPACE", 1), + (187, "GET.WINDOW", -1), + (188, "GET.DOCUMENT", -1), + (189, "DPRODUCT", 3), + (190, "ISNONTEXT", 1), + (191, "GET.NOTE", -1), + (192, "NOTE", -1), + (193, "STDEVP", -1), + (194, "VARP", -1), + (195, "DSTDEVP", 3), + (196, "DVARP", 3), + (197, "TRUNC", -1), + (198, "ISLOGICAL", 1), + (199, "DCOUNTA", 3), + (200, "DELETE.BAR", 1), + (201, "UNREGISTER", 1), + (204, "USDOLLAR", -1), + (205, "FINDB", -1), + (206, "SEARCHB", -1), + (207, "REPLACEB", 4), + (208, "LEFTB", -1), + (209, "RIGHTB", -1), + (210, "MIDB", 3), + (211, "LENB", 1), + (212, "ROUNDUP", 2), + (213, "ROUNDDOWN", 2), + (214, "ASC", 1), + (215, "DBCS", 1), + (216, "RANK", -1), + (219, "ADDRESS", -1), + (220, "DAYS360", -1), + (221, "TODAY", 0), + (222, "VDB", -1), + (223, "ELSE", 0), + (224, "ELSE.IF", 1), + (225, "END.IF", 0), + (226, "FOR.CELL", -1), + (227, "MEDIAN", -1), + (228, "SUMPRODUCT", -1), + (229, "SINH", 1), + (230, "COSH", 1), + (231, "TANH", 1), + (232, "ASINH", 1), + (233, "ACOSH", 1), + (234, "ATANH", 1), + (235, "DGET", 3), + (236, "CREATE.OBJECT", -1), + (237, "VOLATILE", -1), + (238, "LAST.ERROR", 0), + (239, "CUSTOM.UNDO", -1), + (240, "CUSTOM.REPEAT", -1), + (241, "FORMULA.CONVERT", -1), + (242, "GET.LINK.INFO", -1), + (243, "TEXT.BOX", -1), + (244, "INFO", 1), + (245, "GROUP", 0), + (246, "GET.OBJECT", -1), + (247, "DB", -1), + (248, "PAUSE", -1), + (251, "RESUME", -1), + (252, "FREQUENCY", 2), + (253, "ADD.TOOLBAR", -1), + (254, "DELETE.TOOLBAR", 1), + (256, "RESET.TOOLBAR", 1), + (257, "EVALUATE", 1), + (258, "GET.TOOLBAR", -1), + (259, "GET.TOOL", -1), + (260, "SPELLING.CHECK", -1), + (261, "ERROR.TYPE", 1), + (262, "APP.TITLE", -1), + (263, "WINDOW.TITLE", -1), + (264, "SAVE.TOOLBAR", -1), + (265, "ENABLE.TOOL", 3), + (266, "PRESS.TOOL", 3), + (267, "REGISTER.ID", -1), + (268, "GET.WORKBOOK", -1), + (269, "AVEDEV", -1), + (270, "BETADIST", -1), + (271, "GAMMALN", 1), + (272, "BETAINV", -1), + (273, "BINOMDIST", 4), + (274, "CHIDIST", 2), + (275, "CHIINV", 2), + (276, "COMBIN", 2), + (277, "CONFIDENCE", 3), + (278, "CRITBINOM", 3), + (279, "EVEN", 1), + (280, "EXPONDIST", 3), + (281, "FDIST", 3), + (282, "FINV", 3), + (283, "FISHER", 1), + (284, "FISHERINV", 1), + (285, "FLOOR", 2), + (286, "GAMMADIST", 4), + (287, "GAMMAINV", 3), + (288, "CEILING", 2), + (289, "HYPGEOMDIST", 4), + (290, "LOGNORMDIST", 3), + (291, "LOGINV", 3), + (292, "NEGBINOMDIST", 3), + (293, "NORMDIST", 4), + (294, "NORMSDIST", 1), + (295, "NORMINV", 3), + (296, "NORMSINV", 1), + (297, "STANDARDIZE", 3), + (298, "ODD", 1), + (299, "PERMUT", 2), + (300, "POISSON", 3), + (301, "TDIST", 3), + (302, "WEIBULL", 4), + (303, "SUMXMY2", 2), + (304, "SUMX2MY2", 2), + (305, "SUMX2PY2", 2), + (306, "CHITEST", 2), + (307, "CORREL", 2), + (308, "COVAR", 2), + (309, "FORECAST", 3), + (310, "FTEST", 2), + (311, "INTERCEPT", 2), + (312, "PEARSON", 2), + (313, "RSQ", 2), + (314, "STEYX", 2), + (315, "SLOPE", 2), + (316, "TTEST", 4), + (317, "PROB", -1), + (318, "DEVSQ", -1), + (319, "GEOMEAN", -1), + (320, "HARMEAN", -1), + (321, "SUMSQ", -1), + (322, "KURT", -1), + (323, "SKEW", -1), + (324, "ZTEST", -1), + (325, "LARGE", 2), + (326, "SMALL", 2), + (327, "QUARTILE", 2), + (328, "PERCENTILE", 2), + (329, "PERCENTRANK", -1), + (330, "MODE", -1), + (331, "TRIMMEAN", 2), + (332, "TINV", 2), + (334, "MOVIE.COMMAND", -1), + (335, "GET.MOVIE", -1), + (336, "CONCATENATE", -1), + (337, "POWER", 2), + (338, "PIVOT.ADD.DATA", -1), + (339, "GET.PIVOT.TABLE", -1), + (340, "GET.PIVOT.FIELD", -1), + (341, "GET.PIVOT.ITEM", -1), + (342, "RADIANS", 1), + (343, "DEGREES", 1), + (344, "SUBTOTAL", -1), + (345, "SUMIF", -1), + (346, "COUNTIF", 2), + (347, "COUNTBLANK", 1), + (348, "SCENARIO.GET", -1), + (349, "OPTIONS.LISTS.GET", 1), + (350, "ISPMT", 4), + (351, "DATEDIF", 3), + (352, "DATESTRING", 1), + (353, "NUMBERSTRING", 2), + (354, "ROMAN", -1), + (355, "OPEN.DIALOG", -1), + (356, "SAVE.DIALOG", -1), + (357, "VIEW.GET", -1), + (358, "GETPIVOTDATA", -1), + (359, "HYPERLINK", -1), + (360, "PHONETIC", 1), + (361, "AVERAGEA", -1), + (362, "MAXA", -1), + (363, "MINA", -1), + (364, "STDEVPA", -1), + (365, "VARPA", -1), + (366, "STDEVA", -1), + (367, "VARA", -1), + (368, "BAHTTEXT", 1), + (369, "THAIDAYOFWEEK", 1), + (370, "THAIDIGIT", 1), + (371, "THAIMONTHOFYEAR", 1), + (372, "THAINUMSOUND", 1), + (373, "THAINUMSTRING", 1), + (374, "THAISTRINGLENGTH", 1), + (375, "ISTHAIDIGIT", 1), + (376, "ROUNDBAHTDOWN", 1), + (377, "ROUNDBAHTUP", 1), + (378, "THAIYEAR", 1), + (379, "RTD", -1), + (380, "CUBEVALUE", -1), + (381, "CUBEMEMBER", -1), + (382, "CUBEMEMBERPROPERTY", 3), + (383, "CUBERANKEDMEMBER", -1), + (384, "HEX2BIN", -1), + (385, "HEX2DEC", 1), + (386, "HEX2OCT", -1), + (387, "DEC2BIN", -1), + (388, "DEC2HEX", -1), + (389, "DEC2OCT", -1), + (390, "OCT2BIN", -1), + (391, "OCT2HEX", -1), + (392, "OCT2DEC", 1), + (393, "BIN2DEC", 1), + (394, "BIN2OCT", -1), + (395, "BIN2HEX", -1), + (396, "IMSUB", 2), + (397, "IMDIV", 2), + (398, "IMPOWER", 2), + (399, "IMABS", 1), + (400, "IMSQRT", 1), + (401, "IMLN", 1), + (402, "IMLOG2", 1), + (403, "IMLOG10", 1), + (404, "IMSIN", 1), + (405, "IMCOS", 1), + (406, "IMEXP", 1), + (407, "IMARGUMENT", 1), + (408, "IMCONJUGATE", 1), + (409, "IMAGINARY", 1), + (410, "IMREAL", 1), + (411, "COMPLEX", -1), + (412, "IMSUM", -1), + (413, "IMPRODUCT", -1), + (414, "SERIESSUM", 4), + (415, "FACTDOUBLE", 1), + (416, "SQRTPI", 1), + (417, "QUOTIENT", 2), + (418, "DELTA", -1), + (419, "GESTEP", -1), + (420, "ISEVEN", 1), + (421, "ISODD", 1), + (422, "MROUND", 2), + (423, "ERF", -1), + (424, "ERFC", 1), + (425, "BESSELJ", 2), + (426, "BESSELK", 2), + (427, "BESSELY", 2), + (428, "BESSELI", 2), + (429, "XIRR", -1), + (430, "XNPV", 3), + (431, "PRICEMAT", -1), + (432, "YIELDMAT", -1), + (433, "INTRATE", -1), + (434, "RECEIVED", -1), + (435, "DISC", -1), + (436, "PRICEDISC", -1), + (437, "YIELDDISC", -1), + (438, "TBILLEQ", 3), + (439, "TBILLPRICE", 3), + (440, "TBILLYIELD", 3), + (441, "PRICE", -1), + (442, "YIELD", -1), + (443, "DOLLARDE", 2), + (444, "DOLLARFR", 2), + (445, "NOMINAL", 2), + (446, "EFFECT", 2), + (447, "CUMPRINC", 6), + (448, "CUMIPMT", 6), + (449, "EDATE", 2), + (450, "EOMONTH", 2), + (451, "YEARFRAC", -1), + (452, "COUPDAYBS", -1), + (453, "COUPDAYS", -1), + (454, "COUPDAYSNC", -1), + (455, "COUPNCD", -1), + (456, "COUPNUM", -1), + (457, "COUPPCD", -1), + (458, "DURATION", -1), + (459, "MDURATION", -1), + (460, "ODDLPRICE", -1), + (461, "ODDLYIELD", -1), + (462, "ODDFPRICE", -1), + (463, "ODDFYIELD", -1), + (464, "RANDBETWEEN", 2), + (465, "WEEKNUM", -1), + (466, "AMORDEGRC", -1), + (467, "AMORLINC", -1), + (468, "CONVERT", 3), + (469, "ACCRINT", -1), + (470, "ACCRINTM", -1), + (471, "WORKDAY", -1), + (472, "NETWORKDAYS", -1), + (473, "GCD", -1), + (474, "MULTINOMIAL", -1), + (475, "LCM", -1), + (476, "FVSCHEDULE", 2), + (477, "CUBEKPIMEMBER", -1), + (478, "CUBESET", -1), + (479, "CUBESETCOUNT", 1), + (480, "IFERROR", 2), + (481, "COUNTIFS", -1), + (482, "SUMIFS", -1), + (483, "AVERAGEIF", -1), + (484, "AVERAGEIFS", -1), +]; + +/// The function a `PtgFunc` or `PtgFuncVar` calls: its name and fixed argument count (-1 when it +/// takes a variable number). `None` for a number the table doesn't assign. +pub(super) fn function(iftab: u16) -> Option<(&'static str, i8)> { + FTAB.binary_search_by_key(&iftab, |(i, _, _)| *i).ok().and_then(|i| FTAB.get(i)).map(|(_, n, a)| (*n, *a)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn xlsb_function_numbers() { + // `function` binary-searches the table: sorted, each number once. + assert!(FTAB.windows(2).all(|w| w[0].0 < w[1].0)); + // The [MS-XLS] part, unchanged. + assert_eq!(function(0), Some(("COUNT", -1))); + assert_eq!(function(379), Some(("RTD", -1))); + // [MS-XLSB] 2.5.98.10 continues the table from 0x17C. Excel writes these by number in + // XLSB: PtgFunc for a fixed argument count, PtgFuncVar otherwise. + assert_eq!(function(0x17C), Some(("CUBEVALUE", -1))); + assert_eq!(function(449), Some(("EDATE", 2))); + assert_eq!(function(480), Some(("IFERROR", 2))); + assert_eq!(function(482), Some(("SUMIFS", -1))); + // Not in the specification's table, but what Excel writes for CONVERT. + assert_eq!(function(0x1D4), Some(("CONVERT", 3))); + assert_eq!(function(0x17B), Some(("RTD", -1))); + assert_eq!(function(0x1E5), None); + } +} diff --git a/crates/xlsx/tests/common/mod.rs b/crates/xlsx/tests/common/mod.rs index 59d3d83727..30703b3cd5 100644 --- a/crates/xlsx/tests/common/mod.rs +++ b/crates/xlsx/tests/common/mod.rs @@ -3,12 +3,15 @@ use std::collections::BTreeMap; -use craft_xlsx::{CellRef, Error, Limits, Package, Range, SheetKind, Value, Visibility}; +use craft_xlsx::{CellFormula, CellRef, Error, Limits, Package, Range, SheetKind, Value, Visibility}; pub struct Sheet { pub name: String, pub visibility: Visibility, pub cells: BTreeMap, + /// Every cell's formula, and its cell metadata index (`cm`), where it has one. + pub formulas: BTreeMap, + pub cell_metadata: BTreeMap, pub merges: Vec, } @@ -16,6 +19,11 @@ impl Sheet { pub fn value(&self, at: CellRef) -> Value { self.cells.get(&at).cloned().unwrap_or_default() } + + /// The formula text at `at`, if the cell has a formula. + pub fn formula(&self, at: CellRef) -> Option<&str> { + self.formulas.get(&at).map(|f| f.text.as_str()) + } } pub struct Book { @@ -37,8 +45,15 @@ pub fn read_with(bytes: &[u8], limits: &Limits) -> Result { continue; } let mut cells = BTreeMap::new(); + let (mut formulas, mut cell_metadata) = (BTreeMap::new(), BTreeMap::new()); let part = p.sheet(e, |row| { for c in row.cells { + if let Some(f) = c.formula { + formulas.insert(c.at, f); + } + if let Some(m) = c.cell_metadata { + cell_metadata.insert(c.at, m); + } let v = c.value.resolve(&strings, wb.date_1904); if !v.is_empty() { cells.insert(c.at, v); @@ -46,7 +61,7 @@ pub fn read_with(bytes: &[u8], limits: &Limits) -> Result { } Ok(()) })?; - book.sheets.push(Sheet { name: e.name.clone(), visibility: e.visibility, cells, merges: part.merges }); + book.sheets.push(Sheet { name: e.name.clone(), visibility: e.visibility, cells, formulas, cell_metadata, merges: part.merges }); } book.warnings = p.warnings().to_vec(); Ok(book) diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index cef6d9cbe6..748d1b86d9 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -5,7 +5,7 @@ mod common; use common::{read, read_with}; use craft_xlsx::testing::zip; -use craft_xlsx::{CellError, CellRef, Error, Limits, Range, SheetKind, Value, Visibility, is_xlsb}; +use craft_xlsx::{CellError, CellRef, Error, FormulaKind, Limits, Range, SheetKind, Value, Visibility, is_xlsb}; const ROOT: &str = r#""#; const RELS: &str = r#""#; @@ -442,3 +442,641 @@ fn phonetic_runs_use_documented_size_and_tolerate_padding() { } assert!(read(&file(&worksheet(&[row(0), cell(62, 0, &phonetic(2, 12))].concat(), &[]))).is_err()); } + +/// A formula cell (`BrtFmlaNum`, cached 0) with its own tokens and extra data. +fn formula_cell(col: u32, rgce: &[u8], rgcb: &[u8]) -> Vec { + let mut data = col.to_le_bytes().to_vec(); + data.extend([0; 4]); + data.extend(0f64.to_le_bytes()); + data.extend([0; 2]); + data.extend((rgce.len() as u32).to_le_bytes()); + data.extend(rgce); + data.extend((rgcb.len() as u32).to_le_bytes()); + data.extend(rgcb); + record(9, &data) +} + +fn name(flags: u32, text: &str) -> Vec { + let mut data = flags.to_le_bytes().to_vec(); + data.push(0); + data.extend(u32::MAX.to_le_bytes()); // Workbook scope. + data.extend(wide(text)); + data.extend([2, 0, 0, 0, 0x1c, 0x1d, 0, 0, 0, 0]); // Formula `#NAME?`, no extra data. + data.extend(u32::MAX.to_le_bytes()); // No comment. + record(39, &data) +} + +/// `book(false)` with a supporting-link block and defined names, as Excel writes them: this +/// workbook, then another; sheet links Data, Hidden, Data:Hidden, a deleted sheet and the other +/// workbook; hidden names for CONCAT, LET and a LET parameter, then the user name Rate. +fn book_with_links(extern_sheet: &[u8]) -> Vec { + let plain = book(false); + let end = record(132, &[]); + let mut out = plain[..plain.len() - end.len()].to_vec(); + out.extend(record(353, &[])); + out.extend(record(357, &[])); + out.extend(record(355, &wide("rId9"))); + out.extend(record(362, extern_sheet)); + out.extend(record(354, &[])); + const FUTURE: u32 = 0x0002_000b; + out.extend(name(FUTURE, "_xlfn.CONCAT")); + out.extend(name(FUTURE, "_xlfn.LET")); + out.extend(name(0x0002_0019, "_xlpm.x")); + out.extend(name(0, "Rate")); + out.extend(end); + out +} + +fn xti() -> Vec { + let mut out = 5u32.to_le_bytes().to_vec(); + for (book, first, last) in [(0u32, 0i32, 0i32), (0, 1, 1), (0, 0, 1), (0, -1, -1), (1, 0, 0)] { + out.extend(book.to_le_bytes()); + out.extend(first.to_le_bytes()); + out.extend(last.to_le_bytes()); + } + out +} + +fn loc(row: u32, col: u16) -> Vec { + [&row.to_le_bytes()[..], &col.to_le_bytes()].concat() +} + +/// Relative row and column flags of a `ColRelShort`. +const REL: u16 = 0xC000; + +fn warned(wb: &common::Book, why: &str) -> bool { + wb.warnings.iter().any(|w| w.contains("kept as their saved results") && w.contains(why)) +} + +#[test] +fn cell_formulas_are_read_in_their_xlsx_spelling() { + let ref3d = |ixti: u16, row: u32, col: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(row, col)].concat(); + let cells: Vec<(u32, Vec, Vec)> = vec![ + (1, [&[0x44u8][..], &loc(0, REL), &[0x1E, 2, 0, 0x05]].concat(), vec![]), + (2, [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &0u16.to_le_bytes(), &REL.to_le_bytes(), &[0x19, 0x10, 0, 0]].concat(), vec![]), + (3, ref3d(1, 1, 1 | REL), vec![]), + ( + 4, + [ + &[0x3Bu8][..], + &2u16.to_le_bytes(), + &0u32.to_le_bytes(), + &0xFFFFFu32.to_le_bytes(), + &REL.to_le_bytes(), + &REL.to_le_bytes(), + &[0x19, 0x10, 0, 0], + ] + .concat(), + vec![], + ), + (5, [&[0x23u8, 1, 0, 0, 0][..], &[0x17, 1, 0, b'a', 0], &[0x17, 1, 0, b'b', 0], &[0x42, 3, 0xFF, 0]].concat(), vec![]), + (6, vec![0x1E, 1, 0, 0x1E, 0, 0, 0x06, 0x1E, 2, 0, 0x41, 0xE0, 0x01], vec![]), + ( + 7, + [&[0x60u8][..], &[0xAB; 14]].concat(), + [&2u32.to_le_bytes()[..], &2u32.to_le_bytes(), &[0], &1f64.to_le_bytes(), &[1, 1, 0, b'x', 0], &[2, 1], &[4, 0x2A, 0, 0, 0]].concat(), + ), + ( + 8, + [&[0x23u8, 2, 0, 0, 0][..], &[0x23, 3, 0, 0, 0, 0x1E, 1, 0], &[0x23, 3, 0, 0, 0, 0x1E, 1, 0, 0x03], &[0x42, 4, 0xFF, 0]].concat(), + vec![], + ), + (9, ref3d(3, 0, 0), vec![]), + (10, [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &REL.to_le_bytes(), &REL.to_le_bytes(), &[0x41, 20, 0]].concat(), vec![]), + // Kept as their saved results: + (11, vec![0x43, 4, 0, 0, 0, 0x1E, 2, 0, 0x05], vec![]), + (12, ref3d(4, 0, REL), vec![]), + (13, vec![0x01, 0, 0, 0, 0], vec![0, 0, 0, 0]), // Part of a shared formula at A1 that isn't one. + ]; + let mut data = row(0); + data.extend(cell(5, 0, &3.0f64.to_le_bytes())); + for (col, rgce, rgcb) in &cells { + data.extend(formula_cell(*col, rgce, rgcb)); + } + data.extend(record(49, &1u32.to_le_bytes())); // BrtCellMeta: the next formula is a dynamic array. + data.extend(formula_cell(14, &[0x1E, 1, 0], &[])); + data.extend(formula_cell(15, &[0x18, 0x19, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], &[])); // A table reference. + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let sheet = &wb.sheets[0]; + let got: Vec<_> = (1..=15).map(|c| sheet.formula(CellRef::new(0, c))).collect(); + // As an `.xlsx` file holds them: names in their file spelling (`_xlfn.`, `_xlpm.`), and no + // implicit `@`, which is how a calculator reads a legacy formula, not how the file spells it. + let want = [ + Some("A1*2"), + Some("SUM($A$1:A2)"), + Some("Hidden!B2"), + Some("SUM(Data:Hidden!A:A)"), + Some("_xlfn.CONCAT(\"a\",\"b\")"), + Some("IFERROR(1/0,2)"), + Some("{1,\"x\";TRUE,#N/A}"), + Some("_xlfn.LET(_xlpm.x,1,_xlpm.x+1)"), + Some("#REF!"), + Some("SQRT(A1:A2)"), + None, + None, + None, + // A BrtCellMeta before a cell gives it cell metadata, as `cm` does in .xlsx. + Some("1"), + None, + ]; + assert_eq!(got, want); + assert!(sheet.formulas.values().all(|f| f.kind == FormulaKind::Normal)); + assert_eq!(sheet.cell_metadata.iter().collect::>(), [(&CellRef::new(0, 14), &1)]); + // Every formula cell keeps its saved result as its value. + assert!((1..=15).all(|c| sheet.value(CellRef::new(0, c)) == Value::Number(0.0))); + for why in ["defined names", "other workbooks", "missing from the file", "structured table references"] { + assert!(warned(&wb, why), "{why}: {:?}", wb.warnings); + } +} + +#[test] +fn unreadable_links_keep_every_formula_as_its_value() { + // A sheet-link count past the spec's limit, and a truncated list: the file opens as it did + // before formulas were read, with values only. + let mut truncated = xti(); + truncated.truncate(20); + for extern_sheet in [70_000u32.to_le_bytes().to_vec(), truncated] { + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[])].concat(); + let wb = read(&package(&book_with_links(&extern_sheet), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + assert!(wb.warnings.iter().any(|w| w.contains("could not be read")), "{:?}", wb.warnings); + } +} + +#[test] +fn formula_grouping_follows_token_order() { + // Reverse-Polish tokens group by their order alone. Excel writes PtgParen wherever its text + // has parentheses, but another writer need not: the text gets the ones it needs to mean the + // same, and no more. + let a = |row: u32| [&[0x24u8][..], &loc(row, REL)].concat(); + let int = |n: u8| vec![0x1E, n, 0]; + let cases: Vec<(Vec, &str)> = vec![ + ([int(1), int(2), vec![0x03], int(3), vec![0x05]].concat(), "(1+2)*3"), + ([int(1), int(2), int(3), vec![0x04, 0x04]].concat(), "1-(2-3)"), + ([int(1), int(2), vec![0x04], int(3), vec![0x04]].concat(), "1-2-3"), + ([int(2), vec![0x13], int(2), vec![0x07]].concat(), "-2^2"), + ([int(2), int(2), vec![0x07, 0x13]].concat(), "-(2^2)"), + // Excel's tokens for its own `-1%`: the parser groups it the other way, to the same value. + ([int(1), vec![0x13, 0x14]].concat(), "-1%"), + ([int(1), int(2), vec![0x03, 0x14]].concat(), "(1+2)%"), + ([a(0), a(1), vec![0x10], vec![0x19, 0x10, 0, 0]].concat(), "SUM((A1,A2))"), + ([int(1), int(2), vec![0x03, 0x15], int(3), vec![0x05]].concat(), "(1+2)*3"), + ]; + let data: Vec = + [row(0)].into_iter().chain(cases.iter().enumerate().map(|(i, (rgce, _))| formula_cell(i as u32, rgce, &[]))).flatten().collect(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + for (i, (_, want)) in cases.iter().enumerate() { + assert_eq!(wb.sheets[0].formula(CellRef::new(0, i as u32)), Some(*want)); + } +} + +#[test] +fn functions_past_0x17b_are_called_by_number() { + // [MS-XLSB] 2.5.98.10's numbers past the .xls table: IFERROR (PtgFunc) and SUMIFS (PtgFuncVar). + let sumifs = [&[0x1Eu8, 1, 0][..], &[0x1E, 2, 0], &[0x17, 2, 0, b'>', 0, b'0', 0], &[0x42, 3, 0xE2, 0x01]].concat(); + let data = [row(0), formula_cell(0, &[0x1E, 1, 0, 0x1E, 2, 0, 0x41, 0xE0, 0x01], &[]), formula_cell(1, &sumifs, &[])].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("IFERROR(1,2)")); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), Some("SUMIFS(1,2,\">0\")")); +} + +#[test] +fn hostile_formula_tokens_keep_the_saved_result() { + let mut deep = vec![0x1E, 1, 0]; + deep.resize(16384, 0x15); // Thousands of parentheses: refused by the depth guard. + let empty_array = [&[0x60u8][..], &[0; 14]].concat(); + let bad: Vec<(Vec, Vec)> = vec![ + (vec![0x1E, 1], vec![]), // Truncated PtgInt. + (vec![0x17, 1, 0, 0x00, 0xD8], vec![]), // Unpaired surrogate. + (vec![0x17, 0, 1], vec![]), // Text constant over 255. + ([&[0x24u8][..], &loc(1_048_576, 0)].concat(), vec![]), // Row past the grid. + (empty_array.clone(), vec![0; 8]), // Empty array constant. + (empty_array, vec![0xFF; 8]), // Huge one. + (vec![0x1E, 1, 0, 0x1E, 2, 0], vec![]), // Unused operand. + (vec![0x21, 0xD4, 0x01], vec![]), // Unassigned function number. + (vec![0x2C, 0, 0, 0, 0, 0, 0], vec![]), // PtgRefN outside a shared formula. + (vec![0x23, 0xFF, 0xFF, 0xFF, 0xFF], vec![]), // Name index past the list. + ([&[0x5Au8][..], &9u16.to_le_bytes(), &loc(0, 0)].concat(), vec![]), // Missing sheet link. + (deep, vec![]), + ]; + for (rgce, rgcb) in bad { + let data = [row(0), formula_cell(0, &rgce, &rgcb)].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None, "{rgce:?}"); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + } +} + +#[test] +fn python_formulas_need_their_code_in_the_cell() { + // `PY("code", 0)` carries its code; `PY(0, 0)` names a script elsewhere in the package, which + // the reader doesn't read, and keeps its saved result. + let mut book = book_with_links(&xti()); + let end = record(132, &[]); + book.truncate(book.len() - end.len()); + book.extend(name(0x0002_000b, "_xlfn._xlws.PY")); + book.extend(end); + let py = |arg: &[u8]| [&[0x23u8, 5, 0, 0, 0][..], arg, &[0x1E, 0, 0, 0x42, 3, 0xFF, 0]].concat(); + // Code longer than one string constant is written as constants joined with `&`. + let joined = [&[0x17u8, 1, 0, b'1', 0][..], &[0x17, 2, 0, b'+', 0, b'1', 0], &[0x08]].concat(); + // The same strings nested to the right, `"1"&("+"&"1")` by token order: still one flat chain. + let nested = [&[0x17u8, 1, 0, b'1', 0][..], &[0x17, 1, 0, b'+', 0], &[0x17, 1, 0, b'1', 0], &[0x08, 0x08]].concat(); + let data = [ + row(0), + formula_cell(0, &py(&[0x17, 1, 0, b'1', 0]), &[]), + formula_cell(1, &py(&[0x1E, 0, 0]), &[]), + formula_cell(2, &py(&joined), &[]), + formula_cell(3, &py(&nested), &[]), + ] + .concat(); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let formula = |c| wb.sheets[0].formula(CellRef::new(0, c)); + assert_eq!(formula(0), Some("_xlfn._xlws.PY(\"1\",0)")); + assert_eq!(formula(1), None); + assert_eq!(formula(2), Some("_xlfn._xlws.PY(\"1\"&\"+1\",0)")); + assert_eq!(formula(3), Some("_xlfn._xlws.PY(\"1\"&\"+\"&\"1\",0)")); + assert!(warned(&wb, "Python code stored outside"), "{:?}", wb.warnings); +} + +#[test] +fn formula_text_past_the_allowance_keeps_the_saved_result() { + // `1` takes the last byte of a one-byte allowance; the next formula doesn't fit. + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[]), formula_cell(1, &[0x1E, 1, 0], &[])].concat(); + let limits = Limits { binary_formula_text: 1, ..Limits::default() }; + let wb = read_with(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES), &limits).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("1")); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), None); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +fn range_formula(id: u16, (r0, c0, r1, c1): (u32, u32, u32, u32), rgce: &[u8]) -> Vec { + let mut data = vec![]; + for n in [r0, r1, c0, c1] { + data.extend(n.to_le_bytes()); + } + if id == 426 { + data.push(0x08); // The flags Excel writes for an ordinary array. + } + data.extend((rgce.len() as u32).to_le_bytes()); + data.extend(rgce); + data.extend(0u32.to_le_bytes()); + record(id, &data) +} + +/// A cell of the shared or array formula whose first cell is `row`, `col` (PtgExp + PtgExtraCol). +fn part(col: u32, (row, first_col): (u32, u32)) -> Vec { + formula_cell(col, &[&[0x01u8][..], &row.to_le_bytes()].concat(), &first_col.to_le_bytes()) +} + +fn ref_n(row: i32, col: u16) -> Vec { + [&[0x4Cu8][..], &row.to_le_bytes(), &col.to_le_bytes()].concat() +} + +fn at(a1: &str) -> CellRef { + CellRef::parse(a1).unwrap() +} + +#[test] +fn shared_array_and_dynamic_formulas_read_as_from_xlsx() { + // As Excel writes them: C1:C3 share `A1*10` (PtgRefN, column offset -2 as 16382); D1:E2 + // share `$A1+A$1`; F1:F2 hold the Ctrl+Shift+Enter array {=A1:A2*2}; G1 spills `=A1:A2`. + let area = [&[0x45u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &REL.to_le_bytes(), &REL.to_le_bytes()].concat(); + let mut data = row(0); + data.extend(cell(5, 0, &1.0f64.to_le_bytes())); + data.extend(part(2, (0, 2))); + data.extend(range_formula(427, (0, 2, 2, 2), &[ref_n(0, 16382 | REL), vec![0x1E, 10, 0, 0x05]].concat())); + data.extend(part(3, (0, 3))); + data.extend(range_formula(427, (0, 3, 1, 4), &[ref_n(0, 0x8000), ref_n(0, 16381 | 0x4000), vec![0x03]].concat())); + data.extend(part(4, (0, 3))); + data.extend(part(5, (0, 5))); + data.extend(range_formula(426, (0, 5, 1, 5), &[area.clone(), vec![0x1E, 2, 0, 0x05]].concat())); + data.extend(record(49, &1u32.to_le_bytes())); + data.extend(record(50, &1u32.to_le_bytes())); // BrtValueMeta in between, as Excel writes for a spill error. + data.extend(part(6, (0, 6))); + data.extend(range_formula(426, (0, 6, 1, 6), &area)); + data.extend(row(1)); + data.extend(cell(5, 0, &2.0f64.to_le_bytes())); + for (col, first) in [(2, (0, 2)), (3, (0, 3)), (4, (0, 3)), (5, (0, 5)), (6, (0, 6))] { + data.extend(part(col, first)); + } + data.extend(row(2)); + data.extend(part(2, (0, 2))); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let sheet = &wb.sheets[0]; + let formula = |a: &str| sheet.formulas.get(&at(a)); + // Each cell of a shared formula has its own text, decoded at the cell: the first with the + // group's range, all with its index. + for (a, want, si) in [ + ("C1", "A1*10", 0), + ("C2", "A2*10", 0), + ("C3", "A3*10", 0), + ("D1", "$A1+A$1", 1), + ("E1", "$A1+B$1", 1), + ("D2", "$A2+A$1", 1), + ("E2", "$A2+B$1", 1), + ] { + let f = formula(a).unwrap_or_else(|| panic!("{a}")); + assert_eq!((f.kind, f.text.as_str(), f.shared_index), (FormulaKind::Shared, want, Some(si)), "{a}"); + } + assert_eq!(formula("C1").and_then(|f| f.range), Range::parse("C1:C3")); + assert_eq!(formula("D1").and_then(|f| f.range), Range::parse("D1:E2")); + assert_eq!(formula("C2").and_then(|f| f.range), None); + // An array formula's first cell has it, with its range; a dynamic array's has its cell + // metadata too, as `cm` in .xlsx, though Excel wrote a BrtValueMeta in between. + let f1 = formula("F1").unwrap(); + assert_eq!((f1.kind, f1.text.as_str(), f1.range), (FormulaKind::Array, "A1:A2*2", Range::parse("F1:F2"))); + let g1 = formula("G1").unwrap(); + assert_eq!((g1.kind, g1.text.as_str(), g1.range), (FormulaKind::Array, "A1:A2", Range::parse("G1:G2"))); + assert_eq!(sheet.cell_metadata.get(&at("G1")), Some(&1)); + assert_eq!(sheet.cell_metadata.get(&at("F1")), None); + // Their other cells have no formula and keep their saved results, as in .xlsx. + for a in ["F2", "G2"] { + assert!(formula(a).is_none(), "{a}"); + assert_eq!(sheet.value(at(a)), Value::Number(0.0), "{a}"); + } + assert!(!wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); +} + +#[test] +fn unreadable_shared_formulas_keep_their_values() { + // A shared formula with an unsupported token, a range that doesn't start at its first cell, + // a truncated record, and a first cell with no formula record after it: every cell of each + // keeps its saved result, and the file opens. + let unknown = range_formula(427, (0, 0, 1, 0), &[0xFF]); + let wrong_start = range_formula(427, (0, 1, 1, 1), &[0x1E, 1, 0]); + // A well-framed record whose payload stops before rgcb's length. + let short: Vec = [&[0u8; 4][..], &1u32.to_le_bytes(), &[0; 8], &3u32.to_le_bytes(), &[0x1E, 1, 0]].concat(); + let truncated = record(427, &short); + for after_first in [unknown, wrong_start, truncated, cell(5, 1, &1.0f64.to_le_bytes())] { + let data = [row(0), part(0, (0, 0)), after_first, row(1), part(0, (0, 0))].concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + for r in [0, 1] { + assert_eq!(wb.sheets[0].formula(CellRef::new(r, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(r, 0)), Value::Number(0.0)); + } + assert!(wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); + } +} + +#[test] +fn shared_formulas_wrap_and_may_start_inside_their_range() { + // `=` the cell to the left (column offset -1, written 16383), shared over A1:B2 from B1: A1 + // isn't part of it. In column A the offset wraps around the grid, as [MS-XLSB] defines it. + let left = ref_n(0, 16383 | REL); + let data = [ + row(0), + cell(5, 0, &1.0f64.to_le_bytes()), + part(1, (0, 1)), + range_formula(427, (0, 0, 1, 1), &left), + row(1), + part(0, (0, 1)), + part(1, (0, 1)), + ] + .concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let text = |a: &str| wb.sheets[0].formula(at(a)); + assert_eq!((text("A1"), text("B1"), text("A2"), text("B2")), (None, Some("A1"), Some("XFD2"), Some("A2"))); + assert!(!wb.warnings.iter().any(|w| w.contains("kept as their saved results")), "{:?}", wb.warnings); +} + +#[test] +fn a_shared_formula_copy_may_be_longer_than_its_first_cell() { + // SUM of nine SUMs of 255 references to the cell on the left: about 6,900 characters at B9, + // over 18,000 at B999999, where each `A9` is `A999999`. Each copy has its own text. + let mut rgce = vec![]; + for _ in 0..9 { + for _ in 0..255 { + rgce.extend(ref_n(0, 16383 | REL)); + } + rgce.extend([0x22, 255, 4, 0]); + } + rgce.extend([0x22, 9, 4, 0]); + let data = [row(8), part(1, (8, 1)), range_formula(427, (8, 1, 999_998, 1), &rgce), row(999_998), part(1, (8, 1))].concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let (b9, last) = (wb.sheets[0].formula(at("B9")).unwrap(), wb.sheets[0].formula(at("B999999")).unwrap()); + assert!(b9.len() < 8192 && last.len() > 18_000, "{} {}", b9.len(), last.len()); + assert!(last.starts_with("SUM(SUM(A999999,A999999"), "{}", &last[..40]); +} + +#[test] +fn shared_formula_copies_are_charged_before_they_are_made() { + // A1:A3 share `1+1` (3 bytes); with 6 bytes allowed, the first cell and one copy fit, and the + // last copy keeps its value without being decoded. + let one_plus_one = [0x1E, 1, 0, 0x1E, 1, 0, 0x03]; + let data = [row(0), part(0, (0, 0)), range_formula(427, (0, 0, 2, 0), &one_plus_one), row(1), part(0, (0, 0)), row(2), part(0, (0, 0))].concat(); + let limits = Limits { binary_formula_text: 6, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); + let got: Vec<_> = (0..3).map(|r| wb.sheets[0].formula(CellRef::new(r, 0))).collect(); + assert_eq!(got, [Some("1+1"), Some("1+1"), None]); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +#[test] +fn a_shared_formula_stops_decoding_copies_once_one_is_kept_as_its_value() { + // A1:Z2 share `=` the cell to the right. A1 is `B1` (2 bytes), Z1's copy is `AA1` (3): it + // passes the estimate from the first cell but not the allowance, after being decoded. The + // group's later copies keep their values without being decoded, though B2's (`C2`) would fit. + let right = ref_n(0, 1 | REL); + let data = [row(0), part(0, (0, 0)), range_formula(427, (0, 0, 1, 25), &right), part(25, (0, 0)), row(1), part(1, (0, 0))].concat(); + let limits = Limits { binary_formula_text: 4, ..Limits::default() }; + let wb = read_with(&file(&worksheet(&data, &[])), &limits).unwrap(); + let text = |a: &str| wb.sheets[0].formula(at(a)); + assert_eq!((text("A1"), text("Z1"), text("B2")), (Some("B1"), None, None)); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); +} + +#[test] +fn convert_is_called_by_its_number_as_excel_writes_it() { + // Excel's tokens for `=CONVERT(1,"m","ft")` in .xlsb: PtgFunc 0x1D4, which the + // specification's Ftab table leaves out. + let rgce = [0x1E, 0x01, 0x00, 0x17, 0x01, 0x00, 0x6D, 0x00, 0x17, 0x02, 0x00, 0x66, 0x00, 0x74, 0x00, 0x41, 0xD4, 0x01]; + let wb = read(&file(&worksheet(&[row(0), formula_cell(0, &rgce, &[])].concat(), &[]))).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), Some("CONVERT(1,\"m\",\"ft\")")); +} + +#[test] +fn a_dynamic_array_kept_as_its_value_has_no_cell_metadata() { + let meta = record(49, &1u32.to_le_bytes()); + let table_ref = [0x18, 0x19, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]; + let data = [ + row(0), + // A1: a dynamic-array formula the reader can't decode (a table reference). + meta.clone(), + formula_cell(0, &table_ref, &[]), + // B1:B2: a dynamic array whose BrtArrFmla holds an unknown token. + meta.clone(), + part(1, (0, 1)), + range_formula(426, (0, 1, 1, 1), &[0xFF]), + // C1: a value with cell metadata keeps it, as the file has it. + meta.clone(), + cell(5, 2, &1.0f64.to_le_bytes()), + // D1: the first cell of a dynamic array with no BrtArrFmla after it, then a value, E1. + meta.clone(), + part(3, (0, 3)), + cell(5, 4, &1.0f64.to_le_bytes()), + // F1: the same as the last cell of its row. + meta, + part(5, (0, 5)), + row(1), + cell(5, 0, &1.0f64.to_le_bytes()), + ] + .concat(); + let wb = read(&file(&worksheet(&data, &[]))).unwrap(); + let sheet = &wb.sheets[0]; + for a in ["A1", "B1", "D1", "F1"] { + assert_eq!(sheet.formula(at(a)), None, "{a}"); + } + assert_eq!(sheet.cell_metadata.iter().collect::>(), [(&at("C1"), &1)]); + assert!(warned(&wb, "missing from the file"), "{:?}", wb.warnings); +} + +/// `PtgAttrSpace` ([MS-XLSB] 2.5.98.31): its type (0 spaces before the next token, 1 line breaks +/// before it, 2 spaces before a `(`, 4 spaces before a `)`) and count. +fn space(kind: u8, n: u8) -> Vec { + vec![0x19, 0x40, kind, n] +} + +#[test] +fn typed_spacing_numbers_and_iso_functions_read_as_in_xlsx() { + let a1 = || [&[0x24u8][..], &loc(0, REL)].concat(); + let b1 = || [&[0x24u8][..], &loc(0, 1 | REL)].concat(); + let num = |n: f64| [&[0x1Fu8][..], &n.to_le_bytes()].concat(); + let area = |c: u16| [&[0x25u8][..], &0u32.to_le_bytes(), &1u32.to_le_bytes(), &(c | REL).to_le_bytes(), &(c | REL).to_le_bytes()].concat(); + let goto = [0x19u8, 0x08, 0, 0]; + let cells: Vec> = vec![ + // Spacing goes before the next token: an operand, or an operator's symbol. + [&[0x1Eu8, 1, 0][..], &space(0, 2), &[0x1E, 2, 0], &space(0, 1), &[0x03]].concat(), + // ... or a call's `)`, and inside a call's parentheses. + [space(0, 1), a1(), space(0, 1), b1(), space(4, 1), vec![0x42, 2, 4, 0]].concat(), + // Line breaks. + [ + a1(), + vec![0x1E, 0, 0, 0x0D, 0x19, 0x02, 0, 0], + space(1, 1), + space(0, 2), + vec![0x1E, 1, 0], + goto.to_vec(), + space(1, 1), + space(0, 2), + vec![0x1E, 2, 0], + goto.to_vec(), + vec![0x42, 3, 1, 0], + ] + .concat(), + // Inside and before parentheses. + [space(0, 1), vec![0x1E, 1, 0], space(0, 1), vec![0x1E, 2, 0], space(0, 1), vec![0x03], space(4, 1), vec![0x15]].concat(), + [vec![0x1E, 1, 0, 0x1E, 2, 0], space(2, 1), vec![0x15, 0x03]].concat(), + // A call with no arguments, and one through PtgAttrSum. + [space(4, 1), vec![0x41, 19, 0]].concat(), + [area(0), area(1), space(0, 1), vec![0x0F, 0x19, 0x10, 0, 0]].concat(), + // A sign, `%`, and leading spacing (trimmed, as `.xlsx` text is read). + [space(0, 1), vec![0x1E, 1, 0, 0x13], space(0, 1), vec![0x14]].concat(), + [space(0, 3), a1()].concat(), + // A newer function: spacing before its name's token is the first argument's. + [vec![0x1E, 1, 0], space(0, 1), vec![0x23, 5, 0, 0, 0], num(1.5), space(0, 1), vec![0x42, 2, 0xFF, 0, 0x03]].concat(), + vec![0x23, 1, 0, 0, 0, 0x17, 1, 0, b'a', 0, 0x42, 2, 0xFF, 0], + // Numbers written out up to 21 characters, scientific past them. + [num(1e20), num(1e21), vec![0x03], num(1e-19), vec![0x03], num(1.5e-19), vec![0x03], num(1234567890123456.0), vec![0x03]].concat(), + ]; + let mut data = row(0); + for (i, rgce) in cells.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, rgce, &[])); + } + // Name 5: the hidden name ISO.CEILING is called through, as Excel writes it. + let mut book = book_with_links(&xti()); + let end = record(132, &[]); + book.truncate(book.len() - end.len()); + book.extend(name(0x0002_000b, "_xlfn.ISO.CEILING")); + book.extend(end); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + let got: Vec<_> = (1..=cells.len() as u32).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + let want = [ + "1 + 2", + "SUM( A1, B1 )", + "IF(A1>0,\n 1,\n 2)", + "( 1 + 2 )", + "1+ (2)", + "PI( )", + "SUM(A1:A2 B1:B2)", + "- 1 %", + "A1", + "1+ ISO.CEILING( 1.5)", + "_xlfn.CONCAT(\"a\")", + "100000000000000000000+1E+21+0.0000000000000000001+1.5E-19+1234567890123460", + ]; + assert_eq!(got, want.map(Some)); +} + +#[test] +fn references_to_macro_sheets_and_spans_over_chart_sheets_are_named() { + // Sheets Data, a chart sheet, an XLM macro sheet, Hidden; sheet links Macro1, Data:Hidden + // (over the chart sheet) and Chart1 (no cells). + let mut book = record(131, &[]); + book.extend(record(153, &[[0u8; 8].as_slice(), &wide("")].concat())); + book.extend(record(143, &[])); + for (id, rel, name) in [(1u32, "one", "Data"), (3, "c", "Chart1"), (4, "m", "Macro1"), (2, "two", "Hidden")] { + book.extend(record(156, &[&0u32.to_le_bytes()[..], &id.to_le_bytes(), &wide(rel), &wide(name)].concat())); + } + book.extend(record(144, &[])); + let mut xti = 3u32.to_le_bytes().to_vec(); + for (first, last) in [(2i32, 2i32), (0, 3), (1, 1)] { + xti.extend([0u32.to_le_bytes(), first.to_le_bytes(), last.to_le_bytes()].concat()); + } + book.extend([record(353, &[]), record(357, &[]), record(362, &xti), record(354, &[]), record(132, &[])].concat()); + let rels = RELS.replace( + "", + r#""#, + ); + let ref3d = |ixti: u16| [&[0x5Au8][..], &ixti.to_le_bytes(), &loc(0, 0)].concat(); + let data = [row(0), formula_cell(1, &ref3d(0), &[]), formula_cell(2, &ref3d(1), &[]), formula_cell(3, &ref3d(2), &[])].concat(); + let wb = read(&package(&book, &worksheet(&data, &[]), &sst(), ROOT, &rels, TYPES)).unwrap(); + let got: Vec<_> = (1..=3).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + assert_eq!(got, [Some("Macro1!$A$1"), Some("Data:Hidden!$A$1"), None]); + assert!(warned(&wb, "references to sheets with no cells"), "{:?}", wb.warnings); +} + +#[test] +fn a_formulas_array_constants_share_one_allowance() { + // Two arrays of 40,000 Boolean values, each within what one array may hold, added together: + // charged before their values are held, together they pass what a formula's arrays may hold + // (65,536 values), so the cell keeps its saved result. One of them alone decodes. + let array = |n: u32| [&n.to_le_bytes()[..], &1u32.to_le_bytes(), &[2u8, 1].repeat(n as usize)].concat(); + let ptg = [&[0x60u8][..], &[0; 14]].concat(); + let two = [&ptg[..], &ptg, &[0x03]].concat(); + let data = [row(0), formula_cell(0, &two, &[array(40_000), array(40_000)].concat()), formula_cell(1, &ptg, &array(40_000))].concat(); + let wb = read(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert_eq!(wb.sheets[0].value(CellRef::new(0, 0)), Value::Number(0.0)); + assert!(wb.sheets[0].formula(CellRef::new(0, 1)).is_some_and(|f| f.starts_with("{TRUE;TRUE"))); + assert!(warned(&wb, "array constants too large"), "{:?}", wb.warnings); +} + +#[test] +fn a_spent_formula_allowance_skips_decoding() { + // With no allowance, a formula is not decoded at all: an unknown token is never reached. + let data = [row(0), formula_cell(0, &[0xFF], &[])].concat(); + let limits = Limits { binary_formula_text: 0, ..Limits::default() }; + let wb = read_with(&package(&book_with_links(&xti()), &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES), &limits).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert!(warned(&wb, "more formula text than the limits allow"), "{:?}", wb.warnings); + assert!(!warned(&wb, "unknown formula token"), "{:?}", wb.warnings); +} + +#[test] +fn module_sheets_and_supporting_links_are_bounded() { + // 1,025 very hidden module sheets (no relationship) before the worksheets: each keeps a place + // in the sheet links, so together they are past the 1,024-sheet cap. + let plain = book(false); + let at = plain.windows(3).position(|w| w == record(143, &[]).as_slice()).unwrap() + 3; + let module = record(156, &[&2u32.to_le_bytes()[..], &9u32.to_le_bytes(), &u32::MAX.to_le_bytes(), &wide("Module")].concat()); + let modules = [&plain[..at], &module.repeat(1025), &plain[at..]].concat(); + assert!(matches!(read(&package(&modules, &worksheet(&[], &[]), &sst(), ROOT, RELS, TYPES)), Err(Error::TooLarge(_)))); + // 65,537 supporting links: past the cap the links aren't read, and formulas keep their values. + let end = record(132, &[]); + let selves = [&plain[..plain.len() - end.len()], &record(353, &[]), &record(357, &[]).repeat(65_537), &record(354, &[]), &end].concat(); + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[])].concat(); + let wb = read(&package(&selves, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert!(wb.warnings.iter().any(|w| w.contains("sheet links or names could not be read")), "{:?}", wb.warnings); +} diff --git a/crates/zip/README.md b/crates/zip/README.md index 079267b9f4..6cffa77863 100644 --- a/crates/zip/README.md +++ b/crates/zip/README.md @@ -70,3 +70,12 @@ calls it first. `preflight`, `read_entry` and `Budget`: the ZIP half of the craft-archive proposal (#126, #129). `check_entry_count`: craft-opc's `guard`. Duplicate detection: craft-penpot's rule, made exact by walking the directory. The writer: craft-opc's `ZipOut`. + +## Seekable indexing + +`MetadataReader::new(reader, metadata_bytes)` wraps a `Read + Seek` source without loading its +payload into memory. During ZIP indexing it admits reads only from the last `metadata_bytes` +bytes and charges repeated reads against twice that number. Call `Indexing::finish` on the +returned handle after the ZIP index has been parsed to permit normal streaming payload reads. +The caller must still enforce entry-count, declared-size and overlap limits: the wrapper only +bounds metadata reads and does not validate the archive. diff --git a/crates/zip/src/guard.rs b/crates/zip/src/guard.rs index dd3ebe4515..553e1532f4 100644 --- a/crates/zip/src/guard.rs +++ b/crates/zip/src/guard.rs @@ -46,7 +46,7 @@ pub fn check_entry_count(bytes: &[u8], max_entries: u64) -> Result<(), Error> { continue; } let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(at + 8), u16_at(at + 10), u32_at(at + 16)) else { continue }; - let zip64 = total == u16::MAX || cd_offset == u32::MAX; + let zip64 = total == u16::MAX || u32_at(at + 12) == Some(u32::MAX) || cd_offset == u32::MAX; if zip64 && let Some(locator) = at.checked_sub(20) && bytes.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) @@ -155,6 +155,17 @@ mod tests { assert!(check(&prefixed, 20_000).is_err()); } + #[test] + fn zip64_directory_size_sentinel_alone_cannot_bypass_the_count_limit() { + let mut bytes = zip64_entry_count_sample(21); + let eocd = bytes.len() - 22; + // zip recognizes ZIP64 when only the directory size is a sentinel. + bytes[eocd + 8..eocd + 12].copy_from_slice(&[1, 0, 1, 0]); + bytes[eocd + 16..eocd + 20].copy_from_slice(&0u32.to_le_bytes()); + assert!(zip::ZipArchive::new(std::io::Cursor::new(&bytes)).is_ok()); + assert_eq!(check(&bytes, 20), Err(Error::TooManyEntries { declared: 21, limit: 20 })); + } + #[test] fn a_plain_end_record_is_checked_as_zip_reads_it() { assert!(check(&plain(3, b""), 20_000).is_ok()); diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index 452351ee36..0a348dc1fb 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -23,13 +23,17 @@ struct ReadmeExamples; mod archive; mod guard; +mod metadata_reader; pub mod preflight; +mod seekable; mod write; pub use archive::{Archive, Limits}; pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; +pub use metadata_reader::{Indexing, MetadataReader}; +pub use seekable::{InspectError, inspect_seekable}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/metadata_reader.rs b/crates/zip/src/metadata_reader.rs new file mode 100644 index 0000000000..6bba5759d4 --- /dev/null +++ b/crates/zip/src/metadata_reader.rs @@ -0,0 +1,114 @@ +//! Bound the reads a ZIP indexer may perform before accessing entry payloads. + +use std::io::{self, Read, Seek, SeekFrom}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// A seekable reader whose indexing phase is restricted to a tail window and read budget. +/// +/// Keep the returned [`Indexing`] handle until the ZIP central directory has been parsed, then +/// call [`Indexing::finish`] to allow normal entry reads. Repeated reads during indexing count +/// towards the allowance, including reads after seeks. This bounds metadata scanning without +/// buffering the whole file or restricting the size of its payload entries. +pub struct MetadataReader { + inner: R, + indexing: Arc, + metadata_start: u64, + remaining: u64, + position: u64, +} + +/// Controls the indexing restriction for the associated reader. +#[derive(Clone)] +pub struct Indexing(Arc); + +impl Indexing { + /// Permit reads outside the metadata window once indexing is finished. + pub fn finish(&self) { + self.0.store(false, Ordering::Release); + } +} + +impl MetadataReader { + /// Limit indexing to the last `metadata_bytes` bytes and at most twice that many bytes read. + pub fn new(mut inner: R, metadata_bytes: u64) -> io::Result<(Self, Indexing)> { + let end = inner.seek(SeekFrom::End(0))?; + let indexing = Arc::new(AtomicBool::new(true)); + let handle = Indexing(indexing.clone()); + Ok(( + Self { inner, indexing, metadata_start: end.saturating_sub(metadata_bytes), remaining: metadata_bytes.saturating_mul(2), position: end }, + handle, + )) + } +} + +impl Read for MetadataReader { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if bytes.is_empty() { + return Ok(0); + } + let indexing = self.indexing.load(Ordering::Acquire); + if indexing && (self.position < self.metadata_start || self.remaining == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "ZIP metadata exceeds the indexing limit")); + } + let length = if indexing { bytes.len().min(usize::try_from(self.remaining).unwrap_or(usize::MAX)) } else { bytes.len() }; + let read = self.inner.read(bytes.get_mut(..length).unwrap_or_default())?; + self.position = self.position.saturating_add(read as u64); + if indexing { + self.remaining -= read as u64; + } + Ok(read) + } +} + +impl Seek for MetadataReader { + fn seek(&mut self, from: SeekFrom) -> io::Result { + self.position = self.inner.seek(from)?; + Ok(self.position) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn indexing_cannot_read_payloads_outside_the_metadata_window() { + let (mut reader, indexing) = MetadataReader::new(Cursor::new(vec![7; 100]), 8).unwrap(); + reader.seek(SeekFrom::Start(91)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + reader.seek(SeekFrom::Start(92)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + indexing.finish(); + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 100]).unwrap(); + } + + #[test] + fn zip_indexing_is_tail_bounded_then_payload_reads_stream() { + let mut writer = crate::Writer::new(); + writer.add("large.bin", &vec![42; 131_072], crate::Compression::Stored).unwrap(); + let bytes = writer.finish().unwrap(); + let (reader, indexing) = MetadataReader::new(Cursor::new(bytes), 16_384).unwrap(); + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let mut archive = zip::ZipArchive::with_config(config, reader).unwrap(); + assert!(archive.by_name("large.bin").is_err(), "indexing must not read the payload header"); + indexing.finish(); + let mut entry = archive.by_name("large.bin").unwrap(); + let mut payload = Vec::new(); + entry.read_to_end(&mut payload).unwrap(); + assert_eq!(payload, vec![42; 131_072]); + } + + #[test] + fn repeated_metadata_scans_share_one_read_allowance() { + let (mut reader, _indexing) = MetadataReader::new(Cursor::new(vec![7; 8]), 8).unwrap(); + for _ in 0..2 { + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + } + reader.seek(SeekFrom::Start(0)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + } +} diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs new file mode 100644 index 0000000000..2750a0123d --- /dev/null +++ b/crates/zip/src/seekable.rs @@ -0,0 +1,75 @@ +//! Checks for an already indexed, seekable ZIP archive. + +use std::io::{Read, Seek}; + +/// Why an indexed seekable archive exceeded its caller's limits. +#[derive(Debug, thiserror::Error)] +pub enum InspectError { + #[error("the archive has {actual} entries, more than {limit}")] + TooManyEntries { actual: usize, limit: usize }, + #[error("declared entry sizes exceed {limit} bytes")] + DeclaredBytesExceeded { limit: u64 }, + #[error("ZIP entries overlap")] + OverlappingEntries, + #[error("ZIP index: {0}")] + Zip(#[from] zip::result::ZipError), +} + +/// Check every declared payload, including entries the caller may ignore, and reject overlapping +/// entry headers and compressed ranges. This is a post-index check; it does not replace a pre-index count guard or +/// bound bytes actually decompressed by a caller. +pub fn inspect_seekable(archive: &mut zip::ZipArchive, max_entries: usize, max_declared_bytes: u64) -> Result<(), InspectError> { + if archive.len() > max_entries { + return Err(InspectError::TooManyEntries { actual: archive.len(), limit: max_entries }); + } + let mut remaining = max_declared_bytes; + for index in 0..archive.len() { + remaining = + remaining.checked_sub(archive.by_index_raw(index)?.size()).ok_or(InspectError::DeclaredBytesExceeded { limit: max_declared_bytes })?; + } + if archive.has_overlapping_entries()? { + return Err(InspectError::OverlappingEntries); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use std::io::{Cursor, Write}; + + #[test] + fn counts_all_declared_entries_and_detects_aliases() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + writer.start_file("first", options).unwrap(); + writer.write_all(b"payload").unwrap(); + writer.shallow_copy_file("first", "alias").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 1, 14), Err(InspectError::TooManyEntries { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 13), Err(InspectError::DeclaredBytesExceeded { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 14), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn empty_aliases_still_overlap_at_the_header() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("empty", zip::write::SimpleFileOptions::default()).unwrap(); + writer.shallow_copy_file("empty", "alias").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 2, 0), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn permits_exact_limits_and_empty_archive() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a", zip::write::SimpleFileOptions::default()).unwrap(); + writer.write_all(b"123").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(inspect_seekable(&mut archive, 1, 3).is_ok()); + let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner(); + assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok()); + } +} diff --git a/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt new file mode 100644 index 0000000000..4fcb9b583b --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/IJG-NOTICE.txt @@ -0,0 +1,72 @@ +/* + * Ported from mozjpeg to rust + * + * This file was part of the Independent JPEG Group's software: + * Copyright (C) 1991-1996, Thomas G. Lane. + * libjpeg-turbo Modifications: + * Copyright (C) 2015, 2020, D. R. Commander. + * + * Conditions of distribution and use: + * In plain English: + * + * 1. We don't promise that this software works. (But if you find any bugs, + * please let us know!) + * 2. You can use this software for whatever you want. You don't have to pay us. + * 3. You may not pretend that you wrote this software. If you use it in a + * program, you must acknowledge somewhere in your documentation that + * you've used the IJG code. + * + * In legalese: + * + * The authors make NO WARRANTY or representation, either express or implied, + * with respect to this software, its quality, accuracy, merchantability, or + * fitness for a particular purpose. This software is provided "AS IS", and you, + * its user, assume the entire risk as to its quality and accuracy. + * + * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. + * All Rights Reserved except as specified below. + * + * Permission is hereby granted to use, copy, modify, and distribute this + * software (or portions thereof) for any purpose, without fee, subject to these + * conditions: + * (1) If any part of the source code for this software is distributed, then this + * README file must be included, with this copyright and no-warranty notice + * unaltered; and any additions, deletions, or changes to the original files + * must be clearly indicated in accompanying documentation. + * (2) If only executable code is distributed, then the accompanying + * documentation must state that "this software is based in part on the work of + * the Independent JPEG Group". + * (3) Permission for use of this software is granted only if the user accepts + * full responsibility for any undesirable consequences; the authors accept + * NO LIABILITY for damages of any kind. + * + * These conditions apply to any software derived from or based on the IJG code, + * not just to the unmodified library. If you use our work, you ought to + * acknowledge us. + * + * Permission is NOT granted for the use of any IJG author's name or company name + * in advertising or publicity relating to this software or products derived from + * it. This software may be referred to only as "the Independent JPEG Group's + * software". + * + * We specifically permit and encourage the use of this software as the basis of + * commercial products, provided that all warranty or liability claims are + * assumed by the product vendor. + * + * This file contains a slower but more accurate integer implementation of the + * forward DCT (Discrete Cosine Transform). + * + * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT + * on each column. Direct algorithms are also available, but they are + * much more complex and seem not to be any faster when reduced to code. + * + * This implementation is based on an algorithm described in + * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT + * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, + * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. + * The primary algorithm described there uses 11 multiplies and 29 adds. + * We use their alternate method with 12 multiplies and 32 adds. + * The advantage of this method is that no data path contains more than one + * multiplication; this allows a very simple and accurate implementation in + * scaled fixed-point arithmetic, with a minimal number of shifts. + */ diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE new file mode 100644 index 0000000000..dae6969815 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/LICENSE-MIT b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT new file mode 100644 index 0000000000..6a4eb87467 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Volker Ströbel + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt new file mode 100644 index 0000000000..58e09bf431 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SIMD-NOTICE.txt @@ -0,0 +1,8 @@ +/* + * Ported from mozjpeg / jfdctint-avx2.asm to rust + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + */ diff --git a/licenses/jpeg-encoder-0.6.1/SOURCE.json b/licenses/jpeg-encoder-0.6.1/SOURCE.json new file mode 100644 index 0000000000..8a7fb7ab24 --- /dev/null +++ b/licenses/jpeg-encoder-0.6.1/SOURCE.json @@ -0,0 +1,29 @@ +{ + "package": "jpeg-encoder", + "version": "0.6.1", + "source": "https://crates.io/crates/jpeg-encoder/0.6.1", + "registry_checksum": "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f", + "license": "(MIT OR Apache-2.0) AND IJG", + "files": { + "LICENSE-MIT": { + "source": "LICENSE-MIT", + "source_sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503", + "sha256": "4d022727ea392ebba2fe5e9a5f78c610a0eae506b491f3db29c78b6d430d6503" + }, + "LICENSE-APACHE": { + "source": "LICENSE-APACHE", + "source_sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0", + "sha256": "85a884980abd6032fc6b5439ba918ab16db9ac9051b5cf18db9c27c587df07c0" + }, + "IJG-NOTICE.txt": { + "source": "src/fdct.rs", + "source_sha256": "0b59244bbd05b2593ded252ecf0d010a8a4c6ec1d4713b3caeb6fb724586e4d6", + "sha256": "432424ca69caaa82565c0491c11cdab311a2e7d39180970b8ba22017996bf678" + }, + "SIMD-NOTICE.txt": { + "source": "src/avx2/fdct.rs", + "source_sha256": "bc362322f568f92c3699f4ca2922b261c12b7dd997120b01fd3cab58d9d2f9ab", + "sha256": "ee36eeaa9df1f7f09c7046f428ce4a848fcf518394e63d3e2125ec261949e8ba" + } + } +} diff --git a/scripts/test-workspace-concurrency.py b/scripts/test-workspace-concurrency.py new file mode 100644 index 0000000000..96bfae3047 --- /dev/null +++ b/scripts/test-workspace-concurrency.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Check the Workspace workflow's pull-request-only cancellation policy. + +The policy is the top-level `concurrency` block of .github/workflows/workspace.yml. This script +reads those fields, requires the documented expression shapes, and checks which group each event +would be given. The rest of the workflow is left to diff review, not frozen here. + +Use --workflow PATH to read a baseline or a deliberately wrong variant without touching this +checkout. +""" + +import argparse +import re +import sys +import unittest +from pathlib import Path + +try: # cross-check only; the reader below is what a plain `python3` run needs + import yaml +except ImportError: + yaml = None + +DEFAULT_WORKFLOW = Path(__file__).resolve().parent.parent / ".github" / "workflows" / "workspace.yml" +PULL_REQUEST, PUSH, DISPATCH = "pull_request", "push", "workflow_dispatch" + +# The two shapes this policy may use. GitHub reads `a && b || c` as "b, or c when a is false"; these +# patterns are the whole of that expression language this script understands, so a reworded policy +# has to be reworded here too, on purpose. github.ref, never github.head_ref or github.sha. +GROUP_SHAPE = re.compile( + r"(?P[A-Za-z0-9._-]+)-\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*" + r"&&\s*github\.ref\s*\|\|\s*github\.run_id\s*\}\}" +) +CANCEL_SHAPE = re.compile(r"\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*\}\}") + + +def read_concurrency(text): + """The top-level `concurrency` mapping. A deliberately limited reader: two-space fields.""" + lines = text.splitlines() + starts = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(starts) != 1: + raise AssertionError(f"expected one top-level concurrency block, found {len(starts)}") + header = lines[starts[0]].partition("#")[0].strip() + if header != "concurrency:": + # `concurrency: |` and `concurrency: some-string` are scalars, not a mapping. Reading the + # lines under one as fields would let a workflow that is not this policy pass every check. + raise AssertionError(f"concurrency must be a mapping, not a scalar: {lines[starts[0]]!r}") + fields = {} + for line in lines[starts[0] + 1:]: + stripped = line.strip() + if stripped and not line.startswith(" "): + break # the next top-level key + if not stripped or stripped.startswith("#"): + continue + if not line.startswith(" ") or line.startswith(" "): + raise AssertionError(f"unexpected indentation under concurrency: {line!r}") + key, separator, value = stripped.partition(":") + if not separator: + raise AssertionError(f"not a field of concurrency: {line!r}") + fields[key.strip()] = value.strip() + return fields + + +def pull_request(number, run_id): + # github.ref for a pull request is refs/pull//merge: the PR number, never the branch name. + return (PULL_REQUEST, f"refs/pull/{number}/merge", run_id) + + +def other_run(event_name, ref, run_id): + return (event_name, ref, run_id) + + +MAIN, TAG = ("refs/heads/main", "refs/tags/v1.2.3") +SAME_GROUP = [ + ("a newer commit on the same pull request", pull_request(1316, 43599251877), pull_request(1316, 43600899878)), + ("a rerun of one main run", other_run(PUSH, MAIN, 7001), other_run(PUSH, MAIN, 7001)), +] +DIFFERENT_GROUPS = [ + ("two pull requests", pull_request(1316, 1), pull_request(1317, 1)), + ("the same branch name in two forks", pull_request(1316, 2), pull_request(1400, 2)), + ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), + ("two release tag runs", other_run(PUSH, TAG, 5), other_run(PUSH, TAG, 6)), + ("two manual runs", other_run(DISPATCH, MAIN, 7), other_run(DISPATCH, MAIN, 8)), + ("a main push and a pull request", other_run(PUSH, MAIN, 9), pull_request(1316, 9)), + ("a release tag and a pull request", other_run(PUSH, TAG, 10), pull_request(1316, 10)), +] +CANCELLATION = [ + ("a push supersedes the previous run of its pull request", pull_request(1316, 11), True), + ("a push to main is never cancelled", other_run(PUSH, MAIN, 12), False), + ("a release tag run is never cancelled", other_run(PUSH, TAG, 13), False), + ("a manual run is never cancelled", other_run(DISPATCH, MAIN, 14), False), +] + + +class ConcurrencyTests(unittest.TestCase): + workflow = DEFAULT_WORKFLOW + + @classmethod + def setUpClass(cls): + cls.text = cls.workflow.read_text() + cls.fields = read_concurrency(cls.text) + cls.group_shape = GROUP_SHAPE.fullmatch(cls.fields.get("group", "")) + cls.cancel_shape = CANCEL_SHAPE.fullmatch(cls.fields.get("cancel-in-progress", "")) + if not cls.group_shape or not cls.cancel_shape: + raise AssertionError(f"the concurrency fields are not the documented shapes: {cls.fields}") + + def cancels(self, event_name): + return event_name == self.cancel_shape["event"] + + def group(self, event_name, ref, run_id): + return self.group_shape["prefix"] + "-" + (ref if event_name == self.group_shape["event"] else str(run_id)) + + def test_policy_is_the_two_documented_fields(self): + self.assertEqual(sorted(self.fields), ["cancel-in-progress", "group"]) + self.assertEqual(self.group_shape["prefix"], "workspace") + self.assertEqual(self.group_shape["event"], PULL_REQUEST) + self.assertEqual(self.cancel_shape["event"], PULL_REQUEST) + + def test_a_scalar_concurrency_value_is_not_read_as_a_mapping(self): + cases = { + "a block scalar": "concurrency: |\n group: workspace-x\n cancel-in-progress: true\n", + "a plain scalar": "concurrency: workspace-x\njobs: {}\n", + } + for description, text in cases.items(): + with self.subTest(description): + with self.assertRaises(AssertionError): + read_concurrency(text) + + def test_one_group_per_pull_request_and_run(self): + for description, first, second in SAME_GROUP: + with self.subTest(description): + self.assertEqual(self.group(*first), self.group(*second), description) + for description, first, second in DIFFERENT_GROUPS: + with self.subTest(description): + self.assertNotEqual(self.group(*first), self.group(*second), description) + + def test_only_a_pull_request_cancels(self): + for description, context, expected in CANCELLATION: + with self.subTest(description): + self.assertEqual(self.cancels(context[0]), expected, description) + + def test_pyyaml_reads_the_same_fields(self): + if yaml is None: + self.skipTest("PyYAML is not installed; the limited reader above ran alone") + document = yaml.load(self.text, Loader=yaml.BaseLoader) # BaseLoader keeps `on:` a string + self.assertEqual(document["concurrency"], self.fields) + + def test_no_per_job_concurrency_is_added(self): + indented = [line for line in self.text.splitlines() + if line.strip().startswith("concurrency:") and not line.startswith("concurrency:")] + self.assertEqual(indented, [], "the policy belongs to the workflow, not to one job") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--workflow", type=Path, default=DEFAULT_WORKFLOW, help="workflow to read (default: %(default)s)") + arguments, remaining = parser.parse_known_args() + ConcurrencyTests.workflow = arguments.workflow + unittest.main(argv=[sys.argv[0], *remaining]) + + +if __name__ == "__main__": + main() diff --git a/sonar-project.properties b/sonar-project.properties index f30f3ae5fe..c2be7b1929 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -7,7 +7,11 @@ sonar.organization=storytold # *_tests.rs), which includes the browser fault-injection fixtures in crates/platform/tests. sonar.sources=. sonar.tests=. -sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs +# scripts/test-workspace-concurrency.py is a unit-test module for the Workspace workflow's +# cancellation policy: its unittest cases read a workflow and assert on it, so it is test +# code, analysed as a test and still linted, indexed and reported, not counted as production +# code that needs coverage. Its name is listed exactly, so no other script is classified. +sonar.test.inclusions=**/tests/**,**/tests.rs,**/*_tests.rs,scripts/test-workspace-concurrency.py # Codec constant tables are transcribed from the format specifications; their repeated rows are # data, not copy-pasted logic.