mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 09:46:29 +01:00
Merge main into feat/craft-testkit-guards
This commit is contained in:
commit
4729c5cd5d
237 files changed
+29826
-4943
No files matched your search
@@ -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':
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
Generated
+334
-16
@@ -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]]
|
||||
|
||||
@@ -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-<name> = { path = "crates/<name>" }`
|
||||
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" }
|
||||
|
||||
@@ -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 <volkerstroebel@mysurdity.de>
|
||||
|
||||
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 <ossman@cendio.se> 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.
|
||||
*/
|
||||
@@ -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 }
|
||||
|
||||
@@ -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.
|
||||
+34
-10
@@ -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.
|
||||
|
||||
@@ -115,6 +115,50 @@ fn parse_bext(c: &[u8]) -> Option<BwfInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<u64> {
|
||||
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<Option<u32>> {
|
||||
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<Option<(PcmKind, SampleFormat)>> {
|
||||
}
|
||||
|
||||
/// 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<WavParse> {
|
||||
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<WavParse> {
|
||||
let mut ds64_data: Option<u64> = None;
|
||||
let mut fmt: Option<Fmt> = None;
|
||||
let mut bwf: Option<BwfInfo> = 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<WavParse> {
|
||||
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<WavParse> {
|
||||
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()));
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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<EncodeFormat> {
|
||||
@@ -122,6 +148,8 @@ pub fn encode_format_for(name: &str) -> Option<EncodeFormat> {
|
||||
"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<u32> {
|
||||
/// 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<W: Write + Seek> {
|
||||
writer: Writer<W>,
|
||||
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<W: Write + Seek> std::fmt::Debug for FileEncoder<W> {
|
||||
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<W: Write + Seek> std::fmt::Debug for FileEncoder<W> {
|
||||
|
||||
// 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<W: Write + Seek> {
|
||||
#[cfg(feature = "pcm-encode")]
|
||||
Wav(wav::Writer<W>),
|
||||
@@ -188,6 +252,15 @@ enum Writer<W: Write + Seek> {
|
||||
Coded(Box<coded::Writer<W>>),
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
feature = "pcm-encode",
|
||||
feature = "flac-encode",
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode"
|
||||
))]
|
||||
impl<W: Write + Seek> FileEncoder<W> {
|
||||
/// 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<Option<u32>> {
|
||||
#[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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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<Vec<f32>> = [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::<f32>() / 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -10,3 +10,4 @@ mod raw_pcm;
|
||||
mod roundtrip;
|
||||
mod stream;
|
||||
mod wav_empty_data;
|
||||
mod wav_ixml;
|
||||
@@ -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<u8> {
|
||||
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<u8>]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
let high = high.map(|v| format!("<BWF_TIME_REFERENCE_HIGH>{v}</BWF_TIME_REFERENCE_HIGH>")).unwrap_or_default();
|
||||
chunk(b"iXML", format!("<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>{low}</BWF_TIME_REFERENCE_LOW>{high}</BEXT></BWFXML>").as_bytes())
|
||||
}
|
||||
|
||||
fn check(file: Vec<u8>, expected: Option<u64>) {
|
||||
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", "<x>5</x>"] {
|
||||
check(wav(&[xml(low, Some("0"))]), None);
|
||||
}
|
||||
for high in ["4294967296", "-1", "", "oops"] {
|
||||
check(wav(&[xml("5", Some(high))]), None);
|
||||
}
|
||||
for text in [
|
||||
"<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW>",
|
||||
"<BWFXML><!-- <BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW> --></BWFXML>",
|
||||
"<BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW><BWF_TIME_REFERENCE_LOW>6</BWF_TIME_REFERENCE_LOW></BEXT></BWFXML>",
|
||||
"<!DOCTYPE BWFXML><BWFXML><BEXT><BWF_TIME_REFERENCE_LOW>5</BWF_TIME_REFERENCE_LOW></BEXT></BWFXML>",
|
||||
] {
|
||||
check(wav(&[chunk(b"iXML", text.as_bytes())]), None);
|
||||
}
|
||||
check(wav(&[chunk(b"iXML", &vec![b' '; (1 << 20) + 1])]), None);
|
||||
let deep = format!("<BWFXML>{}{}</BWFXML>", "<a>".repeat(40), "</a>".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));
|
||||
}
|
||||
@@ -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<u16> = 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());
|
||||
}
|
||||
@@ -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
|
||||
@@ -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<Vec<u8>> {
|
||||
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<usize> {
|
||||
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>, 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<Vec<Tlv<'_>>> {
|
||||
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<Vec<u8>> {
|
||||
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<usize, Size>;
|
||||
|
||||
/// 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<usize> {
|
||||
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<usize> {
|
||||
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<u8>) -> Option<usize> {
|
||||
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<u8>) -> Option<usize> {
|
||||
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<u8>, 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<u8> {
|
||||
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<u8> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<Item = [f32; 3]>) -> 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<Item = [f32; 3]>) -> 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<LutFile> {
|
||||
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::<Vec<_>>();
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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<W: Write> {
|
||||
out: W,
|
||||
deflate: Compress,
|
||||
/// What `deflate` writes: stored blocks (packed data), else the default level.
|
||||
stored: bool,
|
||||
crc: Crc,
|
||||
buf: Vec<u8>,
|
||||
/// Bytes written (unpacked).
|
||||
total: u64,
|
||||
}
|
||||
|
||||
impl<W: Write> Gz<W> {
|
||||
/// Write a gzip header and construct a writer.
|
||||
pub fn new(mut out: W) -> io::Result<Self> {
|
||||
// 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<W: Write> Write for Gz<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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<u8> = (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<usize> {
|
||||
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");
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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 <volkerstroebel@mysurdity.de>
|
||||
|
||||
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 <ossman@cendio.se> 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.
|
||||
*/
|
||||
@@ -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.
|
||||
@@ -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<u32, CodecError> {
|
||||
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<Vec<u8>, 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<u8>, 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<u8>)> {
|
||||
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<u8> = 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<_>>(),
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>, 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<ravif::RGBA8> = (0..1024).map(|i| ravif::RGBA8::new(100, 120, 140, ((i * 37) % 256) as u8)).collect();
|
||||
let samples: Vec<u8> = 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");
|
||||
}
|
||||
}
|
||||
@@ -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<Image, CodecError> {
|
||||
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<Image, CodecError> {
|
||||
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<Image, CodecError> {
|
||||
};
|
||||
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)));
|
||||
|
||||
@@ -141,12 +141,12 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
/// 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, CodecError> {
|
||||
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<Self, CodecError> {
|
||||
fn open(bytes: B, limits: &Limits, reserve: bool, bounded_stream: bool) -> Result<Self, CodecError> {
|
||||
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<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
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<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
/// 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, CodecError> {
|
||||
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<Self, CodecError> {
|
||||
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<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
/// 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<Option<Image>, CodecError> {
|
||||
self.check_full_output()?;
|
||||
if self.done {
|
||||
return Err(err("the image was already decoded"));
|
||||
}
|
||||
@@ -338,7 +370,9 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
/// `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<E: From<CodecError>>(
|
||||
&mut self,
|
||||
group: u32,
|
||||
@@ -348,12 +382,29 @@ impl<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
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<B: AsRef<[u8]>> PngDecodeRows<B> {
|
||||
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;
|
||||
|
||||
@@ -96,7 +96,7 @@ fn channel(hex: &str) -> Option<u8> {
|
||||
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]);
|
||||
|
||||
@@ -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<f32> {
|
||||
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<Vec<f32>, 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<f32>) {
|
||||
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<f32> = (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::<Vec<_>>();
|
||||
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();
|
||||
|
||||
@@ -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<JpegInfo> {
|
||||
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<u8>)> {
|
||||
|
||||
@@ -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")));
|
||||
|
||||
@@ -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<Vec<u8>, 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<Vec<u8>, 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.
|
||||
|
||||
@@ -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::<CodecError>(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::<CodecError>(4, &mut || false, &mut |_, _| panic!("group is incomplete")).unwrap().is_none());
|
||||
}
|
||||
assert!(decoder.step_stream::<CodecError>(1, &mut || true, &mut |_, _| panic!("changed group reached sink")).is_err());
|
||||
let mut output = Vec::new();
|
||||
decoder
|
||||
.step_stream::<CodecError>(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::<CodecError>(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);
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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.
|
||||
@@ -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<R: BufRead>(reader: &mut R, max_bytes: usize) -> Result<Option<Vec<u8>>, 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<Value, ParseError> {
|
||||
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<Request<'_>> {
|
||||
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<Value>,
|
||||
}
|
||||
|
||||
impl RpcError {
|
||||
pub fn new(code: i64, message: impl Into<String>) -> 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<F, N>(value: &Value, limits: Limits, on_request: &mut F, on_notification: &mut N) -> Option<Value>
|
||||
where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
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<F, N>(value: &Value, limits: Limits, mut on_request: F, mut on_notification: N) -> Result<Option<Value>, ParseError>
|
||||
where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
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)))
|
||||
}
|
||||
@@ -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<usize> {
|
||||
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);
|
||||
}
|
||||
@@ -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#"<materialx>
|
||||
<open_pbr_surface name="S"><input name="base_color" value="0.3,0.4,0.5"/></open_pbr_surface>
|
||||
<tiledimage name="H"><input name="file" value="height.png"/><input name="uvtiling" value="4,2"/></tiledimage>
|
||||
<displacement name="D"><input name="displacement" nodename="H"/></displacement>
|
||||
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/><input name="displacementshader" nodename="D"/></surfacematerial>
|
||||
</materialx>"#;
|
||||
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#"<materialx fileprefix="tex/">
|
||||
|
||||
@@ -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 }
|
||||
@@ -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.
|
||||
@@ -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<MapEntry>,
|
||||
#[serde(default)]
|
||||
pub parameters: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub presets: Vec<Value>,
|
||||
pub source: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MapEntry {
|
||||
pub usage: String,
|
||||
pub file: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// 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<Self, Error> {
|
||||
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<Vec<u8>, 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<Vec<u8>, 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<u8>)], source: &[u8]) -> Result<Vec<u8>, 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());
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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).
|
||||
@@ -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<String>, version: impl Into<String>, 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<Self, RpcError> {
|
||||
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<Result<Value, RpcError>> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
pub model: Option<String>,
|
||||
pub lens: Option<String>,
|
||||
/// Seconds.
|
||||
pub exposure_time: Option<f64>,
|
||||
pub f_number: Option<f64>,
|
||||
pub iso: Option<f64>,
|
||||
/// Millimetres.
|
||||
pub focal_length: Option<f64>,
|
||||
/// 35 mm-equivalent focal length in millimetres.
|
||||
pub focal_length_35mm: Option<f64>,
|
||||
/// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`).
|
||||
pub date_taken: Option<String>,
|
||||
}
|
||||
|
||||
impl CameraInfo {
|
||||
/// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene).
|
||||
pub fn exposure_factor(&self) -> Option<f64> {
|
||||
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<usize>,
|
||||
}
|
||||
|
||||
impl Tiff<'_> {
|
||||
fn u16(&self, o: usize) -> Option<u16> {
|
||||
self.order.read_u16(self.b, o)
|
||||
}
|
||||
fn u32(&self, o: usize) -> Option<u32> {
|
||||
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<usize> {
|
||||
// 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<f64> {
|
||||
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<String> {
|
||||
#[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<usize> = 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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
pub model: Option<String>,
|
||||
pub lens: Option<String>,
|
||||
/// Seconds.
|
||||
pub exposure_time: Option<f64>,
|
||||
pub f_number: Option<f64>,
|
||||
pub iso: Option<f64>,
|
||||
/// Millimetres.
|
||||
pub focal_length: Option<f64>,
|
||||
/// 35 mm-equivalent focal length in millimetres.
|
||||
pub focal_length_35mm: Option<f64>,
|
||||
/// DateTimeOriginal as stored (`YYYY:MM:DD HH:MM:SS`).
|
||||
pub date_taken: Option<String>,
|
||||
}
|
||||
|
||||
impl CameraInfo {
|
||||
/// Linear exposure factor `t · ISO / N²` (relative brightness of the image for one scene).
|
||||
pub fn exposure_factor(&self) -> Option<f64> {
|
||||
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<usize>,
|
||||
}
|
||||
|
||||
impl Tiff<'_> {
|
||||
fn u16(&self, o: usize) -> Option<u16> {
|
||||
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<u32> {
|
||||
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<usize> {
|
||||
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<f64> {
|
||||
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<String> {
|
||||
#[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<usize> = 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<u8> {
|
||||
// IFD0: Make, Model, ExifIFD pointer; Exif IFD: the rest. Data area after the IFDs.
|
||||
let mut ifd0: Vec<(u16, u16, u32, Vec<u8>)> = Vec::new();
|
||||
let mut exif: Vec<(u16, u16, u32, Vec<u8>)> = 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<u8>, entries: &[(u16, u16, u32, Vec<u8>)], extra: Option<u32>| {
|
||||
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
|
||||
}
|
||||
+162
-11
@@ -351,28 +351,70 @@ fn trak(bytes: &[u8], t: &BoxRef, budget: &mut usize) -> Option<Cr3Track> {
|
||||
}
|
||||
}
|
||||
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<u8>, offset: u64, size: u32) -> Vec<u8> {
|
||||
let stsc = [1u32, 1, 1, 1].into_iter().flat_map(u32::to_be_bytes).collect::<Vec<_>>();
|
||||
trak_with_mapping(entry, offset, size, &stsc)
|
||||
}
|
||||
fn trak_with_mapping(entry: Vec<u8>, offset: u64, size: u32, mapping: &[u8]) -> Vec<u8> {
|
||||
trak_with_table(entry, offset, size, b"stsc", mapping)
|
||||
}
|
||||
fn trak_with_table(entry: Vec<u8>, offset: u64, size: u32, table: &[u8; 4], payload: &[u8]) -> Vec<u8> {
|
||||
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::<Vec<_>>();
|
||||
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<u8> {
|
||||
@@ -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<u8>| {
|
||||
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::<Vec<_>>(),
|
||||
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]
|
||||
|
||||
@@ -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;
|
||||
|
||||
+15
-1
@@ -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.
|
||||
@@ -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};
|
||||
|
||||
@@ -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<SyncMessage> {
|
||||
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))
|
||||
}
|
||||
@@ -3,3 +3,4 @@
|
||||
mod lenient;
|
||||
mod sequence;
|
||||
mod smf;
|
||||
mod sync;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>, 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<Vec<u8>, DecodeError> {
|
||||
self.decode_inner(text.as_ref(), true)
|
||||
}
|
||||
|
||||
fn decode_inner(self, text: &[u8], optional_padding: bool) -> Result<Vec<u8>, 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);
|
||||
|
||||
@@ -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::<u8>(), 0..400),
|
||||
junk in proptest::collection::vec(any::<u8>(), 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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<DirectoryStats> {
|
||||
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<Option<FileSignature>> {
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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 = "<commit>" }
|
||||
@@ -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.
|
||||
@@ -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::{
|
||||
|
||||
@@ -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<u16>,
|
||||
}
|
||||
|
||||
/// `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<u8> {
|
||||
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<Tip, String> {
|
||||
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<Tip, String> {
|
||||
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<u16> = 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 })
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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());
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,391 @@
|
||||
use crate::{FormatError, Limits, bytes::Reader};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
Dict(Vec<(String, Value)>),
|
||||
Array(Vec<Value>),
|
||||
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<u8>),
|
||||
/// 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<u64> {
|
||||
match self {
|
||||
Value::Uid(u) => Some(*u),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_int(&self) -> Option<i128> {
|
||||
match self {
|
||||
Value::Integer(i) => Some(*i),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
struct Bin<'a> {
|
||||
r: Reader<'a>,
|
||||
offsets: Vec<usize>,
|
||||
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<Value, FormatError> {
|
||||
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<Value, FormatError> {
|
||||
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<u64> {
|
||||
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<usize, FormatError> {
|
||||
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<usize>) -> Result<Value, FormatError> {
|
||||
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<T>(n: usize) -> Result<Vec<T>, 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<String, FormatError> {
|
||||
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<Option<String>, 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<Option<String>, 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<u8> {
|
||||
self.data.get(off).copied()
|
||||
}
|
||||
|
||||
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
|
||||
self.slice(off, N)?.try_into().ok()
|
||||
}
|
||||
|
||||
pub fn u32_be(&self, off: usize) -> Option<u32> {
|
||||
self.arr(off).map(u32::from_be_bytes)
|
||||
}
|
||||
|
||||
pub fn u64_be(&self, off: usize) -> Option<u64> {
|
||||
self.arr(off).map(u64::from_be_bytes)
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use craft_plist::{Limits, Value, parse_binary, parse_binary_with_limits};
|
||||
fn plist(objects: &[&[u8]]) -> Vec<u8> {
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use craft_plist::{Value, parse_binary};
|
||||
|
||||
fn single_object(object: &[u8]) -> Vec<u8> {
|
||||
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()));
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
use craft_plist::{Value, parse_binary};
|
||||
|
||||
fn single_object(object: &[u8], offset: u8) -> Vec<u8> {
|
||||
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"));
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Self, Error> {
|
||||
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::<u16>().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::<u16>().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::<u16>().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::<std::net::IpAddr>() {
|
||||
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::<std::net::Ipv6Addr>().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<Vec<Server>, 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<Stream> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
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<Vec<Printer>, Error> {
|
||||
printers_at(&endpoints())
|
||||
}
|
||||
|
||||
pub fn printers_at(endpoints: &[Server]) -> Result<Vec<Printer>, 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<Printer> = 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<Vec<String>, 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<String, Error> {
|
||||
print_job_at(&endpoints(), pdf, job)
|
||||
}
|
||||
|
||||
pub(crate) fn print_job_at(endpoints: &[Server], pdf: &[u8], job: &Job) -> Result<String, Error> {
|
||||
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<Vec<Queue>, 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<Vec<Queue>, 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<Option<String>, 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<u32, Error> {
|
||||
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<u32, Error> {
|
||||
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<String, Error> {
|
||||
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<Vec<u8>, Error> {
|
||||
let mut failed: Option<Error> = 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<Vec<u8>, 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<usize> {
|
||||
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<usize> {
|
||||
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<Vec<u8>, 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::<u16>().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<usize> = 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::<usize>().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<Vec<u8>, Error> {
|
||||
fn line(stream: &mut impl Read) -> Result<Vec<u8>, 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<u8>,
|
||||
}
|
||||
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
print_job_request_path(&format!("/printers/{queue}"), pdf, job)
|
||||
}
|
||||
|
||||
fn print_job_request_path(path: &str, pdf: &[u8], job: &Job) -> Vec<u8> {
|
||||
print_job_request_for("localhost", path, pdf, job, "")
|
||||
}
|
||||
|
||||
fn print_job_request_for(authority: &str, path: &str, pdf: &[u8], job: &Job, user: &str) -> Vec<u8> {
|
||||
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<String>,
|
||||
queues: Vec<Queue>,
|
||||
job_id: Option<u32>,
|
||||
}
|
||||
|
||||
/// 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<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
<[u8; N]>::try_from(self.take(N)?).ok()
|
||||
}
|
||||
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.array::<2>().map(u16::from_be_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_reply(reply: &[u8]) -> Result<Reply, Error> {
|
||||
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})")),
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl FakeCups {
|
||||
fn on_unix(replies: Vec<Vec<u8>>) -> std::io::Result<Self> {
|
||||
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<Vec<u8>>) -> std::io::Result<Self> {
|
||||
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<Vec<u8>, 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<Vec<u8>>) -> Receiver<Vec<u8>> {
|
||||
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<Vec<u8>>) -> Receiver<Vec<u8>> {
|
||||
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<VecDeque<Vec<u8>>>, requests: &mpsc::Sender<Vec<u8>>) {
|
||||
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<Vec<u8>> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
vec![tag]
|
||||
}
|
||||
|
||||
fn printer_name(name: &str) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> = 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<u8>)> = 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<u8>)> = 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));
|
||||
}
|
||||
@@ -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))]
|
||||
|
||||
@@ -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 }
|
||||
@@ -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<T: fmt::Display> 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<String> 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");
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<String>>)> {
|
||||
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<Vec<String>> {
|
||||
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<Vec<String>>)> = 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::<u8>(), 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::<u8>(), 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::<Vec<_>>(), [(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<String> = (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);
|
||||
}
|
||||
@@ -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<u64>)> = 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(_))));
|
||||
}
|
||||
@@ -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<IdleEvent, ProtoError> {
|
||||
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::<u32>().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<S: Read + Write> Imap<S> {
|
||||
/// 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<Option<IdleEvent>, 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<Vec<IdleEvent>, 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")
|
||||
}
|
||||
}
|
||||
@@ -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<Option<IdleEvent>, 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::<u8>(), 0..800), greeted in any::<bool>()) {
|
||||
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(_)) });
|
||||
}
|
||||
}
|
||||
@@ -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<String> = (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::<usize>()).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::<Vec<_>>(), [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::<u32>(), 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::<String>()
|
||||
+ "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()));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<u8>),
|
||||
Literal(Vec<u8>),
|
||||
}
|
||||
|
||||
/// 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<u8>),
|
||||
List(Vec<Value>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub(crate) fn atom(&self) -> Option<&str> {
|
||||
match self {
|
||||
Value::Atom(a) => Some(a),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn number(&self) -> Option<u32> {
|
||||
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<String> {
|
||||
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<Piece>) -> Result<Vec<Value>, ProtoError> {
|
||||
// The list being filled is on top; the response itself is at the bottom.
|
||||
let mut stack: Vec<Vec<Value>> = 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: Value) {
|
||||
if let Some(top) = stack.last_mut() {
|
||||
top.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn close(stack: &mut Vec<Vec<Value>>) {
|
||||
if stack.len() > 1
|
||||
&& let Some(list) = stack.pop()
|
||||
{
|
||||
push(stack, Value::List(list));
|
||||
}
|
||||
}
|
||||
|
||||
fn scan(text: &[u8], stack: &mut Vec<Vec<Value>>) -> 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<u8>, 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>) -> 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<Status> {
|
||||
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<Value> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<S: Read + Write> Imap<S> {
|
||||
/// 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))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<Value>) -> Option<FolderStatus> {
|
||||
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<S: Read + Write> Imap<S> {
|
||||
/// STATUS of one mailbox; `None` when the server refuses or leaves a count out.
|
||||
pub fn status(&mut self, raw_name: &str) -> Result<Option<FolderStatus>, 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<Vec<Option<FolderStatus>>, 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<Vec<Option<FolderStatus>>, 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<Option<FolderStatus>> = 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)
|
||||
}
|
||||
}
|
||||
@@ -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::<u8>(), 0..600), names in 0usize..120) {
|
||||
let list: Vec<String> = (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");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<String> {
|
||||
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<u16> = 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<u16>, 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::<char>(), 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<zeroize::Zeroizing<String>>);
|
||||
|
||||
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<String, ProtoError> {
|
||||
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:<ada@example.org> SIZE=120", "MAIL FROM: … (26 bytes)"),
|
||||
("RCPT TO:<bob@example.org>", "RCPT TO: … (17 bytes)"),
|
||||
("550 5.1.1 <bob@example.org>: 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(""), "");
|
||||
}
|
||||
}
|
||||
@@ -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<S> {
|
||||
stream: S,
|
||||
/// Bytes read from the stream and not handed out yet (from `start`).
|
||||
buf: Vec<u8>,
|
||||
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<S> Wire<S> {
|
||||
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<S: Read + Write> Wire<S> {
|
||||
/// 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<Vec<u8>, 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<Option<Vec<u8>>, ProtoError> {
|
||||
self.next_line(true)
|
||||
}
|
||||
|
||||
fn next_line(&mut self, skip: bool) -> Result<Option<Vec<u8>>, 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<usize> = 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<Option<Vec<u8>>, 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<Vec<u8>, 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<S: Read>(stream: &mut S, buf: &mut [u8]) -> Result<usize, ProtoError> {
|
||||
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<Vec<u8>>,
|
||||
reads: usize,
|
||||
}
|
||||
impl Read for ByteAtATime {
|
||||
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.reads += 1;
|
||||
self.bytes.read(&mut out[..1])
|
||||
}
|
||||
}
|
||||
impl Write for ByteAtATime {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
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(_))));
|
||||
}
|
||||
}
|
||||
@@ -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<u8>,
|
||||
pos: usize,
|
||||
step: usize,
|
||||
trickle: bool,
|
||||
pub(crate) written: Vec<u8>,
|
||||
}
|
||||
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
Err(Error::from(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Broken {
|
||||
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
|
||||
Err(Error::from(self.0))
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Err(Error::from(self.0))
|
||||
}
|
||||
}
|
||||
@@ -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<S> {
|
||||
wire: Wire<S>,
|
||||
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<u64>,
|
||||
pub eight_bit_mime: bool,
|
||||
}
|
||||
|
||||
/// Neither the stream nor anything secret is shown.
|
||||
impl<S> std::fmt::Debug for Smtp<S> {
|
||||
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<String>,
|
||||
}
|
||||
|
||||
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<S: Read + Write> Smtp<S> {
|
||||
/// Read the 220 greeting.
|
||||
pub fn connect(stream: S) -> Result<Self, ProtoError> {
|
||||
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<Extensions, ProtoError> {
|
||||
// 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<S, ProtoError> {
|
||||
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<Reply, ProtoError> {
|
||||
self.secret_command(line, line)
|
||||
}
|
||||
|
||||
/// Send `line`; the log gets `shown` instead.
|
||||
fn secret_command(&mut self, line: &str, shown: &str) -> Result<Reply, ProtoError> {
|
||||
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<Reply, ProtoError> {
|
||||
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::<u16>().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<u8>, 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;
|
||||
@@ -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:<ada@example.org> SIZE=23\r\n\
|
||||
RCPT TO:<bob@example.org>\r\n\
|
||||
RCPT TO:<carol@example.org>\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:<x>", "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:<ada@example.org>\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:<ada@example.org> 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:<nobody@example.org>\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:<eve@example.org"]),
|
||||
("ada@example.org", &["bob smith@example.org"]),
|
||||
("ada@example.org", &[""]),
|
||||
("ada@example.org\r\nDATA", &["bob@example.org"]),
|
||||
("ada@example.org", &["bøb@example.org"]),
|
||||
];
|
||||
for (from, to) in cases {
|
||||
let mut s = Script::new("250 ok\r\n250 ok\r\n354 go\r\n250 ok\r\n");
|
||||
assert!(matches!(Smtp::resume(&mut s).send(from, to, b"x"), Err(ProtoError::Protocol(_))), "{from:?} {to:?}");
|
||||
assert_eq!(s.sent(), "", "{from:?} {to:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_replies_are_protocol_errors() {
|
||||
for junk in ["hello there\r\n", "25 ok\r\n", "250ok\r\n", "250-first\r\n251 second\r\n", "\r\n", "2éé ok\r\n"] {
|
||||
let mut s = Script::new(junk);
|
||||
assert!(matches!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Protocol(_))), "{junk:?}");
|
||||
}
|
||||
// A reply that never ends.
|
||||
let mut s = Script::whole("250-more\r\n".repeat(MAX_REPLY_LINES + 1));
|
||||
assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Protocol(said!("the server's reply has too many lines"))));
|
||||
// A greeting that is a success code but not 220.
|
||||
let mut s = Script::new("250 hello\r\n");
|
||||
assert!(matches!(Smtp::connect(&mut s), Err(ProtoError::Protocol(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dead_connection_is_an_io_error() {
|
||||
let mut s = Script::new("250-half a rep");
|
||||
assert_eq!(Smtp::resume(&mut s).hello("localhost"), Err(ProtoError::Io(said!("the server closed the connection"))));
|
||||
assert!(matches!(Smtp::connect(Broken(ErrorKind::TimedOut)), Err(ProtoError::Io(_))));
|
||||
assert!(matches!(Smtp::resume(Broken(ErrorKind::ConnectionReset)).send("a@example.org", &["b@example.org"], b"x"), Err(ProtoError::Io(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting() {
|
||||
let mut s = Script::new("221 bye\r\n");
|
||||
assert_eq!(Smtp::resume(&mut s).quit(), Ok(()));
|
||||
// A server that just hangs up has quit too.
|
||||
let mut s = Script::new("");
|
||||
assert_eq!(Smtp::resume(&mut s).quit(), Ok(()));
|
||||
assert_eq!(s.sent(), "QUIT\r\n");
|
||||
let mut s = Script::new("500 what\r\n");
|
||||
assert!(matches!(Smtp::resume(&mut s).quit(), Err(ProtoError::Rejected(_))));
|
||||
}
|
||||
|
||||
/// Everything a client does, against whatever the "server" says.
|
||||
fn drive(server: &[u8]) {
|
||||
let mut s = Script::new(server);
|
||||
if let Ok(mut smtp) = Smtp::connect(&mut s) {
|
||||
let _ = smtp.hello("localhost");
|
||||
let _ = smtp.auth("ada@example.org", "hunter2");
|
||||
let _ = smtp.send("ada@example.org", &["bob@example.org"], b"Subject: x\r\n\r\n.\r\n");
|
||||
let _ = smtp.quit();
|
||||
}
|
||||
let mut s = Script::new(server);
|
||||
let mut smtp = Smtp::resume(&mut s);
|
||||
smtp.ext = Extensions { auth_login: true, ..Default::default() };
|
||||
let _ = smtp.auth("ada", "hunter2");
|
||||
let _ = smtp.starttls();
|
||||
// With a token, on one line and on its own.
|
||||
for token in ["tok.en-123".to_string(), "t".repeat(700)] {
|
||||
let mut s = Script::new(server);
|
||||
let mut smtp = Smtp::resume(&mut s);
|
||||
smtp.ext = Extensions { auth_xoauth2: true, ..Default::default() };
|
||||
let _ = smtp.auth_xoauth2("ada@example.org", &token);
|
||||
let _ = smtp.send("ada@example.org", &["bob@example.org"], b"x");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn arbitrary_server_bytes_never_panic_or_hang(server in proptest::collection::vec(any::<u8>(), 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::<u8>()], 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);
|
||||
}
|
||||
}
|
||||
@@ -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<u8> {
|
||||
Ok(self.take(1)?.first().copied().unwrap_or_default())
|
||||
}
|
||||
fn u16(&mut self) -> Result<u16> {
|
||||
Ok(u16::from_be_bytes(self.take(2)?.try_into().map_err(|_| PsdError::invalid("annotation u16"))?))
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32> {
|
||||
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<Option<Text<'a>>> {
|
||||
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<Vec<Record<'_>>> {
|
||||
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<u8>, 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<u8>, 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<Vec<u8>> {
|
||||
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<Vec<u8>> {
|
||||
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;
|
||||
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user