diff --git a/.config/nextest.toml b/.config/nextest.toml index 1037b23108..0bc679e473 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,7 +1,6 @@ # cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test -# binaries. The Windows leg of the Workspace gate uses it (.github/workflows/workspace.yml); every -# other leg, and local runs, keep `cargo test`. Nextest does not run doctests, so the Windows leg -# also runs `cargo test --doc`. +# binaries. Every leg of the Workspace gate uses it (.github/workflows/workspace.yml); local runs may +# keep `cargo test`. Nextest does not run doctests, so the gate also runs `cargo test --doc`. # # cargo nextest run --workspace --profile ci # cargo test --workspace --doc @@ -22,6 +21,9 @@ video-fixtures = { max-threads = 1 } # craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests # share the one test print queue the gate installs. print = { max-threads = 1 } +# craft-video integration tests on Linux and macOS: the binaries generate and read the same fixture +# directories (see the `ci` overrides below). +video-integration = { max-threads = 1 } [[profile.default.overrides]] filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))' @@ -42,3 +44,18 @@ test-group = 'print' fail-fast = false slow-timeout = { period = "60s" } failure-output = "immediate-final" + + +# Linux and macOS (the resource audit in craft-libs#2058): every GPU consumer shares the one `gpu` +# slot, and the craft-video integration binaries share their fixture directories. Conservative on +# purpose: the in-process mutexes these tests rely on do not reach across nextest's processes. +# Windows keeps the default groups above, which its leg has passed with since it moved to nextest. +[[profile.ci.overrides]] +platform = 'cfg(unix)' +filter = 'package(craft-ui) | package(craft-keymap) | package(craft-update)' +test-group = 'gpu' + +[[profile.ci.overrides]] +platform = 'cfg(unix)' +filter = 'package(craft-video) & kind(test)' +test-group = 'video-integration' diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 02cdf71c82..e78310f7f4 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -18,7 +18,6 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/cms.yml': - 'actions/checkout@v4.4.0' - 'dtolnay/rust-toolchain@stable' @@ -27,7 +26,6 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/dialogs.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -36,10 +34,6 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - '.github/workflows/docpath.yml': - - 'actions/checkout@v7.0.1' - - 'step-security/dtolnay-rust-toolchain@v1.0.0' - - 'step-security/harden-runner@v2.22.4' '.github/workflows/ecproj-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -52,22 +46,16 @@ workflows: - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - 'step-security/harden-runner@v2.22.4' - - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/full-validation.yml': [] '.github/workflows/house-rules.yml': [] - '.github/workflows/i18n.yml': - - 'actions/checkout@v7.0.1' - - 'step-security/dtolnay-rust-toolchain@v1.0.0' - - 'step-security/harden-runner@v2.22.4' '.github/workflows/jpeg.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/keymap.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' @@ -75,11 +63,10 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/menu.yml': - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - - 'swatinem/rust-cache@v2.9.3' + '.github/workflows/nightly.yml': [] '.github/workflows/pcraft-format.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -89,23 +76,12 @@ workflows: - 'actions/setup-python@v7.1.0' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' - 'step-security/taiki-e-install-action@v2.87.32' - '.github/workflows/print.yml': - - 'actions/checkout@v7.0.1' - - 'step-security/dtolnay-rust-toolchain@v1.0.0' - - 'step-security/harden-runner@v2.22.4' '.github/workflows/proof.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/sonarcloud.yml': [] - '.github/workflows/ui.yml': - - 'actions/checkout@v7.0.1' - - 'step-security/dtolnay-rust-toolchain@v1.0.0' - - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/update.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -118,7 +94,6 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' '.github/workflows/web-api.yml': - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' @@ -128,7 +103,6 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - - 'step-security/rust-cache@v2.9.2' - 'step-security/taiki-e-install-action@v2.87.32' '.github/workflows/window.yml': - 'actions/checkout@v7.0.1' @@ -171,18 +145,8 @@ dependencies: commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' owner_id: 88700172 repo_id: 422287306 - 'step-security/rust-cache@v2.9.2': - ref: 'v2.9.2' - commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e' - owner_id: 88700172 - repo_id: 822636713 'step-security/taiki-e-install-action@v2.87.32': ref: 'v2.87.32' commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' owner_id: 88700172 repo_id: 1382753260 - 'swatinem/rust-cache@v2.9.3': - ref: 'v2.9.3' - commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' - owner_id: 580492 - repo_id: 298565987 diff --git a/.github/workflows/ai-core.yml b/.github/workflows/ai-core.yml index 5471bf1ec0..2be123b233 100644 --- a/.github/workflows/ai-core.yml +++ b/.github/workflows/ai-core.yml @@ -12,20 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: ai-core-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: ai-core-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: ai-core: + name: AI model WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -35,10 +32,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-ai-core --all-targets --locked -- -D warnings - - run: cargo test -p craft-ai-core --locked # The model promises to compile for the web. - run: cargo check -p craft-ai-core --target wasm32-unknown-unknown --locked diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index f72a64f1e1..23de7f9f4f 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -12,20 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: atomic-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: atomic-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this runs what it does not. jobs: atomic: + name: Atomic inherited Linux ACLs timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -35,15 +32,9 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy - name: Install ACL tools - if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y acl - - run: cargo fmt --check - - run: cargo clippy -p craft-atomic -p craft-settings --all-targets --locked -- -D warnings - - run: cargo test -p craft-atomic -p craft-settings --locked -- --nocapture - name: Check inherited Linux ACLs - if: runner.os == 'Linux' run: cargo test -p craft-atomic --locked -- --ignored --nocapture wasm: diff --git a/.github/workflows/audio.yml b/.github/workflows/audio.yml index d6a7ff5e25..5fd971c629 100644 --- a/.github/workflows/audio.yml +++ b/.github/workflows/audio.yml @@ -11,17 +11,22 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-audio-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-audio-${{ github.ref }} + cancel-in-progress: true jobs: lint: timeout-minutes: 15 - name: Audio lint, feature sets, docs, WASM + # fmt, clippy with all features and the minimum Rust version run in the Workspace gate. + name: Audio feature sets, docs, WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -34,13 +39,8 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-audio-lint - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-audio --check # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | @@ -49,7 +49,6 @@ jobs: cargo clippy -p craft-audio --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p craft-audio --all-targets --locked --all-features -- -D warnings # missing_docs is a warning in the crate; -D warnings makes it (and broken links) fail here. - run: cargo doc -p craft-audio --all-features --no-deps --locked env: @@ -63,25 +62,6 @@ jobs: RUSTDOCFLAGS: "-D warnings" - run: cargo check -p craft-audio --all-features --locked --target wasm32-unknown-unknown - run: cargo check -p craft-audio --no-default-features --features lossless-encode --locked --target wasm32-unknown-unknown - msrv: - timeout-minutes: 10 - name: Audio on the minimum Rust version - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - # The workspace's rust-version. - - run: rustup toolchain install 1.95.0 --profile minimal - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-audio-msrv - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo +1.95.0 check -p craft-audio -p craft-media --all-features --locked features: timeout-minutes: 10 name: Audio tests without symphonia and lossless-encode only @@ -97,10 +77,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-audio-features - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo test -p craft-audio --no-default-features --features lossless-encode --locked - run: cargo test -p craft-audio --no-default-features --features pcm-encode --locked --lib - run: cargo test -p craft-audio --no-default-features --features flac-encode --locked --lib @@ -122,10 +98,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-audio-test - save-if: ${{ github.ref == 'refs/heads/main' }} - uses: actions/cache@v6.1.0 with: path: ${{ runner.temp }}/media-fixtures/opus/vectors diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml index 74ce0815fa..9220d8e098 100644 --- a/.github/workflows/cms.yml +++ b/.github/workflows/cms.yml @@ -11,6 +11,13 @@ on: permissions: contents: read +concurrency: + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: cms-${{ github.ref }} + cancel-in-progress: true + +# clippy and the debug tests run in the Workspace gate; this runs the release build of the tests. jobs: cms: timeout-minutes: 20 @@ -18,9 +25,6 @@ jobs: steps: - uses: actions/checkout@v4.4.0 - uses: dtolnay/rust-toolchain@stable - with: - components: clippy - - run: cargo clippy -p craft-cms --all-targets --all-features --locked -- -D warnings # Release: the FOGRA39 fit and ink-limit tests take about 35 s in debug and 4 s here. Tests that need # installed system profiles print "skipped:" when none are present. - run: cargo test -p craft-cms --all-features --release --locked -- --nocapture diff --git a/.github/workflows/crw.yml b/.github/workflows/crw.yml index 54be7ba3ba..466b6c05d7 100644 --- a/.github/workflows/crw.yml +++ b/.github/workflows/crw.yml @@ -12,41 +12,13 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-crw-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-crw-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: - native: - timeout-minutes: 20 - name: CRW lint and tests (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-crw-${{ matrix.os }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-crw --check - - run: cargo clippy -p craft-crw --all-targets --locked -- -D warnings - - run: cargo test -p craft-crw --locked - wasm: timeout-minutes: 10 name: CRW WASM @@ -63,10 +35,6 @@ jobs: with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-crw-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo check -p craft-crw --locked --target wasm32-unknown-unknown samples: @@ -84,10 +52,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-crw-samples - save-if: ${{ github.ref == 'refs/heads/main' }} - name: Cache the CC0 sample files uses: actions/cache@v6.1.0 with: diff --git a/.github/workflows/dialogs.yml b/.github/workflows/dialogs.yml index c8d43d725e..23def9feb0 100644 --- a/.github/workflows/dialogs.yml +++ b/.github/workflows/dialogs.yml @@ -12,10 +12,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: dialogs-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: dialogs-${{ github.ref }} + cancel-in-progress: true jobs: dialogs: @@ -37,6 +37,5 @@ jobs: components: clippy # The macOS code is linted on Linux: it compiles for the target without the SDK. targets: aarch64-apple-darwin - - run: cargo clippy -p craft-dialogs --all-targets --locked -- -D warnings + # Native clippy and the tests run in the Workspace gate. - run: cargo clippy -p craft-dialogs --target aarch64-apple-darwin --locked -- -D warnings - - run: cargo test -p craft-dialogs --locked diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index 6caa4f0eea..6275433817 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -12,20 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: doc-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: doc-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: doc: + name: Craft documents WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -37,11 +34,5 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-doc --all-targets --locked -- -D warnings - - run: cargo clippy -p craft-doc --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-doc --locked -- --nocapture - - run: cargo test -p craft-doc --all-features --locked -- --nocapture - run: cargo check -p craft-doc --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/docpath.yml b/.github/workflows/docpath.yml deleted file mode 100644 index e0115f6f58..0000000000 --- a/.github/workflows/docpath.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Document paths - -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml'] - pull_request: - paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml'] - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: docpath-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - docpath: - timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-docpath --all-targets --locked -- -D warnings - - run: cargo test -p craft-docpath --locked -- --nocapture diff --git a/.github/workflows/ecproj-format.yml b/.github/workflows/ecproj-format.yml index 24a3350af8..048c897b3c 100644 --- a/.github/workflows/ecproj-format.yml +++ b/.github/workflows/ecproj-format.yml @@ -12,20 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: ecproj-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: ecproj-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: ecproj-format: + name: EffectCraft project format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -37,9 +34,5 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-ecproj-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-ecproj-format --locked -- --nocapture - run: cargo check -p craft-ecproj-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/font-store.yml b/.github/workflows/font-store.yml index 0578f18ec4..e655697b3d 100644 --- a/.github/workflows/font-store.yml +++ b/.github/workflows/font-store.yml @@ -12,20 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: font-store-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: font-store-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not. jobs: font-store: + name: Font store WASM timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -35,13 +32,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-font-store --all-targets --locked -- -D warnings - - run: cargo test -p craft-font-store --locked - - run: cargo clippy -p craft-font-catalog --all-targets --locked -- -D warnings - - run: cargo test -p craft-font-catalog --locked - name: Check the web build - if: runner.os == 'Linux' run: cargo check -p craft-font-store --target wasm32-unknown-unknown --locked diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index 84d2c0d7e9..12478d2c95 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -42,11 +42,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-formats-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-formats-${{ github.ref }} + cancel-in-progress: true jobs: check: @@ -68,7 +67,9 @@ jobs: - { crate: craft-tiff, features: "" } - { crate: craft-heif, features: "testdata" } - { crate: craft-cms, features: "" } - name: ${{ matrix.crate }} lint, tests, WASM + # fmt, clippy with default and with all features, and the tests run in the Workspace gate on + # every OS; this lints each feature alone and checks the web build. + name: ${{ matrix.crate }} feature sets, WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -80,32 +81,19 @@ jobs: persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2.9.3 - with: - key: ${{ matrix.crate }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p "$CRATE" --check - env: - CRATE: ${{ matrix.crate }} - - name: Clippy, default features and each feature alone + - name: Clippy, each feature alone + if: matrix.features != '' env: CRATE: ${{ matrix.crate }} FEATURES: ${{ matrix.features }} run: | - cargo clippy -p "$CRATE" --all-targets --locked -- -D warnings for f in $FEATURES; do echo "::group::feature: $f" cargo clippy -p "$CRATE" --all-targets --locked --no-default-features --features "$f" -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p "$CRATE" --all-targets --locked --all-features -- -D warnings - env: - CRATE: ${{ matrix.crate }} - - run: cargo test -p "$CRATE" --all-features --locked - env: - CRATE: ${{ matrix.crate }} - run: cargo check -p "$CRATE" --all-features --locked --target wasm32-unknown-unknown env: CRATE: ${{ matrix.crate }} diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml new file mode 100644 index 0000000000..85ad96f2fe --- /dev/null +++ b/.github/workflows/full-validation.yml @@ -0,0 +1,64 @@ +name: Full validation + +# Add full-validation to a PR for uncapped validation of its merge ref. Keep the label across pushes. +# Fast Workspace checks are not substitutes for these six completed native/PDF gate checks. +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # An unrelated label event must not cancel an active full run. + group: full-validation-${{ github.event.action == 'labeled' && github.event.label.name != 'full-validation' && github.run_id || github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + native: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full native + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: bash scripts/ci-test-inputs.sh + command: | + python scripts/test-full-validation.py + bash scripts/ci-full-validation.sh + + pdf-contracts: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full PDF contracts + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + craft-fonts-ref: "" + require-craft-fonts: false + env: RUSTFLAGS=--cfg craft_pdf_unicode_fixtures + setup-command: | + python scripts/test-fetch-pdf-test-fonts.py + python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" + echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" + command: | + unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES + cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings + cargo test -p craft-pdf --all-features --locked + cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml deleted file mode 100644 index 7e69031884..0000000000 --- a/.github/workflows/i18n.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Translations - -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml'] - pull_request: - paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml'] - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: i18n-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - i18n: - timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-i18n --all-targets --features collate --locked -- -D warnings - - run: cargo test -p craft-i18n --features collate --locked -- --nocapture diff --git a/.github/workflows/jpeg.yml b/.github/workflows/jpeg.yml index 21db0ab794..495af8b232 100644 --- a/.github/workflows/jpeg.yml +++ b/.github/workflows/jpeg.yml @@ -12,16 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-jpeg-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-jpeg-${{ github.ref }} + cancel-in-progress: true jobs: check: - timeout-minutes: 10 - name: JPEG lint, tests, WASM + # Uncached: the wasm check builds its dependencies on every run (about 10 minutes with setup). + timeout-minutes: 20 + # fmt, clippy and the tests run in the Workspace gate on every OS. + name: JPEG WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -34,13 +35,5 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-jpeg - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-jpeg --check - - run: cargo clippy -p craft-jpeg --all-targets --locked -- -D warnings - - run: cargo test -p craft-jpeg --locked - run: cargo check -p craft-jpeg --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/keymap.yml b/.github/workflows/keymap.yml index 41fcc0502d..bd4ef280a3 100644 --- a/.github/workflows/keymap.yml +++ b/.github/workflows/keymap.yml @@ -12,16 +12,17 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: keymap-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: keymap-${{ github.ref }} + cancel-in-progress: true jobs: linux: timeout-minutes: 15 - name: Keymap (Linux) + # fmt, and clippy and the tests with default and with all features, run in the Workspace gate + # on every OS; this runs the feature subsets. + name: Keymap feature sets runs-on: ubuntu-latest env: CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts @@ -43,12 +44,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-keymap-linux - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-keymap --check + components: clippy - run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings # `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU # to run, so the test steps leave them out. @@ -58,40 +54,6 @@ jobs: run: cargo test -p craft-keymap --no-default-features --lib --tests --locked - name: Test egui dispatch and the shortcuts dialog run: cargo test -p craft-keymap --features ui --locked - native: - timeout-minutes: 15 - name: Keymap (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["macos-latest","windows-latest"]') || fromJSON('["windows-latest"]') }} - runs-on: ${{ matrix.os }} - env: - CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - with: - persist-credentials: false - - name: Checkout test fonts - uses: actions/checkout@v7.0.1 - with: - repository: storytold/craft-fonts - ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - path: .test-inputs/craft-fonts - persist-credentials: false - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-keymap-${{ matrix.os }} - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo test -p craft-keymap --features ui --locked wasm: timeout-minutes: 10 name: Keymap WASM @@ -108,8 +70,4 @@ jobs: with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-keymap-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/media.yml b/.github/workflows/media.yml index 4814e35ca8..1b5afaebdf 100644 --- a/.github/workflows/media.yml +++ b/.github/workflows/media.yml @@ -11,17 +11,22 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-media-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-media-${{ github.ref }} + cancel-in-progress: true jobs: lint: timeout-minutes: 10 - name: Media lint, feature sets, WASM + # fmt, and clippy with default and with all features, run in the Workspace gate on every OS. + name: Media feature sets, WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -34,20 +39,12 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-media-lint - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-media --check - run: cargo clippy -p craft-media --all-targets --locked --no-default-features -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features bitstream -- -D warnings - - run: cargo clippy -p craft-media --all-targets --locked -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features ogg -- -D warnings - - run: cargo clippy -p craft-media --all-targets --locked --all-features -- -D warnings - - run: cargo clippy -p craft-media-testkit --all-targets --locked -- -D warnings - run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features serde -- -D warnings - run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown test: @@ -65,10 +62,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-media-test - save-if: ${{ github.ref == 'refs/heads/main' }} - name: Build tests while installing ffmpeg run: | # The man-db index rebuild after dpkg is slow on hosted runners. diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml index 8d10587313..b12c8bcc6a 100644 --- a/.github/workflows/menu.yml +++ b/.github/workflows/menu.yml @@ -18,7 +18,8 @@ concurrency: jobs: linux: timeout-minutes: 15 - name: Menu (Linux) + # fmt, native clippy and the tests run in the Workspace gate on every OS. + name: Menu macOS and WASM lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v7.0.1 @@ -26,14 +27,8 @@ jobs: persist-credentials: false - uses: dtolnay/rust-toolchain@stable with: - components: rustfmt, clippy + components: clippy targets: aarch64-apple-darwin, wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2.9.3 - with: - key: craft-menu-linux - - run: cargo fmt -p craft-menu --check - - run: cargo clippy -p craft-menu --all-targets --locked -- -D warnings # The macOS backend type-checks from Linux; it needs no linker or SDK. - run: cargo clippy -p craft-menu --lib --locked --target aarch64-apple-darwin -- -D warnings - run: cargo clippy -p craft-menu --lib --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-menu --locked diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..ed9d361279 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: Nightly full tests + +# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep +# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The +# rest of the workspace's tests run with them, on Linux, with the gate's setup. +on: + schedule: + - cron: "37 2 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: nightly-${{ github.ref }} + cancel-in-progress: false + +jobs: + full: + name: Full tests + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + timeout-minutes: 120 + tools: cargo-nextest@0.9.150 + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: bash scripts/ci-test-inputs.sh + cache-paths: .test-inputs/photocraft/corpus + cache-key: photocraft-corpus + cache-key-files: scripts/ci-test-inputs.sh + command: cargo nextest run --workspace --all-features --locked --profile ci diff --git a/.github/workflows/pcraft-format.yml b/.github/workflows/pcraft-format.yml index 9c66b5a10d..0e4feabc92 100644 --- a/.github/workflows/pcraft-format.yml +++ b/.github/workflows/pcraft-format.yml @@ -12,20 +12,18 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: pcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: pcraft-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the +# workspace on 1.95; this checks the web build on 1.95. jobs: pcraft-format: + name: PhotoCraft format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -37,9 +35,5 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-pcraft-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-pcraft-format --locked -- --nocapture - run: cargo check -p craft-pcraft-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index 09ddfabcab..7b73977570 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -11,22 +11,23 @@ on: permissions: contents: read +# A fraction of the proptest cases, as in the Workspace gate; nightly.yml runs them in full. +env: + PROPTEST_CASES: "64" + concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-pdf-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-pdf-${{ github.ref }} + cancel-in-progress: true jobs: native: - name: PDF (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + # fmt, clippy and the tests run in the Workspace gate on every OS, with the licensed fonts and + # the plate tests; this runs the tests behind craft_pdf_unicode_fixtures and the read-only + # contract, which is its own workspace. + name: PDF Unicode fixtures and read-only contract + runs-on: ubuntu-latest env: RUSTFLAGS: --cfg craft_pdf_unicode_fixtures steps: @@ -38,11 +39,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-pdf - save-if: ${{ github.ref == 'refs/heads/main' }} - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" @@ -52,9 +48,7 @@ jobs: python scripts/test-fetch-pdf-test-fonts.py python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" - - run: cargo fmt --check - - run: cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-pdf --all-features --locked + - run: cargo test -p craft-pdf --all-features --locked --test unicode_writing --test upstream_compatibility --test upstream_reading - run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked backends: name: PDF vendored contracts @@ -68,10 +62,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-pdf-backends - save-if: ${{ github.ref == 'refs/heads/main' }} - run: bash scripts/test-pdf-backends.sh wasm: name: PDF WASM runtime @@ -89,10 +79,6 @@ jobs: with: toolchain: stable targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-pdf-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - uses: actions/setup-python@v7.1.0 with: python-version: "3.12" @@ -117,31 +103,3 @@ jobs: fallback: cargo-install - run: cargo test -p craft-pdf --all-features --locked --target wasm32-unknown-unknown - run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked --target wasm32-unknown-unknown - plate-test: - name: Plate tests and craft-prepress - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: clippy - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-plate-test - save-if: ${{ github.ref == 'refs/heads/main' }} - - uses: actions/setup-python@v7.1.0 - with: - python-version: "3.12" - - name: Provision licensed PDF test fonts - shell: bash - run: | - python scripts/test-fetch-pdf-test-fonts.py - python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" - echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" - - run: cargo clippy -p craft-plate-test -p craft-prepress --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-plate-test -p craft-prepress --all-features --locked diff --git a/.github/workflows/print.yml b/.github/workflows/print.yml deleted file mode 100644 index 8e2108e096..0000000000 --- a/.github/workflows/print.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Print spooler -on: - workflow_dispatch: - push: - branches: [main] - paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml'] - pull_request: - paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml'] -permissions: - contents: read -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: print-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} -jobs: - print: - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - - run: cargo clippy -p craft-print --all-targets -- -D warnings - - name: Prepare the Windows test driver - if: runner.os == 'Windows' - shell: powershell - run: | - Start-Service Spooler - Add-PrinterDriver -Name 'Generic / Text Only' - - run: cargo test -p craft-print --locked -- --nocapture - timeout-minutes: 10 - env: - CRAFT_PRINT_REQUIRE_QUEUE: ${{ runner.os == 'Windows' && '1' || '0' }} diff --git a/.github/workflows/proof.yml b/.github/workflows/proof.yml index 10365a2306..ea5edb8a56 100644 --- a/.github/workflows/proof.yml +++ b/.github/workflows/proof.yml @@ -12,16 +12,16 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: craft-proof-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: craft-proof-${{ github.ref }} + cancel-in-progress: true jobs: check: timeout-minutes: 20 - name: Proofing lint, tests with and without Language data, WASM + # fmt, and clippy and the tests without Language data, run in the Workspace gate on every OS. + name: Proofing with Language data, WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -43,18 +43,10 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-proof - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-proof --check - - name: Without Language data (a fork, docs.rs, offline) - run: | - cargo clippy -p craft-proof --all-targets --locked -- -D warnings - cargo test -p craft-proof --locked - cargo check -p craft-proof --locked --target wasm32-unknown-unknown + - name: The web build without Language data (a fork, docs.rs, offline) + run: cargo check -p craft-proof --locked --target wasm32-unknown-unknown - name: A release without Language data fails run: | if CRAFT_I18N_REQUIRED=1 cargo check -p craft-proof --locked 2>build.log; then diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml deleted file mode 100644 index f15ef6ddc8..0000000000 --- a/.github/workflows/ui.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Shared UI - -on: - push: - branches: [main] - paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"] - pull_request: - paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"] - workflow_dispatch: - -permissions: - contents: read - -concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-ui-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - native: - timeout-minutes: 30 - name: UI (${{ matrix.os }}) - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - name: Install software Vulkan renderer - if: runner.os == 'Linux' - run: | - sudo apt-get update - sudo apt-get install -y mesa-vulkan-drivers libvulkan1 - echo 'WGPU_BACKEND=vulkan' >> "$GITHUB_ENV" - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - components: rustfmt, clippy - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-ui - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt --check - - run: cargo clippy -p craft-ui --all-targets --locked -- -D warnings - - run: cargo clippy -p craft-ui --all-targets --all-features --locked -- -D warnings - - run: cargo test -p craft-ui --locked - - run: cargo test -p craft-ui --all-features --locked - wasm: - timeout-minutes: 15 - name: UI WASM - runs-on: ubuntu-latest - steps: - - name: Harden runner - uses: step-security/harden-runner@v2.22.4 - with: - egress-policy: audit - - uses: actions/checkout@v7.0.1 - - uses: step-security/dtolnay-rust-toolchain@v1.0.0 - with: - toolchain: stable - targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-ui-wasm - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo check -p craft-ui --all-features --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 9a7139026d..96ab4d6ad2 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -12,20 +12,18 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: update-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: update-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests with default and with all features run in the Workspace gate on every +# OS; this runs the egui feature alone. jobs: update: + name: Update with egui alone timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -39,10 +37,6 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - # Default (no egui) and the egui feature both build and lint cleanly. - - run: cargo clippy -p craft-update --all-targets --locked -- -D warnings + components: clippy - run: cargo clippy -p craft-update --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-update --locked -- --nocapture - run: cargo test -p craft-update --locked --features egui -- --nocapture diff --git a/.github/workflows/vectorcraft-format.yml b/.github/workflows/vectorcraft-format.yml index 74144f30f4..cd66615a50 100644 --- a/.github/workflows/vectorcraft-format.yml +++ b/.github/workflows/vectorcraft-format.yml @@ -12,20 +12,18 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: vectorcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: vectorcraft-format-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the +# workspace on 1.95; this checks the web build on 1.95. jobs: vectorcraft-format: + name: VectorCraft format WASM timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -37,9 +35,5 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - components: rustfmt, clippy targets: wasm32-unknown-unknown - - run: cargo fmt --check - - run: cargo clippy -p craft-vectorcraft-format --all-targets --locked -- -D warnings - - run: cargo test -p craft-vectorcraft-format --locked -- --nocapture - run: cargo check -p craft-vectorcraft-format --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/video.yml b/.github/workflows/video.yml index fa667bdfca..20afe0d700 100644 --- a/.github/workflows/video.yml +++ b/.github/workflows/video.yml @@ -11,6 +11,11 @@ on: permissions: contents: read +# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full. +env: + CRAFT_HOSTILE_DIVISOR: "8" + PROPTEST_CASES: "64" + concurrency: group: shared-video-${{ github.ref }} cancel-in-progress: true @@ -18,7 +23,8 @@ concurrency: jobs: lint: timeout-minutes: 20 - name: Video lint, feature sets, docs, WASM + # fmt and clippy with all features run in the Workspace gate on every OS. + name: Video feature sets, docs, WASM runs-on: ubuntu-latest steps: - name: Harden runner @@ -31,12 +37,8 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-video-lint - - run: cargo fmt -p craft-video --check # Each feature on its own, so code that needs another feature fails here. - name: Clippy, each feature alone run: | @@ -45,19 +47,15 @@ jobs: cargo clippy -p craft-video --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings echo "::endgroup::" done - - run: cargo clippy -p craft-video --all-targets --locked --all-features -- -D warnings - run: cargo doc -p craft-video --all-features --no-deps --locked env: RUSTDOCFLAGS: "-D warnings" - run: cargo check -p craft-video --all-features --locked --target wasm32-unknown-unknown test: timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - runs-on: ${{ matrix.os }} - name: Video tests (${{ matrix.os }}) + # The Workspace gate runs these tests on every OS without ffmpeg; this runs them with it. + runs-on: ubuntu-latest + name: Video tests with ffmpeg steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -69,11 +67,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: "1.95" - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-video-${{ matrix.os }} - - name: Install ffmpeg (Linux) - if: runner.os == 'Linux' + - name: Install ffmpeg run: | sudo rm -f /var/lib/man-db/auto-update sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ffmpeg diff --git a/.github/workflows/web-api.yml b/.github/workflows/web-api.yml index 4bf1a30fe8..f0f8e22da7 100644 --- a/.github/workflows/web-api.yml +++ b/.github/workflows/web-api.yml @@ -12,10 +12,10 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: web-api-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: web-api-${{ github.ref }} + cancel-in-progress: true jobs: web-api: @@ -35,7 +35,7 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - name: Read the wasm-bindgen version from Cargo.lock id: wasm-bindgen @@ -50,8 +50,6 @@ jobs: with: tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }} fallback: cargo-install - - run: cargo fmt --check - - run: cargo clippy -p craft-web-api --all-targets --locked -- -D warnings + # fmt, native clippy and the native tests run in the Workspace gate. - run: cargo clippy -p craft-web-api --all-targets --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-web-api --locked - run: cargo test -p craft-web-api --locked --target wasm32-unknown-unknown diff --git a/.github/workflows/web-host.yml b/.github/workflows/web-host.yml index 76e6701e53..dc0254850a 100644 --- a/.github/workflows/web-host.yml +++ b/.github/workflows/web-host.yml @@ -12,16 +12,16 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it - # always gets to save the cache. - group: shared-web-host-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: shared-web-host-${{ github.ref }} + cancel-in-progress: true jobs: check: timeout-minutes: 20 - name: Web host lint, tests, WASM tests + # fmt, native clippy and the native tests run in the Workspace gate. + name: Web host WASM lint and tests runs-on: ubuntu-latest env: CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner @@ -36,16 +36,9 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy + components: clippy targets: wasm32-unknown-unknown - - uses: step-security/rust-cache@v2.9.2 - with: - key: craft-web-host - save-if: ${{ github.ref == 'refs/heads/main' }} - - run: cargo fmt -p craft-web-host --check - - run: cargo clippy -p craft-web-host --all-targets --locked -- -D warnings - run: cargo clippy -p craft-web-host --all-targets --locked --target wasm32-unknown-unknown -- -D warnings - - run: cargo test -p craft-web-host --locked - name: Read the wasm-bindgen version from Cargo.lock id: wasm-bindgen shell: bash diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index fdd28e2030..c13b1ac3fe 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -12,20 +12,18 @@ permissions: contents: read concurrency: - # Pull requests share one group per branch, so a newer push cancels the older run. Every other - # run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued. - group: window-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + # One group per pull request and per branch: a newer push cancels the run it supersedes, on main + # too, since the newest run checks everything before it. + group: window-${{ github.ref }} + cancel-in-progress: true +# fmt, clippy and the tests with default and with all features (egui and restore together) run in +# the Workspace gate on every OS; this runs each feature alone. jobs: window: + name: Window with each feature alone timeout-minutes: 15 - strategy: - fail-fast: false - matrix: - # macOS runners are kept for releases: macOS runs only when started by hand. - os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-latest steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -39,12 +37,8 @@ jobs: - uses: step-security/dtolnay-rust-toolchain@v1.0.0 with: toolchain: stable - components: rustfmt, clippy - - run: cargo fmt --check - # Default (no egui) and the egui feature both build and lint cleanly. - - run: cargo clippy -p craft-window --all-targets --locked -- -D warnings + components: clippy - run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings - - run: cargo test -p craft-window --locked -- --nocapture - run: cargo test -p craft-window --locked --features egui -- --nocapture - run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings - - run: cargo test -p craft-window --locked --features restore,egui -- --nocapture + - run: cargo test -p craft-window --locked --features restore -- --nocapture diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 4d717fed82..5a9e4989d6 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -6,17 +6,21 @@ on: tags: ["v*"] pull_request: workflow_dispatch: + # A full run on main every 6 hours that is never cancelled, so the caches are saved while pushes + # to main cancel each other. + schedule: + - cron: "17 */6 * * *" 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' }} + # A pull request, and main, each have one group, so a newer push cancels the run it supersedes; + # the newest push's run still tests everything before it. Every other run (a release tag, a + # manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced + # while queued: a release run always finishes, and the scheduled run saves the caches. + group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} jobs: native: @@ -24,47 +28,63 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: os: '["ubuntu-latest","windows-latest","macos-latest"]' + # On a pull request, macOS and Windows run only when it can change platform behaviour: a + # crate with platform cfg code or one that depends on it, the build setup, or a file outside + # the crates (craft-common-actions' select-platforms). The full-ci label runs them anyway + # from the next push or manual run; pushes to main always run every leg. + select-os: '["windows-latest","macos-latest"]' timeout-minutes: 120 - # The Windows leg runs its tests with nextest (.config/nextest.toml). + # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: cargo-nextest@0.9.150 packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan - windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 - env: CRAFT_PRINT_REQUIRE_QUEUE=0 - setup-command: | - set -euo pipefail - corpus_fetcher=.test-inputs/photocraft - mkdir -p "$corpus_fetcher" - git -C "$corpus_fetcher" init - git -C "$corpus_fetcher" remote add origin https://github.com/storytold/PhotoCraft.git - git -C "$corpus_fetcher" fetch --quiet --depth=1 origin 74330157cb601573ae4523a95bb9132822fc3918 - git -C "$corpus_fetcher" checkout --quiet --detach FETCH_HEAD - (cd "$corpus_fetcher" && cargo xtask corpus --psd --psd-tools --atn --exr --heif --pngsuite) - mkdir -p corpus - cp -a "$corpus_fetcher/corpus/." corpus/ - python scripts/test-fetch-pdf-test-fonts.py - python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" - 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" + # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link + # time. A panic still names its file and line; only backtrace frames lose theirs, and the + # Linux and macOS legs keep line tables. + windows-env: | + CRAFT_PRINT_REQUIRE_QUEUE=1 + CARGO_PROFILE_DEV_DEBUG=0 + # The fuzz-style tests run a fraction of their cases here: every hostile-input hammer and + # sweep 1/8 (craft-testkit's CRAFT_HOSTILE_DIVISOR), every proptest without its own case + # count 64 cases instead of 256. nightly.yml runs them all in full. + env: | + CRAFT_PRINT_REQUIRE_QUEUE=0 + CRAFT_HOSTILE_DIVISOR=8 + PROPTEST_CASES=64 + setup-command: bash scripts/ci-test-inputs.sh + # The PhotoCraft corpora, keyed on the script that pins them: a hit skips the PhotoCraft + # checkout and its xtask build (1:51 on Windows). + cache-paths: .test-inputs/photocraft/corpus + cache-key: photocraft-corpus + cache-key-files: scripts/ci-test-inputs.sh + # A `lint ()` leg beside each `gate ()` leg, so clippy is off the tests' critical path. + lint-command: | + if [ "$RUNNER_OS" = Linux ]; then + python3 scripts/test-workspace-concurrency.py + python3 scripts/test-workspace-tests.py + fi + # One rustfmt call gets every source root of the workspace, which is longer than + # Windows allows for a command line (os error 206). rustfmt's result is the same on + # every system, so the Linux and macOS legs check it. + if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check + fi + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo clippy --workspace --all-targets --all-features --locked -- -D warnings 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 - cargo test --workspace --locked - cargo test --workspace --all-features --locked - windows-command: | - powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo fmt --check - cargo clippy --workspace --all-targets --locked -- -D warnings - cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - # The same tests as `cargo test`, run in parallel across test binaries instead of one - # binary at a time; nextest skips doctests, so `cargo test --doc` runs them. - cargo nextest run --workspace --locked --profile ci - cargo test --workspace --doc --locked + # The tests run once, with every feature, in parallel across test binaries; nextest skips + # doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's + # first clippy run; the last command runs the crates whose tests check behaviour with a + # feature off, which an all-features build cannot reach. cargo nextest run --workspace --all-features --locked --profile ci cargo test --workspace --doc --all-features --locked + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci + windows-command: | + powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' + cargo nextest run --workspace --all-features --locked --profile ci + cargo test --workspace --doc --all-features --locked + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci msrv: name: Rust 1.95 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4c86afd610..1b6105f242 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -119,16 +119,59 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. +The legacy ZIP Zstandard method-20 mapping and bounded-read regression in `crates/zip/src/lenient` are ported from RRFZ's Craft Anything commit `29badae7c9280fdf4c24795927bf3a91f51694c6` (MIT OR Apache-2.0). RRFZ remains the primary Git author. Firmware scanner detection remains app-owned and is not part of this port. +## TAR/CPIO compatibility updates + +The old GNU sparse-extension traversal, GNU CRC-symlink compatibility and PAX-size precedence fixes and their regression tests in `crates/tar` are ported from RRFZ's Craft Anything PRs #1973 (`8ea2ec66a1bc80f0420f3695baac877a0cb9b9a5`), #1984 (`b226a475f7dce9710e3af7a069386fe7a9720df7`) and #2007 (`d29465c20b0d570ea4973be512a0cb4e212bb60f`). Source is MIT OR Apache-2.0; RRFZ remains the primary Git author of each port. The PAX update adapts to the shared parser's existing `PaxOverrides` structure without changing the source policy. + ## Aligned stored ZIP entries The USDZ alignment requirement and compatibility fixture for `Writer::add_stored_aligned` come from TextureCraft `crates/formats/src/mesh_export/usd.rs`, introduced by bflatastic in `bdbb52c9` and maintained through `9eb20086` (MIT OR Apache-2.0). The shared API and alignment validation are subsequent Dylan M. Taylor work. Scene/material mapping remains in TextureCraft. + The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0. Sanitization, animation fitting and numeric output policy remain caller-owned. + ## Screen Video key frames `crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. +## Source Map v3 parser and lookup + +`crates/sourcemap` extracts the bounded parser, source inventory and generated-position lookup from Craft Anything `crates/formats/src/sourcemap.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). Core-history ports preserve Brandon Thomas, BFlat, Afloat, RRFZ, Nicolas Bohn and Alex Joaquim Pereira as primary authors, with exact source revisions in each commit. Six regression files preserve their source authors; nine core unit tests retain the original tests. App annotation scanning, data URLs, base64 and file I/O are intentionally not imported. Workspace wiring is a subsequent change; existing limits and errors are unchanged. ## JSONC span-preserving editing `crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. + +## XFA XML DOM + +`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. The initial extraction changes visibility and module boundaries; subsequent namespace-retention budget hardening intentionally tightens resource admission. PDF/layout/form policy remains in the app. + +## Java class inspection + +`crates/java-class` extracts Craft Anything `java_class.rs` and `java_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0), preserving separate primary-author source-history ports by Brandon Thomas, BFlat, Afloat and RRFZ. The checked byte-reader, modified UTF-8 unit decoder, descriptor display helper and synthetic class fixtures come from the same source snapshot. Seven regression files retain their source authors. Neutral error wiring and shared crate integration are subsequent changes. No JAR archive, application I/O or bytecode execution is imported. + +## WebAssembly inspection + +`crates/wasm` extracts Craft Anything `crates/formats/src/wasm.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2`, with its checked byte-reader subset and original synthetic WASM/testkit fixtures (MIT OR Apache-2.0). Eight core-history ports preserve Brandon Thomas, Afloat and RRFZ as primary authors; component, repeated-custom-section and referenced-string regression imports retain source authors and commit references. Fixtures come from `crates/testkit/src/formats.rs` and deterministic mutation helpers from `crates/testkit/src/lib.rs`; no third-party binaries. Shared error naming and workspace wiring are subsequent changes. Existing inspection limits and report behavior are unchanged; this crate validates/inspects/renders, never executes modules. + +## Packet capture and protocol inspection + +`crates/pcap` extracts Craft Anything `crates/formats/src/pcap.rs`, its checked byte reader primitives and synthetic packet fixtures/regressions at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the implementation, byte reader and fixtures in `f64ae3bf3c8863a982af1304e06de20653803968`. Subsequent fixes by phatloi0010, GGWA, BFlat, Afloat, NetterSilver, Max Mittelstädt and RRFZ retain separate primary-author source-history commits with immutable source revisions. Shared error/API wiring and chrono-based timestamp formatting with exhaustive day-boundary parity tests are subsequent Dylan M. Taylor changes. No packet reassembly, decryption, live capture or app analysis policy is imported. +## HTTP Archive reader + +`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. + +## Dalvik DEX inspection + +`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained. + +## EVM bytecode inspection + +`crates/evm` extracts Craft Anything `crates/formats/src/evm.rs` at `a31e995858f4312e0f1d59a007112da191ef2d26` (MIT OR Apache-2.0). Eight separate source-history ports preserve Brandon Thomas, Afloat, RRFZ and NetterSilver as primary authors with immutable source references. Synthetic EVM fixtures and deterministic mutation helpers come from the same app source; regression files retain their source provenance. Neutral errors and workspace integration are subsequent changes. No code execution or transaction behavior is imported. + +## XFDF field reader + +`crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository. + +Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. diff --git a/Cargo.lock b/Cargo.lock index 9fa1f44018..6417b2451f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,6 +232,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -1074,6 +1085,18 @@ dependencies = [ "winx", ] +[[package]] +name = "cap-std" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix 1.1.5", +] + [[package]] name = "cast" version = "0.3.0" @@ -1545,6 +1568,16 @@ dependencies = [ "ureq", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-ai-core" version = "0.1.0" @@ -1616,6 +1649,25 @@ dependencies = [ "craft-media-testkit", ] +[[package]] +name = "craft-cloud" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-cloud-local" +version = "0.1.0" +dependencies = [ + "cap-std", + "craft-cloud", + "craft-ui", + "egui", + "tempfile", +] + [[package]] name = "craft-cms" version = "0.1.0" @@ -1644,10 +1696,15 @@ dependencies = [ name = "craft-control" version = "0.1.0" dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", "getrandom 0.3.4", + "log", "proptest", "serde", "serde_json", + "tempfile", ] [[package]] @@ -1722,6 +1779,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dex" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -1761,6 +1827,7 @@ dependencies = [ "craft-wordmodel", "image", "log", + "md4", "miniz_oxide 0.9.1", "proptest", "serde_json", @@ -1881,6 +1948,26 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-esign" +version = "0.1.0" +dependencies = [ + "craft-cloud", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-evm" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ews" version = "0.1.0" @@ -2122,6 +2209,14 @@ dependencies = [ "flate2", ] +[[package]] +name = "craft-har" +version = "0.1.0" +dependencies = [ + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-hdr" version = "0.1.0" @@ -2253,6 +2348,15 @@ dependencies = [ "widestring", ] +[[package]] +name = "craft-java-class" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-jmap" version = "0.1.0" @@ -2603,6 +2707,16 @@ dependencies = [ name = "craft-palette" version = "0.1.0" +[[package]] +name = "craft-pcap" +version = "0.1.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-pcraft-bundle" version = "0.1.0" @@ -2903,6 +3017,7 @@ name = "craft-raster-codecs" version = "0.1.0" dependencies = [ "base64 0.23.1", + "craft-dds", "craft-image-codecs", "image", "thiserror 2.0.21", @@ -3053,6 +3168,15 @@ dependencies = [ name = "craft-sniff" version = "0.1.0" +[[package]] +name = "craft-sourcemap" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ssip" version = "0.1.0" @@ -3091,6 +3215,21 @@ dependencies = [ "weezl 0.2.1", ] +[[package]] +name = "craft-suite-account" +version = "0.1.0" +dependencies = [ + "dirs", + "keyring", + "keyring-core", + "log", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "zeroize", +] + [[package]] name = "craft-svg" version = "0.1.0" @@ -3099,11 +3238,14 @@ dependencies = [ "craft-xml", "data-url", "flate2", + "gif", + "image-webp", "kurbo 0.13.1", "quick-xml 0.41.0", "resvg 0.48.1", "roxmltree 0.21.2", "thiserror 2.0.21", + "toml", "usvg 0.48.1", "vectorcraft-geom", "vectorcraft-pathops", @@ -3121,6 +3263,7 @@ dependencies = [ name = "craft-tar" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", ] @@ -3205,6 +3348,8 @@ dependencies = [ name = "craft-ui" version = "0.1.0" dependencies = [ + "craft-cloud", + "craft-esign", "craft-fonts-build", "craft-i18n", "eframe", @@ -3306,6 +3451,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-wasm" +version = "0.1.0" +dependencies = [ + "craft-testkit", + "serde", + "thiserror 2.0.21", + "wasmparser 0.261.0", + "wasmprinter", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -3380,6 +3536,21 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xfa" +version = "0.1.0" +dependencies = [ + "craft-xml", +] + +[[package]] +name = "craft-xfdf" +version = "0.1.0" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + [[package]] name = "craft-xfl" version = "0.1.0" @@ -4335,7 +4506,7 @@ dependencies = [ "ff 0.13.1", "generic-array", "group 0.13.0", - "hkdf", + "hkdf 0.12.4", "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", @@ -4984,6 +5155,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -5004,6 +5186,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -5613,6 +5796,15 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + [[package]] name = "hmac" version = "0.12.1" @@ -6594,6 +6786,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -6889,6 +7102,15 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "md4" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd76fb0fd6b2e4be62a73f8e0858ca97f81babcb1af322dcaca196f735f17f80" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.8.3" @@ -8068,7 +8290,7 @@ dependencies = [ "generic-array", "getrandom 0.2.17", "hex", - "hkdf", + "hkdf 0.12.4", "idea", "k256", "log", @@ -9633,6 +9855,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf 0.13.0", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -11989,7 +12230,7 @@ dependencies = [ "wasmi_collections", "wasmi_core", "wasmi_ir", - "wasmparser", + "wasmparser 0.228.0", ] [[package]] @@ -12029,6 +12270,28 @@ dependencies = [ "indexmap", ] +[[package]] +name = "wasmparser" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8" +dependencies = [ + "bitflags 2.13.2", + "indexmap", + "semver", +] + +[[package]] +name = "wasmprinter" +version = "0.261.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7" +dependencies = [ + "anyhow", + "termcolor", + "wasmparser 0.261.0", +] + [[package]] name = "wayland-backend" version = "0.3.17" @@ -12420,6 +12683,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -12963,6 +13239,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/Cargo.toml b/Cargo.toml index 50ec3c9176..f167b972b6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,13 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-xfa = { path = "crates/xfa" } +craft-evm = { path = "crates/evm" } +craft-java-class = { path = "crates/java-class" } +craft-sourcemap = { path = "crates/sourcemap" } +craft-pcap = { path = "crates/pcap" } +craft-har = { path = "crates/har" } +craft-xfdf = { path = "crates/xfdf" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } @@ -26,6 +33,7 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } @@ -52,11 +60,16 @@ craft-gzip = { path = "crates/gzip" } craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/app/ai-agents). +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "d94a3593adcff504eaaad9e5aee4c84fd2f07a72" } +craft-dex = { path = "crates/dex" } craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } +craft-cloud = { path = "crates/cloud" } +craft-cloud-local = { path = "crates/cloud-local" } craft-color = { path = "crates/color" } craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } @@ -86,6 +99,7 @@ craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-esign = { path = "crates/esign" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } @@ -164,6 +178,7 @@ craft-settings = { path = "crates/settings" } craft-scraft-format = { path = "crates/scraft-format" } craft-time = { path = "crates/time" } craft-silhouette-studio = { path = "crates/silhouette-studio" } +craft-suite-account = { path = "crates/suite-account" } craft-svg = { path = "crates/svg" } craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index dfe5cee0ba..a0e46a7a5c 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -36,17 +36,23 @@ flac-encode = ["craft-media/bitstream"] # The pure-Rust Vorbis encoder (`vorbis::encoder`) and Ogg Vorbis files through `encode` and # `encode_ogg_vorbis`. vorbis-encode = ["craft-media/ogg"] +# The pure-Rust Vorbis decoder (`vorbis::decoder`), packets and whole Ogg Vorbis files. +vorbis-decode = ["craft-media/ogg"] # 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`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders. +adpcm = ["craft-media/bitstream"] # QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. qoa = ["qoa-decode", "qoa-encode"] qoa-decode = [] qoa-encode = [] # ITU-T G.722 wideband sub-band ADPCM speech codec (64 kbit/s). g722 = [] +# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). +g726 = [] opus-encode = [] # GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own. gsm = ["gsm-decode", "gsm-encode"] @@ -114,10 +120,26 @@ required-features = ["decode", "encode"] name = "mp2_encoder_oracle" required-features = ["mpa-encode"] +[[test]] +name = "adpcm_oracle" +required-features = ["adpcm"] + [[test]] name = "flac_decode" required-features = ["flac-decode", "flac-encode"] +[[test]] +name = "vorbis_decode_oracle" +required-features = ["vorbis-decode", "vorbis-encode", "decode"] + +[[test]] +name = "vorbis_decode_hostile" +required-features = ["vorbis-decode", "vorbis-encode"] + +[[test]] +name = "vorbis_decode_synthetic" +required-features = ["vorbis-decode"] + [[test]] name = "gsm_oracle" required-features = ["gsm"] @@ -134,6 +156,10 @@ required-features = ["dsd"] name = "g722_oracle" required-features = ["g722"] +[[test]] +name = "g726_oracle" +required-features = ["g726"] + [[test]] name = "sbc_oracle" required-features = ["sbc"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 166f3f8176..bd80b54069 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -39,12 +39,14 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | | `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | | `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | +| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | | `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | | `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | | `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | +| `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` | | `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none | | `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none | | `peaks` | `peaks::Peaks` | none | diff --git a/crates/audio/src/adpcm/ima.rs b/crates/audio/src/adpcm/ima.rs new file mode 100644 index 0000000000..dcf6958f7a --- /dev/null +++ b/crates/audio/src/adpcm/ima.rs @@ -0,0 +1,247 @@ +//! IMA ADPCM in WAV blocks (format tag 0x0011). +//! +//! A block is, per channel, a 4-byte header (the first sample as `i16` and the step index as `u8`, +//! then a zero byte), then groups of 4 bytes per channel in channel order, each holding eight +//! 4-bit codes, low nibble first. A block of `block_align` bytes holds +//! `(block_align - 4 * channels) * 2 / channels + 1` samples per channel. A code is a sign bit and +//! three magnitude bits: the decoder adds `step/8` plus `step`, `step/2` and `step/4` for each set +//! magnitude bit from the top, then moves the step index by `[-1, -1, -1, -1, 2, 4, 6, 8]`. + +use super::{Error, Result, clip16, step_at}; + +const INDEX_ADJUST: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8]; + +/// The state of one channel's decoder. +#[derive(Clone, Copy)] +struct State { + predictor: i32, + index: i32, +} + +impl State { + /// The sample after code `nibble`. + fn step(&mut self, nibble: u8) -> i16 { + let step = step_at(self.index); + let mut diff = step >> 3; + if nibble & 1 != 0 { + diff += step >> 2; + } + if nibble & 2 != 0 { + diff += step >> 1; + } + if nibble & 4 != 0 { + diff += step; + } + if nibble & 8 != 0 { + diff = -diff; + } + self.predictor = clip16(self.predictor + diff); + self.index = (self.index + INDEX_ADJUST.get(usize::from(nibble & 7)).copied().unwrap_or(0)).clamp(0, 88); + self.predictor as i16 + } + + /// The code that brings the predictor closest to `sample`, applied to the state. + fn encode(&mut self, sample: i16) -> u8 { + let step = step_at(self.index); + let mut diff = i32::from(sample) - self.predictor; + let mut code = 0u8; + if diff < 0 { + code = 8; + diff = -diff; + } + let mut s = step; + for bit in [4u8, 2, 1] { + if diff >= s { + code |= bit; + diff -= s; + } + s >>= 1; + } + self.step(code); + code + } +} + +/// Samples per channel in a block of `block_align` bytes; `None` when the layout is impossible +/// (a block must hold the headers and whole groups of eight samples, and there are 1 to 8 +/// channels). +pub fn samples_per_block(block_align: usize, channels: usize) -> Option { + if !(1..=8).contains(&channels) { + return None; + } + let header = 4 * channels; + let body = block_align.checked_sub(header)?; + if body == 0 || !body.is_multiple_of(4 * channels) { + return None; + } + let per = (body / channels).checked_mul(2)?.checked_add(1)?; + // Callers size interleaved buffers from this value; the full count must fit too. + per.checked_mul(channels)?; + Some(per) +} + +/// Decode one block, appending its samples interleaved by channel to `out`. +pub fn decode_block(block: &[u8], channels: usize, out: &mut Vec) -> Result<()> { + let per = samples_per_block(block.len(), channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let h = block.get(4 * ch..4 * ch + 4).ok_or(Error::Malformed("truncated block header"))?; + let index = i32::from(h[2]); + if index > 88 { + return Err(Error::Malformed("step index above 88")); + } + states.push(State { predictor: i32::from(i16::from_le_bytes([h[0], h[1]])), index }); + } + let start = out.len(); + out.resize(start + per * channels, 0); + let samples = out.get_mut(start..).ok_or(Error::Malformed("output"))?; + for (ch, s) in states.iter().enumerate() { + if let Some(o) = samples.get_mut(ch) { + *o = s.predictor as i16; + } + } + let body = block.get(4 * channels..).ok_or(Error::Malformed("truncated block"))?; + for (g, group) in body.chunks_exact(4 * channels).enumerate() { + for (ch, bytes) in group.as_chunks::<4>().0.iter().enumerate() { + let Some(state) = states.get_mut(ch) else { continue }; + for (k, b) in bytes.iter().enumerate() { + for (half, nibble) in [b & 0xF, b >> 4].into_iter().enumerate() { + let t = 1 + g * 8 + k * 2 + half; + if let Some(o) = samples.get_mut(t * channels + ch) { + *o = state.step(nibble); + } + } + } + } + } + Ok(()) +} + +/// Decode a stream of blocks of `block_align` bytes. A final partial block is decoded as far as it +/// holds whole groups. +pub fn decode(data: &[u8], channels: usize, block_align: usize) -> Result> { + samples_per_block(block_align, channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut out = Vec::new(); + for block in data.chunks(block_align) { + if block.len() == block_align { + decode_block(block, channels, &mut out)?; + } else { + let (header, group) = (4 * channels, 4 * channels); + let whole = block.len().saturating_sub(header) / group * group; + if whole > 0 { + decode_block(block.get(..header + whole).unwrap_or(block), channels, &mut out)?; + } + } + } + Ok(out) +} + +/// The starting step index for a channel whose first samples are `x`: the index whose first +/// codes follow `x` most closely. +fn start_index(first: i16, x: &[i16]) -> i32 { + let mut best = (i64::MAX, 0); + for index in 0..=88 { + let mut st = State { predictor: i32::from(first), index }; + let mut err = 0i64; + for &s in x.iter().take(16) { + let code = st.encode(s); + let _ = code; + err += (i64::from(s) - i64::from(st.predictor)).pow(2); + } + if err < best.0 { + best = (err, index); + } + } + best.1 +} + +/// Encode one block from exactly `samples_per_block * channels` interleaved samples. +pub fn encode_block(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if samples.len() != per * channels { + return Err(Error::InvalidInput("a block needs exactly samples_per_block samples per channel")); + } + let mut block = vec![0u8; block_align]; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = samples.iter().skip(ch).step_by(channels).copied().collect(); + let first = col.first().copied().unwrap_or(0); + let st = State { predictor: i32::from(first), index: start_index(first, col.get(1..).unwrap_or(&[])) }; + if let Some(h) = block.get_mut(4 * ch..4 * ch + 4) { + h[..2].copy_from_slice(&first.to_le_bytes()); + h[2] = st.index as u8; + } + states.push(st); + } + let groups = (block_align - 4 * channels) / (4 * channels); + for g in 0..groups { + for ch in 0..channels { + let Some(state) = states.get_mut(ch) else { continue }; + for k in 0..4 { + let mut byte = 0u8; + for half in 0..2 { + let t = 1 + g * 8 + k * 2 + half; + let nibble = state.encode(samples.get(t * channels + ch).copied().unwrap_or(0)); + byte |= nibble << (4 * half); + } + if let Some(b) = block.get_mut(4 * channels + g * 4 * channels + ch * 4 + k) { + *b = byte; + } + } + } + } + Ok(block) +} + +/// Encode interleaved samples as blocks of `block_align` bytes. The last block is padded with +/// copies of the last sample, so a decoder returns up to one block more than was given. +pub fn encode(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut out = Vec::new(); + for chunk in samples.chunks(per * channels) { + if chunk.len() == per * channels { + out.extend(encode_block(chunk, channels, block_align)?); + } else { + let mut padded = chunk.to_vec(); + let last: Vec = chunk.get(chunk.len().saturating_sub(channels)..).unwrap_or(&[]).to_vec(); + while padded.len() < per * channels { + padded.extend(last.iter().copied().chain(std::iter::repeat(0)).take(channels)); + } + out.extend(encode_block(&padded, channels, block_align)?); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout() { + assert_eq!(samples_per_block(256, 1), Some(505)); + assert_eq!(samples_per_block(512, 2), Some(505)); + assert_eq!(samples_per_block(4, 1), None); + assert_eq!(samples_per_block(100, 0), None); + assert_eq!(samples_per_block(258, 2), None); + } + + #[test] + fn unrepresentable_interleaved_layout_is_rejected() { + let align = usize::MAX - 7; + assert_eq!(samples_per_block(align, 2), None); + assert!(encode(&[], 2, align).is_err()); + assert!(encode_block(&[], 2, align).is_err()); + } + + #[test] + fn silence_stays_silent() { + let block = encode_block(&vec![0; 505], 1, 256).unwrap(); + let mut out = Vec::new(); + decode_block(&block, 1, &mut out).unwrap(); + assert!(out.iter().all(|&s| s == 0)); + } +} diff --git a/crates/audio/src/adpcm/mod.rs b/crates/audio/src/adpcm/mod.rs new file mode 100644 index 0000000000..da552d3cdf --- /dev/null +++ b/crates/audio/src/adpcm/mod.rs @@ -0,0 +1,56 @@ +//! ADPCM: a decoder and an encoder for four families, each on whole blocks or streams of `i16` +//! samples interleaved by channel (feature `adpcm`). +//! +//! - [`ima`]: IMA / DVI ADPCM in WAV blocks (format tag 0x0011): 4 bits per sample, a 4-byte header +//! per channel and groups of eight samples per channel. +//! - [`ms`]: Microsoft ADPCM in WAV blocks (format tag 0x0002): 4 bits per sample, adaptive +//! two-tap prediction with the seven standard coefficient pairs. +//! - [`yamaha`]: Yamaha ADPCM (the YM2608 / AICA family): a raw stream of 4-bit codes. +//! - [`swf`]: the ADPCM of Flash (SWF) audio: 2 to 5 bits per sample, in blocks of 4096 samples. +//! +//! Written from the public descriptions of the algorithms: the IMA Digital Audio Focus and +//! Technical Working Groups' *Recommended Practices for Enhancing Digital Audio Compatibility* +//! (IMA ADPCM), Microsoft's *Multimedia Standards Update* (the WAVE format tags and the block +//! layout of Microsoft ADPCM), the SWF file format specification (the ADPCM section) and the +//! Yamaha ADPCM-B description. ffmpeg is only run as a black-box oracle in the tests. +//! +//! Decoders return errors, never panic, on damaged blocks. Encoders are greedy: they choose each +//! code to bring the decoder's output closest to the sample. + +pub mod ima; +pub mod ms; +pub mod swf; +pub mod yamaha; + +/// What went wrong decoding or encoding ADPCM. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The data is damaged, truncated or does not fit the stated block layout. + #[error("malformed ADPCM: {0}")] + Malformed(&'static str), + /// The settings or samples given to an encoder cannot be written. + #[error("ADPCM cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// Result with this module's [`Error`]. +pub type Result = std::result::Result; + +/// IMA ADPCM step sizes (the 89-entry table of the IMA recommended practices). +pub(crate) const STEP_TABLE: [i32; 89] = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, + 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, + 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767, +]; + +/// Clamp to the 16-bit sample range. +pub(crate) fn clip16(v: i32) -> i32 { + v.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) +} + +/// The step size at `index` (clamped to the table). +pub(crate) fn step_at(index: i32) -> i32 { + STEP_TABLE.get(index.clamp(0, 88) as usize).copied().unwrap_or(7) +} diff --git a/crates/audio/src/adpcm/ms.rs b/crates/audio/src/adpcm/ms.rs new file mode 100644 index 0000000000..057f93549f --- /dev/null +++ b/crates/audio/src/adpcm/ms.rs @@ -0,0 +1,244 @@ +//! Microsoft ADPCM in WAV blocks (format tag 0x0002). +//! +//! A block starts, for all channels in turn, with one predictor index (a byte, 0 to 6), then one +//! initial step (`delta`, `i16`), then each channel's second-last sample (`sample1`, `i16`) and +//! last sample (`sample2`, `i16`) before the block; the block's first two samples per channel are +//! `sample2` then `sample1`. The rest is 4-bit two's-complement codes, the first channel in the +//! high nibble. A block of `block_align` bytes holds `(block_align - 7 * channels) * 2 / channels +//! + 2` samples per channel. Each sample is predicted as `(sample1 * c1 + sample2 * c2) / 256` (rounding toward zero) +//! from the block's coefficient pair, plus `code * delta`; then `delta` becomes +//! `max(16, delta * a / 256)`, where `a` is the table entry for the code (`ADAPT`). + +use super::{Error, Result, clip16}; + +/// The seven coefficient pairs `(c1, c2)` every Microsoft ADPCM stream uses. +pub const COEFFICIENTS: [(i32, i32); 7] = [(256, 0), (512, -256), (0, 0), (192, 64), (240, 0), (460, -208), (392, -232)]; +/// How the step moves with the code's unsigned value (the index is the 4-bit pattern). +/// The largest step. The reference keeps it in 16 bits and no real stream gets near this bound; it +/// keeps every product in range however long a damaged block runs. +const MAX_DELTA: i32 = 1 << 24; +const ADAPT: [i32; 16] = [230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230]; + +#[derive(Clone, Copy)] +struct State { + c1: i32, + c2: i32, + delta: i32, + s1: i32, + s2: i32, +} + +impl State { + fn step(&mut self, nibble: u8) -> i16 { + let signed = i32::from(nibble) - if nibble & 8 != 0 { 16 } else { 0 }; + let predicted = (self.s1 * self.c1 + self.s2 * self.c2) / 256; + let sample = clip16(predicted + signed * self.delta); + self.s2 = self.s1; + self.s1 = sample; + let adapt = i64::from(ADAPT.get(usize::from(nibble)).copied().unwrap_or(256)); + let new_delta = (adapt * i64::from(self.delta)) >> 8; + self.delta = (new_delta.min(i64::from(MAX_DELTA)) as i32).max(16); + sample as i16 + } + + /// The code that brings the output closest to `sample`, applied to the state. + fn encode(&mut self, sample: i16) -> u8 { + let predicted = (self.s1 * self.c1 + self.s2 * self.c2) / 256; + let err = i32::from(sample) - predicted; + // round to the nearest multiple of delta + let q = if err >= 0 { (err + self.delta / 2) / self.delta } else { -((-err + self.delta / 2) / self.delta) }; + let code = (q.clamp(-8, 7) & 0xF) as u8; + self.step(code); + code + } +} + +/// Samples per channel in a block of `block_align` bytes; `None` for an impossible layout (1 or 2 +/// channels, and room for the header and at least one code byte). +pub fn samples_per_block(block_align: usize, channels: usize) -> Option { + if !(1..=2).contains(&channels) { + return None; + } + let body = block_align.checked_sub(7 * channels).filter(|&b| b > 0)?; + // codes pair up across channels + let per = (body.checked_mul(2)? / channels).checked_add(2)?; + // Include the header samples and all channels before callers size their buffers. + per.checked_mul(channels)?; + Some(per) +} + +/// Decode one block, appending its samples interleaved by channel to `out`. +pub fn decode_block(block: &[u8], channels: usize, out: &mut Vec) -> Result<()> { + let per = samples_per_block(block.len(), channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let header = block.get(..7 * channels).ok_or(Error::Malformed("truncated block header"))?; + let mut states = Vec::with_capacity(channels); + let word = |i: usize| i32::from(i16::from_le_bytes([header.get(i).copied().unwrap_or(0), header.get(i + 1).copied().unwrap_or(0)])); + for ch in 0..channels { + let pred = usize::from(header.get(ch).copied().unwrap_or(0)); + let &(c1, c2) = COEFFICIENTS.get(pred).ok_or(Error::Malformed("predictor index above 6"))?; + states.push(State { c1, c2, delta: word(channels + 2 * ch), s1: word(3 * channels + 2 * ch), s2: word(5 * channels + 2 * ch) }); + } + let start = out.len(); + out.resize(start + per * channels, 0); + let samples = out.get_mut(start..).ok_or(Error::Malformed("output"))?; + for (ch, s) in states.iter().enumerate() { + if let Some(a) = samples.get_mut(ch) { + *a = s.s2 as i16; + } + if let Some(b) = samples.get_mut(channels + ch) { + *b = s.s1 as i16; + } + } + let codes = block.get(7 * channels..).ok_or(Error::Malformed("truncated block"))?; + let mut t = 2 * channels; + for byte in codes { + for nibble in [byte >> 4, byte & 0xF] { + let ch = t % channels; + if let (Some(o), Some(state)) = (samples.get_mut(t), states.get_mut(ch)) { + *o = state.step(nibble); + } + t += 1; + } + } + Ok(()) +} + +/// Decode a stream of blocks of `block_align` bytes. A final partial block is decoded in full if +/// it holds a header and a code byte. +pub fn decode(data: &[u8], channels: usize, block_align: usize) -> Result> { + samples_per_block(block_align, channels).ok_or(Error::Malformed("block size does not fit the channel count"))?; + let mut out = Vec::new(); + for block in data.chunks(block_align) { + if block.len() == block_align || samples_per_block(block.len(), channels).is_some() { + decode_block(block, channels, &mut out)?; + } + } + Ok(out) +} + +/// The squared error of encoding `col` (one channel) from state `st`. +fn trial(mut st: State, col: &[i16]) -> i64 { + let mut err = 0i64; + for &s in col { + st.encode(s); + err += (i64::from(s) - i64::from(st.s1)).pow(2); + } + err +} + +/// Encode one block from exactly `samples_per_block * channels` interleaved samples. Each channel +/// gets the coefficient pair and initial step that code it with the least error. +pub fn encode_block(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if samples.len() != per * channels { + return Err(Error::InvalidInput("a block needs exactly samples_per_block samples per channel")); + } + let mut block = vec![0u8; block_align]; + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = samples.iter().skip(ch).step_by(channels).copied().collect(); + let (x0, x1) = (col.first().copied().unwrap_or(0), col.get(1).copied().unwrap_or(0)); + let rest = col.get(2..).unwrap_or(&[]); + let mut best: Option<(i64, usize, i32)> = None; + for (p, &(c1, c2)) in COEFFICIENTS.iter().enumerate() { + for delta in [16, 64, 256, 1024] { + let st = State { c1, c2, delta, s1: i32::from(x1), s2: i32::from(x0) }; + let e = trial(st, rest); + if best.is_none_or(|(b, _, _)| e < b) { + best = Some((e, p, delta)); + } + } + } + let (_, p, delta) = best.unwrap_or((0, 0, 16)); + let &(c1, c2) = COEFFICIENTS.get(p).unwrap_or(&(256, 0)); + states.push(State { c1, c2, delta, s1: i32::from(x1), s2: i32::from(x0) }); + let (d, a, b) = (delta as i16, x1, x0); + let put = |block: &mut Vec, at: usize, v: i16| { + if let Some(w) = block.get_mut(at..at + 2) { + w.copy_from_slice(&v.to_le_bytes()); + } + }; + if let Some(h) = block.get_mut(ch) { + *h = p as u8; + } + put(&mut block, channels + 2 * ch, d); + put(&mut block, 3 * channels + 2 * ch, a); + put(&mut block, 5 * channels + 2 * ch, b); + } + let mut t = 2 * channels; + for byte in block.iter_mut().skip(7 * channels) { + let mut b = 0u8; + for half in 0..2 { + let ch = t % channels; + let nibble = match states.get_mut(ch) { + Some(st) => st.encode(samples.get(t).copied().unwrap_or(0)), + None => 0, + }; + b |= nibble << (4 * (1 - half)); + t += 1; + } + *byte = b; + } + Ok(block) +} + +/// Encode interleaved samples as blocks of `block_align` bytes. The last block is padded with +/// copies of the last frame, so a decoder returns up to one block more than was given. +pub fn encode(samples: &[i16], channels: usize, block_align: usize) -> Result> { + let per = samples_per_block(block_align, channels).ok_or(Error::InvalidInput("block size does not fit the channel count"))?; + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut out = Vec::new(); + for chunk in samples.chunks(per * channels) { + let mut padded = chunk.to_vec(); + let last: Vec = chunk.get(chunk.len().saturating_sub(channels)..).unwrap_or(&[]).to_vec(); + while padded.len() < per * channels { + padded.extend(last.iter().copied().chain(std::iter::repeat(0)).take(channels)); + } + out.extend(encode_block(&padded, channels, block_align)?); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout() { + assert_eq!(samples_per_block(256, 1), Some(500)); + assert_eq!(samples_per_block(512, 2), Some(500)); + assert_eq!(samples_per_block(7, 1), None); + assert_eq!(samples_per_block(100, 3), None); + } + + #[test] + fn unrepresentable_layouts_are_rejected() { + for (align, channels) in [(usize::MAX / 2 + 7, 1), (usize::MAX / 2 + 14, 2)] { + assert_eq!(samples_per_block(align, channels), None); + assert!(encode(&[], channels, align).is_err()); + assert!(encode_block(&[], channels, align).is_err()); + } + } + + #[test] + fn a_long_run_of_large_codes_cannot_overflow() { + // a step that starts at its largest 16-bit value and grows with every large code + let mut block = vec![0x77u8; 7 + 2000]; + block[..7].copy_from_slice(&[0, 255, 127, 0, 0, 0, 0]); + for b in block.iter_mut().skip(7) { + *b = 0x88; + } + let mut out = Vec::new(); + decode_block(&block, 1, &mut out).unwrap(); + assert_eq!(out.len(), 2000 * 2 + 2); + } + + #[test] + fn bad_predictor_index_is_an_error() { + let mut block = vec![0u8; 64]; + block[0] = 7; + assert!(decode_block(&block, 1, &mut Vec::new()).is_err()); + } +} diff --git a/crates/audio/src/adpcm/swf.rs b/crates/audio/src/adpcm/swf.rs new file mode 100644 index 0000000000..2fc780b1d0 --- /dev/null +++ b/crates/audio/src/adpcm/swf.rs @@ -0,0 +1,168 @@ +//! The ADPCM of Flash (SWF) audio, 2 to 5 bits per sample. +//! +//! The stream starts with two bits, the code size minus 2. It continues in blocks of 4096 samples +//! per channel: each block starts, for every channel, with the first sample (16 bits, signed) and +//! the step index (6 bits, 0 to 88), then 4095 codes per channel, interleaved by sample. All fields +//! are packed most significant bit first. A code is a sign bit and `bits - 1` magnitude bits; the +//! decoder adds `step >> (bits - 1)` plus `step >> k` for each magnitude bit set `k` places below +//! the top one, negated when the sign is set, and moves the step index by the adjustment table of +//! the code size (negative for small magnitudes, positive for large ones). The last block may +//! be shorter. + +use super::{Error, Result, clip16, step_at}; +use craft_media::bitstream::{BitReader, BitWriter}; + +/// Samples per channel in a full block. +pub const BLOCK_SAMPLES: usize = 4096; + +/// The index adjustment for each magnitude, per code size. +fn adjust(bits: u32) -> &'static [i32] { + match bits { + 2 => &[-1, 2], + 3 => &[-1, -1, 2, 4], + 4 => &[-1, -1, -1, -1, 2, 4, 6, 8], + _ => &[-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16], + } +} + +#[derive(Clone, Copy)] +struct State { + predictor: i32, + index: i32, +} + +impl State { + fn apply(&mut self, code: u32, bits: u32) -> i16 { + let step = step_at(self.index); + let mag = code & ((1 << (bits - 1)) - 1); + let mut diff = step >> (bits - 1); + for k in 0..bits - 1 { + if mag & (1 << (bits - 2 - k)) != 0 { + diff += step >> k; + } + } + if code & (1 << (bits - 1)) != 0 { + diff = -diff; + } + self.predictor = clip16(self.predictor + diff); + self.index = (self.index + adjust(bits).get(mag as usize).copied().unwrap_or(0)).clamp(0, 88); + self.predictor as i16 + } + + fn encode(&mut self, sample: i16, bits: u32) -> u32 { + let step = step_at(self.index); + let mut diff = i32::from(sample) - self.predictor; + let mut code = 0u32; + if diff < 0 { + code = 1 << (bits - 1); + diff = -diff; + } + let mut s = step; + for k in 0..bits - 1 { + if diff >= s { + code |= 1 << (bits - 2 - k); + diff -= s; + } + s >>= 1; + } + self.apply(code, bits); + code + } +} + +/// Decode a stream. `channels` is 1 or 2; the code size comes from the stream's first two bits. +/// The result holds every sample up to the end of the data (a last block cut short decodes as +/// far as it goes). +pub fn decode(data: &[u8], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::Malformed("Flash ADPCM has one or two channels")); + } + let mut r = BitReader::new(data); + let bits = r.read_bits(2).map_err(|_| Error::Malformed("empty stream"))? + 2; + let mut out = Vec::new(); + let header_bits = channels * 22; + while r.bits_left() >= header_bits { + let mut states = Vec::with_capacity(channels); + for _ in 0..channels { + let sample = r.read_bits(16).map_err(|_| Error::Malformed("truncated block"))? as u16 as i16; + let index = r.read_bits(6).map_err(|_| Error::Malformed("truncated block"))? as i32; + if index > 88 { + return Err(Error::Malformed("step index above 88")); + } + out.push(sample); + states.push(State { predictor: i32::from(sample), index }); + } + 'block: for _ in 1..BLOCK_SAMPLES { + if r.bits_left() < channels * (bits as usize) { + break 'block; + } + for st in states.iter_mut() { + match r.read_bits(bits) { + Ok(code) => out.push(st.apply(code, bits)), + Err(_) => break 'block, + } + } + } + } + Ok(out) +} + +/// Encode interleaved samples with `bits` (2 to 5) bits per sample. Blocks hold 4096 samples per +/// channel; the stream ends at a byte boundary. +pub fn encode(samples: &[i16], channels: usize, bits: u32) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::InvalidInput("Flash ADPCM has one or two channels")); + } + if !(2..=5).contains(&bits) { + return Err(Error::InvalidInput("Flash ADPCM codes have 2 to 5 bits")); + } + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut w = BitWriter::new(); + w.write_bits(bits - 2, 2); + for block in samples.chunks(BLOCK_SAMPLES * channels) { + let mut states = Vec::with_capacity(channels); + for ch in 0..channels { + let col: Vec = block.iter().skip(ch).step_by(channels).copied().collect(); + let first = col.first().copied().unwrap_or(0); + // the index whose first codes follow the signal most closely + let mut best = (i64::MAX, 0); + for index in 0..=63 { + let mut st = State { predictor: i32::from(first), index }; + let mut err = 0i64; + for &s in col.iter().skip(1).take(16) { + st.encode(s, bits); + err += (i64::from(s) - i64::from(st.predictor)).pow(2); + } + if err < best.0 { + best = (err, index); + } + } + w.write_bits(u32::from(first as u16), 16); + w.write_bits(best.1 as u32, 6); + states.push(State { predictor: i32::from(first), index: best.1 }); + } + for frame in block.chunks(channels).skip(1) { + for (st, &s) in states.iter_mut().zip(frame) { + w.write_bits(st.encode(s, bits), bits); + } + } + } + w.align_zero(); + Ok(w.finish()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_are_checked() { + assert!(encode(&[0], 3, 4).is_err()); + assert!(encode(&[0], 1, 1).is_err()); + assert!(encode(&[0], 1, 6).is_err()); + assert!(decode(&[], 1).is_err()); + assert!(decode(&[0], 0).is_err()); + } +} diff --git a/crates/audio/src/adpcm/yamaha.rs b/crates/audio/src/adpcm/yamaha.rs new file mode 100644 index 0000000000..22ea0e77f4 --- /dev/null +++ b/crates/audio/src/adpcm/yamaha.rs @@ -0,0 +1,113 @@ +//! Yamaha ADPCM (the ADPCM-B of the YM2608 and the AICA): a raw stream of 4-bit codes, no header. +//! +//! Each channel starts at predictor 0 and step 127. A code is a sign bit and three magnitude bits; +//! the sample moves by `step * [1, 3, 5, 7, 9, 11, 13, 15][magnitude] / 8` (negative when the sign +//! is set) and the step is multiplied by `[230, 230, 230, 230, 307, 409, 512, 614][magnitude] / 256`, +//! kept within 127 and 24576. One channel: the low nibble of a byte is the first sample. Two +//! channels: the low nibble is the left channel and the high nibble the right one of the same +//! frame. + +use super::{Error, Result, clip16}; + +const SCALE: [i32; 8] = [230, 230, 230, 230, 307, 409, 512, 614]; + +#[derive(Clone, Copy)] +struct State { + predictor: i32, + step: i32, +} + +impl State { + fn new() -> State { + State { predictor: 0, step: 127 } + } + + fn apply(&mut self, nibble: u8) -> i16 { + let m = usize::from(nibble & 7); + let diff = self.step * (2 * m as i32 + 1) / 8; + self.predictor = clip16(self.predictor + if nibble & 8 != 0 { -diff } else { diff }); + self.step = ((self.step * SCALE.get(m).copied().unwrap_or(256)) >> 8).clamp(127, 24_576); + self.predictor as i16 + } + + fn encode(&mut self, sample: i16) -> u8 { + let err = i32::from(sample) - self.predictor; + let m = (err.abs() * 8 / self.step / 2).clamp(0, 7); + // the magnitude whose reconstruction (2m + 1) * step / 8 is nearest + let mut best = (i32::MAX, 0u8); + for cand in [m - 1, m, m + 1] { + let c = cand.clamp(0, 7); + let recon = self.step * (2 * c + 1) / 8; + let e = (err.abs() - recon).abs(); + if e < best.0 { + best = (e, c as u8); + } + } + let nibble = best.1 | if err < 0 { 8 } else { 0 }; + self.apply(nibble); + nibble + } +} + +/// Decode a stream of `channels` (1 or 2) interleaved channels. +pub fn decode(data: &[u8], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::Malformed("Yamaha ADPCM has one or two channels")); + } + let mut states = vec![State::new(); channels]; + let mut out = Vec::with_capacity(data.len() * 2); + let mut t = 0usize; + for byte in data { + for nibble in [byte & 0xF, byte >> 4] { + if let Some(st) = states.get_mut(t % channels) { + out.push(st.apply(nibble)); + } + t += 1; + } + } + Ok(out) +} + +/// Encode interleaved samples. With two channels the frame count must be whole bytes, which it +/// always is; with one channel an odd count is padded with a copy of the last sample. +pub fn encode(samples: &[i16], channels: usize) -> Result> { + if !(1..=2).contains(&channels) { + return Err(Error::InvalidInput("Yamaha ADPCM has one or two channels")); + } + if !samples.len().is_multiple_of(channels) { + return Err(Error::InvalidInput("the sample count is not a multiple of the channel count")); + } + let mut states = vec![State::new(); channels]; + let mut out = Vec::with_capacity(samples.len().div_ceil(2)); + let mut t = 0usize; + let mut padded = samples.to_vec(); + if padded.len() % 2 == 1 { + padded.push(padded.last().copied().unwrap_or(0)); + } + for pair in padded.chunks(2) { + let mut byte = 0u8; + for (half, &s) in pair.iter().enumerate() { + let code = match states.get_mut(t % channels) { + Some(st) => st.encode(s), + None => 0, + }; + byte |= code << (4 * half); + t += 1; + } + out.push(byte); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn channel_count_is_checked() { + assert!(decode(&[0], 0).is_err()); + assert!(decode(&[0], 3).is_err()); + assert!(encode(&[0], 3).is_err()); + assert!(encode(&[0, 0, 0], 2).is_err()); + } +} diff --git a/crates/audio/src/g726.rs b/crates/audio/src/g726.rs new file mode 100644 index 0000000000..6ac02359df --- /dev/null +++ b/crates/audio/src/g726.rs @@ -0,0 +1,996 @@ +//! ITU-T Recommendation G.726 ADPCM speech codec (16, 24, 32, 40 kbit/s). +//! +//! Clean-room implementation based on ITU-T Recommendation G.726 (12/1990) +//! "40, 32, 24, 16 kbit/s Adaptive Differential Pulse Code Modulation (ADPCM)". +//! +//! Provides encoding from 8 kHz 16-bit linear PCM to G.726 bitstreams, and decoding +//! from G.726 bitstreams to 8 kHz 16-bit linear PCM. +//! +//! Supports both standard big-endian bit packing (network order / RFC 3551) and +//! little-endian bit packing (RIFF WAV / AVID format tag 0x0045 / 0x0014). + +const MAX_CHANNELS: usize = 8; +const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; +const MAX_SAMPLES: usize = 64 * 1024 * 1024; + +/// Bit rate for G.726 ADPCM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BitRate { + /// 16 kbit/s (2 bits per sample). + Rate16k, + /// 24 kbit/s (3 bits per sample). + Rate24k, + /// 32 kbit/s (4 bits per sample). + Rate32k, + /// 40 kbit/s (5 bits per sample). + Rate40k, +} + +impl BitRate { + /// Number of bits per code (sample). + #[inline] + #[must_use] + pub const fn code_size(self) -> usize { + match self { + Self::Rate16k => 2, + Self::Rate24k => 3, + Self::Rate32k => 4, + Self::Rate40k => 5, + } + } + + /// Bit rate in bits per second. + #[inline] + #[must_use] + pub const fn bit_rate_bps(self) -> u32 { + match self { + Self::Rate16k => 16_000, + Self::Rate24k => 24_000, + Self::Rate32k => 32_000, + Self::Rate40k => 40_000, + } + } +} + +/// Bit packing order within bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BitPacking { + /// Big-endian packing: MSB to LSB (standard RFC 3551 / network order). + #[default] + BigEndian, + /// Little-endian packing: LSB to MSB (WAV / RIFF order). + LittleEndian, +} + +/// Errors returned by G.726 operations. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Channel count must be between 1 and 8. + #[error("unsupported channel count: {0} (must be 1..=8)")] + InvalidChannels(usize), + /// Input exceeds safe maximum memory bound. + #[error("input exceeds safe maximum processing limit")] + InputTooLarge, + /// Output buffer allocation failed. + #[error("memory allocation failed")] + AllocationFailed, +} + +// --------------------------------------------------------------------------- +// G.726 Tables +// --------------------------------------------------------------------------- + +// Table 11..14 (I -> DQS, DQLN) +static OUT_16: [(u8, u16); 4] = [(0, 116), (0, 365), (1, 365), (1, 116)]; + +static OUT_24: [(u8, u16); 8] = [(0, 2048), (0, 135), (0, 273), (0, 373), (1, 373), (1, 273), (1, 135), (1, 2048)]; + +static OUT_32: [(u8, u16); 16] = [ + (0, 2048), + (0, 4), + (0, 135), + (0, 213), + (0, 273), + (0, 323), + (0, 373), + (0, 425), + (1, 425), + (1, 373), + (1, 323), + (1, 273), + (1, 213), + (1, 135), + (1, 4), + (1, 2048), +]; + +static OUT_40: [(u8, u16); 32] = [ + (0, 2048), + (0, 4030), + (0, 28), + (0, 104), + (0, 169), + (0, 224), + (0, 274), + (0, 318), + (0, 358), + (0, 395), + (0, 429), + (0, 459), + (0, 488), + (0, 514), + (0, 539), + (0, 566), + (1, 566), + (1, 539), + (1, 514), + (1, 488), + (1, 459), + (1, 429), + (1, 395), + (1, 358), + (1, 318), + (1, 274), + (1, 224), + (1, 169), + (1, 104), + (1, 28), + (1, 4030), + (1, 2048), +]; + +// FUNCTW: scale factor multipliers WI +static WI_16: [u16; 2] = [4074, 439]; +static WI_24: [u16; 4] = [4092, 30, 137, 582]; +static WI_32: [u16; 8] = [4084, 18, 41, 64, 112, 198, 355, 1122]; +static WI_40: [u16; 16] = [14, 14, 24, 39, 40, 41, 58, 100, 141, 179, 219, 280, 358, 440, 529, 696]; + +#[inline] +fn get_wi(rate: BitRate, code: u8) -> u16 { + match rate { + BitRate::Rate16k => { + let im = if (code >> 1) == 0 { (code & 1) as usize } else { ((3 - code) & 1) as usize }; + WI_16[im] + } + BitRate::Rate24k => { + let im = if (code >> 2) == 0 { (code & 3) as usize } else { ((7 - code) & 3) as usize }; + WI_24[im] + } + BitRate::Rate32k => { + let im = if (code >> 3) == 0 { (code & 7) as usize } else { ((15 - code) & 7) as usize }; + WI_32[im] + } + BitRate::Rate40k => { + let im = if (code >> 4) == 0 { (code & 15) as usize } else { ((31 - code) & 15) as usize }; + WI_40[im] + } + } +} + +#[inline] +fn get_fi(rate: BitRate, code: u8) -> u8 { + match rate { + BitRate::Rate16k => { + let im = if (code >> 1) == 0 { code & 1 } else { (3 - code) & 1 }; + if im == 1 { 7 } else { 0 } + } + BitRate::Rate24k => { + let im = if (code >> 2) == 0 { code & 3 } else { (7 - code) & 3 }; + match im { + 0 => 0, + 1 => 1, + 2 => 2, + _ => 7, + } + } + BitRate::Rate32k => { + let im = if (code >> 3) == 0 { code & 7 } else { (15 - code) & 7 }; + if im <= 2 { + 0 + } else if im <= 5 { + 1 + } else if im == 6 { + 3 + } else { + 7 + } + } + BitRate::Rate40k => { + let im = if (code >> 4) == 0 { code & 15 } else { (31 - code) & 15 }; + if im <= 4 { + 0 + } else if im <= 9 { + 1 + } else { + match im { + 10 => 2, + 11 => 3, + 12 => 4, + 13 => 5, + _ => 6, + } + } + } + } +} + +// Quantizer decision intervals (lo, hi, positive_code, negative_code) +static THRESH_16: [(i32, i32, u8, u8); 1] = [(261, 2047, 1, 2)]; + +static THRESH_24: [(i32, i32, u8, u8); 3] = [(331, 2047, 3, 4), (218, 330, 2, 5), (8, 217, 1, 6)]; + +static THRESH_32: [(i32, i32, u8, u8); 8] = [ + (400, 2047, 7, 8), + (349, 399, 6, 9), + (300, 348, 5, 10), + (246, 299, 4, 11), + (178, 245, 3, 12), + (80, 177, 2, 13), + (0, 79, 1, 14), + (3972, 4095, 1, 14), +]; + +static THRESH_40: [(i32, i32, u8, u8); 16] = [ + (553, 2047, 15, 16), + (528, 552, 14, 17), + (502, 527, 13, 18), + (475, 501, 12, 19), + (445, 474, 11, 20), + (413, 444, 10, 21), + (378, 412, 9, 22), + (339, 377, 8, 23), + (298, 338, 7, 24), + (250, 297, 6, 25), + (198, 249, 5, 26), + (139, 197, 4, 27), + (68, 138, 3, 28), + (0, 67, 2, 29), + (4080, 4095, 2, 29), + (3974, 4079, 1, 30), +]; + +#[inline] +fn quantize_16(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_16 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + if ds == 0 { 0 } else { 3 } +} + +#[inline] +fn quantize_24(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_24 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 7 +} + +#[inline] +fn quantize_32(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_32 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 15 +} + +#[inline] +fn quantize_40(dln: i32, ds: u8) -> u8 { + for &(lo, hi, pos, neg) in &THRESH_40 { + if (lo..=hi).contains(&dln) { + return if ds == 0 { pos } else { neg }; + } + } + 31 +} + +// --------------------------------------------------------------------------- +// G.726 Core State +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct Core { + rate: BitRate, + is_40k: bool, + a: [u16; 2], + b: [u16; 6], + dms: i16, + dml: i16, + ap: i16, + yu: i16, + yl: i32, + sr: [u16; 2], + dq: [u16; 6], + pk: [u8; 2], + td: i16, +} + +impl Core { + fn new(rate: BitRate) -> Self { + let is_40k = matches!(rate, BitRate::Rate40k); + let mut core = + Self { rate, is_40k, a: [0; 2], b: [0; 6], dms: 0, dml: 0, ap: 0, yu: 544, yl: 34816, sr: [32, 32], dq: [32; 6], pk: [0; 2], td: 0 }; + core.reset(); + core + } + + fn reset(&mut self) { + self.a = [0; 2]; + self.b = [0; 6]; + self.dms = 0; + self.dml = 0; + self.ap = 0; + self.yu = 544; + self.yl = 34816; + self.sr = [32, 32]; + self.dq = [32; 6]; + self.pk = [0; 2]; + self.td = 0; + } + + #[inline] + fn fmult(an: u16, srn: u16) -> u16 { + let an_s = (an >> 15) & 1; + let an_mag = if an_s == 0 { (an >> 2) & 0x1FFF } else { (16384_u32.wrapping_sub((an >> 2) as u32) & 0x1FFF) as u16 }; + let an_exp = if an_mag > 0 { (16 - an_mag.leading_zeros()).min(13) as u16 } else { 0 }; + let an_mant = if an_mag == 0 { 1 << 5 } else { (((an_mag as u32) << 6) >> an_exp) as u16 & 0x3F }; + + let srn_s = (srn >> 10) & 1; + let srn_exp = (srn >> 6) & 15; + let srn_mant = srn & 63; + + let wan_s = srn_s ^ an_s; + let wan_exp = srn_exp + an_exp; + let wan_mant = (((srn_mant as u32 * an_mant as u32) + 48) >> 4) as u16; + + let wan_mag = + if wan_exp <= 26 { ((wan_mant as u32) << 7) >> (26 - wan_exp) } else { (((wan_mant as u32) << 7) << (wan_exp - 26)) & 0x7FFF } as u16; + + if wan_s == 0 { wan_mag } else { (65536_u32.wrapping_sub(wan_mag as u32) & 0xFFFF) as u16 } + } + + #[inline] + fn quantize(&self, dln: i32, ds: u8) -> u8 { + match self.rate { + BitRate::Rate16k => quantize_16(dln, ds), + BitRate::Rate24k => quantize_24(dln, ds), + BitRate::Rate32k => quantize_32(dln, ds), + BitRate::Rate40k => quantize_40(dln, ds), + } + } + + #[inline] + fn table_lookup(&self, code: u8) -> (u8, u16) { + match self.rate { + BitRate::Rate16k => OUT_16[(code & 3) as usize], + BitRate::Rate24k => OUT_24[(code & 7) as usize], + BitRate::Rate32k => OUT_32[(code & 15) as usize], + BitRate::Rate40k => OUT_40[(code & 31) as usize], + } + } + + #[inline] + fn compute_accum(&self) -> (i16, i16) { + let wa0 = Self::fmult(self.a[0], self.sr[0]); + let wa1 = Self::fmult(self.a[1], self.sr[1]); + let mut sezi: u32 = 0; + for i in 0..6 { + sezi = (sezi + Self::fmult(self.b[i], self.dq[i]) as u32) & 0xFFFF; + } + let sei = (sezi + wa1 as u32 + wa0 as u32) & 0xFFFF; + let sez = (sezi as i16) >> 1; + let se = (sei as i16) >> 1; + (sez, se) + } + + #[inline] + fn compute_mix(&self) -> i32 { + let al = if self.ap >= 256 { 64 } else { self.ap >> 2 } as i32; + let dif = (self.yu as i32 + 16384 - (self.yl >> 6)) & 16383; + let difs = (dif >> 13) & 1; + let difm = if difs == 0 { dif } else { (16384 - dif) & 8191 }; + let prodm = (difm * al) >> 6; + let prod = if difs == 0 { prodm } else { (16384 - prodm) & 8191 }; + ((self.yl >> 6) + prod) & 8191 + } + + #[inline] + fn quantize_sample(&self, sample: i16, se: i16, y: i32) -> u8 { + let sl = (sample >> 2) as i32; + let sl_ext = if sl >= 0 { sl } else { 65536 + sl }; + let se_ext = if se >= 0 { se as i32 } else { 65536 + se as i32 }; + let d = ((sl_ext + 65536 - se_ext) & 0xFFFF) as u16; + + let ds = ((d >> 15) & 1) as u8; + let dqm = if ds == 0 { d } else { (65536_u32.wrapping_sub(d as u32) & 0x7FFF) as u16 }; + let exp = if dqm > 1 { (15 - dqm.leading_zeros()).min(14) } else { 0 }; + let mant = (((dqm as u32) << 7) >> exp) & 127; + let dl = ((exp << 7) + mant) as u16; + let dln = (dl as i32 + 4096 - (y >> 2)) & 4095; + self.quantize(dln, ds) + } + + #[inline] + fn step(&mut self, sample: i16, is_encoder: bool, code_in: u8) -> (u8, i16) { + let (sez, se) = self.compute_accum(); + let y = self.compute_mix(); + + let code = if is_encoder { self.quantize_sample(sample, se, y) } else { code_in }; + + // 4. RECONST & ADDA & ANTILOG + let (dqs, dqln) = self.table_lookup(code); + let dql = (dqln as i32 + (y >> 2)) & 4095; + let dex = (dql >> 7) & 15; + let dmn = dql & 127; + let dqt = 128 + dmn; + let dqmag = if (dql >> 11) == 0 { ((dqt << 7) >> (14 - dex)) as u16 } else { 0 }; + let dq = if self.is_40k { ((dqs as u16) << 15) | (dqmag & 0x7FFF) } else { ((dqs as u16) << 14) | (dqmag & 0x3FFF) }; + + // 5. ADDB & ADDC + let dqi = if dqs == 0 { + dq as u32 + } else if self.is_40k { + 65536_u32.wrapping_sub((dq & 0x7FFF) as u32) & 0xFFFF + } else { + 65536_u32.wrapping_sub((dq & 0x3FFF) as u32) & 0xFFFF + }; + let sei_ext = if se >= 0 { se as u32 } else { (65536 + se as i32) as u32 }; + let sr = ((dqi + sei_ext) & 0xFFFF) as u16; + + let sezi_ext = if sez >= 0 { sez as u32 } else { (65536 + sez as i32) as u32 }; + let dqsez = ((dqi + sezi_ext) & 0xFFFF) as u16; + let pk0 = ((dqsez >> 15) & 1) as u8; + let sigpk = if dqsez == 0 { 1 } else { 0 }; + + // 6. FLOATA & FLOATB + let dq_mag = if self.is_40k { dq & 0x7FFF } else { dq & 0x3FFF }; + let (dq_exp, dq_mant) = if dq_mag == 0 { + (0, 32) + } else { + let max_exp = if self.is_40k { 15 } else { 14 }; + let exp = (16 - dq_mag.leading_zeros()).min(max_exp); + let mant = (((dq_mag as u32) << 6) >> exp) as u16; + (exp as u16, mant) + }; + let dq0 = ((dqs as u16) << 10) | (dq_exp << 6) | (dq_mant & 63); + + let sr_s = ((sr >> 15) & 1) as u8; + let sr_mag = if sr_s == 0 { sr } else { (65536_u32.wrapping_sub(sr as u32) & 0x7FFF) as u16 }; + let (sr_exp, sr_mant) = if sr_mag == 0 { + (0, 32) + } else { + let exp = (16 - sr_mag.leading_zeros()).min(15); + let mant = (((sr_mag as u32) << 6) >> exp) as u16; + (exp as u16, mant) + }; + let sr0 = ((sr_s as u16) << 10) | (sr_exp << 6) | (sr_mant & 63); + + self.update_adaptation_and_predictors(code, y, pk0, sigpk, dqs, dq_mag); + + self.sr = [sr0, self.sr[0]]; + self.dq = [dq0, self.dq[0], self.dq[1], self.dq[2], self.dq[3], self.dq[4]]; + self.pk = [pk0, self.pk[0]]; + + let sr_signed = if sr < 32768 { sr as i32 } else { sr as i32 - 65536 }; + let out_pcm = (sr_signed << 2).clamp(-32768, 32767) as i16; + (code, out_pcm) + } + + #[inline] + fn adapt_scale(&mut self, code: u8, y: i32) { + let wi = get_wi(self.rate, code); + let dif = (((wi as i32) << 5) + 131072 - y) & 131071; + let difs = (dif >> 16) & 1; + let difsx = if difs == 0 { dif >> 5 } else { (dif >> 5) + 4096 }; + let yut = (y + difsx) & 8191; + let yup = yut.clamp(544, 5120); + + let dif = (yup + ((1048576 - self.yl) >> 6)) & 16383; + let difs = (dif >> 13) & 1; + let difsx = if difs == 0 { dif } else { dif + 507904 }; + self.yu = yup as i16; + self.yl = (self.yl + difsx) & 524287; + } + + #[inline] + fn adapt_speed(&mut self, code: u8, y: i32, dq_mag: u16) -> (i16, i16, u8) { + let fi = get_fi(self.rate, code); + let dif = (((fi as i32) << 9) + 8192 - self.dms as i32) & 8191; + let difs = (dif >> 12) & 1; + let difsx = if difs == 0 { dif >> 5 } else { (dif >> 5) + 3840 }; + let dmsp = ((difsx + self.dms as i32) & 4095) as i16; + + let dif = (((fi as i32) << 11) + 32768 - self.dml as i32) & 32767; + let difs = (dif >> 14) & 1; + let difsx = if difs == 0 { dif >> 7 } else { (dif >> 7) + 16128 }; + let dmlp = ((difsx + self.dml as i32) & 16383) as i16; + + let dif = (((dmsp as i32) << 2) + 32768 - dmlp as i32) & 32767; + let difs = (dif >> 14) & 1; + let difm = if difs == 0 { dif } else { (32768 - dif) & 16383 }; + let dthr = (dmlp as i32) >> 3; + + let tdp = if (32768..53760).contains(&self.a[1]) { 1 } else { 0 }; + let ax = if y >= 1536 && tdp == 0 && difm < dthr { 0 } else { 1 }; + + let dif = ((ax << 9) + 2048 - self.ap as i32) & 2047; + let difs = (dif >> 10) & 1; + let difsx = if difs == 0 { dif >> 4 } else { (dif >> 4) + 1920 }; + let app = ((difsx + self.ap as i32) & 1023) as i16; + + let ylint = (self.yl >> 15) as u32; + let ylfrac = ((self.yl >> 10) & 31) as u32; + let thr1 = (32 + ylfrac) << ylint; + let thr2 = if self.is_40k && ylint > 9 { + 31 << 10 + } else if !self.is_40k && ylint > 8 { + 31 << 9 + } else { + thr1 + }; + let dqthr = (thr2 + (thr2 >> 1)) >> 1; + let tr = if (dq_mag as u32) > dqthr && self.td == 1 { 1 } else { 0 }; + let apr = if tr == 1 { 256 } else { app }; + + self.dms = dmsp; + self.dml = dmlp; + self.ap = apr; + self.td = if tr == 1 { 0 } else { tdp }; + + (apr, tdp, tr) + } + + #[inline] + fn update_predictors(&mut self, pk0: u8, sigpk: u8, dqs: u8, dq_mag: u16, tr: u8) { + let pks = pk0 ^ self.pk[0]; + let uga1 = if sigpk == 1 { + 0 + } else if pks == 0 { + 192 + } else { + 65344 + }; + let a1s = (self.a[0] >> 15) & 1; + let ula1 = if a1s == 0 { + (65536_u32.wrapping_sub((self.a[0] >> 8) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.a[0] >> 8) + 65280) as u32) & 0xFFFF) as u16 + }; + let ua1 = (uga1 as u32 + ula1 as u32) & 0xFFFF; + let a1t = ((self.a[0] as u32 + ua1) & 0xFFFF) as u16; + + let pks1 = pk0 ^ self.pk[0]; + let pks2 = pk0 ^ self.pk[1]; + let uga2a = if pks2 == 0 { 16384_u32 } else { 114688_u32 }; + let a1_u = self.a[0]; + let fa1 = if a1s == 0 { + if a1_u <= 8191 { (a1_u as u32) << 2 } else { 8191 << 2 } + } else if a1_u >= 57345 { + ((a1_u as u32) << 2) & 131071 + } else { + 24577 << 2 + }; + let fa = if pks1 == 1 { fa1 } else { (131072_u32.wrapping_sub(fa1)) & 131071 }; + let uga2b = (uga2a + fa) & 131071; + let uga2s = (uga2b >> 16) & 1; + let uga2 = if sigpk == 1 { + 0 + } else if uga2s == 0 { + uga2b >> 7 + } else { + (uga2b >> 7) + 64512 + } as u16; + let a2s = (self.a[1] >> 15) & 1; + let ula2 = if a2s == 0 { + (65536_u32.wrapping_sub((self.a[1] >> 7) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.a[1] >> 7) + 65024) as u32) & 0xFFFF) as u16 + }; + let ua2 = (uga2 as u32 + ula2 as u32) & 0xFFFF; + let a2t = ((self.a[1] as u32 + ua2) & 0xFFFF) as u16; + + let a2p = if (32768..=53248).contains(&a2t) { + 53248 + } else if (12288..=32767).contains(&a2t) { + 12288 + } else { + a2t + }; + + let ome = 15360_u32; + let a1ul = ((ome + 65536 - a2p as u32) & 0xFFFF) as u16; + let a1ll = ((a2p as u32 + 65536 - ome) & 0xFFFF) as u16; + let a1p = if a1t >= 32768 && a1t <= a1ll { + a1ll + } else if a1t >= a1ul && a1t <= 32767 { + a1ul + } else { + a1t + }; + + let a1r = if tr == 1 { 0 } else { a1p }; + let a2r = if tr == 1 { 0 } else { a2p }; + + let mut new_b = [0u16; 6]; + for (i, slot) in new_b.iter_mut().enumerate() { + let un = (dqs ^ ((self.dq[i] >> 10) as u8)) & 1; + let ugbn = if dq_mag == 0 { + 0 + } else if un == 0 { + 128 + } else { + 65408 + }; + let bns = (self.b[i] >> 15) & 1; + let ulbn = if self.is_40k { + if bns == 0 { + (65536_u32.wrapping_sub((self.b[i] >> 9) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.b[i] >> 9) + 65408) as u32) & 0xFFFF) as u16 + } + } else if bns == 0 { + (65536_u32.wrapping_sub((self.b[i] >> 8) as u32) & 0xFFFF) as u16 + } else { + (65536_u32.wrapping_sub(((self.b[i] >> 8) + 65280) as u32) & 0xFFFF) as u16 + }; + let ubn = (ugbn as u32 + ulbn as u32) & 0xFFFF; + let bnp = ((self.b[i] as u32 + ubn) & 0xFFFF) as u16; + *slot = if tr == 1 { 0 } else { bnp }; + } + + self.a[0] = a1r; + self.a[1] = a2r; + self.b = new_b; + } + + #[inline] + fn update_adaptation_and_predictors(&mut self, code: u8, y: i32, pk0: u8, sigpk: u8, dqs: u8, dq_mag: u16) { + self.adapt_scale(code, y); + let (_, _, tr) = self.adapt_speed(code, y, dq_mag); + self.update_predictors(pk0, sigpk, dqs, dq_mag, tr); + } +} + +// --------------------------------------------------------------------------- +// Decoder & Encoder structs +// --------------------------------------------------------------------------- + +/// G.726 ADPCM decoder. +#[derive(Debug, Clone)] +pub struct Decoder { + core: Core, + packing: BitPacking, + bit_buf: u32, + num_bits: usize, +} + +impl Decoder { + /// Create a new G.726 decoder at the specified bit rate and bit packing. + #[must_use] + pub fn new(rate: BitRate, packing: BitPacking) -> Self { + Self { core: Core::new(rate), packing, bit_buf: 0, num_bits: 0 } + } + + /// Reset decoder internal predictor state. + pub fn reset(&mut self) { + self.core.reset(); + self.bit_buf = 0; + self.num_bits = 0; + } + + /// Decode a single quantized ADPCM code into an 8 kHz 16-bit linear PCM sample. + /// Bits above the configured code width are ignored, as in packed-stream decoding. + #[inline] + pub fn decode_sample(&mut self, code: u8) -> i16 { + // Adaptation must see the same bounded codeword as the reconstruction table; + // otherwise unused high bits can underflow its unsigned inverse-code arithmetic. + let code = code & ((1u8 << self.core.rate.code_size()) - 1); + self.core.step(0, false, code).1 + } + + /// Decode G.726 bitstream bytes into 8 kHz 16-bit linear PCM samples, appending to `dst`. + pub fn decode(&mut self, src: &[u8], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let cs = self.core.rate.code_size(); + let est_samples = (src.len() * 8) / cs; + dst.try_reserve(est_samples).map_err(|_| Error::AllocationFailed)?; + + match self.packing { + BitPacking::BigEndian => { + for &b in src { + self.bit_buf = ((self.bit_buf & ((1 << self.num_bits) - 1)) << 8) | (b as u32); + self.num_bits += 8; + while self.num_bits >= cs { + let code = ((self.bit_buf >> (self.num_bits - cs)) & ((1 << cs) - 1)) as u8; + self.num_bits -= cs; + let s = self.decode_sample(code); + dst.push(s); + } + self.bit_buf &= (1 << self.num_bits) - 1; + } + } + BitPacking::LittleEndian => { + for &b in src { + self.bit_buf |= (b as u32) << self.num_bits; + self.num_bits += 8; + while self.num_bits >= cs { + let code = (self.bit_buf & ((1 << cs) - 1)) as u8; + self.bit_buf >>= cs; + self.num_bits -= cs; + let s = self.decode_sample(code); + dst.push(s); + } + } + } + } + Ok(()) + } +} + +/// G.726 ADPCM encoder. +#[derive(Debug, Clone)] +pub struct Encoder { + core: Core, + packing: BitPacking, + bit_buf: u32, + num_bits: usize, +} + +impl Encoder { + /// Create a new G.726 encoder at the specified bit rate and bit packing. + #[must_use] + pub fn new(rate: BitRate, packing: BitPacking) -> Self { + Self { core: Core::new(rate), packing, bit_buf: 0, num_bits: 0 } + } + + /// Reset encoder internal predictor state. + pub fn reset(&mut self) { + self.core.reset(); + self.bit_buf = 0; + self.num_bits = 0; + } + + /// Encode a single 8 kHz 16-bit linear PCM sample into an ADPCM code word. + #[inline] + pub fn encode_sample(&mut self, sample: i16) -> u8 { + self.core.step(sample, true, 0).0 + } + + /// Encode 8 kHz 16-bit linear PCM samples into G.726 bitstream bytes, appending to `dst`. + pub fn encode(&mut self, src: &[i16], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let cs = self.core.rate.code_size(); + let est_bytes = (src.len() * cs).div_ceil(8); + dst.try_reserve(est_bytes).map_err(|_| Error::AllocationFailed)?; + + match self.packing { + BitPacking::BigEndian => { + for &s in src { + let code = self.encode_sample(s); + self.bit_buf = ((self.bit_buf & ((1 << self.num_bits) - 1)) << cs) | ((code as u32) & ((1 << cs) - 1)); + self.num_bits += cs; + while self.num_bits >= 8 { + dst.push(((self.bit_buf >> (self.num_bits - 8)) & 0xFF) as u8); + self.num_bits -= 8; + } + self.bit_buf &= (1 << self.num_bits) - 1; + } + } + BitPacking::LittleEndian => { + for &s in src { + let code = self.encode_sample(s); + self.bit_buf |= (code as u32) << self.num_bits; + self.num_bits += cs; + while self.num_bits >= 8 { + dst.push((self.bit_buf & 0xFF) as u8); + self.bit_buf >>= 8; + self.num_bits -= 8; + } + } + } + } + Ok(()) + } + + /// Flush any remaining buffered bits into `dst`, padding with zeroes. + pub fn flush(&mut self, dst: &mut Vec) -> Result<(), Error> { + if self.num_bits > 0 { + dst.try_reserve(1).map_err(|_| Error::AllocationFailed)?; + match self.packing { + BitPacking::BigEndian => { + let b = ((self.bit_buf << (8 - self.num_bits)) & 0xFF) as u8; + dst.push(b); + } + BitPacking::LittleEndian => { + let b = (self.bit_buf & 0xFF) as u8; + dst.push(b); + } + } + self.bit_buf = 0; + self.num_bits = 0; + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Public Top-Level Functions +// --------------------------------------------------------------------------- + +/// Decode a mono G.726 bitstream into 8 kHz 16-bit linear PCM samples. +pub fn decode(bytes: &[u8], rate: BitRate, packing: BitPacking) -> Result, Error> { + let mut decoder = Decoder::new(rate, packing); + let mut out = Vec::new(); + decoder.decode(bytes, &mut out)?; + Ok(out) +} + +/// Encode mono 8 kHz 16-bit linear PCM samples into a G.726 bitstream. +pub fn encode(samples: &[i16], rate: BitRate, packing: BitPacking) -> Result, Error> { + let mut encoder = Encoder::new(rate, packing); + let mut out = Vec::new(); + encoder.encode(samples, &mut out)?; + encoder.flush(&mut out)?; + Ok(out) +} + +/// Decode an interleaved multi-channel G.726 stream into interleaved 8 kHz 16-bit PCM samples. +pub fn decode_interleaved(bytes: &[u8], channels: usize, rate: BitRate, packing: BitPacking) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return decode(bytes, rate, packing); + } + if bytes.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + + let mut decoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + decoders.push(Decoder::new(rate, packing)); + } + + let cs = rate.code_size(); + let est_samples = (bytes.len() * 8) / cs; + let mut out = Vec::new(); + out.try_reserve(est_samples).map_err(|_| Error::AllocationFailed)?; + + let mut ch_outs: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + ch_outs.push(Vec::new()); + } + + for (i, &b) in bytes.iter().enumerate() { + let ch = i % channels; + decoders[ch].decode(&[b], &mut ch_outs[ch])?; + } + + let min_len = ch_outs.iter().map(Vec::len).min().unwrap_or(0); + for i in 0..min_len { + for ch_out in ch_outs.iter().take(channels) { + out.push(ch_out[i]); + } + } + + Ok(out) +} + +/// Encode interleaved 8 kHz 16-bit PCM samples into an interleaved multi-channel G.726 stream. +pub fn encode_interleaved(samples: &[i16], channels: usize, rate: BitRate, packing: BitPacking) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return encode(samples, rate, packing); + } + if samples.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + + let mut encoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + encoders.push(Encoder::new(rate, packing)); + } + + let cs = rate.code_size(); + let est_bytes = (samples.len() * cs).div_ceil(8); + let mut out = Vec::new(); + out.try_reserve(est_bytes).map_err(|_| Error::AllocationFailed)?; + + let mut ch_samples: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + ch_samples.push(Vec::new()); + } + + for (i, &s) in samples.iter().enumerate() { + let ch = i % channels; + ch_samples[ch].push(s); + } + + let mut ch_bytes: Vec> = Vec::with_capacity(channels); + for ch in 0..channels { + let mut b = Vec::new(); + encoders[ch].encode(&ch_samples[ch], &mut b)?; + encoders[ch].flush(&mut b)?; + ch_bytes.push(b); + } + + let min_bytes = ch_bytes.iter().map(Vec::len).min().unwrap_or(0); + for i in 0..min_bytes { + for ch_b in ch_bytes.iter().take(channels) { + out.push(ch_b[i]); + } + } + + Ok(out) +} + +// --------------------------------------------------------------------------- +// Unit tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sample_api_ignores_unused_codeword_bits() { + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + let mask = (1u8 << rate.code_size()) - 1; + let mut actual = Decoder::new(rate, BitPacking::BigEndian); + let mut expected = Decoder::new(rate, BitPacking::BigEndian); + for code in 0..=u8::MAX { + assert_eq!(actual.decode_sample(code), expected.decode_sample(code & mask)); + } + // High bits must not leave a different predictor state for later valid codes. + for code in 0..=mask { + assert_eq!(actual.decode_sample(code), expected.decode_sample(code)); + } + } + } + + #[test] + fn reject_invalid_channels() { + assert!(decode_interleaved(&[], 0, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(decode_interleaved(&[], 9, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(encode_interleaved(&[], 0, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + assert!(encode_interleaved(&[], 9, BitRate::Rate32k, BitPacking::BigEndian).is_err()); + } + + #[test] + fn roundtrip_silence_all_rates() { + let pcm = vec![0i16; 64]; + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let encoded = encode(&pcm, rate, packing).expect("encode silence"); + let decoded = decode(&encoded, rate, packing).expect("decode silence"); + assert_eq!(decoded.len(), pcm.len()); + for &s in &decoded { + assert!(s.abs() <= 16, "silence sample too large: {s}"); + } + } + } + } + + #[test] + fn hostile_input_does_not_panic() { + let mut decoder = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut out = Vec::new(); + let hostile = vec![0xFF; 1024]; + let _ = decoder.decode(&hostile, &mut out); + + let mut decoder = Decoder::new(BitRate::Rate16k, BitPacking::LittleEndian); + let mut out = Vec::new(); + let _ = decoder.decode(&[0x00, 0xAA, 0x55, 0x12, 0x34], &mut out); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index a2704c3e7a..5ab2b8089e 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -13,6 +13,7 @@ //! demuxers and [`TrackDecoder`]; everything else (FLAC, Vorbis, CAF, ADPCM, A-law, µ-law) through //! `symphonia`, which is to be replaced by native decoders. Feature `decode-native` is the //! same without symphonia. +//! - [`vorbis::decoder`] (feature `vorbis-decode`): the pure-Rust Vorbis I decoder, packets and Ogg files. //! - [`encode_ogg_vorbis`] and [`vorbis::encoder`] (feature `vorbis-encode`): Ogg Vorbis files //! and Vorbis packets from a pure-Rust encoder, 1 to 8 channels, quality -1 to 10, with tags. //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar @@ -30,8 +31,8 @@ //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; -//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), -//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), +//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), //! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: //! Sierra VMD sound). //! @@ -41,6 +42,8 @@ pub mod aac; #[cfg(any(feature = "ac3-decode", feature = "ac3-encode", feature = "eac3-encode"))] pub mod ac3; +#[cfg(feature = "adpcm")] +pub mod adpcm; #[cfg(any(feature = "alac-decode", feature = "alac-encode"))] pub mod alac; mod buffer; @@ -48,6 +51,8 @@ mod buffer; pub mod dsd; #[cfg(feature = "g722")] pub mod g722; +#[cfg(feature = "g726")] +pub mod g726; #[cfg(any(feature = "gsm-decode", feature = "gsm-encode"))] pub mod gsm; mod layout; @@ -71,7 +76,7 @@ pub mod sbc; mod track; #[cfg(feature = "vmd-decode")] pub mod vmd; -#[cfg(feature = "vorbis-encode")] +#[cfg(any(feature = "vorbis-decode", feature = "vorbis-encode"))] pub mod vorbis; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; diff --git a/crates/audio/src/vorbis/decoder/bits.rs b/crates/audio/src/vorbis/decoder/bits.rs new file mode 100644 index 0000000000..6735d3d3d2 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/bits.rs @@ -0,0 +1,96 @@ +//! The Vorbis bit reader (Vorbis I §2): bits are taken least significant first from each byte. + +/// Reading past the end of the packet ("end-of-packet", §2.1.8). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Eop; + +pub(super) struct BitReader<'a> { + data: &'a [u8], + /// The position of the next bit. + pos: usize, +} + +impl<'a> BitReader<'a> { + pub(super) fn new(data: &'a [u8]) -> Self { + Self { data, pos: 0 } + } + + /// The bits not yet read. + pub(super) fn remaining(&self) -> usize { + (self.data.len() * 8).saturating_sub(self.pos) + } + + /// Read `n` (at most 32) bits as an unsigned integer. A read that does not fit takes nothing. + pub(super) fn read(&mut self, n: u32) -> Result { + if n == 0 { + return Ok(0); + } + if (n as usize) > self.remaining() { + self.pos = self.data.len() * 8; + return Err(Eop); + } + let mut value = 0u64; + let mut got = 0u32; + while got < n { + let byte = u64::from(self.data[self.pos / 8]); + let shift = (self.pos % 8) as u32; + let take = (8 - shift).min(n - got); + value |= ((byte >> shift) & ((1 << take) - 1)) << got; + got += take; + self.pos += take as usize; + } + Ok(value as u32) + } + + pub(super) fn bit(&mut self) -> Result { + Ok(self.read(1)? == 1) + } +} + +/// `ilog(x)` (§9.2.1): the position of the highest set bit, 0 for values below 1. +pub(super) fn ilog(x: i64) -> u32 { + if x <= 0 { 0 } else { 64 - (x as u64).leading_zeros() } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_least_significant_bit_first() { + // Fields come out of each byte from its least significant bit. + let mut r = BitReader::new(&[0xFC, 0x08]); + assert_eq!(r.read(4), Ok(0xC)); + assert_eq!(r.read(4), Ok(0xF)); + assert_eq!(r.read(1), Ok(0)); + assert_eq!(r.read(3), Ok(4)); + assert_eq!(r.read(4), Ok(0)); + assert_eq!(r.read(1), Err(Eop)); + } + + #[test] + fn wide_reads_span_bytes_and_zero_bits_are_free() { + let mut r = BitReader::new(&[0x01, 0x02, 0x03, 0x04, 0x05]); + assert_eq!(r.read(0), Ok(0)); + assert_eq!(r.read(32), Ok(0x0403_0201)); + assert_eq!(r.read(8), Ok(5)); + assert_eq!(r.read(0), Ok(0)); + assert_eq!(r.read(1), Err(Eop)); + assert_eq!(r.remaining(), 0); + } + + #[test] + fn a_failed_read_consumes_the_rest() { + let mut r = BitReader::new(&[0xFF]); + assert_eq!(r.read(3), Ok(7)); + assert_eq!(r.read(6), Err(Eop)); + assert_eq!(r.read(1), Err(Eop)); + } + + #[test] + fn ilog_matches_the_specification_examples() { + for (x, want) in [(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (7, 3), (-5, 0), (255, 8), (256, 9)] { + assert_eq!(ilog(x), want, "ilog({x})"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/codebook.rs b/crates/audio/src/vorbis/decoder/codebook.rs new file mode 100644 index 0000000000..9d083c9e47 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/codebook.rs @@ -0,0 +1,409 @@ +//! Codebooks (Vorbis I §3): a Huffman code over entry numbers and an optional table of vectors. + +use super::Error; +use super::bits::{BitReader, Eop, ilog}; + +const NONE: u32 = u32::MAX; +const LEAF: u32 = 1 << 31; +/// Entries a codebook may declare. +const MAX_ENTRIES: u32 = 1 << 20; +/// Nodes of one codeword tree. +const MAX_NODES: usize = 1 << 22; + +#[derive(Clone, Copy)] +struct Node { + child: [u32; 2], + full: bool, +} + +pub(super) struct Codebook { + pub(super) dimensions: usize, + pub(super) entries: usize, + tree: Vec, + /// The only used entry of a single-entry book. + single: Option, + /// `entries * dimensions` values when the book has a lookup table. + vectors: Vec, +} + +/// `float32_unpack` (§9.2.2). +fn float32_unpack(x: u32) -> f64 { + let mantissa = f64::from(x & 0x001F_FFFF); + let exponent = ((x & 0x7FE0_0000) >> 21) as i32; + let m = if x & 0x8000_0000 != 0 { -mantissa } else { mantissa }; + m * 2f64.powi(exponent - 788) +} + +/// `lookup1_values` (§9.2.3): the greatest `v` with `v^dimensions <= entries`. +fn lookup1_values(entries: u32, dimensions: u32) -> u32 { + let mut v = 1u32; + loop { + let next = u128::from(v) + 1; + let mut p = 1u128; + for _ in 0..dimensions { + p *= next; + if p > u128::from(entries) { + return v; + } + } + v += 1; + } +} + +fn insert(tree: &mut Vec, at: usize, depth: u32, len: u32, entry: u32) -> bool { + for b in 0..2 { + let child = tree[at].child[b]; + if depth + 1 == len { + if child == NONE { + tree[at].child[b] = LEAF | entry; + refresh(tree, at); + return true; + } + continue; + } + if child == NONE { + if tree.len() >= MAX_NODES { + return false; + } + tree.push(Node { child: [NONE; 2], full: false }); + let new = tree.len() - 1; + tree[at].child[b] = new as u32; + if insert(tree, new, depth + 1, len, entry) { + refresh(tree, at); + return true; + } + return false; + } + if child & LEAF != 0 || tree[child as usize].full { + continue; + } + if insert(tree, child as usize, depth + 1, len, entry) { + refresh(tree, at); + return true; + } + } + false +} + +fn refresh(tree: &mut [Node], at: usize) { + let done = |c: u32, t: &[Node]| c != NONE && (c & LEAF != 0 || t[c as usize].full); + let full = done(tree[at].child[0], tree) && done(tree[at].child[1], tree); + tree[at].full = full; +} + +impl Codebook { + /// Read one codebook from a setup header. `budget` is the bytes the setup's codebooks may + /// still take in all. + pub(super) fn read(r: &mut BitReader<'_>, budget: &mut usize) -> Result { + let bad = |m: &'static str| Error::Setup(m); + let eop = |_: Eop| Error::Setup("setup header ends inside a codebook"); + if r.read(24).map_err(eop)? != 0x0056_4342 { + return Err(bad("codebook sync pattern missing")); + } + let dimensions = r.read(16).map_err(eop)?; + let entries = r.read(24).map_err(eop)?; + if dimensions == 0 || entries == 0 || entries > MAX_ENTRIES { + return Err(bad("codebook with no dimensions, no entries or too many")); + } + let mut lengths: Vec = Vec::with_capacity(entries as usize); + if r.bit().map_err(eop)? { + // Ordered: the number of codewords of each length. + let mut current = 0u32; + let mut len = r.read(5).map_err(eop)? + 1; + while current < entries { + let number = r.read(ilog(i64::from(entries - current))).map_err(eop)?; + if number > entries - current || len > 32 { + return Err(bad("ordered codebook lengths overrun the entries")); + } + lengths.extend(std::iter::repeat_n(len as u8, number as usize)); + current += number; + len += 1; + } + } else { + let sparse = r.bit().map_err(eop)?; + for _ in 0..entries { + if sparse && !r.bit().map_err(eop)? { + lengths.push(0); + } else { + lengths.push((r.read(5).map_err(eop)? + 1) as u8); + } + } + } + + // The codeword tree. + let used = lengths.iter().filter(|&&l| l != 0).count(); + let mut tree = vec![Node { child: [NONE; 2], full: false }]; + let mut single = None; + if used == 1 { + let entry = lengths.iter().position(|&l| l != 0).unwrap_or(0); + if lengths[entry] != 1 { + return Err(bad("a codebook with one used entry must give it length 1")); + } + single = Some(entry as u32); + } else if used > 1 { + for (entry, &len) in lengths.iter().enumerate() { + if len != 0 && !insert(&mut tree, 0, 0, u32::from(len), entry as u32) { + return Err(bad("overspecified codebook")); + } + } + if !tree[0].full { + return Err(bad("underspecified codebook")); + } + } + let tree_bytes = tree.len() * std::mem::size_of::(); + if tree_bytes > *budget { + return Err(Error::Limit("the codebooks are too large")); + } + *budget -= tree_bytes; + + // The lookup table. + let lookup_type = r.read(4).map_err(eop)?; + let mut vectors = Vec::new(); + if lookup_type > 2 { + return Err(bad("reserved codebook lookup type")); + } + if lookup_type != 0 { + let minimum = float32_unpack(r.read(32).map_err(eop)?); + let delta = float32_unpack(r.read(32).map_err(eop)?); + let value_bits = r.read(4).map_err(eop)? + 1; + let sequence = r.bit().map_err(eop)?; + // Check before multiplying or reading multiplicands: the product can overflow + // usize on 32-bit targets, and a type-2 table otherwise allocates before admission. + let total = (entries as usize) + .checked_mul(dimensions as usize) + .filter(|&n| n <= *budget / std::mem::size_of::()) + .ok_or(Error::Limit("the codebooks' vector tables are too large"))?; + let values = if lookup_type == 1 { lookup1_values(entries, dimensions) as usize } else { total }; + if !minimum.is_finite() || !delta.is_finite() || values > r.remaining() / value_bits as usize { + return Err(bad("codebook lookup table is damaged or truncated")); + } + let multiplicands: Vec = (0..values).map(|_| r.read(value_bits).unwrap_or(0)).collect(); + *budget -= total * std::mem::size_of::(); + vectors = vec![0f32; total]; + for e in 0..entries as usize { + let out = &mut vectors[e * dimensions as usize..(e + 1) * dimensions as usize]; + let mut last = 0f64; + let mut divisor = 1usize; + for (i, slot) in out.iter_mut().enumerate() { + let m = if lookup_type == 1 { + let at = (e / divisor) % values; + divisor = divisor.saturating_mul(values); + multiplicands[at] + } else { + multiplicands[e * dimensions as usize + i] + }; + let v = f64::from(m) * delta + minimum + last; + if sequence { + last = v; + } + *slot = v as f32; + } + } + } + Ok(Self { dimensions: dimensions as usize, entries: entries as usize, tree, single, vectors }) + } + + /// Whether the book has a lookup table. + pub(super) fn has_vectors(&self) -> bool { + !self.vectors.is_empty() + } + + /// Read a codeword; the entry number (scalar context). + pub(super) fn scalar(&self, r: &mut BitReader<'_>) -> Result { + if let Some(e) = self.single { + r.read(1)?; + return Ok(e); + } + let mut at = 0usize; + loop { + let c = self.tree[at].child[usize::from(r.bit()?)]; + if c == NONE { + return Err(Eop); + } + if c & LEAF != 0 { + return Ok(c & !LEAF); + } + at = c as usize; + } + } + + /// Read a codeword and return its vector (VQ context); `None` for a book without a table. + pub(super) fn vector(&self, r: &mut BitReader<'_>) -> Result, Eop> { + let e = self.scalar(r)? as usize; + Ok(self.vectors.get(e * self.dimensions..(e + 1) * self.dimensions)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pack fields least significant bit first. + struct W(Vec, usize); + impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.1.is_multiple_of(8) { + self.0.push(0); + } + let last = self.0.len() - 1; + self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8); + self.1 += 1; + } + } + } + + fn book_bytes(lengths: &[u32], lookup: Option<(u32, u32, &[u32])>) -> Vec { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(lengths.len() as u64, 24); + w.put(0, 1); // not ordered + w.put(0, 1); // not sparse + for &l in lengths { + w.put(u64::from(l - 1), 5); + } + match lookup { + None => w.put(0, 4), + Some((ty, bits, mult)) => { + w.put(u64::from(ty), 4); + w.put(0, 32); // minimum: 0.0 + w.put(0, 32); + w.put(u64::from(bits - 1), 4); + w.put(0, 1); + for &m in mult { + w.put(u64::from(m), bits); + } + } + } + w.0 + } + + #[test] + fn the_specification_example_assigns_its_codewords() { + // §3.2.1: lengths 2 4 4 4 4 2 3 3 -> 00, 0100, 0101, 0110, 0111, 10, 110, 111. + let bytes = book_bytes(&[2, 4, 4, 4, 4, 2, 3, 3], None); + let mut budget = 1 << 26; + let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book"); + let code = |bits: &[u8]| { + let mut w = W(Vec::new(), 0); + for &b in bits { + w.put(u64::from(b), 1); + } + let mut r = BitReader::new(&w.0); + book.scalar(&mut r).expect("entry") + }; + assert_eq!(code(&[0, 0]), 0); + assert_eq!(code(&[0, 1, 0, 0]), 1); + assert_eq!(code(&[0, 1, 1, 1]), 4); + assert_eq!(code(&[1, 0]), 5); + assert_eq!(code(&[1, 1, 0]), 6); + assert_eq!(code(&[1, 1, 1]), 7); + } + + #[test] + fn over_and_underspecified_books_are_errors() { + let mut budget = 1 << 26; + let over = book_bytes(&[1, 1, 1], None); + assert!(Codebook::read(&mut BitReader::new(&over), &mut budget).is_err()); + let under = book_bytes(&[2, 2, 2], None); + assert!(Codebook::read(&mut BitReader::new(&under), &mut budget).is_err()); + } + + #[test] + fn a_single_entry_book_sinks_one_bit_of_either_value() { + let mut budget = 1 << 26; + let bytes = book_bytes(&[1], None); + let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book"); + for byte in [0u8, 1] { + let data = [byte]; + let mut r = BitReader::new(&data); + assert_eq!(book.scalar(&mut r), Ok(0)); + assert_eq!(r.remaining(), 7); + } + let bad = book_bytes(&[2], None); + assert!(Codebook::read(&mut BitReader::new(&bad), &mut budget).is_err()); + } + + #[test] + fn lookup_type_one_builds_a_lattice() { + // 4 entries, 2 dimensions, 2 values per dimension: minimum 0 and delta 1 in the packed + // float format are written below by hand (mantissa 1, exponent 788 -> 1.0). + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(2, 16); + w.put(4, 24); + w.put(0, 1); + w.put(0, 1); + for _ in 0..4 { + w.put(1, 5); // length 2 each + } + w.put(1, 4); // lookup type 1 + w.put(0, 32); // minimum 0 + w.put((788u64 << 21) | 1, 32); // delta 1.0 + w.put(0, 4); // 1 bit per value + w.put(0, 1); + w.put(0b10, 2); // multiplicands 0, 1 + let mut budget = 1 << 26; + let book = Codebook::read(&mut BitReader::new(&w.0), &mut budget).expect("book"); + assert_eq!(lookup1_values(4, 2), 2); + // Entry e is (m[e % 2], m[(e / 2) % 2]). + assert_eq!(book.vectors, vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + } + + #[test] + fn vector_budget_is_checked_before_reading_lookup_values() { + // A valid single-entry tree, but two values exceed the remaining budget. + // No multiplicands follow: admission must reject it before reading them. + for lookup in [1, 2] { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(2, 16); + w.put(1, 24); + w.put(0, 1); + w.put(0, 1); + w.put(0, 5); + w.put(lookup, 4); + w.put(0, 32); + w.put(0, 32); + w.put(15, 4); + w.put(0, 1); + let mut budget = std::mem::size_of::() + 4; + assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_)))); + } + } + + #[test] + fn vector_size_that_overflows_32_bits_is_refused() { + for lookup in [1, 2] { + let mut w = W(Vec::new(), 0); + w.put(0x56_4342, 24); + w.put(65535, 16); + w.put(65538, 24); // product is above u32::MAX + w.put(0, 1); // unordered + w.put(1, 1); // sparse: only one entry is used + w.put(1, 1); + w.put(0, 5); // length 1 + for _ in 1..65538 { + w.put(0, 1); + } + w.put(lookup, 4); + w.put(0, 32); + w.put(0, 32); + w.put(0, 4); + w.put(0, 1); + w.put(0, 1); // lookup type 1's single multiplicand + let mut budget = 256 << 20; + assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_)))); + } + } + + #[test] + fn helper_functions() { + assert_eq!(float32_unpack((788u32 << 21) | 5), 5.0); + assert_eq!(float32_unpack(0x8000_0000 | (789u32 << 21) | 3), -6.0); + for (entries, dims, want) in [(8, 3, 2), (9, 2, 3), (1, 5, 1), (10, 1, 10), (1000, 3, 10), (4_000_000, 2, 2000)] { + assert_eq!(lookup1_values(entries, dims), want, "{entries} entries, {dims} dims"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/floor.rs b/crates/audio/src/vorbis/decoder/floor.rs new file mode 100644 index 0000000000..bc6ce4e365 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/floor.rs @@ -0,0 +1,385 @@ +//! Floors (Vorbis I §6 and §7): the spectral envelope each channel's residue is multiplied by. + +use super::Error; +use super::bits::{BitReader, Eop, ilog}; +use super::codebook::Codebook; +use super::tables::INVERSE_DB; + +/// Why a floor could not be decoded from a packet. +pub(super) enum Fail { + /// The packet ended (a nominal event: the channel is silent). + Eop, + /// The packet names a codebook that does not exist: it cannot be decoded (§6.2.2). + Invalid, +} + +impl From for Fail { + fn from(_: Eop) -> Self { + Fail::Eop + } +} + +/// What a decoded floor gives to synthesis. +pub(super) enum FloorData { + One { y: Vec, step2: Vec }, + Zero { amplitude: u32, coefficients: Vec }, +} + +pub(super) struct Floor0 { + order: usize, + rate: u32, + bark_map_size: u32, + amplitude_bits: u32, + amplitude_offset: u32, + books: Vec, +} + +pub(super) struct Floor1 { + partition_class: Vec, + class_dimensions: Vec, + class_subclasses: Vec, + class_masterbook: Vec, + subclass_books: Vec>, + multiplier: i32, + range: i32, + xlist: Vec, + /// `(low, high)` neighbour positions of each X from index 2 on. + neighbours: Vec<(usize, usize)>, + /// Indices of `xlist` in ascending X order. + sorted: Vec, +} + +pub(super) enum Floor { + Zero(Floor0), + One(Floor1), +} + +fn eop(_: Eop) -> Error { + Error::Setup("setup header ends inside a floor") +} + +impl Floor { + pub(super) fn read(floor_type: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result { + match floor_type { + 0 => { + let order = r.read(8).map_err(eop)? as usize; + let rate = r.read(16).map_err(eop)?; + let bark_map_size = r.read(16).map_err(eop)?; + let amplitude_bits = r.read(6).map_err(eop)?; + let amplitude_offset = r.read(8).map_err(eop)?; + let count = r.read(4).map_err(eop)? as usize + 1; + let mut list = Vec::with_capacity(count); + for _ in 0..count { + let b = r.read(8).map_err(eop)? as usize; + match books.get(b) { + Some(book) if book.has_vectors() => list.push(b), + _ => return Err(Error::Setup("floor 0 names a missing codebook or one without vectors")), + } + } + if order == 0 || rate == 0 || bark_map_size == 0 || amplitude_bits > 32 { + return Err(Error::Setup("floor 0 with a zero order, rate or map size, or more than 32 amplitude bits")); + } + Ok(Self::Zero(Floor0 { order, rate, bark_map_size, amplitude_bits, amplitude_offset, books: list })) + } + 1 => { + let partitions = r.read(5).map_err(eop)? as usize; + let mut partition_class = Vec::with_capacity(partitions); + for _ in 0..partitions { + partition_class.push(r.read(4).map_err(eop)? as usize); + } + let classes = partition_class.iter().max().map_or(0, |m| m + 1); + let (mut class_dimensions, mut class_subclasses, mut class_masterbook, mut subclass_books) = (vec![], vec![], vec![], vec![]); + for _ in 0..classes { + class_dimensions.push(r.read(3).map_err(eop)? as usize + 1); + let subs = r.read(2).map_err(eop)?; + class_subclasses.push(subs); + let master = if subs != 0 { r.read(8).map_err(eop)? as usize } else { 0 }; + if subs != 0 && master >= books.len() { + return Err(Error::Setup("floor 1 master book out of range")); + } + class_masterbook.push(master); + let mut list = Vec::new(); + for _ in 0..(1u32 << subs) { + let b = r.read(8).map_err(eop)? as i32 - 1; + if b >= books.len() as i32 { + return Err(Error::Setup("floor 1 subclass book out of range")); + } + list.push(b); + } + subclass_books.push(list); + } + let multiplier = r.read(2).map_err(eop)? as i32 + 1; + let rangebits = r.read(4).map_err(eop)?; + let mut xlist = vec![0, 1i32 << rangebits]; + for &c in &partition_class { + for _ in 0..class_dimensions[c] { + xlist.push(r.read(rangebits).map_err(eop)? as i32); + } + } + if xlist.len() > 65 { + return Err(Error::Setup("floor 1 has more than 65 points")); + } + let mut seen = xlist.clone(); + seen.sort_unstable(); + if seen.windows(2).any(|w| w[0] == w[1]) { + return Err(Error::Setup("floor 1 repeats an X position")); + } + // Low and high neighbours (§9.2.4, §9.2.5) of each point, among those before it. + let mut neighbours = Vec::new(); + for i in 2..xlist.len() { + let (mut lo, mut hi) = (0usize, 1usize); + for j in 0..i { + if xlist[j] < xlist[i] && xlist[j] > xlist[lo] { + lo = j; + } + if xlist[j] > xlist[i] && xlist[j] < xlist[hi] { + hi = j; + } + } + neighbours.push((lo, hi)); + } + let mut sorted: Vec = (0..xlist.len()).collect(); + sorted.sort_by_key(|&i| xlist[i]); + let range = [256, 128, 86, 64][multiplier as usize - 1]; + Ok(Self::One(Floor1 { + partition_class, + class_dimensions, + class_subclasses, + class_masterbook, + subclass_books, + multiplier, + range, + xlist, + neighbours, + sorted, + })) + } + _ => Err(Error::Setup("unknown floor type")), + } + } + + /// Decode one channel's floor from a packet: `None` when the channel is unused this block. + pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Fail> { + match self { + Self::One(f) => Ok(f.decode(r, books)?), + Self::Zero(f) => f.decode(r, books), + } + } + + /// The floor curve over `n` bins (`n` is half the block size). + pub(super) fn curve(&self, data: &FloorData, n: usize) -> Vec { + match (self, data) { + (Self::One(f), FloorData::One { y, step2 }) => f.curve(y, step2, n), + (Self::Zero(f), FloorData::Zero { amplitude, coefficients }) => f.curve(*amplitude, coefficients, n), + _ => vec![0.0; n], + } + } +} + +/// `render_point` (§9.2.6). +fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 { + let dy = i64::from(y1 - y0); + let adx = i64::from(x1 - x0); + let err = dy.abs() * i64::from(x - x0); + let off = (err / adx) as i32; + if dy < 0 { y0 - off } else { y0 + off } +} + +/// `render_line` (§9.2.7), writing the bins that fall inside `v`. +fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) { + let dy = y1 - y0; + let adx = x1 - x0; + let base = dy / adx; + let ady = dy.abs() - base.abs() * adx; + let sy = if dy < 0 { base - 1 } else { base + 1 }; + let (mut y, mut err) = (y0, 0); + if let Some(slot) = usize::try_from(x0).ok().and_then(|x| v.get_mut(x)) { + *slot = y; + } + for x in x0 + 1..x1 { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + match usize::try_from(x).ok().and_then(|x| v.get_mut(x)) { + Some(slot) => *slot = y, + None => break, + } + } +} + +impl Floor1 { + fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Eop> { + if !r.bit()? { + return Ok(None); + } + let bits = ilog(i64::from(self.range) - 1); + let mut y = vec![0i32; self.xlist.len()]; + y[0] = r.read(bits)? as i32; + y[1] = r.read(bits)? as i32; + let mut offset = 2usize; + for &class in &self.partition_class { + let cdim = self.class_dimensions[class]; + let cbits = self.class_subclasses[class]; + let csub = (1u32 << cbits) - 1; + let mut cval = 0u32; + if cbits > 0 { + cval = books[self.class_masterbook[class]].scalar(r)?; + } + for j in 0..cdim { + let book = self.subclass_books[class][(cval & csub) as usize]; + cval >>= cbits; + y[offset + j] = if book >= 0 { books[book as usize].scalar(r)? as i32 } else { 0 }; + } + offset += cdim; + } + + // Step 1: amplitude synthesis (§7.2.4). + let mut step2 = vec![false; self.xlist.len()]; + step2[0] = true; + step2[1] = true; + let mut fin = y.clone(); + for i in 2..self.xlist.len() { + let (lo, hi) = self.neighbours[i - 2]; + let predicted = render_point(self.xlist[lo], fin[lo], self.xlist[hi], fin[hi], self.xlist[i]); + let val = y[i]; + let highroom = self.range - predicted; + let lowroom = predicted; + let room = if highroom < lowroom { highroom * 2 } else { lowroom * 2 }; + if val != 0 { + step2[lo] = true; + step2[hi] = true; + step2[i] = true; + fin[i] = if val >= room { + if highroom > lowroom { val - lowroom + predicted } else { predicted - val + highroom - 1 } + } else if val % 2 == 1 { + predicted - (val + 1) / 2 + } else { + predicted + val / 2 + }; + } else { + fin[i] = predicted; + } + // Valid setups never leave the range; a damaged one must not carry out-of-range values on. + fin[i] = fin[i].clamp(0, self.range - 1); + } + Ok(Some(FloorData::One { y: fin, step2 })) + } + + fn curve(&self, fin: &[i32], step2: &[bool], n: usize) -> Vec { + let mut floor = vec![0i32; n]; + let (mut hx, mut hy) = (0i32, 0i32); + let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * self.multiplier); + for &i in &self.sorted[1..] { + if step2[i] { + hy = fin[i] * self.multiplier; + hx = self.xlist[i]; + render_line(lx, ly, hx, hy, &mut floor); + lx = hx; + ly = hy; + } + } + if (hx as usize) < n { + render_line(hx, hy, n as i32, hy, &mut floor); + } + floor.iter().map(|&v| INVERSE_DB[v.clamp(0, 255) as usize]).collect() + } +} + +impl Floor0 { + fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result, Fail> { + let amplitude = r.read(self.amplitude_bits)?; + if amplitude == 0 { + return Ok(None); + } + let book = r.read(ilog(self.books.len() as i64))? as usize; + let Some(&book) = self.books.get(book) else { return Err(Fail::Invalid) }; + let book = &books[book]; + let mut coefficients: Vec = Vec::with_capacity(self.order + book.dimensions); + let mut last = 0f32; + while coefficients.len() < self.order { + let Some(v) = book.vector(r)? else { return Err(Fail::Invalid) }; + coefficients.extend(v.iter().map(|&x| x + last)); + last = coefficients[coefficients.len() - 1]; + } + Ok(Some(FloorData::Zero { amplitude, coefficients })) + } + + fn curve(&self, amplitude: u32, coefficients: &[f32], n: usize) -> Vec { + let bark = |x: f64| 13.1 * (0.00074 * x).atan() + 2.24 * (0.000_000_018_5 * x * x).atan() + 0.0001 * x; + let scale = f64::from(self.bark_map_size) / bark(0.5 * f64::from(self.rate)); + let map: Vec = (0..n) + .map(|i| { + let foobar = (bark(f64::from(self.rate) * i as f64 / (2.0 * n as f64)) * scale).floor() as i64; + foobar.min(i64::from(self.bark_map_size) - 1) + }) + .collect(); + let cos_c: Vec = coefficients.iter().take(self.order).map(|&c| f64::from(c).cos()).collect(); + let amp = f64::from(amplitude); + let offset = f64::from(self.amplitude_offset); + let top = (2f64).powi(self.amplitude_bits as i32) - 1.0; + let mut out = vec![0f32; n]; + let mut i = 0usize; + while i < n { + let omega = std::f64::consts::PI * map[i] as f64 / f64::from(self.bark_map_size); + let cw = omega.cos(); + let (p, q); + if self.order % 2 == 1 { + let mut pp = 1.0 - cw * cw; + for j in 0..(self.order - 1) / 2 { + let d = cos_c[2 * j + 1] - cw; + pp *= 4.0 * d * d; + } + let mut qq = 0.25; + for j in 0..=(self.order - 1) / 2 { + let d = cos_c[2 * j] - cw; + qq *= 4.0 * d * d; + } + p = pp; + q = qq; + } else { + let mut pp = (1.0 - cw) / 2.0; + let mut qq = (1.0 + cw) / 2.0; + for j in 0..self.order / 2 { + let d1 = cos_c[2 * j + 1] - cw; + pp *= 4.0 * d1 * d1; + let d0 = cos_c[2 * j] - cw; + qq *= 4.0 * d0 * d0; + } + p = pp; + q = qq; + } + let linear = (0.115_129_25 * (amp * offset / (top * (p + q).sqrt()) - offset)).exp() as f32; + let key = map[i]; + while i < n && map[i] == key { + out[i] = linear; + i += 1; + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn render_line_matches_a_bresenham_walk() { + let mut v = vec![0i32; 16]; + render_line(0, 0, 8, 4, &mut v); + assert_eq!(&v[..8], &[0, 0, 1, 1, 2, 2, 3, 3]); + let mut v = vec![0i32; 16]; + render_line(2, 10, 6, 2, &mut v); + assert_eq!(&v[2..6], &[10, 8, 6, 4]); + // Lines running past the vector stop at its end. + let mut v = vec![0i32; 4]; + render_line(0, 0, 100, 100, &mut v); + assert_eq!(v, vec![0, 1, 2, 3]); + assert_eq!(render_point(0, 0, 10, 10, 5), 5); + assert_eq!(render_point(0, 10, 10, 0, 5), 5); + } +} diff --git a/crates/audio/src/vorbis/decoder/mdct.rs b/crates/audio/src/vorbis/decoder/mdct.rs new file mode 100644 index 0000000000..b4eb6c8ec8 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/mdct.rs @@ -0,0 +1,164 @@ +//! The inverse MDCT of a block (Vorbis I §4.3.7) and the window slopes. +//! +//! `y[j] = sum_k X[k] cos(2*pi/n * (j + 1/2 + n/4) * (k + 1/2))` for `n/2` coefficients and `n` +//! samples, computed as a DCT-IV of the coefficients through an `n/8`-point complex FFT, then +//! unfolded. + +use std::f64::consts::PI; + +#[derive(Clone, Copy, Default)] +struct Cpx { + re: f64, + im: f64, +} + +impl Cpx { + fn mul(self, o: Cpx) -> Cpx { + Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } + } +} + +fn cis(t: f64) -> Cpx { + Cpx { re: t.cos(), im: t.sin() } +} + +pub(super) struct Imdct { + n: usize, + twiddle: Vec, + post: Vec, + fft_tw: Vec, + rev: Vec, +} + +impl Imdct { + /// For blocks of `n` samples, a power of two of at least 16. + pub(super) fn new(n: usize) -> Self { + let m = n / 2; + let h = m / 2; + let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect(); + let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect(); + let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect(); + let bits = h.trailing_zeros(); + let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect(); + Self { n, twiddle, post, fft_tw, rev } + } + + /// `x`: `n/2` coefficients; `out`: `n` samples. + pub(super) fn inverse(&self, x: &[f32], out: &mut [f32]) { + let m = self.n / 2; + let q = self.n / 4; + let h = m / 2; + let mut z: Vec = (0..h).map(|j| Cpx { re: f64::from(x[2 * j]), im: f64::from(x[m - 1 - 2 * j]) }.mul(self.twiddle[j])).collect(); + self.fft(&mut z); + let mut v = vec![0f64; m]; + for (k, c) in z.iter().enumerate() { + let d = c.mul(self.post[k]); + v[2 * k] = d.re; + v[m - 1 - 2 * k] = -d.im; + } + // Unfold the DCT-IV output to the block. + for i in 0..q { + out[3 * q - 1 - i] = (-v[i]) as f32; + out[3 * q + i] = (-v[i]) as f32; + } + for i in q..2 * q { + out[i - q] = v[i] as f32; + out[3 * q - 1 - i] = (-v[i]) as f32; + } + } + + fn fft(&self, a: &mut [Cpx]) { + let h = a.len(); + for (i, &j) in self.rev.iter().enumerate() { + if i < j { + a.swap(i, j); + } + } + let mut len = 2; + while len <= h { + let step = h / len; + for start in (0..h).step_by(len) { + for k in 0..len / 2 { + let w = self.fft_tw[k * step]; + let u = a[start + k]; + let t = a[start + k + len / 2].mul(w); + a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im }; + a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im }; + } + } + len *= 2; + } + } +} + +/// The rising half of the Vorbis window over `len` samples (§4.3.1): +/// `sin(pi/2 * sin^2((i + 0.5) / len * pi/2))`. +pub(super) fn slope(len: usize) -> Vec { + (0..len) + .map(|i| { + let s = (PI / 2.0 * (i as f64 + 0.5) / len as f64).sin(); + (PI / 2.0 * s * s).sin() as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_direct_formula() { + for n in [16usize, 64, 256, 2048] { + let x: Vec = (0..n / 2).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect(); + let mut fast = vec![0f32; n]; + Imdct::new(n).inverse(&x, &mut fast); + for j in [0usize, 1, 2, n / 4, n / 2, n - 1] { + let direct: f64 = + (0..n / 2).map(|k| f64::from(x[k]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum(); + assert!((direct - f64::from(fast[j])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} j={j}: {direct} vs {}", fast[j]); + } + } + } + + #[test] + fn windowed_overlap_add_reconstructs_the_signal() { + // Forward MDCT by the definition with the 2/M scale an encoder uses, then this inverse. + let n = 64usize; + let m = n / 2; + let signal: Vec = (0..n * 6).map(|i| ((i * 37 % 101) as f64 - 50.0) / 50.0).collect(); + let w: Vec = slope(m).into_iter().chain(slope(m).into_iter().rev()).collect(); + let imdct = Imdct::new(n); + let mut out = vec![0f64; signal.len()]; + let mut start = 0; + while start + n <= signal.len() { + let coeffs: Vec = (0..m) + .map(|k| { + let s: f64 = (0..n) + .map(|j| { + signal[start + j] * f64::from(w[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos() + }) + .sum(); + (s * 2.0 / m as f64) as f32 + }) + .collect(); + let mut y = vec![0f32; n]; + imdct.inverse(&coeffs, &mut y); + for j in 0..n { + out[start + j] += f64::from(y[j]) * f64::from(w[j]); + } + start += m; + } + for i in m..signal.len() - m { + assert!((out[i] - signal[i]).abs() < 1e-4, "sample {i}: {} vs {}", out[i], signal[i]); + } + } + + #[test] + fn the_slope_is_power_complementary() { + let s = slope(1024); + for i in 0..1024 { + let sum = s[i] * s[i] + s[1023 - i] * s[1023 - i]; + assert!((sum - 1.0).abs() < 1e-5, "{i}: {sum}"); + } + } +} diff --git a/crates/audio/src/vorbis/decoder/mod.rs b/crates/audio/src/vorbis/decoder/mod.rs new file mode 100644 index 0000000000..7485e34b84 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/mod.rs @@ -0,0 +1,552 @@ +//! A clean-room Vorbis I decoder (feature `vorbis-decode`), written from the Vorbis I +//! specification (Xiph.Org, 2020). +//! +//! [`Decoder`] works on packets: build it from the three header packets (identification, comment +//! and setup), then give it audio packets in order. Each call returns the PCM the packet +//! completes, planar `f32` in the nominal range -1.0 to 1.0 (not clipped), channels in the order of +//! the stream. The first packet only primes the overlap and returns nothing. [`decode_ogg`] reads a +//! whole Ogg Vorbis file. +//! +//! Codebooks, floors 0 and 1, residues 0, 1 and 2, channel coupling and both block sizes with their +//! hybrid windows are implemented. Damaged input is an error, never a panic: setup sizes are +//! bounded before anything is allocated, and the codeword trees are checked for completeness. + +mod bits; +mod codebook; +mod floor; +mod mdct; +mod residue; +mod tables; + +use bits::{BitReader, Eop, ilog}; +use codebook::Codebook; +use floor::{Fail, Floor, FloorData}; +use mdct::{Imdct, slope}; +use residue::Residue; + +/// Errors of the Vorbis decoder. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The identification or comment header is not valid Vorbis. + #[error("invalid Vorbis header: {0}")] + Header(&'static str), + /// The setup header is damaged or uses something Vorbis I does not allow. + #[error("invalid Vorbis setup: {0}")] + Setup(&'static str), + /// The setup or decoded PCM asks for more memory than the decoder allows. + #[error("Vorbis decode above the limits: {0}")] + Limit(&'static str), + /// The packet is not an audio packet (a header, or a packet with its first bit set). + #[error("not an audio packet")] + NotAudio, + /// The packet is damaged: it ends before its mode and window flags are read, or names a mode + /// that does not exist. + #[error("damaged audio packet: {0}")] + Packet(&'static str), + /// An Ogg file with no Vorbis stream, or one that cannot be read. + #[error("Ogg Vorbis file: {0}")] + Ogg(String), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The identification header (§4.2.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Identification { + /// The channel count, at least 1. + pub channels: u8, + /// Samples per second per channel. + pub sample_rate: u32, + /// The maximum bit rate in bits per second, 0 or negative when not set. + pub bitrate_maximum: i32, + /// The nominal bit rate in bits per second, 0 or negative when not set. + pub bitrate_nominal: i32, + /// The minimum bit rate in bits per second, 0 or negative when not set. + pub bitrate_minimum: i32, + /// The short block size in samples. + pub blocksize_0: u32, + /// The long block size in samples. + pub blocksize_1: u32, +} + +/// The comment header (§5): a vendor string and `NAME=value` comments. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Comments { + /// The vendor string of the encoder. + pub vendor: String, + /// The user comments, each `NAME=value`. + pub comments: Vec, +} + +impl Comments { + /// The first comment named `name` (case-insensitive), its value. + #[must_use] + pub fn get(&self, name: &str) -> Option<&str> { + self.comments.iter().find_map(|c| { + let (k, v) = c.split_once('=')?; + k.eq_ignore_ascii_case(name).then_some(v) + }) + } +} + +fn header_start(packet: &[u8], kind: u8) -> Result> { + if packet.len() < 7 || packet[0] != kind || &packet[1..7] != b"vorbis" { + return Err(Error::Header("wrong packet type or missing \"vorbis\" tag")); + } + let mut r = BitReader::new(packet); + let _ = r.read(8); + for _ in 0..6 { + let _ = r.read(8); + } + Ok(r) +} + +fn read_identification(packet: &[u8]) -> Result { + let mut r = header_start(packet, 1)?; + let eop = |_: Eop| Error::Header("identification header is truncated"); + if r.read(32).map_err(eop)? != 0 { + return Err(Error::Header("unsupported Vorbis version")); + } + let channels = r.read(8).map_err(eop)? as u8; + let sample_rate = r.read(32).map_err(eop)?; + let bitrate_maximum = r.read(32).map_err(eop)? as i32; + let bitrate_nominal = r.read(32).map_err(eop)? as i32; + let bitrate_minimum = r.read(32).map_err(eop)? as i32; + let e0 = r.read(4).map_err(eop)?; + let e1 = r.read(4).map_err(eop)?; + if !r.bit().map_err(eop)? { + return Err(Error::Header("identification header framing bit is not set")); + } + if channels == 0 || sample_rate == 0 { + return Err(Error::Header("no channels or a zero sample rate")); + } + if !(6..=13).contains(&e0) || !(6..=13).contains(&e1) || e0 > e1 { + return Err(Error::Header("block sizes must be powers of two from 64 to 8192, the short one not above the long one")); + } + Ok(Identification { channels, sample_rate, bitrate_maximum, bitrate_nominal, bitrate_minimum, blocksize_0: 1 << e0, blocksize_1: 1 << e1 }) +} + +/// Comments are best effort: damage here is not fatal (§4.2.1). +fn read_comments(packet: &[u8]) -> Result { + header_start(packet, 3)?; + let mut at = 7usize; + let mut take = |n: usize| -> Option<&[u8]> { + let s = packet.get(at..at.checked_add(n)?)?; + at += n; + Some(s) + }; + let word = |b: &[u8]| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize; + let mut out = Comments::default(); + let Some(n) = take(4).map(word) else { return Ok(out) }; + let Some(vendor) = take(n) else { return Ok(out) }; + out.vendor = String::from_utf8_lossy(vendor).into_owned(); + let Some(count) = take(4).map(word) else { return Ok(out) }; + for _ in 0..count { + let Some(n) = take(4).map(word) else { break }; + let Some(c) = take(n) else { break }; + out.comments.push(String::from_utf8_lossy(c).into_owned()); + } + Ok(out) +} + +struct Mapping { + coupling: Vec<(usize, usize)>, + mux: Vec, + /// `(floor, residue)` of each submap. + submaps: Vec<(usize, usize)>, +} + +struct Mode { + long: bool, + mapping: usize, +} + +struct Setup { + books: Vec, + floors: Vec, + residues: Vec, + mappings: Vec, + modes: Vec, +} + +/// Bytes the codebooks of a setup may take in all (codeword trees and vector tables). +const CODEBOOK_BUDGET: usize = 256 << 20; + +fn read_setup(packet: &[u8], channels: usize) -> Result { + let mut r = header_start(packet, 5)?; + let eop = |_: Eop| Error::Setup("setup header is truncated"); + let count = r.read(8).map_err(eop)? as usize + 1; + let mut budget = CODEBOOK_BUDGET; + let mut books = Vec::with_capacity(count); + for _ in 0..count { + books.push(Codebook::read(&mut r, &mut budget)?); + } + // Time domain transforms: placeholders. + for _ in 0..r.read(6).map_err(eop)? + 1 { + if r.read(16).map_err(eop)? != 0 { + return Err(Error::Setup("a time domain transform is not zero")); + } + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut floors = Vec::with_capacity(count); + for _ in 0..count { + let kind = r.read(16).map_err(eop)?; + floors.push(Floor::read(kind, &mut r, &books)?); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut residues = Vec::with_capacity(count); + for _ in 0..count { + let kind = r.read(16).map_err(eop)?; + if kind > 2 { + return Err(Error::Setup("unknown residue type")); + } + residues.push(Residue::read(kind, &mut r, &books)?); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut mappings = Vec::with_capacity(count); + for _ in 0..count { + if r.read(16).map_err(eop)? != 0 { + return Err(Error::Setup("unknown mapping type")); + } + let submaps = if r.bit().map_err(eop)? { r.read(4).map_err(eop)? as usize + 1 } else { 1 }; + let mut coupling = Vec::new(); + if r.bit().map_err(eop)? { + let steps = r.read(8).map_err(eop)? as usize + 1; + let bits = ilog(channels as i64 - 1); + for _ in 0..steps { + let magnitude = r.read(bits).map_err(eop)? as usize; + let angle = r.read(bits).map_err(eop)? as usize; + if magnitude == angle || magnitude >= channels || angle >= channels { + return Err(Error::Setup("channel coupling names an invalid channel pair")); + } + coupling.push((magnitude, angle)); + } + } + if r.read(2).map_err(eop)? != 0 { + return Err(Error::Setup("reserved mapping bits are set")); + } + let mut mux = vec![0usize; channels]; + if submaps > 1 { + for m in &mut mux { + *m = r.read(4).map_err(eop)? as usize; + if *m >= submaps { + return Err(Error::Setup("channel multiplexed to a submap that does not exist")); + } + } + } + let mut list = Vec::with_capacity(submaps); + for _ in 0..submaps { + r.read(8).map_err(eop)?; + let floor = r.read(8).map_err(eop)? as usize; + let residue = r.read(8).map_err(eop)? as usize; + if floor >= floors.len() || residue >= residues.len() { + return Err(Error::Setup("submap names a floor or residue that does not exist")); + } + list.push((floor, residue)); + } + mappings.push(Mapping { coupling, mux, submaps: list }); + } + let count = r.read(6).map_err(eop)? as usize + 1; + let mut modes = Vec::with_capacity(count); + for _ in 0..count { + let long = r.bit().map_err(eop)?; + let window = r.read(16).map_err(eop)?; + let transform = r.read(16).map_err(eop)?; + let mapping = r.read(8).map_err(eop)? as usize; + if window != 0 || transform != 0 || mapping >= mappings.len() { + return Err(Error::Setup("a mode has a nonzero window or transform type or an unknown mapping")); + } + modes.push(Mode { long, mapping }); + } + if !r.bit().map_err(eop)? { + return Err(Error::Setup("setup header framing bit is not set")); + } + Ok(Setup { books, floors, residues, mappings, modes }) +} + +/// The previous block, windowed, kept for overlap-add. +struct Previous { + n: usize, + data: Vec>, +} + +/// A Vorbis I packet decoder. +pub struct Decoder { + id: Identification, + comments: Comments, + setup: Setup, + imdct: [Imdct; 2], + slopes: [Vec; 2], + previous: Option, +} + +impl Decoder { + /// A decoder from the three header packets, in order. A damaged comment header is tolerated + /// (its comments are then empty); the other two must be valid. + pub fn new(identification: &[u8], comment: &[u8], setup: &[u8]) -> Result { + let id = read_identification(identification)?; + let comments = read_comments(comment)?; + let setup = read_setup(setup, usize::from(id.channels))?; + let (b0, b1) = (id.blocksize_0 as usize, id.blocksize_1 as usize); + Ok(Self { id, comments, setup, imdct: [Imdct::new(b0), Imdct::new(b1)], slopes: [slope(b0 / 2), slope(b1 / 2)], previous: None }) + } + + /// The identification header. + #[must_use] + pub fn identification(&self) -> &Identification { + &self.id + } + + /// The comment header. + #[must_use] + pub fn comments(&self) -> &Comments { + &self.comments + } + + /// Forget the previous block, as after a seek: the next packet only primes the overlap again. + pub fn reset(&mut self) { + self.previous = None; + } + + /// The window of a block (§4.3.1). + fn window(&self, n: usize, long: bool, prev_long: bool, next_long: bool) -> Vec { + let half = n / 2; + let b0 = self.id.blocksize_0 as usize; + let mut w = vec![0f32; n]; + // Left half. + if long && !prev_long { + let (start, end) = (n / 4 - b0 / 4, n / 4 + b0 / 4); + w[start..end].copy_from_slice(&self.slopes[0]); + w[end..half].fill(1.0); + } else { + w[..half].copy_from_slice(&self.slopes[usize::from(long)]); + } + // Right half. + if long && !next_long { + let start = 3 * n / 4 - b0 / 4; + w[half..start].fill(1.0); + for (i, s) in self.slopes[0].iter().rev().enumerate() { + w[start + i] = *s; + } + } else { + for (i, s) in self.slopes[usize::from(long)].iter().rev().enumerate() { + w[half + i] = *s; + } + } + w + } + + /// Decode one audio packet. The result holds one `Vec` per channel, all of the same length: + /// the samples this packet completes (none for the first packet after a start or reset). + pub fn decode_packet(&mut self, packet: &[u8]) -> Result>> { + let channels = usize::from(self.id.channels); + let mut r = BitReader::new(packet); + match r.bit() { + Ok(false) => {} + Ok(true) => return Err(Error::NotAudio), + Err(_) => return Err(Error::Packet("empty packet")), + } + let mode_bits = ilog(self.setup.modes.len() as i64 - 1); + let mode_number = r.read(mode_bits).map_err(|_| Error::Packet("packet ends inside the mode number"))? as usize; + let Some(mode) = self.setup.modes.get(mode_number) else { return Err(Error::Packet("mode number out of range")) }; + let long = mode.long; + let n = if long { self.id.blocksize_1 } else { self.id.blocksize_0 } as usize; + let (mut prev_long, mut next_long) = (true, true); + if long { + prev_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?; + next_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?; + } + let window = self.window(n, long, prev_long, next_long); + let half = n / 2; + let mapping = &self.setup.mappings[mode.mapping]; + + let spectrum = self.spectrum(&mut r, mapping, half, channels)?; + // Inverse transform and window. + let which = usize::from(long); + let mut blocks: Vec> = Vec::with_capacity(channels); + for s in &spectrum { + let mut y = vec![0f32; n]; + self.imdct[which].inverse(s, &mut y); + for (v, w) in y.iter_mut().zip(&window) { + *v *= *w; + } + blocks.push(y); + } + + // Overlap-add with the previous block (§4.3.8). + let out = match &self.previous { + None => vec![Vec::new(); channels], + Some(prev) => { + let count = prev.n / 4 + n / 4; + blocks + .iter() + .zip(&prev.data) + .map(|(cur, old)| { + (0..count) + .map(|k| { + let a = old.get(prev.n / 2 + k).copied().unwrap_or(0.0); + let b = (n / 4 + k).checked_sub(prev.n / 4).and_then(|i| cur.get(i)).copied().unwrap_or(0.0); + a + b + }) + .collect() + }) + .collect() + } + }; + self.previous = Some(Previous { n, data: blocks }); + Ok(out) + } + + /// Floors, residues, coupling and the dot product: the spectrum of each channel (§4.3.2 to 4.3.6). + fn spectrum(&self, r: &mut BitReader<'_>, mapping: &Mapping, half: usize, channels: usize) -> Result>> { + let zero = || vec![vec![0f32; half]; channels]; + let setup = &self.setup; + // Floors, in channel order. + let mut floors: Vec> = Vec::with_capacity(channels); + for ch in 0..channels { + let (floor, _) = mapping.submaps[mapping.mux[ch]]; + match setup.floors[floor].decode(r, &setup.books) { + Ok(f) => floors.push(f), + Err(Fail::Eop) => return Ok(zero()), + Err(Fail::Invalid) => return Err(Error::Packet("a floor names a codebook that does not exist")), + } + } + let mut no_residue: Vec = floors.iter().map(Option::is_none).collect(); + for &(m, a) in &mapping.coupling { + if !no_residue[m] || !no_residue[a] { + no_residue[m] = false; + no_residue[a] = false; + } + } + // Residues, in submap order. + let mut residue = zero(); + for (i, &(_, res)) in mapping.submaps.iter().enumerate() { + let members: Vec = (0..channels).filter(|&c| mapping.mux[c] == i).collect(); + if members.is_empty() { + continue; + } + let skip: Vec = members.iter().map(|&c| no_residue[c]).collect(); + let mut vectors = vec![vec![0f32; half]; members.len()]; + setup.residues[res].decode(r, &setup.books, half, &skip, &mut vectors); + for (v, &c) in vectors.into_iter().zip(&members) { + residue[c] = v; + } + } + // Inverse channel coupling (§4.3.5), last step first. + for &(m, a) in mapping.coupling.iter().rev() { + let mut mag = std::mem::take(&mut residue[m]); + let mut ang = std::mem::take(&mut residue[a]); + for (mv, av) in mag.iter_mut().zip(ang.iter_mut()) { + let (big, small) = (*mv, *av); + let (new_m, new_a); + if big > 0.0 { + if small > 0.0 { + new_m = big; + new_a = big - small; + } else { + new_a = big; + new_m = big + small; + } + } else if small > 0.0 { + new_m = big; + new_a = big + small; + } else { + new_a = big; + new_m = big - small; + } + *mv = new_m; + *av = new_a; + } + residue[m] = mag; + residue[a] = ang; + } + // The floor times the residue. + for ch in 0..channels { + match &floors[ch] { + Some(data) => { + let (floor, _) = mapping.submaps[mapping.mux[ch]]; + let curve = setup.floors[floor].curve(data, half); + for (v, c) in residue[ch].iter_mut().zip(curve) { + *v *= c; + } + } + None => residue[ch].fill(0.0), + } + } + Ok(residue) + } +} + +/// A decoded Ogg Vorbis file. +#[derive(Debug, Clone, PartialEq)] +pub struct Decoded { + /// Samples per second per channel. + pub sample_rate: u32, + /// One `Vec` of samples per channel. + pub channels: Vec>, + /// The stream's comment header. + pub comments: Comments, + /// Audio packets that could not be decoded and were skipped. + pub damaged_packets: usize, +} + +/// Decode the first Vorbis stream of an Ogg file. The result is trimmed to the stream's final +/// granule position, so an encoder's padding at the end is dropped. Damaged packets are skipped +/// and counted, not fatal. Collected PCM is limited to 256 MiB; use the packet +/// decoder for longer streams without retaining the entire output. +pub fn decode_ogg(data: &[u8]) -> Result { + let ogg = craft_media::ogg::open(data).map_err(|e| Error::Ogg(e.to_string()))?; + let index = ogg.stream_of(craft_media::ogg::Codec::Vorbis).ok_or_else(|| Error::Ogg("no Vorbis stream".into()))?; + let stream = &ogg.streams[index]; + let [id, comment, setup, ..] = stream.headers.as_slice() else { return Err(Error::Ogg("the stream has fewer than three header packets".into())) }; + let mut decoder = Decoder::new(id, comment, setup)?; + let channel_count = usize::from(decoder.id.channels); + let mut channels = vec![Vec::new(); channel_count]; + let mut damaged = 0; + for i in 0..stream.packets.len() { + let packet = ogg.read_packet(data, index, i).map_err(|e| Error::Ogg(e.to_string()))?; + match decoder.decode_packet(&packet) { + Ok(pcm) => { + append_pcm(&mut channels, pcm, 256 << 20)?; + } + Err(_) => damaged += 1, + } + } + if let Some(total) = stream.last_granule.and_then(|g| usize::try_from(g).ok()) { + for c in &mut channels { + c.truncate(total); + } + } + Ok(Decoded { sample_rate: decoder.id.sample_rate, channels, comments: decoder.comments.clone(), damaged_packets: damaged }) +} + +// Admit every channel together before extending any of them. Limit retained PCM, +// not the compressed input, setup tables or the decoder's bounded packet scratch. +fn append_pcm(channels: &mut [Vec], pcm: Vec>, budget: usize) -> Result<()> { + let samples = channels.iter().chain(&pcm).try_fold(0usize, |n, c| n.checked_add(c.len())); + if samples.is_none_or(|n| n > budget / std::mem::size_of::()) { + return Err(Error::Limit("decoded PCM exceeds the whole-file budget")); + } + for (all, new) in channels.iter_mut().zip(pcm) { + all.try_reserve_exact(new.len()).map_err(|_| Error::Limit("cannot allocate decoded PCM"))?; + all.extend(new); + } + Ok(()) +} + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn pcm_budget_counts_all_channels_before_extending() { + let mut channels = vec![vec![1.0], vec![2.0]]; + append_pcm(&mut channels, vec![vec![3.0], vec![4.0]], 16).expect("exact budget"); + let before = channels.clone(); + assert!(matches!(append_pcm(&mut channels, vec![vec![5.0], vec![6.0]], 23), Err(Error::Limit(_)))); + assert_eq!(channels, before); + append_pcm(&mut channels, vec![Vec::new(), Vec::new()], 16).expect("empty packet"); + } +} diff --git a/crates/audio/src/vorbis/decoder/residue.rs b/crates/audio/src/vorbis/decoder/residue.rs new file mode 100644 index 0000000000..99918d3791 --- /dev/null +++ b/crates/audio/src/vorbis/decoder/residue.rs @@ -0,0 +1,196 @@ +//! Residues (Vorbis I §8): the fine detail of the spectrum, coded as vectors in passes. + +use super::Error; +use super::bits::{BitReader, Eop}; +use super::codebook::Codebook; + +pub(super) struct Residue { + kind: u32, + begin: usize, + end: usize, + partition_size: usize, + classifications: usize, + classbook: usize, + /// `books[class][pass]`. + books: Vec<[Option; 8]>, +} + +fn eop(_: Eop) -> Error { + Error::Setup("setup header ends inside a residue") +} + +impl Residue { + pub(super) fn read(kind: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result { + let begin = r.read(24).map_err(eop)? as usize; + let end = r.read(24).map_err(eop)? as usize; + let partition_size = r.read(24).map_err(eop)? as usize + 1; + let classifications = r.read(6).map_err(eop)? as usize + 1; + let classbook = r.read(8).map_err(eop)? as usize; + let Some(cb) = books.get(classbook) else { return Err(Error::Setup("residue class book out of range")) }; + // classifications ^ dimensions must not exceed the book's entries. + let mut reach = 1u128; + for _ in 0..cb.dimensions { + reach = reach.saturating_mul(classifications as u128); + if reach > cb.entries as u128 { + return Err(Error::Setup("residue class book has too few entries for its classifications")); + } + } + let mut cascade = Vec::with_capacity(classifications); + for _ in 0..classifications { + let low = r.read(3).map_err(eop)?; + let high = if r.bit().map_err(eop)? { r.read(5).map_err(eop)? } else { 0 }; + cascade.push(high * 8 + low); + } + let mut list = Vec::with_capacity(classifications); + for &c in &cascade { + let mut row = [None; 8]; + for (j, slot) in row.iter_mut().enumerate() { + if c & (1 << j) != 0 { + let b = r.read(8).map_err(eop)? as usize; + match books.get(b) { + Some(book) if book.has_vectors() => *slot = Some(b), + _ => return Err(Error::Setup("residue names a missing codebook or one without vectors")), + } + } + } + list.push(row); + } + Ok(Self { kind, begin, end, partition_size, classifications, classbook, books: list }) + } + + /// Decode a bundle of vectors, each `n` long (half the block size), into `out`; a vector marked + /// in `skip` is left zero. End of packet ends decoding where it is (a nominal event). + pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook], n: usize, skip: &[bool], out: &mut [Vec]) { + let ch = out.len(); + if skip.iter().all(|&s| s) { + return; + } + if self.kind == 2 { + let mut flat = vec![vec![0f32; n * ch]]; + let _ = self.decode_vectors(r, books, n * ch, &[false], &mut flat); + for i in 0..n { + for (j, v) in out.iter_mut().enumerate() { + v[i] = flat[0][i * ch + j]; + } + } + } else { + let _ = self.decode_vectors(r, books, n, skip, out); + } + } + + fn decode_vectors(&self, r: &mut BitReader<'_>, books: &[Codebook], actual: usize, skip: &[bool], out: &mut [Vec]) -> Result<(), Eop> { + let ch = out.len(); + let begin = self.begin.min(actual); + let end = self.end.min(actual); + if end <= begin { + return Ok(()); + } + let classbook = &books[self.classbook]; + let cpw = classbook.dimensions; + let partitions = (end - begin) / self.partition_size; + // Classbook dimensions may greatly exceed the actual partition count. + // Retain only digits that this block can use, not padding per channel. + let mut classes = vec![vec![0usize; partitions]; ch]; + for pass in 0..8 { + let mut count = 0usize; + while count < partitions { + if pass == 0 { + for j in 0..ch { + if skip[j] { + continue; + } + let mut temp = classbook.scalar(r)? as usize; + for i in (0..cpw).rev() { + if i + count < partitions { + classes[j][i + count] = temp % self.classifications; + } + temp /= self.classifications; + } + } + } + let mut i = 0; + while i < cpw && count < partitions { + for j in 0..ch { + if skip[j] { + continue; + } + let Some(book) = self.books[classes[j][count]][pass] else { continue }; + let book = &books[book]; + let offset = begin + count * self.partition_size; + self.partition(r, book, &mut out[j][offset..offset + self.partition_size])?; + } + count += 1; + i += 1; + } + } + } + Ok(()) + } + + /// One partition into `v` (the slice of the vector it covers). + fn partition(&self, r: &mut BitReader<'_>, book: &Codebook, v: &mut [f32]) -> Result<(), Eop> { + let n = v.len(); + let dims = book.dimensions; + let step = n / dims; + if self.kind == 0 { + for i in 0..step { + let Some(entry) = book.vector(r)? else { return Ok(()) }; + for (j, &e) in entry.iter().enumerate() { + v[i + j * step] += e; + } + } + } else { + let mut i = 0; + for _ in 0..step { + let Some(entry) = book.vector(r)? else { return Ok(()) }; + for &e in entry { + v[i] += e; + i += 1; + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn huge_class_dimensions_keep_only_actual_partitions() { + let mut data = Vec::::new(); + let mut bits = 0usize; + let mut put = |value: u32, n: usize| { + for i in 0..n { + if bits.is_multiple_of(8) { + data.push(0); + } + let last = data.len() - 1; + data[last] |= (((value >> i) & 1) as u8) << (bits % 8); + bits += 1; + } + }; + put(0x56_4342, 24); + put(65535, 16); + put(1, 24); + put(0, 1); // unordered, not sparse, one length-1 entry + put(0, 1); + put(0, 5); + put(0, 4); // scalar-only classbook + let book = Codebook::read(&mut BitReader::new(&data), &mut (1 << 20)).expect("classbook"); + let books = [book]; + for kind in [0, 1] { + let residue = Residue { kind, begin: 0, end: 32, partition_size: 1, classifications: 1, classbook: 0, books: vec![[None; 8]] }; + let mut out = vec![vec![0.0; 32]; 255]; + let packet = [0u8; 32]; + let mut r = BitReader::new(&packet); + residue.decode(&mut r, &books, 32, &[false; 255], &mut out); + assert_eq!(r.remaining(), 1); // one classword per channel, not 32 + assert!(out.iter().flatten().all(|&x| x == 0.0)); + let mut r = BitReader::new(&packet); + residue.decode(&mut r, &books, 32, &[true; 255], &mut out); + assert_eq!(r.remaining(), 256); // skipped channels consume nothing + } + } +} diff --git a/crates/audio/src/vorbis/decoder/tables.rs b/crates/audio/src/vorbis/decoder/tables.rs new file mode 100644 index 0000000000..49e5b97b9c --- /dev/null +++ b/crates/audio/src/vorbis/decoder/tables.rs @@ -0,0 +1,263 @@ +//! `floor1_inverse_dB_table` (Vorbis I §10.1): the 256 linear amplitudes of the floor 1 integer values. + +// The values are printed to the digits the specification gives them. +#![allow(clippy::excessive_precision)] + +pub(super) const INVERSE_DB: [f32; 256] = [ + 1.0649863e-07, + 1.1341951e-07, + 1.2079015e-07, + 1.2863978e-07, + 1.3699951e-07, + 1.4590251e-07, + 1.5538408e-07, + 1.6548181e-07, + 1.7623575e-07, + 1.8768855e-07, + 1.9988561e-07, + 2.1287530e-07, + 2.2670913e-07, + 2.4144197e-07, + 2.5713223e-07, + 2.7384213e-07, + 2.9163793e-07, + 3.1059021e-07, + 3.3077411e-07, + 3.5226968e-07, + 3.7516214e-07, + 3.9954229e-07, + 4.2550680e-07, + 4.5315863e-07, + 4.8260743e-07, + 5.1396998e-07, + 5.4737065e-07, + 5.8294187e-07, + 6.2082472e-07, + 6.6116941e-07, + 7.0413592e-07, + 7.4989464e-07, + 7.9862701e-07, + 8.5052630e-07, + 9.0579828e-07, + 9.6466216e-07, + 1.0273513e-06, + 1.0941144e-06, + 1.1652161e-06, + 1.2409384e-06, + 1.3215816e-06, + 1.4074654e-06, + 1.4989305e-06, + 1.5963394e-06, + 1.7000785e-06, + 1.8105592e-06, + 1.9282195e-06, + 2.0535261e-06, + 2.1869758e-06, + 2.3290978e-06, + 2.4804557e-06, + 2.6416497e-06, + 2.8133190e-06, + 2.9961443e-06, + 3.1908506e-06, + 3.3982101e-06, + 3.6190449e-06, + 3.8542308e-06, + 4.1047004e-06, + 4.3714470e-06, + 4.6555282e-06, + 4.9580707e-06, + 5.2802740e-06, + 5.6234160e-06, + 5.9888572e-06, + 6.3780469e-06, + 6.7925283e-06, + 7.2339451e-06, + 7.7040476e-06, + 8.2047000e-06, + 8.7378876e-06, + 9.3057248e-06, + 9.9104632e-06, + 1.0554501e-05, + 1.1240392e-05, + 1.1970856e-05, + 1.2748789e-05, + 1.3577278e-05, + 1.4459606e-05, + 1.5399272e-05, + 1.6400004e-05, + 1.7465768e-05, + 1.8600792e-05, + 1.9809576e-05, + 2.1096914e-05, + 2.2467911e-05, + 2.3928002e-05, + 2.5482978e-05, + 2.7139006e-05, + 2.8902651e-05, + 3.0780908e-05, + 3.2781225e-05, + 3.4911534e-05, + 3.7180282e-05, + 3.9596466e-05, + 4.2169667e-05, + 4.4910090e-05, + 4.7828601e-05, + 5.0936773e-05, + 5.4246931e-05, + 5.7772202e-05, + 6.1526565e-05, + 6.5524908e-05, + 6.9783085e-05, + 7.4317983e-05, + 7.9147585e-05, + 8.4291040e-05, + 8.9768747e-05, + 9.5602426e-05, + 0.00010181521, + 0.00010843174, + 0.00011547824, + 0.00012298267, + 0.00013097477, + 0.00013948625, + 0.00014855085, + 0.00015820453, + 0.00016848555, + 0.00017943469, + 0.00019109536, + 0.00020351382, + 0.00021673929, + 0.00023082423, + 0.00024582449, + 0.00026179955, + 0.00027881276, + 0.00029693158, + 0.00031622787, + 0.00033677814, + 0.00035866388, + 0.00038197188, + 0.00040679456, + 0.00043323036, + 0.00046138411, + 0.00049136745, + 0.00052329927, + 0.00055730621, + 0.00059352311, + 0.00063209358, + 0.00067317058, + 0.00071691700, + 0.00076350630, + 0.00081312324, + 0.00086596457, + 0.00092223983, + 0.00098217216, + 0.0010459992, + 0.0011139742, + 0.0011863665, + 0.0012634633, + 0.0013455702, + 0.0014330129, + 0.0015261382, + 0.0016253153, + 0.0017309374, + 0.0018434235, + 0.0019632195, + 0.0020908006, + 0.0022266726, + 0.0023713743, + 0.0025254795, + 0.0026895994, + 0.0028643847, + 0.0030505286, + 0.0032487691, + 0.0034598925, + 0.0036847358, + 0.0039241906, + 0.0041792066, + 0.0044507950, + 0.0047400328, + 0.0050480668, + 0.0053761186, + 0.0057254891, + 0.0060975636, + 0.0064938176, + 0.0069158225, + 0.0073652516, + 0.0078438871, + 0.0083536271, + 0.0088964928, + 0.009474637, + 0.010090352, + 0.010746080, + 0.011444421, + 0.012188144, + 0.012980198, + 0.013823725, + 0.014722068, + 0.015678791, + 0.016697687, + 0.017782797, + 0.018938423, + 0.020169149, + 0.021479854, + 0.022875735, + 0.024362330, + 0.025945531, + 0.027631618, + 0.029427276, + 0.031339626, + 0.033376252, + 0.035545228, + 0.037855157, + 0.040315199, + 0.042935108, + 0.045725273, + 0.048696758, + 0.051861348, + 0.055231591, + 0.058820850, + 0.062643361, + 0.066714279, + 0.071049749, + 0.075666962, + 0.080584227, + 0.085821044, + 0.091398179, + 0.097337747, + 0.10366330, + 0.11039993, + 0.11757434, + 0.12521498, + 0.13335215, + 0.14201813, + 0.15124727, + 0.16107617, + 0.17154380, + 0.18269168, + 0.19456402, + 0.20720788, + 0.22067342, + 0.23501402, + 0.25028656, + 0.26655159, + 0.28387361, + 0.30232132, + 0.32196786, + 0.34289114, + 0.36517414, + 0.38890521, + 0.41417847, + 0.44109412, + 0.46975890, + 0.50028648, + 0.53279791, + 0.56742212, + 0.60429640, + 0.64356699, + 0.68538959, + 0.72993007, + 0.77736504, + 0.82788260, + 0.88168307, + 0.9389798, + 1.0, +]; diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs index 29c423f1d0..15b81bb26d 100644 --- a/crates/audio/src/vorbis/mod.rs +++ b/crates/audio/src/vorbis/mod.rs @@ -1,4 +1,7 @@ -//! Vorbis I (feature `vorbis-encode`): the pure-Rust [`encoder`]. Decoding Vorbis goes through -//! [`crate::decode`]. +//! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature +//! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia. +#[cfg(feature = "vorbis-decode")] +pub mod decoder; +#[cfg(feature = "vorbis-encode")] pub mod encoder; diff --git a/crates/audio/tests/adpcm_oracle.rs b/crates/audio/tests/adpcm_oracle.rs new file mode 100644 index 0000000000..c89fe64440 --- /dev/null +++ b/crates/audio/tests/adpcm_oracle.rs @@ -0,0 +1,516 @@ +//! ADPCM (feature `adpcm`): every family decodes what ffmpeg's encoder writes to ffmpeg's own +//! samples, and ffmpeg decodes what our encoder writes to our own decoder's samples (oracle; +//! skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`); plus the +//! round trip through our own encoder and decoder, and damaged input. + +use craft_audio::adpcm::{ima, ms, swf, yamaha}; +use std::path::Path; +use std::process::Command; + +const RATE: u32 = 22_050; + +/// Interleaved test audio: tones, a sweep, noise bursts, silence and a full-scale square. +fn signal(channels: usize, frames: usize) -> Vec { + let mut seed = 0x2545_F491u32; + let mut out = Vec::with_capacity(frames * channels); + for i in 0..frames { + for c in 0..channels { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let t = i as f64; + let v = match (i / 1500) % 5 { + 0 => (t * (0.03 + 0.011 * c as f64)).sin() * 9000.0, + 1 => (t * 0.002 * (1.0 + t / 3000.0)).sin() * 14000.0, + 2 => f64::from(seed % 12000) - 6000.0, + 3 => 0.0, + _ => { + if (i / 40) % 2 == 0 { + 20000.0 + } else { + -20000.0 + } + } + }; + out.push(v as i16); + } + } + out +} + +fn snr(a: &[i16], b: &[i16]) -> f64 { + let (mut s, mut n) = (0f64, 0f64); + for (x, y) in a.iter().zip(b) { + s += f64::from(*x).powi(2); + n += (f64::from(*x) - f64::from(*y)).powi(2); + } + 10.0 * (s / n.max(1.0)).log10() +} + +fn max_diff(a: &[i16], b: &[i16]) -> i32 { + a.iter().zip(b).map(|(x, y)| (i32::from(*x) - i32::from(*y)).abs()).max().unwrap_or(0) +} + +#[test] +fn encode_then_decode_is_close_to_the_input() { + for channels in [1usize, 2] { + let x = signal(channels, 20_000); + // (name, decoded, minimum SNR dB, a few dB under what each reaches): the signal has noise bursts + // and full-scale square waves, which codes this small follow loosely + let cases: Vec<(&str, Vec, f64)> = vec![ + ("ima", ima::decode(&ima::encode(&x, channels, 512).unwrap(), channels, 512).unwrap(), 5.0), + ("ms", ms::decode(&ms::encode(&x, channels, 512).unwrap(), channels, 512).unwrap(), 18.0), + ("yamaha", yamaha::decode(&yamaha::encode(&x, channels).unwrap(), channels).unwrap(), 5.0), + ("swf2", swf::decode(&swf::encode(&x, channels, 2).unwrap(), channels).unwrap(), 1.0), + ("swf3", swf::decode(&swf::encode(&x, channels, 3).unwrap(), channels).unwrap(), 3.0), + ("swf4", swf::decode(&swf::encode(&x, channels, 4).unwrap(), channels).unwrap(), 5.0), + ("swf5", swf::decode(&swf::encode(&x, channels, 5).unwrap(), channels).unwrap(), 7.0), + ]; + for (name, y, min) in cases { + assert!(y.len() >= x.len(), "{name}: {} samples for {}", y.len(), x.len()); + let s = snr(&x, &y[..x.len()]); + println!("{name} {channels}ch: SNR {s:.1} dB"); + assert!(s >= min, "{name} {channels}ch: SNR {s:.1} dB under {min}"); + } + } +} + +#[test] +fn damaged_input_is_an_error_or_decodes_never_panics() { + let x = signal(2, 4000); + let streams: Vec<(&str, Vec)> = vec![ + ("ima", ima::encode(&x, 2, 256).unwrap()), + ("ms", ms::encode(&x, 2, 256).unwrap()), + ("yamaha", yamaha::encode(&x, 2).unwrap()), + ("swf", swf::encode(&x, 2, 4).unwrap()), + ]; + let mut seed = 99u32; + for (name, s) in &streams { + for cut in (0..s.len()).step_by(7) { + let part = &s[..cut]; + let _ = match *name { + "ima" => ima::decode(part, 2, 256).map(drop), + "ms" => ms::decode(part, 2, 256).map(drop), + "yamaha" => yamaha::decode(part, 2).map(drop), + _ => swf::decode(part, 2).map(drop), + }; + } + for _ in 0..300 { + let mut d = s.clone(); + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let at = seed as usize % d.len(); + d[at] ^= (seed >> 8) as u8 | 1; + let _ = match *name { + "ima" => ima::decode(&d, 2, 256).map(drop), + "ms" => ms::decode(&d, 2, 256).map(drop), + "yamaha" => yamaha::decode(&d, 2).map(drop), + _ => swf::decode(&d, 2).map(drop), + }; + } + } + // the impossible layouts + assert!(ima::decode(&[0; 10], 2, 10).is_err()); + assert!(ima::decode(&[0; 8], 9, 8).is_err()); + assert!(ms::decode(&[0; 8], 3, 8).is_err()); + assert!(ima::encode(&[0; 3], 2, 256).is_err()); + assert!(ima::encode_block(&[0; 3], 1, 256).is_err()); + assert!(ms::encode_block(&[0; 3], 1, 256).is_err()); + // a block whose step index or predictor is out of range + let mut bad = ima::encode_block(&vec![0; 505], 1, 256).unwrap(); + bad[2] = 200; + assert!(ima::decode_block(&bad, 1, &mut Vec::new()).is_err()); + let mut bad = swf::encode(&[0; 10], 1, 4).unwrap(); + bad[2] = 0xFF; + let _ = swf::decode(&bad, 1); +} + +#[test] +fn huge_layouts_and_big_jumps_are_handled() { + // block sizes whose sample counts do not fit in a usize + assert_eq!(ima::samples_per_block(usize::MAX - 3, 1), None); + assert_eq!(ms::samples_per_block(usize::MAX, 1), None); + assert!(ima::encode(&[], 1, usize::MAX - 3).is_err()); + assert!(ms::encode(&[], 1, usize::MAX).is_err()); + // a Flash stream's header holds the step index in six bits: a jump from silence to full scale + // still decodes to what the encoder's own state says + for bits in [2u32, 3, 4, 5] { + let x = [0i16, 32767, -32768, 0, 0]; + let y = swf::decode(&swf::encode(&x, 1, bits).unwrap(), 1).unwrap(); + // the stream has no length: up to seven padding bits can read as one more code + assert!((x.len()..=x.len() + 3).contains(&y.len()), "{bits} bits: {} samples", y.len()); + assert!(y[1] > 0 && y[2] < y[1], "{bits} bits: {y:?}"); + } + // padding bits at the end of a stream are not a code: no incomplete stereo frame + for bits in [2u32, 3, 4, 5] { + let y = swf::decode(&swf::encode(&[0, 0, 5, -5, 9, 9], 2, bits).unwrap(), 2).unwrap(); + assert_eq!(y.len() % 2, 0, "{bits} bits: {y:?}"); + assert!((6..=8).contains(&y.len()), "{bits} bits: {} samples", y.len()); + } +} + +#[test] +fn partial_final_blocks_are_handled() { + let x = signal(1, 1000); + // IMA: 256-byte blocks hold 505 samples; 1000 samples is two blocks, the second padded + let enc = ima::encode(&x, 1, 256).unwrap(); + assert_eq!(enc.len(), 2 * 256); + assert_eq!(ima::decode(&enc, 1, 256).unwrap().len(), 1010); + // a stream cut inside the last block decodes as far as it goes + let cut = ima::decode(&enc[..256 + 4 + 40], 1, 256).unwrap(); + assert_eq!(cut.len(), 505 + 1 + 80); + let enc = ms::encode(&x, 1, 256).unwrap(); + assert_eq!(ms::decode(&enc, 1, 256).unwrap().len(), 1000); + assert!(ima::encode(&[], 1, 256).unwrap().is_empty()); + assert!(ms::encode(&[], 1, 256).unwrap().is_empty()); + assert!(yamaha::encode(&[], 1).unwrap().is_empty()); + assert_eq!(yamaha::decode(&yamaha::encode(&[5, 6, 7], 1).unwrap(), 1).unwrap().len(), 4); +} + +// ---- the other rounding some ffmpeg versions use for IMA and Flash ADPCM +// +// The IMA recommended practices build the step difference from `step >> 3` and the shifted steps +// of the magnitude bits that are set; some decoders (including older ffmpeg releases) compute +// `((2 * magnitude + 1) * step) >> (bits - 1)` instead, which rounds differently by a few units +// and so drifts apart through the predictor. A stream decodes to ours or to this one. + +fn alt_diff(mag: i32, step: i32, bits: u32) -> i32 { + ((2 * mag + 1) * step) >> (bits - 1) +} + +const INDEX_4: [i32; 8] = [-1, -1, -1, -1, 2, 4, 6, 8]; +const INDEX_5: [i32; 16] = [-1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16]; +const STEPS: [i32; 89] = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, + 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, + 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767, +]; + +fn index_table(bits: u32) -> &'static [i32] { + match bits { + 2 => &[-1, 2], + 3 => &[-1, -1, 2, 4], + 4 => &INDEX_4, + _ => &INDEX_5, + } +} + +/// `ima::decode` with the other rounding. +fn alt_ima_decode(data: &[u8], channels: usize, block_align: usize) -> Vec { + let per = ima::samples_per_block(block_align, channels).expect("layout"); + let mut out = Vec::new(); + for block in data.chunks_exact(block_align) { + let mut pred = vec![0i32; channels]; + let mut idx = vec![0i32; channels]; + let base = out.len(); + out.resize(base + per * channels, 0); + for ch in 0..channels { + pred[ch] = i32::from(i16::from_le_bytes([block[4 * ch], block[4 * ch + 1]])); + idx[ch] = i32::from(block[4 * ch + 2]); + out[base + ch] = pred[ch] as i16; + } + for (g, group) in block[4 * channels..].chunks_exact(4 * channels).enumerate() { + for (ch, bytes) in group.as_chunks::<4>().0.iter().enumerate() { + for (k, b) in bytes.iter().enumerate() { + for (half, nib) in [b & 0xF, b >> 4].into_iter().enumerate() { + let step = STEPS[idx[ch] as usize]; + let d = alt_diff(i32::from(nib & 7), step, 4); + pred[ch] = (pred[ch] + if nib & 8 != 0 { -d } else { d }).clamp(-32768, 32767); + idx[ch] = (idx[ch] + INDEX_4[usize::from(nib & 7)]).clamp(0, 88); + out[base + (1 + g * 8 + k * 2 + half) * channels + ch] = pred[ch] as i16; + } + } + } + } + } + out +} + +/// `swf::decode` with the other rounding (one stream). +fn alt_swf_decode(data: &[u8], channels: usize) -> Vec { + let mut bitpos = 0usize; + let mut get = |n: usize| -> Option { + let mut v = 0u32; + for _ in 0..n { + let byte = *data.get(bitpos / 8)?; + v = (v << 1) | u32::from((byte >> (7 - bitpos % 8)) & 1); + bitpos += 1; + } + Some(v) + }; + let bits = get(2).expect("header") + 2; + let mut out = Vec::new(); + loop { + let mut pred = Vec::new(); + let mut idx = Vec::new(); + for _ in 0..channels { + let (Some(p), Some(i)) = (get(16), get(6)) else { return out }; + out.push(p as u16 as i16); + pred.push(i32::from(p as u16 as i16)); + idx.push(i as i32); + } + for _ in 1..4096 { + for ch in 0..channels { + let Some(code) = get(bits as usize) else { return out }; + let mag = (code & ((1 << (bits - 1)) - 1)) as i32; + let d = alt_diff(mag, STEPS[idx[ch] as usize], bits); + pred[ch] = (pred[ch] + if code >> (bits - 1) != 0 { -d } else { d }).clamp(-32768, 32767); + idx[ch] = (idx[ch] + index_table(bits)[mag as usize]).clamp(0, 88); + out.push(pred[ch] as i16); + } + } + } +} + +/// Assert `theirs` is `ours` or `alt` over their common length (and say which). +fn same_as_either(what: &str, ours: &[i16], alt: &[i16], theirs: &[i16]) { + let n = ours.len().min(theirs.len()); + let (a, b) = (max_diff(&ours[..n], &theirs[..n]), max_diff(&alt[..n.min(alt.len())], &theirs[..n.min(alt.len())])); + println!("{what}: largest difference from ours {a}, from the other rounding {b}"); + assert!(a == 0 || b == 0, "{what}: ffmpeg's decode is neither ours ({a}) nor the other rounding ({b})"); +} + +/// A name, the WAV file around our stream, our decode of it and the other rounding's. +type Stream = (&'static str, Vec, Vec, Vec); + +// ---- ffmpeg as the reference + +fn ffmpeg(ff: &Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +fn write_pcm(path: &Path, x: &[i16]) { + std::fs::write(path, x.iter().flat_map(|v| v.to_le_bytes()).collect::>()).expect("write"); +} + +fn read_pcm(path: &Path) -> Vec { + std::fs::read(path).expect("read").as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect() +} + +/// The `fmt ` chunk's fields and the `data` chunk of a WAV file. +fn wav_parts(bytes: &[u8]) -> (u16, usize, usize, Vec) { + let mut at = 12; + let (mut tag, mut channels, mut align) = (0, 0, 0); + while at + 8 <= bytes.len() { + let id = &bytes[at..at + 4]; + let len = u32::from_le_bytes([bytes[at + 4], bytes[at + 5], bytes[at + 6], bytes[at + 7]]) as usize; + let body = &bytes[at + 8..(at + 8 + len).min(bytes.len())]; + if id == b"fmt " { + tag = u16::from_le_bytes([body[0], body[1]]); + channels = usize::from(u16::from_le_bytes([body[2], body[3]])); + align = usize::from(u16::from_le_bytes([body[12], body[13]])); + } else if id == b"data" { + return (tag, channels, align, body.to_vec()); + } + at += 8 + len + (len & 1); + } + panic!("no data chunk"); +} + +/// A WAV file around `data`. +fn wav(tag: u16, channels: usize, align: usize, bits: u16, extra: &[u8], data: &[u8]) -> Vec { + let mut fmt = Vec::new(); + fmt.extend(tag.to_le_bytes()); + fmt.extend((channels as u16).to_le_bytes()); + fmt.extend(RATE.to_le_bytes()); + fmt.extend((RATE * align as u32 / 500).to_le_bytes()); + fmt.extend((align as u16).to_le_bytes()); + fmt.extend(bits.to_le_bytes()); + if !extra.is_empty() || tag == 0x11 || tag == 2 { + fmt.extend((extra.len() as u16).to_le_bytes()); + fmt.extend(extra); + } + let mut out = b"RIFF".to_vec(); + out.extend((4 + 8 + fmt.len() as u32 + 8 + data.len() as u32).to_le_bytes()); + out.extend(b"WAVEfmt "); + out.extend((fmt.len() as u32).to_le_bytes()); + out.extend(fmt); + out.extend(b"data"); + out.extend((data.len() as u32).to_le_bytes()); + out.extend(data); + out +} + +#[test] +fn we_decode_what_ffmpeg_encodes_to_the_samples_ffmpeg_decodes() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 30_000); + let pcm = dir.join(format!("in{channels}.pcm")); + write_pcm(&pcm, &x); + let input = ["-f", "s16le", "-ar", "22050", "-ac", if channels == 1 { "1" } else { "2" }, "-i"]; + for (name, codec, align) in [("ima", "adpcm_ima_wav", 512usize), ("ms", "adpcm_ms", 512), ("yamaha", "adpcm_yamaha", 0)] { + let file = dir.join(format!("{name}{channels}.wav")); + let mut args: Vec = input.iter().map(|a| a.to_string()).collect(); + args.extend([s(&pcm), "-c:a".into(), codec.into()]); + if align > 0 { + args.extend(["-block_size".into(), align.to_string()]); + } + args.push(s(&file)); + ffmpeg(&ff, &args.iter().map(String::as_str).collect::>()); + let back = dir.join(format!("{name}{channels}.out.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let (tag, ch, block, data) = wav_parts(&std::fs::read(&file).expect("read")); + assert_eq!(ch, channels); + let ours = match name { + "ima" => { + assert_eq!(tag, 0x11); + ima::decode(&data, ch, block).expect("decode") + } + "ms" => { + assert_eq!(tag, 2); + ms::decode(&data, ch, block).expect("decode") + } + _ => yamaha::decode(&data, ch).expect("decode"), + }; + let n = ours.len().min(theirs.len()); + assert!(n >= 29_000 * channels, "{name} {channels}ch: {} ours, {} theirs", ours.len(), theirs.len()); + if name == "ima" { + same_as_either(&format!("{name} {channels}ch"), &ours, &alt_ima_decode(&data, ch, block), &theirs); + } else { + let d = max_diff(&ours[..n], &theirs[..n]); + println!("{name} {channels}ch: {n} samples, largest difference from ffmpeg's decode {d}"); + assert_eq!(d, 0, "{name} {channels}ch"); + } + // our encoder is as good as ffmpeg's on the same audio, to within 3 dB + let mine = match name { + "ima" => ima::decode(&ima::encode(&x, ch, block).expect("encode"), ch, block).expect("decode"), + "ms" => ms::decode(&ms::encode(&x, ch, block).expect("encode"), ch, block).expect("decode"), + _ => yamaha::decode(&yamaha::encode(&x, ch).expect("encode"), ch).expect("decode"), + }; + let m = x.len().min(mine.len()).min(theirs.len()); + let (a, b) = (snr(&x[..m], &mine[..m]), snr(&x[..m], &theirs[..m])); + println!("{name} {channels}ch: SNR {a:.1} dB ours, {b:.1} dB ffmpeg's"); + assert!(a + 3.0 >= b, "{name} {channels}ch: our encoder {a:.1} dB against ffmpeg's {b:.1} dB"); + } + } +} + +#[test] +fn ffmpeg_decodes_what_we_encode_to_the_samples_we_decode() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 12_000); + let coefs: Vec = ms::COEFFICIENTS.iter().flat_map(|&(a, b)| [a as i16, b as i16].into_iter().flat_map(i16::to_le_bytes)).collect(); + let streams: Vec = { + let e = ima::encode(&x, channels, 512).unwrap(); + let per = ima::samples_per_block(512, channels).unwrap() as u16; + let d = ima::decode(&e, channels, 512).unwrap(); + let d_alt = alt_ima_decode(&e, channels, 512); + let ima_wav = wav(0x11, channels, 512, 4, &per.to_le_bytes(), &e); + let e = ms::encode(&x, channels, 512).unwrap(); + let per = ms::samples_per_block(512, channels).unwrap() as u16; + let d2 = ms::decode(&e, channels, 512).unwrap(); + let mut extra = per.to_le_bytes().to_vec(); + extra.extend(7u16.to_le_bytes()); + extra.extend(&coefs); + let ms_wav = wav(2, channels, 512, 4, &extra, &e); + let e = yamaha::encode(&x, channels).unwrap(); + let d3 = yamaha::decode(&e, channels).unwrap(); + let y_wav = wav(0x20, channels, 512 * channels, 4, &[], &e); + vec![("ima", ima_wav, d, d_alt), ("ms", ms_wav, d2.clone(), d2), ("yamaha", y_wav, d3.clone(), d3)] + }; + for (name, bytes, ours, alt) in streams { + let file = dir.join(format!("our_{name}{channels}.wav")); + std::fs::write(&file, bytes).expect("write"); + let back = dir.join(format!("our_{name}{channels}.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let n = ours.len().min(theirs.len()); + assert!(n + 2048 >= ours.len(), "{name} {channels}ch: ffmpeg decoded {} of {}", theirs.len(), ours.len()); + same_as_either(&format!("{name} {channels}ch, our stream"), &ours, &alt, &theirs); + } + } +} + +/// The audio tags of an FLV file: each tag's body without its flags byte. +fn flv_audio(bytes: &[u8]) -> Vec> { + let mut at = 13; + let mut out = Vec::new(); + while at + 11 <= bytes.len() { + let kind = bytes[at]; + let len = (usize::from(bytes[at + 1]) << 16) | (usize::from(bytes[at + 2]) << 8) | usize::from(bytes[at + 3]); + let body = &bytes[at + 11..(at + 11 + len).min(bytes.len())]; + if kind == 8 && body.len() > 1 { + assert_eq!(body[0] >> 4, 1, "SWF ADPCM tag"); + out.push(body[1..].to_vec()); + } + at += 11 + len + 4; + } + out +} + +/// An FLV file of 44.1 kHz audio tags with these ADPCM bodies. +fn flv(stereo: bool, tags: &[Vec]) -> Vec { + let mut out = b"FLV\x01\x04\0\0\0\x09\0\0\0\0".to_vec(); + let flags = (1u8 << 4) | (3 << 2) | (1 << 1) | u8::from(stereo); + for (i, t) in tags.iter().enumerate() { + let len = t.len() + 1; + let ts = (i * 4096 * 1000 / 44_100) as u32; + out.extend([ + 8, + (len >> 16) as u8, + (len >> 8) as u8, + len as u8, + (ts >> 16) as u8, + (ts >> 8) as u8, + ts as u8, + (ts >> 24) as u8, + 0, + 0, + 0, + flags, + ]); + out.extend(t); + out.extend((len as u32 + 11).to_be_bytes()); + } + out +} + +#[test] +fn flash_adpcm_matches_ffmpeg_in_both_directions() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("adpcm"); + for channels in [1usize, 2] { + let x = signal(channels, 4096 * 3); + let pcm = dir.join(format!("swf_in{channels}.pcm")); + write_pcm(&pcm, &x); + // ffmpeg encodes (it needs 44.1 kHz for FLV) + let file = dir.join(format!("swf{channels}.flv")); + ffmpeg(&ff, &["-f", "s16le", "-ar", "44100", "-ac", &channels.to_string(), "-i", &s(&pcm), "-c:a", "adpcm_swf", "-f", "flv", &s(&file)]); + let tags = flv_audio(&std::fs::read(&file).expect("read")); + assert!(tags.len() >= 3, "{} tags", tags.len()); + let back = dir.join(format!("swf{channels}.out.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + let ours: Vec = tags.iter().flat_map(|t| swf::decode(t, channels).expect("decode")).collect(); + assert_eq!(ours.len(), 4096 * 3 * channels); + assert_eq!(theirs.len(), 4096 * 3 * channels); + let alt: Vec = tags.iter().flat_map(|t| alt_swf_decode(t, channels)).collect(); + same_as_either(&format!("swf {channels}ch"), &ours, &alt, &theirs); + // ffmpeg decodes ours, one 4096-sample stream per tag + for bits in [2u32, 3, 4, 5] { + let tags: Vec> = x.chunks(4096 * channels).map(|c| swf::encode(c, channels, bits).expect("encode")).collect(); + let ours: Vec = tags.iter().flat_map(|t| swf::decode(t, channels).expect("decode")).collect(); + let file = dir.join(format!("our_swf{channels}_{bits}.flv")); + std::fs::write(&file, flv(channels == 2, &tags)).expect("write"); + let back = dir.join(format!("our_swf{channels}_{bits}.pcm")); + ffmpeg(&ff, &["-i", &s(&file), "-f", "s16le", "-acodec", "pcm_s16le", &s(&back)]); + let theirs = read_pcm(&back); + assert_eq!(ours.len(), 4096 * 3 * channels); + assert_eq!(theirs.len(), 4096 * 3 * channels); + let alt: Vec = tags.iter().flat_map(|t| alt_swf_decode(t, channels)).collect(); + same_as_either(&format!("swf {channels}ch {bits} bits, our stream"), &ours, &alt, &theirs); + } + } +} diff --git a/crates/audio/tests/g726_oracle.rs b/crates/audio/tests/g726_oracle.rs new file mode 100644 index 0000000000..ec875e2c47 --- /dev/null +++ b/crates/audio/tests/g726_oracle.rs @@ -0,0 +1,218 @@ +#![cfg(feature = "g726")] + +use craft_audio::g726::{BitPacking, BitRate, Decoder, Encoder, decode, decode_interleaved, encode, encode_interleaved}; +use std::process::Command; + +fn pearson_correlation(x: &[i16], y: &[i16]) -> f64 { + let n = x.len().min(y.len()); + if n == 0 { + return 0.0; + } + let x = &x[..n]; + let y = &y[..n]; + let mean_x = x.iter().map(|&v| v as f64).sum::() / (n as f64); + let mean_y = y.iter().map(|&v| v as f64).sum::() / (n as f64); + let mut num = 0.0; + let mut denom_x = 0.0; + let mut denom_y = 0.0; + for (&a, &b) in x.iter().zip(y) { + let da = (a as f64) - mean_x; + let db = (b as f64) - mean_y; + num += da * db; + denom_x += da * da; + denom_y += db * db; + } + let denom = (denom_x * denom_y).sqrt(); + if denom > 0.0 { num / denom } else { 0.0 } +} + +fn find_ffmpeg() -> Option { + for cmd in ["ffmpeg", "/opt/homebrew/bin/ffmpeg", "/usr/bin/ffmpeg"] { + if Command::new(cmd).arg("-version").output().is_ok() { + return Some(cmd.to_string()); + } + } + None +} + +#[test] +fn test_silence_roundtrip() { + let pcm = vec![0i16; 80]; + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let enc = encode(&pcm, rate, packing).expect("encode"); + let dec = decode(&enc, rate, packing).expect("decode"); + assert_eq!(dec.len(), pcm.len()); + for &s in &dec { + assert!(s.abs() <= 16, "silence sample too large: {s}"); + } + } + } +} + +#[test] +fn test_sine_wave_roundtrip_fidelity() { + let sample_rate = 8000.0; + let freq = 300.0; + let num_samples = 160; + let mut pcm = Vec::with_capacity(num_samples); + for i in 0..num_samples { + let t = i as f64 / sample_rate; + let s = (4000.0 * (2.0 * std::f64::consts::PI * freq * t).sin()) as i16; + pcm.push(s); + } + + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for packing in [BitPacking::BigEndian, BitPacking::LittleEndian] { + let enc = encode(&pcm, rate, packing).expect("encode sine"); + let dec = decode(&enc, rate, packing).expect("decode sine"); + let corr = pearson_correlation(&pcm, &dec); + assert!(corr > 0.90, "correlation {corr} too low for rate {rate:?} packing {packing:?}"); + } + } +} + +#[test] +fn test_encoder_and_decoder_reset() { + let mut enc = Encoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut dec = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + + let pcm = vec![1000i16, 2000, 3000, 2000, 1000, 0, -1000, -2000]; + let mut out1 = Vec::new(); + enc.encode(&pcm, &mut out1).expect("enc 1"); + enc.flush(&mut out1).expect("flush 1"); + + let mut dec_pcm1 = Vec::new(); + dec.decode(&out1, &mut dec_pcm1).expect("dec 1"); + + enc.reset(); + dec.reset(); + + let mut out2 = Vec::new(); + enc.encode(&pcm, &mut out2).expect("enc 2"); + enc.flush(&mut out2).expect("flush 2"); + + let mut dec_pcm2 = Vec::new(); + dec.decode(&out2, &mut dec_pcm2).expect("dec 2"); + + assert_eq!(out1, out2); + assert_eq!(dec_pcm1, dec_pcm2); +} + +#[test] +fn test_stereo_multichannel_roundtrip() { + let mut stereo_pcm = Vec::new(); + for i in 0..160 { + let left = (3000.0 * (i as f64 * 0.05).sin()) as i16; + let right = (2000.0 * (i as f64 * 0.03).cos()) as i16; + stereo_pcm.push(left); + stereo_pcm.push(right); + } + + let enc = encode_interleaved(&stereo_pcm, 2, BitRate::Rate32k, BitPacking::BigEndian).expect("encode stereo"); + let dec = decode_interleaved(&enc, 2, BitRate::Rate32k, BitPacking::BigEndian).expect("decode stereo"); + + assert_eq!(dec.len(), stereo_pcm.len()); + let corr = pearson_correlation(&stereo_pcm, &dec); + assert!(corr > 0.90, "stereo correlation {corr} too low"); +} + +#[test] +fn test_hostile_inputs_do_not_crash() { + let mut dec = Decoder::new(BitRate::Rate32k, BitPacking::BigEndian); + let mut out = Vec::new(); + let hostile = vec![0xEE; 1000]; + let _ = dec.decode(&hostile, &mut out); + + let mut enc = Encoder::new(BitRate::Rate40k, BitPacking::LittleEndian); + let mut out_enc = Vec::new(); + let hostile_pcm = vec![i16::MIN, i16::MAX, -1, 1, 0]; + let _ = enc.encode(&hostile_pcm, &mut out_enc); + let _ = enc.flush(&mut out_enc); +} + +#[test] +fn test_ffmpeg_g726_oracle_encoder_and_decoder() { + let ff = match find_ffmpeg() { + Some(f) => f, + None => return, + }; + + let sample_rate = 8000; + let num_samples = 240; + let mut pcm = Vec::with_capacity(num_samples); + for i in 0..num_samples { + let t = i as f64 / sample_rate as f64; + let s = (5000.0 * (2.0 * std::f64::consts::PI * 350.0 * t).sin()) as i16; + pcm.push(s); + } + + let dir = std::env::temp_dir().join("craft_g726_oracle"); + let _ = std::fs::create_dir_all(&dir); + let in_pcm_path = dir.join("input.s16le"); + let mut in_bytes = Vec::with_capacity(pcm.len() * 2); + for &s in &pcm { + in_bytes.extend_from_slice(&s.to_le_bytes()); + } + std::fs::write(&in_pcm_path, &in_bytes).expect("write input pcm"); + + for rate in [BitRate::Rate16k, BitRate::Rate24k, BitRate::Rate32k, BitRate::Rate40k] { + for (packing, ff_codec, ff_fmt) in [(BitPacking::BigEndian, "g726", "g726"), (BitPacking::LittleEndian, "g726le", "g726le")] { + let cs = rate.code_size(); + let ff_g726_path = dir.join(format!("ff_{}_{}.g726", cs, ff_codec)); + + // 1. FFmpeg encodes PCM to G.726 + let out = Command::new(&ff) + .args(["-y", "-f", "s16le", "-ar", "8000", "-ac", "1", "-i"]) + .arg(&in_pcm_path) + .args(["-c:a", ff_codec, "-code_size", &cs.to_string(), "-f", ff_fmt]) + .arg(&ff_g726_path) + .output() + .expect("ffmpeg encode"); + assert!(out.status.success(), "ffmpeg encode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_g726_bytes = std::fs::read(&ff_g726_path).expect("read ff g726"); + + // 2. FFmpeg decodes its own G.726 stream + let ff_pcm_back_path = dir.join(format!("ff_back_{}_{}.s16le", cs, ff_codec)); + let out = Command::new(&ff) + .args(["-y", "-f", ff_fmt, "-code_size", &cs.to_string(), "-i"]) + .arg(&ff_g726_path) + .args(["-f", "s16le", "-ar", "8000", "-ac", "1"]) + .arg(&ff_pcm_back_path) + .output() + .expect("ffmpeg decode"); + assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_back_bytes = std::fs::read(&ff_pcm_back_path).expect("read ff back pcm"); + let ff_back_samples: Vec = ff_back_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // 3. Our decoder decodes FFmpeg's stream + let our_decoded = decode(&ff_g726_bytes, rate, packing).expect("our decode"); + let corr = pearson_correlation(&our_decoded, &ff_back_samples); + assert!(corr > 0.998, "correlation {corr} too low between our decoder and FFmpeg decoder for rate {rate:?} packing {packing:?}"); + + // 4. Our encoder encodes PCM to G.726 + let our_g726_bytes = encode(&pcm, rate, packing).expect("our encode"); + let our_g726_path = dir.join(format!("our_{}_{}.g726", cs, ff_codec)); + std::fs::write(&our_g726_path, &our_g726_bytes).expect("write our g726"); + + // 5. FFmpeg decodes our encoded stream + let our_decoded_by_ff_path = dir.join(format!("our_by_ff_{}_{}.s16le", cs, ff_codec)); + let out = Command::new(&ff) + .args(["-y", "-f", ff_fmt, "-code_size", &cs.to_string(), "-i"]) + .arg(&our_g726_path) + .args(["-f", "s16le", "-ar", "8000", "-ac", "1"]) + .arg(&our_decoded_by_ff_path) + .output() + .expect("ffmpeg decode of our stream"); + assert!(out.status.success(), "ffmpeg decode of our stream failed: {}", String::from_utf8_lossy(&out.stderr)); + let our_by_ff_bytes = std::fs::read(&our_decoded_by_ff_path).expect("read our by ff pcm"); + let our_by_ff_samples: Vec = our_by_ff_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + let corr_input = pearson_correlation(&pcm, &our_by_ff_samples); + assert!( + corr_input > 0.90, + "correlation {corr_input} too low for input vs FFmpeg-decoded our stream for rate {rate:?} packing {packing:?}" + ); + } + } +} diff --git a/crates/audio/tests/vorbis_decode_hostile.rs b/crates/audio/tests/vorbis_decode_hostile.rs new file mode 100644 index 0000000000..fba004e109 --- /dev/null +++ b/crates/audio/tests/vorbis_decode_hostile.rs @@ -0,0 +1,230 @@ +//! Hostile input to the Vorbis decoder: damaged headers and packets, truncations, and headers that +//! ask for absurd sizes. Every case is an error or a result, never a panic or a large allocation. + +use craft_audio::vorbis::decoder::{Decoder, Error, decode_ogg}; +use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis}; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +struct Parts { + ogg: Vec, + headers: Vec>, + packets: Vec>, +} + +fn parts(channels: usize) -> Parts { + let signal: Vec> = (0..channels) + .map(|c| (0..20_000).map(|i| ((i as f32 * (0.03 + 0.01 * c as f32)).sin() * 0.4) + ((i * 7 % 13) as f32 - 6.0) / 60.0).collect()) + .collect(); + let ogg = + encode_ogg_vorbis(&AudioBuffer { sample_rate: 44_100, channels: signal }, &OggVorbisOptions::default().with_quality(4.0)).expect("encode"); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let s = &file.streams[0]; + let packets = (0..s.packets.len()).map(|i| file.read_packet(ogg.as_slice(), 0, i).expect("packet")).collect(); + Parts { headers: s.headers.clone(), packets, ogg } +} + +fn decoder(p: &Parts) -> Decoder { + Decoder::new(&p.headers[0], &p.headers[1], &p.headers[2]).expect("valid headers") +} + +#[test] +fn every_truncated_header_is_an_error() { + let p = parts(2); + for which in [0usize, 2] { + for n in 0..p.headers[which].len() { + let mut h = p.headers.clone(); + h[which].truncate(n); + assert!(Decoder::new(&h[0], &h[1], &h[2]).is_err(), "header {which} cut to {n} bytes"); + } + } + // A damaged comment header is not fatal. + let mut h = p.headers.clone(); + h[1].truncate(12); + let d = Decoder::new(&h[0], &h[1], &h[2]).expect("comments are best effort"); + assert!(d.comments().comments.is_empty()); + assert!(Decoder::new(&p.headers[0], &[], &p.headers[2]).is_err(), "the comment header still needs its tag"); +} + +#[test] +fn damaged_headers_never_panic() { + let p = parts(2); + let mut seed = 99u32; + for which in [0usize, 2] { + let len = p.headers[which].len(); + for _ in 0..800 { + let mut h = p.headers.clone(); + for _ in 0..1 + xorshift(&mut seed) % 3 { + let at = xorshift(&mut seed) as usize % len; + h[which][at] = xorshift(&mut seed) as u8; + } + if let Ok(mut d) = Decoder::new(&h[0], &h[1], &h[2]) { + // A setup that survives must also survive audio packets. + for pk in p.packets.iter().take(6) { + let _ = d.decode_packet(pk); + } + } + } + } +} + +#[test] +fn damaged_packets_never_panic() { + let p = parts(2); + let mut seed = 7u32; + let mut d = decoder(&p); + for pk in &p.packets { + for _ in 0..6 { + let mut bad = pk.clone(); + match xorshift(&mut seed) % 3 { + 0 => bad.truncate(xorshift(&mut seed) as usize % (bad.len() + 1)), + 1 => { + let at = xorshift(&mut seed) as usize % bad.len(); + bad[at] = xorshift(&mut seed) as u8; + } + _ => bad = (0..xorshift(&mut seed) % 300).map(|_| xorshift(&mut seed) as u8).collect(), + } + let _ = d.decode_packet(&bad); + } + } + // The decoder still decodes good packets after all that. + d.reset(); + assert!(d.decode_packet(&p.packets[3]).is_ok()); +} + +#[test] +fn header_packets_and_empty_packets_are_not_audio() { + let p = parts(1); + let mut d = decoder(&p); + assert_eq!(d.decode_packet(&p.headers[0]), Err(Error::NotAudio)); + assert_eq!(d.decode_packet(&p.headers[2]), Err(Error::NotAudio)); + assert!(matches!(d.decode_packet(&[]), Err(Error::Packet(_)))); +} + +#[test] +fn damaged_files_never_panic() { + let p = parts(2); + let mut seed = 31u32; + for _ in 0..120 { + let mut bad = p.ogg.clone(); + for _ in 0..1 + xorshift(&mut seed) % 4 { + let at = xorshift(&mut seed) as usize % bad.len(); + bad[at] = xorshift(&mut seed) as u8; + } + let _ = decode_ogg(&bad); + bad.truncate(xorshift(&mut seed) as usize % bad.len()); + let _ = decode_ogg(&bad); + } + assert!(matches!(decode_ogg(b"not an ogg file"), Err(Error::Ogg(_)))); + assert!(matches!(decode_ogg(&[]), Err(Error::Ogg(_)))); +} + +/// A bit writer for hand-built setups. +#[derive(Default)] +struct W(Vec, usize); +impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.1.is_multiple_of(8) { + self.0.push(0); + } + let last = self.0.len() - 1; + self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8); + self.1 += 1; + } + } +} + +fn setup_with_first_book(book: impl FnOnce(&mut W)) -> Vec { + let mut w = W::default(); + w.put(5, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + w.put(0, 8); // one book + book(&mut w); + w.0 +} + +#[test] +fn absurd_codebook_sizes_are_refused_before_allocating() { + let p = parts(1); + let try_setup = |setup: Vec| Decoder::new(&p.headers[0], &p.headers[1], &setup); + // 2^24 - 1 entries. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(0xFF_FFFF, 24); + w.put(1, 1); // ordered + w.put(0, 5); + })) + .is_err() + ); + // An ordered book whose lengths overrun its entries. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(1, 16); + w.put(8, 24); + w.put(1, 1); + w.put(0, 5); + w.put(0xFF, 4); // asks for more codewords of length 1 than there are entries + })) + .is_err() + ); + // A lookup table of 65535 dimensions over a million entries: 69 billion values. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(0xFFFF, 16); + w.put(1 << 20, 24); + w.put(1, 1); // ordered + w.put(19, 5); // length 20 + w.put(1 << 20, 21); // all the entries + w.put(2, 4); // lookup type 2 + w.put(0, 32); + w.put(0, 32); + w.put(0, 4); + w.put(0, 1); + })) + .is_err() + ); + // A million-entry book with a legitimate tree but a lookup table that is not in the packet. + assert!( + try_setup(setup_with_first_book(|w| { + w.put(0x56_4342, 24); + w.put(4, 16); + w.put(1 << 20, 24); + w.put(1, 1); + w.put(19, 5); + w.put(1 << 20, 21); + w.put(1, 4); // lookup type 1 + w.put(0, 32); + w.put(0, 32); + w.put(15, 4); + w.put(0, 1); + })) + .is_err() + ); +} + +#[test] +fn identification_header_limits() { + let p = parts(1); + let mut h = p.headers[0].clone(); + let setup = &p.headers[2]; + h[11] = 0; // no channels + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); + let mut h = p.headers[0].clone(); + h[28] = 0x95; // a short block size of 2^5 is below the 64 Vorbis allows + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); + let mut h = p.headers[0].clone(); + h[7] = 1; // version 1 + assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_)))); +} diff --git a/crates/audio/tests/vorbis_decode_oracle.rs b/crates/audio/tests/vorbis_decode_oracle.rs new file mode 100644 index 0000000000..a23d2a954f --- /dev/null +++ b/crates/audio/tests/vorbis_decode_oracle.rs @@ -0,0 +1,216 @@ +//! The Vorbis decoder against ffmpeg's as the reference (oracle; skipped when ffmpeg is absent, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). Streams come from two encoders, this crate's and +//! ffmpeg's own, so the setups differ: different floors, residues, block sizes, channel counts and +//! coupling. Both decoders must return the same samples. + +use craft_audio::AudioBuffer; +use craft_audio::vorbis::decoder::{Decoder, decode_ogg}; +use craft_audio::{OggVorbisOptions, encode_ogg_vorbis}; +use std::path::Path; +use std::process::Command; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +/// A signal with tones, noise bursts, clicks and silence, different in every channel. +fn signal(rate: u32, channels: usize, frames: usize) -> Vec> { + let mut seed = 0x1234_5678u32; + (0..channels) + .map(|c| { + (0..frames) + .map(|i| { + let t = i as f64 / f64::from(rate); + let tone = + (t * (220.0 + 110.0 * c as f64) * std::f64::consts::TAU).sin() * 0.3 + (t * 3100.0 * std::f64::consts::TAU).sin() * 0.05; + let noise = (f64::from(xorshift(&mut seed) % 2000) - 1000.0) / 6000.0; + let s = match (i / (rate as usize / 4)) % 6 { + 0 | 1 => tone, + 2 => noise, + 3 => 0.0, + 4 => tone + if i % 3000 < 8 { 0.6 } else { 0.0 }, + _ => tone * (t * 4.0).sin(), + }; + s as f32 + }) + .collect() + }) + .collect() +} + +fn ffmpeg_decode(ffmpeg: &Path, ogg: &Path, channels: usize) -> Vec> { + let out = Command::new(ffmpeg) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(ogg) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg failed on {}: {}", ogg.display(), String::from_utf8_lossy(&out.stderr)); + let all: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + (0..channels).map(|c| all.iter().skip(c).step_by(channels).copied().collect()).collect() +} + +/// Each of our channels matches a different one of theirs (ffmpeg reorders the channels of surround +/// streams), to within float rounding. +fn assert_same(name: &str, ours: &[Vec], theirs: &[Vec]) { + assert_prefix(name, ours, theirs, true); +} + +/// As [`assert_same`], but with `exact` unset ffmpeg may return more samples than we do (it does +/// not always trim a stream to its last granule position); the common part must agree. +fn assert_prefix(name: &str, ours: &[Vec], theirs: &[Vec], exact: bool) { + assert_eq!(ours.len(), theirs.len(), "{name}: channel count"); + assert!(ours.iter().chain(theirs).flatten().all(|v| v.is_finite()), "{name}: non-finite oracle input or output"); + let mut used = vec![false; theirs.len()]; + for (c, o) in ours.iter().enumerate() { + let mut best: Option<(usize, f32)> = None; + for (k, t) in theirs.iter().enumerate() { + if used[k] { + continue; + } + if exact { + assert_eq!(o.len(), t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len()); + } else { + assert!(o.len() <= t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len()); + } + let worst = o.iter().zip(t).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); + if best.is_none_or(|(_, w)| worst < w) { + best = Some((k, worst)); + } + } + let (k, worst) = best.expect("a free channel"); + used[k] = true; + assert!(worst < 2e-4, "{name}: channel {c} differs from ffmpeg's channel {k} by up to {worst}"); + } +} + +#[test] +fn ffmpeg_decodes_our_encoders_streams_to_the_same_samples() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_decode"); + for (rate, channels, quality) in + [(44_100u32, 2usize, 6.0f32), (44_100, 1, 3.0), (48_000, 2, -1.0), (22_050, 1, 10.0), (44_100, 6, 5.0), (32_000, 8, 4.0)] + { + let buf = AudioBuffer { sample_rate: rate, channels: signal(rate, channels, rate as usize * 2 + 777) }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(quality)).expect("encode"); + let file = dir.join(format!("ours_{rate}_{channels}_{quality}.ogg")); + std::fs::write(&file, &ogg).expect("write fixture"); + let decoded = decode_ogg(&ogg).expect("decode"); + assert_eq!(decoded.damaged_packets, 0); + assert_eq!(decoded.sample_rate, rate); + assert_same(&format!("our stream {rate} Hz {channels} ch q{quality}"), &decoded.channels, &ffmpeg_decode(&ffmpeg, &file, channels)); + } +} + +/// ffmpeg's own Vorbis encoder (stereo only) writes setups ours does not: coupled channels, residue +/// type 2, floor classes with subclasses and master books, two block sizes. The reference is +/// Symphonia, an independent decoder. ffmpeg's decoder agrees on the first channel but not on the +/// second of these streams, where it differs from both Symphonia and this decoder; the stream does +/// not show which reading it means (the channel comes back poorly, about 3 dB SNR, in all three), +/// so ffmpeg is compared on the first channel only. The setups ffmpeg's decoder does read the same +/// way as we do are covered, on both channels, in `vorbis_decode_synthetic.rs`. +#[test] +fn we_decode_ffmpegs_encoder_streams_like_symphonia() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_decode"); + for (rate, bitrate) in [(44_100u32, "128k"), (48_000, "96k"), (22_050, "48k"), (32_000, "64k")] { + let channels = 2usize; + let pcm: Vec = { + let s = signal(rate, channels, rate as usize * 2 + 301); + (0..s[0].len()).flat_map(|i| s.iter().map(move |c| c[i])).collect() + }; + let raw = dir.join(format!("src_{rate}_{channels}.f32")); + std::fs::write(&raw, pcm.iter().flat_map(|v| v.to_le_bytes()).collect::>()).expect("write source"); + let file = dir.join(format!("ffmpeg_{rate}_{channels}_{bitrate}.ogg")); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-nostdin", "-y", "-f", "f32le", "-ar"]) + .arg(rate.to_string()) + .arg("-ac") + .arg(channels.to_string()) + .arg("-i") + .arg(&raw) + .args(["-c:a", "vorbis", "-strict", "-2", "-b:a", bitrate]) + .arg(&file) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg could not encode {}: {}", file.display(), String::from_utf8_lossy(&out.stderr)); + let ogg = std::fs::read(&file).expect("read"); + let ours = decode_ogg(&ogg).expect("decode"); + assert_eq!(ours.damaged_packets, 0, "{}", file.display()); + let (_, symphonia) = craft_audio::decode(&ogg, Some("ogg")).expect("symphonia"); + let name = format!("ffmpeg-encoded {rate} Hz {bitrate}"); + assert_prefix(&name, &ours.channels, &symphonia.channels, false); + // The first channel also agrees with ffmpeg's decoder. + let theirs = ffmpeg_decode(&ffmpeg, &file, channels); + assert_prefix(&format!("{name} (channel 0 against ffmpeg)"), &ours.channels[..1], &theirs[..1], true); + } +} + +#[test] +fn packets_decode_one_at_a_time_to_the_file_result() { + let buf = AudioBuffer { sample_rate: 44_100, channels: signal(44_100, 2, 30_000) }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(5.0)).expect("encode"); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let s = &file.streams[file.stream_of(craft_media::ogg::Codec::Vorbis).expect("vorbis")]; + let mut dec = Decoder::new(&s.headers[0], &s.headers[1], &s.headers[2]).expect("decoder"); + assert_eq!((dec.identification().channels, dec.identification().sample_rate), (2, 44_100)); + let mut got: Vec> = vec![Vec::new(); 2]; + for i in 0..s.packets.len() { + let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet"); + for (a, b) in got.iter_mut().zip(dec.decode_packet(&p).expect("packet decodes")) { + a.extend(b); + } + } + let whole = decode_ogg(&ogg).expect("file"); + for (a, b) in got.iter().zip(&whole.channels) { + assert!(a.len() >= b.len() && a[..b.len()] == b[..]); + } + // After a reset the next packet only primes the overlap again. + dec.reset(); + let p = file.read_packet(ogg.as_slice(), 0, 5).expect("packet"); + assert!(dec.decode_packet(&p).expect("decodes").iter().all(Vec::is_empty)); +} + +#[test] +fn the_round_trip_through_our_encoder_is_faithful() { + let src = signal(44_100, 2, 44_100); + let buf = AudioBuffer { sample_rate: 44_100, channels: src.clone() }; + let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(8.0)).expect("encode"); + let out = decode_ogg(&ogg).expect("decode"); + assert_eq!(out.channels[0].len(), src[0].len()); + let (mut sig, mut err) = (0f64, 0f64); + for (a, b) in src[0].iter().zip(&out.channels[0]) { + sig += f64::from(*a) * f64::from(*a); + err += f64::from(a - b) * f64::from(a - b); + } + assert!(10.0 * (sig / err).log10() > 15.0, "SNR {:.1} dB", 10.0 * (sig / err).log10()); +} + +/// A stream from libvorbis itself (the repository's `tone.ogg` fixture, made with ffmpeg's libvorbis +/// wrapper): mono, 8 kHz, the lowest quality. +#[test] +fn a_libvorbis_stream_decodes_like_ffmpeg() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/tone.ogg"); + let ogg = std::fs::read(&path).expect("fixture"); + let ours = decode_ogg(&ogg).expect("decode"); + assert_eq!((ours.sample_rate, ours.channels.len(), ours.damaged_packets), (8000, 1, 0)); + assert!(ours.comments.vendor.contains("Lavf") || ours.comments.vendor.contains("libVorbis"), "vendor {:?}", ours.comments.vendor); + assert!(ours.channels[0].iter().any(|s| s.abs() > 0.1), "the fixture is a tone"); + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + assert_prefix("libvorbis tone.ogg", &ours.channels, &ffmpeg_decode(&ffmpeg, &path, 1), false); +} + +#[test] +#[should_panic(expected = "non-finite oracle input or output")] +fn oracle_comparison_rejects_nan_output() { + assert_same("NaN output", &[vec![f32::NAN]], &[vec![0.0]]); +} + +#[test] +#[should_panic(expected = "non-finite oracle input or output")] +fn oracle_comparison_rejects_nan_reference() { + assert_same("NaN reference", &[vec![0.0]], &[vec![f32::NAN]]); +} diff --git a/crates/audio/tests/vorbis_decode_synthetic.rs b/crates/audio/tests/vorbis_decode_synthetic.rs new file mode 100644 index 0000000000..46c48eced3 --- /dev/null +++ b/crates/audio/tests/vorbis_decode_synthetic.rs @@ -0,0 +1,384 @@ +//! Differential tests on streams built by hand: a setup header written here, with floor 0 and +//! floor 1 side by side, residues 0, 1 and 2, several submaps and channel coupling, followed by +//! random audio packets. Every packet of random bits is decodable, so the two decoders (ours and +//! ffmpeg's, the oracle; skipped when ffmpeg is absent, a failure with +//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`) must return the same samples, and no encoder's habits narrow +//! what is exercised. Floor 0, residue 0 and multi-submap mappings are the parts no encoder here +//! writes. + +use craft_audio::vorbis::decoder::{Decoder, decode_ogg}; +use craft_media::ogg::{PageWriter, vorbis_comment}; +use std::process::Command; + +fn xorshift(seed: &mut u32) -> u32 { + *seed ^= *seed << 13; + *seed ^= *seed >> 17; + *seed ^= *seed << 5; + *seed +} + +/// A least-significant-bit-first bit writer. +#[derive(Default)] +struct W { + bytes: Vec, + bits: usize, +} + +impl W { + fn put(&mut self, v: u64, n: u32) { + for i in 0..n { + if self.bits.is_multiple_of(8) { + self.bytes.push(0); + } + let last = self.bytes.len() - 1; + self.bytes[last] |= (((v >> i) & 1) as u8) << (self.bits % 8); + self.bits += 1; + } + } + fn flag(&mut self, b: bool) { + self.put(u64::from(b), 1); + } +} + +fn float_bits(v: f64) -> u64 { + // The Vorbis float32 packing: sign, 10-bit exponent biased by 788, 21-bit mantissa. + if v == 0.0 { + return 0; + } + let (sign, a) = if v < 0.0 { (1u64 << 31, -v) } else { (0, v) }; + let mut exp = 0i32; + let mut m = a; + while m >= (1 << 21) as f64 { + m /= 2.0; + exp += 1; + } + while m < (1 << 20) as f64 { + m *= 2.0; + exp -= 1; + } + sign | (((exp + 788) as u64) << 21) | (m.round() as u64 & 0x1F_FFFF) +} + +/// A complete codebook: `entries` codewords all of length `len` (`entries == 2^len`), optionally +/// with a lookup table: `(type, minimum, delta, value_bits, multiplicands)`. +fn book(w: &mut W, dims: u32, entries: u32, len: u32, lookup: Option<(u32, f64, f64, u32, Vec)>) { + w.put(0x56_4342, 24); + w.put(u64::from(dims), 16); + w.put(u64::from(entries), 24); + w.flag(false); // not ordered + w.flag(false); // not sparse + for _ in 0..entries { + w.put(u64::from(len - 1), 5); + } + match lookup { + None => w.put(0, 4), + Some((ty, min, delta, bits, mult)) => { + w.put(u64::from(ty), 4); + w.put(float_bits(min), 32); + w.put(float_bits(delta), 32); + w.put(u64::from(bits - 1), 4); + w.flag(ty == 1); // sequence_p: cumulative for the floor 0 book + for m in mult { + w.put(u64::from(m), bits); + } + } + } +} + +struct Layout { + channels: u8, + /// The residue type of each of the two residues. + residue_types: [u32; 2], + /// The submap of each channel (0 or 1): submap 0 uses floor 0 and residue 0, submap 1 uses + /// floor 1 and residue 1. + mux: Vec, + coupling: Vec<(u8, u8)>, +} + +fn identification(channels: u8) -> Vec { + let mut w = W::default(); + w.put(1, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + w.put(0, 32); + w.put(u64::from(channels), 8); + w.put(16_000, 32); + w.put(0, 32); + w.put(0, 32); + w.put(0, 32); + w.put(8, 4); // short blocks: 256 + w.put(10, 4); // long blocks: 1024 + w.flag(true); + w.bytes +} + +fn setup(l: &Layout) -> Vec { + let mut w = W::default(); + w.put(5, 8); + for c in b"vorbis" { + w.put(u64::from(*c), 8); + } + // Books: 0 floor 0 vectors, 1 class book, 2 and 3 residue vectors, 4 floor 1 values. + w.put(4, 8); // five books + book(&mut w, 4, 16, 4, Some((1, 0.7, 0.2, 1, vec![0, 1]))); // lookup1_values(16, 4) = 2 + book(&mut w, 1, 4, 2, None); + book(&mut w, 2, 16, 4, Some((1, -0.4, 0.25, 2, vec![0, 1, 2, 3]))); // lookup1_values(16, 2) = 4 + book(&mut w, 4, 16, 4, Some((1, -0.3, 0.6, 1, vec![0, 1]))); + book(&mut w, 1, 128, 7, None); + // One time domain placeholder. + w.put(0, 6); + w.put(0, 16); + // Floors: 0 and 1. + w.put(1, 6); // two floors + w.put(0, 16); + w.put(8, 8); // order + w.put(16_000, 16); // rate + w.put(64, 16); // bark map size + w.put(8, 6); // amplitude bits + w.put(2, 8); // amplitude offset + w.put(0, 4); // one book + w.put(0, 8); + w.put(1, 16); + w.put(1, 5); // one partition + w.put(0, 4); // class 0 + w.put(2, 3); // dimension 3 + w.put(0, 2); // no subclasses + w.put(4 + 1, 8); // subclass book: book 4 (stored plus one) + w.put(1, 2); // multiplier 2 + w.put(8, 4); // rangebits + for x in [10, 40, 130] { + w.put(x, 8); + } + // Residues. + w.put(1, 6); // two residues + for ty in l.residue_types { + w.put(u64::from(ty), 16); + w.put(0, 24); // begin + w.put(if ty == 2 { 96 } else { 48 }, 24); // end + w.put(7, 24); // partition size 8 + w.put(3, 6); // four classifications + w.put(1, 8); // class book + for _ in 0..4 { + w.put(0b011, 3); // passes 0 and 1 + w.flag(false); + } + for class in 0..4 { + w.put(2 + (class % 2), 8); // pass 0 uses book 2 or 3 + w.put(3 - (class % 2), 8); // pass 1 uses book 3 or 2 + } + } + // One mapping, two submaps. + w.put(0, 6); + w.put(0, 16); + w.flag(true); + w.put(1, 4); // two submaps + w.flag(!l.coupling.is_empty()); + if !l.coupling.is_empty() { + w.put(l.coupling.len() as u64 - 1, 8); + let bits = if l.channels <= 1 { 0 } else { 8 - (l.channels - 1).leading_zeros() }; + for &(m, a) in &l.coupling { + w.put(u64::from(m), bits); + w.put(u64::from(a), bits); + } + } + w.put(0, 2); + for &m in &l.mux { + w.put(u64::from(m), 4); + } + for sub in 0..2u64 { + w.put(0, 8); + w.put(sub, 8); // floor + w.put(sub, 8); // residue + } + // Two modes over the one mapping. + w.put(1, 6); + for long in [false, true] { + w.flag(long); + w.put(0, 16); + w.put(0, 16); + w.put(0, 8); + } + w.flag(true); + w.bytes +} + +fn stream(l: &Layout, packets: usize, seed: &mut u32) -> Vec { + let mut pages = PageWriter::new(7); + let mut out = pages.header(&identification(l.channels)); + out.extend(pages.header(&vorbis_comment("synthetic", &[("TITLE", "hand built")]))); + out.extend(pages.header(&setup(l))); + // The window flags of a long block say whether its neighbours are long, so choose the block + // sizes first. + let longs: Vec = (0..packets).map(|_| !xorshift(seed).is_multiple_of(3)).collect(); + let mut granule = 0i64; + for i in 0..packets { + let long = longs[i]; + // Packet type 0, the mode bit, and for a long block the two neighbour flags. + let prev = i == 0 || longs[i - 1]; + let next = i + 1 >= packets || longs[i + 1]; + let mut w = W::default(); + w.flag(false); + w.flag(long); + if long { + w.flag(prev); + w.flag(next); + } + // Floor 0 needs a codebook number that exists, which random bits would not give, so the + // channels that use it (the first ones) are written properly: an amplitude, book 0 and two + // codewords of its vectors (a full tree of 4-bit codes: the code is the entry number). + for _ in 0..l.mux.iter().take_while(|&&m| m == 0).count() { + w.put(1 + u64::from(xorshift(seed)) % 24, 8); + w.put(0, 1); + for _ in 0..2 { + let entry = xorshift(seed) % 16; + for bit in (0..4).rev() { + w.put(u64::from(entry >> bit) & 1, 1); + } + } + } + // The rest is random bits, enough that no residue runs out of packet. + let mut p = w.bytes; + let fixed = p.len(); + p.extend((0..200 + xorshift(seed) as usize % 200).map(|_| xorshift(seed) as u8)); + let _ = fixed; + // The bits after the fixed fields start mid-byte: the last fixed byte keeps its own bits and + // takes random ones above them. + let used = w.bits % 8; + if used != 0 { + let last = fixed - 1; + p[last] |= (xorshift(seed) as u8) << used; + } + if i > 0 { + let size = |long: bool| if long { 1024 } else { 256 }; + granule += (size(longs[i - 1]) / 4 + size(long) / 4) as i64; + } + out.extend(pages.packet(&p, granule)); + } + out.extend(pages.finish(None)); + out +} + +/// `tolerance`: the largest difference from ffmpeg, as a fraction of the peak output. A floor 0 +/// curve is an exponential of a quotient that random coefficients can make very large, so where +/// two floors meet in one stream (ffmpeg computes in single precision, we in double) the results +/// agree only to about a thousandth of the peak. +fn run(name: &str, l: &Layout, seed: u32, tolerance: f32) { + let mut s = seed; + let ogg = stream(l, 40, &mut s); + // Packet by packet our decoder must accept every one. + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let st = &file.streams[0]; + let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("setup decodes"); + let mut total = vec![Vec::new(); usize::from(l.channels)]; + for i in 0..st.packets.len() { + let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet"); + let pcm = dec.decode_packet(&p).unwrap_or_else(|e| panic!("{name}: packet {i}: {e}")); + for (t, c) in total.iter_mut().zip(pcm) { + t.extend(c); + } + } + let expected = usize::try_from(st.last_granule.expect("generated final granule")).expect("nonnegative granule"); + for channel in &total { + assert_eq!(channel.len(), expected, "{name}: decoded sample count"); + assert!(channel.iter().all(|v| v.is_finite()), "{name}: non-finite output"); + } + let whole = decode_ogg(&ogg).expect("whole file"); + assert_eq!(whole.channels, total, "{name}: packet and file decoding differ"); + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("vorbis_synthetic"); + let path = dir.join(format!("{name}.ogg")); + std::fs::write(&path, &ogg).expect("write fixture"); + let out = Command::new(&ffmpeg) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("run ffmpeg"); + assert!(out.status.success(), "{name}: ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); + let all: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + let ch = usize::from(l.channels); + let theirs: Vec> = (0..ch).map(|c| all.iter().skip(c).step_by(ch).copied().collect()).collect(); + assert!(theirs.iter().flatten().all(|v| v.is_finite()), "{name}: non-finite ffmpeg output"); + for channel in &theirs { + assert!(channel.len() >= expected, "{name}: ffmpeg returned fewer than the expected samples"); + } + // ffmpeg puts the channels of surround streams in its own order, so each of ours is matched + // with the channel of theirs it agrees with best, and every one of theirs is used once. + let mut used = vec![false; ch]; + #[allow(clippy::needless_range_loop)] + for c in 0..ch { + let mut best: Option<(usize, f32, f32)> = None; + for (k, t) in theirs.iter().enumerate().filter(|(k, _)| !used[*k]) { + let n = total[c].len().min(t.len()); + assert!(n > 1000, "{name}: only {n} samples to compare"); + let scale = total[c][..n].iter().fold(1e-3f32, |m, v| m.max(v.abs())); + let worst = (0..n).map(|i| (total[c][i] - t[i]).abs()).fold(0f32, f32::max); + if best.is_none_or(|(_, w, sc)| worst / scale < w / sc) { + best = Some((k, worst, scale)); + } + } + let (k, worst, scale) = best.expect("a free channel"); + used[k] = true; + assert!(worst <= tolerance * scale + 1e-5, "{name}: channel {c} differs from ffmpeg's channel {k} by {worst} (peak {scale})"); + } +} + +#[test] +fn mono_floor_zero_and_residue_zero() { + run("mono_f0_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![0], coupling: vec![] }, 11, 1e-4); +} + +#[test] +fn mono_floor_one_and_residue_one() { + run("mono_f1_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![1], coupling: vec![] }, 12, 1e-4); +} + +#[test] +fn two_submaps_floor_zero_and_one() { + run("stereo_mixed", &Layout { channels: 2, residue_types: [0, 1], mux: vec![0, 1], coupling: vec![] }, 13, 3e-3); +} + +#[test] +fn coupled_stereo_residue_two() { + run("stereo_coupled_r2", &Layout { channels: 2, residue_types: [2, 2], mux: vec![1, 1], coupling: vec![(0, 1)] }, 14, 1e-4); +} + +#[test] +fn six_channels_with_coupling_and_submaps() { + let l = Layout { channels: 6, residue_types: [1, 2], mux: vec![0, 0, 0, 1, 1, 1], coupling: vec![(0, 3), (1, 2), (4, 5)] }; + run("six", &l, 15, 3e-3); +} + +#[test] +fn mono_floor_one_and_residue_zero() { + run("mono_f1_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![1], coupling: vec![] }, 16, 1e-4); +} + +#[test] +fn mono_floor_zero_and_residue_one() { + run("mono_f0_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] }, 17, 1e-4); +} + +/// A packet that names a floor 0 codebook that does not exist cannot be decoded (§6.2.2); the +/// decoder says so and the stream goes on with the next packet. +#[test] +fn a_floor_zero_codebook_that_does_not_exist_is_a_packet_error() { + let l = Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] }; + let mut seed = 5u32; + let ogg = stream(&l, 6, &mut seed); + let file = craft_media::ogg::open(ogg.as_slice()).expect("open"); + let st = &file.streams[0]; + let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("decoder"); + let good = file.read_packet(ogg.as_slice(), 0, 0).expect("packet"); + assert!(dec.decode_packet(&good).is_ok()); + // A short block: type 0, mode 0, then the 8 amplitude bits, then book number 1 (only 0 exists). + let mut w = W::default(); + w.flag(false); + w.flag(false); + w.put(9, 8); + w.put(1, 1); + w.put(0, 64); + assert!(matches!(dec.decode_packet(&w.bytes), Err(craft_audio::vorbis::decoder::Error::Packet(_)))); + assert!(dec.decode_packet(&good).is_ok(), "the decoder carries on"); +} diff --git a/crates/cloud-local/Cargo.toml b/crates/cloud-local/Cargo.toml new file mode 100644 index 0000000000..39d6dfa6ef --- /dev/null +++ b/crates/cloud-local/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "craft-cloud-local" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "A reference CloudBackend over a local folder, proving the contract needs no specific provider" + +[lints] +workspace = true + +[dependencies] +# Resolution-time confinement: every path this crate resolves goes through a `Dir` capability +# opened on the configured root, never through an absolute OS path this crate builds itself. +# `craft-font-store` already depends on the lower-level `cap-primitives` for the same family of +# guarantee; this crate uses the ergonomic `cap-std` built on top of it instead of hand-rolling +# the equivalent `Dir`-style API again. +cap-std = "4" +craft-cloud = { workspace = true } +craft-ui = { workspace = true, features = ["cloud"] } + +[dev-dependencies] +tempfile = "3" +egui = { workspace = true } diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md new file mode 100644 index 0000000000..a5006c2ca3 --- /dev/null +++ b/crates/cloud-local/README.md @@ -0,0 +1,39 @@ +# craft-cloud-local + +A reference `CloudBackend` over one folder on disk, proving that `craft-cloud`'s contract needs +no specific provider behind it. + +## No-escape policy + +Every path this crate is handed, a `Job::List`/`Read`/`Write` path or a `Job::Create` name, is +confined to the configured root before anything touches a filesystem, in two layers. + +A path's segments are accepted only when each one parses as a single `Component::Normal`: no +`..`, no `.`, no empty segment, and no absolute form. A `Create` name goes through a stricter +check of its own, since it is one chosen name and not a path: it additionally refuses a +backslash, a colon, or a Windows reserved device name (`CON`, `COM1`, `CONIN$`, and so on), on +every platform this crate builds for, not only on Windows, because a chosen name reaches this +backend from whatever platform the UI runs on. An existing name that already has one of those +characters, discovered through `list`, stays reachable: `:` and `\` are not path separators on +any platform's filesystem, so refusing to read a real file back because of a byte in its name +(macOS stores a `/` typed in Finder as `:` on disk) would be a usability bug with no matching +security benefit. + +The second layer is the one that actually keeps resolution inside the root: every already +segment-checked relative path is handed to a [`cap-std`](https://docs.rs/cap-std) `Dir` +capability opened on the root, never joined onto the root as an absolute OS path this crate +builds itself. `cap-std` resolves one path component at a time against real, already-open +directory handles, so a symlink or (on Windows) a directory junction anywhere under the root, +dangling or already pointing outside, cannot walk resolution above the root. There is no separate +"does this still look like it is inside the root" check with a window for the directory tree to +change underneath it between the check and the actual read or write; the one resolution is the +open. + +## Hard links + +A hard link is not a symlink, and this backend does not refuse one: from inside the sandbox the +inode it names is an ordinary file. What it protects instead is the shared inode's content: a +write never truncates its target in place. It writes a new sibling file and renames that sibling +over the target, so the target's directory entry is replaced rather than its bytes being +overwritten. A rename only ever changes one name; it does not reach through to any other name, +inside the root or out, that happens to point at the same inode. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs new file mode 100644 index 0000000000..b3cf5cbe9d --- /dev/null +++ b/crates/cloud-local/src/lib.rs @@ -0,0 +1,510 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! A reference [`CloudBackend`] that treats one folder on disk as the cloud. +//! +//! [`craft_ui::cloud::CloudBackend`] names a contract and nothing about who +//! answers it. This crate is the proof: a working implementation that reaches +//! no service, a vendor, or a personal repo anybody else has to trust. An app +//! wires [`LocalBackend`] the same way it would wire a provider's own client, +//! by calling [`craft_ui::cloud::CloudFiles::connect`]. Swapping one for the +//! other is the whole point; nothing above the [`CloudBackend`] seam can tell +//! the difference. +//! +//! What this is not: a sync engine, a sharing service, or a place to keep a +//! credential. A folder has no concept of another account, so +//! [`Job::SharedWithMe`] answers empty and [`Job::Conversation`] answers with +//! a [`Fault`], and [`Account::capabilities`] claims neither. Reporting a +//! capability this backend cannot honour would be the broken window the +//! contract's own docs warn about. +//! +//! Every job answers on its own [`std::thread`]. [`CloudBackend::submit`] +//! must return before the file is opened, let alone read, or a twenty +//! megabyte document would freeze the window that called it. +//! +//! # The no-escape policy +//! +//! `Entry::id` and `Entry::path` are the same slash-separated path relative to +//! `root`, always starting with `/` below the root itself (the root's own +//! path is the empty string, matching [`Job::List`]'s contract), and a +//! [`Job::Create`] name is one plain file name, not a path at all. Neither is +//! an OS path string handed to `std::fs`. Confinement happens in two layers: +//! +//! 1. [`confine_segment`] (every path segment) and [`confine_name`] (a +//! `Create` name, stricter) reject `..`, `.`, an empty segment, an +//! absolute form, and anything that is not exactly one +//! [`std::path::Component::Normal`]. `confine_name` additionally refuses a +//! backslash, a colon, and a Windows reserved device name +//! (`CON`, `COM1`, `CONIN$`, ...) on every platform this crate builds for, +//! because a chosen name reaches this backend from whatever platform the +//! UI runs on. Browsing an *existing* name is more lenient: a literal `:` +//! or `\` already on disk (macOS stores a `/` typed in Finder as `:`) is +//! not itself a path separator on any platform's filesystem, so +//! `confine_segment` lets `list`, `read` and `write` keep such a name +//! reachable instead of discovering it and then refusing to open it. +//! 2. [`open_root`] opens `root` as a [`cap_std::fs::Dir`] capability once per +//! job. Every [`list`], [`read`], [`write`] and [`create`] routes its +//! already-segment-checked relative path through that one `Dir`, never +//! through an absolute OS path built by this crate. `cap_std` resolves one +//! component at a time against real, already-open directory handles, so a +//! symlink or a Windows junction anywhere under `root`, dangling or not, +//! cannot walk resolution above `root`: there is no separate "is this +//! still inside the root" check with a window for the directory tree to +//! change underneath it, because the one resolution *is* the open. +//! +//! A hard link is not a symlink and `cap_std` does not refuse one; the inode +//! it names is an ordinary file from inside the sandbox. [`write`] protects +//! it a different way: it always writes a sibling temporary file and renames +//! it over the target, rather than truncating the target in place. A rename +//! replaces one name's directory entry; it never reaches through to another +//! name that happens to point at the same inode outside `root`. + +use std::ffi::OsStr; +use std::fs; +use std::io::{Read as _, Write as _}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use cap_std::fs::{Dir, OpenOptions}; +use craft_cloud::{Capability, Entry, EntryKind}; +use craft_ui::cloud::{Account, CloudBackend, Event, Fault, Job, Post}; + +/// Where "the cloud" lives for this backend: one directory on disk. +pub struct LocalBackend { + root: PathBuf, + /// Shown in the account badge. Nothing else reads it. + display: String, +} + +impl LocalBackend { + /// Treat `root` as the cloud. The directory is not created here; a + /// listing of a root that does not exist yet answers with a [`Fault`] + /// the same way a real provider's missing folder would. [`Job::Create`] + /// is the one exception, and always has been: it brings a fresh root + /// into existence itself, the same way a first Save As does not require + /// the destination folder to already be there. + pub fn new(root: PathBuf) -> LocalBackend { + LocalBackend { root, display: "Local disk".to_owned() } + } + + /// Name shown in the account badge, in place of the default "Local disk". + pub fn named(mut self, display: impl Into) -> LocalBackend { + self.display = display.into(); + self + } +} + +impl CloudBackend for LocalBackend { + fn submit(&self, job: Job, post: Post) { + let root = self.root.clone(); + match job { + // Nothing is saved between runs and nothing was ever signed into, + // so there is nothing to forget. The trait states no answer for + // this job; CloudFiles::sign_out clears its own state regardless + // of whether anything ever arrives. + Job::SignOut => {} + Job::Account | Job::SignIn => { + let display = self.display.clone(); + std::thread::spawn(move || post.send(Event::Account(Ok(account(display))))); + } + // There is no browser round trip: a local folder is already + // "linked" the moment it exists. Reporting that immediately, + // rather than inventing a URL nobody needs to visit, is what the + // contract calls honest. + Job::LinkStart | Job::LinkPoll(_) => { + std::thread::spawn(move || post.send(Event::Linked(Ok(true)))); + } + Job::List(path) => { + std::thread::spawn(move || post.send(Event::Listed { entries: list(&root, &path), path })); + } + Job::SharedWithMe => { + std::thread::spawn(move || post.send(Event::Shared(Ok(Vec::new())))); + } + Job::Read { entry, into } => { + std::thread::spawn(move || match read(&root, &entry) { + Ok((entry, bytes)) => post.send(Event::Read { entry, into, bytes: Ok(bytes) }), + Err(fault) => post.send(Event::Read { entry, into, bytes: Err(fault) }), + }); + } + Job::Write { uid, entry, bytes } => { + std::thread::spawn(move || post.send(Event::Saved { uid, entry: write(&root, &entry, &bytes) })); + } + Job::Create { uid, folder, name, bytes } => { + std::thread::spawn(move || post.send(Event::Saved { uid, entry: create(&root, &folder, &name, &bytes) })); + } + // No sharing, no accounts beyond this one, and so nowhere for a + // conversation to live. A reference backend that invented one + // would be lying about what a folder on disk can do. + Job::Conversation(_) => { + std::thread::spawn(move || { + post.send(Event::Conversation(Err(Fault::Refused("this reference backend has no shared workspace to converse in".to_owned())))) + }); + } + } + } +} + +fn account(display: String) -> Account { + Account { display, capabilities: vec![Capability::Files, Capability::Etags], provider_linked: true } +} + +/// Turns a [`Job`]'s slash-separated path into a path relative to `root`, +/// refusing anything that is not a run of ordinary names. The result is +/// never joined onto `root` as an OS path; every caller hands it to a +/// [`cap_std::fs::Dir`] opened on `root` instead, which is the layer that +/// actually keeps resolution from leaving `root`. +/// +/// `.` and repeated or leading slashes are just an empty segment and are +/// skipped, the same way a browser's address bar collapses them. Every other +/// segment goes through [`confine_segment`]. +fn relative(path: &str) -> Result { + let mut rel = PathBuf::new(); + for segment in path.split('/') { + if segment.is_empty() || segment == "." { + continue; + } + rel.push(confine_segment(segment)?); + } + Ok(rel) +} + +/// Confines one path segment to a single ordinary file or folder name. +/// +/// Accepted only when `segment` parses as exactly one [`Component::Normal`] +/// equal to `segment` itself: no empty name, no `.` or `..`, no absolute +/// form, and nothing left over for a second component to hide in. +/// +/// This is deliberately lenient about an ordinary character such as `:` or +/// `\` that is not, on its own, a path separator on any platform's +/// filesystem: `list` discovers real names from disk, and a name containing +/// one of those (macOS stores a `/` typed in Finder as `:` on disk) must stay +/// reachable by a later `read` or `write`, not become visible-but-unopenable. +/// [`confine_name`] is the stricter check for a name being chosen new, where +/// refusing those characters costs nothing and closes a real escape. +fn confine_segment(segment: &str) -> Result<&str, Fault> { + let mut components = Path::new(segment).components(); + match (components.next(), components.next()) { + (Some(Component::Normal(name)), None) if name == OsStr::new(segment) => Ok(segment), + _ => Err(Fault::Refused(format!("{segment} is not a plain file name"))), + } +} + +/// Windows device names that name a device rather than a file, with or +/// without a trailing extension (`CON`, `con.txt`, ...). Checked on every +/// platform: a name chosen here can end up read on a Windows client too. +const WINDOWS_RESERVED_NAMES: &[&str] = &[ + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", + "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", +]; + +fn is_windows_reserved_name(name: &str) -> bool { + let stem = name.split('.').next().unwrap_or(name); + WINDOWS_RESERVED_NAMES.iter().any(|reserved| stem.eq_ignore_ascii_case(reserved)) +} + +/// Confines a [`Job::Create`] `name` to a single ordinary file name that is +/// safe to choose on any platform, not only the one this crate is built for. +/// +/// Stricter than [`confine_segment`]: a backslash or colon is refused +/// outright first, because a Unix build's [`Component`] parser does not +/// treat either as a separator and would wave a Windows drive letter or UNC +/// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A +/// Windows reserved device name is refused the same way. None of this costs +/// anything here, unlike applying it to a name `list` merely discovered. +fn confine_name(name: &str) -> Result<&str, Fault> { + if name.contains('\\') || name.contains(':') { + return Err(Fault::Refused(format!("{name} is not a plain file name"))); + } + if is_windows_reserved_name(name) { + return Err(Fault::Refused(format!("{name} is a reserved device name on Windows"))); + } + confine_segment(name) +} + +/// Opens `root` as the one ambient-authority capability this crate holds. +/// Every other path in this crate is resolved relative to the [`Dir`] this +/// returns, never as an absolute OS path built by string concatenation. +fn open_root(root: &Path) -> Result { + Dir::open_ambient_dir(root, cap_std::ambient_authority()).map_err(|error| io_fault(&error)) +} + +/// The path a listed child gets, given the folder it was found in. +fn child_path(folder: &str, name: &str) -> String { + format!("{}/{name}", folder.trim_end_matches('/')) +} + +/// An opaque version token for a file's current bytes. +/// +/// Not a timestamp for a person to read (that would go through `chrono`, per +/// this workspace's rule); just enough to tell "the file I read" from "the +/// file as it is now" apart, which is all a conditional write needs. +fn etag_of(meta: &cap_std::fs::Metadata) -> String { + let stamp = + meta.modified().ok().and_then(|time| time.duration_since(cap_std::time::SystemClock::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0); + format!("{}-{stamp}", meta.len()) +} + +fn io_fault(error: &std::io::Error) -> Fault { + use std::io::ErrorKind; + match error.kind() { + ErrorKind::NotFound => Fault::Refused("no such file or folder".to_owned()), + ErrorKind::PermissionDenied => Fault::Refused("permission denied".to_owned()), + _ => Fault::Unreachable(error.to_string()), + } +} + +fn list(root: &Path, path: &str) -> Result, Fault> { + let rel = relative(path)?; + let dir = open_root(root)?; + let read = if rel.as_os_str().is_empty() { dir.entries() } else { dir.read_dir(&rel) }; + let read = read.map_err(|error| io_fault(&error))?; + let mut entries = Vec::new(); + for item in read { + let item = item.map_err(|error| io_fault(&error))?; + let meta = item.metadata().map_err(|error| io_fault(&error))?; + let name = item.file_name().to_string_lossy().into_owned(); + let id = child_path(path, &name); + entries.push(Entry { + room: format!("local:{id}"), + name, + kind: if meta.is_dir() { EntryKind::Folder } else { EntryKind::File }, + size: if meta.is_dir() { None } else { Some(meta.len()) }, + modified: None, + mime: None, + etag: if meta.is_dir() { None } else { Some(etag_of(&meta)) }, + writable: true, + shared_by: None, + path: id.clone(), + id, + }); + } + entries.sort_by(|a, b| (a.kind != EntryKind::Folder, &a.name).cmp(&(b.kind != EntryKind::Folder, &b.name))); + Ok(entries) +} + +/// Reads a file's bytes together with the entry for the version just read. +/// +/// The entry is built from a fresh metadata call here, not handed back +/// unchanged from what the caller already believed. A reload after a conflict +/// hands in the stale entry it is trying to get past; echoing that back would +/// carry the old etag into the reloaded document, so the very next save would +/// conflict again on a copy that is actually current. +/// +/// Refuses outright if `entry.id` names a symlink, the same policy `write` +/// uses: this backend never reports the bytes of whatever a link happens to +/// point at, inside `root` or out. +fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { + let rel = relative(&entry.id)?; + let dir = open_root(root)?; + // Stats without following only the last component; every component + // before it is still resolved, and sandboxed, normally, so a link + // earlier in `rel` is refused by `open_root`'s `Dir` itself when `open` + // below walks it, never silently followed here either way. + match dir.symlink_metadata(&rel) { + Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(io_fault(&error)), + } + let mut file = dir.open(&rel).map_err(|error| io_fault(&error))?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(|error| io_fault(&error))?; + let meta = file.metadata().map_err(|error| io_fault(&error))?; + let fresh = Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }; + Ok((fresh, bytes)) +} + +/// Saves back over `entry`, refusing the write when the file moved on since +/// `entry.etag` was read. A file that no longer exists has nothing to +/// conflict with, the same way a provider treats a deleted document. +/// +/// Never truncates `entry.id`'s current bytes in place. [`write_replacing`] +/// writes a sibling temporary file and renames it over the target instead, +/// so a hard link sharing the target's inode keeps its own, unmodified copy: +/// the rename replaces `entry.id`'s directory entry, and never reaches +/// through to any other name pointing at the same inode. +fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { + let rel = relative(&entry.id)?; + let dir = open_root(root)?; + match dir.symlink_metadata(&rel) { + Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) => { + if Some(etag_of(&meta)) != entry.etag { + return Err(Fault::Conflict); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(io_fault(&error)), + } + if let Some(parent) = rel.parent() { + dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; + } + write_replacing(&dir, &rel, bytes)?; + let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) +} + +/// The next in a run of sibling temporary names, unique within this process. +/// Not meant to resist a second process picking the same name; the create +/// this writes with is exclusive (`create_new`), so a collision there is +/// just retried under a new counter value rather than silently overwritten. +static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); + +/// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that +/// sibling over `rel`. See the module docs for why: a direct write would +/// truncate whatever `rel` currently names in place, and if that happens to +/// be a hard link to a file outside `root`, the outside copy would be +/// corrupted along with it. A rename only ever replaces `rel`'s own +/// directory entry. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { + let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; + let mut temp_name = OsStr::new(".").to_os_string(); + temp_name.push(name); + temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed))); + let temp_rel = match rel.parent() { + Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name), + _ => PathBuf::from(&temp_name), + }; + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + let written = (|| -> Result<(), Fault> { + let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?; + handle.write_all(bytes).map_err(|error| io_fault(&error))?; + handle.sync_all().map_err(|error| io_fault(&error)) + })(); + if let Err(fault) = written { + let _ = dir.remove_file(&temp_rel); + return Err(fault); + } + if let Err(error) = dir.rename(&temp_rel, dir, rel) { + let _ = dir.remove_file(&temp_rel); + return Err(io_fault(&error)); + } + Ok(()) +} + +fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { + // `name` is never a path: it is one `Job::Create` field that names the + // new file, so it goes through `confine_name` directly rather than + // through `relative`, which only ever splits and confines a slash path. + let name = confine_name(name)?; + // `root` is the operator-configured boundary, never attacker input, so + // creating it directly with `std::fs` is safe; this is also the one + // place that has always brought a fresh root into existence (see + // `LocalBackend::new`'s docs), and `Dir::open_ambient_dir` below needs it + // to already exist. + fs::create_dir_all(root).map_err(|error| io_fault(&error))?; + let dir = open_root(root)?; + let rel_folder = relative(folder)?; + dir.create_dir_all(&rel_folder).map_err(|error| io_fault(&error))?; + let rel = rel_folder.join(name); + // Exclusive creation, not an `exists` check ahead of a separate write: two + // creates of the same name racing both see "not there yet" otherwise, and + // the second write silently replaces the first with neither ever refused. + // `create_new` asks the filesystem to open and create in one step, so the + // loser gets an error instead of a chance to overwrite the winner. It also + // refuses outright when `name` already exists as a symlink, dangling or + // not: `O_EXCL` never follows one to decide whether it is "in the way". + let mut create_options = OpenOptions::new(); + create_options.write(true).create_new(true); + let mut handle = match dir.open_with(&rel, &create_options) { + Ok(handle) => handle, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + return Err(Fault::Refused(format!("{name} already exists"))); + } + Err(error) => return Err(io_fault(&error)), + }; + handle.write_all(bytes).map_err(|error| io_fault(&error))?; + drop(handle); + let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let id = child_path(folder, name); + Ok(Entry { + room: format!("local:{id}"), + name: name.to_owned(), + kind: EntryKind::File, + size: Some(meta.len()), + modified: None, + mime: None, + etag: Some(etag_of(&meta)), + writable: true, + shared_by: None, + path: id.clone(), + id, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_parent_segment_cannot_walk_out_of_root() { + assert!(relative("../secrets").is_err()); + assert!(relative("Archive/../../../etc/passwd").is_err()); + } + + #[test] + fn repeated_and_trailing_slashes_collapse_like_a_browser_address_bar() { + assert_eq!(relative("//Archive//2026/").unwrap(), Path::new("Archive").join("2026")); + assert_eq!(relative("").unwrap(), PathBuf::new()); + } + + #[test] + fn confine_segment_accepts_only_a_single_ordinary_name() { + for ordinary in ["Minutes.txt", "Archive", "2026", "a name with spaces.docx"] { + assert!(confine_segment(ordinary).is_ok(), "{ordinary} is an ordinary name"); + } + } + + #[test] + fn confine_segment_refuses_empty_dot_and_dot_dot() { + for bad in ["", ".", ".."] { + assert!(confine_segment(bad).is_err(), "{bad:?} is not a single ordinary name"); + } + } + + #[test] + fn confine_segment_refuses_a_slash_hidden_inside_a_create_name() { + assert!(confine_segment("folder/evil").is_err()); + assert!(confine_segment("../outside.txt").is_err()); + assert!(confine_segment("/outside.txt").is_err()); + } + + /// The fix for the non-blocking finding that `list` made a real macOS + /// name (a literal `/`, stored on disk as `:`) visible but unreadable: an + /// existing name with an ordinary `:` byte is not refused by the lenient + /// per-segment check, only by `confine_name` for a chosen one. A literal + /// `\` is not tested the same way here: on a Windows build it really is + /// a second path component (`std::path::Component` already splits on + /// it), so there is no existing-name case for `confine_segment` to stay + /// lenient about cross-platform the way there is for `:`. + #[test] + fn confine_segment_tolerates_a_colon_already_on_disk() { + assert!(confine_segment("weird:name.txt").is_ok()); + assert!(relative("weird:name.txt").is_ok()); + } + + #[test] + fn confine_name_refuses_backslash_and_colon_on_every_platform() { + for bad in ["..\\outside.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"] { + assert!(confine_name(bad).is_err(), "{bad:?} must be refused on every platform, not only on Windows"); + } + } + + #[test] + fn confine_name_refuses_windows_reserved_device_names() { + for bad in ["CON", "con", "con.txt", "NUL", "COM1", "lpt9.log", "CONIN$"] { + assert!(confine_name(bad).is_err(), "{bad:?} names a Windows device, not a file"); + } + for ordinary in ["console.txt", "NULLABLE.md", "COM10"] { + assert!(confine_name(ordinary).is_ok(), "{ordinary} only resembles a reserved name"); + } + } + + #[test] + fn a_folder_announces_no_capability_this_backend_cannot_honour() { + let reported = account("Local disk".to_owned()).capabilities; + for absent in [Capability::SharedWithMe, Capability::Sharing, Capability::Conversation, Capability::Contacts] { + assert!(!reported.contains(&absent), "a folder has no {absent:?}"); + } + } +} diff --git a/crates/cloud-local/tests/backend.rs b/crates/cloud-local/tests/backend.rs new file mode 100644 index 0000000000..d2a9fd4e55 --- /dev/null +++ b/crates/cloud-local/tests/backend.rs @@ -0,0 +1,244 @@ +//! Drives [`craft_cloud_local::LocalBackend`] the way an app does: through +//! `craft_ui::cloud`'s own public functions, never by calling the backend +//! directly. That is the seam this crate exists to prove, so the tests stay +//! on the application's side of it. + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_cloud::{Entry, EntryKind}; +use craft_cloud_local::LocalBackend; +use craft_ui::cloud::{self, Account, CloudApp, CloudFiles, Destination, DocumentKind, Job}; + +const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" }; + +/// A document the harness was told to open: its name and its bytes. +type OpenedDocs = Arc)>>>; + +/// The least a [`CloudApp`] can be. What it was told to open is recorded, so a +/// round trip can be checked by content and not only by the entry metadata +/// `craft_ui` itself remembers. +struct Harness { + cloud: CloudFiles, + share: craft_ui::share::ShareDialog, + presence: craft_ui::presence::PresenceBar, + opened: OpenedDocs, + said: Arc>>, +} + +impl Harness { + fn new() -> Harness { + Harness { + cloud: CloudFiles::new(), + share: craft_ui::share::ShareDialog::new(), + presence: craft_ui::presence::PresenceBar::new(), + opened: Arc::new(Mutex::new(Vec::new())), + said: Arc::new(Mutex::new(Vec::new())), + } + } +} + +impl CloudApp for Harness { + fn cloud(&self) -> &CloudFiles { + &self.cloud + } + + fn cloud_mut(&mut self) -> &mut CloudFiles { + &mut self.cloud + } + + fn kind(&self) -> DocumentKind { + NOTE + } + + fn active(&self) -> Option { + None + } + + fn title(&self, _uid: u64) -> String { + String::new() + } + + fn open_bytes(&mut self, name: &str, bytes: Vec) -> Result, String> { + self.opened.lock().unwrap().push((name.to_owned(), bytes)); + Ok(Some(1)) + } + + fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result, String> { + Ok(Vec::new()) + } + + fn close(&mut self, _uid: u64) {} + + fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog { + &mut self.share + } + + fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar { + &mut self.presence + } + + fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {} + + fn open_url(&self, _url: &str) {} + + fn say(&mut self, text: String) { + self.said.lock().unwrap().push(text); + } + + fn app_name(&self) -> &str { + "Harness" + } +} + +fn wired(root: std::path::PathBuf) -> (Harness, egui::Context) { + let mut app = Harness::new(); + app.cloud.connect(LocalBackend::new(root)); + (app, egui::Context::default()) +} + +/// Drains whatever the backend's worker threads have sent so far, until +/// `done` says the state the test is waiting for arrived or five seconds pass. +/// Five seconds is far more than a thread doing local file IO ever needs; it +/// only guards against a real bug leaving the test to hang forever. +fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) { + let start = Instant::now(); + loop { + ctx.begin_pass(Default::default()); + cloud::pump(app, ctx); + ctx.end_pass().textures_delta.clear(); + if done(app) { + return; + } + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +#[test] +fn account_and_sign_in_report_the_same_fixed_identity_with_no_browser_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::start(&mut app); + settle(&mut app, &ctx, |app| app.cloud().account.is_some()); + + assert_eq!( + app.cloud().account, + Some(Account { + display: "Local disk".to_owned(), + capabilities: vec![craft_cloud::Capability::Files, craft_cloud::Capability::Etags], + provider_linked: true + }) + ); + // There was never an account to link, so nothing was ever offered. + assert!(app.cloud().link.is_none()); +} + +#[test] +fn creating_a_document_writes_real_bytes_a_read_gets_back() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"first draft".to_vec() }); + settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1)); + + let entry = app.cloud().origins.get(&1).unwrap().entry.clone(); + assert_eq!(entry.name, "Minutes.txt"); + assert_eq!(entry.id, "/Minutes.txt"); + assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"first draft"); + + cloud::submit(&app, Job::Read { entry, into: None }); + settle(&mut app, &ctx, |app| !app.opened.lock().unwrap().is_empty()); + + let opened = app.opened.lock().unwrap().clone(); + assert_eq!(opened, vec![("Minutes.txt".to_owned(), b"first draft".to_vec())], "the read got back exactly what the create wrote"); +} + +#[test] +fn a_write_under_a_stale_version_is_refused_and_never_overwrites_the_newer_file() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"v1".to_vec() }); + settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1)); + let stale = app.cloud().origins.get(&1).unwrap().entry.clone(); + + // Somebody else saves first, changing the file's etag without going + // through this window at all. + std::fs::write(dir.path().join("Minutes.txt"), b"somebody else's edit").unwrap(); + + cloud::submit(&app, Job::Write { uid: 1, entry: stale, bytes: b"this window's edit".to_vec() }); + settle(&mut app, &ctx, |app| app.cloud().conflict.is_some()); + + assert_eq!(app.cloud().conflict.as_ref().unwrap().uid, 1); + assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"somebody else's edit", "the refused write never touched the file"); +} + +#[test] +fn listing_the_root_reflects_a_file_nobody_went_through_this_backend_to_write() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Agenda.txt"), b"1. roll call").unwrap(); + std::fs::create_dir(dir.path().join("Archive")).unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::browse(&mut app, ""); + settle(&mut app, &ctx, |app| app.cloud().mine.loaded); + + let names: Vec<_> = app.cloud().mine.entries.iter().map(|entry| entry.name.clone()).collect(); + assert_eq!(names, vec!["Archive".to_owned(), "Agenda.txt".to_owned()], "folders first, then files, each alphabetised"); + let folder = app.cloud().mine.entries.iter().find(|entry| entry.name == "Archive").unwrap(); + assert_eq!(folder.kind, EntryKind::Folder); + assert!(folder.size.is_none()); +} + +#[test] +fn nobody_has_shared_anything_with_a_folder() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::load_shared(&mut app); + settle(&mut app, &ctx, |app| app.cloud().shared.loaded); + + assert_eq!(app.cloud().shared.entries, Vec::new()); + assert!(app.cloud().shared.error.is_none(), "an empty share list is not a failure"); +} + +#[test] +fn a_conversation_is_a_fault_this_backend_is_honest_about() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + cloud::submit(&app, Job::Conversation("/Minutes.txt".to_owned())); + settle(&mut app, &ctx, |app| app.cloud().status.is_some()); + + assert_eq!(app.cloud().status, Some("this reference backend has no shared workspace to converse in".to_owned())); +} + +#[test] +fn a_read_of_a_document_that_is_not_there_is_put_to_the_user_not_silently_dropped() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = wired(dir.path().to_path_buf()); + + let ghost = Entry { + id: "/ghost.txt".to_owned(), + room: "local:/ghost.txt".to_owned(), + name: "ghost.txt".to_owned(), + path: "/ghost.txt".to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + }; + cloud::submit(&app, Job::Read { entry: ghost, into: None }); + settle(&mut app, &ctx, |app| !app.said.lock().unwrap().is_empty()); + + assert!(app.said.lock().unwrap()[0].contains("ghost.txt"), "the message names the document, not just that something failed"); +} + +fn fs_read(root: &std::path::Path, name: &str) -> Vec { + std::fs::read(root.join(name)).unwrap() +} diff --git a/crates/cloud-local/tests/confinement_regressions.rs b/crates/cloud-local/tests/confinement_regressions.rs new file mode 100644 index 0000000000..6356e51500 --- /dev/null +++ b/crates/cloud-local/tests/confinement_regressions.rs @@ -0,0 +1,431 @@ +//! Confinement regressions for `crates/cloud-local`. The first round (FredApps' re-review) found +//! that `resolve` only split on `/` and rejected a segment equal to `..`, with no constraint on a +//! Windows backslash, a drive letter or UNC prefix, or a filesystem link, and that `create` +//! joined `name` onto the resolved folder with no validation of `name` at all. The second round +//! (benandez's re-review) reproduced three escapes the first fix still left open: a dangling +//! symlink, a check-then-use race on a swapped link, and a hard link sharing a file's inode. +//! Driven through `craft_ui::cloud`'s public functions the way an application does, with a +//! sentinel file and directory kept as a sibling of the configured root: every test here must +//! leave both untouched and unread. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_cloud::{Entry, EntryKind}; +use craft_cloud_local::LocalBackend; +use craft_ui::cloud::{self, CloudApp, CloudFiles, Destination, DocumentKind, Job}; + +const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" }; + +/// A document the harness was told to open: its name and its bytes. +type OpenedDocs = Arc)>>>; + +struct Harness { + cloud: CloudFiles, + share: craft_ui::share::ShareDialog, + presence: craft_ui::presence::PresenceBar, + opened: OpenedDocs, + said: Arc>>, +} + +impl Harness { + fn new() -> Harness { + Harness { + cloud: CloudFiles::new(), + share: craft_ui::share::ShareDialog::new(), + presence: craft_ui::presence::PresenceBar::new(), + opened: Arc::new(Mutex::new(Vec::new())), + said: Arc::new(Mutex::new(Vec::new())), + } + } +} + +impl CloudApp for Harness { + fn cloud(&self) -> &CloudFiles { + &self.cloud + } + fn cloud_mut(&mut self) -> &mut CloudFiles { + &mut self.cloud + } + fn kind(&self) -> DocumentKind { + NOTE + } + fn active(&self) -> Option { + None + } + fn title(&self, _uid: u64) -> String { + String::new() + } + fn open_bytes(&mut self, name: &str, bytes: Vec) -> Result, String> { + self.opened.lock().unwrap().push((name.to_owned(), bytes)); + Ok(Some(1)) + } + fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result, String> { + Ok(Vec::new()) + } + fn close(&mut self, _uid: u64) {} + fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog { + &mut self.share + } + fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar { + &mut self.presence + } + fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {} + fn open_url(&self, _url: &str) {} + fn say(&mut self, text: String) { + self.said.lock().unwrap().push(text); + } + fn app_name(&self) -> &str { + "Harness" + } +} + +fn wired(root: PathBuf) -> (Harness, egui::Context) { + let mut app = Harness::new(); + app.cloud.connect(LocalBackend::new(root)); + (app, egui::Context::default()) +} + +/// Drains whatever the backend's worker threads have sent so far, until `done` says the state +/// the test is waiting for arrived or five seconds pass. Five seconds is far more than a thread +/// doing local file IO ever needs; it only guards against a real bug leaving the test to hang. +fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) { + let start = Instant::now(); + loop { + ctx.begin_pass(Default::default()); + cloud::pump(app, ctx); + ctx.end_pass().textures_delta.clear(); + if done(app) { + return; + } + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Clears both event sinks, then waits for the next job to land in either one. Clearing first +/// matters for a test that submits several jobs in a loop: without it, a stale `said` from two +/// iterations ago would satisfy `settle` immediately, before the new job had actually answered. +fn said(app: &mut Harness, ctx: &egui::Context) -> Vec { + app.opened.lock().unwrap().clear(); + app.said.lock().unwrap().clear(); + settle(app, ctx, |app| !app.said.lock().unwrap().is_empty() || !app.opened.lock().unwrap().is_empty()); + app.said.lock().unwrap().clone() +} + +/// A tempdir holding the cloud root, plus a sentinel file and a sentinel directory that sit +/// beside it rather than inside it. Every test below must leave both exactly as they start. +struct Sentinels { + // Kept only so the tempdir outlives every test that borrows the paths below; nothing reads + // it back once the paths it was built from are in hand. + _arena: tempfile::TempDir, + root: PathBuf, + sentinel_file: PathBuf, + sentinel_dir: PathBuf, +} + +const SENTINEL_FILE_BYTES: &[u8] = b"a sibling file this backend must never read or write"; +const SENTINEL_DIR_FILE_BYTES: &[u8] = b"a sibling directory this backend must never list"; + +fn sentinels() -> Sentinels { + let arena = tempfile::tempdir().unwrap(); + let root = arena.path().join("root"); + std::fs::create_dir(&root).unwrap(); + let sentinel_file = arena.path().join("sentinel.txt"); + std::fs::write(&sentinel_file, SENTINEL_FILE_BYTES).unwrap(); + let sentinel_dir = arena.path().join("sentinel-dir"); + std::fs::create_dir(&sentinel_dir).unwrap(); + std::fs::write(sentinel_dir.join("secret.txt"), SENTINEL_DIR_FILE_BYTES).unwrap(); + Sentinels { _arena: arena, root, sentinel_file, sentinel_dir } +} + +fn assert_sentinels_untouched(sentinels: &Sentinels) { + assert_eq!(std::fs::read(&sentinels.sentinel_file).unwrap(), SENTINEL_FILE_BYTES, "the sentinel file outside the root was changed"); + assert_eq!( + std::fs::read(sentinels.sentinel_dir.join("secret.txt")).unwrap(), + SENTINEL_DIR_FILE_BYTES, + "the sentinel directory's file outside the root was changed" + ); +} + +/// Every one of these is a [`Job::Create`] `name` that must be refused before any byte reaches +/// disk: the review's own examples (a parent segment, an absolute path, and the three +/// Windows-shaped forms), none of which a Unix build's native parser alone would catch, and a +/// name that already is nothing but a Windows separator or drive prefix on top of that. +fn malicious_create_names() -> Vec<&'static str> { + vec!["../sentinel.txt", "/sentinel.txt", "..\\sentinel.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"] +} + +#[test] +fn create_refuses_every_escaping_name_and_the_sentinels_stay_untouched() { + for name in malicious_create_names() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + + cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: name.to_owned(), bytes: b"pwned".to_vec() }); + let messages = said(&mut app, &ctx); + + assert!(cloud::origin(&app).is_none(), "{name:?} must not be reported as created"); + assert!(!messages.is_empty(), "{name:?} must be refused, not silently dropped"); + assert_sentinels_untouched(&sentinels); + } +} + +// ------------------------------------------------------------------- link-based escapes +// +// `escape(&sentinels)` places one link named `escape` inside the cloud root, pointing out to +// `sentinels.sentinel_dir`: a symlink on Unix, a directory junction on Windows, which needs no +// elevated privilege, unlike a Windows symlink. The Linux gate runs the symlink half of every +// test below; CI's windows-latest lanes run the junction half. Either way `root/escape/...` +// reaches into the sentinel directory through the link. + +/// Nothing to clean up on Unix: `tempfile`'s own recursive removal of the arena directory +/// removes a plain symlink entry without following it. This exists only so `escape` returns the +/// same shape of RAII handle on every platform, rather than a bare `()` some lint would flag. +#[cfg(unix)] +struct Linked; + +#[cfg(unix)] +fn escape(sentinels: &Sentinels) -> Linked { + std::os::unix::fs::symlink(&sentinels.sentinel_dir, sentinels.root.join("escape")).unwrap(); + Linked +} + +/// A directory junction, removed on drop before the tempdir it sits beside is cleaned up. +#[cfg(windows)] +struct Junction(PathBuf); + +#[cfg(windows)] +impl Drop for Junction { + fn drop(&mut self) { + let _ = std::fs::remove_dir(&self.0); + } +} + +#[cfg(windows)] +fn escape(sentinels: &Sentinels) -> Junction { + use std::os::windows::process::CommandExt as _; + let link = sentinels.root.join("escape"); + let target = &sentinels.sentinel_dir; + 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) +} + +/// An [`Entry`] stub naming `id`, for a [`Job::Read`] or [`Job::Write`] this file submits +/// directly rather than through an entry the backend itself handed back. +fn leaked_entry(id: &str, name: &str) -> Entry { + Entry { + id: id.to_owned(), + room: format!("local:{id}"), + name: name.to_owned(), + path: id.to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + } +} + +#[cfg(any(unix, windows))] +#[test] +fn listing_a_linked_folder_cannot_see_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::browse(&mut app, "escape"); + settle(&mut app, &ctx, |app| app.cloud().mine.loaded); + + assert!(app.cloud().mine.error.is_some(), "listing through a symlink or junction out of the root must be refused"); + assert!(app.cloud().mine.entries.is_empty()); + assert_sentinels_untouched(&sentinels); +} + +#[cfg(any(unix, windows))] +#[test] +fn reading_through_a_linked_folder_cannot_return_bytes_from_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::submit(&app, Job::Read { entry: leaked_entry("/escape/secret.txt", "secret.txt"), into: None }); + said(&mut app, &ctx); + + assert!(app.opened.lock().unwrap().is_empty(), "a read through a symlink or junction out of the root must not deliver bytes"); + assert_sentinels_untouched(&sentinels); +} + +/// benandez's finding 4: the original version of this test targeted the pre-existing +/// `secret.txt`, with `etag: None`. `write` refused that for an unrelated reason, a version +/// mismatch, before confinement ever ran, so the test passed whether or not confinement worked. +/// Targeting a name that does not exist yet under the link reaches the code that actually +/// matters, and the oracle (the file must never be created) is one confinement failing would +/// actually flip. +#[cfg(any(unix, windows))] +#[test] +fn writing_through_a_linked_folder_cannot_create_a_file_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::submit(&app, Job::Write { uid: 1, entry: leaked_entry("/escape/not-yet-created.txt", "not-yet-created.txt"), bytes: b"pwned".to_vec() }); + said(&mut app, &ctx); + + assert!(!sentinels.sentinel_dir.join("not-yet-created.txt").exists(), "a write through a link must not create a file outside the root"); + assert_sentinels_untouched(&sentinels); +} + +/// benandez's finding 5: nothing previously exercised a link in the `folder` a `Create` targets. +#[cfg(any(unix, windows))] +#[test] +fn creating_through_a_linked_folder_cannot_create_a_file_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::submit(&app, Job::Create { uid: 1, folder: "escape".to_owned(), name: "new.txt".to_owned(), bytes: b"pwned".to_vec() }); + let messages = said(&mut app, &ctx); + + assert!(cloud::origin(&app).is_none(), "a create into a linked folder must not be reported as created"); + assert!(!messages.is_empty(), "a create into a linked folder must be refused, not silently dropped"); + assert!(!sentinels.sentinel_dir.join("new.txt").exists(), "a create through a link must not create a file outside the root"); + assert_sentinels_untouched(&sentinels); +} + +// ------------------------------------------------------------------- Unix-only reproductions +// +// Directory junctions cannot be dangling (`mklink /J` requires the target to exist) and the +// race and hard-link reproductions below are exactly benandez's own repros, run on Linux only, +// as stated in that review. The structural fix (resolving through a `cap_std::fs::Dir`, and +// writing through a temporary file and rename) is the same code on every platform; these three +// just do not have a Windows-shaped equivalent worth a separate repro. + +/// benandez's finding 1, reproduced exactly: `root/doc.txt` is a symlink to a file that does not +/// exist yet, outside the root. The old code's `confine_to_root` canonicalised the dangling link +/// to `NotFound`, walked up to `root`, accepted it, found no file to conflict with, and `write` +/// created the target for real, outside the root. +#[cfg(unix)] +#[test] +fn writing_through_a_dangling_symlink_cannot_create_a_file_outside_the_root() { + let sentinels = sentinels(); + let outside_target = sentinels._arena.path().join("outside-planted.txt"); + std::os::unix::fs::symlink(&outside_target, sentinels.root.join("doc.txt")).unwrap(); + let (mut app, ctx) = wired(sentinels.root.clone()); + + cloud::submit(&app, Job::Write { uid: 1, entry: leaked_entry("/doc.txt", "doc.txt"), bytes: b"pwned".to_vec() }); + said(&mut app, &ctx); + + assert!(!outside_target.exists(), "a write through a dangling symlink must not create its target outside the root"); + assert_sentinels_untouched(&sentinels); +} + +/// benandez's finding 3, reproduced exactly: `root/hl` is a hard link sharing an inode with a +/// file outside the root. Reading it through the backend is legitimate (it is, from inside the +/// sandbox, an ordinary file), which is also how this test gets a real, matching etag to write +/// with, the same way a real caller would after opening the document. The old code's `write` +/// truncated the shared inode in place; `write_replacing` must instead replace `hl`'s own +/// directory entry, leaving the sentinel file's inode, and its other name, untouched. +#[cfg(unix)] +#[test] +fn writing_through_a_hard_link_replaces_the_entry_without_touching_the_shared_file() { + let sentinels = sentinels(); + std::fs::hard_link(&sentinels.sentinel_file, sentinels.root.join("hl")).unwrap(); + let (mut app, ctx) = wired(sentinels.root.clone()); + + cloud::submit(&app, Job::Read { entry: leaked_entry("/hl", "hl"), into: None }); + settle(&mut app, &ctx, |app| !app.opened.lock().unwrap().is_empty()); + let real_entry = app.cloud().origins.get(&1).expect("the read registered an origin for uid 1").entry.clone(); + + // A successful write answers through `cloud.status`, not through `said` or `opened`, so it + // needs its own wait condition rather than the `said` helper used everywhere else in this + // file for a refusal. The read above already set `status` once (`Opened hl from the + // cloud.`), so that has to be cleared first or this would observe the read's own status and + // never actually wait for the write to finish. + app.cloud_mut().status = None; + cloud::submit(&app, Job::Write { uid: 1, entry: real_entry, bytes: b"replaced via rename, not truncated in place".to_vec() }); + settle(&mut app, &ctx, |app| app.cloud().status.is_some() || app.cloud().conflict.is_some() || !app.said.lock().unwrap().is_empty()); + assert!(app.cloud().conflict.is_none(), "the write through the hard-linked name should succeed, not conflict"); + assert!( + app.said.lock().unwrap().is_empty(), + "the write through the hard-linked name should succeed, not be refused: {:?}", + app.said.lock().unwrap() + ); + + assert_eq!( + std::fs::read(sentinels.root.join("hl")).unwrap(), + b"replaced via rename, not truncated in place", + "the write through the hard-linked name should still succeed" + ); + assert_sentinels_untouched(&sentinels); +} + +/// benandez's finding 2, reproduced at a smaller scale: a background thread swaps `root/d` +/// between a symlink into an inside folder and a symlink to the sentinel directory, as fast as +/// it can, with no coordination with the reads below. The old code's `confine_to_root` checked +/// one path string and then `fs::read` resolved that path again, a second, later lookup a swap +/// could land in between; out of 3000 such reads benandez's own run returned the outside file's +/// bytes 347 times. `cap_std::fs::Dir::open` resolves and opens `d` as one operation with no +/// such second lookup, so this must come back empty every time, not merely most of the time. +#[cfg(unix)] +#[test] +fn reading_through_a_link_being_swapped_never_observes_the_outside_target() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let sentinels = sentinels(); + let inside = sentinels.root.join("inside"); + std::fs::create_dir(&inside).unwrap(); + std::fs::write(inside.join("secret.txt"), b"inside bytes, always safe to read").unwrap(); + let link = sentinels.root.join("d"); + std::os::unix::fs::symlink(&inside, &link).unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let swapper = { + let stop = stop.clone(); + let link = link.clone(); + let outside = sentinels.sentinel_dir.clone(); + std::thread::spawn(move || { + let temp = link.with_extension("swap"); + let mut toward_outside = false; + while !stop.load(Ordering::Relaxed) { + let target = if toward_outside { &outside } else { &inside }; + // A stale `temp` from a rename that did not happen (should not occur, but a + // leftover `temp` would otherwise wedge every later iteration's `symlink` call, + // silently stopping the swap rather than failing the test loudly) is cleared + // first so this loop cannot get stuck. + let _ = std::fs::remove_file(&temp); + if std::os::unix::fs::symlink(target, &temp).is_ok() { + let _ = std::fs::rename(&temp, &link); + } + toward_outside = !toward_outside; + } + }) + }; + + let (mut app, ctx) = wired(sentinels.root.clone()); + let mut leaked = false; + for _ in 0..200 { + cloud::submit(&app, Job::Read { entry: leaked_entry("/d/secret.txt", "secret.txt"), into: None }); + said(&mut app, &ctx); + if let Some((_, bytes)) = app.opened.lock().unwrap().first() { + leaked |= bytes.as_slice() == SENTINEL_DIR_FILE_BYTES; + } + } + + stop.store(true, Ordering::Relaxed); + swapper.join().unwrap(); + + assert!(!leaked, "a read observed the outside target's bytes while the link was being swapped underneath it"); + assert_sentinels_untouched(&sentinels); +} diff --git a/crates/cloud-local/tests/save_path_regressions.rs b/crates/cloud-local/tests/save_path_regressions.rs new file mode 100644 index 0000000000..76cec678a3 --- /dev/null +++ b/crates/cloud-local/tests/save_path_regressions.rs @@ -0,0 +1,160 @@ +//! Two save-path defects that need a real backend to show: a reload after a conflict carrying a +//! stale etag into the next save, and two creates of the same name racing past an exists check. +//! Driven through craft_ui::cloud's public functions the way an application does. + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_cloud::{Entry, EntryKind}; +use craft_cloud_local::LocalBackend; +use craft_ui::cloud::{self, CloudApp, CloudFiles, Destination, DocumentKind}; + +const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" }; + +struct Window { + cloud: CloudFiles, + share: craft_ui::share::ShareDialog, + presence: craft_ui::presence::PresenceBar, + body: Vec, + said: Arc>>, +} + +impl Window { + fn new(root: std::path::PathBuf, body: &[u8]) -> Window { + let mut w = Window { + cloud: CloudFiles::new(), + share: craft_ui::share::ShareDialog::new(), + presence: craft_ui::presence::PresenceBar::new(), + body: body.to_vec(), + said: Arc::default(), + }; + w.cloud.connect(LocalBackend::new(root)); + w + } +} + +impl CloudApp for Window { + fn cloud(&self) -> &CloudFiles { + &self.cloud + } + fn cloud_mut(&mut self) -> &mut CloudFiles { + &mut self.cloud + } + fn kind(&self) -> DocumentKind { + NOTE + } + fn active(&self) -> Option { + Some(1) + } + fn title(&self, _uid: u64) -> String { + String::new() + } + fn open_bytes(&mut self, _name: &str, bytes: Vec) -> Result, String> { + self.body = bytes; + Ok(Some(1)) + } + fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result, String> { + Ok(self.body.clone()) + } + fn close(&mut self, _uid: u64) {} + fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog { + &mut self.share + } + fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar { + &mut self.presence + } + fn paint_icon(&self, _p: &egui::Painter, _r: egui::Rect, _k: EntryKind, _c: egui::Color32) {} + fn open_url(&self, _url: &str) {} + fn say(&mut self, text: String) { + self.said.lock().unwrap().push(text); + } + fn app_name(&self) -> &str { + "Review" + } +} + +fn settle(app: &mut Window, ctx: &egui::Context, mut done: impl FnMut(&Window) -> bool) { + let start = Instant::now(); + loop { + ctx.begin_pass(Default::default()); + cloud::pump(app, ctx); + ctx.end_pass().textures_delta.clear(); + if done(app) { + return; + } + assert!(start.elapsed() < Duration::from_secs(5), "timed out"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn listed(app: &mut Window, ctx: &egui::Context, name: &str) -> Entry { + cloud::browse(app, ""); + settle(app, ctx, |a| a.cloud.mine.loaded); + app.cloud.mine.entries.iter().find(|e| e.name == name).cloned().expect("listed") +} + +/// Open v1, another writer stores v2, Save conflicts, the user picks "Reload from the cloud" +/// (`reload_active`, what the modal calls). The window now shows v2's bytes, so the next Save +/// must go through rather than conflict again on the etag the reloaded copy was read at. +#[test] +fn reload_after_a_conflict_carries_the_freshly_read_etag_so_the_next_save_succeeds() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("note.txt"), b"v1").unwrap(); + let ctx = egui::Context::default(); + let mut app = Window::new(root.path().to_owned(), b""); + let v1 = listed(&mut app, &ctx, "note.txt"); + cloud::open_entry(&mut app, v1.clone(), None); + settle(&mut app, &ctx, |a| a.cloud.busy.is_none() && a.body == b"v1"); + + std::thread::sleep(Duration::from_millis(20)); + std::fs::write(root.path().join("note.txt"), b"v2 by someone else").unwrap(); + + app.body = b"my edit".to_vec(); + cloud::save(&mut app).unwrap(); + settle(&mut app, &ctx, |a| a.cloud.busy.is_none()); + assert!(app.cloud.conflict.is_some(), "the first save is refused (correct)"); + + cloud::reload_active(&mut app).unwrap(); + settle(&mut app, &ctx, |a| a.cloud.busy.is_none()); + assert_eq!(app.body, b"v2 by someone else", "reload shows the stored bytes"); + let origin_etag = cloud::report(&app)["origin"]["etag"].clone(); + + cloud::save(&mut app).unwrap(); + settle(&mut app, &ctx, |a| a.cloud.busy.is_none()); + let on_disk = std::fs::read(root.path().join("note.txt")).unwrap(); + assert!( + app.cloud.conflict.is_none(), + "after reloading v2 the save conflicted again: origin etag after reload = {origin_etag} \ + (listing etag was {:?}); file on disk = {:?}", + v1.etag, + String::from_utf8_lossy(&on_disk) + ); +} + +/// Two windows Save As the same new name at once. At most one create may succeed; the other +/// must be refused ("already exists") rather than both reporting success while one silently +/// replaces the other on disk. +#[test] +fn concurrent_create_of_one_name_refuses_the_loser() { + let rounds = 300; + let (mut both_ok, mut example) = (0, String::new()); + for round in 0..rounds { + let root = tempfile::tempdir().unwrap(); + let ctx = egui::Context::default(); + let mut a = Window::new(root.path().to_owned(), format!("window A round {round}").as_bytes()); + let mut b = Window::new(root.path().to_owned(), format!("window B round {round}").as_bytes()); + cloud::save_as(&mut a, "", "Report.txt").unwrap(); + cloud::save_as(&mut b, "", "Report.txt").unwrap(); + settle(&mut a, &ctx, |w| w.cloud.busy.is_none()); + settle(&mut b, &ctx, |w| w.cloud.busy.is_none()); + let (a_ok, b_ok) = (cloud::origin(&a).is_some(), cloud::origin(&b).is_some()); + if a_ok && b_ok { + both_ok += 1; + if example.is_empty() { + let disk = std::fs::read_to_string(root.path().join("Report.txt")).unwrap(); + example = format!("round {round}: A status {:?}, B status {:?}, file holds {disk:?}", a.cloud.status, b.cloud.status); + } + } + } + assert_eq!(both_ok, 0, "{both_ok}/{rounds} rounds: both windows were told the new file was created; e.g. {example}"); +} diff --git a/crates/cloud/Cargo.toml b/crates/cloud/Cargo.toml new file mode 100644 index 0000000000..055feff390 --- /dev/null +++ b/crates/cloud/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-cloud" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "What a cloud provider offers the Craft apps: files, sharing, contacts, notifications and mail as contracts, with no vendor and no IO" + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/cloud/src/error.rs b/crates/cloud/src/error.rs new file mode 100644 index 0000000000..ede71ac0c3 --- /dev/null +++ b/crates/cloud/src/error.rs @@ -0,0 +1,68 @@ +//! One error type for every contract. +//! +//! The cases are the ones a caller acts on differently. A UI shows a different +//! thing for "you may not" than for "the server is unreachable", and a save +//! retries on a conflict where it would not on a refusal. + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + /// The provider could not be reached. Worth retrying. + #[error("the provider could not be reached: {0}")] + Unreachable(String), + + /// The credential was rejected. The user has to sign in again. + #[error("the provider rejected the credential")] + Unauthenticated, + + /// Authenticated, and not allowed to do this. Signing in again will not + /// help, so a UI must not offer it. + #[error("not permitted: {0}")] + Forbidden(String), + + /// No such document, folder or share. + #[error("{what} not found: {id}")] + NotFound { what: &'static str, id: String }, + + /// The document changed since the caller last read it. A save that would + /// have overwritten somebody else's work lands here. + #[error("{0} changed since you opened it")] + Conflict(String), + + /// The provider does not offer this at all. + /// + /// Distinct from [`Error::Forbidden`]: there is nothing to grant. A UI + /// hides the feature rather than explaining it. + #[error("this provider does not support {0}")] + Unsupported(&'static str), + + /// The answer did not match the protocol. + #[error("malformed {what}: {detail}")] + Malformed { what: &'static str, detail: String }, + + /// A name or path could not be used safely. Carried, never panicked. + #[error("invalid {what}: {detail}")] + Invalid { what: &'static str, detail: String }, +} + +impl Error { + pub fn not_found(what: &'static str, id: impl Into) -> Error { + Error::NotFound { what, id: id.into() } + } + + pub fn malformed(what: &'static str, detail: impl Into) -> Error { + Error::Malformed { what, detail: detail.into() } + } + + pub fn invalid(what: &'static str, detail: impl Into) -> Error { + Error::Invalid { what, detail: detail.into() } + } + + /// Whether trying again could succeed without the user doing anything. + pub fn is_transient(&self) -> bool { + matches!(self, Error::Unreachable(_)) + } +} + +pub type Result = std::result::Result; diff --git a/crates/cloud/src/lib.rs b/crates/cloud/src/lib.rs new file mode 100644 index 0000000000..7f02dd4684 --- /dev/null +++ b/crates/cloud/src/lib.rs @@ -0,0 +1,189 @@ +//! What a cloud provider has to offer the Craft apps, and nothing about who +//! provides it. +//! +//! Every capability here is an RFC or an ordinary HTTP API that many systems +//! implement. Files are WebDAV. Contacts are CardDAV. Calendars are CalDAV. +//! Sharing and notification are the only genuinely vendor-shaped parts, and +//! they are small. So there is no reason for an app to know which server it is +//! talking to, and no reason to write the same logic again for the next one. +//! +//! Nothing in this crate opens a socket. Each trait is implemented by a +//! provider crate that brings its own transport, which keeps this testable +//! with no server and keeps the contracts honest about what they need. +//! +//! No type here names a vendor. If a field only makes sense for one product, +//! it belongs in that provider's crate. +//! +//! Nothing here says where an implementation runs. A local adapter may +//! implement these traits against a provider directly, and an application may +//! consume them that way. The contracts do not care. +//! +//! CollabCraft chooses otherwise for its own apps. They reach one service, and +//! that service is the single place a provider is configured, a credential is +//! held and a permission is decided. A desktop binary carrying a provider +//! credential leaks one the moment somebody copies the file, which is what +//! that arrangement exists to prevent. It is a deployment policy, and this +//! crate imposes it on nobody. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod types; + +pub use error::{Error, Result}; +pub use types::{ + Capability, Contact, Conversation, Entry, EntryKind, Identity, MailMessage, Notification, Permission, Share, ShareOptions, ShareTarget, +}; + +/// Reading and writing documents. +/// +/// `list` and `shared_with_me` are separate because they answer different +/// questions. One is a folder's contents, the other is everything another +/// person has given this user access to, which has no single parent folder. +pub trait Files { + /// One folder's contents. An empty path means the user's root. + fn list(&self, path: &str) -> Result>; + + /// Everything shared with this user, wherever it lives. + /// + /// A provider with no concept of this returns an empty list rather than an + /// error, because "nobody has shared anything with you" and "this server + /// cannot tell you" look the same to a file picker. + fn shared_with_me(&self) -> Result>; + + /// One document's bytes. + fn read(&self, id: &str) -> Result>; + + /// A byte range of one document. + /// + /// Defaulted to a full [`read`] and a slice, so providers that have no + /// ranged GET still satisfy the trait. A provider with real range support + /// overrides this. + fn read_range(&self, id: &str, offset: u64, length: u64) -> Result> { + let bytes = self.read(id)?; + let start = usize::try_from(offset).unwrap_or(usize::MAX); + if start >= bytes.len() { + return Ok(Vec::new()); + } + let take = usize::try_from(length).unwrap_or(usize::MAX); + let end = start.saturating_add(take).min(bytes.len()); + Ok(bytes[start..end].to_vec()) + } + + /// Replace one document's bytes. + /// + /// `if_match` carries the etag the caller last saw. A provider that + /// supports conditional writes uses it to refuse a save that would + /// overwrite somebody else's, returning [`Error::Conflict`]. Passing + /// `None` means "write regardless", which is what a Save As does. + fn write(&self, id: &str, bytes: &[u8], if_match: Option<&str>) -> Result; + + /// Create a document and return it. + fn create(&self, folder: &str, name: &str, bytes: &[u8]) -> Result; + + /// One document's metadata, without its bytes. + fn stat(&self, id: &str) -> Result; +} + +/// Giving other people access to a document. +/// +/// Persisting a share through the provider matters more than it looks. A share +/// recorded only by the caller would be invisible in the provider's own file +/// manager, so the two would disagree about who can open what. The provider +/// stays the authority. +pub trait Sharing { + /// Share a document. + /// + /// A link share has no recipient, so [`ShareTarget::Link`] is how a caller + /// asks for one. The returned [`Share::url`] is what to hand out. + fn share(&self, id: &str, with: &ShareTarget, permission: Permission, options: &ShareOptions) -> Result; + + /// Who currently has access. + fn shares(&self, id: &str) -> Result>; + + /// Withdraw one share. + fn unshare(&self, share_id: &str) -> Result<()>; +} + +/// Looking people up, for a share dialog's autocomplete. +/// +/// This is the only thing the share dialog needs, so it is the only thing the +/// contract exposes. A full address book API would be a bigger surface for no +/// gain. +pub trait Contacts { + /// People matching a partial name or address. + /// + /// `limit` exists because this runs on every keystroke. A provider is free + /// to return fewer. + fn search(&self, query: &str, limit: usize) -> Result>; +} + +/// Telling somebody something happened. +/// +/// Separate from [`Mail`] on purpose. An in-app notification is cheap, arrives +/// instantly and is read in context. An email is none of those and is the +/// right choice for somebody who is not currently in the app. A share usually +/// wants both. +pub trait Notifications { + fn notify(&self, user: &str, notification: &Notification) -> Result<()>; +} + +/// Sending mail as the provider. +pub trait Mail { + fn send(&self, message: &MailMessage) -> Result<()>; +} + +/// Who the caller is, according to the provider. +pub trait Accounts { + /// Resolve the signed-in user. + fn me(&self) -> Result; +} + +/// Working together on a document, through whatever the provider calls it. +/// +/// Defaulted throughout. A provider without the feature writes an empty +/// `impl` and reports [`Capability::Conversation`] as absent. The caller +/// then draws no control at all. +pub trait Conversations { + /// What this provider calls the feature. `None` where it has none. + /// + /// Separate from the capability on purpose. The name is a property of + /// the provider. Whether it is available is a property of the + /// instance, and an administrator decides that one. + fn conversation_name(&self) -> Option { + None + } + + /// Start a conversation about a document, or join the one already there. + /// + /// Two people pressing the same control have to arrive in the same + /// place, so this is expected to be idempotent for a given document. + /// + /// `id` is the provider's own handle and means nothing outside the + /// account it came from. A conversation is therefore keyed on the + /// provider, the account and the document together, and `self` carries + /// the first two. A document copied into another account is a different + /// document to its provider, so it gets a conversation of its own. + /// Nothing here can attach one account's thread to another's. + fn conversation(&self, _id: &str, _title: &str) -> Result { + Err(Error::Unsupported("conversations")) + } +} + +/// Everything one provider can do. +/// +/// A provider implements the capabilities it has and reports the rest as +/// absent, so a caller can hide a share button on a server with no sharing +/// rather than offering a feature that will fail. +pub trait Provider: Files + Sharing + Contacts + Notifications + Mail + Accounts + Conversations { + /// A stable identifier, such as `nextcloud`. Used in configuration and + /// logs, never shown to a user. + fn id(&self) -> &str; + + /// What this provider actually supports. + fn capabilities(&self) -> Vec; + + fn supports(&self, capability: Capability) -> bool { + self.capabilities().contains(&capability) + } +} diff --git a/crates/cloud/src/types.rs b/crates/cloud/src/types.rs new file mode 100644 index 0000000000..ab8c005a1b --- /dev/null +++ b/crates/cloud/src/types.rs @@ -0,0 +1,216 @@ +//! The data the contracts pass around. +//! +//! Every type here is plain and vendor-neutral. A field that only means +//! something to one product belongs in that provider's crate. + +use serde::{Deserialize, Serialize}; + +/// What a provider can do. +/// +/// Reported rather than assumed, so a caller hides a share button on a +/// server without sharing instead of offering a feature that fails on use. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Capability { + Files, + SharedWithMe, + Sharing, + Contacts, + Notifications, + Mail, + /// Conditional writes, so a save can refuse to clobber a newer version. + Etags, + /// Public links. Absent on a server that forbids them, and the dialog then + /// offers no Copy link rather than a button that fails. + LinkShares, + /// A key on a public link. This is what most places mean when they talk + /// about sharing with somebody who has no account. + LinkPassword, + /// The server requires that key, so a link cannot be made without one. + LinkPasswordRequired, + /// An expiry date on a share. + ShareExpiry, + /// The provider can tell a recipient that something was shared with them. + /// + /// Distinct from [`Capability::Mail`], which is about sending arbitrary + /// mail. A provider commonly has this and not that: it will notify the + /// person a share names without offering any way to send mail in general. + ShareNotify, + /// A conversation about a document, such as a call or a chat room. + /// + /// Every provider that has this calls it something else, so the name + /// comes from [`crate::Conversations::conversation_name`]. Reported + /// separately from that name: a provider knows what it would call the + /// feature whether or not an administrator installed it. + Conversation, +} + +/// A file or folder. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + /// An opaque handle for reading, writing and sharing this entry. + /// + /// Only the provider that issued it may interpret it. A caller passes it + /// back and never parses it. + pub id: String, + /// The stable identity used for a collaboration room. + /// + /// Separate from `id` on purpose. A provider's read and write handle is + /// often a path, and a path changes when somebody renames or moves the + /// file. A room keyed on that would silently split in two mid-session, + /// with each half seeing only its own edits. This one survives a rename. + pub room: String, + /// What to show the user. + pub name: String, + /// Where it sits, for a breadcrumb. Never a handle. + pub path: String, + pub kind: EntryKind, + /// Bytes, absent for a folder. + pub size: Option, + /// RFC 3339. Absent when the provider does not say. + pub modified: Option, + /// For matching a document to the app that opens it. + pub mime: Option, + /// The version the caller last saw, for a conditional write. + pub etag: Option, + /// Whether this user may change it. A read-only share still lists. + pub writable: bool, + /// Who shared it, when it came from somebody else. + pub shared_by: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EntryKind { + File, + Folder, +} + +/// A person, as a share dialog needs them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Contact { + /// What the provider wants back when sharing with this person. + pub id: String, + /// How to share with them, decided by the provider and never guessed. + /// + /// The distinction is not cosmetic. A contact with an account is a user + /// share. One known only by address is an email share. Sharing an address + /// as though it were a user id fails with "not found", because no such + /// user exists, and nothing in `id` alone says which case this is. + pub target: ShareTarget, + /// What to show. A display name where there is one. + pub name: String, + pub email: Option, + /// An avatar, as a URL the client may fetch. Never image bytes: a search + /// returning ten people would otherwise carry ten pictures nobody asked + /// for yet. + pub avatar: Option, + /// A group rather than a person. Shown differently and shared differently. + pub is_group: bool, +} + +/// Who to share with. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "kind", content = "id")] +pub enum ShareTarget { + User(String), + Group(String), + /// Somebody with no account, reached by address. + Email(String), + /// Anybody holding the link. + Link, +} + +/// What a share allows. +/// +/// Deliberately coarse. Providers disagree on the fine detail, and a dialog +/// offering a distinction the server cannot keep is worse than one that does +/// not. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Permission { + /// Open and read. No edits reach the document. + View, + /// Open and edit. + Edit, +} + +/// Everything optional about a share. +/// +/// A struct rather than more positional arguments. The list grew past the +/// point where a call site reads correctly, and a provider that cannot honour +/// one of these needs to see which it was given. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShareOptions { + /// Shown to the recipient. + pub note: Option, + /// Send mail where the provider can. + pub notify: bool, + /// A key the recipient must present. Only meaningful for a link, and + /// refused by a server that does not allow one. + pub password: Option, + /// `YYYY-MM-DD`. After this the share stops working. + pub expires: Option, +} + +/// Where to go to work together on a document. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Conversation { + /// Where to join. Handed to a browser, or to the provider's own app. + pub url: String, + /// What the provider calls the feature, for the control's wording. A + /// menu item reading "Work together in Talk" is built from this. + pub name: String, +} + +/// A share that exists. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Share { + pub id: String, + pub target: ShareTarget, + /// What to call the recipient, where the provider says. + /// + /// A share carries the handle the server wants back, which for a user is + /// an account id. People are not known to each other by account id. A + /// provider that knows the difference says so here. + pub display: Option, + pub permission: Permission, + /// Present for a link share, absent otherwise. + pub url: Option, + pub note: Option, + /// RFC 3339. + pub created: Option, +} + +/// Something worth telling a user about, in the app. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Notification { + /// A short machine-readable kind, such as `document_shared`. Lets a client + /// decide how to render without parsing prose. + pub kind: String, + pub subject: String, + pub body: Option, + /// Where to go when it is clicked. + pub link: Option, +} + +/// An email to send. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct MailMessage { + pub to: Vec, + pub subject: String, + pub body: String, + /// Whether `body` is HTML. Plain text otherwise. + pub html: bool, +} + +/// The signed-in user, as the provider sees them. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Identity { + /// The provider's identifier for this account. + pub id: String, + /// What to show. Never an identity: two people can share a display name. + pub display: String, + pub email: Option, + pub avatar: Option, +} diff --git a/crates/cms/README.md b/crates/cms/README.md index 71f3146d50..cbee391cd9 100644 --- a/crates/cms/README.md +++ b/crates/cms/README.md @@ -81,6 +81,12 @@ Buffers are checked once per call, before any pixel is written. the exact and float paths compare each pixel with white; all other colours are left as the profiles give them. With a profile whose white falls between its nodes (`coated-cmyk`: 0.4 % C), the last step to white is that much larger than its neighbours. +* Black preservation (opt-in, `BlackPreserving`): for CMYK → CMYK, a colour with exactly zero + C, M and Y comes out as exactly `(0, 0, 0, K')`, where `K'` is the destination black whose + K-only L* equals the source's (both K ramps sampled at 1024 points when the transform is + built, with its intent and BPC). The test is exact zero, so an input with any chromatic ink + takes the ordinary path. Absolute colorimetric, non-CMYK profiles and K ramps that reverse at + one of the 1024 samples are refused (a reversal between samples is not detected). ## Built-in profiles (all CC0-1.0, generated by this crate) diff --git a/crates/cms/profiles/craft-coated-fogra39.icc b/crates/cms/profiles/craft-coated-fogra39.icc index 13590238ea..1ef3cad1fd 100644 Binary files a/crates/cms/profiles/craft-coated-fogra39.icc and b/crates/cms/profiles/craft-coated-fogra39.icc differ diff --git a/crates/cms/src/black.rs b/crates/cms/src/black.rs new file mode 100644 index 0000000000..f80defeef1 --- /dev/null +++ b/crates/cms/src/black.rs @@ -0,0 +1,205 @@ +//! K-only black preservation for CMYK → CMYK transforms. +//! +//! A CMYK → CMYK transform goes through the three-component PCS, so black alone (C = M = Y = 0) +//! comes out as a four-ink mix. ISO 32000-2 §8.6.5.7 notes that this loses fidelity in the black +//! component. ICC defines no black preservation; this is a named policy the caller opts into. +//! +//! [`BlackPreserving`] converts like its [`Transform`], except that a colour with exactly zero +//! cyan, magenta and yellow becomes exactly `(0, 0, 0, K')`. `K'` is the destination black whose +//! K-only L* equals the source's, both measured to Lab with the transform's own intent and BPC +//! setting: both ramps are sampled once, at construction, and the destination ramp is inverted. +//! A source black darker than the destination's maximum black maps to K = 1. The test is exact zero, so the transform is discontinuous at C = M = Y = 0: an input +//! with any chromatic ink takes the ordinary path. + +use crate::transform::{Transform, TransformOptions}; +use crate::{Builtin, CmsError, ColorSpace, Intent, Profile, invalid_arg}; + +/// Samples along each K-only ramp. Linear interpolation between samples of a smooth ramp is far +/// below the 16-bit quantum. +const K_SAMPLES: usize = 1024; +/// Slack for the monotonicity checks (L* units, K units). +const MONOTONIC_EPS: f64 = 1e-6; + +/// A CMYK → CMYK transform that keeps black-only colours black-only. +#[derive(Debug)] +pub struct BlackPreserving { + transform: Transform, + /// Destination K for source K at `i / (K_SAMPLES - 1)`; `K_SAMPLES` values in `[0, 1]`. + curve: Vec, + /// Source K from which the source black is at least as dark as the destination's darkest: + /// mapped to exactly 1. Infinite when the destination's black is the darker. + saturate: f32, + /// The mapping at the 256 8-bit source codes, already quantised. + curve8: [u8; 256], +} + +impl BlackPreserving { + /// Transform from `src` to `dst` with black preservation. + /// + /// Errors with [`CmsError::InvalidArgument`] when either profile is not CMYK or the intent is + /// absolute colorimetric (which reproduces the source's paper and black, so there is no + /// black to map), and with [`CmsError::Unsupported`] when a profile's K-only ramp is not + /// monotonic at its 1024 samples (black that gets lighter as K rises has no equal-lightness + /// inverse; a reversal between samples is not detected). Other errors + /// are those of [`Transform::with_options`]. + pub fn new(src: &Profile, dst: &Profile, opts: TransformOptions) -> Result { + if src.color_space != ColorSpace::Cmyk || dst.color_space != ColorSpace::Cmyk { + return Err(invalid_arg("black preservation needs CMYK source and destination profiles")); + } + if opts.intent == Intent::AbsoluteColorimetric { + return Err(invalid_arg("black preservation does not apply to absolute colorimetric")); + } + let transform = Transform::with_options(src, dst, opts)?; + let src_l = k_ramp_lightness(src, opts)?; + let dst_l = k_ramp_lightness(dst, opts)?; + let (curve, saturate) = k_curve(&src_l, &dst_l)?; + let mut curve8 = [0u8; 256]; + for (code, slot) in curve8.iter_mut().enumerate() { + *slot = quantise(map(&curve, saturate, code as f32 / 255.0), 255.0) as u8; + } + Ok(BlackPreserving { transform, curve, saturate, curve8 }) + } + + /// The ordinary transform, which every colour with chromatic ink goes through. Converting with + /// it directly does not preserve black. + pub fn transform(&self) -> &Transform { + &self.transform + } + + /// Destination K for a black-only source colour of `k` (clamped to `[0, 1]`). + pub fn map_k(&self, k: f32) -> f32 { + map(&self.curve, self.saturate, k) + } + + /// Exact evaluation of one colour; slices as in [`Transform::eval`]. + pub fn eval(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> { + self.transform.eval(input, out)?; + self.patch_one(input, out); + Ok(()) + } + + /// Lookup-table evaluation of one colour; slices as in [`Transform::eval`]. + pub fn eval_fast(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> { + self.transform.eval_fast(input, out)?; + self.patch_one(input, out); + Ok(()) + } + + /// Converts float pixels; layout and errors as in [`Transform::convert_f32`]. + pub fn convert_f32(&self, src: &[f32], src_stride: usize, dst: &mut [f32], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_f32(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + self.patch_one(s, d); + } + Ok(()) + } + + /// Converts 8-bit pixels; layout and errors as in [`Transform::convert_u8`]. + pub fn convert_u8(&self, src: &[u8], src_stride: usize, dst: &mut [u8], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_u8(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) { + (*c, *m, *y) = (0, 0, 0); + *kd = self.curve8[usize::from(*k)]; + } + } + Ok(()) + } + + /// Converts 16-bit pixels; layout and errors as in [`Transform::convert_u16`]. + pub fn convert_u16(&self, src: &[u16], src_stride: usize, dst: &mut [u16], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_u16(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) { + (*c, *m, *y) = (0, 0, 0); + *kd = quantise(self.map_k(f32::from(*k) / 65535.0), 65535.0) as u16; + } + } + Ok(()) + } + + fn patch_one(&self, input: &[f32], out: &mut [f32]) { + if let ([0.0, 0.0, 0.0, k, ..], [c, m, y, kd, ..]) = (input, out) { + (*c, *m, *y) = (0.0, 0.0, 0.0); + *kd = self.map_k(*k); + } + } +} + +/// The sampled mapping from the source to the destination K-only ramp, and the source K at +/// which the destination's darkest black is reached (the `saturate` field). +fn k_curve(src_l: &[f64], dst_l: &[f64]) -> Result<(Vec, f32), CmsError> { + let curve: Vec = src_l.iter().map(|&l| invert(dst_l, l) as f32).collect(); + if !curve.windows(2).all(|w| f64::from(w[0]) - f64::from(w[1]) <= MONOTONIC_EPS) { + return Err(CmsError::Unsupported("black preservation: the K mapping is not monotonic".into())); + } + let saturate = match (src_l.last(), dst_l.last()) { + (Some(&s), Some(&d)) if s < d => invert(src_l, d) as f32, + _ => f32::INFINITY, + }; + Ok((curve, saturate)) +} + +/// L* of `p`'s K-only ramp at `K_SAMPLES` points, light to dark; refused when it is not +/// non-increasing. +fn k_ramp_lightness(p: &Profile, opts: TransformOptions) -> Result, CmsError> { + let to_lab = Transform::with_options(p, Builtin::LabD50.profile(), TransformOptions { precise_float: true, ..opts })?; + let mut ramp = Vec::with_capacity(K_SAMPLES); + let mut lab = [0.0f32; 3]; + for i in 0..K_SAMPLES { + let k = i as f32 / (K_SAMPLES - 1) as f32; + to_lab.eval(&[0.0, 0.0, 0.0, k], &mut lab)?; + ramp.push(f64::from(lab[0]) * 100.0); + } + if !ramp.iter().all(|l| l.is_finite()) || !ramp.windows(2).all(|w| w[1] - w[0] <= MONOTONIC_EPS) { + return Err(CmsError::Unsupported("black preservation: a K-only ramp is not monotonic".into())); + } + Ok(ramp) +} + +/// The K in `[0, 1]` at which the non-increasing `ramp` reaches `target`, clamped to its ends. +fn invert(ramp: &[f64], target: f64) -> f64 { + let (Some(&first), Some(&last)) = (ramp.first(), ramp.last()) else { return 0.0 }; + if ramp.len() < 2 || target >= first { + return 0.0; + } + if target <= last { + return 1.0; + } + // ramp[lo] > target >= ramp[hi] + let (mut lo, mut hi) = (0usize, ramp.len() - 1); + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + if ramp.get(mid).is_some_and(|&v| v > target) { + lo = mid; + } else { + hi = mid; + } + } + let (a, b) = (ramp.get(lo).copied().unwrap_or(first), ramp.get(hi).copied().unwrap_or(last)); + let t = if a - b > MONOTONIC_EPS { (a - target) / (a - b) } else { 0.0 }; + (lo as f64 + t) / (ramp.len() - 1) as f64 +} + +/// Linear interpolation in `curve` (samples over `[0, 1]`) at `k`, clamped; 1 from `saturate`. +fn map(curve: &[f32], saturate: f32, k: f32) -> f32 { + let Some(&last) = curve.last() else { return 0.0 }; + let k = if k.is_nan() { 0.0 } else { k.clamp(0.0, 1.0) }; + if k >= saturate { + return 1.0; + } + let x = k * (curve.len() - 1) as f32; + let i = x.floor() as usize; + match (curve.get(i), curve.get(i + 1)) { + (Some(&a), Some(&b)) => a + (b - a) * (x - i as f32), + _ => last, + } +} + +fn quantise(v: f32, max: f32) -> f32 { + (v.clamp(0.0, 1.0) * max + 0.5).floor() +} + +#[cfg(test)] +#[path = "black_tests.rs"] +mod tests; diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs new file mode 100644 index 0000000000..8752cdaa2b --- /dev/null +++ b/crates/cms/src/black_tests.rs @@ -0,0 +1,149 @@ +use super::*; + +fn coated() -> &'static Profile { + Builtin::CoatedCmyk.profile() +} +fn fogra() -> &'static Profile { + Builtin::CoatedFogra39.profile() +} +fn opts() -> TransformOptions { + TransformOptions::default() +} + +/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. +fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { + let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); + let mut lab = [0.0f32; 3]; + t.eval(&cmyk, &mut lab).unwrap(); + lab[0] * 100.0 +} + +#[test] +fn the_plain_transform_turns_black_into_four_inks() { + // What the policy is for: without it, black alone gains chromatic ink across presses. + let t = Transform::with_options(coated(), fogra(), opts()).unwrap(); + let mut out = [0.0f32; 4]; + t.eval(&[0.0, 0.0, 0.0, 0.5], &mut out).unwrap(); + assert!(out[..3].iter().any(|v| *v > 0.01), "{out:?}"); +} + +#[test] +fn black_only_stays_black_only_on_every_path() { + for (src, dst) in [(coated(), fogra()), (fogra(), coated()), (fogra(), fogra())] { + let bp = BlackPreserving::new(src, dst, opts()).unwrap(); + for k in [0.0f32, 0.1, 0.5, 0.9, 1.0] { + for fast in [false, true] { + let mut out = [1.0f32; 4]; + if fast { bp.eval_fast(&[0.0, 0.0, 0.0, k], &mut out) } else { bp.eval(&[0.0, 0.0, 0.0, k], &mut out) }.unwrap(); + assert_eq!(out[..3], [0.0; 3], "k {k} fast {fast}"); + assert_eq!(out[3], bp.map_k(k)); + } + } + let src8: Vec = (0..=255u8).flat_map(|k| [0, 0, 0, k, 7]).collect(); + let mut dst8 = vec![0u8; src8.len()]; + bp.convert_u8(&src8, 5, &mut dst8, 5, true).unwrap(); + for (k, px) in dst8.as_chunks::<5>().0.iter().enumerate() { + assert_eq!(px[..3], [0; 3], "u8 k {k}"); + assert!((f32::from(px[3]) - bp.map_k(k as f32 / 255.0) * 255.0).abs() <= 0.5, "u8 k {k}: {}", px[3]); + assert_eq!(px[4], 7, "extra channel copied"); + } + let src16: Vec = (0..=64u16).flat_map(|k| [0, 0, 0, k * 1023]).collect(); + let mut dst16 = vec![0u16; src16.len()]; + bp.convert_u16(&src16, 4, &mut dst16, 4, false).unwrap(); + for (px, k) in dst16.as_chunks::<4>().0.iter().zip(src16.as_chunks::<4>().0) { + assert_eq!(px[..3], [0; 3], "u16 {k:?}"); + assert!((f32::from(px[3]) - bp.map_k(f32::from(k[3]) / 65535.0) * 65535.0).abs() <= 0.5, "u16 {k:?}: {}", px[3]); + } + let srcf: Vec = (0..=10).flat_map(|k| [0.0, 0.0, 0.0, k as f32 / 10.0]).collect(); + let mut dstf = vec![0.0f32; srcf.len()]; + bp.convert_f32(&srcf, 4, &mut dstf, 4, false).unwrap(); + for (px, k) in dstf.as_chunks::<4>().0.iter().zip(srcf.as_chunks::<4>().0) { + assert_eq!(*px, [0.0, 0.0, 0.0, bp.map_k(k[3])], "f32 {k:?}"); + } + } +} + +#[test] +fn the_destination_black_matches_the_source_lightness() { + // Measured worst error over 201 K steps, both directions, both intents, BPC on and off: + // 0.007 L*. + for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { + for bpc in [true, false] { + let o = TransformOptions { intent, bpc, ..opts() }; + for (src, dst) in [(coated(), fogra()), (fogra(), coated())] { + let bp = BlackPreserving::new(src, dst, o).unwrap(); + let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] { + let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + if want <= dst_black { + assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); + continue; + } + let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); + } + assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); + assert!(bp.map_k(1.0) > 0.95, "full black stays near full black: {}", bp.map_k(1.0)); + assert!(bp.map_k(0.25) < bp.map_k(0.75)); + } + } + } + let same = BlackPreserving::new(fogra(), fogra(), opts()).unwrap(); + for k in [0.0f32, 0.2, 0.6, 1.0] { + assert!((same.map_k(k) - k).abs() < 1e-3, "{k} -> {}", same.map_k(k)); + } +} + +#[test] +fn colours_with_any_chromatic_ink_take_the_ordinary_path() { + let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap(); + for input in [[1e-6f32, 0.0, 0.0, 0.5], [0.0, 0.2, 0.0, 0.5], [0.3, 0.3, 0.3, 0.0], [0.0, 0.0, 1.0, 1.0]] { + let (mut a, mut b) = ([0.0f32; 4], [0.0f32; 4]); + bp.eval(&input, &mut a).unwrap(); + bp.transform().eval(&input, &mut b).unwrap(); + assert_eq!(a, b, "{input:?}"); + } + let src = [1u8, 0, 0, 128, 0, 1, 0, 128]; + let (mut a, mut b) = ([0u8; 8], [0u8; 8]); + bp.convert_u8(&src, 4, &mut a, 4, false).unwrap(); + bp.transform().convert_u8(&src, 4, &mut b, 4, false).unwrap(); + assert_eq!(a, b); +} + +#[test] +fn refusals_and_hostile_values() { + let srgb = Builtin::Srgb.profile(); + assert!(matches!(BlackPreserving::new(srgb, fogra(), opts()), Err(CmsError::InvalidArgument(_)))); + assert!(matches!(BlackPreserving::new(fogra(), srgb, opts()), Err(CmsError::InvalidArgument(_)))); + let abs = TransformOptions { intent: Intent::AbsoluteColorimetric, ..opts() }; + assert!(matches!(BlackPreserving::new(fogra(), coated(), abs), Err(CmsError::InvalidArgument(_)))); + let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap(); + for k in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 2.0] { + assert!((0.0..=1.0).contains(&bp.map_k(k)), "{k}"); + } + let mut out = [0.0f32; 4]; + assert!(bp.eval(&[0.0; 3], &mut out).is_err(), "short input"); + assert!(bp.convert_u8(&[0, 0, 0, 9, 0], 4, &mut [0u8; 4], 4, false).is_err(), "partial pixel"); + assert_eq!(invert(&[], 50.0), 0.0); + assert_eq!(invert(&[100.0], 50.0), 0.0); + assert_eq!(invert(&[100.0, 0.0], 150.0), 0.0); + assert_eq!(invert(&[100.0, 0.0], -5.0), 1.0); + assert!((invert(&[100.0, 50.0, 0.0], 25.0) - 0.75).abs() < 1e-12); + assert_eq!(map(&[], f32::INFINITY, 0.5), 0.0); +} + +#[test] +fn black_beyond_the_destination_maximum_maps_to_full_black_between_samples() { + // Source L* = 100 (1 - K), destination L* = 100 - 50 K: from K = 0.5 the source is darker + // than any destination black, and 0.5 falls between the 1024 samples. + let ramp = |f: fn(f64) -> f64| (0..K_SAMPLES).map(|i| f(i as f64 / (K_SAMPLES - 1) as f64)).collect::>(); + let (src, dst) = (ramp(|k| 100.0 * (1.0 - k)), ramp(|k| 100.0 - 50.0 * k)); + let (curve, saturate) = k_curve(&src, &dst).unwrap(); + assert!((saturate - 0.5).abs() < 1e-6, "{saturate}"); + for k in [0.5001f32, 0.6, 1.0] { + assert_eq!(map(&curve, saturate, k), 1.0, "{k}"); + } + assert!((map(&curve, saturate, 0.25) - 0.5).abs() < 1e-4); + let (_, never) = k_curve(&dst, &src).unwrap(); + assert_eq!(never, f32::INFINITY, "a lighter source never saturates"); +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index b082f67a5b..38f926dcf1 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -19,6 +19,7 @@ //! CIE 15, and Adobe's published black point compensation paper. #![forbid(unsafe_code)] +pub mod black; pub mod builtin; mod builtin_v2; pub mod clut; @@ -39,6 +40,7 @@ pub mod transform; mod write; pub mod write_v2; +pub use black::BlackPreserving; pub use builtin::Builtin; pub use clut::Clut; pub use curve::Curve; diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index b1535f78c2..d192127ec4 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -19,6 +19,9 @@ //! L* is scaled onto the device black, chroma is softly compressed against a gamut boundary //! descriptor sampled from the forward model — then solved as above. //! +//! That is [`GamutMapping::Legacy`]. [`GamutMapping::Oklab`] maps out-of-gamut colours in Oklab +//! instead and gives saturation its own table; the Coated FOGRA39 built-in uses it. +//! //! The model is plausible for coated offset, not a measured characterisation: use a real //! profile from your print provider for production print. //! @@ -49,6 +52,11 @@ pub struct CmykParams { pub k_max: f64, /// Exponent of the black generation curve above `gcr_start`. pub gcr_gamma: f64, + /// Black generation as a curve of `[gray component, black]` points with increasing gray + /// components in `[0, 1]`, interpolated linearly and held flat beyond the ends. Empty by + /// default: black is then `k_max` times the ramp of `gcr_start` and `gcr_gamma` (the curve + /// of the shipped Photocraft profile). + pub gcr_curve: Vec<[f64; 2]>, /// Tone value increase at 50 % for C, M, Y, K. pub tvi: [f64; 4], /// Grid points of the AToB (4D) and BToA (3D) tables. @@ -60,6 +68,32 @@ pub struct CmykParams { /// encoding and separates to a trace of ink. Off by default, which keeps the bytes of the /// shipped Photocraft profile. pub white_on_node: bool, + /// How the BToA tables bring colours into the gamut. [`GamutMapping::Legacy`] by default, + /// which keeps the bytes of the shipped Photocraft profile. + pub mapping: GamutMapping, +} + +/// How the BToA tables map colours the printer cannot reach. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum GamutMapping { + /// The shipped Photocraft profile: out-of-gamut colours land on the closest reachable + /// colour (ΔE76); perceptual scales L* onto the device black and compresses Lab chroma; + /// saturation shares the perceptual table. + Legacy, + /// Gamut mapping in Oklab, whose hue lines stay perceptually constant (a CIELAB hue line + /// from a saturated blue toward grey drifts toward purple; an Oklab one does not): + /// + /// * **Colorimetric**: in-gamut colours separate exactly. An out-of-gamut colour takes the + /// closest colour the printer reaches in Oklab, lightness and hue weighted above chroma, + /// and more so the further outside it is; black is generated from the clipped colour, so + /// inks the clip drives to 100 % stay there. + /// * **Perceptual** and **saturation**: the ICC v4 perceptual reference black is mapped + /// onto the device black linearly in XYZ (as black point compensation does) for neutrals, + /// fading out with Oklab chroma, so greys separate as with colorimetric + BPC and colourful + /// colours keep their lightness. Perceptual then compresses Oklab chroma above `knee` × + /// the gamut boundary into the boundary; saturation scales Oklab chroma by `saturation` + /// and clips as colorimetric does. + Oklab { knee: f64, saturation: f64 }, } impl Default for CmykParams { @@ -71,10 +105,12 @@ impl Default for CmykParams { gcr_start: 0.2, k_max: 0.95, gcr_gamma: 1.1, + gcr_curve: Vec::new(), tvi: [0.14, 0.14, 0.14, 0.17], grid_a2b: 11, grid_b2a: 21, white_on_node: false, + mapping: GamutMapping::Legacy, } } } @@ -183,6 +219,11 @@ impl Forward for TableForward { /// Bounded least-squares solve for C, M, Y given K, minimising ΔE76 to `target`, subject to /// `C + M + Y ≤ limit` (projected Levenberg–Marquardt with a numerical Jacobian). fn solve_cmy(model: &F, target: [f64; 3], k: f64, limit: f64, seeds: &[[f64; 3]]) -> ([f64; 3], f64) { + solve_cmy_by(model, k, limit, seeds, |l| [l[0] - target[0], l[1] - target[1], l[2] - target[2]]) +} + +/// [`solve_cmy`] minimising the norm of `residual(lab)` instead of ΔE76. +fn solve_cmy_by(model: &F, k: f64, limit: f64, seeds: &[[f64; 3]], residual: impl Fn([f64; 3]) -> [f64; 3]) -> ([f64; 3], f64) { let project = |mut x: [f64; 3]| { for _ in 0..4 { for v in &mut x { @@ -202,10 +243,7 @@ fn solve_cmy(model: &F, target: [f64; 3], k: f64, limit: f6 } x }; - let err = |x: [f64; 3]| { - let l = model.lab([x[0], x[1], x[2], k]); - [l[0] - target[0], l[1] - target[1], l[2] - target[2]] - }; + let err = |x: [f64; 3]| residual(model.lab([x[0], x[1], x[2], k])); let norm2 = |e: [f64; 3]| e[0] * e[0] + e[1] * e[1] + e[2] * e[2]; let mut best = ([0.0; 3], f64::INFINITY); for seed in seeds { @@ -275,13 +313,32 @@ fn solve_cmy(model: &F, target: [f64; 3], k: f64, limit: f6 const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]]; +/// Black for a gray component `g` (the smallest of C, M, Y without black). +fn gcr(p: &CmykParams, g: f64) -> f64 { + let Some(first) = p.gcr_curve.first() else { + // The Photocraft profile's curve. + return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) }; + }; + let mut k = first[1]; + for w in p.gcr_curve.windows(2) { + let ([g0, k0], [g1, k1]) = (w[0], w[1]); + if g >= g1 { + k = k1; + } else if g > g0 { + k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); + break; + } + } + k.clamp(0.0, 1.0) +} + /// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve. pub fn separate(model: &F, p: &CmykParams, target: [f64; 3], warm: Option<[f64; 4]>) -> ([f64; 4], f64) { let mut seeds: Vec<[f64; 3]> = warm.map(|w| vec![[w[0], w[1], w[2]]]).unwrap_or_default(); seeds.extend_from_slice(&SEEDS); let (cmy0, _) = solve_cmy(model, target, 0.0, 3.0, &seeds); let g = cmy0[0].min(cmy0[1]).min(cmy0[2]); - let k = if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) }; + let k = gcr(p, g); let mut seeds2 = vec![[(cmy0[0] - k).max(0.0), (cmy0[1] - k).max(0.0), (cmy0[2] - k).max(0.0)], cmy0]; seeds2.extend_from_slice(&seeds); let (cmy, de) = solve_cmy(model, target, k, (p.tac - k).max(0.0), &seeds2); @@ -383,6 +440,187 @@ impl Gbd { } } +/// ΔE76 under which a separation counts as reaching its target. +const REACH: f64 = 1.5; +/// Oklab chroma beyond any printable colour: the top of the boundary search. +const OKLAB_CHROMA_MAX: f64 = 0.5; +/// Oklab chroma above which the perceptual and saturation tables no longer lift black: they lift +/// neutrals fully, and less the more colourful a colour is. +const LIFT_CHROMA: f64 = 0.1; +/// Weight of lightness and hue against chroma when a colour just outside the gamut is clipped. +const CLIP_WEIGHT: f64 = 1.5; +/// Growth of that weight with the squared share of chroma the clip loses. +const CLIP_WEIGHT_GROWTH: f64 = 200.0; + +// Oklab (Björn Ottosson, 2020): XYZ (D65) → cone response → cube root → Lab-like axes. +const OKLAB_M1: math::Mat3 = + [[0.8189330101, 0.3618667424, -0.1288597137], [0.0329845436, 0.9293118715, 0.0361456387], [0.0482003018, 0.2643662691, 0.6338517070]]; +const OKLAB_M2: math::Mat3 = + [[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660]]; +const OKLAB_M1_INV: math::Mat3 = + [[1.2270138511, -0.5577999807, 0.2812561490], [-0.0405801784, 1.1122568696, -0.0716766787], [-0.0763812845, -0.4214819784, 1.5861632204]]; +const OKLAB_M2_INV: math::Mat3 = [[1.0, 0.3963377774, 0.2158037573], [1.0, -0.1055613458, -0.0638541728], [1.0, -0.0894841775, -1.2914855480]]; + +/// The [`GamutMapping::Oklab`] separations of one forward model. +struct OklabMapper<'a, F: Forward + ?Sized> { + model: &'a F, + p: &'a CmykParams, + knee: f64, + saturation: f64, + /// XYZ scale that maps the v4 perceptual reference black onto the device black (the white + /// stays fixed): `v' = a·v + w·(1 − a)`. + black_scale: f64, + to_d65: math::Mat3, + to_d50: math::Mat3, +} + +impl<'a, F: Forward + ?Sized> OklabMapper<'a, F> { + fn new(model: &'a F, p: &'a CmykParams, knee: f64, saturation: f64) -> Self { + let d65 = math::xy_to_xyz(math::D65_XY); + // The darkest neutral the printer reaches. + let (black, _) = separate(model, p, [0.0, 0.0, 0.0], None); + let device = math::lab_to_xyz([model.lab(black)[0], 0.0, 0.0], math::D50)[1]; + let reference = crate::transform::PERCEPTUAL_BLACK[1]; + OklabMapper { + model, + p, + knee, + saturation, + black_scale: (1.0 - device) / (1.0 - reference), + to_d65: math::bradford(math::D50, d65), + to_d50: math::bradford(d65, math::D50), + } + } + + fn oklab(&self, lab: [f64; 3]) -> [f64; 3] { + let xyz = math::apply(&self.to_d65, math::lab_to_xyz(lab, math::D50)); + math::apply(&OKLAB_M2, math::apply(&OKLAB_M1, xyz).map(f64::cbrt)) + } + + fn lab(&self, ok: [f64; 3]) -> [f64; 3] { + let lms = math::apply(&OKLAB_M2_INV, ok).map(|v| v * v * v); + math::xyz_to_lab(math::apply(&self.to_d50, math::apply(&OKLAB_M1_INV, lms)), math::D50) + } + + /// The most chroma (scale of `ok`'s chroma in `[0, top]`) the printer reaches at `ok`'s + /// lightness and hue, and its separation; `None` when even the neutral is out of reach. + fn boundary(&self, ok: [f64; 3], top: f64, warm: Option<[f64; 4]>) -> Option<(f64, [f64; 4])> { + let (grey, d) = separate(self.model, self.p, self.lab([ok[0], 0.0, 0.0]), warm); + if d > REACH { + return None; + } + let (mut lo, mut hi, mut best) = (0.0, top, grey); + for _ in 0..14 { + let mid = 0.5 * (lo + hi); + let (c, d) = separate(self.model, self.p, self.lab([ok[0], ok[1] * mid, ok[2] * mid]), Some(best)); + if d <= REACH { + lo = mid; + best = c; + } else { + hi = mid; + } + } + Some((lo, best)) + } + + /// Colorimetric: exact in gamut; outside, the closest colour the printer reaches in Oklab, + /// lightness and hue weighted above chroma, and more so the further outside the colour is. + fn clip(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] { + let (cmyk, de) = separate(self.model, self.p, lab, warm); + if de <= REACH { + return cmyk; + } + let ok = self.oklab(lab); + let c0 = ok[1].hypot(ok[2]); + // Unit vectors along the colour's chroma and hue directions. + let (u, v) = if c0 > 1e-9 { ([ok[1] / c0, ok[2] / c0], [-ok[2] / c0, ok[1] / c0]) } else { ([1.0, 0.0], [0.0, 1.0]) }; + // Lightness and hue errors weighted by `w`, chroma error by 1; scaled by 100 so the + // solver's step tolerances suit it as they suit ΔE76. + let residual = |w: f64| { + move |l: [f64; 3]| { + let o = self.oklab(l); + let (da, db) = (o[1] - ok[1], o[2] - ok[2]); + [100.0 * w * (o[0] - ok[0]), 100.0 * (da * u[0] + db * u[1]), 100.0 * w * (da * v[0] + db * v[1])] + } + }; + let solve = |w: f64, k: f64, from: [f64; 3]| { + let mut seeds = vec![from]; + seeds.extend_from_slice(&SEEDS); + solve_cmy_by(self.model, k, (self.p.tac - k).max(0.0), &seeds, residual(w)).0 + }; + // A first clip without black measures how far outside the colour is. A colour just + // outside may give up a little lightness and hue to keep its chroma (a red reaches the + // full magenta and yellow edge); one far outside keeps its lightness and hue and loses + // chroma (a saturated blue does not slide along the gamut surface). + let first = solve(CLIP_WEIGHT, 0.0, [cmyk[0], cmyk[1], cmyk[2]]); + let o = self.oklab(self.model.lab([first[0], first[1], first[2], 0.0])); + let loss = if c0 > 1e-9 { (1.0 - o[1].hypot(o[2]) / c0).clamp(0.0, 1.0) } else { 0.0 }; + let w = CLIP_WEIGHT * (1.0 + CLIP_WEIGHT_GROWTH * loss * loss); + let free = solve(w, 0.0, first); + let norm = |c: [f64; 4]| residual(w)(self.model.lab(c)).iter().map(|v| v * v).sum::(); + // Candidates, the closest kept: the separation itself (a colour it nearly reaches stays + // continuous with its in-gamut neighbours), the clip with the separation's black, and + // the clip with black generated from the black-free clip's gray component (inks the + // clip drives to 100 % stay there and black replaces the rest). + let mut best = (norm(cmyk), cmyk); + for k in [cmyk[3], gcr(self.p, free[0].min(free[1]).min(free[2]))] { + for from in [[cmyk[0], cmyk[1], cmyk[2]], free] { + let cmy = solve(w, k, from); + let c = [cmy[0], cmy[1], cmy[2], k]; + let n = norm(c); + if n < best.0 { + best = (n, c); + } + } + } + // Near paper white the gamut narrows to a point: the separation's closest colour keeps + // light tints' chroma where holding lightness would drop them toward bare paper, and + // the table nodes there carry the in-gamut tints between them. The inks blend from the + // clip at L* 85 to the separation at L* 95. + let clip_share = ((95.0 - lab[0]) / 10.0).clamp(0.0, 1.0); + std::array::from_fn(|i| clip_share * best.1[i] + (1.0 - clip_share) * cmyk[i]) + } + + /// Maps the v4 perceptual reference black onto the device black, linearly in XYZ, for + /// neutrals; colourful colours keep their lightness. + fn lift_black(&self, lab: [f64; 3]) -> [f64; 3] { + let ok = self.oklab(lab); + let neutral = (1.0 - ok[1].hypot(ok[2]) / LIFT_CHROMA).clamp(0.0, 1.0); + let a = 1.0 - neutral * (1.0 - self.black_scale); + let xyz = math::lab_to_xyz(lab, math::D50); + math::xyz_to_lab(std::array::from_fn(|i| a * xyz[i] + math::D50[i] * (1.0 - a)), math::D50) + } + + fn perceptual(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] { + let lab = self.lift_black(lab); + let ok = self.oklab(lab); + let c = ok[1].hypot(ok[2]); + if c < 1e-9 { + return self.clip(lab, warm); + } + let Some((s, edge)) = self.boundary(ok, OKLAB_CHROMA_MAX / c, warm) else { + return self.clip(lab, warm); + }; + // Chroma above the knee is compressed smoothly into the boundary chroma `cb`. + let cb = s * c; + let knee = self.knee * cb; + if c <= knee { + return self.clip(lab, warm); + } + let c2 = knee + (cb - knee) * ((c - knee) / (cb - knee).max(1e-9)).tanh(); + let f = c2 / c; + if f >= s { + return edge; + } + self.clip(self.lab([ok[0], ok[1] * f, ok[2] * f]), Some(edge)) + } + + fn saturation(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] { + let ok = self.oklab(self.lift_black(lab)); + self.clip(self.lab([ok[0], ok[1] * self.saturation, ok[2] * self.saturation]), warm) + } +} + fn lab_node_legacy(i: usize, n: usize) -> f64 { i as f64 / (n - 1) as f64 } @@ -419,6 +657,18 @@ fn white_node_curve(l_axis: bool, x: f64) -> f64 { } fn b2a_table(model: &F, p: &CmykParams, gbd: Option<&Gbd>) -> Result { + b2a_table_with(p, |lab, warm| { + let target = match gbd { + Some(g) => g.compress(lab), + None => lab, + }; + separate(model, p, target, warm).0 + }) +} + +/// Samples a BToA table: `node` separates each relative Lab node, warm-started from the +/// previous node along b. +fn b2a_table_with(p: &CmykParams, node: impl Fn([f64; 3], Option<[f64; 4]>) -> [f64; 4] + Sync) -> Result { let n = p.grid_b2a.max(2); let nodes = n * n * n; let step = (n - 1) as f64; @@ -434,11 +684,7 @@ fn b2a_table(model: &F, p: &CmykParams, gbd: Option<&Gbd>) } else { decode_v2([lab_node_legacy(li, n), lab_node_legacy(ai, n), lab_node_legacy(bi, n)]) }; - let target = match gbd { - Some(g) => g.compress(lab), - None => lab, - }; - let (cmyk, _) = if p.white_on_node && lab == [100.0, 0.0, 0.0] { ([0.0; 4], 0.0) } else { separate(model, p, target, warm) }; + let cmyk = if p.white_on_node && lab == [100.0, 0.0, 0.0] { [0.0; 4] } else { node(lab, warm) }; warm = Some(cmyk); out.extend(cmyk.map(|v| v as f32)); } @@ -460,6 +706,15 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> { if p.white_on_node && p.grid_b2a.is_multiple_of(2) { return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a))); } + let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x)); + if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) { + return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve))); + } + if let GamutMapping::Oklab { knee, saturation } = p.mapping + && !((0.0..1.0).contains(&knee) && saturation.is_finite() && saturation > 0.0) + { + return Err(invalid_arg(format!("Oklab gamut mapping needs a knee in [0, 1) and a positive saturation, not {knee} and {saturation}"))); + } Ok(()) } @@ -518,11 +773,23 @@ pub fn cmyk_profile_from_model(model: &F, paper: [f64; 3], } fn lut_profile(model: &F, a2b: Clut, paper: [f64; 3], p: &CmykParams) -> Result { - let gbd = Gbd::new(model, p); - let colorimetric = b2a_table(model, p, None)?; - let perceptual = b2a_table(model, p, Some(&gbd))?; + let (perceptual, colorimetric, saturation) = match p.mapping { + GamutMapping::Legacy => { + let gbd = Gbd::new(model, p); + let colorimetric = b2a_table(model, p, None)?; + let perceptual = b2a_table(model, p, Some(&gbd))?; + (perceptual.clone(), colorimetric, perceptual) + } + GamutMapping::Oklab { knee, saturation } => { + let m = OklabMapper::new(model, p, knee, saturation); + let colorimetric = b2a_table_with(p, |lab, warm| m.clip(lab, warm))?; + let perceptual = b2a_table_with(p, |lab, warm| m.perceptual(lab, warm))?; + let saturation = b2a_table_with(p, |lab, warm| m.saturation(lab, warm))?; + (perceptual, colorimetric, saturation) + } + }; let a2b = lut16(a2b, false); - let (b0, b1) = (lut16(perceptual, p.white_on_node), lut16(colorimetric, p.white_on_node)); + let (b0, b1, b2) = (lut16(perceptual, p.white_on_node), lut16(colorimetric, p.white_on_node), lut16(saturation, p.white_on_node)); Ok(Profile { version: (4, 0x30), class: ProfileClass::Output, @@ -538,7 +805,7 @@ fn lut_profile(model: &F, a2b: Clut, paper: [f64; 3], p: &C trc: None, gray_trc: None, a2b: [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)], - b2a: [Some(b0.clone()), Some(b1), Some(b0)], + b2a: [Some(b0), Some(b1), Some(b2)], bytes: None, hash: Default::default(), } @@ -576,6 +843,46 @@ mod tests { } } + #[test] + fn oklab_mapping_refuses_bad_parameters() { + for (knee, saturation) in [(1.0, 1.0), (-0.1, 1.0), (f64::NAN, 1.0), (0.5, 0.0), (0.5, f64::INFINITY), (0.5, f64::NAN)] { + let p = CmykParams { grid_a2b: 2, grid_b2a: 2, mapping: GamutMapping::Oklab { knee, saturation }, ..CmykParams::default() }; + assert!(cmyk_profile(&p).is_err(), "knee {knee}, saturation {saturation}"); + } + } + + #[test] + fn black_generation_curve() { + let p = CmykParams { gcr_curve: vec![[0.0, 0.0], [0.5, 0.2], [1.0, 0.9]], ..CmykParams::default() }; + for (g, k) in [(-1.0, 0.0), (0.0, 0.0), (0.25, 0.1), (0.5, 0.2), (0.75, 0.55), (1.0, 0.9), (2.0, 0.9)] { + assert!((gcr(&p, g) - k).abs() < 1e-12, "g {g}: {} != {k}", gcr(&p, g)); + } + for curve in [vec![[0.5, 0.2], [0.5, 0.3]], vec![[0.5, 0.2], [0.2, 0.3]], vec![[0.0, 1.5]], vec![[f64::NAN, 0.0]]] { + let p = CmykParams { grid_a2b: 2, grid_b2a: 2, gcr_curve: curve.clone(), ..CmykParams::default() }; + assert!(cmyk_profile(&p).is_err(), "{curve:?}"); + } + } + + #[test] + fn oklab_round_trips() { + let m = CmykModel::coated(CmykParams::default().tvi); + let p = CmykParams::default(); + let mapper = OklabMapper::new(&m, &p, 0.65, 1.05); + for lab in [[50.0, 0.0, 0.0], [44.0, 63.7, 47.0], [31.9, 32.9, -76.8], [90.0, -5.0, 80.0]] { + let back = mapper.lab(mapper.oklab(lab)); + // The published matrices carry 10 digits, so the inverses are exact to about 1e-5 ΔE. + assert!(math::delta_e76(lab, back) < 1e-3, "{lab:?} -> {back:?}"); + } + } + + #[test] + fn oklab_profile_has_three_tables() { + let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; + let profile = cmyk_profile(&p).unwrap(); + let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") }; + assert!(b0 != b1 && b0 != b2, "perceptual shares a table"); + } + #[test] fn separation_hits_in_gamut_targets() { let m = CmykModel::coated(CmykParams::default().tvi); diff --git a/crates/cms/src/transform.rs b/crates/cms/src/transform.rs index c4f6e11cc8..38a3223d96 100644 --- a/crates/cms/src/transform.rs +++ b/crates/cms/src/transform.rs @@ -46,7 +46,7 @@ const OUT_TABLE: usize = GpuMatrixShaper::OUTPUT_ENTRIES; const _: () = assert!(OUT_TABLE.is_power_of_two()); /// ICC v4 perceptual reference medium black (ICC.1:2010 §6.3.4.4), XYZ. -const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287]; +pub(crate) const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287]; /// Accelerated representation of a transform. #[derive(Debug)] diff --git a/crates/cms/tests/fogra39.rs b/crates/cms/tests/fogra39.rs index f958ffc511..d08e3bae60 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -12,7 +12,7 @@ //! ([`synth::cmyk_profile_from_model`]). use craft_cms::math::{self, delta_e2000}; -use craft_cms::synth::{self, CmykParams, Forward}; +use craft_cms::synth::{self, CmykParams, Forward, GamutMapping}; use craft_cms::{Builtin, Intent, Profile, Transform}; const DATA: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/FOGRA39.txt"); @@ -346,8 +346,10 @@ fn regen_coated_fogra39() { description: Builtin::CoatedFogra39.description().into(), copyright: craft_cms::builtin::COATED_FOGRA39_COPYRIGHT.into(), tac: 3.3, + gcr_curve: vec![[0.0, 0.0], [0.2, 0.05], [0.5, 0.205], [0.67, 0.5], [1.0, 0.95]], grid_b2a: 33, white_on_node: true, + mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() }; let profile = synth::cmyk_profile_from_model(&f, paper(&p), ¶ms).unwrap(); @@ -564,3 +566,60 @@ fn stand_in_separations_respect_the_ink_limit() { } } } + +/// sRGB patches and their separations by the reference application (Convert to Profile to +/// Coated FOGRA39, dither on), CMYK % per intent: relative + BPC, relative, perceptual, +/// saturation, absolute. Measured for storytold/photocraft#14267. +const REFERENCE_SEPARATIONS: [([u8; 3], [[f32; 4]; 5]); 3] = [ + ( + [200, 30, 30], + [[14.5, 97.7, 95.3, 4.3], [13.3, 100.0, 100.0, 5.5], [18.0, 96.9, 92.9, 8.6], [14.9, 100.0, 100.0, 5.9], [8.6, 100.0, 100.0, 2.4]], + ), + ([30, 60, 200], [[91.8, 75.3, 0.0, 0.0], [94.5, 76.5, 0.0, 0.0], [94.5, 77.7, 0.0, 0.0], [93.7, 76.9, 0.0, 0.0], [92.6, 74.9, 0.0, 0.0]]), + ( + [128, 128, 128], + [[49.0, 38.4, 38.4, 20.0], [49.8, 39.2, 38.8, 21.2], [49.0, 38.4, 38.4, 20.0], [49.0, 38.4, 38.4, 20.0], [46.7, 36.9, 38.4, 18.4]], + ), +]; + +const SEPARATION_INTENTS: [(Intent, bool); 5] = [ + (Intent::RelativeColorimetric, true), + (Intent::RelativeColorimetric, false), + (Intent::Perceptual, true), + (Intent::Saturation, true), + (Intent::AbsoluteColorimetric, false), +]; + +fn separation(intent: Intent, bpc: bool, rgb: [u8; 3]) -> [f32; 4] { + let t = Transform::new(Builtin::Srgb.profile(), fogra39(), intent, bpc).unwrap(); + let mut o = [0.0f32; 4]; + t.eval(&rgb.map(|v| v as f32 / 255.0), &mut o).unwrap(); + o.map(|v| v * 100.0) +} + +/// sRGB → Coated FOGRA39 matches the reference application's inks on a red, a saturated blue +/// and a mid grey for every intent. Most land within 2 % per ink; red at the magenta–yellow +/// edge lands between table nodes that are and are not clipped, which costs up to 2.2 % with +/// the 33³ BToA tables. +#[test] +fn separates_like_the_reference_application() { + let mut worst = 0.0f32; + for (rgb, want) in REFERENCE_SEPARATIONS { + for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) { + let got = separation(intent, bpc, rgb); + let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max); + eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})"); + worst = worst.max(diff); + } + } + assert!(worst <= 2.5, "worst ink difference {worst} %"); +} + +/// Saturation has its own table: a red separates with more magenta and yellow than +/// perceptual, whose chroma compression takes some back. +#[test] +fn saturation_and_perceptual_separate_differently() { + let red = [200, 30, 30]; + let (perceptual, saturation) = (separation(Intent::Perceptual, true, red), separation(Intent::Saturation, true, red)); + assert!(saturation[1] > perceptual[1] + 1.0 && saturation[2] > perceptual[2] + 1.0, "perceptual {perceptual:?}, saturation {saturation:?}"); +} diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 0a18ccc99c..5c4a902427 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -10,6 +10,12 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# AI agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file and +# the `-cli mcp` side that finds the open window. The agent settings build without it. +agents = ["dep:craft-ai-agents", "dep:craft-atomic", "dep:craft-flags", "dep:log"] + [dependencies] serde = { workspace = true } serde_json = { workspace = true } @@ -18,6 +24,16 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). getrandom = "0.3" +# The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). +craft-ai-agents = { workspace = true, optional = true } +craft-atomic = { workspace = true, optional = true } +craft-flags = { workspace = true, optional = true } +log = { workspace = true, optional = true } [dev-dependencies] proptest = { workspace = true } +tempfile = "3" + +[[test]] +name = "agents" +required-features = ["agents"] diff --git a/crates/control/src/agents/connection.rs b/crates/control/src/agents/connection.rs new file mode 100644 index 0000000000..0c0bcebc7b --- /dev/null +++ b/crates/control/src/agents/connection.rs @@ -0,0 +1,115 @@ +//! The connection file: where an app's control server listens for agents. + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// The connection file in the app's settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The token file the app keeps in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// How long [`probe`] waits for a connection to be accepted. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// The version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// The largest connection file read; anything bigger is not one. +const MAX_CONNECTION_BYTES: u64 = 1 << 20; + +/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`. +/// Holds no secret: the token stays in its own owner-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// The file format's version (1). + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// The loopback port of the control server. + pub port: u16, + /// The file holding the token. + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + /// This process's connection on `port`, naming `app` (the app's version string). + pub fn new(port: u16, token_file: PathBuf, app: impl Into) -> Self { + Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> std::io::Error { + std::io::Error::other(format!("{}: {e}", path.display())) +} + +/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a +/// file. +pub fn write_connection(dir: &Path, c: &Connection) -> std::io::Result<()> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?; + craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file of another version, with port 0, or one +/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next +/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over +/// 1 MiB is an error, and left alone. +pub fn read_connection(dir: &Path) -> std::io::Result> { + let path = dir.join(CONNECTION_FILE); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + if !meta.is_file() { + return Err(io_error(&path, "not a regular file")); + } + if meta.len() > MAX_CONNECTION_BYTES { + return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); + } + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Removes the connection file in `dir` when nothing listens on its port any more (an app that +/// crashed or quit without removing it), or when it does not read as a connection. A live +/// instance's file is kept, and so is anything but a regular file. Errors are ignored. +pub fn remove_stale_connection(dir: &Path) { + let path = dir.join(CONNECTION_FILE); + let stale = match read_connection(dir) { + Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), + Ok(None) => path.is_file(), + Err(_) => false, + }; + if stale { + let _ = std::fs::remove_file(path); + } +} + +/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does. +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs new file mode 100644 index 0000000000..49b242ff5d --- /dev/null +++ b/crates/control/src/agents/live.rs @@ -0,0 +1,601 @@ +//! The other end of the link: where an app's `-cli mcp` sends each tool call. +//! +//! [`Live::resolve`] runs before every tool call. It reads the connection file the app publishes +//! while it accepts agents ([`super::write_connection`]), so the app may start, quit or move to another port +//! while the MCP client stays connected, and the client's configuration holds no port and no +//! token: +//! +//! - An app that accepts agents: the call goes to its open window ([`Route::Window`]). The same +//! port, token and process id keep the window client the app made; any change makes a new one. +//! - No app accepts agents, and the person doesn't let agents use it ([`Consent::allowed`] off, or +//! [`AgentSettings::allow_agent_control`] off, under which the app doesn't listen either): a +//! session without a window with only the folders given to the command +//! ([`LiveConfig::read_roots`], [`LiveConfig::write_root`]), as `mcp` always worked. The app's own +//! folders are for agents the person let in. +//! - No app accepts agents, but agents are allowed: the closed-app choice decides +//! ([`LiveConfig::when_closed`], otherwise [`AgentSettings::when_app_closed`]): start the app and +//! wait until it accepts agents, a headless session with the app's agent folders (the command's +//! folders win), or an error that says what to do. +//! +//! Once headless, the session stays headless: documents don't move under the agent. Only a session +//! made with the app's agent folders ends when the person stops letting agents in; the next call +//! gets one with the command's folders. A window route is dropped as soon as no app accepts agents. +//! Lookups are +//! serialised, so concurrent calls start the app once: calls that queued while a start was under +//! way and found no window get that start's error rather than starting the app again; a call made +//! after it tries again. +//! +//! The crate has no async runtime: `resolve` blocks (file reads, a loopback probe, and while an +//! app starts, polling), so an async MCP server calls it from its blocking pool. What a window +//! client and a headless session are stays the app's ([`LiveConfig::new`]'s `connect` and +//! `headless`), and so do the tools and the transport. Errors are the tool call's result: words +//! for the agent, and through it the person, naming the app. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use super::{AgentSettings, Connection, PROBE_TIMEOUT, WhenAppClosed, probe, read_connection}; + +/// Starts the desktop app; see [`launcher`]. +pub type LaunchFn = Box Result<(), String> + Send + Sync>; +/// What the person allows now, read from the app's settings folder before every call. +pub type ConsentFn = Box Consent + Send + Sync>; +/// Makes the app's client for its open window. +pub type ConnectFn = Box Result + Send + Sync>; +/// Makes the app's headless session with these folders. +pub type HeadlessFn = Box Result + Send + Sync>; + +/// How long a started app gets to accept agents. A first start can take a while (GPU shader +/// caches, a font scan), but MCP clients give a tool call about a minute. +pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(45); +/// How often a starting app's connection file is looked for. +pub const LAUNCH_POLL: Duration = Duration::from_millis(250); +/// The longest [`LiveConfig::launch_timeout`] used; a longer one is cut to this. +const MAX_LAUNCH_TIMEOUT: Duration = Duration::from_secs(600); +/// The range [`LiveConfig::poll`] is kept in. +const POLL_RANGE: (Duration, Duration) = (Duration::from_millis(1), Duration::from_secs(1)); + +/// The open window a call goes to: from the connection file, with the token from its token file. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Window { + /// The loopback port of the app's control server. + pub port: u16, + /// The app's process id. + pub pid: u32, + /// The control token, as its token file holds it (trimmed). + pub token: String, +} + +impl Window { + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +impl fmt::Debug for Window { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Never the token: Debug output ends up in logs. + f.debug_struct("Window").field("port", &self.port).field("pid", &self.pid).finish_non_exhaustive() + } +} + +/// Whether the person lets agents use the app now, and its agent settings. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Consent { + /// Agents may use the app: `agents_allowed(mcp_flag(), launcher_allows(""), legacy)` + /// ([`super::agents_allowed`]), with the suite's `AI-MCP` flag the ArtCraft Launcher's switch. + /// [`Live`] also requires [`AgentSettings::allow_agent_control`]. + pub allowed: bool, + /// The app's agent settings (closed-app choice, folders). + pub settings: AgentSettings, +} + +impl Consent { + /// `allowed` with these settings. + pub fn new(allowed: bool, settings: AgentSettings) -> Self { + Self { allowed, settings } + } +} + +/// The folders a headless session may open from and save to. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct HeadlessFolders { + /// Folders files may be opened from. + pub read: Vec, + /// The folder files may be saved to. + pub write: Option, +} + +/// Where a tool call goes: the app's window client or its headless session. +#[derive(Clone, Debug)] +pub enum Route { + /// The open window. + Window(W), + /// A session without a window. + Headless(H), +} + +/// What [`Live`] needs from the app. +#[non_exhaustive] +pub struct LiveConfig { + /// The app's name in messages (`"PhotoCraft"`). + pub app_name: String, + /// The app's settings folder: connection file, token file and settings. + pub config_dir: PathBuf, + /// Overrides the app's closed-app choice (the CLI's `--when-closed`). + pub when_closed: Option, + /// Folders a headless session may open from (the CLI's read roots); while agents are allowed + /// they replace the app's read folder. + pub read_roots: Vec, + /// The folder a headless session may save to (the CLI's write root); while agents are allowed + /// it replaces the app's write folder. + pub write_root: Option, + /// Starts the app; `None` when this install can't ([`launcher`] found nothing to start). + pub launch: Option, + /// How long a started app gets to accept agents ([`LAUNCH_TIMEOUT`]; at most 10 minutes). + pub launch_timeout: Duration, + /// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s). + pub poll: Duration, + consent: ConsentFn, + connect: ConnectFn, + headless: HeadlessFn, +} + +impl LiveConfig { + /// The app `app_name` with its settings in `config_dir`: `consent` reads whether agents may + /// use it, `connect` makes a client for its open window, `headless` a session without one. + pub fn new( + app_name: impl Into, + config_dir: PathBuf, + consent: impl Fn(&Path) -> Consent + Send + Sync + 'static, + connect: impl Fn(&Window) -> Result + Send + Sync + 'static, + headless: impl Fn(&HeadlessFolders) -> Result + Send + Sync + 'static, + ) -> Self { + Self { + app_name: app_name.into(), + config_dir, + when_closed: None, + read_roots: Vec::new(), + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + poll: LAUNCH_POLL, + consent: Box::new(consent), + connect: Box::new(connect), + headless: Box::new(headless), + } + } +} + +/// The port, token and process id a window client was made for: a restarted app may keep its +/// port and token, but its old socket is gone. +type WindowKey = (u16, String, u32); +/// The route the last call took. +struct Current { + route: Route, + /// For a window, the key its client was made for. + key: Option, + /// A headless session that holds folders of the app's agent settings: it lasts only while + /// the person lets agents in. + app_folders: bool, +} + +/// Resolves each tool call of one MCP session; see the module docs. +pub struct Live { + cfg: LiveConfig, + /// Serialises lookups, so concurrent calls start the app once; holds the last start's error. + lookup: Mutex>, + /// How many starts have finished, read before a call queues for `lookup`. + finished: AtomicU64, + current: Mutex>>, +} + +impl Live { + /// A session that has not resolved anything yet. + pub fn new(cfg: LiveConfig) -> Self { + Self { cfg, lookup: Mutex::new(None), finished: AtomicU64::new(0), current: Mutex::new(None) } + } + + /// The route the last [`Self::resolve`] chose, if any. + pub fn current(&self) -> Option> { + self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|c| c.route.clone()) + } + + fn set(&self, route: Route, key: Option, app_folders: bool) -> Route { + *self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some(Current { route: route.clone(), key, app_folders }); + route + } + + /// The headless session to keep using, if any: one made with the app's folders only while + /// agents are still `allowed`. A route that may not be kept is dropped. + fn sticky_headless(&self, allowed: bool) -> Option> { + let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + match current.as_ref() { + Some(c) if matches!(c.route, Route::Headless(_)) && (allowed || !c.app_folders) => Some(c.route.clone()), + Some(c) if matches!(c.route, Route::Headless(_)) => { + *current = None; + None + } + _ => None, + } + } + + /// Forgets a window route: no app accepts agents any more, so its client is for a socket + /// that is gone. + fn drop_window(&self) { + let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + if current.as_ref().is_some_and(|c| matches!(c.route, Route::Window(_))) { + *current = None; + } + } + + /// Where the next tool call goes. Blocks; see the module docs. The error is the tool call's + /// result. + pub fn resolve(&self) -> Result, String> { + let queued_at = self.finished.load(Ordering::Acquire); + let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); + let consent = (self.cfg.consent)(&self.cfg.config_dir); + // Allow Agent Control off refuses agents, as the app does: it doesn't listen then. + let allowed = consent.allowed && consent.settings.allow_agent_control; + if let Some(route) = self.sticky_headless(allowed) { + return Ok(route); + } + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + self.drop_window(); + let app = &self.cfg.app_name; + if !allowed { + let folders = HeadlessFolders { read: self.cfg.read_roots.clone(), write: self.cfg.write_root.clone() }; + return self.headless(&folders, false, &format!("{app} can't use the automation roots")); + } + match self.cfg.when_closed.unwrap_or(consent.settings.when_app_closed) { + WhenAppClosed::Error => Err(format!("{app} isn't running: open it, then try again.")), + WhenAppClosed::Headless => { + let app_read = self.cfg.read_roots.is_empty() && consent.settings.read_folder().is_some(); + let app_write = self.cfg.write_root.is_none() && consent.settings.write_folder().is_some(); + let read = + if self.cfg.read_roots.is_empty() { consent.settings.read_folder().into_iter().collect() } else { self.cfg.read_roots.clone() }; + let write = self.cfg.write_root.clone().or_else(|| consent.settings.write_folder()); + let why = format!("{app} isn't running and its agent folders can't be used"); + self.headless(&HeadlessFolders { read, write }, app_read || app_write, &why) + } + WhenAppClosed::Launch => { + // A start finished while this call waited and the app still isn't there: its answer + // is this call's too, rather than a second start of an app that may be opening. + if self.finished.load(Ordering::Acquire) != queued_at + && let Some(failure) = last_failure.as_ref() + { + return Err(failure.clone()); + } + let started = self.launch_and_wait(); + *last_failure = started.as_ref().err().cloned(); + self.finished.fetch_add(1, Ordering::AcqRel); + started + } + } + } + + /// A headless session with `folders` from now on; `app_folders` when some of them are the + /// app's agent folders. `why` leads its error. + fn headless(&self, folders: &HeadlessFolders, app_folders: bool, why: &str) -> Result, String> { + let session = (self.cfg.headless)(folders).map_err(|e| format!("{why}: {e}"))?; + Ok(self.set(Route::Headless(session), None, app_folders)) + } + + /// Starts the app and waits until it accepts agents, at most the launch timeout. + fn launch_and_wait(&self) -> Result, String> { + let app = &self.cfg.app_name; + let Some(launch) = &self.cfg.launch else { + return Err(format!("{app} isn't running, and this install can't start it from here: open {app}, then try again.")); + }; + launch().map_err(|e| format!("couldn't start {app}: {e}"))?; + let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT); + let started = Instant::now(); + let deadline = started.checked_add(timeout).unwrap_or(started); + let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1); + loop { + std::thread::sleep(poll); + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + if Instant::now() >= deadline { + return Err(format!( + "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", + timeout.as_secs() + )); + } + } + } + + /// The client for `window`: the one made for the same port, token and process, or a new one. + fn use_window(&self, window: Window) -> Result, String> { + let key: WindowKey = (window.port, window.token.clone(), window.pid); + { + let current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(c) = current.as_ref() + && c.key.as_ref() == Some(&key) + { + return Ok(c.route.clone()); + } + } + let client = (self.cfg.connect)(&window).map_err(|e| format!("couldn't reach {}'s window: {e}", self.cfg.app_name))?; + Ok(self.set(Route::Window(client), Some(key), false)) + } + + /// The app accepting agents now: `None` when there is no connection file, or one left by an + /// app that crashed (nothing listens on its port). + fn find_app(&self) -> Result, String> { + find_window(&self.cfg.config_dir, &self.cfg.app_name) + } +} + +/// The window accepting agents with its settings in `dir`, with the token from its token file; +/// `None` when no app accepts agents there. `app_name` names the app in errors. +pub fn find_window(dir: &Path, app_name: &str) -> Result, String> { + let Some(c): Option = read_connection(dir).map_err(|e| e.to_string())? else { return Ok(None) }; + if !probe(c.port, PROBE_TIMEOUT) { + return Ok(None); + } + let token = read_token(&c.token_file).map_err(|e| format!("{app_name}'s agent token: {e}"))?; + Ok(Some(Window { port: c.port, pid: c.pid, token })) +} + +/// The largest token file read; a token is far shorter. +const MAX_TOKEN_FILE: u64 = 4096; + +/// The token in the token file at `path`, trimmed and otherwise as written: the app's server +/// compares it exactly ([`crate::auth::tokens_match`]). The file must be a regular file of at most +/// [`MAX_TOKEN_FILE`] bytes holding one token (no spaces or control characters in it), and on Unix +/// readable by its owner only: a token others could read is refused rather than used. +fn read_token(path: &Path) -> Result { + use std::io::Read; + let shown = |e: &dyn fmt::Display| format!("{}: {e}", path.display()); + // Before opening: opening a FIFO for reading blocks until something writes to it. + if !std::fs::metadata(path).map_err(|e| shown(&e))?.is_file() { + return Err(shown(&"not a regular file")); + } + let file = std::fs::File::open(path).map_err(|e| shown(&e))?; + let meta = file.metadata().map_err(|e| shown(&e))?; + if !meta.is_file() { + return Err(shown(&"not a regular file")); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if meta.mode() & 0o077 != 0 { + return Err(shown(&format!("readable by group or others (mode {:o}); restrict it to its owner", meta.mode() & 0o777))); + } + } + let mut text = String::new(); + file.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).map_err(|e| shown(&e))?; + if text.len() as u64 > MAX_TOKEN_FILE { + return Err(shown(&format!("larger than {MAX_TOKEN_FILE} bytes"))); + } + let token = text.trim(); + if token.is_empty() || token.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(shown(&"not a control token")); + } + Ok(token.to_owned()) +} + +/// How to start the desktop app `exe` (its file name without `.exe`) that ships beside the CLI at +/// `cli`: detached and with no standard streams, since the CLI's carry the MCP protocol and the +/// app must outlive the MCP client. `None` where this install can't start it: inside a Flatpak, +/// or with no app beside the CLI. +pub fn launcher(cli: &Path, exe: &str) -> Option { + use std::process::{Command, Stdio}; + let env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()); + // Both sides resolved, so a mount reached through a symlink (`$TMPDIR`) still matches. + let resolved = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let install = Install { + platform: Platform::current(), + flatpak: env("FLATPAK_ID").is_some(), + appimage: env("APPIMAGE"), + appdir: env("APPDIR").map(|d| resolved(Path::new(&d)).into_os_string()), + system_root: env("SystemRoot"), + }; + let (program, args) = launch_command(&resolved(cli), exe, &install, &|p| p.is_file())?; + let mut command = Command::new(program); + command.args(args); + let command = Mutex::new(command); + Some(Box::new(move || { + let mut c = command.lock().unwrap_or_else(PoisonError::into_inner); + c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + detach(&mut c); + let child = c.spawn().map_err(|e| e.to_string())?; + reap(child); + Ok(()) + })) +} + +/// Waits for `child` on a thread of its own, so a start helper that exits (`open`, Explorer) or an +/// app that quits before the CLI does is reaped rather than left a zombie until the MCP client +/// ends; the app keeps running on its own either way. Without a thread the child is dropped, as +/// before. +fn reap(mut child: std::process::Child) { + let _ = std::thread::Builder::new().name("app-start-reaper".into()).spawn(move || { + let _ = child.wait(); + }); +} + +/// What [`launch_command`] needs to know about the install, from the environment. +#[derive(Clone, Debug, Default)] +struct Install { + platform: Platform, + /// Inside a Flatpak (`FLATPAK_ID`). + flatpak: bool, + /// The AppImage the running image set (`APPIMAGE`). + appimage: Option, + /// That image's mount point (`APPDIR`). + appdir: Option, + /// `%SystemRoot%` (Windows). + system_root: Option, +} + +/// The platform [`launch_command`] plans for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Platform { + Windows, + MacOs, + #[default] + Other, +} + +impl Platform { + /// The platform this build runs on. + fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::MacOs + } else { + Self::Other + } + } +} + +/// The program and arguments that start the app; see [`launcher`]. +fn launch_command(cli: &Path, exe: &str, install: &Install, is_file: &dyn Fn(&Path) -> bool) -> Option<(PathBuf, Vec)> { + let platform = install.platform; + if install.flatpak { + return None; + } + // Only when this CLI runs from that image's mount: a process started from another AppImage + // (an MCP client packaged as one) inherits its `APPIMAGE` too. + if let (Some(image), Some(mount)) = (&install.appimage, &install.appdir) + && cli.starts_with(mount) + { + // The AppImage's mount point goes away with the CLI; the image itself stays. + return Some((PathBuf::from(image), Vec::new())); + } + let dir = cli.parent()?; + if platform == Platform::MacOs + && dir.ends_with("Contents/MacOS") + && let Some(bundle) = dir.parent().and_then(Path::parent) + { + // A macOS app bundle: LaunchServices starts (or brings forward) the app. + return Some((PathBuf::from("/usr/bin/open"), vec![OsString::from("-a"), bundle.as_os_str().to_os_string()])); + } + let app = dir.join(if platform == Platform::Windows { format!("{exe}.exe") } else { exe.to_owned() }); + if !is_file(&app) { + return None; + } + Some(if platform == Platform::Windows { windows_launch(&app, install.system_root.as_deref()) } else { (app, Vec::new()) }) +} + +/// How Windows starts the app at `app`: through Explorer, as a double-click would. The app is then +/// no child of the CLI, so it outlives the MCP client ending the CLI's process tree (Claude Code +/// does on Windows), and it runs outside the container of a Microsoft Store client (Claude +/// Desktop): there, new files under `%APPDATA%` land in the client's package, where the app +/// started from the Start menu would never see them. Explorer reads a comma as a separator, so +/// such a path is started directly. (`%WINDIR%` can be empty under a Store client, hence +/// `%SystemRoot%`.) +fn windows_launch(app: &Path, system_root: Option<&OsStr>) -> (PathBuf, Vec) { + if app.to_string_lossy().contains(',') { + return (app.to_path_buf(), Vec::new()); + } + let root = system_root.filter(|r| !r.is_empty()).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + (root.join("explorer.exe"), vec![app.as_os_str().to_os_string()]) +} + +/// Keeps the app running when the MCP client stops the CLI (and its process group). +fn detach(c: &mut std::process::Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + c.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + #[cfg(not(any(unix, windows)))] + let _ = c; +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + fn plan( + cli: &str, + platform: Platform, + flatpak: bool, + appimage: Option<&str>, + root: Option<&str>, + exists: bool, + ) -> Option<(PathBuf, Vec)> { + // An AppImage's mount is where its CLI runs from. + let appdir = appimage.map(|_| OsString::from("/tmp/.mount")); + let install = Install { platform, flatpak, appimage: appimage.map(OsString::from), appdir, system_root: root.map(OsString::from) }; + launch_command(Path::new(cli), "photocraft", &install, &|_| exists) + } + + #[test] + fn windows_starts_the_app_through_explorer() { + let app = Path::new(r"C:\Program Files\PhotoCraft\photocraft.exe"); + let (program, args) = windows_launch(app, Some(OsStr::new(r"D:\Win"))); + assert_eq!(program, Path::new(r"D:\Win").join("explorer.exe")); + assert_eq!(args, [app.as_os_str()]); + // No usable %SystemRoot%: the default Windows folder. + let default = Path::new(r"C:\Windows").join("explorer.exe"); + assert_eq!(windows_launch(app, Some(OsStr::new(""))).0, default); + assert_eq!(windows_launch(app, None).0, default); + // Explorer would split this path at the comma. + let comma = Path::new(r"C:\Apps, tools\photocraft.exe"); + assert_eq!(windows_launch(comma, None), (comma.to_path_buf(), Vec::new())); + } + + #[test] + fn the_launch_command_fits_the_install() { + // Flatpak: the sandbox can't start the app. + assert_eq!(plan("/app/bin/photocraft-cli", Platform::Other, true, Some("/x.AppImage"), None, true), None); + // An AppImage starts its image, not the mount point the CLI runs from. + assert_eq!( + plan("/tmp/.mount/usr/bin/photocraft-cli", Platform::Other, false, Some("/home/a/P.AppImage"), None, false), + Some((PathBuf::from("/home/a/P.AppImage"), Vec::new())) + ); + // Another AppImage's variables (an MCP client packaged as one): the app beside the CLI. + let client = plan("/opt/pc/photocraft-cli", Platform::Other, false, Some("/home/a/Client.AppImage"), None, true); + assert_eq!(client, Some((PathBuf::from("/opt/pc/photocraft"), Vec::new()))); + let no_mount = Install { appimage: Some("/home/a/P.AppImage".into()), ..Install::default() }; + assert_eq!( + launch_command(Path::new("/tmp/.mount/usr/bin/photocraft-cli"), "photocraft", &no_mount, &|_| false), + None, + "APPIMAGE without APPDIR" + ); + // A macOS bundle opens through LaunchServices. + let (program, args) = plan("/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli", Platform::MacOs, false, None, None, false).unwrap(); + assert_eq!(program, Path::new("/usr/bin/open")); + assert_eq!(args, [OsString::from("-a"), OsString::from("/Applications/PhotoCraft.app")]); + // Beside the CLI, by the app's file name. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, true), Some((PathBuf::from("/opt/pc/photocraft"), Vec::new()))); + let (program, args) = plan(r"C:\PC\photocraft-cli.exe", Platform::Windows, false, None, Some(r"C:\Win"), true).unwrap(); + assert_eq!(program, Path::new(r"C:\Win").join("explorer.exe")); + // The app beside the CLI (on a non-Windows host the backslashes are no separators). + assert_eq!(args, [Path::new(r"C:\PC\photocraft-cli.exe").parent().unwrap().join("photocraft.exe").into_os_string()]); + // No app beside the CLI: nothing to start. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, false), None); + assert_eq!(plan("photocraft-cli", Platform::Other, false, None, None, true).map(|p| p.0), Some(PathBuf::from("photocraft"))); + } + + #[test] + fn a_window_never_shows_its_token() { + let w = Window { port: 7, pid: 9, token: "ab".repeat(32) }; + assert!(!format!("{w:?}").contains("abab")); + assert_eq!(w.addr(), "127.0.0.1:7"); + } +} diff --git a/crates/control/src/agents/mod.rs b/crates/control/src/agents/mod.rs new file mode 100644 index 0000000000..e1b0b9923e --- /dev/null +++ b/crates/control/src/agents/mod.rs @@ -0,0 +1,78 @@ +//! AI agents in the open window, with no UI toolkit: whether the person lets agents use the app, +//! how the app tells its own `-cli mcp` where it listens, and where that CLI sends each tool +//! call. +//! +//! One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents +//! use Craft apps*, which writes the launcher's app list (`craft_ai_agents`). With the suite's +//! `AI-MCP` flag on, an app lets agents in when that list names it ([`AgentSwitch`]); without the +//! flag, the app's own earlier consent decides ([`agents_allowed`]). Apps have no agents switch of +//! their own. +//! +//! While agents may connect, the app serves its control channel on loopback with a token +//! ([`crate::server`], [`crate::auth`], or its own) and publishes where in its settings folder +//! ([`CONNECTION_FILE`]): the port, its process id and the token file. The app's `-cli mcp` +//! reads that file before every tool call ([`Live`]), so an MCP client's configuration never holds +//! a port or a token. The file holds no secret. A crashed app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch removes it +//! ([`remove_stale_connection`]). An app that quits removes its own ([`remove_connection`]). +//! +//! | Part | Names | Builds | +//! |---|---|---| +//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | +//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | +//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | +//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | +//! +//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`), +//! which adds the egui link host and the Agents page of Preferences. +//! +//! # Adding an app +//! +//! The app (its id is the one in the ArtCraft Launcher's catalog, `"gridcraft"`): +//! +//! 1. At start, [`remove_stale_connection`] in its settings folder, then +//! `AgentSwitch::watch("gridcraft", wake)`, where `wake` asks the UI for a frame. +//! 2. Agents may connect while `settings.allow_agent_control && switch.allows(legacy)` +//! ([`AgentSettings::allow_agent_control`], [`AgentSwitch::allows`]); check it again when the +//! launcher's switch wakes the app and when the person changes the setting. When it turns true, +//! listen on loopback with a token, the token in an owner-only file +//! ([`crate::auth::App::write_token_file`]), and [`write_connection`] with [`Connection::new`]; +//! when it turns false, and when the app quits, stop listening and [`remove_connection`] with +//! the app's process id. No restart, no agents switch of its own. There is one connection file +//! per settings folder: an app that runs more than one process on one folder lets only one of +//! them accept agents. +//! +//! Its `gridcraft-cli mcp`: +//! +//! 1. A [`LiveConfig`] with the app's settings folder; `consent` reads its saved +//! [`AgentSettings`] and answers `agents_allowed(mcp_flag(), launcher_allows("gridcraft"), legacy)` +//! ([`agents_allowed`], [`mcp_flag`], [`launcher_allows`]); `connect` makes the app's client for a +//! [`Window`] (its address and token); `headless` makes its session without a window for +//! [`HeadlessFolders`]. [`launcher`] starts the app beside the CLI. +//! 2. Before every tool call, [`Live::resolve`] (from a blocking thread in an async server), then +//! the call goes to the [`Route`] it returns. `--headless` skips [`Live`] altogether. + +// The links above name items of the `agents` feature; without it they have nothing to point at, +// and the docs of the settings alone still build. +#![cfg_attr(not(all(feature = "agents", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))] + +mod settings; +pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder}; + +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod connection; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod live; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod switch; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use connection::{ + CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use live::{ + ConnectFn, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, Live, LiveConfig, Route, Window, find_window, + launcher, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag}; diff --git a/crates/control/src/agents/settings.rs b/crates/control/src/agents/settings.rs new file mode 100644 index 0000000000..04ae933aaf --- /dev/null +++ b/crates/control/src/agents/settings.rs @@ -0,0 +1,124 @@ +//! The agent settings an app saves in its preferences, and who decides that agents may connect. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in +/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +#[non_exhaustive] +pub struct AgentSettings { + /// Off refuses every control server, `--control` included. + pub allow_agent_control: bool, + /// The loopback port agents connect to; 0 is any free port, published in the connection file. + pub control_port: u32, + /// The folder agents may open from; empty is none. Applied at once while agents are connected. + pub read_root: String, + /// The folder agents may save to; empty is none. Applied at once while agents are connected. + pub write_root: String, + /// What the app's `-cli mcp` does while agents may use the app but it is closed. + pub when_app_closed: WhenAppClosed, +} + +impl Default for AgentSettings { + fn default() -> Self { + Self { + allow_agent_control: true, + control_port: 0, + read_root: String::new(), + write_root: String::new(), + when_app_closed: WhenAppClosed::Launch, + } + } +} + +impl AgentSettings { + /// [`Self::read_root`] as a path ([`folder`]). + pub fn read_folder(&self) -> Option { + folder(&self.read_root) + } + + /// [`Self::write_root`] as a path ([`folder`]). + pub fn write_folder(&self) -> Option { + folder(&self.write_root) + } +} + +/// A folder setting as a path, trimmed; empty or blank is `None`. +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +/// What an app's `-cli mcp` does when an agent calls a tool while the app is closed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WhenAppClosed { + /// Open the app and wait for it. + #[default] + Launch, + /// Run the tool without a window. + Headless, + /// Answer with an error that asks to open the app. + Error, +} + +impl WhenAppClosed { + /// The saved names, in [`Self::ALL`] order. + pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"]; + /// Every choice, in the order a menu lists them. + pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error]; + + /// The saved name. + pub fn name(self) -> &'static str { + match self { + Self::Launch => "launch", + Self::Headless => "headless", + Self::Error => "error", + } + } + + /// The choice a saved name means; `None` for any other text. + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.name() == name) + } +} + +/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's +/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own +/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch). +/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]). +pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool { + if mcp_flag { launcher } else { legacy } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + // The saved names read back as the same choice, and nothing else reads as one. + #[test] + fn when_app_closed_names_round_trip() { + for choice in WhenAppClosed::ALL { + assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice)); + assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name())); + } + assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name)); + assert_eq!(WhenAppClosed::parse("Launch"), None); + let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap(); + assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true)); + } + + // A folder setting is trimmed; empty or blank means no folder. + #[test] + fn folder_preferences_are_trimmed() { + assert_eq!(folder(""), None); + assert_eq!(folder(" "), None); + assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); + let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() }; + assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None)); + } +} diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs new file mode 100644 index 0000000000..9165879dc3 --- /dev/null +++ b/crates/control/src/agents/switch.rs @@ -0,0 +1,94 @@ +//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use super::agents_allowed; + +/// How often [`AgentSwitch::watch`] reads the launcher's app list. +pub const POLL: Duration = Duration::from_secs(2); + +/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file; +/// what could not be read is logged. +pub fn mcp_flag() -> bool { + let flags = craft_flags::load(); + for problem in &flags.problems { + log::warn!("flags: {problem}"); + } + flags.enabled(&craft_flags::AI_MCP) +} + +/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use +/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two +/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that). +pub fn launcher_allows(app_id: &str) -> bool { + mcp_flag() && craft_ai_agents::allowed(app_id) +} + +/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the +/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`]. +/// Clones share one watch; the thread ends after the last clone is dropped. +#[derive(Clone, Debug)] +pub struct AgentSwitch { + mcp_flag: bool, + on: Arc, +} + +impl AgentSwitch { + /// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake` (the + /// app asks for a frame there). + /// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then. + pub fn watch(app_id: &'static str, wake: impl Fn() + Send + 'static) -> Self { + let flag = mcp_flag(); + if !flag { + return Self::fixed(false, false); + } + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + } + + /// A switch that never changes: tests, the web, an app without agents. + pub fn fixed(mcp_flag: bool, launcher: bool) -> Self { + Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } + } + + /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + #[doc(hidden)] + pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + let on = Arc::new(AtomicBool::new(probe())); + let seen: Weak = Arc::downgrade(&on); + let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { + loop { + std::thread::sleep(poll); + let now = probe(); + let Some(seen) = seen.upgrade() else { return }; + if seen.swap(now, Ordering::Relaxed) != now { + log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); + wake(); + } + } + }); + // Without a thread a later "off" in the launcher would never be seen: agents stay out. + if let Err(e) = started { + log::warn!("couldn't watch the ArtCraft Launcher's agents switch, so agents stay off: {e}"); + on.store(false, Ordering::Relaxed); + } + Self { mcp_flag, on } + } + + /// The `AI-MCP` flag as it was when the watch started. + pub fn mcp_flag(&self) -> bool { + self.mcp_flag + } + + /// Whether the launcher's list named the app at the last poll. + pub fn launcher(&self) -> bool { + self.on.load(Ordering::Relaxed) + } + + /// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own + /// earlier consent, which counts only without the flag. + pub fn allows(&self, legacy: bool) -> bool { + agents_allowed(self.mcp_flag, self.launcher(), legacy) + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 26727a97c8..56ce2e685a 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -2,12 +2,15 @@ //! files ([`auth`]), the loopback server that admits a connection by the token and hands each //! request to the window ([`server`]), the client that talks to it ([`client`]), the request the //! window answers ([`ControlRequest`]), the document watch subscribed connections wait on -//! ([`DocumentWatch`]), and what a request still running does when it finishes ([`Effect`]). It +//! ([`DocumentWatch`]), what a request still running does when it finishes ([`Effect`]), and AI +//! agents in the open window behind the ArtCraft Launcher's switch ([`agents`]: its settings on +//! every target, the switch, the connection file and the CLI's side with feature `agents`). It //! needs no UI toolkit; the window's own requests over egui (`ui.screenshot`, `ui.resize`) are //! `craft-control-egui`. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod agents; pub mod auth; mod cancel; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs new file mode 100644 index 0000000000..95a4651eb4 --- /dev/null +++ b/crates/control/tests/agents.rs @@ -0,0 +1,572 @@ +//! AI agents in the open window: the launcher's switch, the connection file, and where an app's +//! `-cli mcp` sends each tool call. +// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_control::agents::{ + AgentSettings, AgentSwitch, CONNECTION_FILE, Connection, Consent, HeadlessFolders, Live, LiveConfig, Route, TOKEN_FILE, WhenAppClosed, Window, + agents_allowed, find_window, read_connection, remove_connection, remove_stale_connection, write_connection, +}; + +fn temp_dir(tag: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") +} + +/// Waits up to five seconds for `done`. +fn wait_for(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while !done() { + if started.elapsed() > Duration::from_secs(5) { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// Writes `text` as an owner-only token file, as an app's own token writer does. +fn write_token(path: &Path, text: &str) { + std::fs::write(path, text).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +/// An app accepting agents in `dir`: a listener on a free loopback port, its token file and its +/// connection file. Dropping the listener leaves the file behind, as a crashed app would. +fn publish(dir: &Path) -> (TcpListener, Connection) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + write_token(&dir.join(TOKEN_FILE), &format!("{}\n", TOKEN.to_ascii_uppercase())); + let c = Connection::new(listener.local_addr().unwrap().port(), dir.join(TOKEN_FILE), "Test 1.0"); + write_connection(dir, &c).unwrap(); + (listener, c) +} + +// ---- The launcher's switch ---------------------------------------------------------------------- + +/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. +#[test] +fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + assert!(agents_allowed(false, false, true), "without the flag, the app's earlier consent"); + assert!(!agents_allowed(false, true, false), "the launcher's list means nothing without the flag"); + assert!(agents_allowed(true, true, false)); + assert!(!agents_allowed(true, false, true), "no second switch in the app"); + assert!(AgentSwitch::fixed(true, true).allows(false)); + assert!(!AgentSwitch::fixed(false, true).allows(false)); +} + +/// The switch follows the launcher's list within a poll, wakes the app once per change rather than +/// once per poll, and its thread ends once the last clone is dropped. +#[test] +fn the_switch_wakes_once_per_change() { + let launcher = Arc::new(AtomicBool::new(false)); + let probes = Arc::new(AtomicUsize::new(0)); + let wakes = Arc::new(AtomicUsize::new(0)); + // Held by the watch thread through its probe: gone once the thread has ended. + let alive = Arc::new(()); + let probe = { + let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone()); + move || { + let _ = &alive; + probes.fetch_add(1, Ordering::Relaxed); + launcher.load(Ordering::Relaxed) + } + }; + let wake = { + let wakes = wakes.clone(); + move || { + wakes.fetch_add(1, Ordering::Relaxed); + } + }; + let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let clone = switch.clone(); + assert!(!switch.launcher()); + + launcher.store(true, Ordering::Relaxed); + assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(switch.allows(false)); + let polled = probes.load(Ordering::Relaxed); + assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + launcher.store(false, Ordering::Relaxed); + assert!(wait_for(|| !switch.launcher())); + assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); + + drop(switch); + drop(clone); + assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch"); + let after_end = probes.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended"); +} + +// ---- The connection file ------------------------------------------------------------------------ + +/// A published connection reads back in its documented shape, and only the process that wrote it +/// removes it. +#[test] +fn a_published_connection_reads_back_and_only_its_writer_removes_it() { + let dir = temp_dir("conn"); + let dir = dir.path(); + assert_eq!(read_connection(dir).unwrap(), None, "no file"); + let c = Connection::new(7878, dir.join(TOKEN_FILE), "MyApp 1.2.3"); + write_connection(dir, &c).unwrap(); + assert_eq!(read_connection(dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64(), v["app"].as_str()), (Some(1), Some(7878), Some("MyApp 1.2.3"))); + + remove_connection(dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); +} + +/// A damaged, foreign or port-0 file reads as none; a directory in its place is an error and is +/// left alone; a file nobody listens on is removed as stale and a live one kept. +#[test] +fn a_damaged_foreign_or_stale_connection_file_counts_as_none() { + let dir = temp_dir("bad-conn"); + let dir = dir.path(); + for text in [ + &b""[..], + b"{not json", + b"[]", + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } + + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(dir).is_err()); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_dir(), "anything but a regular file is left alone"); + std::fs::remove_dir(dir.join(CONNECTION_FILE)).unwrap(); + + let live = TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + let closed = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); +} + +// ---- The CLI's side ----------------------------------------------------------------------------- + +/// What the stand-in app made: a window client (its window) or a headless session (its folders), +/// with counts of each. +#[derive(Default)] +struct Made { + connects: AtomicUsize, + sessions: AtomicUsize, +} + +type TestLive = Live; + +fn config(dir: &Path, consent: Consent, made: &Arc) -> LiveConfig { + let (a, b) = (made.clone(), made.clone()); + let mut cfg = LiveConfig::new( + "Test", + dir.to_path_buf(), + move |_: &Path| consent.clone(), + move |w: &Window| { + a.connects.fetch_add(1, Ordering::Relaxed); + Ok(w.clone()) + }, + move |f: &HeadlessFolders| { + b.sessions.fetch_add(1, Ordering::Relaxed); + Ok(f.clone()) + }, + ); + cfg.poll = Duration::from_millis(5); + cfg +} + +fn settings(when: WhenAppClosed, read: &str, write: &str) -> AgentSettings { + let mut s = AgentSettings::default(); + s.when_app_closed = when; + s.read_root = read.into(); + s.write_root = write.into(); + s +} + +fn allowed(when: WhenAppClosed) -> Consent { + Consent::new(true, settings(when, "/app-in", "/app-out")) +} + +fn headless_folders(route: Result, String>) -> HeadlessFolders { + match route { + Ok(Route::Headless(f)) => f, + Ok(Route::Window(w)) => panic!("expected headless, got the window {w:?}"), + Err(e) => panic!("expected headless, got the error {e}"), + } +} + +fn window(route: Result, String>) -> Window { + match route { + Ok(Route::Window(w)) => w, + Ok(Route::Headless(f)) => panic!("expected the window, went headless with {f:?}"), + Err(e) => panic!("expected the window, got the error {e}"), + } +} + +fn paths(p: &[&str]) -> Vec { + p.iter().map(PathBuf::from).collect() +} + +/// An app accepting agents takes the call; the same port, token and process keep the client, a +/// restarted app (another process on the same port and token) gets a new one. +#[test] +fn an_open_app_takes_the_call_and_keeps_its_client_until_it_restarts() { + let dir = temp_dir("window"); + let (_listener, c) = publish(dir.path()); + let made = Arc::new(Made::default()); + // Even without consent: an app publishes its connection only while it accepts agents. + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + let w = window(live.resolve()); + assert_eq!( + (w.port, w.pid, w.token.as_str(), w.addr()), + (c.port, c.pid, TOKEN.to_ascii_uppercase().as_str(), c.addr()), + "the token is trimmed, otherwise as written" + ); + window(live.resolve()); + assert_eq!(made.connects.load(Ordering::Relaxed), 1, "the same window keeps its client"); + assert!(matches!(live.current(), Some(Route::Window(_)))); + + write_connection(dir.path(), &Connection { pid: c.pid.wrapping_add(1), ..c.clone() }).unwrap(); + assert_eq!(window(live.resolve()).pid, c.pid.wrapping_add(1)); + assert_eq!(made.connects.load(Ordering::Relaxed), 2, "a restarted app gets a new client"); + assert_eq!(made.sessions.load(Ordering::Relaxed), 0); +} + +/// No app accepts agents and the person doesn't let them use it: headless with only the command's +/// folders, never the app's. +#[test] +fn without_consent_a_closed_app_runs_headless_with_the_commands_folders_only() { + let dir = temp_dir("no-consent"); + let made = Arc::new(Made::default()); + let consent = Consent::new(false, settings(WhenAppClosed::Launch, "/app-in", "/app-out")); + let live = TestLive::new(config(dir.path(), consent.clone(), &made)); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "no folders given, none used"); + + let mut cfg = config(dir.path(), consent, &made); + cfg.read_roots = paths(&["/cli-in"]); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "headless": the app's agent folders, each replaced by the command's. +#[test] +fn allowed_and_closed_runs_headless_with_the_apps_folders_unless_the_command_gives_its_own() { + let dir = temp_dir("headless"); + let made = Arc::new(Made::default()); + let f = headless_folders(TestLive::new(config(dir.path(), allowed(WhenAppClosed::Headless), &made)).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.read_roots = paths(&["/cli-a", "/cli-b"]); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-a", "/cli-b"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "error": the call fails with words that name the app; the command's +/// choice wins over the app's. +#[test] +fn the_closed_app_choice_decides_and_the_command_overrides_it() { + let dir = temp_dir("error"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running: open it, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Error), &made); + cfg.when_closed = Some(WhenAppClosed::Headless); + headless_folders(TestLive::new(cfg).resolve()); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.when_closed = Some(WhenAppClosed::Error); + assert!(TestLive::new(cfg).resolve().is_err()); +} + +/// Once headless, the session stays headless even when the app starts, so documents don't move +/// under the agent. +#[test] +fn a_headless_session_stays_headless() { + let dir = temp_dir("sticky"); + let made = Arc::new(Made::default()); + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + headless_folders(live.resolve()); + let _app = publish(dir.path()); + headless_folders(live.resolve()); + assert_eq!((made.sessions.load(Ordering::Relaxed), made.connects.load(Ordering::Relaxed)), (1, 0), "one session, no window"); +} + +/// A connection file left by an app that crashed counts as a closed app. +#[test] +fn a_crashed_apps_connection_file_counts_as_closed() { + let dir = temp_dir("crashed"); + drop(publish(dir.path()).0); + let made = Arc::new(Made::default()); + headless_folders(TestLive::new(config(dir.path(), Consent::default(), &made)).resolve()); + assert_eq!(find_window(dir.path(), "Test").unwrap(), None); +} + +/// A token file that isn't a token, is too big, is missing, isn't a regular file or (on Unix) +/// others can read fails the call and names the app; nothing is sent to the window. +#[test] +fn a_bad_token_file_fails_the_call() { + let dir = temp_dir("token"); + let (_listener, _c) = publish(dir.path()); + let made = Arc::new(Made::default()); + for bad in ["", " \n", "not a token", &"a".repeat(5000)] { + write_token(&dir.path().join(TOKEN_FILE), bad); + let err = TestLive::new(config(dir.path(), Consent::default(), &made)).resolve().err().unwrap(); + assert!(err.starts_with("Test's agent token: "), "{err}"); + } + // Any token the app's server accepts is passed on: upper case, dashes. + write_token(&dir.path().join(TOKEN_FILE), "AB12-cd34-EF56-0000-1111-2222-3333-4444"); + assert_eq!(find_window(dir.path(), "Test").unwrap().unwrap().token, "AB12-cd34-EF56-0000-1111-2222-3333-4444"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let token = dir.path().join(TOKEN_FILE); + write_token(&token, TOKEN); + std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o644)).unwrap(); + let err = find_window(dir.path(), "Test").err().unwrap(); + assert!(err.contains("readable by group or others"), "{err}"); + // A FIFO would block a plain open until something writes to it. + std::fs::remove_file(&token).unwrap(); + assert!(std::process::Command::new("mkfifo").arg(&token).status().unwrap().success()); + let err = find_window(dir.path(), "Test").err().unwrap(); + assert!(err.contains("not a regular file"), "{err}"); + } + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + assert!(find_window(dir.path(), "Test").is_err()); + assert_eq!(made.connects.load(Ordering::Relaxed), 0); +} + +/// The app's own errors reach the agent with what was being done. +#[test] +fn the_apps_errors_reach_the_agent() { + let dir = temp_dir("app-errors"); + let consent = Consent::default(); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + move |_: &Path| consent.clone(), + |w: &Window| Ok(w.clone()), + |_: &HeadlessFolders| Err("no such folder".into()), + ); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "Test can't use the automation roots: no such folder"); + + let (_listener, _c) = publish(dir.path()); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + |_: &Path| Consent::default(), + |_: &Window| Err("refused".into()), + |f: &HeadlessFolders| Ok(f.clone()), + ); + let live = TestLive::new(cfg); + assert_eq!(live.resolve().err().unwrap(), "couldn't reach Test's window: refused"); + assert!(live.current().is_none(), "a failed connect leaves no route"); +} + +/// "Launch" without a way to start the app, a start that fails, and an app that never accepts +/// agents each end with words that say what to do. +#[test] +fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { + let dir = temp_dir("launch-fails"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Launch), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running, and this install can't start it from here: open Test, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Err("boom".into()))); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "couldn't start Test: boom"); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::from_millis(40); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); +} + +/// "Launch" starts the app once, also for calls that arrive together, and the calls go to its +/// window once it accepts agents. +#[test] +fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { + let dir = temp_dir("launch"); + let made = Arc::new(Made::default()); + let launches = Arc::new(AtomicUsize::new(0)); + let app: Arc>> = Arc::new(Mutex::new(None)); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + cfg.launch = Some(Box::new(move || { + n.fetch_add(1, Ordering::Relaxed); + let (d, slot) = (d.clone(), slot.clone()); + // The app takes a moment before it accepts agents. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(60)); + *slot.lock().unwrap() = Some(publish(&d).0); + }); + Ok(()) + })); + let live = Arc::new(TestLive::new(cfg)); + let calls: Vec<_> = (0..4) + .map(|_| { + let live = live.clone(); + std::thread::spawn(move || window(live.resolve())) + }) + .collect(); + let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); + assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); + assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); + assert_eq!(made.connects.load(Ordering::Relaxed), 1); +} + +/// Calls that queued while a start was under way get its error when the app still isn't there, +/// rather than starting it again; a call made afterwards tries again. +#[test] +fn calls_queued_behind_a_failed_start_share_its_error() { + let dir = temp_dir("launch-shared"); + let made = Arc::new(Made::default()); + let launches = Arc::new(AtomicUsize::new(0)); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let entered = Arc::new(AtomicUsize::new(0)); + let (n, e) = (launches.clone(), entered.clone()); + // The app is started but never accepts agents within the timeout. The start waits until every + // call is under way and then a while longer, so a call that hasn't reached its lookup by the + // time the start ends is very unlikely (there is no hook between the two). + cfg.launch = Some(Box::new(move || { + n.fetch_add(1, Ordering::Relaxed); + assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts"); + std::thread::sleep(Duration::from_millis(250)); + Ok(()) + })); + cfg.launch_timeout = Duration::from_millis(150); + let live = Arc::new(TestLive::new(cfg)); + let calls: Vec<_> = (0..4) + .map(|_| { + let (live, entered) = (live.clone(), entered.clone()); + std::thread::spawn(move || { + entered.fetch_add(1, Ordering::Relaxed); + live.resolve() + }) + }) + .collect(); + let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect(); + assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for the calls that came together"); + for answer in &answers { + let err = answer.as_ref().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within"), "{err}"); + } + assert!(live.resolve().is_err()); + assert_eq!(launches.load(Ordering::Relaxed), 2, "a later call starts the app again"); +} + +/// Allow Agent Control off refuses agents on the CLI's side too, as the app does by not +/// listening: no start, and only the command's folders. +#[test] +fn allow_agent_control_off_counts_as_not_allowed() { + let dir = temp_dir("aac-off"); + let made = Arc::new(Made::default()); + let mut s = settings(WhenAppClosed::Launch, "/app-in", "/app-out"); + s.allow_agent_control = false; + let mut cfg = config(dir.path(), Consent::new(true, s), &made); + cfg.launch = Some(Box::new(|| panic!("nothing may start the app"))); + cfg.read_roots = paths(&["/cli-in"]); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-in"]), None)); +} + +/// A window route is dropped once no app accepts agents, so a dead client isn't kept or handed +/// back. +#[test] +fn a_window_that_went_away_is_forgotten() { + let dir = temp_dir("gone"); + let made = Arc::new(Made::default()); + let live = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made)); + let (listener, c) = publish(dir.path()); + window(live.resolve()); + drop(listener); + remove_connection(dir.path(), c.pid); + assert!(live.resolve().is_err(), "the app is closed and the choice is an error"); + assert!(live.current().is_none(), "the dead window is gone"); +} + +/// A headless session with the app's agent folders ends when the person stops letting agents in; +/// one with only the command's folders stays. +#[test] +fn a_headless_session_with_the_apps_folders_ends_with_consent() { + let dir = temp_dir("revoke"); + let made = Arc::new(Made::default()); + let on = Arc::new(AtomicBool::new(true)); + let gate = on.clone(); + let (b, c) = (made.clone(), made.clone()); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + move |_: &Path| Consent::new(gate.load(Ordering::Relaxed), settings(WhenAppClosed::Headless, "/app-in", "/app-out")), + move |w: &Window| { + b.connects.fetch_add(1, Ordering::Relaxed); + Ok(w.clone()) + }, + move |f: &HeadlessFolders| { + c.sessions.fetch_add(1, Ordering::Relaxed); + Ok(f.clone()) + }, + ); + let live = TestLive::new(cfg); + assert_eq!(headless_folders(live.resolve()).read, paths(&["/app-in"])); + on.store(false, Ordering::Relaxed); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "the app's folders went with the consent"); + on.store(true, Ordering::Relaxed); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "a session without the app's folders stays"); + assert_eq!(made.sessions.load(Ordering::Relaxed), 2); +} + +/// A huge launch timeout or poll is cut down rather than overflowing the deadline or blocking. +#[test] +fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() { + let dir = temp_dir("huge"); + let made = Arc::new(Made::default()); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let (d, app) = (dir.path().to_path_buf(), Arc::new(Mutex::new(None))); + let slot = app.clone(); + cfg.launch = Some(Box::new(move || { + *slot.lock().unwrap() = Some(publish(&d).0); + Ok(()) + })); + cfg.launch_timeout = Duration::MAX; + cfg.poll = Duration::MAX; + let started = Instant::now(); + window(TestLive::new(cfg).resolve()); + assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); +} diff --git a/crates/csv/README.md b/crates/csv/README.md index bfd525c8cf..8fd264d4c8 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record counts the delimiters of the first record up to the end of the sample, or up to a quoted field still open there, and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 70f6148a6e..395ad21523 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -33,13 +33,17 @@ pub use decode::{decode_text, decode_utf8}; /// Picks comma, semicolon or tab by consistent field counts in the first non-blank records. /// Quotes start only at a candidate field boundary; candidates with incoherent quoted fields /// are discarded when another coherent candidate separates the records. Ties prefer tab, -/// then comma, then semicolon. Comma is the fallback when no candidate separates the text. +/// then comma, then semicolon. When no candidate separates the records that hold other text, +/// the same rules pick among the candidates whose records hold only their delimiters and +/// whitespace, such as an exported row of empty cells; a candidate that finds a record with +/// other text is left out of that pick. Comma is the fallback when neither pick finds one. /// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, /// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate -/// that finds no complete record counts the delimiters read so far in the first record, and that -/// record is incoherent when it has a quote inside a field that does not start with one. When one -/// of those candidates ends the sample inside a quoted field, each of them counts only up to that -/// field's opening quote. +/// that finds no complete record with other text counts the delimiters read so far in the first +/// such record, unless it found rows of its empty cells and that record has none of its +/// delimiters. That record is incoherent when it has a quote inside a field that does not start +/// with one. When one of those candidates ends the sample inside a quoted field, each of them +/// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { const SAMPLE_BYTES: usize = 64 * 1024; let mut sample_end = text.len().min(SAMPLE_BYTES); @@ -64,7 +68,15 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { (scan.count, scan.record_has_content, scan.record_coherent, scan.record_bare_quote) = (before_cut.count, before_cut.record_has_content, before_cut.record_coherent, before_cut.record_bare_quote); } - if scan.record_has_content { + if scan.delimiter_only_counts.is_empty() { + if scan.record_has_content { + scan.coherent &= scan.record_coherent && !scan.record_bare_quote; + scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); + } + } else if scan.record_has_content && scan.count > 0 { + // After rows of empty cells, a cut record without this delimiter is left out. scan.coherent &= scan.record_coherent && !scan.record_bare_quote; scan.counts.push(scan.count); } @@ -79,6 +91,8 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } else if scan.record_has_content { scan.coherent &= scan.record_coherent; scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); } } } @@ -86,23 +100,34 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { - let candidates = - scans.map(|scan| (scan.delimiter, scan.counts.iter().copied().min().unwrap_or(0), scan.counts.iter().sum::(), scan.coherent)); + let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent)); + // Records of delimiters alone have no quotes, so they are coherent. + let delimiters_only = + scans.each_ref().map(|scan| (scan.delimiter, if scan.counts.is_empty() { scan.delimiter_only_counts.as_slice() } else { &[] }, true)); + best_delimiter(with_text).or_else(|| best_delimiter(delimiters_only)).unwrap_or(b',') +} + +fn best_delimiter(candidates: [(u8, &[usize], bool); 3]) -> Option { + let candidates = candidates + .map(|(delimiter, counts, coherent)| (delimiter, counts.iter().copied().min().unwrap_or(0), counts.iter().sum::(), coherent)); let prefer_coherent = candidates.iter().any(|(_, min, _, coherent)| *min > 0 && *coherent); - let mut best = (b',', 0usize, 0usize); + let mut best: Option<(u8, usize, usize)> = None; for (delimiter, min, total, coherent) in candidates { - if min > 0 && (!prefer_coherent || coherent) && (min, total) > (best.1, best.2) { - best = (delimiter, min, total); + if min > 0 && (!prefer_coherent || coherent) && best.is_none_or(|(_, best_min, best_total)| (min, total) > (best_min, best_total)) { + best = Some((delimiter, min, total)); } } - best.0 + best.map(|(delimiter, _, _)| delimiter) } /// One candidate delimiter's pass over the sample in [`sniff_delimiter`]. struct DelimiterScan { delimiter: u8, - /// Delimiter counts of the complete non-blank records, at most 20. + /// Delimiter counts of the complete records that hold other text, at most 20. counts: Vec, + /// Delimiter counts of the complete records that hold only this candidate's delimiters and + /// whitespace, at most 20. They do not count toward the 20 records above. + delimiter_only_counts: Vec, /// Whether every counted record had coherent quoted fields. coherent: bool, reached_record_limit: bool, @@ -117,10 +142,21 @@ struct DelimiterScan { open_quote: Option, } +impl DelimiterScan { + /// Keeps the open record's delimiter count when the record has no other text and at least + /// one delimiter. + fn push_delimiter_only_record(&mut self) { + if !self.record_has_content && self.count > 0 && self.delimiter_only_counts.len() < 20 { + self.delimiter_only_counts.push(self.count); + } + } +} + fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { let mut scan = DelimiterScan { delimiter, counts: Vec::new(), + delimiter_only_counts: Vec::new(), coherent: true, reached_record_limit: false, count: 0, @@ -158,6 +194,8 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { scan.reached_record_limit = true; break; } + } else { + scan.push_delimiter_only_record(); } scan.count = 0; after_quote = false; @@ -403,6 +441,64 @@ mod tests { assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); } + // A sheet whose only value is far down exports rows of empty cells that fill the whole sample. + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export() { + assert_eq!(sniff_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export_with_crlf() { + assert_eq!(sniff_delimiter(&format!("{};7\r\n", ";\r\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_tab_export() { + assert_eq!(sniff_delimiter(&format!("{}\t7\r\n", "\t\r\n".repeat(40_000)), '"'), b'\t'); + } + + #[test] + fn delimiter_sniffing_reads_a_short_file_of_empty_semicolon_cells() { + assert_eq!(sniff_delimiter(";;\n;;\n", '"'), b';'); + assert_eq!(sniff_delimiter(";;\r\n;;", '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_empty_semicolon_cells_padded_with_whitespace() { + assert_eq!(sniff_delimiter(&"; ; \n".repeat(20_000), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_first_record_of_empty_cells_longer_than_the_sample() { + assert_eq!(sniff_delimiter(&format!("{}\n1;2\n", ";".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_leaves_out_a_cut_record_after_a_row_of_empty_cells() { + assert_eq!(sniff_delimiter(&format!(";\n{};7\n", "x".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_counts_a_long_record_after_a_row_of_empty_cells() { + // Delimiters inside the long record's quoted field are text for every candidate. + assert_eq!(sniff_delimiter(&format!("\t\nname\t\"{}\"\n", "x,y".repeat(30_000)), '"'), b'\t'); + assert_eq!(sniff_delimiter(&format!(";\nname;\"{}\"\n", "x,y\t".repeat(20_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_lets_records_with_text_outweigh_records_of_delimiters_alone() { + // Rows of tabs alone are blank to the other candidates and do not outweigh them. + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\n".repeat(25)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\t\n".repeat(25)), '"'), b';'); + // The same holds for a record with text cut off at the end of the sample. + assert_eq!(sniff_delimiter(&format!("\t\n{}", "x;".repeat(40_000)), '"'), b';'); + // A candidate with a record of other text is judged on those records alone. + assert_eq!(sniff_delimiter(&format!("title\n{}", ";\n".repeat(25)), '"'), b','); + // Rows of empty cells in a comma file; comma is also the fallback. + assert_eq!(sniff_delimiter("a,b,c,d\n,,,\n,,,\n1,2,3,4\n", '"'), b','); + assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b','); + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 183ec4fa14..685ce81dd6 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -430,6 +430,7 @@ pub struct Texture<'a> { encoding: Encoding, /// Where the top level's pixel data starts. start: usize, + levels: u32, } impl<'a> Texture<'a> { @@ -456,7 +457,8 @@ impl<'a> Texture<'a> { if width == 0 || height == 0 { return Err(bad("texture dimensions must be nonzero")); } - Ok(Texture { bytes: b, flags, width, height, encoding, start }) + let levels = le32(b, 28)?.max(1).min(mip_levels(width, height)); + Ok(Texture { bytes: b, flags, width, height, encoding, start, levels }) } pub fn width(&self) -> u32 { @@ -472,6 +474,51 @@ impl<'a> Texture<'a> { self.encoding.layout() } + /// Number of declared mip levels, capped by the chain down to one pixel. + pub fn levels(&self) -> u32 { + self.levels + } + + /// The encoding named by the header, including unsigned BC4 and BC5. + pub fn compression(&self) -> DdsCompression { + match self.encoding { + Encoding::Masks { .. } | Encoding::Unorm16 { .. } => DdsCompression::None, + Encoding::Bc1 => DdsCompression::Bc1, + Encoding::Bc2 => DdsCompression::Bc2, + Encoding::Bc3 => DdsCompression::Bc3, + Encoding::Bc4 => DdsCompression::Bc4, + Encoding::Bc5 => DdsCompression::Bc5, + } + } + + /// A borrowed view of one mip level, without allocating or decoding pixels. + /// Lower levels are tightly packed; only the top level uses the header's row pitch. + pub fn mip_level(&self, index: u32) -> Result, DdsError> { + if index >= self.levels { + return Err(bad("mip level index is outside the declared chain")); + } + let (mut width, mut height, mut start) = (self.width, self.height, self.start); + for i in 0..index { + let pitch = if i == 0 && self.flags & DDSD_PITCH != 0 { Some(le32(self.bytes, 20)?) } else { None }; + let (_, size) = self.encoding.level_layout(width, height, pitch)?; + start = start.checked_add(size).ok_or_else(|| bad("mip offset overflow"))?; + if start > self.bytes.len() { + return Err(bad("truncated mip data")); + } + width = (width / 2).max(1); + height = (height / 2).max(1); + } + Ok(Texture { + bytes: self.bytes, + flags: if index == 0 { self.flags } else { self.flags & !DDSD_PITCH }, + width, + height, + encoding: self.encoding, + start, + levels: self.levels - index, + }) + } + /// The top mip level's pixels in [`Texture::layout`], bounded by [`DEFAULT_MAX_DECODE_BYTES`]. pub fn decode(&self) -> Result, DdsError> { self.decode_with_limit(DEFAULT_MAX_DECODE_BYTES) diff --git a/crates/dds/tests/boundary.rs b/crates/dds/tests/boundary.rs index ecd3aac112..3a891f73ab 100644 --- a/crates/dds/tests/boundary.rs +++ b/crates/dds/tests/boundary.rs @@ -44,3 +44,53 @@ fn default_budget_rejects_oversized_header_before_payload_or_allocation() { assert!(matches!(texture.decode(), Err(craft_dds::DdsError::LimitExceeded { limit: craft_dds::DEFAULT_MAX_DECODE_BYTES, .. }))); assert!(matches!(texture.decode_with_limit(u64::MAX), Err(craft_dds::DdsError::Malformed(_)))); } + +#[test] +fn mip_views_reuse_shared_decoders_and_keep_their_bounds() { + for (compression, layout, channels) in [ + (DdsCompression::None, Layout::Gray, 1), + (DdsCompression::Bc1, Layout::Rgba, 4), + (DdsCompression::Bc4, Layout::Gray, 1), + (DdsCompression::Bc5, Layout::Rgb, 3), + ] { + let bytes = encode(4, 4, layout, &vec![71; 16 * channels], DdsOptions { compression, mipmaps: true }).unwrap(); + let texture = Texture::parse(&bytes).unwrap(); + assert_eq!(texture.levels(), 3); + assert_eq!(texture.compression(), compression); + assert!(texture.mip_level(3).is_err()); + assert!(texture.mip_level(u32::MAX).is_err()); + for (index, side) in [(0, 4), (1, 2), (2, 1)] { + let level = texture.mip_level(index).unwrap(); + assert_eq!((level.width(), level.height()), (side, side)); + let len = side as usize * side as usize * channels; + assert!(matches!(level.decode_with_limit((len - 1) as u64), Err(craft_dds::DdsError::LimitExceeded { .. }))); + assert_eq!(level.decode_with_limit(len as u64).unwrap().len(), len); + } + let nested = texture.mip_level(1).unwrap().mip_level(1).unwrap(); + assert_eq!(nested.decode().unwrap(), texture.mip_level(2).unwrap().decode().unwrap()); + } +} + +#[test] +fn sixteen_bit_mip_views_preserve_samples_and_stored_offsets() { + for (layout, channels) in [(Layout::Gray, 1), (Layout::GrayA, 2), (Layout::Rgba, 4)] { + let pixels: Vec = (0..16).flat_map(|p| (0..channels).map(move |c| (p * 400 + c * 31 + 7) as u16)).collect(); + let bytes = craft_dds::encode16(4, 4, layout, &pixels, DdsOptions { compression: DdsCompression::None, mipmaps: true }).unwrap(); + let texture = Texture::parse(&bytes).unwrap(); + assert_eq!(texture.compression(), DdsCompression::None); + assert_eq!(texture.levels(), 3); + assert_eq!(texture.decode16().unwrap(), pixels); + for (index, averages) in [(1, vec![1000, 1800, 4200, 5000]), (2, vec![3000])] { + let expected: Vec = averages.iter().flat_map(|p| (0..channels).map(move |c| (p + c * 31 + 7) as u16)).collect(); + let level = texture.mip_level(index).unwrap(); + let budget = (expected.len() * 2) as u64; + assert!(matches!(level.decode16_with_limit(budget - 1), Err(craft_dds::DdsError::LimitExceeded { .. }))); + assert_eq!(level.decode16_with_limit(budget).unwrap(), expected); + let rounded: Vec = expected.iter().map(|&v| ((u32::from(v) + 128) / 257) as u8).collect(); + assert_eq!(level.decode().unwrap(), rounded); + } + assert_eq!(texture.mip_level(1).unwrap().mip_level(1).unwrap().decode16().unwrap(), texture.mip_level(2).unwrap().decode16().unwrap()); + let truncated = Texture::parse(&bytes[..bytes.len() - 1]).unwrap(); + assert!(truncated.mip_level(2).unwrap().decode16().is_err()); + } +} diff --git a/crates/designcraft-format/src/lib.rs b/crates/designcraft-format/src/lib.rs index eab431eab8..9ce481a3b1 100644 --- a/crates/designcraft-format/src/lib.rs +++ b/crates/designcraft-format/src/lib.rs @@ -127,9 +127,10 @@ pub fn starts_designcraft(prefix: &[u8]) -> bool { craft_document_bundle::starts_with_mimetype(prefix, BUNDLE) } -/// Read the first-page PNG preview from a ZIP package, with a fixed 4 MiB cap. +/// Read the first-page PNG preview from an unprefixed native ZIP package, with a fixed 4 MiB cap. +/// Nonmatching signatures are rejected after at most four bytes read. pub fn read_preview(reader: R) -> Option> { - craft_document_bundle::read_preview_from(reader, PREVIEW) + craft_document_bundle::read_unprefixed_preview_from(reader, PREVIEW) } fn is_linked(document: &Value, id: &str) -> bool { diff --git a/crates/designcraft-format/src/tests.rs b/crates/designcraft-format/src/tests.rs index 38cf1c34f5..736d2e17cd 100644 --- a/crates/designcraft-format/src/tests.rs +++ b/crates/designcraft-format/src/tests.rs @@ -167,3 +167,37 @@ fn bytes_supplied_for_a_linked_asset_are_not_written() -> Result<(), Box(&bytes)?.assets, [("8".to_owned(), b"kept".to_vec())]); Ok(()) } + +#[test] +fn preview_uses_the_strict_signature_path_without_losing_cursor_independence() -> Result<(), Box> { + struct Counted { + cursor: std::io::Cursor>, + bytes_read: usize, + } + impl std::io::Read for Counted { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + let n = self.cursor.read(out)?; + self.bytes_read += n; + Ok(n) + } + } + impl std::io::Seek for Counted { + fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result { + self.cursor.seek(position) + } + } + let mut non_zip = Counted { cursor: std::io::Cursor::new(vec![0x42; 1 << 20]), bytes_read: 0 }; + non_zip.cursor.set_position(100); + assert_eq!(read_preview(&mut non_zip), None); + assert!(non_zip.bytes_read <= 4); + + let bytes = save(&json!({}), "DesignCraft test", Some(b"png"), &[], &[])?; + let mut cursor = std::io::Cursor::new(&bytes); + cursor.set_position(bytes.len() as u64); + assert_eq!(read_preview(cursor), Some(b"png".to_vec())); + let mut prefixed = b"MZsynthetic-prefix".to_vec(); + prefixed.extend(bytes); + assert_eq!(craft_document_bundle::read_preview_from(std::io::Cursor::new(&prefixed), PREVIEW), Some(b"png".to_vec())); + assert_eq!(read_preview(std::io::Cursor::new(prefixed)), None); + Ok(()) +} diff --git a/crates/dex/Cargo.toml b/crates/dex/Cargo.toml new file mode 100644 index 0000000000..fc7e35d1d4 --- /dev/null +++ b/crates/dex/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name="craft-dex" +description="Dalvik DEX reader and bytecode decoder with retained input bounds and partial-report semantics" +version.workspace=true +edition.workspace=true +license.workspace=true +rust-version.workspace=true +repository.workspace=true +[lints] +workspace=true +[dependencies] +serde={workspace=true} +thiserror={workspace=true} + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/dex/src/bytes.rs b/crates/dex/src/bytes.rs new file mode 100644 index 0000000000..3e69ae4fdf --- /dev/null +++ b/crates/dex/src/bytes.rs @@ -0,0 +1,85 @@ +//! 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 is_empty(&self) -> bool { + self.data.is_empty() + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. + pub fn cstr(&self, off: usize, max: usize) -> Option { + let rest = self.data.get(off..)?; + let rest = rest.get(..max.min(rest.len()))?; + let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); + Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) + } + + /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. + pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { + let mut result = 0u64; + for i in 0..10usize { + let b = self.u8(off.checked_add(i)?)?; + let payload = u64::from(b & 0x7f); + let shift = 7 * i as u32; + if shift > 0 && payload.checked_shl(shift)? >> shift != payload { + return None; + } + result |= payload << shift; + if b & 0x80 == 0 { + return Some((result, i + 1)); + } + } + None + } +} + +/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves, +/// so a damaged sequence cannot hide valid text or borrow missing bytes. +pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) { + match bytes { + [a @ 0x00..=0x7f, ..] => (u16::from(*a), 1), + [0xc0, 0x80, ..] => (0, 2), + [a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2), + [a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => { + ((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3) + } + _ => (0xfffd, 1), + } +} diff --git a/crates/dex/src/dex.rs b/crates/dex/src/dex.rs new file mode 100644 index 0000000000..8c0b25573a --- /dev/null +++ b/crates/dex/src/dex.rs @@ -0,0 +1,1154 @@ +//! Dalvik executables (DEX): header, string/type/proto/field/method ids, class definitions, +//! class data, code items with try/catch handlers, class annotations, a smali-like listing of +//! method bodies and a reference finder. Counts are checked against the file size, strings are +//! decoded from MUTF-8 under a total budget, and every read is bounds-checked. + +use crate::FormatError; +use crate::bytes::Reader; +use crate::dex_ops::{IndexKind, Insn, Payload}; +use serde::Serialize; + +pub const NO_INDEX: u32 = 0xffff_ffff; +/// Longest string decoded (UTF-16 units). +const MAX_STRING_UNITS: usize = 16 * 1024; +/// Total UTF-16 units decoded across all strings of one file. +const STRING_BUDGET: usize = 64 * 1024 * 1024; +/// Most members per class list. +const MAX_MEMBERS: usize = 65_536; +/// Most try blocks / handlers per method. +const MAX_TRIES: usize = 4096; +const MAX_HANDLERS: usize = 256; +/// Most handler descriptor bytes retained while reading one code item, however many try blocks +/// share a handler list. +const MAX_HANDLER_DESCRIPTOR_BYTES: usize = 1 << 20; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Header { + pub version: String, + pub checksum: String, + /// Adler-32 recomputed over the file. + pub checksum_ok: bool, + /// SHA-1 field as stored (not recomputed). + pub signature: String, + pub file_size: u32, + pub header_size: u32, + pub endian_tag: String, + pub string_ids: u32, + pub type_ids: u32, + pub proto_ids: u32, + pub field_ids: u32, + pub method_ids: u32, + pub class_defs: u32, + pub data_size: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ProtoId { + shorty: u32, + ret: u32, + params_off: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MemberId { + pub class_idx: u16, + /// Type (fields) or proto (methods). + pub type_or_proto: u16, + pub name_idx: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ClassDef { + pub class_idx: u32, + pub access: u32, + pub superclass_idx: u32, + pub interfaces_off: u32, + pub source_file_idx: u32, + pub annotations_off: u32, + pub class_data_off: u32, + pub static_values_off: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct EncodedField { + pub field_idx: u32, + pub access: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct EncodedMethod { + pub method_idx: u32, + pub access: u32, + pub code_off: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ClassData { + pub static_fields: Vec, + pub instance_fields: Vec, + pub direct_methods: Vec, + pub virtual_methods: Vec, + pub complete: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Handler { + /// Exception type descriptor; `None` for catch-all. + pub exception: Option, + pub address: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Try { + pub start: u32, + pub end: u32, + pub handlers: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Code { + pub registers: u16, + pub ins: u16, + pub outs: u16, + pub insns: Vec, + pub tries: Vec, + pub debug_info_off: u32, +} + +/// A parsed DEX file. +#[derive(Debug, Clone)] +pub struct Dex<'a> { + data: &'a [u8], + pub header: Header, + pub strings: Vec, + types: Vec, + protos: Vec, + pub fields: Vec, + pub methods: Vec, + pub classes: Vec, + pub warnings: Vec, +} + +fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for chunk in data.chunks(5552) { + for &x in chunk { + a += u32::from(x); + b += a; + } + a %= 65521; + b %= 65521; + } + (b << 16) | a +} + +/// Decode modified UTF-8 (as used by DEX and class files) to a String. +pub fn mutf8(r: &Reader<'_>, mut at: usize, max_units: usize) -> (String, usize) { + let mut units: Vec = Vec::new(); + let mut consumed = 0usize; + while units.len() < max_units { + let Some(b0) = r.u8(at) else { break }; + if b0 == 0 { + break; + } + let (u, n) = crate::bytes::mutf8_unit(r.data().get(at..).unwrap_or_default()); + units.push(u); + at = at.saturating_add(n); + consumed += n; + } + (String::from_utf16_lossy(&units), consumed) +} + +/// Signed 32-bit DEX LEB128 at `off`: (value, bytes), using at most five bytes. +pub fn sleb128(r: &Reader<'_>, off: usize) -> Option<(i64, usize)> { + let mut result = 0i64; + let mut shift = 0u32; + for i in 0..5usize { + let b = r.u8(off.checked_add(i)?)?; + // Four value bits remain in byte five; the other bits must extend the sign. + if i == 4 && !matches!(b, 0x00..=0x07 | 0x78..=0x7f) { + return None; + } + result |= i64::from(b & 0x7f).checked_shl(shift)?; + shift += 7; + if b & 0x80 == 0 { + if shift < 64 && b & 0x40 != 0 { + result |= -1i64 << shift; + } + return Some((result, i + 1)); + } + } + None +} + +/// `Lcom/x/Y;` → `com.x.Y`; `[I` → `int[]`. +pub fn java_name(desc: &str) -> String { + let dims = desc.chars().take_while(|&c| c == '[').count(); + let base = desc.get(dims..).unwrap_or(""); + let name = match base { + "V" => "void".to_string(), + "Z" => "boolean".to_string(), + "B" => "byte".to_string(), + "S" => "short".to_string(), + "C" => "char".to_string(), + "I" => "int".to_string(), + "J" => "long".to_string(), + "F" => "float".to_string(), + "D" => "double".to_string(), + b if b.starts_with('L') && b.ends_with(';') => b.get(1..b.len() - 1).unwrap_or("").replace('/', "."), + b => b.to_string(), + }; + format!("{name}{}", "[]".repeat(dims.min(255))) +} + +/// `com.x.Y` or `com/x/Y` or `Lcom/x/Y;` → `Lcom/x/Y;`. +pub fn to_descriptor(name: &str) -> String { + let n = name.trim(); + if n.starts_with('L') && n.ends_with(';') { n.to_string() } else { format!("L{};", n.replace('.', "/")) } +} + +/// Access flag names for a class, field or method. +pub fn access_flags(flags: u32, kind: &str) -> Vec<&'static str> { + let mut v = Vec::new(); + let table: &[(u32, &str)] = &[ + (0x1, "public"), + (0x2, "private"), + (0x4, "protected"), + (0x8, "static"), + (0x10, "final"), + (0x100, "native"), + (0x200, "interface"), + (0x400, "abstract"), + (0x800, "strictfp"), + (0x1000, "synthetic"), + (0x2000, "annotation"), + (0x4000, "enum"), + (0x10000, "constructor"), + (0x20000, "declared-synchronized"), + ]; + for (bit, name) in table { + if flags & bit != 0 { + v.push(*name); + } + } + match kind { + "method" => { + if flags & 0x20 != 0 { + v.push("synchronized"); + } + if flags & 0x40 != 0 { + v.push("bridge"); + } + if flags & 0x80 != 0 { + v.push("varargs"); + } + } + "field" => { + if flags & 0x40 != 0 { + v.push("volatile"); + } + if flags & 0x80 != 0 { + v.push("transient"); + } + } + _ => {} + } + v +} + +fn table(r: &Reader<'_>, count_off: usize, what: &str, entry: usize) -> Result<(usize, usize), FormatError> { + let n = r.u32_le(count_off).ok_or_else(|| FormatError::Truncated("header".into()))? as usize; + let off = r.u32_le(count_off + 4).ok_or_else(|| FormatError::Truncated("header".into()))? as usize; + if n == 0 { + return Ok((0, 0)); + } + let bytes = n.checked_mul(entry).ok_or_else(|| FormatError::Malformed(format!("{what} count overflows")))?; + if off.checked_add(bytes).is_none_or(|e| e > r.len()) { + return Err(FormatError::Malformed(format!("{n} {what} at offset {off} run past the end of the file"))); + } + Ok((n, off)) +} + +/// True when bytes start with a DEX magic. +pub fn is_dex(data: &[u8]) -> bool { + data.starts_with(b"dex\n") && data.len() >= 0x70 +} + +/// Parse a DEX file. +pub fn parse(data: &[u8]) -> Result, FormatError> { + let r = Reader::new(data); + if !data.starts_with(b"dex\n") { + return Err(FormatError::Malformed("not a DEX file (no dex magic)".into())); + } + if data.len() < 0x70 { + return Err(FormatError::Truncated("DEX header".into())); + } + let mut warnings = Vec::new(); + let version = r.cstr(4, 4).unwrap_or_default(); + let checksum = r.u32_le(8).unwrap_or(0); + let file_size = r.u32_le(32).unwrap_or(0); + let endian = r.u32_le(40).unwrap_or(0); + if endian != 0x1234_5678 { + return Err(FormatError::Unsupported(format!("byte-swapped DEX (endian tag {endian:#x})"))); + } + if file_size as usize != data.len() { + warnings.push(format!("header says {file_size} bytes, the file has {}", data.len())); + } + let sum_end = (file_size as usize).min(data.len()); + let checksum_ok = data.get(12..sum_end).is_some_and(|d| adler32(d) == checksum); + if !checksum_ok { + warnings.push("Adler-32 checksum does not match the content".into()); + } + let (ns, so) = table(&r, 56, "strings", 4)?; + let (nt, to) = table(&r, 64, "types", 4)?; + let (np, po) = table(&r, 72, "protos", 12)?; + let (nf, fo) = table(&r, 80, "fields", 8)?; + let (nm, mo) = table(&r, 88, "methods", 8)?; + let (nc, co) = table(&r, 96, "classes", 32)?; + let header = Header { + version, + checksum: format!("{checksum:08x}"), + checksum_ok, + signature: r.slice(12, 20).map(|b| b.iter().map(|x| format!("{x:02x}")).collect()).unwrap_or_default(), + file_size, + header_size: r.u32_le(36).unwrap_or(0), + endian_tag: format!("{endian:#x}"), + string_ids: ns as u32, + type_ids: nt as u32, + proto_ids: np as u32, + field_ids: nf as u32, + method_ids: nm as u32, + class_defs: nc as u32, + data_size: r.u32_le(104).unwrap_or(0), + }; + let mut strings = Vec::with_capacity(ns); + let mut budget = STRING_BUDGET; + let mut over_budget = false; + for i in 0..ns { + let off = r.u32_le(so + i * 4).unwrap_or(0) as usize; + let s = match r.uleb128(off) { + Some((len, n)) if budget > 0 => { + let want = (len as usize).min(MAX_STRING_UNITS).min(budget); + let (s, _) = mutf8(&r, off.saturating_add(n), want); + budget = budget.saturating_sub(want.max(1)); + s + } + Some(_) => { + over_budget = true; + format!("") + } + None => format!(""), + }; + strings.push(s); + } + if over_budget { + warnings.push("string decoding budget reached; later strings are shown as ".into()); + } + let types = (0..nt).map(|i| r.u32_le(to + i * 4).unwrap_or(NO_INDEX)).collect(); + let protos = (0..np) + .map(|i| { + let o = po + i * 12; + ProtoId { shorty: r.u32_le(o).unwrap_or(0), ret: r.u32_le(o + 4).unwrap_or(NO_INDEX), params_off: r.u32_le(o + 8).unwrap_or(0) } + }) + .collect(); + let member = |o: usize| MemberId { + class_idx: r.u16_le(o).unwrap_or(0), + type_or_proto: r.u16_le(o + 2).unwrap_or(0), + name_idx: r.u32_le(o + 4).unwrap_or(NO_INDEX), + }; + let fields = (0..nf).map(|i| member(fo + i * 8)).collect(); + let methods = (0..nm).map(|i| member(mo + i * 8)).collect(); + let classes = (0..nc) + .map(|i| { + let o = co + i * 32; + let g = |k: usize| r.u32_le(o + k * 4).unwrap_or(0); + ClassDef { + class_idx: g(0), + access: g(1), + superclass_idx: g(2), + interfaces_off: g(3), + source_file_idx: g(4), + annotations_off: g(5), + class_data_off: g(6), + static_values_off: g(7), + } + }) + .collect(); + Ok(Dex { data, header, strings, types, protos, fields, methods, classes, warnings }) +} + +impl<'a> Dex<'a> { + fn r(&self) -> Reader<'a> { + Reader::new(self.data) + } + + pub fn string(&self, i: u32) -> &str { + self.strings.get(i as usize).map(String::as_str).unwrap_or("") + } + + /// The descriptor of type `i` (`Lcom/x/Y;`). + pub fn type_desc(&self, i: u32) -> String { + match self.types.get(i as usize) { + Some(&s) => self.string(s).to_string(), + None => format!(""), + } + } + + fn type_list(&self, off: u32) -> Vec { + if off == 0 { + return Vec::new(); + } + let r = self.r(); + let n = r.u32_le(off as usize).unwrap_or(0) as usize; + (0..n.min(256)).filter_map(|i| r.u16_le(off as usize + 4 + i * 2).map(u32::from)).collect() + } + + /// `(Ljava/lang/String;I)V` + pub fn proto_desc(&self, i: u32) -> String { + match self.protos.get(i as usize) { + Some(p) => { + let params: String = self.type_list(p.params_off).into_iter().map(|t| self.type_desc(t)).collect(); + format!("({params}){}", self.type_desc(p.ret)) + } + None => format!(""), + } + } + + /// Parameter type descriptors and return type of proto `i`. + pub fn proto_parts(&self, i: u32) -> (Vec, String) { + match self.protos.get(i as usize) { + Some(p) => (self.type_list(p.params_off).into_iter().map(|t| self.type_desc(t)).collect(), self.type_desc(p.ret)), + None => (Vec::new(), "?".into()), + } + } + + pub fn shorty(&self, i: u32) -> &str { + self.protos.get(i as usize).map(|p| self.string(p.shorty)).unwrap_or("") + } + + /// `Lcls;->name:Ltype;` + pub fn field_ref(&self, i: u32) -> String { + match self.fields.get(i as usize) { + Some(f) => { + format!("{}->{}:{}", self.type_desc(u32::from(f.class_idx)), self.string(f.name_idx), self.type_desc(u32::from(f.type_or_proto))) + } + None => format!(""), + } + } + + /// `Lcls;->name(…)R` + pub fn method_ref(&self, i: u32) -> String { + match self.methods.get(i as usize) { + Some(m) => { + format!("{}->{}{}", self.type_desc(u32::from(m.class_idx)), self.string(m.name_idx), self.proto_desc(u32::from(m.type_or_proto))) + } + None => format!(""), + } + } + + pub fn class_name(&self, c: &ClassDef) -> String { + self.type_desc(c.class_idx) + } + + pub fn find_class(&self, name: &str) -> Option<&ClassDef> { + let want = to_descriptor(name); + self.classes.iter().find(|c| self.class_name(c) == want) + } + + pub fn interfaces(&self, c: &ClassDef) -> Vec { + self.type_list(c.interfaces_off).into_iter().map(|t| self.type_desc(t)).collect() + } + + /// Type descriptors of the class-level annotations. + pub fn annotations(&self, c: &ClassDef) -> Vec { + let r = self.r(); + let mut out = Vec::new(); + if c.annotations_off == 0 { + return out; + } + let Some(set_off) = r.u32_le(c.annotations_off as usize) else { return out }; + if set_off == 0 { + return out; + } + let n = r.u32_le(set_off as usize).unwrap_or(0) as usize; + for i in 0..n.min(256) { + let Some(item_at) = (set_off as usize).checked_add(4).and_then(|base| base.checked_add(i * 4)) else { break }; + let Some(item) = r.u32_le(item_at) else { break }; + // visibility u8, then encoded_annotation: uleb type_idx … + let (Some(vis), Some(annotation_at)) = (r.u8(item as usize), (item as usize).checked_add(1)) else { continue }; + if let Some((t, _)) = r.uleb128(annotation_at) { + let v = match vis { + 0 => "build", + 1 => "runtime", + 2 => "system", + _ => "?", + }; + out.push(format!("{} ({v})", self.type_desc(t as u32))); + } + } + out + } + + pub fn class_data(&self, c: &ClassDef) -> ClassData { + let mut cd = ClassData::default(); + if c.class_data_off == 0 { + cd.complete = true; + return cd; + } + let r = self.r(); + let mut pos = c.class_data_off as usize; + let next = |pos: &mut usize| -> Option { + let (v, n) = r.uleb128(*pos)?; + *pos += n; + u32::try_from(v).ok() + }; + let (Some(sf), Some(inf), Some(dm), Some(vm)) = (next(&mut pos), next(&mut pos), next(&mut pos), next(&mut pos)) else { return cd }; + let remaining = self.data.len().saturating_sub(pos); + let total: u64 = [sf, inf, dm, vm].iter().map(|&x| u64::from(x)).sum(); + if total > remaining as u64 || total > MAX_MEMBERS as u64 * 4 { + return cd; + } + for (count, is_method, slot) in [(sf, false, 0), (inf, false, 1), (dm, true, 2), (vm, true, 3)] { + let mut idx: u32 = 0; + for _ in 0..count.min(MAX_MEMBERS as u32) { + let Some(diff) = next(&mut pos) else { return cd }; + let Some(access) = next(&mut pos) else { return cd }; + idx = match idx.checked_add(diff) { + Some(v) => v, + None => return cd, + }; + if is_method { + let Some(code_off) = next(&mut pos) else { return cd }; + let m = EncodedMethod { method_idx: idx, access, code_off }; + if slot == 2 { + cd.direct_methods.push(m); + } else { + cd.virtual_methods.push(m); + } + } else { + let f = EncodedField { field_idx: idx, access }; + if slot == 0 { + cd.static_fields.push(f); + } else { + cd.instance_fields.push(f); + } + } + } + if count > MAX_MEMBERS as u32 { + return cd; + } + } + cd.complete = true; + cd + } + + /// The code item at `off`. + pub fn code(&self, off: u32) -> Option { + if off == 0 { + return None; + } + let r = self.r(); + let o = off as usize; + let registers = r.u16_le(o)?; + let ins = r.u16_le(o + 2)?; + let outs = r.u16_le(o + 4)?; + let tries_size = usize::from(r.u16_le(o + 6)?); + let debug_info_off = r.u32_le(o + 8)?; + let n = r.u32_le(o + 12)? as usize; + let bytes = r.slice(o + 16, n.checked_mul(2)?)?; + let insns: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let mut tries = Vec::new(); + let mut t_off = o + 16 + n * 2; + if tries_size > 0 && n % 2 == 1 { + t_off += 2; + } + let handlers_base = t_off + tries_size * 8; + let mut retained = 0usize; + 'tries: for i in 0..tries_size.min(MAX_TRIES) { + let at = t_off + i * 8; + let (Some(start), Some(count), Some(h_off)) = (r.u32_le(at), r.u16_le(at + 4), r.u16_le(at + 6)) else { break }; + let mut handlers = Vec::new(); + let mut p = handlers_base + usize::from(h_off); + if let Some((size, k)) = sleb128(&r, p) { + p += k; + for _ in 0..size.unsigned_abs().min(MAX_HANDLERS as u64) { + let Some((t, k1)) = r.uleb128(p) else { break }; + let Some((addr, k2)) = r.uleb128(p + k1) else { break }; + p += k1 + k2; + let desc = self.type_desc(t as u32); + let Some(next) = retained.checked_add(desc.len()) else { break 'tries }; + if next > MAX_HANDLER_DESCRIPTOR_BYTES { + break 'tries; + } + retained = next; + handlers.push(Handler { exception: Some(desc), address: addr as u32 }); + } + if size <= 0 + && handlers.len() as u64 == size.unsigned_abs() + && let Some((addr, _)) = r.uleb128(p) + { + handlers.push(Handler { exception: None, address: addr as u32 }); + } + } + tries.push(Try { start, end: start.saturating_add(u32::from(count)), handlers }); + } + Some(Code { registers, ins, outs, insns, tries, debug_info_off }) + } + + /// Name of method `i`. + pub fn method_name(&self, i: u32) -> &str { + self.methods.get(i as usize).map(|m| self.string(m.name_idx)).unwrap_or("") + } + + /// Java-like signature: `public static void log(java.lang.String)`. + pub fn method_signature(&self, m: &EncodedMethod) -> String { + let Some(id) = self.methods.get(m.method_idx as usize) else { return format!("", m.method_idx) }; + let (params, ret) = self.proto_parts(u32::from(id.type_or_proto)); + let flags = access_flags(m.access, "method").into_iter().filter(|f| *f != "constructor").collect::>().join(" "); + let params = params.iter().map(|p| java_name(p)).collect::>().join(", "); + format!("{}{}{} {}({params})", flags, if flags.is_empty() { "" } else { " " }, java_name(&ret), self.string(id.name_idx)).trim().to_string() + } + + /// Render one instruction smali-style. + pub fn format_insn(&self, i: &Insn) -> String { + let mut parts: Vec = Vec::new(); + if !i.regs.is_empty() { + let is_list = i.name.starts_with("invoke") || i.name.starts_with("filled-new-array"); + if i.range { + match (i.regs.first(), i.regs.last()) { + (Some(a), Some(b)) => parts.push(format!("{{v{a} .. v{b}}}")), + _ => parts.push("{}".into()), + } + } else if is_list { + parts.push(format!("{{{}}}", i.regs.iter().map(|r| format!("v{r}")).collect::>().join(", "))); + } else { + parts.extend(i.regs.iter().map(|r| format!("v{r}"))); + } + } else if i.range || i.name.starts_with("invoke") { + parts.push("{}".into()); + } + if let Some(l) = i.literal { + parts.push(if (-9..=9).contains(&l) { format!("{l}") } else { format!("{l:#x}") }); + } + if let Some(idx) = i.index { + parts.push(match i.index_kind { + IndexKind::String => format!("{:?}", self.string(idx)), + IndexKind::Type => self.type_desc(idx), + IndexKind::Field => self.field_ref(idx), + IndexKind::Method => self.method_ref(idx), + IndexKind::CallSite => format!("call_site@{idx}"), + IndexKind::MethodHandle => format!("method_handle@{idx}"), + IndexKind::Proto => self.proto_desc(idx), + IndexKind::None => format!("@{idx}"), + }); + } + if let Some(p) = i.index2 { + parts.push(self.proto_desc(p)); + } + if let Some(t) = i.target { + parts.push(format!(":{t:04x}")); + } + let mut s = if parts.is_empty() { i.name.to_string() } else { format!("{} {}", i.name, parts.join(", ")) }; + match (&i.payload, i.opcode) { + (Some(Payload::PackedSwitch { first_key, targets }), 0x2b) => { + let cases: Vec = targets + .iter() + .enumerate() + .take(32) + .map(|(k, t)| format!("{} -> :{:04x}", i64::from(*first_key) + k as i64, i64::from(i.offset) + i64::from(*t))) + .collect(); + s.push_str(&format!(" # {}", cases.join(", "))); + } + (Some(Payload::SparseSwitch { keys, targets }), 0x2c) => { + let cases: Vec = + keys.iter().zip(targets).take(32).map(|(k, t)| format!("{k} -> :{:04x}", i64::from(i.offset) + i64::from(*t))).collect(); + s.push_str(&format!(" # {}", cases.join(", "))); + } + (Some(Payload::FillArrayData { element_width, count, .. }), _) => s.push_str(&format!(" # {count} x {element_width}-byte elements")), + (Some(Payload::PackedSwitch { targets, .. }), 0) => s.push_str(&format!(" ({} cases)", targets.len())), + (Some(Payload::SparseSwitch { targets, .. }), 0) => s.push_str(&format!(" ({} cases)", targets.len())), + _ => {} + } + s + } +} + +/// One place code refers to a class, method or field. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Reference { + /// Caller method, `Lcls;->name(…)R`. + pub caller: String, + /// Code unit offset in the caller. + pub offset: u32, + pub instruction: &'static str, + /// method, field or type + pub kind: &'static str, + pub target: String, +} + +/// Maximum caller and target string bytes retained across a reference query. +/// A count limit alone cannot bound repeated, amplified method signatures. +const MAX_REFERENCE_BYTES: usize = 64 << 20; + +/// Every instruction that refers to class `desc` (optionally only its methods named `method`). +/// Reports truncation for incomplete class data, unreadable nonzero code offsets, incomplete +/// instruction decoding, or an exhausted count or byte budget. +pub fn references(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize) -> (Vec, bool) { + references_with_byte_limit(dex, desc, method, max, MAX_REFERENCE_BYTES) +} + +fn references_with_byte_limit(dex: &Dex<'_>, desc: &str, method: Option<&str>, max: usize, max_bytes: usize) -> (Vec, bool) { + let mut bytes_left = max_bytes; + let mut out = Vec::new(); + let mut complete = true; + for c in &dex.classes { + let cd = dex.class_data(c); + complete &= cd.complete; + for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { + let Some(code) = dex.code(m.code_off) else { + // Zero means no implementation (native/abstract), not damaged code. + // A nonzero unreadable body may hide references from this query. + complete &= m.code_off == 0; + continue; + }; + let (insns, decoded) = crate::dex_ops::decode(&code.insns, 200_000); + complete &= decoded; + for i in &insns { + let Some(idx) = i.index else { continue }; + let hit = match i.index_kind { + IndexKind::Method => dex.methods.get(idx as usize).and_then(|id| { + let cls = dex.type_desc(u32::from(id.class_idx)); + (cls == desc && method.is_none_or(|n| dex.string(id.name_idx) == n)).then(|| ("method", dex.method_ref(idx))) + }), + IndexKind::Field if method.is_none() => dex + .fields + .get(idx as usize) + .and_then(|id| (dex.type_desc(u32::from(id.class_idx)) == desc).then(|| ("field", dex.field_ref(idx)))), + IndexKind::Type if method.is_none() => { + let t = dex.type_desc(idx); + (t.trim_start_matches('[') == desc).then_some(("type", t)) + } + _ => None, + }; + if let Some((kind, target)) = hit { + if out.len() >= max { + return (out, true); + } + let caller = dex.method_ref(m.method_idx); + let Some(left) = bytes_left.checked_sub(caller.len()).and_then(|left| left.checked_sub(target.len())) else { + return (out, true); + }; + bytes_left = left; + out.push(Reference { caller, offset: i.offset, instruction: i.name, kind, target }); + } + } + } + } + (out, !complete) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::android as fx; + + #[test] + fn reference_queries_preserve_incomplete_decode_across_methods() { + for incomplete in [false, true] { + let mut builder = fx::DexBuilder::default(); + let class = builder.ty("LTest;"); + let first = builder.method("LTest;", "first", "V", &[]); + let second = builder.method("LTest;", "second", "V", &[]); + let mut first_code = vec![0x0071, second as u16, 0]; + if incomplete { + first_code.push(0x0071); // truncated invoke-static + } + let code = |insns| Some(fx::CodeSpec { insns, ..Default::default() }); + builder.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: first, access: 0, code: code(first_code) }, + fx::MethodSpec { method: second, access: 0, code: code(vec![0x000e]) }, + ], + ..Default::default() + }); + let data = builder.build(); + let dex = parse(&data).unwrap(); + let (found, truncated) = references(&dex, "LTest;", Some("second"), 10); + assert_eq!(found.len(), 1); + assert_eq!(found[0].caller, "LTest;->first()V"); + assert_eq!(found[0].target, "LTest;->second()V"); + assert_eq!(truncated, incomplete); + let (absent, truncated) = references(&dex, "LAbsent;", None, 10); + assert!(absent.is_empty()); + assert_eq!(truncated, incomplete); + } + } + + #[test] + fn reference_queries_keep_class_data_and_code_parse_failures() { + let mut builder = fx::DexBuilder::default(); + let class = builder.ty("LTest;"); + let target = builder.method("LTest;", "target", "V", &[]); + let caller = builder.method("LTest;", "caller", "V", &[]); + builder.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: target, access: 0, code: Some(fx::CodeSpec { insns: vec![0x000e], ..Default::default() }) }, + fx::MethodSpec { + method: caller, + access: 0, + code: Some(fx::CodeSpec { insns: vec![0x0071, target as u16, 0], ..Default::default() }), + }, + ], + ..Default::default() + }); + let bytes = builder.build(); + let mut dex = parse(&bytes).unwrap(); + let expected = references(&dex, "LTest;", Some("target"), 10); + assert_eq!(expected.0.len(), 1); + assert!(!expected.1); + + // A damaged class before a valid one must not hide the valid result or reset truncation. + let mut bad = dex.classes[0]; + bad.class_data_off = bytes.len() as u32; + dex.classes.insert(0, bad); + assert!(!dex.class_data(&dex.classes[0]).complete); + assert_eq!(references(&dex, "LTest;", Some("target"), 10), (expected.0.clone(), true)); + assert_eq!(references(&dex, "LAbsent;", None, 10), (Vec::new(), true)); + + // Locate the first method's code offset, after four counts and its index/access. + let original = parse(&bytes).unwrap(); + let reader = Reader::new(&bytes); + let mut at = original.classes[0].class_data_off as usize; + for _ in 0..6 { + at += reader.uleb128(at).unwrap().1; + } + let width = reader.uleb128(at).unwrap().1; + for missing in [false, true] { + let mut changed = bytes.clone(); + // Preserve the encoded width so the later valid method stays aligned. + changed[at..at + width].fill(if missing { 0xff } else { 0x80 }); + changed[at + width - 1] = if missing { 0x7f } else { 0 }; + let dex = parse(&changed).unwrap(); + let methods = dex.class_data(&dex.classes[0]); + assert!(methods.complete); + let offset = methods.direct_methods[0].code_off; + if missing { + assert!(offset as usize >= changed.len()); + } else { + assert_eq!(offset, 0); + } + assert!(dex.code(offset).is_none()); + assert_eq!(references(&dex, "LTest;", Some("target"), 10), (expected.0.clone(), missing)); + assert_eq!(references(&dex, "LAbsent;", None, 10), (Vec::new(), missing)); + } + } + + #[test] + fn fixture_strings_round_trip_utf16_surrogate_pairs() { + let mut builder = fx::DexBuilder::default(); + let text = "A\0é😀"; + let index = builder.string(text); + let data = builder.build(); + let dex = parse(&data).unwrap(); + assert_eq!(dex.string(index), text); + let offset = Reader::new(&data).u32_le(0x70).unwrap() as usize; + assert_eq!(&data[offset..offset + 13], &[5, 0x41, 0xc0, 0x80, 0xc3, 0xa9, 0xed, 0xa0, 0xbd, 0xed, 0xb8, 0x80, 0]); + } + + #[test] + fn parses_fixture() { + let data = fx::notes_dex(); + let d = parse(&data).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.header.checksum_ok); + assert_eq!(d.header.version, "035"); + assert_eq!(d.classes.len(), 2); + let main = d.find_class("com.example.notes.MainActivity").unwrap(); + assert_eq!(d.type_desc(main.superclass_idx), "Landroid/app/Activity;"); + assert_eq!(d.interfaces(main), vec!["Ljava/lang/Runnable;"]); + assert_eq!(d.string(main.source_file_idx), "MainActivity.java"); + assert_eq!(d.annotations(main), vec!["Ljava/lang/Deprecated; (runtime)"]); + let cd = d.class_data(main); + assert!(cd.complete); + assert_eq!(cd.static_fields.len(), 1); + assert_eq!(cd.instance_fields.len(), 1); + assert_eq!(cd.direct_methods.len(), 1); + assert_eq!(cd.virtual_methods.len(), 3); + let on_create = cd.virtual_methods.iter().find(|m| d.method_name(m.method_idx) == "onCreate").unwrap(); + assert_eq!(d.method_signature(on_create), "public void onCreate(android.os.Bundle)"); + let code = d.code(on_create.code_off).unwrap(); + let (ins, complete) = crate::dex_ops::decode(&code.insns, 1000); + assert!(complete); + let text: Vec = ins.iter().map(|i| d.format_insn(i)).collect(); + assert_eq!(text[0], "const-string v0, \"Hello, Craft!\""); + assert_eq!(text[1], "invoke-static {v0}, Lcom/example/notes/Util;->log(Ljava/lang/String;)V"); + let pick = cd.virtual_methods.iter().find(|m| d.method_name(m.method_idx) == "pick").unwrap(); + let pc = d.code(pick.code_off).unwrap(); + assert_eq!(pc.tries.len(), 1); + assert_eq!(pc.tries[0].handlers[0].exception.as_deref(), Some("Ljava/lang/RuntimeException;")); + assert_eq!(pc.tries[0].handlers[1].exception, None); + let (pins, _) = crate::dex_ops::decode(&pc.insns, 1000); + let sw = pins.iter().find(|i| i.name == "packed-switch").unwrap(); + assert!(d.format_insn(sw).contains("# 1 -> :"), "{}", d.format_insn(sw)); + let (refs, more) = references(&d, "Lcom/example/notes/Util;", Some("log"), 100); + assert!(!more); + assert_eq!(refs.len(), 2, "{refs:?}"); + assert_eq!(refs[0].caller, "Lcom/example/notes/MainActivity;->onCreate(Landroid/os/Bundle;)V"); + let (all, _) = references(&d, "Ljava/lang/System;", None, 100); + assert_eq!(all[0].kind, "field"); + } + + #[test] + fn helpers() { + assert_eq!(java_name("[[Ljava/lang/String;"), "java.lang.String[][]"); + assert_eq!(java_name("J"), "long"); + assert_eq!(to_descriptor("a.b.C"), "La/b/C;"); + assert_eq!(to_descriptor("La/b/C;"), "La/b/C;"); + assert_eq!(access_flags(0x10009, "method"), vec!["public", "static", "constructor"]); + let r = Reader::new(&[0x7f]); + assert_eq!(sleb128(&r, 0), Some((-1, 1))); + let s = [0xc0, 0x80, 0xe2, 0x82, 0xac, 0x41, 0]; + assert_eq!(mutf8(&Reader::new(&s), 0, 100).0, "\0\u{20ac}A"); + } + + #[test] + fn hostile() { + let data = fx::notes_dex(); + let walk = |d: &Dex<'_>| { + for c in &d.classes { + let cd = d.class_data(c); + let _ = d.annotations(c); + let _ = d.interfaces(c); + for m in cd.direct_methods.iter().chain(&cd.virtual_methods) { + let _ = d.method_signature(m); + if let Some(code) = d.code(m.code_off) { + let (ins, _) = crate::dex_ops::decode(&code.insns, 10_000); + for i in &ins { + let _ = d.format_insn(i); + } + } + } + } + let _ = references(d, "Lcom/example/notes/Util;", None, 100); + }; + for m in crate::test_support::mutations(&data) { + if let Ok(d) = parse(&m) { + walk(&d); + } + } + for len in 0..data.len() { + if let Ok(d) = parse(&data[..len]) { + walk(&d); + } + } + for seed in 0..64 { + let mut n = crate::test_support::noise(seed, 2048); + n[..8].copy_from_slice(b"dex\n035\0"); + n[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + if let Ok(d) = parse(&n) { + walk(&d); + } + } + } + + fn bare_dex<'a>(data: &'a [u8], strings: Vec, types: Vec) -> Dex<'a> { + Dex { + data, + header: Header { + version: "035".into(), + checksum: String::new(), + checksum_ok: false, + signature: String::new(), + file_size: data.len() as u32, + header_size: 0x70, + endian_tag: String::new(), + string_ids: 0, + type_ids: 0, + proto_ids: 0, + field_ids: 0, + method_ids: 0, + class_defs: 0, + data_size: 0, + }, + strings, + types, + protos: Vec::new(), + fields: Vec::new(), + methods: Vec::new(), + classes: Vec::new(), + warnings: Vec::new(), + } + } + + #[test] + fn repeated_handler_lists_stop_at_the_descriptor_budget() { + let desc = format!("L{};", "a".repeat(16 * 1024)); + let mut data = vec![0u8; 4]; + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + data.extend_from_slice(&(MAX_TRIES as u16).to_le_bytes()); + data.extend_from_slice(&0u32.to_le_bytes()); + data.extend_from_slice(&0u32.to_le_bytes()); + for _ in 0..MAX_TRIES { + data.extend_from_slice(&0u32.to_le_bytes()); + data.extend_from_slice(&1u16.to_le_bytes()); + data.extend_from_slice(&0u16.to_le_bytes()); + } + data.push(0x01); // sleb128: one typed handler + data.push(0x00); // type index 0 + data.push(0x00); // handler address + let d = bare_dex(&data, vec![desc.clone()], vec![0]); + let code = d.code(4).expect("code item"); + assert!(!code.tries.is_empty()); + assert!(code.tries.len() < MAX_TRIES, "read {} tries", code.tries.len()); + assert_eq!(code.tries[0].handlers[0].exception.as_deref(), Some(desc.as_str())); + let retained: usize = code.tries.iter().flat_map(|t| &t.handlers).filter_map(|h| h.exception.as_ref()).map(String::len).sum(); + assert!(retained <= MAX_HANDLER_DESCRIPTOR_BYTES, "{retained}"); + } + + #[test] + fn annotations_reject_an_unrepresentable_item_offset() { + let mut data = vec![0u8; 4]; + data.extend_from_slice(&8u32.to_le_bytes()); + data.extend_from_slice(&1u32.to_le_bytes()); + data.extend_from_slice(&u32::MAX.to_le_bytes()); + let d = bare_dex(&data, Vec::new(), Vec::new()); + let c = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 4, + class_data_off: 0, + static_values_off: 0, + }; + assert!(d.annotations(&c).is_empty()); + } + + #[test] + fn class_data_counts_do_not_overflow() { + let mut data = vec![0u8; 4]; + for mut x in [u32::MAX, 1, 0, 0] { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + if x == 0 { + data.push(b); + break; + } + data.push(b | 0x80); + } + } + let d = bare_dex(&data, Vec::new(), Vec::new()); + let c = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 0, + class_data_off: 4, + static_values_off: 0, + }; + assert!(!d.class_data(&c).complete); + } + + #[test] + fn references_bound_repeated_long_signatures_before_retaining_results() { + let mut data = vec![0u8; 578]; + data[4..8].copy_from_slice(&256u32.to_le_bytes()); + // 256 parameter entries all refer to the same long descriptor. + // One direct method at offset 520, with code at 544 (ULEB128 A0 04). + data[520..528].copy_from_slice(&[0, 0, 1, 0, 0, 0, 0xa0, 4]); + data[556..560].copy_from_slice(&9u32.to_le_bytes()); + for offset in [560, 566, 572] { + data[offset..offset + 2].copy_from_slice(&0x0071u16.to_le_bytes()); + } + let desc = format!("L{};", "x".repeat(256)); + let mut dex = bare_dex(&data, vec![desc.clone(), "run".into()], vec![0]); + dex.protos.push(ProtoId { shorty: 0, ret: 0, params_off: 4 }); + dex.methods.push(MemberId { class_idx: 0, type_or_proto: 0, name_idx: 1 }); + dex.classes.push(ClassDef { + class_idx: 0, + access: 0, + superclass_idx: NO_INDEX, + interfaces_off: 0, + source_file_idx: NO_INDEX, + annotations_off: 0, + class_data_off: 520, + static_values_off: 0, + }); + let signature = dex.method_ref(0); + assert!(signature.len() > 256 * 256); + let pair_bytes = signature.len() * 2; + let (all, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes * 3); + assert!(!truncated); + assert_eq!(all.len(), 3); + assert!(all.iter().all(|r| r.caller == signature && r.target == signature)); + let (bounded, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes * 2); + assert!(truncated); + assert_eq!(bounded, all[..2]); + assert_eq!(bounded.iter().map(|r| r.caller.len() + r.target.len()).sum::(), pair_bytes * 2); + let (below_one, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 100, pair_bytes - 1); + assert!(truncated); + assert!(below_one.is_empty()); + let (count_limited, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 1, usize::MAX); + assert!(truncated); + assert_eq!(count_limited, all[..1]); + let (zero, truncated) = references_with_byte_limit(&dex, &desc, Some("run"), 0, usize::MAX); + assert!(truncated); + assert!(zero.is_empty()); + assert_eq!(references(&dex, &desc, Some("run"), 100), (all, false)); + } + #[test] + fn references_report_incomplete_instruction_decoding() { + for (insns, incomplete) in [(vec![0x000e], false), (vec![0x0071], true), (vec![0; 200_001], true)] { + let mut b = fx::DexBuilder::default(); + let class = b.ty("Ltest;"); + let method = b.method("Ltest;", "run", "V", &[]); + b.classes.push(fx::ClassSpec { + class, + direct: vec![fx::MethodSpec { method, access: 0, code: Some(fx::CodeSpec { insns, ..Default::default() }) }], + ..Default::default() + }); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + let (hits, truncated) = references(&dex, "Lmissing;", None, 100); + assert!(hits.is_empty()); + assert_eq!(truncated, incomplete); + } + } + + #[test] + fn references_keep_incompleteness_across_later_complete_methods() { + let mut b = fx::DexBuilder::default(); + let class = b.ty("Ltest;"); + let broken = b.method("Ltest;", "broken", "V", &[]); + let complete = b.method("Ltest;", "complete", "V", &[]); + b.classes.push(fx::ClassSpec { + class, + direct: vec![ + fx::MethodSpec { method: broken, access: 0, code: Some(fx::CodeSpec { insns: vec![0x0071], ..Default::default() }) }, + fx::MethodSpec { method: complete, access: 0, code: Some(fx::CodeSpec { insns: vec![0x000e], ..Default::default() }) }, + ], + ..Default::default() + }); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + assert_eq!(references(&dex, "Lmissing;", None, 100), (Vec::new(), true)); + } + + #[test] + fn fixture_strings_round_trip_supplementary_and_null_characters() { + let mut b = fx::DexBuilder::default(); + let text = "a\0é😀z"; + let id = b.string(text); + let bytes = b.build(); + let dex = parse(&bytes).unwrap(); + assert_eq!(dex.string(id), text); + } +} diff --git a/crates/dex/src/dex_ops.rs b/crates/dex/src/dex_ops.rs new file mode 100644 index 0000000000..3c27d4c5cb --- /dev/null +++ b/crates/dex/src/dex_ops.rs @@ -0,0 +1,696 @@ +//! Dalvik bytecode: the opcode table (all 256 slots and three payload pseudo-instructions) and a +//! decoder for every instruction format. Pure decoding; index operands are resolved by the caller. + +use serde::Serialize; + +/// What an index operand refers to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum IndexKind { + None, + String, + Type, + Field, + Method, + CallSite, + MethodHandle, + Proto, +} + +/// Instruction formats from the Dalvik specification (`10x`, `35c`, …). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum Fmt { + F10x, + F12x, + F11n, + F11x, + F10t, + F20t, + F22x, + F21t, + F21s, + F21h, + F21c, + F23x, + F22b, + F22t, + F22s, + F22c, + F30t, + F32x, + F31i, + F31t, + F31c, + F35c, + F3rc, + F45cc, + F4rcc, + F51l, +} + +impl Fmt { + /// Length in 16-bit code units. + pub fn units(self) -> usize { + use Fmt::*; + match self { + F10x | F12x | F11n | F11x | F10t => 1, + F20t | F22x | F21t | F21s | F21h | F21c | F23x | F22b | F22t | F22s | F22c => 2, + F30t | F32x | F31i | F31t | F31c | F35c | F3rc => 3, + F45cc | F4rcc => 4, + F51l => 5, + } + } +} + +/// One opcode slot. +#[derive(Debug, Clone, Copy)] +pub struct Op { + pub name: &'static str, + pub fmt: Fmt, + pub index: IndexKind, +} + +const fn op(name: &'static str, fmt: Fmt, index: IndexKind) -> Op { + Op { name, fmt, index } +} + +const UNUSED: Op = op("unused", Fmt::F10x, IndexKind::None); + +const UNOPS: [&str; 21] = [ + "neg-int", + "not-int", + "neg-long", + "not-long", + "neg-float", + "neg-double", + "int-to-long", + "int-to-float", + "int-to-double", + "long-to-int", + "long-to-float", + "long-to-double", + "float-to-int", + "float-to-long", + "float-to-double", + "double-to-int", + "double-to-long", + "double-to-float", + "int-to-byte", + "int-to-char", + "int-to-short", +]; + +const BINOPS: [&str; 32] = [ + "add-int", + "sub-int", + "mul-int", + "div-int", + "rem-int", + "and-int", + "or-int", + "xor-int", + "shl-int", + "shr-int", + "ushr-int", + "add-long", + "sub-long", + "mul-long", + "div-long", + "rem-long", + "and-long", + "or-long", + "xor-long", + "shl-long", + "shr-long", + "ushr-long", + "add-float", + "sub-float", + "mul-float", + "div-float", + "rem-float", + "add-double", + "sub-double", + "mul-double", + "div-double", + "rem-double", +]; + +const BINOPS_2ADDR: [&str; 32] = [ + "add-int/2addr", + "sub-int/2addr", + "mul-int/2addr", + "div-int/2addr", + "rem-int/2addr", + "and-int/2addr", + "or-int/2addr", + "xor-int/2addr", + "shl-int/2addr", + "shr-int/2addr", + "ushr-int/2addr", + "add-long/2addr", + "sub-long/2addr", + "mul-long/2addr", + "div-long/2addr", + "rem-long/2addr", + "and-long/2addr", + "or-long/2addr", + "xor-long/2addr", + "shl-long/2addr", + "shr-long/2addr", + "ushr-long/2addr", + "add-float/2addr", + "sub-float/2addr", + "mul-float/2addr", + "div-float/2addr", + "rem-float/2addr", + "add-double/2addr", + "sub-double/2addr", + "mul-double/2addr", + "div-double/2addr", + "rem-double/2addr", +]; + +const LIT16: [&str; 8] = + ["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"]; +const LIT8: [&str; 11] = [ + "add-int/lit8", + "rsub-int/lit8", + "mul-int/lit8", + "div-int/lit8", + "rem-int/lit8", + "and-int/lit8", + "or-int/lit8", + "xor-int/lit8", + "shl-int/lit8", + "shr-int/lit8", + "ushr-int/lit8", +]; +const CMP: [&str; 5] = ["cmpl-float", "cmpg-float", "cmpl-double", "cmpg-double", "cmp-long"]; +const IF2: [&str; 6] = ["if-eq", "if-ne", "if-lt", "if-ge", "if-gt", "if-le"]; +const IFZ: [&str; 6] = ["if-eqz", "if-nez", "if-ltz", "if-gez", "if-gtz", "if-lez"]; +const ARR: [&str; 14] = [ + "aget", + "aget-wide", + "aget-object", + "aget-boolean", + "aget-byte", + "aget-char", + "aget-short", + "aput", + "aput-wide", + "aput-object", + "aput-boolean", + "aput-byte", + "aput-char", + "aput-short", +]; +const IFIELD: [&str; 14] = [ + "iget", + "iget-wide", + "iget-object", + "iget-boolean", + "iget-byte", + "iget-char", + "iget-short", + "iput", + "iput-wide", + "iput-object", + "iput-boolean", + "iput-byte", + "iput-char", + "iput-short", +]; +const SFIELD: [&str; 14] = [ + "sget", + "sget-wide", + "sget-object", + "sget-boolean", + "sget-byte", + "sget-char", + "sget-short", + "sput", + "sput-wide", + "sput-object", + "sput-boolean", + "sput-byte", + "sput-char", + "sput-short", +]; +const INVOKE: [&str; 5] = ["invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface"]; +const INVOKE_RANGE: [&str; 5] = + ["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"]; + +fn pick(list: &[&'static str], i: u8, base: u8) -> &'static str { + list.get(usize::from(i.wrapping_sub(base))).copied().unwrap_or("unused") +} + +/// The opcode table entry for `b`. +pub fn opcode(b: u8) -> Op { + use Fmt::*; + use IndexKind as K; + match b { + 0x00 => op("nop", F10x, K::None), + 0x01 => op("move", F12x, K::None), + 0x02 => op("move/from16", F22x, K::None), + 0x03 => op("move/16", F32x, K::None), + 0x04 => op("move-wide", F12x, K::None), + 0x05 => op("move-wide/from16", F22x, K::None), + 0x06 => op("move-wide/16", F32x, K::None), + 0x07 => op("move-object", F12x, K::None), + 0x08 => op("move-object/from16", F22x, K::None), + 0x09 => op("move-object/16", F32x, K::None), + 0x0a => op("move-result", F11x, K::None), + 0x0b => op("move-result-wide", F11x, K::None), + 0x0c => op("move-result-object", F11x, K::None), + 0x0d => op("move-exception", F11x, K::None), + 0x0e => op("return-void", F10x, K::None), + 0x0f => op("return", F11x, K::None), + 0x10 => op("return-wide", F11x, K::None), + 0x11 => op("return-object", F11x, K::None), + 0x12 => op("const/4", F11n, K::None), + 0x13 => op("const/16", F21s, K::None), + 0x14 => op("const", F31i, K::None), + 0x15 => op("const/high16", F21h, K::None), + 0x16 => op("const-wide/16", F21s, K::None), + 0x17 => op("const-wide/32", F31i, K::None), + 0x18 => op("const-wide", F51l, K::None), + 0x19 => op("const-wide/high16", F21h, K::None), + 0x1a => op("const-string", F21c, K::String), + 0x1b => op("const-string/jumbo", F31c, K::String), + 0x1c => op("const-class", F21c, K::Type), + 0x1d => op("monitor-enter", F11x, K::None), + 0x1e => op("monitor-exit", F11x, K::None), + 0x1f => op("check-cast", F21c, K::Type), + 0x20 => op("instance-of", F22c, K::Type), + 0x21 => op("array-length", F12x, K::None), + 0x22 => op("new-instance", F21c, K::Type), + 0x23 => op("new-array", F22c, K::Type), + 0x24 => op("filled-new-array", F35c, K::Type), + 0x25 => op("filled-new-array/range", F3rc, K::Type), + 0x26 => op("fill-array-data", F31t, K::None), + 0x27 => op("throw", F11x, K::None), + 0x28 => op("goto", F10t, K::None), + 0x29 => op("goto/16", F20t, K::None), + 0x2a => op("goto/32", F30t, K::None), + 0x2b => op("packed-switch", F31t, K::None), + 0x2c => op("sparse-switch", F31t, K::None), + 0x2d..=0x31 => op(pick(&CMP, b, 0x2d), F23x, K::None), + 0x32..=0x37 => op(pick(&IF2, b, 0x32), F22t, K::None), + 0x38..=0x3d => op(pick(&IFZ, b, 0x38), F21t, K::None), + 0x44..=0x51 => op(pick(&ARR, b, 0x44), F23x, K::None), + 0x52..=0x5f => op(pick(&IFIELD, b, 0x52), F22c, K::Field), + 0x60..=0x6d => op(pick(&SFIELD, b, 0x60), F21c, K::Field), + 0x6e..=0x72 => op(pick(&INVOKE, b, 0x6e), F35c, K::Method), + 0x74..=0x78 => op(pick(&INVOKE_RANGE, b, 0x74), F3rc, K::Method), + 0x7b..=0x8f => op(pick(&UNOPS, b, 0x7b), F12x, K::None), + 0x90..=0xaf => op(pick(&BINOPS, b, 0x90), F23x, K::None), + 0xb0..=0xcf => op(pick(&BINOPS_2ADDR, b, 0xb0), F12x, K::None), + 0xd0..=0xd7 => op(pick(&LIT16, b, 0xd0), F22s, K::None), + 0xd8..=0xe2 => op(pick(&LIT8, b, 0xd8), F22b, K::None), + 0xfa => op("invoke-polymorphic", F45cc, K::Method), + 0xfb => op("invoke-polymorphic/range", F4rcc, K::Method), + 0xfc => op("invoke-custom", F35c, K::CallSite), + 0xfd => op("invoke-custom/range", F3rc, K::CallSite), + 0xfe => op("const-method-handle", F21c, K::MethodHandle), + 0xff => op("const-method-type", F21c, K::Proto), + _ => UNUSED, + } +} + +/// Switch and array payloads. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "kebab-case")] +pub enum Payload { + PackedSwitch { first_key: i32, targets: Vec }, + SparseSwitch { keys: Vec, targets: Vec }, + FillArrayData { element_width: u16, count: u32, data: Vec }, +} + +/// One decoded instruction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Insn { + /// Offset in 16-bit code units from the start of the method's code. + pub offset: u32, + pub opcode: u8, + pub name: &'static str, + /// Length in code units. + pub units: u32, + /// Registers in operand order (for ranges: every register in the range). + pub regs: Vec, + /// True for `/range` forms. + pub range: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub literal: Option, + /// Absolute branch or payload target, in code units. + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + pub index_kind: IndexKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub index: Option, + /// Second index (the proto of `invoke-polymorphic`). + #[serde(skip_serializing_if = "Option::is_none")] + pub index2: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub payload: Option, +} + +/// Most entries decoded from one payload. +const MAX_PAYLOAD: usize = 65_536; +/// Maximum payload bytes retained by one decoded method, including copies attached to users. +pub const DEFAULT_MAX_PAYLOAD_BYTES: usize = 64 << 20; + +impl Payload { + fn retained_bytes(&self) -> usize { + match self { + Self::PackedSwitch { targets, .. } => targets.len().saturating_mul(4), + Self::SparseSwitch { keys, targets } => keys.len().saturating_add(targets.len()).saturating_mul(4), + Self::FillArrayData { data, .. } => data.len(), + } + } + + fn complete(&self) -> bool { + match self { + Self::FillArrayData { element_width, count, data } => u64::from(*element_width) * u64::from(*count) == data.len() as u64, + _ => true, + } + } +} + +fn u32_at(code: &[u16], i: usize) -> Option { + Some(u32::from(*code.get(i)?) | (u32::from(*code.get(i + 1)?) << 16)) +} + +/// Decode a payload pseudo-instruction at `pc`; returns it and its length in units. +fn payload(code: &[u16], pc: usize) -> Option<(Payload, usize)> { + let ident = *code.get(pc)?; + match ident { + 0x0100 => { + let size = usize::from(*code.get(pc + 1)?); + let first_key = u32_at(code, pc + 2)? as i32; + let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD)); + for i in 0..size.min(MAX_PAYLOAD) { + targets.push(u32_at(code, pc + 4 + i * 2)? as i32); + } + Some((Payload::PackedSwitch { first_key, targets }, size * 2 + 4)) + } + 0x0200 => { + let size = usize::from(*code.get(pc + 1)?); + let mut keys = Vec::with_capacity(size.min(MAX_PAYLOAD)); + let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD)); + for i in 0..size.min(MAX_PAYLOAD) { + keys.push(u32_at(code, pc + 2 + i * 2)? as i32); + targets.push(u32_at(code, pc + 2 + size * 2 + i * 2)? as i32); + } + Some((Payload::SparseSwitch { keys, targets }, size * 4 + 2)) + } + 0x0300 => { + let width = *code.get(pc + 1)?; + if !matches!(width, 1 | 2 | 4 | 8) { + return None; + } + let count = u32_at(code, pc + 2)?; + let bytes = usize::from(width).checked_mul(count as usize)?; + let units = bytes.checked_add(1)? / 2 + 4; + if pc.checked_add(units)? > code.len() { + return None; + } + let mut data = Vec::with_capacity(bytes.min(MAX_PAYLOAD)); + for i in 0..bytes.min(MAX_PAYLOAD) { + let u = *code.get(pc + 4 + i / 2)?; + data.push(if i % 2 == 0 { u as u8 } else { (u >> 8) as u8 }); + } + Some((Payload::FillArrayData { element_width: width, count, data }, units)) + } + _ => None, + } +} + +/// Decode one instruction at `pc`, or `None` when it runs past the end. +pub fn decode_one(code: &[u16], pc: usize) -> Option { + use Fmt::*; + let u0 = *code.get(pc)?; + let b = (u0 & 0xff) as u8; + let hi = (u0 >> 8) as u8; + if b == 0 && hi != 0 { + let (p, units) = payload(code, pc)?; + let name = match p { + Payload::PackedSwitch { .. } => "packed-switch-payload", + Payload::SparseSwitch { .. } => "sparse-switch-payload", + Payload::FillArrayData { .. } => "array-data-payload", + }; + return Some(Insn { + offset: pc as u32, + opcode: 0, + name, + units: units as u32, + regs: vec![], + range: false, + literal: None, + target: None, + index_kind: IndexKind::None, + index: None, + index2: None, + payload: Some(p), + }); + } + let o = opcode(b); + let n = o.fmt.units(); + if pc.checked_add(n)? > code.len() { + return None; + } + let u = |i: usize| code.get(pc + i).copied().unwrap_or(0); + let a4 = u32::from(hi & 0x0f); + let b4 = u32::from(hi >> 4); + let aa = u32::from(hi); + let rel = |d: i64| pc as i64 + d; + let mut insn = Insn { + offset: pc as u32, + opcode: b, + name: o.name, + units: n as u32, + regs: vec![], + range: false, + literal: None, + target: None, + index_kind: o.index, + index: None, + index2: None, + payload: None, + }; + match o.fmt { + F10x => {} + F12x => insn.regs = vec![a4, b4], + F11n => { + insn.regs = vec![a4]; + insn.literal = Some(i64::from((hi as i8) >> 4)); + } + F11x => insn.regs = vec![aa], + F10t => insn.target = Some(rel(i64::from(hi as i8))), + F20t => insn.target = Some(rel(i64::from(u(1) as i16))), + F22x => insn.regs = vec![aa, u32::from(u(1))], + F21t => { + insn.regs = vec![aa]; + insn.target = Some(rel(i64::from(u(1) as i16))); + } + F21s => { + insn.regs = vec![aa]; + insn.literal = Some(i64::from(u(1) as i16)); + } + F21h => { + insn.regs = vec![aa]; + let v = i64::from(u(1) as i16); + insn.literal = Some(if b == 0x19 { v << 48 } else { v << 16 }); + } + F21c => { + insn.regs = vec![aa]; + insn.index = Some(u32::from(u(1))); + } + F23x => insn.regs = vec![aa, u32::from(u(1) & 0xff), u32::from(u(1) >> 8)], + F22b => { + insn.regs = vec![aa, u32::from(u(1) & 0xff)]; + insn.literal = Some(i64::from((u(1) >> 8) as u8 as i8)); + } + F22t => { + insn.regs = vec![a4, b4]; + insn.target = Some(rel(i64::from(u(1) as i16))); + } + F22s => { + insn.regs = vec![a4, b4]; + insn.literal = Some(i64::from(u(1) as i16)); + } + F22c => { + insn.regs = vec![a4, b4]; + insn.index = Some(u32::from(u(1))); + } + F30t => insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32))), + F32x => insn.regs = vec![u32::from(u(1)), u32::from(u(2))], + F31i => { + insn.regs = vec![aa]; + insn.literal = Some(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32)); + } + F31t => { + insn.regs = vec![aa]; + insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32))); + } + F31c => { + insn.regs = vec![aa]; + insn.index = Some(u32::from(u(1)) | (u32::from(u(2)) << 16)); + } + F35c | F45cc => { + if b4 > 5 { + return None; + } + let count = b4 as usize; + let g = a4; + let w = u(2); + let all = [u32::from(w & 0xf), u32::from((w >> 4) & 0xf), u32::from((w >> 8) & 0xf), u32::from(w >> 12), g]; + insn.regs = all.iter().take(count).copied().collect(); + insn.index = Some(u32::from(u(1))); + if o.fmt == F45cc { + insn.index2 = Some(u32::from(u(3))); + } + } + F3rc | F4rcc => { + let first = u32::from(u(2)); + let end = first.checked_add(aa)?; + if end > u32::from(u16::MAX) + 1 { + return None; + } + insn.regs = (first..end).collect(); + insn.range = true; + insn.index = Some(u32::from(u(1))); + if o.fmt == F4rcc { + insn.index2 = Some(u32::from(u(3))); + } + } + F51l => { + insn.regs = vec![aa]; + let v = u64::from(u(1)) | (u64::from(u(2)) << 16) | (u64::from(u(3)) << 32) | (u64::from(u(4)) << 48); + insn.literal = Some(v as i64); + } + } + Some(insn) +} + +/// Decode a whole method body, attaching each switch/array payload to the instruction that +/// references it. Stops at `max` instructions and caps all retained payload copies together. +pub fn decode(code: &[u16], max: usize) -> (Vec, bool) { + decode_with_payload_limit(code, max, DEFAULT_MAX_PAYLOAD_BYTES) +} + +/// Decode with an explicit aggregate payload byte budget. Payloads that do not fit are omitted; +/// their instruction metadata remains and the returned completeness flag is false. A source +/// payload and every attached copy consume the same budget, before the copy is allocated. +pub fn decode_with_payload_limit(code: &[u16], max: usize, max_payload_bytes: usize) -> (Vec, bool) { + let mut out = Vec::new(); + let mut pc = 0usize; + let mut complete = true; + let mut bytes_left = max_payload_bytes; + while pc < code.len() { + if out.len() >= max { + complete = false; + break; + } + match decode_one(code, pc) { + Some(mut i) => { + pc += (i.units as usize).max(1); + if let Some(p) = &i.payload { + complete &= p.complete(); + if let Some(left) = bytes_left.checked_sub(p.retained_bytes()) { + bytes_left = left; + } else { + i.payload = None; + complete = false; + } + } + out.push(i); + } + None => { + complete = false; + break; + } + } + } + // Attach payloads to their users (31t formats). + // The decoder visits offsets in order. Index their positions without copying any payload. + let payloads: Vec<(i64, usize)> = out.iter().enumerate().filter(|(_, i)| i.payload.is_some()).map(|(n, i)| (i64::from(i.offset), n)).collect(); + for n in 0..out.len() { + let Some(target) = out.get(n).filter(|i| matches!(i.opcode, 0x26 | 0x2b | 0x2c)).and_then(|i| i.target) else { continue }; + let Ok(position) = payloads.binary_search_by_key(&target, |(offset, _)| *offset) else { continue }; + let Some(payload) = payloads.get(position).and_then(|(_, index)| out.get(*index)).and_then(|i| i.payload.as_ref()) else { continue }; + let Some(left) = bytes_left.checked_sub(payload.retained_bytes()) else { + complete = false; + continue; + }; + bytes_left = left; + let copy = payload.clone(); + if let Some(instruction) = out.get_mut(n) { + instruction.payload = Some(copy); + } + } + (out, complete) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn table_is_complete() { + let mut named = 0; + for b in 0..=255u8 { + let o = opcode(b); + if o.name != "unused" { + named += 1; + } + } + // 256 slots minus the 0x3e-0x43, 0x73, 0x79-0x7a and 0xe3-0xf9 holes. + assert_eq!(named, 256 - 6 - 1 - 2 - 23); + assert_eq!(opcode(0x6e).name, "invoke-virtual"); + assert_eq!(opcode(0x8f).name, "int-to-short"); + assert_eq!(opcode(0xaf).name, "rem-double"); + assert_eq!(opcode(0xcf).name, "rem-double/2addr"); + assert_eq!(opcode(0xe2).name, "ushr-int/lit8"); + } + + #[test] + fn decodes_formats() { + // const/4 v1, #-1 ; invoke-static {v0, v1}, meth@5 ; packed-switch v0, +4 ; return-void + // payload: packed, size 2, first 10, targets 1, 2 + let code: Vec = vec![0xf112, 0x2071, 5, 0x0010, 0x002b, 4, 0, 0x000e, 0x0100, 2, 10, 0, 1, 0, 2, 0]; + let (ins, complete) = decode(&code, 100); + assert!(complete); + assert_eq!(ins[0].name, "const/4"); + assert_eq!(ins[0].literal, Some(-1)); + assert_eq!(ins[0].regs, vec![1]); + assert_eq!(ins[1].name, "invoke-static"); + assert_eq!(ins[1].regs, vec![0, 1]); + assert_eq!(ins[1].index, Some(5)); + assert_eq!(ins[2].name, "packed-switch"); + assert_eq!(ins[2].target, Some(8)); + assert_eq!(ins[2].payload, Some(Payload::PackedSwitch { first_key: 10, targets: vec![1, 2] })); + assert_eq!(ins[4].name, "packed-switch-payload"); + // const-wide v0, 0x1122334455667788 + let (w, _) = decode(&[0x0018, 0x7788, 0x5566, 0x3344, 0x1122], 10); + assert_eq!(w[0].literal, Some(0x1122_3344_5566_7788)); + // fill-array-data payload width 1 count 3 + let (f, _) = decode(&[0x0300, 1, 3, 0, 0x0201, 0x0003], 10); + assert_eq!(f[0].payload, Some(Payload::FillArrayData { element_width: 1, count: 3, data: vec![1, 2, 3] })); + // invoke-virtual/range {v4..v6} + let (r, _) = decode(&[0x0374, 9, 4], 10); + assert_eq!(r[0].regs, vec![4, 5, 6]); + assert!(r[0].range); + } + + #[test] + fn hostile() { + for seed in 0..200 { + let n = crate::test_support::noise(seed, 256); + let code: Vec = n.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let _ = decode(&code, 1000); + } + let _ = decode(&[0x0300, 0xffff, 0xffff, 0xffff], 10); + let _ = decode(&[0x0200, 0xffff], 10); + let _ = decode(&[0x0018], 10); + } +} diff --git a/crates/dex/src/lib.rs b/crates/dex/src/lib.rs new file mode 100644 index 0000000000..97d28b7f49 --- /dev/null +++ b/crates/dex/src/lib.rs @@ -0,0 +1,42 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Dalvik DEX inspection and bytecode decoding. Never executes bytecode. +mod bytes; +/// Checked byte reader accepted by the signed-LEB compatibility helper. +pub use bytes::Reader; +pub mod dex; +pub mod dex_ops; +pub use dex::*; +#[cfg(test)] +mod test_support; +/// Parser admission failures; damaged substructures retain the original partial-report behavior. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DexError { + #[error("the file ends early ({0})")] + Truncated(String), + #[error("the file is malformed ({0})")] + Malformed(String), + #[error("not supported: {0}")] + Unsupported(String), +} +use DexError as FormatError; + +#[cfg(test)] +#[path = "regressions/array_widths.rs"] +mod array_widths; + +#[cfg(test)] +#[path = "regressions/capped_table_boundaries.rs"] +mod capped_table_boundaries; + +#[cfg(test)] +#[path = "regressions/invoke_registers.rs"] +mod invoke_registers; + +#[cfg(test)] +#[path = "regressions/payload_budgets.rs"] +mod payload_budgets; + +#[cfg(test)] +#[path = "regressions/signed_leb128.rs"] +mod signed_leb128; diff --git a/crates/dex/src/regressions/array_widths.rs b/crates/dex/src/regressions/array_widths.rs new file mode 100644 index 0000000000..37524b0022 --- /dev/null +++ b/crates/dex/src/regressions/array_widths.rs @@ -0,0 +1,39 @@ +use crate::dex_ops::{Payload, decode, decode_one}; + +#[test] +fn zero_width_does_not_describe_a_huge_complete_array() { + let code = [0x0300, 0, 0xffff, 0xffff]; + assert!(decode_one(&code, 0).is_none()); + assert!(!decode(&code, 16).1); +} + +#[test] +fn unsupported_element_widths_are_refused_even_for_empty_arrays() { + for width in [0, 3, 5, 6, 7, 9, 16, u16::MAX] { + assert!(decode_one(&[0x0300, width, 0, 0], 0).is_none(), "width {width}"); + } +} + +#[test] +fn all_primitive_widths_and_odd_byte_padding_still_decode() { + for width in [1u16, 2, 4, 8] { + let count = 3u32; + let bytes = usize::from(width) * count as usize; + let mut code = vec![0x0300, width, count as u16, 0]; + code.resize(4 + bytes.div_ceil(2), 0x2211); + let instruction = decode_one(&code, 0).unwrap(); + assert_eq!(instruction.units as usize, code.len()); + match instruction.payload.unwrap() { + Payload::FillArrayData { element_width, count: decoded, data } => { + assert_eq!(element_width, width); + assert_eq!(decoded, count); + assert_eq!(data.len(), bytes); + assert_eq!(data[0], 0x11); + } + other => panic!("unexpected payload {other:?}"), + } + assert!(decode_one(&[0x0300, width, 0, 0], 0).is_some()); + code.pop(); + assert!(decode_one(&code, 0).is_none()); + } +} diff --git a/crates/dex/src/regressions/capped_table_boundaries.rs b/crates/dex/src/regressions/capped_table_boundaries.rs new file mode 100644 index 0000000000..7fbb419f50 --- /dev/null +++ b/crates/dex/src/regressions/capped_table_boundaries.rs @@ -0,0 +1,114 @@ +use crate::dex::{self, ClassDef, Code}; + +const MEMBER_CAP: usize = 65_536; +const HANDLER_CAP: usize = 256; + +fn uleb(mut value: u32, bytes: &mut Vec) { + loop { + let byte = (value & 0x7f) as u8; + value >>= 7; + bytes.push(byte | if value == 0 { 0 } else { 0x80 }); + if value == 0 { + break; + } + } +} + +fn sleb(mut value: i32, bytes: &mut Vec) { + loop { + let byte = value as u8 & 0x7f; + value >>= 7; + let done = (value == 0 && byte & 0x40 == 0) || (value == -1 && byte & 0x40 != 0); + bytes.push(byte | if done { 0 } else { 0x80 }); + if done { + break; + } + } +} + +fn header() -> Vec { + let mut bytes = vec![0; 0x70]; + bytes[..8].copy_from_slice(b"dex\n035\0"); + bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes()); + bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + bytes +} + +fn class_data(count: usize) -> dex::ClassData { + let mut bytes = header(); + for n in [count as u32, 0, 1, 0] { + uleb(n, &mut bytes); + } + bytes.extend_from_slice(&[0, 1].repeat(count)); + bytes.extend_from_slice(&[3, 9, 7]); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + let class = ClassDef { + class_idx: 0, + access: 0, + superclass_idx: 0, + interfaces_off: 0, + source_file_idx: 0, + annotations_off: 0, + class_data_off: 0x70, + static_values_off: 0, + }; + dex::parse(&bytes).unwrap().class_data(&class) +} + +fn code(size: i32, payload: &[u8]) -> Code { + let mut bytes = header(); + bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]); + bytes.extend_from_slice(&[0; 16]); + bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]); + bytes.push(1); + sleb(size, &mut bytes); + bytes.extend_from_slice(payload); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + dex::parse(&bytes).unwrap().code(0x70).unwrap() +} + +#[test] +fn capped_class_members_do_not_become_the_next_group() { + let data = class_data(MEMBER_CAP + 1); + assert_eq!(data.static_fields.len(), MEMBER_CAP); + assert!(data.direct_methods.is_empty()); + assert!(!data.complete); +} + +#[test] +fn an_exact_member_limit_keeps_the_following_group() { + let data = class_data(MEMBER_CAP); + assert_eq!(data.static_fields.len(), MEMBER_CAP); + assert!(data.complete); + assert_eq!(data.direct_methods, [dex::EncodedMethod { method_idx: 3, access: 9, code_off: 7 }]); +} + +#[test] +fn an_unread_typed_handler_is_not_a_catch_all() { + let mut payload = [0, 1].repeat(HANDLER_CAP + 1); + payload.push(7); + let parsed = code(-((HANDLER_CAP + 1) as i32), &payload); + assert_eq!(parsed.tries[0].handlers.len(), HANDLER_CAP); + assert!(parsed.tries[0].handlers.iter().all(|handler| handler.exception.is_some() && handler.address == 1)); +} + +#[test] +fn an_incomplete_typed_handler_cannot_supply_a_catch_all_address() { + let parsed = code(-2, &[0, 1, 0]); + assert_eq!(parsed.tries[0].handlers.len(), 1); + assert!(parsed.tries[0].handlers[0].exception.is_some()); + assert_eq!(parsed.tries[0].handlers[0].address, 1); +} + +#[test] +fn complete_typed_lists_keep_their_real_catch_all() { + for count in [0, 1, HANDLER_CAP] { + let mut payload = [0, 1].repeat(count); + payload.push(7); + let parsed = code(-(count as i32), &payload); + assert_eq!(parsed.tries[0].handlers.len(), count + 1); + assert_eq!(parsed.tries[0].handlers.last(), Some(&dex::Handler { exception: None, address: 7 })); + } +} diff --git a/crates/dex/src/regressions/invoke_registers.rs b/crates/dex/src/regressions/invoke_registers.rs new file mode 100644 index 0000000000..c2c6faab60 --- /dev/null +++ b/crates/dex/src/regressions/invoke_registers.rs @@ -0,0 +1,33 @@ +use crate::dex_ops::{decode, decode_one}; + +#[test] +fn fixed_register_lists_cannot_claim_more_than_five_arguments() { + for op in [0x24u16, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfa, 0xfc] { + for count in 6..=15 { + let code = [(count << 12) | op, 1, 0x4321, 2]; + assert!(decode_one(&code, 0).is_none(), "opcode {op:#x}, count {count}"); + assert!(!decode(&code, 16).1); + } + } +} + +#[test] +fn range_arguments_cannot_leave_the_encoded_register_space() { + for op in [0x25u16, 0x74, 0x75, 0x76, 0x77, 0x78, 0xfb, 0xfd] { + assert!(decode_one(&[0x0200 | op, 1, u16::MAX, 2], 0).is_none(), "{op:#x}"); + assert!(decode_one(&[0xff00 | op, 1, u16::MAX - 1, 2], 0).is_none(), "{op:#x}"); + } +} + +#[test] +fn zero_and_boundary_register_lists_remain_valid() { + let fixed = decode_one(&[0x5571, 1, 0x4321], 0).unwrap(); + assert_eq!(fixed.regs, vec![1, 2, 3, 4, 5]); + assert!(decode_one(&[0x0071, 1, 0], 0).unwrap().regs.is_empty()); + let range = decode_one(&[0x0277, 1, u16::MAX - 1], 0).unwrap(); + assert_eq!(range.regs, vec![65534, 65535]); + assert!(decode_one(&[0x0077, 1, u16::MAX], 0).unwrap().regs.is_empty()); + let polymorphic = decode_one(&[0x01fb, 1, u16::MAX, 2], 0).unwrap(); + assert_eq!(polymorphic.regs, vec![65535]); + assert_eq!(polymorphic.index2, Some(2)); +} diff --git a/crates/dex/src/regressions/payload_budgets.rs b/crates/dex/src/regressions/payload_budgets.rs new file mode 100644 index 0000000000..8680373a4e --- /dev/null +++ b/crates/dex/src/regressions/payload_budgets.rs @@ -0,0 +1,88 @@ +use crate::dex_ops::{self, Payload}; + +fn arrays(references: usize, bytes: usize) -> Vec { + let mut code = Vec::new(); + let offset = (references * 3).next_multiple_of(2); + for n in 0..references { + let relative = u32::try_from(offset - n * 3).unwrap(); + code.extend([0x0026, relative as u16, (relative >> 16) as u16]); + } + code.resize(offset, 0); + let count = u32::try_from(bytes).unwrap(); + code.extend([0x0300, 1, count as u16, (count >> 16) as u16]); + code.resize(code.len() + bytes.div_ceil(2), 0x5a5a); + code +} + +fn bytes(rows: &[dex_ops::Insn]) -> usize { + rows.iter() + .map(|i| match i.payload.as_ref() { + Some(Payload::FillArrayData { data, .. }) => data.len(), + Some(Payload::PackedSwitch { targets, .. }) => targets.len() * 4, + Some(Payload::SparseSwitch { keys, targets }) => (keys.len() + targets.len()) * 4, + None => 0, + }) + .sum() +} + +#[test] +fn shared_arrays_charge_the_source_and_each_attached_copy() { + let code = arrays(4, 8); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24); + assert!(!complete); + assert_eq!(bytes(&rows), 24); + assert!(rows[0].payload.is_some() && rows[1].payload.is_some()); + assert!(rows[2].payload.is_none() && rows[3].payload.is_none()); + assert!(rows.last().unwrap().payload.is_some()); + let (full, complete) = dex_ops::decode_with_payload_limit(&code, 100, 40); + assert!(complete); + assert_eq!(bytes(&full), 40); +} + +#[test] +fn zero_budget_keeps_offsets_and_payload_instruction_metadata() { + let code = arrays(2, 8); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 0); + assert!(!complete); + assert_eq!(rows.iter().map(|i| i.offset).collect::>(), [0, 3, 6]); + assert_eq!(rows[2].name, "array-data-payload"); + assert_eq!(rows[2].units, 8); + assert!(rows.iter().all(|i| i.payload.is_none())); + assert!(dex_ops::decode_with_payload_limit(&[0x000e], 100, 0).1); +} + +#[test] +fn both_switch_tables_are_accounted_and_backward_references_work() { + // packed table: one target; sparse table: one key and one target; users follow the tables. + let code = [0x0100, 1, 7, 0, 1, 0, 0x0200, 1, 9, 0, 2, 0, 0x002b, 0xfff4, 0xffff, 0x002c, 0xfff7, 0xffff]; + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24); + assert!(complete); + assert_eq!(rows[2].payload, Some(Payload::PackedSwitch { first_key: 7, targets: vec![1] })); + assert_eq!(rows[3].payload, Some(Payload::SparseSwitch { keys: vec![9], targets: vec![2] })); + let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 16); + assert!(!complete); + assert!(rows[2].payload.is_some()); + assert!(rows[3].payload.is_none()); + assert_eq!(bytes(&rows), 16); +} + +#[test] +fn the_existing_per_array_cap_is_reported_as_partial() { + let (rows, complete) = dex_ops::decode(&arrays(1, 65_537), 100); + assert!(!complete); + assert_eq!(bytes(&rows), 2 * 65_536); + let (rows, complete) = dex_ops::decode(&arrays(1, 8), 1); + assert!(!complete); + assert_eq!(rows.len(), 1); + assert!(rows[0].payload.is_none()); +} + +#[test] +#[ignore = "memory regression: run separately with a 128 MiB address-space limit"] +fn repeated_array_references_stay_under_the_default_byte_budget() { + let code = arrays(2048, 65_536); + let (rows, complete) = dex_ops::decode(&code, 200_000); + assert!(!complete); + assert_eq!(rows.len(), 2049); + assert_eq!(bytes(&rows), dex_ops::DEFAULT_MAX_PAYLOAD_BYTES); +} diff --git a/crates/dex/src/regressions/signed_leb128.rs b/crates/dex/src/regressions/signed_leb128.rs new file mode 100644 index 0000000000..f38fd8db6d --- /dev/null +++ b/crates/dex/src/regressions/signed_leb128.rs @@ -0,0 +1,94 @@ +use crate::bytes::Reader; +use crate::dex::{self, Code, Handler, sleb128}; + +#[test] +fn rejects_invalid_fifth_byte_sign_extensions() { + for prefix in [0x80, 0xff] { + for last in 0x08..=0x77 { + let mut encoded = vec![prefix; 4]; + encoded.push(last); + assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "last byte {last:#x}"); + } + } +} + +#[test] +fn retains_signed_32_bit_limits_and_ordinary_values() { + assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x07]), 0), Some((i64::from(i32::MAX), 5))); + assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x78]), 0), Some((i64::from(i32::MIN), 5))); + assert_eq!(sleb128(&Reader::new(&[0x9b, 0xf1, 0x59]), 0), Some((-624485, 3))); + assert_eq!(sleb128(&Reader::new(&[0xe5, 0x8e, 0x26]), 0), Some((624485, 3))); + assert_eq!(sleb128(&Reader::new(&[0xff, 0x7f]), 0), Some((-1, 2))); + assert_eq!(sleb128(&Reader::new(&[0x80, 0]), 0), Some((0, 2))); + assert_eq!(sleb128(&Reader::new(&[0x55, 0x7f, 0x55]), 1), Some((-1, 1))); +} + +#[test] +fn retains_valid_five_byte_sign_extensions() { + assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0]), 0), Some((0, 5))); + assert_eq!(sleb128(&Reader::new(&[0x81, 0x80, 0x80, 0x80, 0]), 0), Some((1, 5))); + assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x7f]), 0), Some((-1, 5))); +} + +#[test] +fn rejects_values_longer_than_five_bytes() { + for (prefix, last) in [(0x80, 0), (0xff, 0x7f)] { + for length in [6, 10] { + let mut encoded = vec![prefix; length - 1]; + encoded.push(last); + assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "{encoded:x?}"); + } + } +} + +#[test] +fn rejects_truncated_values_and_out_of_range_offsets() { + assert_eq!(sleb128(&Reader::new(&[0x80; 5]), 0), None); + assert_eq!(sleb128(&Reader::new(&[0x80]), 0), None); + assert_eq!(sleb128(&Reader::new(&[]), 0), None); + assert_eq!(sleb128(&Reader::new(&[0]), usize::MAX), None); +} + +fn code_with_handler(size: &[u8], payload: &[u8]) -> Code { + let mut bytes = vec![0; 0x70]; + bytes[..8].copy_from_slice(b"dex\n035\0"); + bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes()); + bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + // Eight nop instructions and one try entry pointing to the first encoded handler. + bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]); + bytes.extend_from_slice(&[0; 16]); + bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]); + bytes.push(1); + bytes.extend_from_slice(size); + bytes.extend_from_slice(payload); + let len = bytes.len() as u32; + bytes[32..36].copy_from_slice(&len.to_le_bytes()); + dex::parse(&bytes).unwrap().code(0x70).unwrap() +} + +#[test] +fn invalid_sizes_do_not_create_handlers() { + let sizes: &[&[u8]] = &[ + &[0x80, 0x80, 0x80, 0x80, 0x08], + &[0x80, 0x80, 0x80, 0x80, 0x77], + &[0x80, 0x80, 0x80, 0x80, 0x80, 0], + &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], + ]; + for size in sizes { + // These bytes could be a type/address pair or a catch-all address if size is accepted. + let code = code_with_handler(size, &[0, 7]); + assert_eq!(code.tries.len(), 1); + assert!(code.tries[0].handlers.is_empty(), "invalid size {size:x?}"); + } +} + +#[test] +fn valid_catch_all_handlers_are_retained() { + for size in [&[0][..], &[0x80, 0x80, 0x80, 0x80, 0][..]] { + let code = code_with_handler(size, &[7]); + assert_eq!(code.tries.len(), 1); + assert_eq!(code.tries[0].start, 0); + assert_eq!(code.tries[0].end, 1); + assert_eq!(code.tries[0].handlers, vec![Handler { exception: None, address: 7 }]); + } +} diff --git a/crates/dex/src/test_support.rs b/crates/dex/src/test_support.rs new file mode 100644 index 0000000000..772a9f0e45 --- /dev/null +++ b/crates/dex/src/test_support.rs @@ -0,0 +1,430 @@ +// Synthetic DEX fixture and deterministic mutations retained from Craft Anything. +pub use craft_testkit::sample_damage::{mutations, noise}; + +pub mod android { + pub const HELLO: &str = "Hello, Craft!"; + fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); + } + fn uleb(v: &mut Vec, mut x: u32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + if x == 0 { + v.push(b); + break; + } + v.push(b | 0x80); + } + } + fn sleb(v: &mut Vec, mut x: i32) { + loop { + let b = (x & 0x7f) as u8; + x >>= 7; + let done = (x == 0 && b & 0x40 == 0) || (x == -1 && b & 0x40 != 0); + v.push(if done { b } else { b | 0x80 }); + if done { + break; + } + } + } + fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } + } + + #[derive(Debug, Clone, Default)] + pub struct TrySpec { + pub start: u32, + pub count: u16, + /// (type idx, handler address) + pub handlers: Vec<(u32, u32)>, + pub catch_all: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct CodeSpec { + pub registers: u16, + pub ins: u16, + pub outs: u16, + pub insns: Vec, + pub tries: Vec, + } + + #[derive(Debug, Clone)] + pub struct MethodSpec { + pub method: u32, + pub access: u32, + pub code: Option, + } + + #[derive(Debug, Clone, Default)] + pub struct ClassSpec { + pub class: u32, + pub access: u32, + pub superclass: u32, + pub interfaces: Vec, + pub source_file: u32, + pub annotations: Vec, + pub static_fields: Vec<(u32, u32)>, + pub instance_fields: Vec<(u32, u32)>, + pub direct: Vec, + pub virtuals: Vec, + } + + #[derive(Debug, Clone, Default)] + pub struct DexBuilder { + strings: Vec, + types: Vec, + protos: Vec<(u32, u32, Vec)>, + fields: Vec<(u32, u32, u32)>, + methods: Vec<(u32, u32, u32)>, + pub classes: Vec, + } + + impl DexBuilder { + pub fn string(&mut self, s: &str) -> u32 { + if let Some(i) = self.strings.iter().position(|x| x == s) { + return i as u32; + } + self.strings.push(s.to_string()); + (self.strings.len() - 1) as u32 + } + + pub fn ty(&mut self, desc: &str) -> u32 { + let s = self.string(desc); + if let Some(i) = self.types.iter().position(|&x| x == s) { + return i as u32; + } + self.types.push(s); + (self.types.len() - 1) as u32 + } + + pub fn proto(&mut self, ret: &str, params: &[&str]) -> u32 { + let short = |d: &str| if d.starts_with('L') || d.starts_with('[') { 'L' } else { d.chars().next().unwrap() }; + let shorty: String = std::iter::once(short(ret)).chain(params.iter().map(|p| short(p))).collect(); + let s = self.string(&shorty); + let r = self.ty(ret); + let ps: Vec = params.iter().map(|p| self.ty(p)).collect(); + if let Some(i) = self.protos.iter().position(|p| p.1 == r && p.2 == ps) { + return i as u32; + } + self.protos.push((s, r, ps)); + (self.protos.len() - 1) as u32 + } + + pub fn field(&mut self, cls: &str, ty: &str, name: &str) -> u32 { + let c = self.ty(cls); + let t = self.ty(ty); + let n = self.string(name); + if let Some(i) = self.fields.iter().position(|&f| f == (c, t, n)) { + return i as u32; + } + self.fields.push((c, t, n)); + (self.fields.len() - 1) as u32 + } + + pub fn method(&mut self, cls: &str, name: &str, ret: &str, params: &[&str]) -> u32 { + let c = self.ty(cls); + let p = self.proto(ret, params); + let n = self.string(name); + if let Some(i) = self.methods.iter().position(|&m| m == (c, p, n)) { + return i as u32; + } + self.methods.push((c, p, n)); + (self.methods.len() - 1) as u32 + } + + pub fn build(self) -> Vec { + let ns = self.strings.len(); + let nt = self.types.len(); + let np = self.protos.len(); + let nf = self.fields.len(); + let nm = self.methods.len(); + let nc = self.classes.len(); + let string_ids = 0x70; + let type_ids = string_ids + ns * 4; + let proto_ids = type_ids + nt * 4; + let field_ids = proto_ids + np * 12; + let method_ids = field_ids + nf * 8; + let class_defs = method_ids + nm * 8; + let mut data_start = class_defs + nc * 32; + data_start = (data_start + 3) & !3; + let mut d: Vec = Vec::new(); + let at = |d: &Vec| (data_start + d.len()) as u32; + // type lists + let tl = |d: &mut Vec, list: &[u32]| -> u32 { + if list.is_empty() { + return 0; + } + align4(d); + let o = at(d); + u32le(d, list.len() as u32); + for &t in list { + u16le(d, t as u16); + } + o + }; + let proto_params: Vec = self.protos.iter().map(|p| tl(&mut d, &p.2)).collect(); + let class_ifaces: Vec = self.classes.iter().map(|c| tl(&mut d, &c.interfaces)).collect(); + // string data + let mut string_offs = Vec::new(); + for s in &self.strings { + string_offs.push(at(&d)); + uleb(&mut d, s.encode_utf16().count() as u32); + for c in s.encode_utf16() { + if c == 0 { + d.extend_from_slice(&[0xc0, 0x80]); + } else if c < 0x80 { + d.push(c as u8); + } else if c < 0x800 { + d.extend_from_slice(&[0xc0 | (c >> 6) as u8, 0x80 | (c & 0x3f) as u8]); + } else { + d.extend_from_slice(&[0xe0 | (c >> 12) as u8, 0x80 | ((c >> 6) & 0x3f) as u8, 0x80 | (c & 0x3f) as u8]); + } + } + d.push(0); + } + // code items, class data, annotations + let mut class_data_offs = Vec::new(); + let mut annot_offs = Vec::new(); + for c in &self.classes { + let code_off = |d: &mut Vec, m: &MethodSpec| -> u32 { + let Some(code) = &m.code else { return 0 }; + align4(d); + let o = at(d); + u16le(d, code.registers); + u16le(d, code.ins); + u16le(d, code.outs); + u16le(d, code.tries.len() as u16); + u32le(d, 0); + u32le(d, code.insns.len() as u32); + for &i in &code.insns { + u16le(d, i); + } + if !code.tries.is_empty() { + if code.insns.len() % 2 == 1 { + u16le(d, 0); + } + let mut list = Vec::new(); + uleb(&mut list, code.tries.len() as u32); + let mut offs = Vec::new(); + for t in &code.tries { + offs.push(list.len() as u16); + let n = t.handlers.len() as i32; + sleb(&mut list, if t.catch_all.is_some() { -n } else { n }); + for &(ty, addr) in &t.handlers { + uleb(&mut list, ty); + uleb(&mut list, addr); + } + if let Some(a) = t.catch_all { + uleb(&mut list, a); + } + } + for (t, off) in code.tries.iter().zip(offs) { + u32le(d, t.start); + u16le(d, t.count); + u16le(d, off); + } + d.extend_from_slice(&list); + } + o + }; + let mut direct = c.direct.clone(); + direct.sort_by_key(|m| m.method); + let mut virtuals = c.virtuals.clone(); + virtuals.sort_by_key(|m| m.method); + let direct_offs: Vec = direct.iter().map(|m| code_off(&mut d, m)).collect(); + let virtual_offs: Vec = virtuals.iter().map(|m| code_off(&mut d, m)).collect(); + let cd = at(&d); + let mut sf = c.static_fields.clone(); + sf.sort(); + let mut inf = c.instance_fields.clone(); + inf.sort(); + uleb(&mut d, sf.len() as u32); + uleb(&mut d, inf.len() as u32); + uleb(&mut d, direct.len() as u32); + uleb(&mut d, virtuals.len() as u32); + for list in [&sf, &inf] { + let mut prev = 0; + for &(f, a) in list.iter() { + uleb(&mut d, f - prev); + uleb(&mut d, a); + prev = f; + } + } + for (list, offs) in [(&direct, &direct_offs), (&virtuals, &virtual_offs)] { + let mut prev = 0; + for (m, &o) in list.iter().zip(offs.iter()) { + uleb(&mut d, m.method - prev); + uleb(&mut d, m.access); + uleb(&mut d, o); + prev = m.method; + } + } + class_data_offs.push(cd); + if c.annotations.is_empty() { + annot_offs.push(0); + } else { + let mut items = Vec::new(); + for &t in &c.annotations { + items.push(at(&d)); + d.push(1); // runtime visibility + uleb(&mut d, t); + uleb(&mut d, 0); + } + align4(&mut d); + let set_off = at(&d); + u32le(&mut d, items.len() as u32); + for i in items { + u32le(&mut d, i); + } + let dir = at(&d); + u32le(&mut d, set_off); + u32le(&mut d, 0); + u32le(&mut d, 0); + u32le(&mut d, 0); + annot_offs.push(dir); + } + } + align4(&mut d); + let file_size = data_start + d.len(); + let mut out = vec![0u8; data_start]; + out[..8].copy_from_slice(b"dex\n035\0"); + let put = |out: &mut Vec, off: usize, v: u32| out[off..off + 4].copy_from_slice(&v.to_le_bytes()); + put(&mut out, 32, file_size as u32); + put(&mut out, 36, 0x70); + put(&mut out, 40, 0x1234_5678); + for (i, (n, o)) in + [(ns, string_ids), (nt, type_ids), (np, proto_ids), (nf, field_ids), (nm, method_ids), (nc, class_defs)].iter().enumerate() + { + put(&mut out, 56 + i * 8, *n as u32); + put(&mut out, 60 + i * 8, if *n == 0 { 0 } else { *o as u32 }); + } + put(&mut out, 104, d.len() as u32); + put(&mut out, 108, data_start as u32); + for (i, o) in string_offs.iter().enumerate() { + put(&mut out, string_ids + i * 4, *o); + } + for (i, t) in self.types.iter().enumerate() { + put(&mut out, type_ids + i * 4, *t); + } + for (i, p) in self.protos.iter().enumerate() { + put(&mut out, proto_ids + i * 12, p.0); + put(&mut out, proto_ids + i * 12 + 4, p.1); + put(&mut out, proto_ids + i * 12 + 8, proto_params[i]); + } + for (i, (c, t, n)) in self.fields.iter().enumerate() { + out[field_ids + i * 8..field_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[field_ids + i * 8 + 2..field_ids + i * 8 + 4].copy_from_slice(&(*t as u16).to_le_bytes()); + put(&mut out, field_ids + i * 8 + 4, *n); + } + for (i, (c, p, n)) in self.methods.iter().enumerate() { + out[method_ids + i * 8..method_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes()); + out[method_ids + i * 8 + 2..method_ids + i * 8 + 4].copy_from_slice(&(*p as u16).to_le_bytes()); + put(&mut out, method_ids + i * 8 + 4, *n); + } + for (i, c) in self.classes.iter().enumerate() { + let o = class_defs + i * 32; + for (k, v) in + [c.class, c.access, c.superclass, class_ifaces[i], c.source_file, annot_offs[i], class_data_offs[i], 0].iter().enumerate() + { + put(&mut out, o + k * 4, *v); + } + } + out.extend_from_slice(&d); + let sum = adler32(&out[12..]); + put(&mut out, 8, sum); + out + } + } + + fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for &x in data { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + (b << 16) | a + } + + const MAIN: &str = "Lcom/example/notes/MainActivity;"; + const UTIL: &str = "Lcom/example/notes/Util;"; + const STRING: &str = "Ljava/lang/String;"; + + /// `classes.dex` of the Notes app: `MainActivity` (constructor, `onCreate`, `run`, `pick` with a + /// packed switch inside a try/catch) and `Util` (two `log` overloads printing through + /// `System.out`). + pub fn notes_dex() -> Vec { + let mut b = DexBuilder::default(); + let activity = b.ty("Landroid/app/Activity;"); + let main = b.ty(MAIN); + let runnable = b.ty("Ljava/lang/Runnable;"); + let deprecated = b.ty("Ljava/lang/Deprecated;"); + let rte = b.ty("Ljava/lang/RuntimeException;"); + let object = b.ty("Ljava/lang/Object;"); + let util = b.ty(UTIL); + let tag = b.field(MAIN, STRING, "TAG"); + let count = b.field(MAIN, "I", "count"); + let out = b.field("Ljava/lang/System;", "Ljava/io/PrintStream;", "out"); + let super_init = b.method("Landroid/app/Activity;", "", "V", &[]); + let super_create = b.method("Landroid/app/Activity;", "onCreate", "V", &["Landroid/os/Bundle;"]); + let init = b.method(MAIN, "", "V", &[]); + let on_create = b.method(MAIN, "onCreate", "V", &["Landroid/os/Bundle;"]); + let run = b.method(MAIN, "run", "V", &[]); + let pick = b.method(MAIN, "pick", "I", &["I"]); + let log_s = b.method(UTIL, "log", "V", &[STRING]); + let log_i = b.method(UTIL, "log", "V", &["I"]); + let println = b.method("Ljava/io/PrintStream;", "println", "V", &[STRING]); + let hello = b.string(HELLO); + let main_src = b.string("MainActivity.java"); + let util_src = b.string("Util.java"); + let code = |registers, ins, outs, insns: Vec| Some(CodeSpec { registers, ins, outs, insns, tries: vec![] }); + b.classes.push(ClassSpec { + class: main, + access: 0x1, + superclass: activity, + interfaces: vec![runnable], + source_file: main_src, + annotations: vec![deprecated], + static_fields: vec![(tag, 0x1a)], + instance_fields: vec![(count, 0x2)], + direct: vec![MethodSpec { method: init, access: 0x10001, code: code(1, 1, 1, vec![0x1070, super_init as u16, 0x0000, 0x000e]) }], + virtuals: vec![ + MethodSpec { + method: on_create, + access: 0x1, + code: code(3, 2, 2, vec![0x001a, hello as u16, 0x1071, log_s as u16, 0x0000, 0x206f, super_create as u16, 0x0021, 0x000e]), + }, + MethodSpec { method: run, access: 0x1, code: code(1, 1, 1, vec![0x7012, 0x1071, log_i as u16, 0x0000, 0x000e]) }, + MethodSpec { + method: pick, + access: 0x1, + code: Some(CodeSpec { + registers: 3, + ins: 2, + outs: 0, + insns: vec![0x022b, 10, 0, 0x0012, 0x000f, 0x1012, 0x000f, 0x2012, 0x000f, 0x0000, 0x0100, 2, 1, 0, 5, 0, 7, 0], + tries: vec![TrySpec { start: 0, count: 3, handlers: vec![(rte, 3)], catch_all: Some(3) }], + }), + }, + ], + }); + b.classes.push(ClassSpec { + class: util, + access: 0x11, + superclass: object, + source_file: util_src, + direct: vec![ + MethodSpec { method: log_s, access: 0x9, code: code(2, 1, 2, vec![0x0062, out as u16, 0x206e, println as u16, 0x0010, 0x000e]) }, + MethodSpec { method: log_i, access: 0x9, code: code(1, 1, 0, vec![0x000e]) }, + ], + ..ClassSpec::default() + }); + b.build() + } +} diff --git a/crates/doc-binary/Cargo.toml b/crates/doc-binary/Cargo.toml index 6c5a5625e5..98b7e2c69b 100644 --- a/crates/doc-binary/Cargo.toml +++ b/crates/doc-binary/Cargo.toml @@ -17,6 +17,7 @@ craft-wordmodel = { workspace = true } chrono = { version = "0.4.45", default-features = false, features = ["std"] } image = { version = "0.25", default-features = false, features = ["png", "bmp"] } log = "0.4" +md4 = "0.11" miniz_oxide = "0.9" sha1 = "0.11" thiserror = { workspace = true } diff --git a/crates/doc-binary/src/write/picture.rs b/crates/doc-binary/src/write/picture.rs index 07eb19fa4e..6454c320f9 100644 --- a/crates/doc-binary/src/write/picture.rs +++ b/crates/doc-binary/src/write/picture.rs @@ -3,7 +3,7 @@ //! picture's place in the BLIP store, crop, alt text) and the `OfficeArtFBSE` with the BLIP //! embedded in it. The character 0x01 in the text points here through `sprmCPicLocation`. -use sha1::Digest; +use md4::Digest; /// `PICF.cbHeader`. const CB_HEADER: u16 = 0x44; @@ -77,14 +77,15 @@ impl Blip { } } - /// The `OfficeArtBlip*` record. - fn record(&self, w_emu: i32, h_emu: i32) -> Vec { + /// The `OfficeArtBlip*` record and its format-defined identifier. + fn record(&self, w_emu: i32, h_emu: i32) -> (Vec, [u8; 16]) { let (raw, (typ, inst)) = match self { Blip::Png(b) => (b, BLIP_PNG), Blip::Jpeg(b) => (b, BLIP_JPEG), Blip::Metafile(b, emf) => (b, if *emf { BLIP_EMF } else { BLIP_WMF }), }; - let mut body = uid(raw).to_vec(); + let id = uid(raw); + let mut body = id.to_vec(); match self { Blip::Png(b) | Blip::Jpeg(b) => { body.push(0xFF); // tag @@ -106,16 +107,14 @@ impl Blip { body.extend_from_slice(&packed); } } - rec(0, inst, typ, &body) + (rec(0, inst, typ, &body), id) } } -/// A 16-byte id for a BLIP (the format wants an MD4; any digest identifies it). +/// MS-ODRAW requires MD4 of the uncompressed BLIP payload, not the original import file. +/// This legacy-format identifier is not authentication or a security integrity check. fn uid(bytes: &[u8]) -> [u8; 16] { - let d = sha1::Sha1::digest(bytes); - let mut u = [0u8; 16]; - u.copy_from_slice(d.get(..16).unwrap_or(&[0; 16])); - u + md4::Md4::digest(bytes).into() } /// An OfficeArt record: header (version, instance, type, length) then the body. @@ -147,9 +146,10 @@ impl Pictures { let gh = (h.max(1.0) / (1.0 - ct - cb).max(0.01)).min(1584.0); let emu = |pt: f32| (pt * 12_700.0).round() as i32; - let blip_rec = blip.record(emu(gw), emu(gh)); + let (blip_rec, id) = blip.record(emu(gw), emu(gh)); let mut fbse = vec![blip.bt(), blip.bt()]; - fbse.extend_from_slice(&uid(bytes)); + // Reuse the embedded BLIP's identifier after PNG conversion/placeable-header removal. + fbse.extend_from_slice(&id); fbse.extend_from_slice(&0x00FFu16.to_le_bytes()); // tag fbse.extend_from_slice(&(blip_rec.len() as u32).to_le_bytes()); fbse.extend_from_slice(&1u32.to_le_bytes()); // cRef @@ -209,3 +209,70 @@ impl Pictures { u32::try_from(at).ok() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blip_uid_matches_rfc1320_vectors() { + assert_eq!(uid(b""), [0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0]); + assert_eq!(uid(b"abc"), [0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d]); + } + + fn check_record_ids(input: &[u8], payload: &[u8]) { + let mut pictures = Pictures::default(); + assert_eq!(pictures.add(input, 1.0, 1.0, [0.0; 4], ""), Some(0)); + let bytes = &pictures.data; + let shape = usize::from(CB_HEADER); + let shape_len = u32::from_le_bytes(bytes[shape + 4..shape + 8].try_into().unwrap()) as usize; + let fbse = shape + 8 + shape_len; + assert_eq!(&bytes[fbse + 2..fbse + 4], &FBSE.to_le_bytes()); + let embedded = fbse + 8 + 36; + let typ = u16::from_le_bytes(bytes[embedded + 2..embedded + 4].try_into().unwrap()); + let emitted = if typ == BLIP_WMF.0 || typ == BLIP_EMF.0 { + // Controlled tiny fixtures: skip the UID and 34-byte metafile header. + miniz_oxide::inflate::decompress_to_vec_zlib(&bytes[embedded + 58..]).unwrap() + } else { + assert!(typ == BLIP_PNG.0 || typ == BLIP_JPEG.0); + bytes[embedded + 25..].to_vec() + }; + assert_eq!(emitted, payload, "stored image bytes must retain the expected conversion"); + let expected = uid(&emitted); + assert_eq!(&bytes[fbse + 10..fbse + 26], &expected, "FBSE must identify stored data"); + assert_eq!(&bytes[embedded + 8..embedded + 24], &expected, "BLIP must share the same identifier"); + } + + #[test] + fn blip_ids_identify_unmodified_payloads() { + // Tiny format-dispatch fixtures exercise identifier bytes, not image validation. + let png = b"\x89PNGsmall"; + check_record_ids(png, png); + let jpeg = b"\xff\xd8\xffsmall"; + check_record_ids(jpeg, jpeg); + let wmf = [1, 0, 9, 0, 0, 3, 9, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0]; + check_record_ids(&wmf, &wmf); + let mut emf = vec![0; 44]; + emf[..4].copy_from_slice(&1u32.to_le_bytes()); + emf[40..44].copy_from_slice(b" EMF"); + check_record_ids(&emf, &emf); + } + + #[test] + fn blip_ids_exclude_placeable_wmf_header() { + let wmf = [1, 0, 9, 0, 0, 3, 9, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0]; + let mut placeable = vec![0; 22]; + placeable[..4].copy_from_slice(&[0xd7, 0xcd, 0xc6, 0x9a]); + placeable.extend_from_slice(&wmf); + check_record_ids(&placeable, &wmf); + } + + #[test] + fn blip_ids_identify_converted_bmp_payload() { + let mut bmp = std::io::Cursor::new(Vec::new()); + image::DynamicImage::new_rgb8(1, 1).write_to(&mut bmp, image::ImageFormat::Bmp).unwrap(); + let Blip::Png(encoded) = Blip::of(bmp.get_ref()).unwrap() else { panic!("BMP must become PNG") }; + assert_ne!(bmp.get_ref(), &encoded); + check_record_ids(bmp.get_ref(), &encoded); + } +} diff --git a/crates/document-bundle/src/lib.rs b/crates/document-bundle/src/lib.rs index 70a960a1f4..b425856add 100644 --- a/crates/document-bundle/src/lib.rs +++ b/crates/document-bundle/src/lib.rs @@ -315,7 +315,8 @@ pub fn read_preview(bytes: &[u8], preview_entry: &str) -> Option> { archive.read(preview_entry, PREVIEW_LIMIT).ok().flatten() } -/// Read a bounded preview from a seekable file without loading the full bundle into memory. +/// Read a preview from a seekable ZIP, including archives with a leading prefix. +/// The decompressed preview is limited to 4 MiB; archive discovery may perform substantial I/O. pub fn read_preview_from(reader: R, preview_entry: &str) -> Option> { const PREVIEW_LIMIT: u64 = 4 << 20; let mut zip = zip::ZipArchive::new(reader).ok()?; @@ -328,6 +329,22 @@ pub fn read_preview_from(reader: R, preview_entry: &str) -> Opti (u64::try_from(preview.len()).ok()? <= PREVIEW_LIMIT).then_some(preview) } +/// Read a preview only from a ZIP with a local-file header at byte zero. +/// +/// Use for native formats whose contract excludes prefixed/self-extracting archives. +/// Nonmatching inputs require at most four bytes read, regardless of the initial cursor position. +/// Matching ZIPs still require directory I/O; this is not an overall read/time budget. +pub fn read_unprefixed_preview_from(mut reader: R, preview_entry: &str) -> Option> { + reader.seek(std::io::SeekFrom::Start(0)).ok()?; + let mut magic = [0u8; 4]; + reader.read_exact(&mut magic).ok()?; + if &magic != b"PK\x03\x04" { + return None; + } + reader.seek(std::io::SeekFrom::Start(0)).ok()?; + read_preview_from(reader, preview_entry) +} + fn read_legacy(bytes: &[u8], spec: Spec<'_>) -> Result { let mut document: Value = serde_json::from_slice(bytes).map_err(|e| Error::NotBundle(e.to_string()))?; let mut assets = Vec::new(); @@ -409,6 +426,67 @@ mod tests { assert_eq!(read_preview(&bytes, SPEC.preview_entry).as_deref(), Some(&b"png"[..])); } + /// Counts the bytes read through it. + struct Counting { + inner: R, + read: usize, + } + + impl Read for Counting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n; + Ok(n) + } + } + + impl Seek for Counting { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } + } + + #[test] + fn preview_from_a_reader_reads_a_bundle() { + let bytes = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + assert_eq!(read_preview_from(Cursor::new(&bytes), SPEC.preview_entry).as_deref(), Some(&b"png"[..])); + } + + #[test] + fn prefixed_bundle_admission_is_explicit() { + let bundle = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + let mut bytes = b"MZsynthetic-prefix".to_vec(); + bytes.extend(bundle); + let mut original = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let mut preview = Vec::new(); + original.by_name(SPEC.preview_entry).unwrap().read_to_end(&mut preview).unwrap(); + assert_eq!(preview, b"png"); + assert!(has_document(&bytes, SPEC)); + assert!(!starts_with_mimetype(&bytes, SPEC)); + assert_eq!(read_preview_from(Cursor::new(&bytes), SPEC.preview_entry), Some(preview)); + assert_eq!(read_unprefixed_preview_from(Cursor::new(&bytes), SPEC.preview_entry), None); + } + + #[test] + fn preview_from_an_advanced_reader_still_reads_the_bundle() { + let bytes = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + for offset in [1, 4, bytes.len() / 2, bytes.len()] { + let mut reader = Cursor::new(&bytes); + reader.set_position(offset as u64); + assert_eq!(read_preview_from(reader.clone(), SPEC.preview_entry).as_deref(), Some(&b"png"[..]), "offset {offset}"); + assert_eq!(read_unprefixed_preview_from(reader, SPEC.preview_entry).as_deref(), Some(&b"png"[..]), "offset {offset}"); + } + } + + #[test] + fn preview_from_a_non_zip_reads_only_its_signature() { + let mut file = Counting { inner: Cursor::new(vec![0x42u8; 1 << 20]), read: 0 }; + assert_eq!(read_unprefixed_preview_from(&mut file, SPEC.preview_entry), None); + assert!(file.read <= 4, "read {} bytes of a file that is not a zip", file.read); + let mut empty = Counting { inner: Cursor::new(Vec::new()), read: 0 }; + assert_eq!(read_unprefixed_preview_from(&mut empty, SPEC.preview_entry), None); + } + #[test] fn extracts_legacy_inline_assets() { let loaded = read(br#"{"assetData":{"7":"AQID"},"name":"x"}"#, 4, SPEC).unwrap(); diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index c3c3e8df3d..68d41ab4d2 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -3,8 +3,8 @@ //! [`read`] turns a `.docx` package into a [`craft_wordmodel::Document`]; [`write`] does the //! reverse. Both are written from the public specification. The reader is lenient (unknown //! markup is skipped, bad numbers fall back to defaults) and bounded (zip entry sizes, total -//! decompressed size, XML depth and element counts are capped), so hostile input yields an -//! error or a best-effort document, never a panic. +//! decompressed size, XML depth, element counts per part and a package-wide element budget are +//! capped), so hostile input yields an error or a best-effort document, never a panic. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The code came from an app whose lints allow this. #![allow(clippy::type_complexity)] diff --git a/crates/docx/src/package.rs b/crates/docx/src/package.rs index 3c7f45d943..6f90f56ba3 100644 --- a/crates/docx/src/package.rs +++ b/crates/docx/src/package.rs @@ -1,5 +1,6 @@ //! OPC package access: bounded zip reading, relationships, part names. +use std::cell::Cell; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -216,6 +217,14 @@ fn opc_error(e: craft_opc::Error) -> DocxError { /// document keeps as it is (a picture, an embedded object) is handed over rather than copied. pub struct Package { opc: craft_opc::Package, + /// Elements this package's XML parts may still be parsed into. Every XML part read through + /// [`Package::xml`] charges it, so a file of many parts each inside the per-part cap builds + /// bounded tree memory in total — a chart part with no series builds a maximal tree for + /// almost no graphic work, and the trees the reader keeps accumulate. + budget: Cell, + /// What [`Package::reset_budget`] restores: the cap the package was opened with (the default, + /// or a smaller one from [`Package::open_limited_within`]). + budget_cap: usize, } impl Package { @@ -227,8 +236,16 @@ impl Package { /// `max_total` (counting entries that fail their checksum), is an error. A damaged entry is /// left out with a logged warning. pub fn open_limited(bytes: &[u8], max_part: u64, max_total: u64) -> Result { + Package::open_limited_within(bytes, max_part, max_total, xml::MAX_ELEMENTS_TOTAL) + } + + /// [`open_limited`] with an XML element budget of its own (nested documents share their + /// container's, tests use a small one). + pub fn open_limited_within(bytes: &[u8], max_part: u64, max_total: u64, max_elements: usize) -> Result { let limits = craft_opc::Limits::new(MAX_ENTRIES, max_part, max_total); - craft_opc::Package::open(bytes, &limits).map(|opc| Package { opc }).map_err(opc_error) + craft_opc::Package::open(bytes, &limits) + .map(|opc| Package { opc, budget: Cell::new(max_elements), budget_cap: max_elements }) + .map_err(opc_error) } /// The bytes of all its parts. @@ -244,7 +261,27 @@ impl Package { /// A package from parts already in memory (a Flat OPC file, a converted document), by part /// name without the leading `/`. pub fn from_parts(files: BTreeMap>) -> Package { - Package { opc: craft_opc::Package::from_parts(files) } + Package { opc: craft_opc::Package::from_parts(files), budget: Cell::new(xml::MAX_ELEMENTS_TOTAL), budget_cap: xml::MAX_ELEMENTS_TOTAL } + } + + /// Start a read's element budget over: the budget is per read, not per package's lifetime. + pub(crate) fn reset_budget(&self) { + self.budget.set(self.budget_cap); + } + + /// The XML elements left of the package's budget: nested documents open within it. + pub(crate) fn elements_left(&self) -> usize { + self.budget.get() + } + + /// Charge `count` elements a parsed part built against the budget. + pub(crate) fn charge(&self, count: usize) -> Result<(), DocxError> { + let left = self.budget.get(); + if count > left { + return Err(DocxError::Limit(format!("{count} XML elements, {left} left of the package's {} budget", self.budget_cap))); + } + self.budget.set(left - count); + Ok(()) } /// Part bytes by name (leading `/` ignored; case-insensitive). @@ -261,14 +298,28 @@ impl Package { /// [`Package::xml`] for the main document part: malformed XML is an error, not a truncated read. pub fn xml_strict(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse_strict(b).map(Some), + Some(b) => { + // The parser stops at the remaining budget or the per-part cap, whichever is less: + // a part over what is left of the package's budget is refused before the whole + // per-part tree is built. + let (el, count) = xml::parse_strict_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } + /// A package part as a parsed XML tree, charged against the element budget: the parser + /// stops at what is left of the budget or the per-part cap, whichever is less, and the + /// count it built is charged after. A lenient read: malformed XML is a truncated one. pub fn xml(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse(b).map(Some), + Some(b) => { + let (el, count) = xml::parse_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } @@ -448,6 +499,82 @@ mod tests { let junk = EmbeddedManifest::parse(b"R\tnope\trId1\tk\tt\tI\nP\tonly-two\n\t\t\n\xff\xfe"); assert!(junk.parts.is_empty()); } + + /// A file of many parts each inside the per-part cap is bounded in total: every XML part + /// read through the package charges a package-wide budget, and a part over it is skipped + /// (warned), never built. A chart part with no series builds a maximal tree for almost no + /// graphic work, so the trees a reader keeps would otherwise accumulate one per part. + #[test] + fn the_xml_element_budget_is_package_wide() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let rels = r#""#; + let document = format!(r#""#); + let dense = |root: &str| format!(r#"<{root} {ns}>{}"#, "".repeat(900)); + let z = zip_of(&[ + ("word/document.xml", document.into_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes().to_vec()), + ("word/styles.xml", dense("w:styles").into_bytes()), + ("word/numbering.xml", dense("w:numbering").into_bytes()), + ]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 1_000).unwrap(); + // styles (900 elements) reads; numbering (900 more) is over what is left and is skipped + // with a warning, not built. + let read = || crate::read::read_opened(&pkg, None); + let (first, warned) = crate::test_log::warnings(read); + assert!(first.is_ok(), "{:?}", first.err()); + let refused: Vec<_> = warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).collect(); + assert_eq!(refused.len(), 1, "{warned:?}"); + // The budget is per read: a second read starts it over and behaves the same. + let (second, warned) = crate::test_log::warnings(read); + assert!(second.is_ok(), "{:?}", second.err()); + assert_eq!(warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).count(), 1, "{warned:?}"); + } + + /// The main document part itself is strict: over the budget it is an error, not a + /// best-effort read of a tree the file then paid for. + #[test] + fn a_main_part_over_the_element_budget_is_refused() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(20)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 10).unwrap(); + assert!(matches!(crate::read::read_opened(&pkg, None), Err(DocxError::Limit(_)))); + } + + /// A part over what is left of the package's budget is refused while parsing, not after the + /// whole per-part tree is built: the parser stops at the remaining budget or the per-part + /// cap, whichever is less, so the file pays for at most what is left of the budget. + #[test] + fn a_part_over_the_remaining_budget_is_refused_while_parsing() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(200)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + // 200 elements: inside the per-part cap, over the package's 100 budget. The parse + // refuses at the budget, so the error is the parse's, not the charge's, and names + // the effective limit for this parse (the remaining budget), not the whole budget. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + let e = crate::read::read_opened(&pkg, None).expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 100 elements".into())); + } + + /// A part parsed earlier shrinks what is left of the budget: the next part is refused while + /// parsing at the remaining, not at the whole budget, and the error names the effective limit + /// for this parse (the remaining), not the package's budget. + #[test] + fn an_earlier_part_reduces_the_remaining_budget_the_next_part_names_it() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let styles = format!(r#"{}"#, "".repeat(60)); + let settings = format!(r#"{}"#, "".repeat(60)); + let z = zip_of(&[("word/styles.xml", styles.into_bytes()), ("word/settings.xml", settings.into_bytes())]); + // 100 elements of budget. The styles part parses (the main-part path: `xml_strict`) and + // charges its 61 elements, leaving 39. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + pkg.xml_strict("word/styles.xml").unwrap(); + // The settings part needs 61 elements, over the 39 left and under the per-part cap: the + // parse refuses at the remaining, so the error names 39, not the package's 100 budget. + let e = pkg.xml("word/settings.xml").expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 39 elements".into())); + } } #[cfg(test)] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 746225e97e..18c9ea47a0 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -154,9 +154,11 @@ pub(crate) fn read_opened(pkg: &Package, chunks: Option) -> Resul read_opened_in(pkg, ChunkState::new(chunks)).map(|(doc, ..)| doc) } -/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes and -/// graphic work left of that. -fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize), DocxError> { +/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes, +/// graphic work and XML elements left of that. +fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize, usize), DocxError> { + // The budget is per read, so a package read twice (tests, a Flat OPC conversion) starts over. + pkg.reset_budget(); let root_rels = pkg.rels(""); let main = root_rels.by_type(rt::OFFICE_DOC).filter(|r| !r.external).map(|r| r.target.clone()).unwrap_or_else(|| "word/document.xml".to_string()); let Some(root) = pkg.xml_strict(&main)? else { @@ -371,11 +373,11 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, if r.shape_ids { keep_glued_ids(&mut r.doc, &r.glued); } - let (left, bytes, graphic) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic); + let (left, bytes, graphic, elements) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic, pkg.elements_left()); let mut doc = r.doc; doc.skipped_parts.extend(pkg.skipped().iter().cloned()); doc.ensure_nonempty(); - Ok((doc, left, bytes, graphic)) + Ok((doc, left, bytes, graphic, elements)) } /// Most move ranges open at once, and most move names tracked, per file. diff --git a/crates/docx/src/read/chunk.rs b/crates/docx/src/read/chunk.rs index 2dc1674a79..113c701ff3 100644 --- a/crates/docx/src/read/chunk.rs +++ b/crates/docx/src/read/chunk.rs @@ -110,11 +110,27 @@ impl Reader<'_> { log::warn!("docx: alternative format chunks nest deeper than {MAX_CHUNK_NESTING}; the inner ones are left out"); return None; } - let pkg = - Package::open_limited(bytes, MAX_PART, self.chunks.bytes).map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")).ok()?; + // The nested document shares the file's element budget: open_limited_within, not a + // fresh cap — nesting goes deep, so 5 packages each getting 16M is the OOM class the + // budget exists for. The container's own parse spent part of the chain, so the cap is + // the lesser of the chain and what the container has left. + let cap = self.chunks.elements.min(self.pkg.elements_left()); + let pkg = Package::open_limited_within(bytes, MAX_PART, self.chunks.bytes, cap) + .map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")) + .ok()?; self.chunks.bytes = self.chunks.bytes.saturating_sub(pkg.size()); let state = ChunkState { nesting: self.chunks.nesting + 1, depth: depth + 1, ..self.chunks }; - let (doc, left, bytes, graphic) = match super::read_opened_in(&pkg, state) { + let read = super::read_opened_in(&pkg, state); + // A parsed main part can still fail semantic validation (for example, a non-Word + // root). Charge its elements before returning that error, so later siblings cannot + // reuse the reservation. On success this is the same single charge as before. + let elements = pkg.elements_left(); + self.chunks.elements = elements; + let spent = cap.saturating_sub(elements); + if let Err(e) = self.pkg.charge(spent) { + log::warn!("docx: nested document chunk outspent the container's element budget: {e}"); + } + let (doc, left, bytes, graphic, _) = match read { Ok(read) => read, Err(e) => { log::warn!("docx: unreadable nested document chunk: {e}"); @@ -139,6 +155,9 @@ pub(crate) struct ChunkState<'a> { /// Graphic work left in the file's budget ([`super::MAX_GRAPHIC_WORK`]): nested documents' /// charts and diagrams count against it too. pub graphic: usize, + /// XML elements left in the file's budget: nested packages share their container's + /// ([`crate::xml::MAX_ELEMENTS_TOTAL`]), not one of their own. + pub elements: usize, /// How deep in nested WordprocessingML chunks this reader is. pub nesting: u8, /// The XML depth its stories start at (a nested document's: that of the chunk naming it). @@ -148,7 +167,15 @@ pub(crate) struct ChunkState<'a> { impl<'a> ChunkState<'a> { pub fn new(import: Option>) -> Self { - ChunkState { left: MAX_CHUNKS, bytes: MAX_TOTAL, graphic: super::MAX_GRAPHIC_WORK, nesting: 0, depth: 0, import } + ChunkState { + left: MAX_CHUNKS, + bytes: MAX_TOTAL, + graphic: super::MAX_GRAPHIC_WORK, + elements: crate::xml::MAX_ELEMENTS_TOTAL, + nesting: 0, + depth: 0, + import, + } } } @@ -159,7 +186,7 @@ mod tests { use craft_wordmodel::{Block, Document, InlineObject}; use super::ChunkState; - use crate::package::Package; + use crate::package::{MAX_PART, MAX_TOTAL, Package}; /// A package whose body is `body`, with the document relationship `rel` (id, type, target) to /// the part `(name, bytes)`. @@ -198,8 +225,8 @@ mod tests { let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); let pkg = Package::open(&outer).unwrap(); let read = |graphic| { - let (d, .., left) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); - (drawn(&d), left) + let (d, .., work, _) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); + (drawn(&d), work) }; let (shown, left) = read(super::super::MAX_GRAPHIC_WORK); assert!(shown); @@ -207,4 +234,152 @@ mod tests { // With the file's budget spent, the nested document doesn't get one of its own. assert_eq!(read(0), (false, 0)); } + + /// A package whose body is `body`, with the document relationships `rels` (id, type, target) + /// and the parts `(name, bytes)` they name. + fn package_parts(body: &str, rels: &[(&str, &str, &str)], parts: &[(&str, &[u8])]) -> Vec { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + let rels_xml = + |inner: &str| format!(r#"{inner}"#); + let rel = |(id, ty, target): &(&str, &str, &str)| { + format!(r#""#) + }; + let names: String = rels.iter().map(rel).collect::>().join(""); + let mut files: Vec<(&str, Vec)> = vec![ + ("_rels/.rels", rels_xml(&rel(&("rId1", "officeDocument", "word/document.xml"))).into_bytes()), + ("word/document.xml", format!(r#"{body}"#).into_bytes()), + ("word/_rels/document.xml.rels", rels_xml(&names).into_bytes()), + ]; + files.extend(parts.iter().map(|(name, bytes)| (*name, bytes.to_vec()))); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in files { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(&bytes).unwrap(); + } + zw.finish().unwrap().into_inner() + } + + /// Whether the body holds a paragraph with `s`. + fn has(d: &Document, s: &str) -> bool { + d.body.iter().any(|b| b.as_para().map(|p| p.text.contains(s)).unwrap_or(false)) + } + + #[test] + fn a_nested_documents_elements_come_out_of_the_files_budget() { + // Three levels: the outer's altChunk names the inner, whose altChunk names the + // innermost. The chain spends down: the inner's own parse charges the file's budget, + // so the innermost opens with what the inner has left, not a fresh cap. + let innermost = package(r#"innermost"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"inner"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), has(&d, "innermost")) + }; + // With room, both levels flow in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true)); + // The inner's own parse (its rels, then its main part) charged the file's budget: the + // innermost is left out instead of getting one of its own (before this, each nested + // package started with the full 16M). + assert_eq!(read(10), (true, false)); + } + + #[test] + fn a_nested_documents_elements_charge_the_container() { + // The nested document's XML usage comes out of the container's budget too: the cap + // the nested package was given, minus its returned remainder, is charged, so the + // container's remaining parts parse against what is left of the shared cap — not a + // budget that ignores the chunk. + let nested = package(r#"inner"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let body = r#"after"#; + let with = package(&format!(r#"{body}"#), ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &nested)); + let without = package(body, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let read = |outer: &[u8]| { + let pkg = Package::open(outer).unwrap(); + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements: 10, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), pkg.elements_left()) + }; + let (inner_in, charged) = read(&with); + assert!(inner_in); + let (_, base) = read(&without); + assert!(charged < base, "the nested document's usage is the container's: {charged} of {base}"); + } + + #[test] + fn a_grandchilds_reservation_charges_every_level() { + // Three levels: the innermost's reservation comes out of the inner's budget, and the + // inner's out of the outer's — the chain charges every container, so the outer's + // remainder is smaller with the deeper chain than with a shallow one. + let innermost = package(r#"leaf"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"mid"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let (d, .., elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(has(&d, "mid"), "the inner document didn't flow in"); + assert!(has(&d, "leaf"), "the innermost document didn't flow in"); + // The same container with a shallow chain: one reservation instead of two. + let shallow = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &innermost)); + let pkg = Package::open(&shallow).unwrap(); + let (.., shallow_elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(elements < shallow_elements, "every level's reservation is charged: {elements} of {shallow_elements}"); + } + + #[test] + fn a_charged_budget_bounds_the_containers_part_and_the_sibling_after_it() { + // The container's budget pays for the parts it parses (the section's header, read + // during the chunk's own walk) and for the chunks after the first one: with a budget + // that fits the grandchild chunk and the header but not the sibling document's XML, + // the sibling is left out; skip the header's charge and it would flow in. + let hdr = r#"headheadhead"#; + let gc = package(r#"gc"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let sibling = + package(&r#"sibling"#.repeat(8), ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package_parts( + r#"mid"#, + &[("rIdD", "aFChunk", "afchunk.docx"), ("rIdH", "header", "header1.xml"), ("rIdS", "aFChunk", "afchunk2.docx")], + &[("word/afchunk.docx", &gc), ("word/header1.xml", hdr.as_bytes()), ("word/afchunk2.docx", &sibling)], + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "mid"), has(&d, "gc"), has(&d, "sibling")) + }; + // With room, everything flows in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true, true)); + // The grandchild chunk and the header fit the file's budget; the sibling document's + // XML (8 paragraphs) doesn't, so it's left out instead of getting a fresh cap. + assert_eq!(read(40), (true, true, false)); + } + + #[test] + fn a_rejected_nested_root_still_charges_the_siblings_budget() { + // Four outer elements, sixty rejected elements, five sibling elements: 69 in total. + let bad_xml = format!("{}", "".repeat(59)); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bad_xml.as_bytes()).unwrap(); + let bad = zip.finish().unwrap().into_inner(); + let sibling = package_parts(r#"sibling"#, &[], &[]); + let outer = package_parts( + r#""#, + &[("bad", "aFChunk", "bad.docx"), ("good", "aFChunk", "good.docx")], + &[("word/bad.docx", &bad), ("word/good.docx", &sibling)], + ); + for (cap, included, remaining) in [(69, true, 0), (68, false, 4)] { + let pkg = Package::open_limited_within(&outer, MAX_PART, MAX_TOTAL, cap).unwrap(); + let doc = super::super::read_opened(&pkg, None).unwrap(); + assert_eq!(has(&doc, "sibling"), included, "budget {cap}"); + assert_eq!(pkg.elements_left(), remaining, "budget {cap}"); + } + } } diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index fa50d217a0..46da6911d4 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -10,6 +10,10 @@ use crate::DocxError; pub const MAX_DEPTH: usize = 256; /// Maximum number of elements in one part. pub const MAX_ELEMENTS: usize = 8_000_000; +/// Maximum number of elements summed over every part a read parses: a file of many parts each +/// inside [`MAX_ELEMENTS`] would otherwise cost a tree per part, and the trees a reader keeps +/// (the main part's, charts' and diagrams') accumulate. +pub const MAX_ELEMENTS_TOTAL: usize = MAX_ELEMENTS * 2; /// Maximum number of attributes on one element (#3702). pub const MAX_ATTRS: usize = 1024; @@ -329,19 +333,31 @@ pub fn parse(bytes: &[u8]) -> Result { parse_ns(bytes, &[]) } +/// [`parse`], with the number of elements it built, stopping early at `max` elements: the caller +/// charges the count against a package-wide budget (see [`MAX_ELEMENTS_TOTAL`]), and a part over +/// what is left of it is refused before the whole per-part tree is built. +pub fn parse_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], false, max) +} + +/// [`parse_counted`], strict, for a part whose loss would be silent data loss (the main +/// document): a mismatched end tag or an element left open at the end of the data is an error, +/// not a cue to stop reading. +pub fn parse_strict_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], true, max) +} + /// [`parse`] with `extra` namespaces (prefix, URI) mapped to canonical prefixes first, so a /// related vocabulary (WordprocessingML 2003) reads with the prefixes the reader knows. pub fn parse_ns(bytes: &[u8], extra: &[(&'static str, &str)]) -> Result { - parse_with(bytes, extra, false) + parse_with(bytes, extra, false, MAX_ELEMENTS).map(|(e, _)| e) } -/// [`parse`] for a part whose loss would be silent data loss (the main document): a mismatched end -/// tag or an element left open at the end of the data is an error, not a cue to stop reading. -pub fn parse_strict(bytes: &[u8]) -> Result { - parse_with(bytes, &[], true) -} - -fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Result { +/// The XML parser everything else goes through: transcodes UTF-16, walks the events and builds +/// the tree depth-first, stopping at `max` elements and counting the ones it built. A mismatched +/// end tag or an element left open at the end of the data is an error when `strict`, a cue to +/// stop reading when not. +fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool, max: usize) -> Result<(El, usize), DocxError> { let namespaces: Vec<(&str, &str)> = extra.iter().copied().chain(NAMESPACES.iter().copied()).chain(OTHER_NAMESPACES.iter().copied()).chain(STRICT.iter().copied()).collect(); // The prefix of an element: its namespace's, with two exceptions for Strict documents @@ -375,7 +391,9 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res max_depth: MAX_DEPTH + 1, // Text stretches count as nodes too: two for each element. max_nodes: 2 * MAX_ELEMENTS, - max_elements: MAX_ELEMENTS, + // The parse stops here before the whole tree is built: a part over what is left of the + // package's element budget pays for at most that, not for the per-part cap. + max_elements: max, max_attrs: MAX_ATTRS, max_attrs_total: 2 * MAX_ELEMENTS, }; @@ -383,17 +401,27 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res if strict { options = options.strict(); } - let root = options.parse(bytes).map_err(|e| if e.is_limit() { DocxError::Limit(e.to_string()) } else { DocxError::Xml(e.to_string()) })?; - Ok(from_tree(root)) + let root = options.parse(bytes).map_err(|e| match &e { + craft_xml::Error::TooManyElements(_) => DocxError::Limit(format!("over the XML element budget for this parse: at most {max} elements")), + e if e.is_limit() => DocxError::Limit(e.to_string()), + e => DocxError::Xml(e.to_string()), + })?; + Ok(from_tree_counted(root)) } -/// The `craft-xml` tree as this module's (whose shape the reader was written against). +/// The `craft-xml` tree as this module's (whose shape the reader was written against), with the +/// number of elements the subtree holds (the caller charges it against a package-wide budget). // shortcut: one copy of each parsed part; read craft_xml::El directly when the reader is ported to it. -fn from_tree(e: craft_xml::El) -> El { +fn from_tree_counted(e: craft_xml::El) -> (El, usize) { let mut kids = Vec::with_capacity(e.children.len()); + let mut count = 1usize; for n in e.children { match n { - craft_xml::Node::El(c) => kids.push(Node::El(from_tree(c))), + craft_xml::Node::El(c) => { + let (kid, built) = from_tree_counted(c); + count += built; + kids.push(Node::El(kid)); + } craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => match kids.last_mut() { Some(Node::Text(prev)) => prev.push_str(&t), _ => kids.push(Node::Text(t)), @@ -401,7 +429,7 @@ fn from_tree(e: craft_xml::El) -> El { craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {} } } - El { name: e.name, attrs: e.attrs, kids } + (El { name: e.name, attrs: e.attrs, kids }, count) } /// This module's tree as `craft-xml`'s, for the shared readers (`craft-drawingml`, `craft-math`) @@ -515,12 +543,13 @@ mod tests { fn strict_parsing_rejects_a_dropped_entity_and_trailing_markup() { let bad = [&b"before &unknown; after"[..], b"", b""]; for xml in bad { - assert!(parse_strict(xml).is_err(), "{}", String::from_utf8_lossy(xml)); + assert!(parse_strict_counted(xml, MAX_ELEMENTS).is_err(), "{}", String::from_utf8_lossy(xml)); } assert!( - parse_strict( + parse_strict_counted( b"x & y -" +", + MAX_ELEMENTS ) .is_ok() ); diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs new file mode 100644 index 0000000000..6b220ae7ce --- /dev/null +++ b/crates/docx/tests/it/element_budget.rs @@ -0,0 +1,44 @@ +//! The package-wide XML element budget: a file of many parts each inside the per-part +//! cap reads bounded, where every part used to build its own tree and the trees the +//! reader keeps accumulated. + +use crate::fixtures; +use craft_docx::read; + +const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#; + +#[test] +fn a_file_of_element_budget_parts_still_reads() { + // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later + // parts are skipped with a warning instead of built, and the file still reads. Before + // the budget, every part's whole tree was parsed and the chart trees stayed cached for + // the whole read (~230 MB per 2M-element part, measured), so a file like this cost one + // tree per part and scales linearly with the part count. + let parts = 9usize; + let chunk = "".repeat(2_000_000); + let chart_xml = format!(r#"{chunk}"#); + let mut document = format!( + r#""# + ); + for i in 0..parts { + document.push_str(&format!( + r#""# + )); + } + document.push_str(""); + let mut rels = String::from(r#""#); + for i in 0..parts { + rels.push_str(&format!( + r#""# + )); + } + rels.push_str(""); + let mut entries: Vec<(&str, Vec)> = vec![("word/document.xml", document.into_bytes()), ("word/_rels/document.xml.rels", rels.into_bytes())]; + for i in 0..parts { + entries.push((Box::leak(format!("word/charts/chart{i}.xml").into_boxed_str()), chart_xml.clone().into_bytes())); + } + let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (*n, b.as_slice())).collect(); + let z = fixtures::zip(&refs); + let doc = read(&z).expect("a file over the element budget still reads, the extra parts skipped"); + assert_eq!(doc.body.len(), parts, "the document's own paragraphs read"); +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index 926cb5154c..942d946ae6 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -16,6 +16,7 @@ mod default_size; mod drawing_payload; mod east_asian_lang; mod east_asian_layout; +mod element_budget; mod emphasis_marks; mod fixtures; mod font_table; diff --git a/crates/drawingml/src/table/styles.rs b/crates/drawingml/src/table/styles.rs index cae3e0dd8a..9be9680880 100644 --- a/crates/drawingml/src/table/styles.rs +++ b/crates/drawingml/src/table/styles.rs @@ -211,6 +211,26 @@ fn style_def(w: &mut Writer, id: &str, name: &str) { /// opened file defined (`defs`), written back as they were read. A generated style is named /// `"{name_prefix} {label}"` (`"Acme Medium 2 Accent 1"`). pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], name_prefix: &str) -> Vec { + table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), name_prefix, |raw| { + crate::xmlx::parse(raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) + }) +} + +/// Write table style definitions without copying a caller's model or raw XML. +/// +/// `defs` yields `(id, raw_xml)` in file order and must replay the same sequence when cloned. +/// `valid` retains the caller's bounded XML-admission policy; accepted fragments are emitted +/// verbatim. It must reject fragments the caller cannot safely preserve. The ordinary +/// [`table_styles_xml`] API continues to use this crate's bounded parser. +/// +/// Input/output budgets remain caller-owned. Duplicate selection, case handling, and validation +/// order match [`table_styles_xml`]; invalid first definitions do not fall through to later ones. +pub fn table_styles_xml_with<'a>( + used: &[String], + defs: impl Iterator + Clone, + name_prefix: &str, + mut valid: impl FnMut(&str) -> bool, +) -> Vec { let mut w = Writer::document(); w.tag("a:tblStyleLst").attr("xmlns:a", NS_A).attr("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}").open(); let names = crate::table::table_styles(); @@ -218,19 +238,19 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n // definitions by lower-case id (the first wins). let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); - let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); - for d in defs { - def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); + let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); + for (id, raw) in defs.clone() { + def_of.entry(id.to_ascii_lowercase()).or_insert(raw); } for s in used { if !done.insert(s.as_str()) { continue; } done_lower.insert(s.to_ascii_lowercase()); - if let Some(d) = def_of.get(&s.to_ascii_lowercase()) - && crate::xmlx::parse(d.raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) + if let Some(raw) = def_of.get(&s.to_ascii_lowercase()) + && valid(raw) { - w.raw(&d.raw); + w.raw(raw); continue; } let (_, define) = guid_for_style(s); @@ -241,13 +261,13 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n style_def(&mut w, s, &name); } // Styles the file defined but no table uses still belong to the deck. - for d in defs { - if done_lower.contains(&d.id.to_ascii_lowercase()) { + for (id, raw) in defs { + if done_lower.contains(&id.to_ascii_lowercase()) { continue; } - if crate::xmlx::parse(d.raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) { - done_lower.insert(d.id.to_ascii_lowercase()); - w.raw(&d.raw); + if valid(raw) { + done_lower.insert(id.to_ascii_lowercase()); + w.raw(raw); } } w.close(); @@ -258,6 +278,27 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n mod tests { use super::*; + #[test] + fn borrowed_writer_preserves_model_api_and_validation_order() { + let defs = [ + crate::table::TableStyleDef { id: "custom".into(), raw: "".into(), ..Default::default() }, + crate::table::TableStyleDef { id: "CUSTOM".into(), raw: "".into(), ..Default::default() }, + ]; + let used = vec!["custom".into(), "custom".into(), "light1-accent1".into()]; + let borrowed = || defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())); + assert_eq!( + table_styles_xml(&used, &defs, "App"), + table_styles_xml_with(&used, borrowed(), "App", |raw| { crate::xmlx::parse(raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) }) + ); + let mut checked = Vec::new(); + let bytes = table_styles_xml_with(&used, borrowed(), "App", |raw| { + checked.push(raw.to_owned()); + false + }); + assert_eq!(checked, [""]); + assert!(!String::from_utf8(bytes).unwrap().contains("duplicate=")); + } + #[test] fn style_parts_follow_schema_order() { const ORDER: [&str; 14] = [ diff --git a/crates/esign/Cargo.toml b/crates/esign/Cargo.toml new file mode 100644 index 0000000000..7a2efc3246 --- /dev/null +++ b/crates/esign/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-esign" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "What an e-sign service offers the Craft apps: envelopes, recipients and events as contracts, with no vendor and no IO" + +[lints] +workspace = true + +[dependencies] +craft-cloud = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/esign/src/error.rs b/crates/esign/src/error.rs new file mode 100644 index 0000000000..fca354b453 --- /dev/null +++ b/crates/esign/src/error.rs @@ -0,0 +1,63 @@ +//! One error type for every e-sign contract. +//! +//! Cloud failures are wrapped so a host can surface sign-in and reachability +//! the same way it already does for files. The e-sign-only cases are the ones +//! a UI acts on differently: declined, voided, expired, identity check. + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + /// Something the cloud contracts already classify. + #[error(transparent)] + Cloud(#[from] craft_cloud::Error), + + /// A recipient refused to sign. + #[error("declined: {0}")] + Declined(String), + + /// The sender voided the envelope. + #[error("voided: {0}")] + Voided(String), + + /// The envelope passed its deadline without completing. + #[error("expired: {0}")] + Expired(String), + + /// The provider rejected the signer's identity check. + #[error("identity check failed: {0}")] + IdentityCheck(String), + + /// The chosen provider refuses this request under its policy. + #[error("provider policy: {0}")] + ProviderPolicy(String), + + /// The service does not offer this at all. + #[error("this signing service does not support {0}")] + Unsupported(&'static str), + + /// The answer did not match the protocol. + #[error("malformed {what}: {detail}")] + Malformed { what: &'static str, detail: String }, + + /// A field the caller supplied could not be used safely. + #[error("invalid {what}: {detail}")] + Invalid { what: &'static str, detail: String }, +} + +impl Error { + pub fn malformed(what: &'static str, detail: impl Into) -> Error { + Error::Malformed { what, detail: detail.into() } + } + + pub fn invalid(what: &'static str, detail: impl Into) -> Error { + Error::Invalid { what, detail: detail.into() } + } + + /// Whether trying again could succeed without the user doing anything. + pub fn is_transient(&self) -> bool { + matches!(self, Error::Cloud(e) if e.is_transient()) + } +} + +pub type Result = std::result::Result; diff --git a/crates/esign/src/lib.rs b/crates/esign/src/lib.rs new file mode 100644 index 0000000000..e9e6fa04bc --- /dev/null +++ b/crates/esign/src/lib.rs @@ -0,0 +1,318 @@ +//! What an e-sign service has to offer the Craft apps, and nothing about who +//! provides it. +//! +//! An envelope is a ceremony: a document snapshot, a set of recipients, field +//! placements, and a status. The legal audit trail, identity checks and +//! invitation mail belong to the signing service. This crate only names the +//! contracts an app needs to create, send, watch and finish that ceremony. +//! +//! Nothing in this crate opens a socket. Each trait is implemented by a host +//! (CollabCraft, a desktop adapter, a test double) that brings its own +//! transport. No type here names a vendor. No type here knows about PDF +//! structure: a document is opaque bytes plus a content hash. +//! +//! This crate sits beside `craft-cloud`. It reuses [`craft_cloud::Identity`] +//! and the idea of a contact for autocomplete, but it does not extend +//! [`craft_cloud::Provider`] or [`craft_cloud::Capability`]. Signing is not +//! file access, and a signer role is not a share permission. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod types; + +pub use error::{Error, Result}; +pub use types::{ + CompletedDocument, Envelope, EnvelopeDraft, EnvelopeEvent, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus, +}; + +/// Creating and driving envelopes. +/// +/// Methods that a minimal service may omit are defaulted to +/// [`Error::Unsupported`], the same pattern [`craft_cloud::Conversations`] +/// uses for optional cloud features. +pub trait Envelopes { + /// Create a draft from a document snapshot. + /// + /// `document` is the exact byte sequence the ceremony seals. The + /// implementation hashes it and stores `content_sha256` on the envelope. + /// `idempotency_key` makes a retried create return the same envelope. + fn create(&self, draft: &EnvelopeDraft, document: &[u8], idempotency_key: &str) -> Result; + + /// Send invitations and move the envelope to [`EnvelopeStatus::Sent`]. + fn send(&self, envelope: &str) -> Result; + + /// Current status, including per-recipient progress. + fn status(&self, envelope: &str) -> Result; + + /// The finished document and provider evidence. + /// + /// Fails unless status is [`EnvelopeStatus::Completed`]. The returned + /// [`CompletedDocument`] carries both the original document's content + /// digest and the signed artifact's digest, computed honestly rather + /// than copied from one another: the implementation must not assume the + /// provider's sealing left the bytes unchanged. + fn completed(&self, envelope: &str) -> Result; + + /// Cancel an in-flight envelope. + fn void(&self, _envelope: &str, _reason: &str) -> Result<()> { + Err(Error::Unsupported("void")) + } + + /// Nudge one recipient who has not signed yet. + fn remind(&self, _envelope: &str, _recipient: &str) -> Result<()> { + Err(Error::Unsupported("reminders")) + } + + /// A URL the recipient opens to sign inside the provider's UI. + fn signing_url(&self, _envelope: &str, _recipient: &str, _return_to: &str) -> Result { + Err(Error::Unsupported("embedded signing")) + } +} + +/// Turning provider webhooks into [`EnvelopeEvent`]s. +/// +/// Server-side only. A desktop host that implements [`Envelopes`] never needs +/// a webhook secret and need not implement this beyond refusing. +pub trait EventIntake { + /// Verify authenticity and parse zero or more events from one HTTP body. + fn verify_event(&self, headers: &[(String, String)], body: &[u8]) -> Result>; +} + +/// Everything one signing service can do. +/// +/// A service implements the capabilities it has and reports the rest as +/// absent, so a caller can hide void on a stub that only supports the happy +/// path rather than offering a control that fails on use. +pub trait SigningService: Envelopes + EventIntake { + /// A stable identifier, such as `stub` or `documenso`. Used in + /// configuration and logs, never shown to a user. + fn id(&self) -> &str; + + /// What this service actually supports. + fn capabilities(&self) -> Vec; + + fn supports(&self, capability: EsignCapability) -> bool { + self.capabilities().contains(&capability) + } + + /// The party that holds legal and compliance responsibility for the + /// ceremony. Shown to senders before they send (upstream #2315). + fn responsible_party(&self) -> String; +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + use craft_cloud::Identity; + + struct RefuseAll; + + impl Envelopes for RefuseAll { + fn create(&self, _: &EnvelopeDraft, _: &[u8], _: &str) -> Result { + Err(Error::Unsupported("create")) + } + + fn send(&self, _: &str) -> Result { + Err(Error::Unsupported("send")) + } + + fn status(&self, _: &str) -> Result { + Err(Error::Unsupported("status")) + } + + fn completed(&self, _: &str) -> Result { + Err(Error::Unsupported("completed")) + } + } + + impl EventIntake for RefuseAll { + fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result> { + Err(Error::Unsupported("webhooks")) + } + } + + impl SigningService for RefuseAll { + fn id(&self) -> &str { + "refuse" + } + + fn capabilities(&self) -> Vec { + Vec::new() + } + + fn responsible_party(&self) -> String { + "nobody".into() + } + } + + #[test] + fn defaulted_methods_are_unsupported() { + let s = RefuseAll; + assert!(matches!(s.void("e", "x"), Err(Error::Unsupported("void")))); + assert!(matches!(s.remind("e", "r"), Err(Error::Unsupported("reminders")))); + assert!(matches!(s.signing_url("e", "r", "https://example"), Err(Error::Unsupported("embedded signing")))); + assert!(!s.supports(EsignCapability::Envelopes)); + assert_eq!(s.responsible_party(), "nobody"); + } + + #[test] + fn draft_round_trips_json() { + let draft = EnvelopeDraft { + title: "NDA".into(), + message: Some("please sign".into()), + sender: Identity { id: "u1".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }, + document_id: Some("doc-1".into()), + document_etag: Some("\"abc\"".into()), + recipients: vec![Recipient { + id: "r1".into(), + name: "Bob".into(), + email: "bob@example.com".into(), + role: "Signer".into(), + required: true, + status: RecipientStatus::Pending, + }], + placements: vec![FieldPlacement { + role: "Signer".into(), + page: 0, + x: 0.1, + y: 0.2, + w: 0.3, + h: 0.05, + kind: "signature".into(), + required: true, + }], + expires: Some("2026-12-31".into()), + }; + let json = serde_json::to_string(&draft).expect("serialize"); + let back: EnvelopeDraft = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, draft); + } + + #[test] + fn cloud_errors_wrap_and_report_transient() { + let err = Error::from(craft_cloud::Error::Unreachable("down".into())); + assert!(err.is_transient()); + let err = Error::Declined("no".into()); + assert!(!err.is_transient()); + } + + /// A non-cryptographic stand-in for a content digest. Good enough to + /// prove two byte strings differ; this crate takes no hashing + /// dependency, since hashing the document is an adapter's job. + fn fake_digest(bytes: &[u8]) -> String { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut hasher); + format!("{:016x}", hasher.finish()) + } + + /// An honest in-process double for [`Envelopes`]. It keeps the exact + /// bytes `create` was given, and on `completed` returns a "signed" + /// artifact built by appending a stub provider seal to those bytes, so + /// `original_content_sha256` and `signed_content_sha256` are computed + /// from genuinely different byte strings, the way a real provider's + /// sealing would produce them, rather than one copied from the other. + struct Double { + document: Mutex>>, + } + + impl Double { + fn new() -> Double { + Double { document: Mutex::new(None) } + } + } + + impl Envelopes for Double { + fn create(&self, draft: &EnvelopeDraft, document: &[u8], _idempotency_key: &str) -> Result { + *self.document.lock().expect("lock") = Some(document.to_vec()); + Ok(Envelope { + id: "env-double".into(), + title: draft.title.clone(), + message: draft.message.clone(), + sender: draft.sender.clone(), + document_id: draft.document_id.clone(), + document_etag: draft.document_etag.clone(), + content_sha256: fake_digest(document), + recipients: draft.recipients.clone(), + placements: draft.placements.clone(), + status: EnvelopeStatus::Draft, + expires: draft.expires.clone(), + created: None, + completed_at: None, + }) + } + + fn send(&self, envelope: &str) -> Result { + self.status(envelope) + } + + fn status(&self, envelope: &str) -> Result { + let document = self.document.lock().expect("lock").clone().unwrap_or_default(); + Ok(Envelope { + id: envelope.into(), + title: "Double".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: None, + document_etag: None, + content_sha256: fake_digest(&document), + recipients: Vec::new(), + placements: Vec::new(), + status: EnvelopeStatus::Completed, + expires: None, + created: None, + completed_at: None, + }) + } + + fn completed(&self, envelope: &str) -> Result { + let original = self.document.lock().expect("lock").clone().unwrap_or_default(); + let mut signed = original.clone(); + signed.extend_from_slice(b"\0provider-seal"); + Ok(CompletedDocument { + envelope_id: envelope.into(), + bytes: signed.clone(), + original_content_sha256: fake_digest(&original), + signed_content_sha256: fake_digest(&signed), + evidence: b"certificate-of-completion".to_vec(), + }) + } + } + + /// RFC-0021's evidence guarantee: `CompletedDocument` carries the + /// original document's digest and the signed artifact's digest as two + /// distinct, honestly computed fields, and they differ when the + /// provider's sealing changes the bytes. + #[test] + fn completed_document_keeps_original_and_signed_digests_distinct() { + let double = Double::new(); + let draft = EnvelopeDraft { + title: "Contract".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: Some("doc-1".into()), + document_etag: None, + recipients: Vec::new(), + placements: Vec::new(), + expires: None, + }; + let original_bytes = b"the original document bytes"; + let envelope = double.create(&draft, original_bytes, "idem-1").expect("create"); + let completed = double.completed(&envelope.id).expect("completed"); + + assert_eq!(completed.original_content_sha256, fake_digest(original_bytes)); + assert_ne!(completed.bytes, original_bytes, "the signed artifact's bytes differ from the original"); + assert_eq!(completed.signed_content_sha256, fake_digest(&completed.bytes)); + assert_ne!( + completed.original_content_sha256, completed.signed_content_sha256, + "sealing changed the bytes, so the two digests must not be conflated" + ); + + let json = serde_json::to_string(&completed).expect("serialize"); + let back: CompletedDocument = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, completed); + } +} diff --git a/crates/esign/src/types.rs b/crates/esign/src/types.rs new file mode 100644 index 0000000000..08d42456e4 --- /dev/null +++ b/crates/esign/src/types.rs @@ -0,0 +1,186 @@ +//! The data the e-sign contracts pass around. +//! +//! Every type here is plain and vendor-neutral. A field that only means +//! something to one product belongs in that provider's crate. Nothing here +//! knows about PDF structure; a document is opaque bytes plus a content hash. + +use craft_cloud::Identity; +use serde::{Deserialize, Serialize}; + +/// What a signing service can do. +/// +/// Reported rather than assumed, so a caller hides void or remind on a service +/// that only supports create/send/status/completed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EsignCapability { + /// Create, send, poll status, and fetch the completed document. + Envelopes, + /// Cancel an in-flight envelope. + Void, + /// Nudge a recipient who has not signed yet. + Reminders, + /// Return a URL the recipient opens to sign in the provider's UI. + EmbeddedSigning, + /// Accept provider webhooks and turn them into [`EnvelopeEvent`]s. + Webhooks, +} + +/// Where an envelope is in its life. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvelopeStatus { + /// Created but not yet sent to recipients. + Draft, + /// At least one recipient still owes a signature. + Sent, + /// Every required recipient has signed. + Completed, + /// The sender cancelled it. + Voided, + /// A recipient declined. + Declined, + /// The deadline passed without completion. + Expired, +} + +/// What one recipient still owes, or has done. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RecipientStatus { + Pending, + Viewed, + Signed, + Declined, +} + +/// Who must sign, as the dialog and the service agree. +/// +/// Built from a [`craft_cloud::Contact`] by an explicit conversion at the host +/// boundary. Never a [`craft_cloud::ShareTarget`]: signing is not access. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipient { + /// Opaque handle the service wants back. + pub id: String, + /// What to show. A display name where there is one. + pub name: String, + /// Delivery address. Required for invitation mail. + pub email: String, + /// Signer role label, such as "Client" or "Countersign". Colours and + /// field placement key off this string within one envelope. + pub role: String, + /// Whether the envelope cannot complete without this person. + pub required: bool, + pub status: RecipientStatus, +} + +/// One signature (or initials / date) placement on the document. +/// +/// Coordinates are normalised page space: origin top-left, `x`/`y`/`w`/`h` in +/// `[0.0, 1.0]` of the page. The document implementation maps these onto its +/// own field model; this crate never sees PDF objects. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FieldPlacement { + /// Recipient role this field belongs to. + pub role: String, + /// Zero-based page index. + pub page: u32, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + /// Machine-readable kind: `signature`, `initials`, `date`, `text`. + pub kind: String, + pub required: bool, +} + +impl PartialEq for FieldPlacement { + fn eq(&self, other: &Self) -> bool { + self.role == other.role + && self.page == other.page + && self.kind == other.kind + && self.required == other.required + && self.x.to_bits() == other.x.to_bits() + && self.y.to_bits() == other.y.to_bits() + && self.w.to_bits() == other.w.to_bits() + && self.h.to_bits() == other.h.to_bits() + } +} + +impl Eq for FieldPlacement {} + +/// What the caller wants to send, before the service assigns an id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeDraft { + /// Human title for the ceremony. + pub title: String, + /// Optional note shown to recipients. + pub message: Option, + /// Who is asking for signatures. Bound to the active account at send time. + pub sender: Identity, + /// Cloud document identity at the moment of the snapshot, when known. + pub document_id: Option, + pub document_etag: Option, + pub recipients: Vec, + pub placements: Vec, + /// `YYYY-MM-DD`. After this the envelope expires if still open. + pub expires: Option, +} + +/// An envelope the service knows about. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Envelope { + pub id: String, + pub title: String, + pub message: Option, + pub sender: Identity, + pub document_id: Option, + pub document_etag: Option, + /// SHA-256 of the document bytes at create time, lowercase hex. + pub content_sha256: String, + pub recipients: Vec, + pub placements: Vec, + pub status: EnvelopeStatus, + pub expires: Option, + /// RFC 3339. + pub created: Option, + /// RFC 3339 when status became [`EnvelopeStatus::Completed`]. + pub completed_at: Option, +} + +/// The finished document plus whatever evidence the provider returns. +/// +/// Carries two digests as distinct fields, never conflated: the original +/// document's content digest and the returned signed artifact's digest. The +/// two are the same hash family as [`Envelope::content_sha256`] and can +/// differ in value. A provider's sealing (a certificate page, flattening, a +/// visible audit stamp) can change the signed bytes relative to the document +/// the envelope was created from, so a caller must not assume `bytes` hashes +/// back to `original_content_sha256`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompletedDocument { + pub envelope_id: String, + /// Signed document bytes. Opaque to this crate. + pub bytes: Vec, + /// SHA-256 of the original document bytes the envelope was created from, + /// lowercase hex. Matches the envelope's own `content_sha256`. + pub original_content_sha256: String, + /// SHA-256 of `bytes`, the returned signed artifact, lowercase hex. May + /// differ from `original_content_sha256`; see the struct's docs. + pub signed_content_sha256: String, + /// Provider evidence (certificate of completion, audit export, …). + pub evidence: Vec, +} + +/// Something that happened to an envelope. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeEvent { + pub envelope_id: String, + /// Machine-readable kind: `sent`, `viewed`, `signed`, `declined`, `voided`, `completed`. + pub kind: String, + /// Recipient id when the event is about one person. + pub recipient_id: Option, + /// RFC 3339. + pub at: Option, + pub detail: Option, +} diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml new file mode 100644 index 0000000000..018f5dff05 --- /dev/null +++ b/crates/evm/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-evm" +description = "Read-only EVM bytecode dispatcher and compiler metadata inspection" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/evm/README.md b/crates/evm/README.md new file mode 100644 index 0000000000..6214c45b45 --- /dev/null +++ b/crates/evm/README.md @@ -0,0 +1,7 @@ +# craft-evm + +Read-only EVM bytecode inspection: strict raw/hex admission, opcode listing, dispatcher selector and jump-pattern facts, and Solidity/Vyper CBOR metadata. No VM execution, RPC, wallet, signing or transaction support. + +Preserves Craft Anything's parser behavior and limits: 16 MiB decoded bytecode, 4,096 reported functions and 400 listing entries, plus existing bounded CBOR recursion/collection parsing. These are not a total allocator-byte guarantee. Dispatcher facts are heuristics, not a full control-flow or semantic proof. EOF containers remain unsupported. + +Application file I/O, evidence policy and selector naming remain outside this crate. diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs new file mode 100644 index 0000000000..29d254b405 --- /dev/null +++ b/crates/evm/src/lib.rs @@ -0,0 +1,895 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! EVM bytecode: the public function selectors a contract's dispatcher compares against, where +//! each one jumps, whether it refuses payments, fallback/receive presence, and the compiler +//! metadata (CBOR) appended to the code. Nothing is executed; this is a linear sweep that +//! respects PUSH data plus pattern matching over the instruction stream. + +use EvmError as FormatError; + +/// Neutral inspection failure; no code is executed. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum EvmError { + #[error("truncated input: {0}")] + Truncated(String), + #[error("malformed input: {0}")] + Malformed(String), + #[error("unsupported: {0}")] + Unsupported(String), + #[error("input too large: {0}")] + TooLarge(String), +} + +#[cfg(test)] +mod test_support; +use serde::Serialize; +use serde_json::{Map, Value}; +use std::collections::BTreeSet; + +/// Largest bytecode we analyse (16 MiB; deployed contracts are at most 24 KiB). +pub const MAX_CODE: usize = 16 << 20; +const MAX_FUNCTIONS: usize = 4096; +const LISTING_CAP: usize = 400; + +/// How input bytes are encoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Encoding { + /// Hex when the bytes are all hex digits (with an optional 0x), raw otherwise. + Auto, + Raw, + Hex, +} + +/// Turn input bytes into bytecode. Hex is strict: optional `0x`, even length, only hex digits; +/// surrounding whitespace is ignored. +pub fn decode_input(input: &[u8], enc: Encoding) -> Result<(Vec, &'static str), FormatError> { + let trimmed = input.trim_ascii(); + let body = trimmed.strip_prefix(b"0x").or_else(|| trimmed.strip_prefix(b"0X")).unwrap_or(trimmed); + let looks_hex = !body.is_empty() && body.iter().all(u8::is_ascii_hexdigit); + let hex = match enc { + Encoding::Hex => true, + Encoding::Raw => false, + Encoding::Auto => looks_hex, + }; + if !hex { + if input.len() > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", input.len()))); + } + return Ok((input.to_vec(), "raw")); + } + if body.is_empty() { + return Err(FormatError::Malformed("no hex digits".into())); + } + if let Some(p) = body.iter().position(|b| !b.is_ascii_hexdigit()) { + return Err(FormatError::Malformed(format!("not a hex digit at position {p}"))); + } + if !body.len().is_multiple_of(2) { + return Err(FormatError::Malformed(format!("odd number of hex digits ({})", body.len()))); + } + if body.len() / 2 > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", body.len() / 2))); + } + let nib = |c: u8| -> u8 { + match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + _ => c.wrapping_sub(b'A').wrapping_add(10) & 0x0f, + } + }; + Ok((body.chunks(2).map(|p| (nib(p.first().copied().unwrap_or(b'0')) << 4) | nib(p.get(1).copied().unwrap_or(b'0'))).collect(), "hex")) +} + +#[derive(Debug, Clone, Copy)] +struct Ins { + off: usize, + op: u8, + /// Immediate (PUSH data) start and length. + imm: (usize, usize), +} + +fn push_len(op: u8) -> usize { + if (0x60..=0x7f).contains(&op) { usize::from(op - 0x5f) } else { 0 } +} + +/// The mnemonic of an opcode (`UNKNOWN_0x…` for unassigned ones). +pub fn mnemonic(op: u8) -> String { + let s = match op { + 0x00 => "STOP", + 0x01 => "ADD", + 0x02 => "MUL", + 0x03 => "SUB", + 0x04 => "DIV", + 0x05 => "SDIV", + 0x06 => "MOD", + 0x07 => "SMOD", + 0x08 => "ADDMOD", + 0x09 => "MULMOD", + 0x0a => "EXP", + 0x0b => "SIGNEXTEND", + 0x10 => "LT", + 0x11 => "GT", + 0x12 => "SLT", + 0x13 => "SGT", + 0x14 => "EQ", + 0x15 => "ISZERO", + 0x16 => "AND", + 0x17 => "OR", + 0x18 => "XOR", + 0x19 => "NOT", + 0x1a => "BYTE", + 0x1b => "SHL", + 0x1c => "SHR", + 0x1d => "SAR", + 0x20 => "KECCAK256", + 0x30 => "ADDRESS", + 0x31 => "BALANCE", + 0x32 => "ORIGIN", + 0x33 => "CALLER", + 0x34 => "CALLVALUE", + 0x35 => "CALLDATALOAD", + 0x36 => "CALLDATASIZE", + 0x37 => "CALLDATACOPY", + 0x38 => "CODESIZE", + 0x39 => "CODECOPY", + 0x3a => "GASPRICE", + 0x3b => "EXTCODESIZE", + 0x3c => "EXTCODECOPY", + 0x3d => "RETURNDATASIZE", + 0x3e => "RETURNDATACOPY", + 0x3f => "EXTCODEHASH", + 0x40 => "BLOCKHASH", + 0x41 => "COINBASE", + 0x42 => "TIMESTAMP", + 0x43 => "NUMBER", + 0x44 => "PREVRANDAO", + 0x45 => "GASLIMIT", + 0x46 => "CHAINID", + 0x47 => "SELFBALANCE", + 0x48 => "BASEFEE", + 0x49 => "BLOBHASH", + 0x4a => "BLOBBASEFEE", + 0x50 => "POP", + 0x51 => "MLOAD", + 0x52 => "MSTORE", + 0x53 => "MSTORE8", + 0x54 => "SLOAD", + 0x55 => "SSTORE", + 0x56 => "JUMP", + 0x57 => "JUMPI", + 0x58 => "PC", + 0x59 => "MSIZE", + 0x5a => "GAS", + 0x5b => "JUMPDEST", + 0x5c => "TLOAD", + 0x5d => "TSTORE", + 0x5e => "MCOPY", + 0x5f => "PUSH0", + 0x60..=0x7f => return format!("PUSH{}", op - 0x5f), + 0x80..=0x8f => return format!("DUP{}", op - 0x7f), + 0x90..=0x9f => return format!("SWAP{}", op - 0x8f), + 0xa0..=0xa4 => return format!("LOG{}", op - 0xa0), + 0xf0 => "CREATE", + 0xf1 => "CALL", + 0xf2 => "CALLCODE", + 0xf3 => "RETURN", + 0xf4 => "DELEGATECALL", + 0xf5 => "CREATE2", + 0xfa => "STATICCALL", + 0xfd => "REVERT", + 0xfe => "INVALID", + 0xff => "SELFDESTRUCT", + _ => return format!("UNKNOWN_{op:#04x}"), + }; + s.to_string() +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct EvmFunction { + /// `0x` + 8 hex digits. + pub selector: String, + /// Where the dispatcher sends calls with this selector. + pub bytecode_offset: usize, + /// Offset of the comparison in the dispatcher. + pub compare_offset: usize, + pub dispatch: &'static str, + /// `eq-jumpi` (jump on match) or `eq-iszero-fallthrough` (body follows the check). + pub pattern: &'static str, + /// `nonpayable`, `payable` or `unknown` (view/pure cannot be told from the dispatcher). + pub mutability: &'static str, + /// Why the mutability was chosen. + pub mutability_reason: String, + /// False when the destination is not a JUMPDEST (the match is then doubtful). + pub jumpdest_valid: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct EvmMetadata { + pub offset: usize, + pub length: usize, + pub entries: Value, + pub compiler: Option, + pub ipfs: Option, + pub swarm: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct EvmInterface { + pub code_size: usize, + /// Bytes analysed after removing the metadata tail. + pub analysed_size: usize, + pub metadata: Option, + pub instructions: usize, + pub jumpdests: usize, + /// How the selector is pulled from calldata: `shr-224`, `div-2^224`, `and-mask`, or none. + pub selector_extraction: Option<&'static str>, + pub dispatcher_offset: Option, + /// `solc-like`, `vyper-like`, `mixed` or `none`. + pub style: &'static str, + pub functions: Vec, + /// Comparisons that split the selector range (binary-search dispatchers). + pub binary_search_splits: usize, + /// A CALLVALUE check that runs before any selector comparison (all functions non-payable). + pub callvalue_check_before_dispatch: bool, + pub short_calldata_check: bool, + /// `present`, `absent` or `unknown`. + pub fallback: &'static str, + /// `present` or `not-detected`. + pub receive: &'static str, + /// The dispatcher region as text (first instructions only). + pub dispatcher_listing: Vec, + pub warnings: Vec, +} + +fn sweep(code: &[u8]) -> Vec { + let mut out = Vec::with_capacity(code.len().min(1 << 20) / 2); + let mut i = 0usize; + while i < code.len() { + let op = code.get(i).copied().unwrap_or(0); + let n = push_len(op); + out.push(Ins { off: i, op, imm: (i + 1, n) }); + i = i.saturating_add(1).saturating_add(n); + } + out +} + +fn imm<'a>(code: &'a [u8], ins: &Ins) -> &'a [u8] { + // Truncated PUSH data at the end of code reads as zero-padded; we only use what exists. + let (s, n) = ins.imm; + code.get(s..s.saturating_add(n).min(code.len())).unwrap_or(&[]) +} + +fn imm_u64(code: &[u8], ins: &Ins) -> Option { + let b = imm(code, ins); + if ins.imm.1 > 8 || b.len() != ins.imm.1 { + return None; + } + Some(b.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x))) +} + +fn is_push(op: u8) -> bool { + (0x60..=0x7f).contains(&op) +} + +/// Strip and decode a trailing CBOR metadata block. +fn split_metadata(code: &[u8]) -> (usize, Option) { + let n = code.len(); + if n < 4 { + return (n, None); + } + let len = usize::from(u16::from_be_bytes([code.get(n - 2).copied().unwrap_or(0), code.get(n - 1).copied().unwrap_or(0)])); + if len == 0 || len.saturating_add(2) > n { + return (n, None); + } + let start = n - 2 - len; + let Some(cbor) = code.get(start..n - 2) else { return (n, None) }; + if !matches!(cbor.first(), Some(0xa1..=0xb8 | 0xbf)) { + return (n, None); + } + let mut pos = 0usize; + let Some(v) = cbor_item(cbor, &mut pos, 0) else { return (n, None) }; + if pos != cbor.len() { + return (n, None); + } + let Value::Object(map) = &v else { return (n, None) }; + let compiler = map + .get("solc") + .and_then(|s| s.as_str().map(String::from)) + .map(|v| format!("solc {v}")) + .or_else(|| map.get("vyper").and_then(Value::as_str).map(|v| format!("vyper {v}"))); + let ipfs = map.get("ipfs").and_then(Value::as_str).map(String::from); + let swarm = map.get("bzzr1").or_else(|| map.get("bzzr0")).and_then(Value::as_str).map(String::from); + (start, Some(EvmMetadata { offset: start, length: len + 2, entries: v.clone(), compiler, ipfs, swarm })) +} + +fn cbor_arg(b: &[u8], pos: &mut usize, info: u8) -> Option { + let take = |pos: &mut usize, k: usize| -> Option { + let s = b.get(*pos..pos.checked_add(k)?)?; + *pos += k; + Some(s.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x))) + }; + match info { + 0..=23 => Some(u64::from(info)), + 24 => take(pos, 1), + 25 => take(pos, 2), + 26 => take(pos, 4), + 27 => take(pos, 8), + _ => None, + } +} + +/// Decode one bounded metadata item. An incomplete or unsupported value invalidates the metadata trailer. +fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { + if depth > 4 { + return None; + } + let ib = *b.get(*pos)?; + *pos += 1; + let major = ib >> 5; + let info = ib & 0x1f; + match major { + 0 => cbor_arg(b, pos, info).map(Value::from), + 2 | 3 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + let s = b.get(*pos..pos.checked_add(n)?)?; + *pos += n; + Some(if major == 3 { Value::from(std::str::from_utf8(s).ok()?) } else { Value::from(bytes_value(s)) }) + } + 4 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + if n > 64 { + return None; + } + let mut items = Vec::new(); + for _ in 0..n { + items.push(cbor_item(b, pos, depth + 1)?); + } + Some(Value::Array(items)) + } + 5 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + if n > 32 { + return None; + } + let mut m = Map::new(); + for _ in 0..n { + // The metadata view uses JSON object keys. Coercing other CBOR key + // types to strings can merge distinct keys and hide bytecode. + if b.get(*pos).map(|byte| byte >> 5) != Some(3) { + return None; + } + let Value::String(k) = cbor_item(b, pos, depth + 1)? else { return None }; + if m.contains_key(&k) { + return None; + } + let v = cbor_item(b, pos, depth + 1)?; + let v = match (k.as_str(), &v) { + ("solc" | "vyper", Value::Array(items)) if items.len() == 3 && items.iter().all(Value::is_u64) => { + Value::from(items.iter().map(|v| v.to_string()).collect::>().join(".")) + } + ("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => { + let d: Vec = (0..3).filter_map(|i| hex_byte(s.get(2 + 2 * i..4 + 2 * i)?)).collect(); + if let [a, bb, c] = d.as_slice() { Value::from(format!("{a}.{bb}.{c}")) } else { v } + } + ("ipfs", Value::String(s)) if s.starts_with("0x1220") => Value::from(base58(&hex_decode(s.get(2..).unwrap_or("")))), + _ => v, + }; + m.insert(k, v); + } + Some(Value::Object(m)) + } + 7 => match info { + 20 => Some(Value::Bool(false)), + 21 => Some(Value::Bool(true)), + 22 => Some(Value::Null), + _ => None, + }, + _ => None, + } +} + +fn bytes_value(s: &[u8]) -> String { + let mut out = String::with_capacity(2 + s.len() * 2); + out.push_str("0x"); + for b in s { + out.push_str(&format!("{b:02x}")); + } + out +} + +/// One byte from two hex digits; `from_str_radix` alone would also accept a leading `+`. +fn hex_byte(pair: &str) -> Option { + if pair.bytes().all(|c| c.is_ascii_hexdigit()) { u8::from_str_radix(pair, 16).ok() } else { None } +} + +fn hex_decode(s: &str) -> Vec { + (0..s.len() / 2).filter_map(|i| hex_byte(s.get(2 * i..2 * i + 2)?)).collect() +} + +fn base58(b: &[u8]) -> String { + const A: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + let zeros = b.iter().take_while(|&&x| x == 0).count(); + let mut digits: Vec = Vec::new(); + for &byte in b.iter().take(128) { + let mut carry = u32::from(byte); + for d in digits.iter_mut() { + carry += u32::from(*d) << 8; + *d = (carry % 58) as u8; + carry /= 58; + } + while carry > 0 { + digits.push((carry % 58) as u8); + carry /= 58; + } + } + let mut s: String = std::iter::repeat_n('1', zeros).collect(); + s.extend(digits.iter().rev().map(|&d| char::from(*A.get(usize::from(d)).unwrap_or(&b'1')))); + s +} + +fn selector_extraction(body: &[u8], ins: &[Ins]) -> Option<(&'static str, usize)> { + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + // Selector extraction: CALLDATALOAD followed by SHR 224, DIV 2^224 or a 4-byte mask. + let mut extraction: Option<(&'static str, usize)> = None; + for (k, i) in ins.iter().enumerate() { + if i.op != 0x35 { + continue; + } + for d in 1..=6 { + let Some(n) = at(k + d) else { break }; + let kind = match n.op { + 0x60 if imm(body, n) == [0xe0] && op_at(k + d + 1) == Some(0x1c) => Some("shr-224"), + 0x7c if d == 1 + && imm(body, n).first() == Some(&1) + && imm(body, n).iter().skip(1).all(|&b| b == 0) + && op_at(k + d + 1) == Some(0x90) + && op_at(k + d + 2) == Some(0x04) => + { + Some("div-2^224") + } + 0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => { + Some("and-mask") + } + _ => None, + }; + if let Some(kind) = kind { + extraction = Some((kind, k)); + break; + } + } + if extraction.is_some() { + break; + } + } + extraction +} + +fn short_calldata_path(body: &[u8], ins: &[Ins], disp_start: usize) -> (bool, &'static str) { + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + // Short calldata path and receive(). + let mut short_calldata = false; + let mut receive = "not-detected"; + for (k, i) in ins.iter().enumerate().take(disp_start.saturating_add(64)) { + if i.op != 0x36 { + continue; + } + if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) { + receive = "present"; + } + // LT pops the size first in PUSH 4, CALLDATASIZE, LT. + if k.checked_sub(1).and_then(at).is_some_and(|p| is_push(p.op) && imm_u64(body, p) == Some(4)) + && op_at(k + 1) == Some(0x10) + && at(k + 2).is_some_and(|p| is_push(p.op)) + && op_at(k + 3) == Some(0x57) + { + short_calldata = true; + } + } + (short_calldata, receive) +} + +/// Analyse bytecode (already decoded from hex if needed). +pub fn analyze(code: &[u8]) -> Result { + if code.is_empty() { + return Err(FormatError::Truncated("no bytecode".into())); + } + if code.len() > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", code.len()))); + } + if code.starts_with(&[0xef, 0x00]) { + return Err(FormatError::Unsupported("EVM Object Format (EOF, 0xEF00) containers are not analysed".into())); + } + let mut warnings = Vec::new(); + let (end, metadata) = split_metadata(code); + let body = code.get(..end).unwrap_or(code); + let ins = sweep(body); + let jumpdests = ins.iter().filter(|i| i.op == 0x5b).count(); + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + let index_of = |off: usize| ins.binary_search_by_key(&off, |i| i.off).ok(); + + let extraction = selector_extraction(body, &ins); + let disp_start = extraction.map(|(_, k)| k).unwrap_or(0); + if extraction.is_none() { + warnings.push("no selector extraction (CALLDATALOAD then SHR/DIV/AND) was seen; matches below are less certain".into()); + } + + // Only a guard on the straight-line entry path can apply to every selector. + let callvalue_before = ins + .iter() + .take(disp_start) + .enumerate() + .take_while(|(_, i)| !matches!(i.op, 0x00 | 0x56 | 0x57 | 0xf3 | 0xfd | 0xfe | 0xff)) + .any(|(k, i)| i.op == 0x34 && rejects_value(body, &ins, k, &index_of)); + + let mut functions: Vec = Vec::new(); + let mut selectors = BTreeSet::new(); + let mut splits = 0usize; + let mut last_jumpi: Option = None; + let mut solc_like = 0usize; + let mut vyper_like = 0usize; + for k in disp_start..ins.len() { + let Some(i) = at(k) else { break }; + let n = push_len(i.op); + if !(1..=4).contains(&n) { + continue; + } + let Some(sel) = imm_u64(body, i) else { continue }; + let found = |dk: usize| -> Option { + let p = at(dk)?; + (is_push(p.op) && p.imm.1 <= 3 && op_at(dk + 1) == Some(0x57)).then_some(dk) + }; + // PUSH sel, [DUP2], EQ, PUSH dest, JUMPI + let eq_k = if op_at(k + 1) == Some(0x14) { + Some(k + 1) + } else if matches!(op_at(k + 1), Some(0x80..=0x8f)) && op_at(k + 2) == Some(0x14) { + Some(k + 2) + } else { + None + }; + let mut hit: Option<(usize, usize, &'static str)> = None; + if let Some(e) = eq_k { + if let Some(pk) = found(e + 1) + && let Some(dest) = at(pk).and_then(|p| imm_u64(body, p)) + { + hit = Some((usize::try_from(dest).unwrap_or(usize::MAX), pk + 1, "eq-jumpi")); + } else if n == 4 && op_at(e + 1) == Some(0x15) && found(e + 2).is_some() { + // Vyper-style: if selector != x jump to the next check; the body follows. + if let Some(next) = at(e + 4) { + hit = Some((next.off, e + 3, "eq-iszero-fallthrough")); + } + } + } else if n == 4 { + // Vyper also loads the selector from memory: PUSH sel, PUSH1 0, MLOAD, EQ, ISZERO … + let load = at(k + 1).is_some_and(|p| (p.op == 0x5f || is_push(p.op)) && imm_u64(body, p) == Some(0)); + if load + && op_at(k + 2) == Some(0x51) + && op_at(k + 3) == Some(0x14) + && op_at(k + 4) == Some(0x15) + && found(k + 5).is_some() + && let Some(next) = at(k + 7) + { + hit = Some((next.off, k + 6, "eq-iszero-fallthrough")); + } + let direct = matches!(op_at(k + 1), Some(0x10 | 0x11)) && found(k + 2).is_some(); + let via_dup = matches!(op_at(k + 1), Some(0x80..=0x8f)) && matches!(op_at(k + 2), Some(0x10 | 0x11)) && found(k + 3).is_some(); + if hit.is_none() && (direct || via_dup) { + splits += 1; + } + } + let Some((dest, jumpi_k, pattern)) = hit else { continue }; + if n < 4 && extraction.is_none() { + continue; + } + // Duplicate identities still advance the end of the recognized dispatcher. + // Otherwise the fallback scan starts inside a later comparison, not after it. + last_jumpi = Some(jumpi_k); + if !selectors.insert(sel) { + continue; + } + let selector = format!("0x{sel:08x}"); + if pattern == "eq-jumpi" { + solc_like += 1; + } else { + vyper_like += 1; + } + let di = index_of(dest); + let jumpdest_valid = pattern != "eq-jumpi" || di.and_then(at).is_some_and(|x| x.op == 0x5b); + let (mutability, reason) = if !jumpdest_valid { + ("unknown", "the destination is not a JUMPDEST".to_owned()) + } else if callvalue_before { + ("nonpayable", "a CALLVALUE check runs before the dispatcher, so every function refuses payments".to_string()) + } else { + match di { + Some(d) => payability(body, &ins, d, &index_of), + None => ("unknown", "the destination is not an instruction boundary".to_string()), + } + }; + functions.push(EvmFunction { + selector, + bytecode_offset: dest, + compare_offset: i.off, + dispatch: "abi", + pattern, + mutability, + mutability_reason: reason, + jumpdest_valid, + }); + if functions.len() >= MAX_FUNCTIONS { + warnings.push(format!("stopped at {MAX_FUNCTIONS} selectors")); + break; + } + } + if functions.iter().any(|f| !f.jumpdest_valid) { + warnings.push("some destinations are not JUMPDESTs; those matches may be data, not dispatch".into()); + } + + let (short_calldata, receive) = short_calldata_path(body, &ins, disp_start); + let mut fallback = "unknown"; + // At the selector cap the remaining dispatcher has not been scanned. + // Its next comparison is not evidence that a fallback body exists. + if let Some(j) = last_jumpi + && functions.len() < MAX_FUNCTIONS + && solc_like > 0 + { + fallback = if reverts_soon(body, &ins, j + 1, &index_of) { "absent" } else { "present" }; + } + let style = match (solc_like > 0, vyper_like > 0) { + (true, true) => "mixed", + (true, false) => "solc-like", + (false, true) => "vyper-like", + _ => "none", + }; + let listing_end = last_jumpi.map(|j| j + 8).unwrap_or(LISTING_CAP).min(LISTING_CAP); + let dispatcher_listing = ins + .iter() + .take(listing_end) + .map(|i| { + let d = imm(body, i); + if d.is_empty() && push_len(i.op) == 0 { + format!("{:#06x}: {}", i.off, mnemonic(i.op)) + } else { + format!("{:#06x}: {} {}", i.off, mnemonic(i.op), bytes_value(d)) + } + }) + .collect(); + if functions.is_empty() { + warnings.push( + "no selector dispatcher was recognised (the code may be creation code without runtime, a proxy, a library, or use a jump-table dispatcher)".into(), + ); + } + Ok(EvmInterface { + code_size: code.len(), + analysed_size: body.len(), + metadata, + instructions: ins.len(), + jumpdests, + selector_extraction: extraction.map(|(k, _)| k), + dispatcher_offset: extraction.and_then(|(_, k)| at(k)).map(|i| i.off), + style, + functions, + binary_search_splits: splits, + callvalue_check_before_dispatch: callvalue_before, + short_calldata_check: short_calldata, + fallback, + receive, + dispatcher_listing, + warnings, + }) +} + +/// Resolve the destination of a JUMP to an instruction index, when the PUSH right before it is +/// readable and lands on an instruction boundary. +fn jump_destination(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option) -> Option { + let push = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op))?; + index_of(usize::try_from(imm_u64(code, push)?).ok()?) +} + +/// Follow a function's entry for a few instructions (and up to two unconditional jumps) looking +/// for a CALLVALUE check. +fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) -> Option) -> (&'static str, String) { + let mut k = start; + let mut hops = 0; + for _ in 0..48 { + let Some(i) = ins.get(k) else { break }; + match i.op { + 0x34 if rejects_value(code, ins, k, index_of) => return ("nonpayable", format!("rejects nonzero CALLVALUE at {:#x}", i.off)), + 0x56 => match jump_destination(code, ins, k, index_of) { + Some(t) if hops < 2 && ins.get(t).is_some_and(|target| target.op == 0x5b) => { + hops += 1; + k = t; + continue; + } + _ => return ("unknown", "jumps somewhere we cannot follow before any CALLVALUE check".into()), + }, + 0x57 => return ("unknown", "branches before any CALLVALUE check".into()), + 0xfd | 0xfe => return ("unknown", "halts with an error before any CALLVALUE check".into()), + 0x00 | 0xf3 | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => { + return ("payable", format!("reaches {} at {:#x} without a CALLVALUE check", mnemonic(i.op), i.off)); + } + _ => {} + } + k += 1; + } + ("unknown", "no CALLVALUE check in the first instructions".into()) +} + +/// CALLVALUE only reads the payment. Recognize a direct test that sends the nonzero path +/// to a rejection, allowing the common DUP1 that preserves the original value for cleanup. +fn rejects_value(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option) -> bool { + let mut next = k + 1; + if ins.get(next).is_some_and(|i| i.op == 0x80) { + next += 1; + } + let jumps_when_zero = ins.get(next).is_some_and(|i| i.op == 0x15); + next += usize::from(jumps_when_zero); + let Some(push) = ins.get(next).filter(|i| is_push(i.op)) else { return false }; + if ins.get(next + 1).is_none_or(|i| i.op != 0x57) { + return false; + } + let Some(target) = imm_u64(code, push).and_then(|v| usize::try_from(v).ok()).and_then(index_of) else { return false }; + if ins.get(target).is_none_or(|i| i.op != 0x5b) { + return false; + } + reverts_soon(code, ins, if jumps_when_zero { next + 2 } else { target }, index_of) +} + +fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) -> Option) -> bool { + let mut hops = 0; + for _ in 0..12 { + let Some(i) = ins.get(k) else { return false }; + match i.op { + 0xfd | 0xfe => return true, + 0x56 => match jump_destination(code, ins, k, index_of) { + Some(t) if hops < 2 => { + hops += 1; + k = t; + continue; + } + _ => return false, + }, + 0x5b | 0x50 | 0x80..=0x9f | 0x5f | 0x60..=0x7f => {} + _ => return false, + } + k += 1; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::formats as fx; + + #[test] + fn hex_signs_are_not_hex_digits() { + let solc = |v: &str| { + let mut b = vec![0xa1, 0x64]; + b.extend(b"solc"); + b.push(0x60 + v.len() as u8); + b.extend(v.as_bytes()); + cbor_item(&b, &mut 0, 0).unwrap()["solc"].clone() + }; + assert_eq!(solc("0x+1+2+3"), "0x+1+2+3"); + assert_eq!(solc("0x000008"), "0.0.8"); + assert!(hex_decode("+f").is_empty()); + assert_eq!(hex_decode("0f"), vec![15]); + } + + /// A plausible trailer length alone must not remove instructions from the analyzed bytecode. + #[test] + fn incomplete_cbor_must_not_shorten_the_analyzed_contract() { + // A nested array declares 65 integers but supplies just 64. The top-level map + // and its length suffix otherwise look complete. + let mut short = vec![0xa1, 0x61, b'x', 0x98, 65]; + short.extend([0; 64]); + let mut short_map = vec![0xa1, 0x61, b'x', 0xb8, 33]; + for key in 0..32 { + short_map.extend([0x18, key, 0]); + } + for cbor in [short, short_map, vec![0xa1, 0x61, b'x', 0x61, 0xff]] { + let mut code = vec![0x00]; + code.extend(&cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + assert!(split_metadata(&code).1.is_none()); + assert_eq!(analyze(&code).unwrap().analysed_size, code.len()); + } + } + + #[test] + fn dispatcher_selectors_and_metadata() { + let (code, dests) = fx::evm_runtime(); + let r = analyze(&code).unwrap(); + assert_eq!(r.selector_extraction, Some("shr-224")); + assert_eq!(r.style, "solc-like"); + let sels: Vec<_> = r.functions.iter().map(|f| f.selector.clone()).collect(); + assert_eq!(sels, fx::EVM_SELECTORS.iter().map(|s| format!("0x{s:08x}")).collect::>()); + for (f, d) in r.functions.iter().zip(dests) { + assert_eq!(f.bytecode_offset, d); + assert!(f.jumpdest_valid); + } + assert_eq!(r.functions[0].mutability, "nonpayable"); + assert_eq!(r.functions[1].mutability, "nonpayable"); + assert_eq!(r.functions[2].mutability, "payable"); + assert!(r.short_calldata_check); + assert_eq!(r.fallback, "absent"); + let m = r.metadata.unwrap(); + assert_eq!(m.compiler.as_deref(), Some("solc 0.8.19")); + assert!(m.ipfs.unwrap().starts_with("Qm")); + assert_eq!(r.analysed_size + m.length, code.len()); + } + + #[test] + fn hex_input_rules() { + let (code, _) = fx::evm_runtime(); + let hex = fx::to_hex(&code); + assert_eq!(decode_input(format!(" {hex}\n").as_bytes(), Encoding::Auto).unwrap(), (code.clone(), "hex")); + assert_eq!(decode_input(&code, Encoding::Auto).unwrap().1, "raw"); + assert!(decode_input(b"0x123", Encoding::Hex).is_err()); + assert!(decode_input(b"0xzz", Encoding::Hex).is_err()); + assert!(decode_input(b"", Encoding::Hex).is_err()); + assert!(matches!(analyze(&[0xef, 0x00, 0x01]), Err(FormatError::Unsupported(_)))); + assert_eq!(base58(&[0, 0, 1]), "112"); + } + + #[test] + fn vyper_style_fallthrough() { + // PUSH1 0 CALLDATALOAD PUSH1 0xe0 SHR PUSH1 0 MSTORE PUSH4 sel PUSH1 0 MLOAD EQ ISZERO PUSH2 next JUMPI + let mut c = vec![ + 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c, 0x60, 0x00, 0x52, 0x63, 0x12, 0x34, 0x56, 0x78, 0x60, 0x00, 0x51, 0x14, 0x15, 0x61, 0x00, 0x20, 0x57, + ]; + let body = c.len(); + c.extend_from_slice(&[0x34, 0x15, 0x00]); + let r = analyze(&c).unwrap(); + assert_eq!(r.style, "vyper-like"); + assert_eq!(r.functions[0].selector, "0x12345678"); + assert_eq!(r.functions[0].bytecode_offset, body); + assert_eq!(r.functions[0].mutability, "payable", "ISZERO followed by STOP never rejects payment"); + } + + #[test] + fn nonpayable_needs_a_rejecting_nonzero_branch() { + fn dispatch(prefix: &[u8]) -> EvmInterface { + let mut code = prefix.to_vec(); + code.extend([0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x63, 1, 2, 3, 4, 0x14, 0x60]); + code.extend([(code.len() + 3) as u8, 0x57, 0x00, 0x5b, 0x00]); + analyze(&code).unwrap() + } + let read_only = dispatch(&[0x34, 0x50]); // CALLVALUE POP + assert!(!read_only.callvalue_check_before_dispatch); + assert_eq!(read_only.functions[0].mutability, "payable"); + let guard = dispatch(&[0x34, 0x80, 0x15, 0x60, 9, 0x57, 0x5f, 0x80, 0xfd, 0x5b, 0x50]); + assert!(guard.callvalue_check_before_dispatch); + assert_eq!(guard.functions[0].mutability, "nonpayable"); + // The other common form jumps to REVERT for a nonzero value and otherwise skips it. + let direct = dispatch(&[0x34, 0x60, 7, 0x57, 0x60, 11, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(direct.callvalue_check_before_dispatch); + // Reversing that conditional rejects zero-value calls, not payments. + let reversed = dispatch(&[0x34, 0x15, 0x60, 8, 0x57, 0x60, 12, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(!reversed.callvalue_check_before_dispatch); + // An unconditional jump bypasses the otherwise valid guard before the dispatcher. + let bypassed = dispatch(&[0x60, 12, 0x56, 0x34, 0x80, 0x15, 0x60, 12, 0x57, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(!bypassed.callvalue_check_before_dispatch); + } + + #[test] + fn hostile_inputs_do_not_panic() { + let (code, _) = fx::evm_runtime(); + for m in crate::test_support::mutations(&code) { + let _ = analyze(&m); + } + for n in 0..code.len() { + let _ = analyze(&code[..n]); + } + for seed in 0..200 { + let n = crate::test_support::noise(seed, 300); + let _ = analyze(&n); + let _ = decode_input(&n, Encoding::Auto); + } + // A metadata length that claims everything, and nested CBOR. + let _ = analyze(&[0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0x00, 0x07]); + let _ = analyze(&[0x7f; 40]); + } +} diff --git a/crates/evm/src/test_support.rs b/crates/evm/src/test_support.rs new file mode 100644 index 0000000000..0dc9861ef5 --- /dev/null +++ b/crates/evm/src/test_support.rs @@ -0,0 +1,63 @@ +pub mod formats { + pub const EVM_SELECTORS: [u32; 3] = [0xa905_9cbb, 0x70a0_8231, 0xd0e3_0db0]; + + /// Runtime bytecode with a compiler-style dispatcher, a fallback that reverts, two non-payable + /// functions (CALLVALUE check), one payable function, and a CBOR metadata tail (ipfs + solc 0.8.19). + /// Returns (bytecode, jump destinations of the three functions). + pub fn evm_runtime() -> (Vec, [usize; 3]) { + let mut c: Vec = vec![0x60, 0x80, 0x60, 0x40, 0x52]; + // if calldatasize < 4 goto fallback + c.extend_from_slice(&[0x60, 0x04, 0x36, 0x10, 0x61, 0, 0]); + let fb_patch = c.len() - 2; + c.push(0x57); + c.extend_from_slice(&[0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c]); + let mut patches = Vec::new(); + for sel in EVM_SELECTORS { + c.push(0x80); + c.push(0x63); + c.extend_from_slice(&sel.to_be_bytes()); + c.extend_from_slice(&[0x14, 0x61, 0, 0]); + patches.push(c.len() - 2); + c.push(0x57); + } + let fallback = c.len(); + c.extend_from_slice(&[0x5b, 0x60, 0x00, 0x80, 0xfd]); + let mut dests = [0usize; 3]; + for (i, dest) in dests.iter_mut().enumerate() { + *dest = c.len(); + if i < 2 { + // JUMPDEST CALLVALUE DUP1 ISZERO PUSH2 ok JUMPI PUSH1 0 DUP1 REVERT JUMPDEST POP STOP + c.extend_from_slice(&[0x5b, 0x34, 0x80, 0x15, 0x61, 0, 0]); + let ok_patch = c.len() - 2; + c.extend_from_slice(&[0x57, 0x60, 0x00, 0x80, 0xfd]); + let ok = c.len(); + c.extend_from_slice(&[0x5b, 0x50, 0x00]); + c[ok_patch..ok_patch + 2].copy_from_slice(&(ok as u16).to_be_bytes()); + } else { + c.extend_from_slice(&[0x5b, 0x60, 0x01, 0x60, 0x00, 0x55, 0x00]); + } + } + c[fb_patch..fb_patch + 2].copy_from_slice(&(fallback as u16).to_be_bytes()); + for (p, d) in patches.iter().zip(dests) { + c[*p..*p + 2].copy_from_slice(&(d as u16).to_be_bytes()); + } + c.push(0xfe); + let mut meta = vec![0xa2, 0x64, b'i', b'p', b'f', b's', 0x58, 0x22, 0x12, 0x20]; + meta.extend((0..32u8).map(|i| i.wrapping_mul(7))); + meta.extend_from_slice(&[0x64, b's', b'o', b'l', b'c', 0x43, 0x00, 0x08, 0x13]); + let len = meta.len() as u16; + c.extend_from_slice(&meta); + c.extend_from_slice(&len.to_be_bytes()); + (c, dests) + } + + /// Bytecode as `0x`-prefixed lowercase hex. + pub fn to_hex(b: &[u8]) -> String { + let mut s = String::from("0x"); + for x in b { + s.push_str(&format!("{x:02x}")); + } + s + } +} +pub use craft_testkit::sample_damage::{mutations, noise}; diff --git a/crates/evm/tests/evm_metadata_arrays.rs b/crates/evm/tests/evm_metadata_arrays.rs new file mode 100644 index 0000000000..ceeda5c072 --- /dev/null +++ b/crates/evm/tests/evm_metadata_arrays.rs @@ -0,0 +1,39 @@ +use craft_evm as evm; +use serde_json::json; + +/// Unrelated three-integer arrays stay arrays while compiler versions stay readable. +#[test] +fn cbor_arrays_are_not_all_compiler_versions() { + // {"sizes": [1, 2, 3], "vyper": [0, 3, 10]} + for (cbor, compiler) in [ + (b"\xa2\x65sizes\x83\x01\x02\x03\x65vyper\x83\x00\x03\x0a".as_slice(), "vyper 0.3.10"), + (b"\xa2\x65sizes\x83\x01\x02\x03\x64solc\x83\x00\x08\x13".as_slice(), "solc 0.8.19"), + ] { + let mut code = vec![0x00]; + code.extend(cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + let result = evm::analyze(&code).unwrap(); + let meta = result.metadata.unwrap(); + assert_eq!(meta.entries["sizes"], json!([1, 2, 3])); + assert_eq!(meta.compiler.as_deref(), Some(compiler)); + assert_eq!(result.analysed_size, 1); + } +} + +/// A non-version Vyper array stays typed, and a truncated array stays bytecode. +#[test] +fn invalid_version_shapes_are_not_invented_or_silently_consumed() { + let cbor = b"\xa1\x65vyper\x82\x00\x03"; + let mut code = vec![0x00]; + code.extend(cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + let meta = evm::analyze(&code).unwrap().metadata.unwrap(); + assert_eq!(meta.compiler, None); + assert_eq!(meta.entries["vyper"], json!([0, 3])); + + let mut truncated = code; + truncated[8] = 0x83; // Declare three items but keep only two. + let result = evm::analyze(&truncated).unwrap(); + assert!(result.metadata.is_none()); + assert_eq!(result.analysed_size, truncated.len()); +} diff --git a/crates/evm/tests/evm_metadata_map_keys.rs b/crates/evm/tests/evm_metadata_map_keys.rs new file mode 100644 index 0000000000..17ee4822ca --- /dev/null +++ b/crates/evm/tests/evm_metadata_map_keys.rs @@ -0,0 +1,93 @@ +use craft_evm::analyze; + +fn contract_with_trailer(cbor: &[u8]) -> Vec { + let mut code = vec![0x5b, 0x00]; + code.extend_from_slice(cbor); + code.extend_from_slice(&u16::try_from(cbor.len()).unwrap().to_be_bytes()); + code +} + +fn assert_unrecognized(cbor: &[u8]) { + let code = contract_with_trailer(cbor); + let result = analyze(&code).unwrap(); + assert!(result.metadata.is_none(), "ambiguous map must remain bytecode: {cbor:02x?}"); + assert_eq!(result.analysed_size, code.len()); +} + +#[test] +fn duplicate_compiler_keys_do_not_replace_the_reported_version() { + assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x1a"); +} + +#[test] +fn identical_duplicate_keys_are_also_ambiguous() { + assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x13"); +} + +#[test] +fn numeric_keys_cannot_collide_with_text_keys() { + assert_unrecognized(b"\xa2\x01\x00\x61\x31\x01"); +} + +#[test] +fn metadata_map_keys_must_be_encoded_as_text() { + for key in [vec![0x01], vec![0x41, b'x'], vec![0x83, 0, 1, 2], vec![0xf5], vec![0xf6], vec![0xa0]] { + let mut cbor = vec![0xa1]; + cbor.extend(key); + cbor.push(0); + assert_unrecognized(&cbor); + } +} + +#[test] +fn nested_maps_do_not_silently_overwrite_keys() { + assert_unrecognized(b"\xa1\x65extra\xa2\x61x\x00\x61x\x01"); + assert_unrecognized(b"\xa1\x65extra\xa1\x01\x00"); +} + +#[test] +fn ordinary_compiler_metadata_and_unique_nested_text_keys_still_decode() { + let code = contract_with_trailer(b"\xa2\x64solc\x43\x00\x08\x13\x65extra\xa2\x61x\x00\x61y\x01"); + let result = analyze(&code).unwrap(); + assert_eq!(result.analysed_size, 2); + let metadata = result.metadata.unwrap(); + assert_eq!(metadata.compiler.as_deref(), Some("solc 0.8.19")); + assert_eq!(metadata.entries["extra"]["x"], 0); + assert_eq!(metadata.entries["extra"]["y"], 1); + assert_eq!(metadata.length, code.len() - 2); +} + +#[test] +fn equal_keys_in_separate_maps_are_independent() { + let code = contract_with_trailer(b"\xa2\x61a\xa1\x61x\x00\x61b\xa1\x61x\x01"); + let result = analyze(&code).unwrap(); + assert_eq!(result.analysed_size, 2); + let entries = result.metadata.unwrap().entries; + assert_eq!(entries["a"]["x"], 0); + assert_eq!(entries["b"]["x"], 1); +} + +#[test] +fn extended_length_metadata_maps_respect_the_pair_limit() { + let map = |count: u8| { + let mut cbor = vec![0xb8, count]; + for index in 0..count { + let key = format!("k{index:02}"); + cbor.push(0x63); + cbor.extend_from_slice(key.as_bytes()); + cbor.push(0); + } + cbor + }; + for count in [24, 32] { + let code = contract_with_trailer(&map(count)); + let report = analyze(&code).unwrap(); + assert_eq!(report.analysed_size, 2); + assert_eq!(report.metadata.unwrap().entries.as_object().unwrap().len(), usize::from(count)); + } + assert_unrecognized(&map(33)); + assert_unrecognized(&[0xb8]); + let mut truncated = map(24); + truncated.pop(); + assert_unrecognized(&truncated); +} diff --git a/crates/evm/tests/evm_selector_dedup.rs b/crates/evm/tests/evm_selector_dedup.rs new file mode 100644 index 0000000000..99aac44ba6 --- /dev/null +++ b/crates/evm/tests/evm_selector_dedup.rs @@ -0,0 +1,115 @@ +use craft_evm as evm; + +fn prefix() -> Vec { + vec![0x5b, 0x00, 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c] +} + +fn comparison(code: &mut Vec, selector: u32, width: usize, destination: u8) { + code.push(0x5f + u8::try_from(width).unwrap()); + code.extend_from_slice(&selector.to_be_bytes()[4 - width..]); + code.extend([0x14, 0x60, destination, 0x57]); +} + +#[test] +fn repeated_comparisons_keep_the_first_destination_and_encounter_order() { + let mut code = prefix(); + comparison(&mut code, 0xfeed0002, 4, 0); + comparison(&mut code, 0xfeed0001, 4, 0); + let expected = evm::analyze(&code).unwrap().functions; + for _ in 0..2000 { + comparison(&mut code, 0xfeed0001, 4, 1); + comparison(&mut code, 0xfeed0002, 4, 1); + } + assert_eq!(evm::analyze(&code).unwrap().functions, expected); +} + +#[test] +fn different_push_widths_share_the_same_numeric_selector() { + let mut code = prefix(); + for width in 1..=4 { + comparison(&mut code, 17, width, if width == 1 { 0 } else { 1 }); + } + let result = evm::analyze(&code).unwrap(); + assert_eq!(result.functions.len(), 1); + assert_eq!(result.functions[0].selector, "0x00000011"); + assert_eq!(result.functions[0].bytecode_offset, 0); +} + +#[test] +fn rejected_candidates_do_not_spend_selector_identity() { + let mut code = vec![0x5b, 0x00]; + // Short comparisons without selector extraction are not considered functions. + comparison(&mut code, 17, 1, 1); + // A selector-shaped immediate without a comparison is not a function either. + code.extend([0x63, 0, 0, 0, 17, 0x50]); + comparison(&mut code, 17, 4, 0); + let result = evm::analyze(&code).unwrap(); + assert_eq!(result.functions.len(), 1); + assert_eq!(result.functions[0].bytecode_offset, 0); + assert!(result.functions[0].jumpdest_valid); +} + +#[test] +fn selector_cap_counts_unique_matches() { + let mut code = prefix(); + for selector in 0..4095 { + comparison(&mut code, selector, 4, 0); + } + for _ in 0..10000 { + comparison(&mut code, 4094, 4, 1); + } + let below = evm::analyze(&code).unwrap(); + assert_eq!(below.functions.len(), 4095); + assert!(!below.warnings.iter().any(|warning| warning.contains("stopped at"))); + comparison(&mut code, 4095, 4, 0); + comparison(&mut code, 4096, 4, 0); + let capped = evm::analyze(&code).unwrap(); + assert_eq!(capped.functions.len(), 4096); + assert_eq!(capped.functions.last().unwrap().selector, "0x00000fff"); + assert!(capped.warnings.iter().any(|warning| warning == "stopped at 4096 selectors")); +} + +#[test] +fn repeated_comparisons_keep_fallback_scan_after_the_last_dispatch() { + for (ending, expected) in [(&[0x5f, 0x5f, 0xfd][..], "absent"), (&[0x00][..], "present")] { + let mut code = prefix(); + comparison(&mut code, 0xfeed0001, 4, 0); + comparison(&mut code, 0xfeed0001, 4, 1); + code.extend_from_slice(ending); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 1); + assert_eq!(report.functions[0].bytecode_offset, 0); + assert_eq!(report.fallback, expected); + } +} + +#[test] +fn selector_cap_leaves_fallback_unknown() { + for ending in [&[0x5f, 0x5f, 0xfd][..], &[0x00][..]] { + let mut code = prefix(); + for selector in 0..4097 { + comparison(&mut code, selector, 4, 0); + } + code.extend_from_slice(ending); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 4096); + assert_eq!(report.fallback, "unknown"); + } +} + +#[test] +fn payability_only_follows_jumps_to_jumpdest() { + for (target, expected) in [(&[0x5b, 0x00][..], "payable"), (&[0x00][..], "unknown")] { + let mut code = prefix(); + let entry = u8::try_from(code.len() + 10).unwrap(); + comparison(&mut code, 0xfeed0001, 4, entry); + code.push(0x00); + assert_eq!(code.len(), usize::from(entry)); + code.extend([0x5b, 0x60, entry + 4, 0x56]); + code.extend_from_slice(target); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 1); + assert!(report.functions[0].jumpdest_valid); + assert_eq!(report.functions[0].mutability, expected); + } +} diff --git a/crates/flags/src/lib.rs b/crates/flags/src/lib.rs index c65e9218ff..8552bab2c3 100644 --- a/crates/flags/src/lib.rs +++ b/crates/flags/src/lib.rs @@ -38,7 +38,7 @@ use std::collections::BTreeMap; use std::path::PathBuf; #[cfg(not(target_arch = "wasm32"))] -mod store; +pub(crate) mod store; #[cfg(not(target_arch = "wasm32"))] pub use store::{FlagError, load, set}; @@ -135,6 +135,11 @@ impl Flags { } fn read_file(&mut self, text: &str) { + // The same limit as a file read from disk, also for text handed in directly. + if text.len() as u64 > MAX_FILE_BYTES { + self.problems.push(format!("the flags file is larger than {MAX_FILE_BYTES} bytes, so every flag is at its default")); + return; + } let doc = match text.parse::() { Ok(d) => d, Err(e) => { diff --git a/crates/flags/src/store.rs b/crates/flags/src/store.rs index a601d8731a..6f422aa09b 100644 --- a/crates/flags/src/store.rs +++ b/crates/flags/src/store.rs @@ -1,9 +1,10 @@ //! Reading and changing the flags file (desktop only). use std::fmt; -use std::path::Path; +use std::io::Read; +use std::path::{Path, PathBuf}; -use crate::{ENV, Flags, MAX_FILE_BYTES, default_path, valid_id}; +use crate::{ENV, FILE_ENV, Flags, MAX_FILE_BYTES, default_path, valid_id}; /// Why a flag could not be changed. #[derive(Debug)] @@ -32,32 +33,47 @@ impl std::error::Error for FlagError {} /// The file's text, `None` when it does not exist. A file that isn't a regular file, is too big /// or isn't UTF-8 is an error. fn read_text(path: &Path) -> Result, FlagError> { - let meta = match std::fs::metadata(path) { - Ok(m) => m, + let file = match std::fs::File::open(path) { + Ok(f) => f, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(FlagError::Io(e)), }; + let meta = file.metadata().map_err(FlagError::Io)?; if !meta.is_file() { return Err(FlagError::Unreadable(format!("{} is not a regular file", path.display()))); } - if meta.len() > MAX_FILE_BYTES { + // Read at most one byte past the limit from the file opened: one that grew or was replaced + // after a size check can't bring more. + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes).map_err(FlagError::Io)?; + if bytes.len() as u64 > MAX_FILE_BYTES { return Err(FlagError::Unreadable(format!("{} is larger than {MAX_FILE_BYTES} bytes", path.display()))); } - let bytes = std::fs::read(path).map_err(FlagError::Io)?; String::from_utf8(bytes).map(Some).map_err(|_| FlagError::Unreadable(format!("{} is not UTF-8 text", path.display()))) } /// The flags of this run: [`default_path`] and `CRAFT_FLAGS`. Never fails; what could not be /// read is in [`Flags::problems`]. pub fn load() -> Flags { - let env = std::env::var(ENV).ok(); - let Some(path) = default_path() else { - return Flags::from_parts(None, env.as_deref()); + let named = std::env::var_os(FILE_ENV).is_some_and(|p| !p.is_empty()); + load_from(default_path(), named, std::env::var(ENV).ok().as_deref()) +} + +/// [`load`] from `path`; `named` when `CRAFT_FLAGS_FILE` chose it, so a missing file is worth a +/// word (the usual file not existing yet is not). +pub(crate) fn load_from(path: Option, named: bool, env: Option<&str>) -> Flags { + let Some(path) = path else { + return Flags::from_parts(None, env); }; match read_text(&path) { - Ok(text) => Flags::from_parts(text.as_deref(), env.as_deref()), + Ok(None) if named => { + let mut flags = Flags::from_parts(None, env); + flags.problems.insert(0, format!("{}, named by {FILE_ENV}, does not exist; every flag is at its default", path.display())); + flags + } + Ok(text) => Flags::from_parts(text.as_deref(), env), Err(e) => { - let mut flags = Flags::from_parts(None, env.as_deref()); + let mut flags = Flags::from_parts(None, env); flags.problems.insert(0, format!("{}: {e}; every flag is at its default", path.display())); flags } @@ -65,11 +81,21 @@ pub fn load() -> Flags { } /// Turn the flag `id` on or off in the file at `path` (made if missing). Everything else in the -/// file, comments included, is kept; the write is atomic. +/// file, comments included, is kept; the write is atomic. Two programs changing flags at once +/// (the launcher and an app) take turns, so neither change is lost. pub fn set(path: &Path, id: &str, on: bool) -> Result<(), FlagError> { if !valid_id(id) { return Err(FlagError::BadId(id.to_string())); } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(FlagError::Io)?; + } + // A lock file beside the flags file, which itself is replaced on every write. Released when + // `_lock` is dropped (and by the system if the process ends). + let mut lock_path = path.as_os_str().to_owned(); + lock_path.push(".lock"); + let _lock = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(PathBuf::from(lock_path)).map_err(FlagError::Io)?; + _lock.lock().map_err(FlagError::Io)?; let mut doc = match read_text(path)? { Some(text) => text.parse::().map_err(|e| FlagError::Unreadable(e.to_string()))?, None => toml_edit::DocumentMut::new(), @@ -78,9 +104,16 @@ pub fn set(path: &Path, id: &str, on: bool) -> Result<(), FlagError> { let Some(table) = item.as_table_like_mut() else { return Err(FlagError::Unreadable("`flags` is not a table".into())); }; - table.insert(id, toml_edit::value(on)); - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir).map_err(FlagError::Io)?; + // Keep what surrounds the old value, such as a comment after it. + let mut value = toml_edit::Value::from(on); + if let Some(old) = table.get(id).and_then(toml_edit::Item::as_value) { + *value.decor_mut() = old.decor().clone(); } - craft_atomic::atomic_write(path, doc.to_string().as_bytes()).map_err(FlagError::Io) + table.insert(id, toml_edit::Item::Value(value)); + let text = doc.to_string(); + // What can't be read back is not written: the file stays as it was. + if text.len() as u64 > MAX_FILE_BYTES { + return Err(FlagError::Unreadable(format!("the flags file would grow past {MAX_FILE_BYTES} bytes"))); + } + craft_atomic::atomic_write(path, text.as_bytes()).map_err(FlagError::Io) } diff --git a/crates/flags/src/tests.rs b/crates/flags/src/tests.rs index 3f4bef6670..66c00855b1 100644 --- a/crates/flags/src/tests.rs +++ b/crates/flags/src/tests.rs @@ -48,6 +48,15 @@ fn bad_entries_are_reported_and_left_out_never_fatal() { assert!(!Flags::from_parts(Some("flags = 3"), None).problems.is_empty()); } +#[test] +fn oversized_text_is_not_read() { + let mut text = String::from("[flags]\nAI-MCP = true\n"); + text.push_str(&"#".repeat(MAX_FILE_BYTES as usize)); + let flags = Flags::from_parts(Some(&text), None); + assert!(!flags.enabled(&AI_MCP)); + assert!(flags.problems.iter().any(|p| p.contains("larger than"))); +} + #[test] fn many_entries_are_capped() { let mut text = String::from("[flags]\n"); @@ -79,6 +88,7 @@ fn ids_are_checked() { #[cfg(not(target_arch = "wasm32"))] mod file { use super::super::*; + use crate::store; #[test] fn set_creates_the_file_and_keeps_what_else_is_in_it() { @@ -98,6 +108,58 @@ mod file { assert!(flags.enabled(&AI_MODELS)); } + #[test] + fn set_keeps_the_comment_after_a_flag() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + std::fs::write(&path, "[flags]\nAI-MCP = true # on for testing\n").unwrap(); + set(&path, "AI-MCP", false).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("AI-MCP = false # on for testing"), "{text}"); + } + + #[test] + fn set_refuses_to_write_what_could_not_be_read_back() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + // Readable (just under the limit), so the refusal comes from the size of what `set` would + // write, not from reading. + let mut text = String::from("[flags]\n# "); + let pad = MAX_FILE_BYTES as usize - 4 - text.len(); + text.push_str(&"x".repeat(pad)); + assert_eq!(text.len() as u64, MAX_FILE_BYTES - 4); + std::fs::write(&path, &text).unwrap(); + assert!(Flags::from_parts(Some(&text), None).problems.is_empty(), "the fixture itself reads"); + assert!(matches!(set(&path, "AI-MODELS", true), Err(FlagError::Unreadable(e)) if e.contains("would grow"))); + assert_eq!(std::fs::read_to_string(&path).unwrap(), text, "left as it was"); + } + + #[test] + fn a_missing_file_is_mentioned_only_when_named() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("nope.toml"); + let named = store::load_from(Some(missing.clone()), true, None); + assert!(named.problems.iter().any(|p| p.contains("does not exist")), "{:?}", named.problems); + assert!(store::load_from(Some(missing), false, None).problems.is_empty(), "the usual file not existing yet is normal"); + } + + #[test] + fn two_writers_keep_both_changes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + let ids: Vec = (0..8).map(|i| format!("F{i}")).collect(); + std::thread::scope(|s| { + for id in &ids { + let path = &path; + s.spawn(move || set(path, id, true).unwrap()); + } + }); + let flags = Flags::from_parts(Some(&std::fs::read_to_string(&path).unwrap()), None); + for id in &ids { + assert!(flags.enabled_id(id), "{id} lost"); + } + } + #[test] fn set_never_overwrites_a_file_it_cannot_read() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index e3e9152017..b167779e76 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1114,6 +1114,9 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa // Word. Only Repeat as header row makes it one then. let header = r.props.header || (ri == 0 && style.is_some() && t.props.look.header_row && t.rows.len() > 1); let mut cells = Vec::new(); + for _ in 0..r.first_grid() { + cells.push(Cell::default()); + } for (ci, c) in r.cells.iter().enumerate() { let styled = if bake { styled_cell(t, style.as_ref(), (ri, ci), ncols) } else { None }; let mut rowspan = 1; @@ -1159,6 +1162,8 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa Some(Box::new(crate::CellPic { img, repeat: p.repeat, align: p.align })) }), width: None, + vmerge_restart: c.props.vmerge == VMerge::Restart, + synthetic_covered: false, }); } rows.push(cells); diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 0375c448c2..3d27d521f3 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -284,6 +284,18 @@ impl<'a> Builder<'a> { /// `cp` as a run may keep it: without its link and font once the runs' copies of them are /// over budget. + /// A run's properties with its tracked insertion, deletion and formatting change. + fn tracked_props(&mut self, f: &Fmt) -> CharProps { + let mut cp = self.budget(char_props(f)); + cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); + cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); + if let Some(c) = &f.fmt_change { + let old = self.budget(char_props(&c.old)); + cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); + } + cp + } + fn budget(&mut self, mut cp: CharProps) -> CharProps { let n = cp.link.as_ref().map_or(0, String::len).saturating_add(cp.font.as_ref().map_or(0, String::len)); match self.run_strings.checked_add(n).filter(|&t| t <= MAX_RUN_STRINGS) { @@ -553,13 +565,7 @@ impl<'a> Builder<'a> { match i { Inline::Text(t, f) => { let t = clean_text(t); - let mut cp = self.budget(char_props(f)); - cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); - cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); - if let Some(c) = &f.fmt_change { - let old = self.budget(char_props(&c.old)); - cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); - } + let mut cp = self.tracked_props(f); if p.kind == Kind::Code { // Code's font comes from its style, before a change as after it. if cp.font.as_deref() == Some(MONO_FONT) { @@ -633,7 +639,8 @@ impl<'a> Builder<'a> { } } Inline::Field { instr, result, fmt, locked } => { - let cp = self.budget(char_props(fmt)); + // A field inserted or deleted with tracked changes keeps them (RTF `\chpgn`). + let cp = self.tracked_props(fmt); let (instr, result) = (clean_text(instr), clean_text(result)); if instr.trim().is_empty() { append(&mut out, &result, &cp, None); @@ -907,6 +914,41 @@ impl<'a> Builder<'a> { } tb.rows.push(row); } + let starts: Vec<(usize, usize)> = (0..tb.rows.first().map_or(0, |row| row.cells.len())) + .filter(|&ci| tb.rows.first().and_then(|row| row.cells.get(ci)).is_some_and(|c| c.props.vmerge == VMerge::Continue)) + .map(|ci| (ci, tb.grid_col(0, ci))) + .collect(); + for (ci, g) in starts { + let span = tb.rows.first().map_or(1, |r| r.cells[ci].props.span); + let more = tb + .cell_at_grid(1, g) + .filter(|&i| tb.grid_col(1, i) == g) + .and_then(|i| tb.rows.get(1)?.cells.get(i)) + .is_some_and(|c| c.props.vmerge == VMerge::Continue && c.props.span == span); + if let Some(cell) = tb.rows.first_mut().and_then(|r| r.cells.get_mut(ci)) { + cell.props.vmerge = if more { VMerge::Restart } else { VMerge::None }; + } + } + for r in 1..tb.rows.len() { + for ci in 0..tb.rows[r].cells.len() { + if tb.rows[r].cells[ci].props.vmerge == VMerge::Continue { + let g = tb.grid_col(r, ci); + let span = tb.rows[r].cells[ci].props.span; + let prev_r = r - 1; + if let Some(up_ci) = tb.cell_at_grid(prev_r, g) + && tb.grid_col(prev_r, up_ci) == g + && tb.rows[prev_r].cells[up_ci].props.span == span + { + let up_cell = &mut tb.rows[prev_r].cells[up_ci]; + if up_cell.props.vmerge == VMerge::None { + up_cell.props.vmerge = VMerge::Restart; + } + } else { + tb.rows[r].cells[ci].props.vmerge = VMerge::None; + } + } + } + } // Its markup kept for the writer, by its place among the top's tables. if depth == 0 { if t.kept.is_some() || t.wrap.is_some() { diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index d5abb75375..fcd955a30b 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -881,6 +881,10 @@ pub struct Cell { /// The width, points, the source gives a cell spanning one column (HTML): see /// [`FTable::widths_from_cells`]. pub width: Option, + /// Whether the source explicitly started a vertical merge (`mso-yfti-vmerge:restart`). + pub vmerge_restart: bool, + /// Whether this covered placeholder was synthesized by [`FTable::insert_covered`]. + pub synthetic_covered: bool, } /// A cell's background picture: the picture at its own size, how it fills the cell, and where an @@ -907,6 +911,8 @@ impl Default for Cell { direction: Default::default(), picture: None, width: None, + vmerge_restart: false, + synthetic_covered: false, } } } @@ -999,8 +1005,8 @@ impl FTable { let mut g = 0usize; let mut ci = 0usize; while let Some(c) = self.rows.get(r).and_then(|row| row.get(ci)) { - let (span, rs, covered) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.covered); - if rs > 1 && !covered { + let (span, rs, vmerge_restart) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.vmerge_restart); + if rs > 1 { for k in 1..rs { work += 1; if work > MAX_COVERED_WORK { @@ -1017,8 +1023,14 @@ impl FTable { } x += cc.colspan.clamp(1, 63) as usize; } + if at < row.len() && x == g && row[at].covered && (vmerge_restart || row[at].synthetic_covered) { + // Row already has a matching explicit continuation (when this cell had + // `mso-yfti-vmerge:restart`) or a synthetic placeholder from an earlier + // row. Avoid adding a duplicate covered cell which would make the row ragged. + continue; + } if row.len() < 64 { - row.insert(at, Cell { colspan: span as u32, covered: true, ..Default::default() }); + row.insert(at, Cell { colspan: span as u32, covered: true, synthetic_covered: true, ..Default::default() }); } } } diff --git a/crates/har/Cargo.toml b/crates/har/Cargo.toml new file mode 100644 index 0000000000..c9a1b9f0b4 --- /dev/null +++ b/crates/har/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-har" +description = "Typed HTTP Archive capture reader with explicit input admission" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/har/src/lib.rs b/crates/har/src/lib.rs new file mode 100644 index 0000000000..8f8fba2cb8 --- /dev/null +++ b/crates/har/src/lib.rs @@ -0,0 +1,230 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! HTTP Archive (HAR 1.2) captures, read into typed records. No redaction happens here; callers +//! decide what to keep. Capture headers and bodies can contain secrets: redact before display or sharing. +//! `parse` preserves compatibility and parses the whole JSON before limiting returned entries. +//! Use `parse_bounded` to cap admitted bytes; this is not a precise allocator or output-byte limit. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HarError { + #[error("not valid JSON: {0}")] + BadJson(String), + #[error("not a HAR capture: {0}")] + NotHar(&'static str), +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Har { + pub version: Option, + pub creator: Option, + pub pages: usize, + pub entries: Vec, + pub declared_entries: usize, + pub truncated: bool, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HarEntry { + /// 0-based position in `log.entries`. + pub ordinal: usize, + pub started: Option, + pub time_ms: Option, + pub resource_type: Option, + pub server_ip: Option, + pub request: HarRequest, + pub response: HarResponse, + /// blocked, dns, connect, send, wait, receive, ssl (negative values mean "not applicable"). + pub timings: Vec<(String, f64)>, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HarRequest { + pub method: String, + pub url: String, + pub http_version: Option, + pub headers: Vec<(String, String)>, + pub cookie_names: Vec, + pub post: Option, + pub body_size: Option, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HarBody { + pub mime: Option, + pub text: Option, + /// Form parameter names (values are deliberately not surfaced by this type's users). + pub params: Vec<(String, Option)>, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HarResponse { + pub status: i64, + pub status_text: Option, + pub http_version: Option, + pub headers: Vec<(String, String)>, + pub cookie_names: Vec, + pub redirect_url: Option, + pub content_size: Option, + pub mime: Option, + pub text: Option, + /// `base64` when `text` is base64-encoded. + pub encoding: Option, + pub body_size: Option, +} + +fn s(v: &Value, k: &str) -> Option { + v.get(k).and_then(Value::as_str).map(String::from) +} + +fn pairs(v: Option<&Value>) -> Vec<(String, String)> { + v.and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|h| Some((h.get("name")?.as_str()?.to_string(), h.get("value").and_then(Value::as_str).unwrap_or_default().to_string()))) + .collect() + }) + .unwrap_or_default() +} + +fn names(v: Option<&Value>) -> Vec { + v.and_then(Value::as_array).map(|a| a.iter().filter_map(|c| c.get("name")?.as_str().map(String::from)).collect()).unwrap_or_default() +} + +/// Parse a HAR document, keeping at most `max_entries` entries. +pub fn parse(json: &[u8], max_entries: usize) -> Result { + let json = json.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(json); + let v: Value = serde_json::from_slice(json).map_err(|e| HarError::BadJson(e.to_string()))?; + let log = v.get("log").ok_or(HarError::NotHar("no \"log\" object"))?; + let entries = log.get("entries").and_then(Value::as_array).ok_or(HarError::NotHar("no \"log.entries\" array"))?; + let mut har = Har { + version: s(log, "version"), + creator: log + .get("creator") + .map(|c| format!("{} {}", s(c, "name").unwrap_or_default(), s(c, "version").unwrap_or_default()).trim().to_string()), + pages: log.get("pages").and_then(Value::as_array).map_or(0, Vec::len), + declared_entries: entries.len(), + ..Default::default() + }; + for (i, e) in entries.iter().enumerate() { + if har.entries.len() >= max_entries { + har.truncated = true; + break; + } + let req = e.get("request").unwrap_or(&Value::Null); + let res = e.get("response").unwrap_or(&Value::Null); + let content = res.get("content").unwrap_or(&Value::Null); + let post = req.get("postData").filter(|p| p.is_object()).map(|p| HarBody { + mime: s(p, "mimeType"), + text: s(p, "text"), + params: p + .get("params") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|x| Some((x.get("name")?.as_str()?.to_string(), s(x, "value")))).collect()) + .unwrap_or_default(), + }); + let timings = e + .get("timings") + .and_then(Value::as_object) + .map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_f64()?))).collect()) + .unwrap_or_default(); + har.entries.push(HarEntry { + ordinal: i, + started: s(e, "startedDateTime"), + time_ms: e.get("time").and_then(Value::as_f64), + resource_type: s(e, "_resourceType"), + server_ip: s(e, "serverIPAddress"), + request: HarRequest { + method: s(req, "method").unwrap_or_default(), + url: s(req, "url").unwrap_or_default(), + http_version: s(req, "httpVersion"), + headers: pairs(req.get("headers")), + cookie_names: names(req.get("cookies")), + post, + body_size: req.get("bodySize").and_then(Value::as_i64), + }, + response: HarResponse { + status: res.get("status").and_then(Value::as_i64).unwrap_or(0), + status_text: s(res, "statusText"), + http_version: s(res, "httpVersion"), + headers: pairs(res.get("headers")), + cookie_names: names(res.get("cookies")), + redirect_url: s(res, "redirectURL").filter(|u| !u.is_empty()), + content_size: content.get("size").and_then(Value::as_i64), + mime: s(content, "mimeType"), + text: s(content, "text"), + encoding: s(content, "encoding"), + body_size: res.get("bodySize").and_then(Value::as_i64), + }, + timings, + }); + } + Ok(har) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_a_har_with_a_utf8_bom() { + let capture = br#"{"log":{"entries":[]}}"#; + let mut encoded = vec![0xef, 0xbb, 0xbf]; + encoded.extend_from_slice(capture); + assert_eq!(parse(&encoded, 1).unwrap(), parse(capture, 1).unwrap()); + assert!(parse(&[0xef, 0xbb], 1).is_err()); + } + + #[test] + fn parses_minimal_har() { + let j = br#"{"log":{"version":"1.2","creator":{"name":"x","version":"1"},"entries":[ + {"startedDateTime":"2026-01-01T00:00:00Z","time":12.5, + "request":{"method":"POST","url":"https://api.example.test/v1/items/42","headers":[{"name":"Cookie","value":"s=1"}],"cookies":[{"name":"s","value":"1"}], + "postData":{"mimeType":"application/json","text":"{\"a\":1}"}}, + "response":{"status":201,"headers":[],"content":{"size":2,"mimeType":"application/json","text":"{}"}}, + "timings":{"wait":10,"receive":2.5}}]}}"#; + let h = parse(j, 10).unwrap(); + assert_eq!(h.entries.len(), 1); + let e = &h.entries[0]; + assert_eq!(e.request.method, "POST"); + assert_eq!(e.response.status, 201); + assert_eq!(e.request.cookie_names, vec!["s"]); + assert_eq!(e.timings.len(), 2); + } + + #[test] + fn rejects_non_har() { + assert!(parse(b"{}", 1).is_err()); + assert!(parse(b"nope", 1).is_err()); + assert!(parse(br#"{"log":{"entries":[1,null,"x"]}}"#, 10).is_ok()); + } +} + +/// Reject oversized input before parsing its JSON. `max_entries` only limits returned records. +pub fn parse_bounded(json: &[u8], max_entries: usize, max_bytes: usize) -> Result { + if json.len() > max_bytes { + return Err(HarError::NotHar("input byte limit exceeded")); + } + parse(json, max_entries) +} + +#[cfg(test)] +mod admission_tests { + use super::*; + #[test] + fn input_admission_and_entry_limits_are_independent() { + let input = br#"{"log":{"entries":[null,{}]}}"#; + assert_eq!(parse_bounded(input, 2, input.len()).unwrap(), parse(input, 2).unwrap()); + assert_eq!(parse_bounded(b"bad JSON", 1, 0), Err(HarError::NotHar("input byte limit exceeded"))); + let empty = parse_bounded(input, 0, input.len()).unwrap(); + assert!(empty.truncated && empty.entries.is_empty()); + assert_eq!(empty.declared_entries, 2); + let one = parse_bounded(input, 1, input.len()).unwrap(); + assert!(one.truncated); + assert_eq!(one.entries.len(), 1); + assert_eq!(one.entries[0].ordinal, 0); + assert!(!parse_bounded(input, 2, input.len()).unwrap().truncated); + } +} diff --git a/crates/html/src/doc/builder.rs b/crates/html/src/doc/builder.rs index 68bb7d8dba..022a510156 100644 --- a/crates/html/src/doc/builder.rs +++ b/crates/html/src/doc/builder.rs @@ -55,6 +55,27 @@ struct TableB { row: Option>, /// The table or one of its cells asks for borders. bordered: bool, + /// Explicit column widths from `` and childless ``. + col_widths: Vec>, + /// Pending ``: `(span, width, has_child_cols)`. + pending_colgroup: Option<(usize, Option, bool)>, +} + +impl TableB { + /// Commit pending colgroup widths: if childless, push span columns with group width. + /// When child `` elements are present, they have already received the group width + /// during `` handling; columns from earlier groups are never backfilled. + fn commit_pending_colgroup(&mut self) { + if let Some((span, group_w, has_child_cols)) = self.pending_colgroup.take() + && !has_child_cols + { + for _ in 0..span { + if self.col_widths.len() < MAX_TABLE_COLS { + self.col_widths.push(group_w); + } + } + } + } } struct ElementStyle { @@ -863,6 +884,15 @@ impl<'r> Builder<'r> { } } + /// Finalize an open HTML element popped from the stack. + /// + /// Side effects: + /// - Flushes any buffered inline text into the current block container. + /// - Sets `pending_page_break` if the element requests page break before or after. + /// - For `Cell`: pops the cell container, attaches generated blocks to the cell, and pushes into the active row. + /// - For `Tr`: commits any pending `` definitions and pushes the completed row into the active table. + /// - For `Table`: commits pending colgroup widths, finalizes table rows with `insert_covered` (bounded to `MAX_ROWS`), + /// resolves explicit column widths from colgroups/cells, and appends the resulting table to the enclosing container. fn close(&mut self, e: &El) { if e.page_break_after || e.page_break { self.pending_page_break = true; @@ -881,26 +911,53 @@ impl<'r> Builder<'r> { } } ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } } } ElKind::Table => { if let Some(mut t) = self.tables.pop() { + t.commit_pending_colgroup(); if let Some(r) = t.row.take() { t.rows.push(r); } let borderless = !t.bordered; // Keep at most MAX_ROWS rows (the model drops the rest anyway): bounds the // O(rows × rowspan) work of `insert_covered` on a table of millions of ``. - let rows: Vec<_> = t.rows.into_iter().filter(|r| !r.is_empty()).take(craft_wordmodel::table::MAX_ROWS).collect(); + let rows: Vec<_> = t.rows.into_iter().take(craft_wordmodel::table::MAX_ROWS).collect(); let mut ft = FTable { rows, widths: Vec::new(), borderless, extra: None, kept: None, wrap: None }; + let col_widths = &t.col_widths; if !ft.rows.is_empty() { ft.insert_covered(); - // Columns keep the widths their cells give when every column has one. - if ft.cols() <= MAX_TABLE_COLS { + ft.rows.retain(|r| !r.is_empty()); + } + if !ft.rows.is_empty() { + if col_widths.iter().any(Option::is_some) && ft.cols() <= MAX_TABLE_COLS { + let mut widths = vec![None; ft.cols()]; + for (i, &cw) in col_widths.iter().take(ft.cols()).enumerate() { + if let Some(w) = cw { + widths[i] = Some(w); + } + } + for row in &ft.rows { + let mut g = 0; + for c in row { + if let (Some(w), Some(slot)) = (c.width, widths.get_mut(g)) { + slot.get_or_insert(w); + } + g += c.colspan.clamp(1, 63) as usize; + } + } + if widths.iter().any(Option::is_some) { + let known_sum: f32 = widths.iter().filter_map(|w| *w).sum(); + let known_count = widths.iter().filter(|w| w.is_some()).count(); + let avg = if known_count > 0 { known_sum / known_count as f32 } else { 72.0 }; + ft.widths = widths.into_iter().map(|w| w.unwrap_or(avg)).collect(); + } + } else if ft.cols() <= MAX_TABLE_COLS { ft.widths_from_cells(); } self.container().push(FBlock::Table(ft)); @@ -1001,6 +1058,14 @@ impl<'r> Builder<'r> { } } + /// Process void or special HTML elements (`br`, `hr`, `wbr`, `col`, `colgroup`, `img`). + /// + /// Side effects: + /// - `br` / `wbr`: inserts line break or zero-width break into the active paragraph. + /// - `hr`: inserts a thematic horizontal rule block with borders and spacing into the container. + /// - `col`: extracts span and explicit CSS width, resolves against active ``, and appends up to `MAX_TABLE_COLS` column widths to the table. + /// - `colgroup`: commits any previous pending colgroup and buffers new span and width styles until child cols or closing tag arrive. + /// - `img`: parses dimensions, styles, and data/remote sources, creating an image block or inline image run. fn start_special(&mut self, name: &str, attrs: &[(String, String)]) -> bool { match name { "br" => { @@ -1020,6 +1085,34 @@ impl<'r> Builder<'r> { let fmt = self.fmt(); self.start_para().push_text("\u{200B}", &fmt); } + "col" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + let group_w = if let Some((_, group_w, has_child_cols)) = &mut t.pending_colgroup { + *has_child_cols = true; + *group_w + } else { + None + }; + let effective_w = w.or(group_w); + for _ in 0..span { + if t.col_widths.len() < MAX_TABLE_COLS { + t.col_widths.push(effective_w); + } + } + } + } + "colgroup" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + t.pending_colgroup = Some((span, w, false)); + } + } "img" => { let alt = attr(attrs, "alt").unwrap_or("").to_string(); let dim = |key: &str| attr(attrs, key).and_then(|v| v.trim().trim_end_matches("px").trim().parse::().ok()).map(|p| p * 0.75); @@ -1164,12 +1257,20 @@ impl<'r> Builder<'r> { let css = self.css_of(name, attrs); let ElementStyle { mut fmt, block_background, align, preserve, page_break, page_break_after } = self.element_style(name, attrs, kind, &css); match kind { - ElKind::Table => self.tables.push(TableB { rows: Vec::new(), row: None, bordered: declares_border(attrs, &css, true) }), + ElKind::Table => self.tables.push(TableB { + rows: Vec::new(), + row: None, + bordered: declares_border(attrs, &css, true), + col_widths: Vec::new(), + pending_colgroup: None, + }), ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } + t.row = Some(Vec::new()); } } ElKind::Cell => { @@ -1216,11 +1317,16 @@ impl<'r> Builder<'r> { _ => {} } } + // The last declaration wins, as in the cascade. + let mso_vmerge = decls(&css).filter(|(k, _)| k == "mso-yfti-vmerge").last().map(|(_, v)| v.trim().to_ascii_lowercase()); + let is_mso_vmerge_continue = mso_vmerge.as_deref() == Some("continue"); + let is_mso_vmerge_restart = mso_vmerge.as_deref() == Some("restart"); + let rowspan = attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1); self.cells.push(Cell { blocks: Vec::new(), colspan, - rowspan: attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1), - covered: false, + rowspan, + covered: is_mso_vmerge_continue, header: name == "th", shading, borders: cell_borders(&css), @@ -1229,6 +1335,8 @@ impl<'r> Builder<'r> { direction: Default::default(), picture: None, width: if colspan == 1 { cell_width(&css, attrs) } else { None }, + vmerge_restart: is_mso_vmerge_restart, + synthetic_covered: false, }); fmt.background = None; self.containers.push(Vec::new()); @@ -1261,6 +1369,12 @@ impl<'r> Builder<'r> { } return; } + if name == "colgroup" { + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + } + return; + } let crosses = matches!(name, "table"); let target = if matches!(name, "td" | "th") { self.find_open(|e| e.kind == ElKind::Cell, |e| e.kind == ElKind::Table) diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index 9fb861d855..52f7f50f0a 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -263,21 +263,87 @@ fn para_html(p: &Para) -> String { } } +/// Render an HTML table element, emitting `` column widths and cell attributes. fn table_html(t: &FTable, out: &mut String, depth: usize) { out.push_str("\n"); - for row in &t.rows { - out.push_str(""); - for c in row { - if c.covered { + if !t.widths.is_empty() { + out.push_str("\n"); + for w in &t.widths { + out.push_str(&format!("\n")); + } + out.push_str("\n"); + } + let nrows = t.rows.len(); + let grid_cols: Vec> = t + .rows + .iter() + .map(|row| { + let mut x = 0usize; + row.iter() + .map(|c| { + let start = x; + x = x.saturating_add(c.colspan.clamp(1, 63) as usize); + start + }) + .collect() + }) + .collect(); + let cell_at_grid = |r: usize, target_g: usize| -> Option { grid_cols.get(r)?.binary_search(&target_g).ok() }; + let grid_col = |r: usize, ci: usize| -> usize { grid_cols.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(0) }; + + let mut is_covered: Vec> = t.rows.iter().map(|r| vec![false; r.len()]).collect(); + let mut rowspans: Vec> = t.rows.iter().map(|r| r.iter().map(|c| c.rowspan.clamp(1, 1000)).collect()).collect(); + + for r in 0..nrows { + let row_len = t.rows.get(r).map_or(0, |row| row.len()); + for ci in 0..row_len { + if is_covered.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(false) { continue; } + let Some(c) = t.rows.get(r).and_then(|row| row.get(ci)) else { continue }; + let g = grid_col(r, ci); + let span = c.colspan.clamp(1, 63) as usize; + let mut extent = 1u32; + for down_r in (r + 1)..nrows { + let Some(down_ci) = cell_at_grid(down_r, g) else { break }; + let Some(down_c) = t.rows.get(down_r).and_then(|row| row.get(down_ci)) else { break }; + let down_covered = is_covered.get(down_r).and_then(|row| row.get(down_ci)).copied().unwrap_or(false); + if grid_col(down_r, down_ci) == g + && down_c.colspan.clamp(1, 63) as usize == span + && down_c.covered + && !down_c.vmerge_restart + && !down_covered + { + if let Some(down_row) = is_covered.get_mut(down_r) + && let Some(slot) = down_row.get_mut(down_ci) + { + *slot = true; + } + extent = extent.saturating_add(1); + } else { + break; + } + } + if let Some(slot) = rowspans.get_mut(r).and_then(|row| row.get_mut(ci)) { + *slot = (*slot).max(extent); + } + } + } + + for (ri, row) in t.rows.iter().enumerate() { + out.push_str(""); + for (ci, c) in row.iter().enumerate() { + if is_covered.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(false) { + continue; + } + let rowspan = rowspans.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(c.rowspan.clamp(1, 1000)); let tag = if c.header { "th" } else { "td" }; let mut attrs = String::new(); if c.colspan > 1 { attrs.push_str(&format!(" colspan=\"{}\"", c.colspan)); } - if c.rowspan > 1 { - attrs.push_str(&format!(" rowspan=\"{}\"", c.rowspan)); + if rowspan > 1 { + attrs.push_str(&format!(" rowspan=\"{}\"", rowspan)); } let v_css = match c.valign { Some(VAlign::Center) => "vertical-align:middle", @@ -288,6 +354,9 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) { if !t.borderless { css.insert(0, "border:1px solid #999".to_string()); } + if let Some(w) = c.width { + css.push(format!("width:{w:.2}pt")); + } if let Some(s) = c.shading { css.push(format!("background-color:#{}", s.hex())); } diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index c0b00084b7..c81687d481 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -1,5 +1,22 @@ use super::*; +#[test] +fn widthless_columns_do_not_change_cell_width_resolution() { + let widths = |columns: &str, cells: &str| { + let flow = parse(&format!("
{columns}{cells}
")); + let FBlock::Table(table) = &flow.blocks[0] else { panic!("expected table") }; + table.widths.clone() + }; + let partial = "xy"; + let widthless = ""; + assert!(widths("", partial).is_empty()); + assert_eq!(widths(widthless, partial), widths("", partial)); + let complete = "xy"; + assert_eq!(widths(widthless, complete), vec![30.0, 60.0]); + // An explicitly declared column still enables the existing average-fill rule. + assert_eq!(widths("", "xy"), vec![100.0, 100.0]); +} + #[test] fn numeric_entity_rejects_sign() { assert_eq!(unescape("a&#+65;b"), "a&#+65;b"); @@ -717,6 +734,195 @@ fn cells_give_their_columns_widths() { assert_eq!(t.widths, [75.0, 150.0]); } +#[test] +fn col_elements_give_table_column_widths() { + let f = parse("
AB
"); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [75.0, 150.0]); + + // col with span + let f2 = parse( + "
123
", + ); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, [72.0, 72.0, 144.0]); + + // Childless colgroup defines widths across declared span + let f3 = parse("
12
"); + let FBlock::Table(t3) = &f3.blocks[0] else { panic!() }; + assert_eq!(t3.widths, [75.0, 75.0]); + + // Child col elements override colgroup widths + let f4 = parse("
1
"); + let FBlock::Table(t4) = &f4.blocks[0] else { panic!() }; + assert_eq!(t4.widths, [150.0]); + + // Mixed childless colgroup and colgroup with child col elements + let f5 = parse( + "
123
", + ); + let FBlock::Table(t5) = &f5.blocks[0] else { panic!() }; + assert_eq!(t5.widths, [75.0, 200.0, 300.0]); + + // Child col elements inherit parent colgroup width when unset + let f6 = parse("
12
"); + let FBlock::Table(t6) = &f6.blocks[0] else { panic!() }; + assert_eq!(t6.widths, [90.0, 90.0]); + + // Child col elements without width inherit group width while explicit child width takes precedence + let f7 = parse("
12
"); + let FBlock::Table(t7) = &f7.blocks[0] else { panic!() }; + assert_eq!(t7.widths, [150.0, 90.0]); + + // Partial explicit col widths fall back to average for unset columns + let f8 = parse("
12
"); + let FBlock::Table(t8) = &f8.blocks[0] else { panic!() }; + assert_eq!(t8.widths, [100.0, 100.0]); + + // Export includes colgroup + let doc = model::to_doc(&f); + let html = export(&doc); + assert!(html.contains(""), "html export includes colgroup: {html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); +} + +#[test] +fn word_html_vertical_merge_is_preserved() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, no duplicate synthetic cell"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2, "table model second row has exactly 2 cells"); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn html_multiple_colgroups_do_not_backfill_earlier_groups() { + // Earlier colgroup with unset column must not be backfilled by later colgroup width. + let html = "\ + \ + \ + \ +
12
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [50.0, 50.0], "column 0 was not backfilled by group 2 width of 200pt"); +} + +#[test] +fn word_html_rowspan_with_explicit_vmerge_continue_no_duplicate_cell() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
AB1
A_contB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, not ragged"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn to_doc_normalises_row_0_continue_cell() { + use craft_wordmodel::props::VMerge; + // Case 1: Row 0 has continue and Row 1 has continue -> Row 0 normalised to Restart. + let html_multi = "\ + \ + \ +
TopContB1
BottomContB2
"; + let f_multi = parse(html_multi); + let doc_multi = model::to_doc(&f_multi); + let craft_wordmodel::Block::Table(tb_multi) = &*doc_multi.body[0] else { panic!() }; + assert_eq!(tb_multi.rows[0].cells[0].props.vmerge, VMerge::Restart, "row 0 continue normalised to restart"); + assert_eq!(tb_multi.rows[1].cells[0].props.vmerge, VMerge::Continue); + + // Case 2: Row 0 has continue but table has only 1 row (or no continuation) -> normalised to None. + let html_single = "\ + \ +
SoloContB1
"; + let f_single = parse(html_single); + let doc_single = model::to_doc(&f_single); + let craft_wordmodel::Block::Table(tb_single) = &*doc_single.body[0] else { panic!() }; + assert_eq!(tb_single.rows[0].cells[0].props.vmerge, VMerge::None, "orphaned row 0 continue normalised to none"); + + // Case 3: Row 0 col 1 has continue, Row 1 has a spanning continue starting at col 0 -> col 1 normalised to None. + let html_span = "\ + \ + \ +
A0B0
SpanCont
"; + let f_span = parse(html_span); + let doc_span = model::to_doc(&f_span); + let craft_wordmodel::Block::Table(tb_span) = &*doc_span.body[0] else { panic!() }; + assert_eq!(tb_span.rows[0].cells[1].props.vmerge, VMerge::None, "unaligned spanning continuation in row 1 must not mark row 0 cell as restart"); +} + +/// #1785: A covered continuation cell with `rowspan > 1` expands into the following row when +/// no restart cell above spans it. +#[test] +fn covered_continuation_with_rowspan_expands_into_next_row() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ + \ +
TopB0
MidB1
B2
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 3); + assert_eq!(tb.rows[2].cells.len(), 2, "row 2 should have placeholder + B2"); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::Continue); +} + +/// #1785: A plain `rowspan=2` cell `A` in col 0 followed by `B` (`vmerge:restart`) and `D` +/// must still insert a placeholder for `A` in row 1 even when `B`'s explicit `vmerge:continue` +/// is the first `` in row 1. +#[test] +fn rowspan_before_explicit_vmerge_continue_keeps_grid_columns() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
ABD
B_contD1
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 2); + assert_eq!(tb.rows[0].cells.len(), 3); + assert_eq!(tb.rows[1].cells.len(), 3, "row 1 should have placeholder for A, B_cont, and D1"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells[1].props.vmerge, VMerge::Continue); + let craft_wordmodel::Block::Para(p1) = &*tb.rows[1].cells[1].blocks[0] else { panic!() }; + assert_eq!(p1.text, "B_cont"); + assert_eq!(tb.rows[1].cells[2].props.vmerge, VMerge::None); + let craft_wordmodel::Block::Para(p2) = &*tb.rows[1].cells[2].blocks[0] else { panic!() }; + assert_eq!(p2.text, "D1"); +} + #[test] fn cells_take_their_css_borders() { use craft_wordmodel::props::{Border, BorderStyle}; @@ -768,6 +974,240 @@ fn hostile_style_sheets_never_panic() { } } +#[test] +fn conflicting_mso_vmerge_declarations_last_wins() { + let html_restart_wins = "
A
"; + let f1 = parse(html_restart_wins); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert!(t1.rows[0][0].vmerge_restart); + assert!(!t1.rows[0][0].covered); + + let html_continue_wins = "
B
"; + let f2 = parse(html_continue_wins); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert!(!t2.rows[0][0].vmerge_restart); + assert!(t2.rows[0][0].covered); +} + +#[test] +fn export_flow_derives_rowspan_for_vmerge_continuations() { + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains(""), "covered continuation cell should not be emitted: {exported}"); + assert!(exported.contains(">B1"), "{exported}"); + assert!(exported.contains(">B2"), "{exported}"); +} + +#[test] +fn export_flow_preserves_orphan_covered_continuation_content() { + let html = "\ + \ + \ +
Orphan0B0
A1B1
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains("Orphan0"), "orphan continuation content in row 0 must be preserved: {exported}"); +} + +#[test] +fn html_roundtrip_preserves_colgroups_widths_and_vmerge() { + use craft_wordmodel::props::VMerge; + + let html = "\ + \ + \ + \ + \ +
MergeAB1
MergeA_contB2
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.widths, [80.0, 120.0]); + assert_eq!(t1.rows.len(), 2); + assert_eq!(t1.rows[0].len(), 2); + assert_eq!(t1.rows[1].len(), 2); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_eq!(tb1.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb1.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb1.vertical_extent(0, 0), Some((0, 2))); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains(""), "exported HTML must contain colgroup: {exported}"); + assert!(exported.contains("width:80.00pt"), "{exported}"); + assert!(exported.contains("width:120.00pt"), "{exported}"); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, t1.widths, "column widths must match"); + assert_eq!(t2.rows.len(), t1.rows.len(), "row counts must match"); + assert_eq!(t2.rows[0].len(), t1.rows[0].len(), "row 0 cell count must match"); + assert_eq!(t2.rows[1].len(), t1.rows[1].len(), "row 1 cell count must match"); + assert_eq!(t2.rows[0][0].covered, t1.rows[0][0].covered, "row 0 cell 0 covered flag must match"); + assert_eq!(t2.rows[1][0].covered, t1.rows[1][0].covered, "row 1 cell 0 covered flag must match"); + + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_eq!(tb2.rows[0].cells[0].props.vmerge, tb1.rows[0].cells[0].props.vmerge, "vmerge restart matches"); + assert_eq!(tb2.rows[1].cells[0].props.vmerge, tb1.rows[1].cells[0].props.vmerge, "vmerge continue matches"); + assert_eq!(tb2.vertical_extent(0, 0), tb1.vertical_extent(0, 0), "vertical merge extent matches"); +} + +fn assert_single_col_vmerge_table(tb: &craft_wordmodel::Table) { + use craft_wordmodel::props::VMerge; + assert_eq!(tb.rows.len(), 3, "table must have 3 rows"); + assert_eq!(tb.grid.len(), 1, "table must have 1 column"); + assert_eq!(tb.rows[0].cells.len(), 1); + assert_eq!(tb.rows[1].cells.len(), 1); + assert_eq!(tb.rows[2].cells.len(), 1); + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::None); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); + assert_eq!(tb.grid_col(2, 0), 0, "Bottom cell must be at grid column 0"); + let bottom_text = match &*tb.rows[2].cells[0].blocks[0] { + craft_wordmodel::Block::Para(p) => &p.text, + _ => panic!("expected paragraph in Bottom cell"), + }; + assert_eq!(bottom_text, "Bottom", "Bottom must be at row 2, cell 0"); +} + +#[test] +fn html_roundtrip_preserves_fully_covered_row_and_single_column_table() { + // A one-column table with a Word vertical merge across the first two rows, + // followed by an ordinary "Bottom" cell in row three. + let html = "\ + \ + \ + \ +
Top
Cont
Bottom
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.rows.len(), 3, "initial import must have 3 rows"); + assert_eq!(t1.cols(), 1, "initial import must have 1 column"); + assert_eq!(t1.rows[0].len(), 1); + assert_eq!(t1.rows[1].len(), 1); + assert_eq!(t1.rows[2].len(), 1); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + assert!(!t1.rows[2][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb1); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + assert!(exported.contains(""), "covered row with no visible cells must emit empty tr: {exported}"); + assert!(exported.contains("Bottom"), "exported HTML must contain Bottom: {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.rows.len(), 3, "round-trip Flow must keep 3 rows"); + assert_eq!(t2.cols(), 1, "round-trip Flow must keep 1 column"); + assert_eq!(t2.rows[0].len(), 1, "row 0 has 1 cell"); + assert_eq!(t2.rows[1].len(), 1, "row 1 (fully covered row) has 1 cell"); + assert_eq!(t2.rows[2].len(), 1, "row 2 has 1 cell"); + assert!(!t2.rows[0][0].covered); + assert!(t2.rows[1][0].covered, "row 1 cell must be covered placeholder"); + assert!(!t2.rows[2][0].covered, "row 2 cell (Bottom) must not be covered"); + + // Convert round-tripped flow to document model + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb2); +} + +#[test] +fn vmerge_validation_requires_matching_spans() { + use craft_wordmodel::props::VMerge; + + // 1. Later-row check: row 0 has colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear continuation to None and NOT promote row 0 cell to Restart. + let ft_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span must not promote to Restart"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span must clear Continue to None"); + + // 2. First-row check: row 0 has continuation with colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear row 0 continuation to None, not promote to Restart. + let ft_row0_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, covered: true, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc0 = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_row0_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb0) = &*doc0.body[0] else { panic!() }; + assert_eq!(tb0.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span in row 0 must clear to None"); + assert_eq!(tb0.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span in row 1 must clear to None"); + + // 3. Matching spans: row 0 has colspan=2, row 1 has continuation with colspan=2. + // Matching spans must promote row 0 to Restart and keep row 1 as Continue. + let ft_matching = FTable { + rows: vec![vec![Cell { colspan: 2, ..Cell::default() }], vec![Cell { colspan: 2, covered: true, ..Cell::default() }]], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc_m = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_matching)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb_m) = &*doc_m.body[0] else { panic!() }; + assert_eq!(tb_m.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb_m.rows[1].cells[0].props.vmerge, VMerge::Continue); +} + +#[test] +fn export_table_preserves_first_grid_column_alignment() { + let mut doc = craft_wordmodel::Document::default(); + let mut table = craft_wordmodel::Table::new(2, 3, 240.0); + table.grid = vec![40.0, 80.0, 120.0]; + table.rows[0].cells = vec![craft_wordmodel::Cell::with_text("A"), craft_wordmodel::Cell::with_text("B"), craft_wordmodel::Cell::with_text("C")]; + table.rows[1].props.grid_before = 1; + table.rows[1].cells = vec![craft_wordmodel::Cell::with_text("D"), craft_wordmodel::Cell::with_text("E")]; + doc.body = vec![std::sync::Arc::new(craft_wordmodel::Block::Table(table))]; + + // Flow representation should preserve the leading grid position + let flow = model::from_doc(&doc); + let FBlock::Table(ft) = &flow.blocks[0] else { panic!() }; + assert_eq!(ft.rows.len(), 2); + assert_eq!(ft.rows[0].len(), 3); + assert_eq!(ft.rows[1].len(), 3, "row 1 must have 3 cells (1 leading placeholder + 2 data cells)"); + assert_eq!(ft.widths, vec![40.0, 80.0, 120.0]); + + // HTML export should emit 3 colgroup cols and preserve cell alignment + let html = export(&doc); + assert!(html.contains(""), "must contain col 0 width: {html}"); + assert!(html.contains(""), "must contain col 1 width: {html}"); + assert!(html.contains(""), "must contain col 2 width: {html}"); + assert!(html.contains(">D"), "must contain cell D: {html}"); + assert!(html.contains(">E"), "must contain cell E: {html}"); +} + /// Ensure container elements (such as `div` and `p`) with background colors do not leak /// character shading onto their child text runs (#1786). #[test] diff --git a/crates/image-codecs/src/bmp_probe.rs b/crates/image-codecs/src/bmp_probe.rs index 5b47721bca..89f6a3b977 100644 --- a/crates/image-codecs/src/bmp_probe.rs +++ b/crates/image-codecs/src/bmp_probe.rs @@ -1,5 +1,7 @@ //! Header-only BMP dimensions and pixel-data coverage, without allocating a canvas. +use crate::error::CodecError; + /// Recognize a BMP file header with a supported DIB header kind. /// /// This is a format-routing check, not full validation: dimensions and pixel data may still @@ -13,6 +15,115 @@ pub fn is_supported_header(b: &[u8]) -> bool { false } +/// Wrap a DIB (a BMP without its 14-byte `BITMAPFILEHEADER`, as the Windows clipboard holds one +/// for `CF_DIB` and `CF_DIBV5`) as a BMP file the decoders here read. The pixel offset is computed +/// from the header with saturating arithmetic, so a hostile header cannot overflow; whether the +/// pixel data exists is left to the decoder. Apply [`dib_layout`] first for clipboard DIBs. +/// +/// # Errors +/// +/// Returns [`CodecError::LimitExceeded`] when the output (`dib.len() + 14` bytes) cannot be allocated. +pub fn dib_to_bmp(dib: &[u8]) -> Result, CodecError> { + let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let bi_size = u32_at(0).unwrap_or(40); + let offset = if bi_size == 12 { + let bpp = u16_at(10).unwrap_or(24); + let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; + 14 + bi_size + palette + } else { + let bpp = u16_at(14).unwrap_or(24); + let compression = u32_at(16).unwrap_or(0); + let clr_used = u32_at(32).unwrap_or(0); + let palette_entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + // The masks of a 52- or 56-byte (V2/V3) header are inside the header; only the other + // header kinds carry them as 12 further bytes before the pixels. + let masks = if compression == 3 && bi_size >= 40 && !matches!(bi_size, 52 | 56) { 12 } else { 0 }; + 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) + }; + let total = dib.len().saturating_add(14); + let file_size = u32::try_from(total).unwrap_or(u32::MAX); + let mut bmp = Vec::new(); + bmp.try_reserve_exact(total).map_err(|_| CodecError::LimitExceeded(format!("a {total}-byte BMP")))?; + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&file_size.to_le_bytes()); + bmp.extend_from_slice(&[0u8; 4]); + bmp.extend_from_slice(&offset.to_le_bytes()); + bmp.extend_from_slice(dib); + Ok(bmp) +} + +/// Put a clipboard DIB with a V4 or V5 header (108 bytes or more) in the layout the decoder reads. +/// A 32-bit one whose alpha mask is set but whose compression says `BI_RGB` is marked +/// `BI_BITFIELDS` (with the usual colour masks when it gives none), so its alpha is kept as +/// Windows programs mean it; arboard makes the same change. Bit fields then need the colour masks +/// after the header too, where Windows puts a copy and the decoder skips them; a DIB without that +/// copy gets it. Any other DIB comes back unchanged, as does one whose 12 extra bytes cannot be +/// allocated. +pub fn dib_layout(mut dib: Vec) -> Vec { + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; + let put = |d: &mut Vec, at: usize, v: u32| { + if let Some(b) = d.get_mut(at..at + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + }; + // Decide everything first and mutate only after the 12-byte reservation succeeded, so a failed + // allocation returns the DIB unchanged. + let promote = dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000); + let default_masks = promote && (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)); + let mut masks = dib.get(40..52).and_then(|b| <[u8; 12]>::try_from(b).ok()); + if default_masks { + let mut m = [0u8; 12]; + m[0..4].copy_from_slice(&0x00FF_0000u32.to_le_bytes()); + m[4..8].copy_from_slice(&0x0000_FF00u32.to_le_bytes()); + m[8..12].copy_from_slice(&0x0000_00FFu32.to_le_bytes()); + masks = Some(m); + } + let bitfields = promote || u32_at(&dib, 16) == Some(3); + // Bytes equal to the masks right after the header are a copy only when more bytes follow than + // the pixels need; otherwise they are the pixels (e.g. a 3x1 V5 DIB with pixels equal to the masks). + let has_copy = |m: &[u8; 12]| { + dib.get(size..size.saturating_add(12)) == Some(m.as_slice()) && pixel_bytes(&dib).is_none_or(|need| dib.len().saturating_sub(size) > need) + }; + let insert = match masks { + Some(m) if bitfields && size <= dib.len() && !has_copy(&m) => Some(m), + _ => None, + }; + if insert.is_some() && dib.try_reserve(12).is_err() { + return dib; + } + if promote { + put(&mut dib, 16, 3); + if default_masks { + put(&mut dib, 40, 0x00FF_0000); + put(&mut dib, 44, 0x0000_FF00); + put(&mut dib, 48, 0x0000_00FF); + } + } + if let Some(m) = insert { + dib.splice(size..size, m); + } + dib +} + +/// Bytes of pixel rows (4-byte aligned stride) the info-header dimensions of `dib` call for, or +/// `None` when width, height or bit count cannot be read. +fn pixel_bytes(dib: &[u8]) -> Option { + let i32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes); + let w = u64::try_from(i32_at(4)?).ok()?; + let h = u64::from(i32_at(8)?.unsigned_abs()); + let bpp = u64::from(u16::from_le_bytes(dib.get(14..16)?.try_into().ok()?)); + let stride = w.checked_mul(bpp)?.div_ceil(32).checked_mul(4)?; + usize::try_from(stride.checked_mul(h)?).ok() +} + /// Coverage of the declared pixel array. Row byte counts include row padding; RLE coverage /// counts the pixels drawn by commands and may be smaller than the canvas. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -174,4 +285,335 @@ mod tests { b[0] = b'X'; assert!(!is_supported_header(&b)); } + + // The WordCraft originals, kept verbatim as the oracle. + fn oracle_dib_to_bmp(dib: &[u8]) -> Vec { + let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let bi_size = u32_at(0).unwrap_or(40); + let offset = if bi_size == 12 { + let bpp = u16_at(10).unwrap_or(24); + let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; + 14 + bi_size + palette + } else { + let bpp = u16_at(14).unwrap_or(24); + let compression = u32_at(16).unwrap_or(0); + let clr_used = u32_at(32).unwrap_or(0); + let palette_entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + let masks = if compression == 3 && bi_size >= 40 { 12 } else { 0 }; + 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) + }; + let file_size = u32::try_from(14 + dib.len()).unwrap_or(u32::MAX); + let mut bmp = Vec::with_capacity(14 + dib.len()); + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&file_size.to_le_bytes()); + bmp.extend_from_slice(&[0u8; 4]); + bmp.extend_from_slice(&offset.to_le_bytes()); + bmp.extend_from_slice(dib); + bmp + } + + fn oracle_dib_layout(mut dib: Vec) -> Vec { + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; + let put = |d: &mut Vec, at: usize, v: u32| { + if let Some(b) = d.get_mut(at..at + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + }; + if dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000) { + put(&mut dib, 16, 3); + if (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)) { + put(&mut dib, 40, 0x00FF_0000); + put(&mut dib, 44, 0x0000_FF00); + put(&mut dib, 48, 0x0000_00FF); + } + } + if u32_at(&dib, 16) == Some(3) + && size <= dib.len() + && let Some(masks) = dib.get(40..52).map(<[u8]>::to_vec) + && dib.get(size..size + 12) != Some(masks.as_slice()) + { + dib.splice(size..size, masks); + } + dib + } + + fn core(bpp: u16) -> Vec { + let mut d = Vec::new(); + d.extend_from_slice(&12u32.to_le_bytes()); + d.extend_from_slice(&2u16.to_le_bytes()); + d.extend_from_slice(&2u16.to_le_bytes()); + d.extend_from_slice(&1u16.to_le_bytes()); + d.extend_from_slice(&bpp.to_le_bytes()); + d.resize(12 + 64, 7); + d + } + + #[allow(clippy::too_many_arguments)] + fn info(size: u32, bpp: u16, comp: u32, clr_used: u32, masks: [u32; 4], tail: usize) -> Vec { + let mut d = vec![0u8; size.clamp(40, 124) as usize]; + d[0..4].copy_from_slice(&size.to_le_bytes()); + d[4..8].copy_from_slice(&2i32.to_le_bytes()); + d[8..12].copy_from_slice(&2i32.to_le_bytes()); + d[12..14].copy_from_slice(&1u16.to_le_bytes()); + d[14..16].copy_from_slice(&bpp.to_le_bytes()); + d[16..20].copy_from_slice(&comp.to_le_bytes()); + d[32..36].copy_from_slice(&clr_used.to_le_bytes()); + for (i, m) in masks.iter().enumerate() { + if let Some(b) = d.get_mut(40 + 4 * i..44 + 4 * i) { + b.copy_from_slice(&m.to_le_bytes()); + } + } + d.extend((0..tail).map(|i| (i * 31 + 5) as u8)); + d + } + + fn corpus() -> Vec> { + let mut v = Vec::new(); + for bpp in [1, 4, 8, 24, 0, 99] { + v.push(core(bpp)); + } + for bpp in [1u16, 4, 8, 16, 24, 32, 0, 255] { + for clr in [0u32, 1, 5, 256, u32::MAX] { + v.push(info(40, bpp, 0, clr, [0; 4], 40)); + } + } + for (size, comp, masks) in [ + (40, 3, [0xFF0000, 0xFF00, 0xFF, 0]), + (40, 3, [0; 4]), + (52, 3, [0xFF0000, 0xFF00, 0xFF, 0]), + (108, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (108, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (108, 0, [0, 0, 0, 0xFF00_0000]), + (108, 0, [0; 4]), + (124, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (124, 0, [0, 0, 0, 0xFF00_0000]), + (124, 0, [1, 0, 0, 0xFF00_0000]), + (124, 0, [0xFF0000, 0xFF00, 0xFF, 0]), + (124, 1, [0, 0, 0, 0xFF00_0000]), + (124, 3, [1, 2, 3, 4]), + (0, 0, [0; 4]), + (12, 0, [0; 4]), + (u32::MAX, 3, [0; 4]), + (u32::MAX, 0, [0; 4]), + (200, 3, [9; 4]), + ] { + for bpp in [8u16, 16, 32] { + for clr in [0u32, 2, u32::MAX] { + v.push(info(size, bpp, comp, clr, masks, 48)); + } + } + } + // 52/56-byte bitfields headers with and without a pixel tail, and 3x1 V5 DIBs. + for size in [52, 56] { + v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 4)); + v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0)); + } + v.push(v5_3x1(false)); + v.push(v5_3x1(true)); + v + } + + /// 3x1 32-bit V5 BI_BITFIELDS whose three pixels equal the colour masks; with `copy` the DIB + /// also holds the real 12-byte mask copy before the pixels. + fn v5_3x1(copy: bool) -> Vec { + let masks = [0x00FF_0000u32, 0x0000_FF00, 0x0000_00FF]; + let mut d = info(124, 32, 3, 0, [masks[0], masks[1], masks[2], 0xFF00_0000], 0); + d[4..8].copy_from_slice(&3i32.to_le_bytes()); + d[8..12].copy_from_slice(&1i32.to_le_bytes()); + for _ in 0..usize::from(copy) + 1 { + for m in masks { + d.extend_from_slice(&m.to_le_bytes()); + } + } + d + } + + fn dib_u32(d: &[u8], at: usize) -> Option { + d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) + } + + /// Fixed case 1: a 52- or 56-byte BI_BITFIELDS header holds its masks itself, so `dib_to_bmp` + /// no longer adds the 12 appended-mask bytes the WordCraft original added to the pixel offset. + fn bmp_offset_fixed(dib: &[u8]) -> bool { + matches!(dib_u32(dib, 0).unwrap_or(40), 52 | 56) && dib_u32(dib, 16) == Some(3) + } + + /// Fixed case 2: the original read 12 pixel bytes equal to the masks (exact-length payload) as a + /// mask copy and inserted nothing. Returns the corrected output when `cut` is such a case. + fn exact_length_fixed(cut: &[u8]) -> Option> { + let o = oracle_dib_layout(cut.to_vec()); + let size = usize::try_from(dib_u32(&o, 0).filter(|&s| s >= 108)?).ok()?; + let need = pixel_bytes(&o)?; + let same = o.len() == cut.len() + && dib_u32(&o, 16) == Some(3) + && size <= o.len() + && o.get(size..size + 12).is_some() + && o.get(size..size + 12) == o.get(40..52) + && o.len() - size <= need; + if !same { + return None; + } + let mut want = o.clone(); + want.splice(size..size, o[40..52].to_vec()); + Some(want) + } + + #[test] + fn dib_helpers_match_the_wordcraft_originals_byte_for_byte() { + let (mut total, mut offset_cases, mut exact_cases) = (0usize, 0usize, 0usize); + for dib in corpus() { + for n in 0..=dib.len() { + let cut = &dib[..n]; + total += 1; + let fixed_layout = exact_length_fixed(cut); + match &fixed_layout { + Some(want) => { + exact_cases += 1; + assert_eq!(&dib_layout(cut.to_vec()), want, "exact-length layout len {n}"); + } + None => assert_eq!(dib_layout(cut.to_vec()), oracle_dib_layout(cut.to_vec()), "layout len {n}"), + } + if bmp_offset_fixed(cut) { + offset_cases += 1; + let (new, old) = (dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut)); + assert_eq!(new[..10], old[..10]); + assert_eq!(new[14..], old[14..]); + let (a, b) = (dib_u32(&new, 10).unwrap(), dib_u32(&old, 10).unwrap()); + assert_eq!(a.saturating_add(12), b, "offset len {n}"); + } else { + assert_eq!(dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut), "bmp len {n}"); + } + let both = dib_layout(cut.to_vec()); + let old_both = oracle_dib_layout(cut.to_vec()); + if fixed_layout.is_none() && !bmp_offset_fixed(&both) { + assert_eq!(dib_to_bmp(&both).unwrap(), oracle_dib_to_bmp(&old_both)); + } + } + } + eprintln!("corpus cases {total}: 52/56-byte bitfields offset {offset_cases}, exact-length payload {exact_cases}"); + assert!(offset_cases > 0 && exact_cases > 0); + } + + #[test] + fn dib_helpers_survive_pseudo_random_bytes() { + let mut x = 0x9E37_79B9_7F4A_7C15u64; + for len in 0..300usize { + let d: Vec = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect(); + let laid = dib_layout(d.clone()); + if exact_length_fixed(&d).is_none() && !bmp_offset_fixed(&laid) { + assert_eq!(dib_to_bmp(&laid).unwrap(), oracle_dib_to_bmp(&oracle_dib_layout(d))); + } + } + } + + #[test] + fn huge_palette_count_saturates_the_offset() { + let b = dib_to_bmp(&info(40, 8, 0, u32::MAX, [0; 4], 8)).unwrap(); + assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX); + let b = dib_to_bmp(&info(u32::MAX, 8, 3, u32::MAX, [0; 4], 8)).unwrap(); + assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX); + } + + #[test] + fn wrapped_dibs_decode_and_keep_alpha() { + // 2x2 32-bit V5, BI_RGB with an alpha mask, bottom-up BGRA pixels. + let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 0); + let px = [[1u8, 2, 3, 255], [4, 5, 6, 128], [7, 8, 9, 64], [10, 11, 12, 0]]; + for p in px { + d.extend_from_slice(&p); + } + let bmp = dib_to_bmp(&dib_layout(d)).unwrap(); + let img = crate::decode(&bmp).unwrap(); + let alphas: Vec = img.to_rgba8().chunks(4).map(|p| u16::from(p[3])).collect(); + assert_eq!(alphas, [64, 0, 255, 128]); + // 24-bit plain DIB and a 12-byte core 8-bit one open too. + let mut d = info(40, 24, 0, 0, [0; 4], 0); + d.extend_from_slice(&[0, 0, 255, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + assert!(crate::decode(&dib_to_bmp(&d).unwrap()).is_ok()); + let mut c = core(8); + c.truncate(12); + c.extend((0..256 * 3).map(|i| i as u8)); + c.extend_from_slice(&[0, 1, 0, 0, 2, 3, 0, 0]); + assert!(crate::decode(&dib_to_bmp(&c).unwrap()).is_ok()); + } + + /// 1x1 32-bit BI_BITFIELDS DIB, one pixel B=10 G=20 R=30 A=128, with the given header size. + fn one_pixel(size: u32) -> Vec { + let mut d = info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0); + d[4..8].copy_from_slice(&1i32.to_le_bytes()); + d[8..12].copy_from_slice(&1i32.to_le_bytes()); + if size == 40 { + for m in [0xFF0000u32, 0xFF00, 0xFF] { + d.extend_from_slice(&m.to_le_bytes()); + } + } + d.extend_from_slice(&[10, 20, 30, 128]); + d + } + + #[test] + fn bitfields_pixel_offset_for_each_header_size_decodes() { + for size in [40u32, 52, 56] { + let bmp = dib_to_bmp(&one_pixel(size)).unwrap(); + let off = 14 + size + if size == 40 { 12 } else { 0 }; + assert_eq!(dib_u32(&bmp, 10), Some(off), "offset for {size}"); + let img = crate::decode(&bmp).unwrap_or_else(|e| panic!("{size}-byte header: {e:?}")); + let rgba = img.to_rgba8(); + assert_eq!(&rgba[..3], &[30, 20, 10], "size {size}"); + if size == 56 { + assert_eq!(rgba[3], 128); + } + } + // V5: the header's masks, a copy inserted by `dib_layout`, then the pixel. + let bmp = dib_to_bmp(&dib_layout(one_pixel(124))).unwrap(); + assert_eq!(&crate::decode(&bmp).unwrap().to_rgba8()[..4], &[30, 20, 10, 128]); + } + + #[test] + fn exact_length_pixels_equal_to_the_masks_are_not_a_mask_copy() { + let d = v5_3x1(false); + let laid = dib_layout(d.clone()); + assert_eq!(laid.len(), d.len() + 12); + assert_eq!(laid[124..136], d[40..52]); + assert_eq!(oracle_dib_layout(d).len(), laid.len() - 12, "the original skipped the insertion"); + let img = crate::decode(&dib_to_bmp(&laid).unwrap()).unwrap().to_rgba8(); + assert_eq!(img.len(), 12); + // pixel 0 is 0x00FF0000 (blue 0, green 0, red 255 under the masks). + assert_eq!(&img[..3], &[255, 0, 0]); + // A real copy followed by the pixels is left alone. + let real = v5_3x1(true); + assert_eq!(dib_layout(real.clone()), real); + assert!(crate::decode(&dib_to_bmp(&real).unwrap()).is_ok()); + } + + #[test] + fn layout_decides_before_it_mutates() { + // BI_RGB V5 with an alpha mask and no colour masks: promoted and given a copy together. + let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 16); + d[4..8].copy_from_slice(&2i32.to_le_bytes()); + let laid = dib_layout(d.clone()); + assert_eq!(laid.len(), d.len() + 12); + assert_eq!(dib_u32(&laid, 16), Some(3)); + // Unreadable dimensions keep the byte-equality rule. + let mut odd = info(108, 32, 3, 0, [1, 2, 3, 0], 0); + odd[4..8].copy_from_slice(&(-1i32).to_le_bytes()); + let copy = odd[40..52].to_vec(); + odd.extend_from_slice(©); + assert_eq!(dib_layout(odd.clone()), odd); + } } diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 415a5d7173..989956182d 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -46,6 +46,45 @@ pub(crate) struct JpegMeta { pub held_coefficients: u64, } +/// Validate a JPEG by decoding the 8-bit RGBA output used by renderers. +/// +/// This deliberately uses the existing zune backend's default decode policy. +/// Unlike general JPEG import it does not fall back to additional JPEG modes, +/// apply orientation, or retain pixels. The caller supplies the admitted pixel count. +pub fn validate_jpeg_rgba8(bytes: &[u8], max_pixels: u64) -> Result<(), CodecError> { + validate_jpeg_rgba8_with_panic_policy(bytes, max_pixels, cfg!(panic = "abort")) +} + +fn validate_jpeg_rgba8_with_panic_policy(bytes: &[u8], max_pixels: u64, panic_aborts: bool) -> Result<(), CodecError> { + // The decoder can assert while upsampling these frames. On abort builds the + // unwind guard below cannot turn that assertion into an image omission. + if panic_aborts && first_component_subsampled(bytes) { + return Err(CodecError::malformed(F, "JPEG first component is subsampled below the frame maximum")); + } + let decode = || { + let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA); + let mut decoder = zune_jpeg::JpegDecoder::new_with_options(std::io::Cursor::new(bytes), options); + decoder.decode_headers().map_err(|error| CodecError::malformed(F, format_args!("{error:?}")))?; + let info = decoder.info().ok_or_else(|| CodecError::malformed(F, "missing frame dimensions"))?; + let pixels = u64::from(info.width) * u64::from(info.height); + if pixels == 0 { + return Err(CodecError::malformed(F, "empty frame")); + } + if pixels > max_pixels { + return Err(CodecError::LimitExceeded("JPEG exceeds the admitted pixel count".into())); + } + let length = usize::try_from(pixels * 4).map_err(|_| CodecError::LimitExceeded("JPEG RGBA output is too large".into()))?; + if decoder.output_colorspace() != Some(ColorSpace::RGBA) || decoder.output_buffer_size() != Some(length) { + return Err(CodecError::malformed(F, "unexpected RGBA output")); + } + let mut output = Vec::new(); + output.try_reserve_exact(length).map_err(|_| CodecError::LimitExceeded("could not allocate JPEG RGBA output".into()))?; + output.resize(length, 0); + decoder.decode_into(&mut output).map_err(|error| CodecError::malformed(F, format_args!("{error:?}"))) + }; + std::panic::catch_unwind(decode).map_err(|_| CodecError::malformed(F, "JPEG decoder failed on this frame"))? +} + /// The first frame of `b` as [`crate::JpegInfo`], from its markers alone (see [`crate::jpeg_info`]). pub(crate) fn info(b: &[u8]) -> Option { let m = scan_metadata(b); @@ -86,6 +125,83 @@ fn held_coefficients(marker: u8, seg: &[u8], scan_components: Option) -> u64 factors.iter().map(|&(fh, fv)| mcus * fh * fv * 64 * 2).sum() } +/// Bytes of DCT coefficients to budget for before decoding hostile `b`: the larger of +/// [`crate::JpegInfo::held_coefficients`]'s rule (first frame; SOF2, or SOF0/SOF1 whose first +/// scan lacks components; 8-bit only; sampling factors as written) and a coarser one that +/// keeps a progressive JPEG's coefficients for the whole picture: +/// - every SOF2, SOF6, SOF10 and SOF14 header before the first scan counts, at any precision, and +/// the largest wins; each charges 2 bytes a coefficient: per component, `2 * 64 * h * v` per +/// MCU, with `h` and `v` clamped to 1..=4 and the MCUs covering the frame at the largest `h`, `v`; +/// - a header that can't be followed (a segment that is cut, a length under 2, a frame header +/// without its components, no `0xFF` where a marker belongs) charges the costliest frame, +/// four components sampled 4 × 4, at the first frame's size (as `scan_metadata` reads it), and 0 without one. +/// +/// Never less than either rule. Frames `craft-jpeg` decodes (arithmetic, lossless, 12-bit) +/// enforce `max_alloc` on their own buffers, and SOF6/SOF14 (hierarchical) are not decoded at all, +/// so charging them is only a conservative budget. Arithmetic saturates; the scan is linear. +pub(crate) fn worst_case_coefficients(b: &[u8]) -> u64 { + let m = scan_metadata(b); + let mut at = 2usize; + let mut most = 0u64; + let first: Option<(u64, u64)> = m.frame.map(|(w, h, _)| (u64::from(w), u64::from(h))); + let mut broken = false; + while !broken { + if b.get(at) != Some(&0xFF) { + broken = true; + break; + } + while b.get(at) == Some(&0xFF) { + at += 1; + } + let Some(&code) = b.get(at) else { + broken = true; + break; + }; + at += 1; + match code { + 0xD8 | 0x01 | 0xD0..=0xD7 => continue, + 0xD9 | 0xDA => break, + _ => {} + } + let len = match (b.get(at), b.get(at + 1)) { + (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), + _ => 0, + }; + let Some(seg) = (len >= 2).then(|| b.get(at + 2..at + len)).flatten() else { + broken = true; + break; + }; + if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { + match progressive_frame_coefficients(seg) { + Some(held) => most = most.max(held), + None => { + broken = true; + break; + } + } + } + at += len; + } + if broken && let Some((w, h)) = first { + let mcus = w.div_ceil(32).saturating_mul(h.div_ceil(32)); + most = most.max(mcus.saturating_mul(2 * 64 * 16 * 4)); + } + most.max(m.held_coefficients) +} + +/// [`worst_case_coefficients`]'s charge for one frame header `sof` (after its length). +fn progressive_frame_coefficients(sof: &[u8]) -> Option { + let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); + let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); + let n = usize::from(*sof.get(5)?); + let comps = sof.get(6..6usize.checked_add(n.checked_mul(3)?)?)?; + let factors: Vec<(u64, u64)> = + comps.as_chunks::<3>().0.iter().map(|&[_, f, _]| (u64::from(f >> 4).clamp(1, 4), u64::from(f & 15).clamp(1, 4))).collect(); + let (hmax, vmax) = factors.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); + let mcus = width.div_ceil(8 * hmax).saturating_mul(height.div_ceil(8 * vmax)); + Some(factors.iter().fold(0u64, |sum, &(h, v)| sum.saturating_add(mcus.saturating_mul(2 * 64 * h * v)))) +} + /// Walk the marker segments up to SOS and collect metadata. pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { let mut m = JpegMeta::default(); @@ -340,10 +456,17 @@ fn first_component_subsampled(b: &[u8]) -> bool { return false; } let mut i = 2; - while let (Some(&0xFF), Some(&m)) = (b.get(i), b.get(i + 1)) { + while let Some(&prefix) = b.get(i) { + // The decoder searches forward between segments. Stray bytes and + // stuffed FF 00 pairs must not hide a frame from the abort-build guard. + if prefix != 0xFF { + i += 1; + continue; + } + let Some(&m) = b.get(i + 1) else { return false }; match m { 0xFF => i += 1, - 0x01 | 0xD0..=0xD8 => i += 2, + 0x00 | 0x01 | 0xD0..=0xD8 => i += 2, 0xD9 | 0xDA => return false, _ => { let Some(len) = b.get(i + 2..i + 4).map(|l| usize::from(u16::from_be_bytes([l[0], l[1]]))) else { return false }; @@ -825,6 +948,170 @@ mod tests { assert_eq!(held(&frame(0xC2, 12, &[0x11, 0x11, 0x11], None)), Some(0)); } + /// The consumer's own estimate (WordCraft's `jpeg_coefficients`), ported as the oracle that + /// `worst_case_coefficients` must never undercut. + fn oracle(bytes: &[u8]) -> u64 { + fn worst(bytes: &[u8]) -> u64 { + let Some((w, h)) = info(bytes).map(|i| (i.width, i.height)) else { return 0 }; + let mcus = u64::from(w).div_ceil(32) * u64::from(h).div_ceil(32); + mcus.saturating_mul(2 * 64 * 16 * 4) + } + fn frame(sof: &[u8]) -> Option { + let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); + let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); + let n = usize::from(*sof.get(5)?); + let s: Vec<(u64, u64)> = sof + .get(6..6 + 3 * n)? + .as_chunks::<3>() + .0 + .iter() + .map(|&[_, s, _]| (u64::from(s >> 4).clamp(1, 4), u64::from(s & 15).clamp(1, 4))) + .collect(); + let (hm, vm) = s.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); + let mcus = width.div_ceil(8 * hm).checked_mul(height.div_ceil(8 * vm))?; + s.iter().try_fold(0u64, |sum, &(h, v)| sum.checked_add(mcus.checked_mul(2 * 64 * h * v)?)) + } + let mut at = 2; + let mut most = 0u64; + loop { + if bytes.get(at) != Some(&0xFF) { + return worst(bytes).max(most); + } + while bytes.get(at) == Some(&0xFF) { + at += 1; + } + let Some(&code) = bytes.get(at) else { return worst(bytes).max(most) }; + at += 1; + match code { + 0xD8 | 0x01 | 0xD0..=0xD7 => continue, + 0xD9 | 0xDA => return most, + _ => {} + } + let len = match (bytes.get(at), bytes.get(at + 1)) { + (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), + _ => 0, + }; + let Some(seg) = bytes.get(at + 2..at + len).filter(|_| len >= 2) else { return worst(bytes).max(most) }; + if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { + let Some(h) = frame(seg) else { return worst(bytes).max(most) }; + most = most.max(h); + } + at += len; + } + } + + /// A JPEG header: each frame is (marker, precision, width, height, sampling bytes), then an + /// optional scan of `scan` components, then EOI. + fn header(frames: &[(u8, u8, u16, u16, &[u8])], scan: Option) -> Vec { + let mut b = vec![0xFF, 0xD8]; + for &(marker, precision, w, h, f) in frames { + b.extend_from_slice(&[0xFF, marker]); + b.extend_from_slice(&(8 + 3 * f.len() as u16).to_be_bytes()); + b.push(precision); + b.extend_from_slice(&h.to_be_bytes()); + b.extend_from_slice(&w.to_be_bytes()); + b.push(f.len() as u8); + for (i, &s) in f.iter().enumerate() { + b.extend_from_slice(&[i as u8 + 1, s, 0]); + } + } + if let Some(n) = scan { + b.extend_from_slice(&[0xFF, 0xDA, 0, 6 + 2 * n, n]); + (1..=n).for_each(|c| b.extend_from_slice(&[c, 0])); + b.extend_from_slice(&[0, 63, 0]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + b + } + + /// Never less than the oracle or `held_coefficients`; equal to the larger on valid headers. + #[test] + fn worst_case_coefficients_covers_both_rule_sets() { + const C3: &[u8] = &[0x22, 0x11, 0x11]; + const G: &[u8] = &[0x11]; + let cases: Vec> = vec![ + header(&[(0xC0, 8, 640, 480, C3)], Some(3)), + header(&[(0xC0, 8, 640, 480, G)], Some(1)), + header(&[(0xC0, 8, 640, 480, C3)], Some(1)), + header(&[(0xC1, 8, 640, 480, C3)], None), + header(&[(0xC2, 8, 640, 480, C3)], Some(1)), + header(&[(0xC2, 12, 640, 480, C3)], Some(1)), + header(&[(0xC6, 8, 640, 480, C3)], None), + header(&[(0xCA, 8, 640, 480, C3)], None), + header(&[(0xCE, 8, 640, 480, C3)], None), + header(&[(0xC0, 8, 64, 64, G), (0xC2, 8, 6000, 4000, C3), (0xC2, 8, 100, 100, C3)], Some(1)), + header(&[(0xC2, 8, 640, 480, &[0x00, 0x00, 0x00])], None), + header(&[(0xC2, 8, 640, 480, &[0xFF, 0xFF, 0xFF, 0xFF])], None), + header(&[(0xC2, 8, 65535, 65535, &[0x44; 4])], None), + header(&[(0xC0, 8, 65535, 65535, &[0xFF; 4])], Some(1)), + header(&[], None), + vec![0xFF, 0xD8], + vec![], + b"not a jpeg at all".to_vec(), + ]; + for b in &cases { + let held = scan_metadata(b).held_coefficients; + let got = worst_case_coefficients(b); + assert!(got >= oracle(b) && got >= held, "{b:02x?}"); + assert!(got >= info(b).map_or(0, |i| i.held_coefficients)); + } + let at = |i: usize| worst_case_coefficients(&cases[i]); + // Equal to the oracle where the shared rule charges nothing extra. + for i in [0, 1, 6, 7, 8, 9, 10, 12, 14] { + assert_eq!(at(i), oracle(&cases[i]), "case {i}"); + } + // Where it does, the shared figure wins (the oracle misses a short first scan). + assert_eq!(oracle(&cases[2]), 0); + assert_eq!(at(2), scan_metadata(&cases[2]).held_coefficients); + // Unclamped factors (15 × 15) charge the shared rule more than the clamped oracle. + assert_eq!(at(11), scan_metadata(&cases[11]).held_coefficients); + assert!(at(11) > oracle(&cases[11])); + assert!(at(2) > 0 && at(3) == 0 && at(0) == 0); + // 12-bit and arithmetic progressive frames are charged though craft-jpeg limits itself. + assert_eq!(at(5), at(4)); + // Sampling factors clamp: 0 acts as 1, 15 as 4. + assert_eq!(at(10), 80 * 60 * 3 * 128); + assert_eq!(at(12), 2048 * 2048 * 4 * 2 * 64 * 16); + // The largest of several frames wins. + assert_eq!(at(9), oracle(&header(&[(0xC2, 8, 6000, 4000, C3)], None))); + } + + /// A cut header charges the costliest frame at its size; every prefix and random damage stays + /// bounded, never panics and never undercuts the oracle. + #[test] + fn worst_case_coefficients_hostile_input() { + let full = header(&[(0xC2, 8, 6000, 4000, &[0x22, 0x11, 0x11])], Some(1)); + let cut = &full[..full.len() - 8]; + // Cut inside the component list: a frame the scan can't read, at its own size. + let sof_cut = &full[..14]; + assert_eq!(worst_case_coefficients(sof_cut), oracle(sof_cut)); + assert_eq!(worst_case_coefficients(cut), oracle(cut)); + let mut bases = vec![full.clone(), header(&[(0xC0, 8, 6000, 4000, &[0x11; 3])], Some(1))]; + bases.push(header(&[(0xC2, 8, 65535, 65535, &[0xFF; 4])], None)); + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize + }; + for base in &bases { + for n in 0..=base.len() { + let b = &base[..n]; + let got = worst_case_coefficients(b); + assert!(got >= oracle(b) && got < 1 << 50); + } + for _ in 0..2000 { + let mut b = base.clone(); + for _ in 0..=next() % 4 { + let i = next() % b.len(); + b[i] = next() as u8; + } + b.truncate(next() % (b.len() + 1)); + let got = worst_case_coefficients(&b); + assert!(got >= oracle(&b) && got >= scan_metadata(&b).held_coefficients && got < 1 << 50); + } + } + } + /// An APP1 Extended XMP fragment (GUID, total size, offset, data). fn extended_xmp(offset: u32) -> Vec { let mut seg = EXTENDED_XMP_HEADER.to_vec(); @@ -1073,25 +1360,61 @@ mod tests { (v * 65535.0 / 4095.0).round() as u16 } + fn progressive_frame_header(comps: &[(u8, u8)]) -> Vec { + let mut s = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2, 0, (8 + 3 * comps.len()) as u8, 8, 0, 8, 0, 8, comps.len() as u8]; + for (i, &(h, v)) in comps.iter().enumerate() { + s.extend([i as u8 + 1, (h << 4) | v, 0]); + } + s + } + #[test] fn first_component_subsampling() { - let sof = |comps: &[(u8, u8)]| { - let mut s = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2, 0, (8 + 3 * comps.len()) as u8, 8, 0, 8, 0, 8, comps.len() as u8]; - for (i, &(h, v)) in comps.iter().enumerate() { - s.extend([i as u8 + 1, (h << 4) | v, 0]); - } - s - }; - assert!(first_component_subsampled(&sof(&[(1, 1), (1, 1), (1, 1), (2, 2)]))); - assert!(first_component_subsampled(&sof(&[(1, 2), (1, 2), (2, 1)]))); - assert!(!first_component_subsampled(&sof(&[(2, 2), (1, 1), (1, 1)]))); - assert!(!first_component_subsampled(&sof(&[(1, 1); 4]))); - assert!(!first_component_subsampled(&sof(&[]))); + assert!(first_component_subsampled(&progressive_frame_header(&[(1, 1), (1, 1), (1, 1), (2, 2)]))); + assert!(first_component_subsampled(&progressive_frame_header(&[(1, 2), (1, 2), (2, 1)]))); + assert!(!first_component_subsampled(&progressive_frame_header(&[(2, 2), (1, 1), (1, 1)]))); + assert!(!first_component_subsampled(&progressive_frame_header(&[(1, 1); 4]))); + assert!(!first_component_subsampled(&progressive_frame_header(&[]))); assert!(!first_component_subsampled(&[0xFF, 0xD8, 0xFF, 0xDA, 0, 2])); assert!(!first_component_subsampled(&[0xFF, 0xD8, 0xFF, 0xC0, 0, 20, 8])); assert!(!first_component_subsampled(b"not a jpeg")); } + #[test] + fn renderer_validation_refuses_unsafe_sampling_under_abort_policy() { + // The frame header alone exercises refusal before any pixel decode. + let header = progressive_frame_header(&[(1, 1), (1, 1), (1, 1), (2, 2)]); + let refuses_sampling = |result| { + matches!( + result, + Err(CodecError::Malformed { format: Format::Jpeg, message }) + if message == "JPEG first component is subsampled below the frame maximum" + ) + }; + assert!(refuses_sampling(validate_jpeg_rgba8_with_panic_policy(&header, 64, true))); + assert!(!refuses_sampling(validate_jpeg_rgba8_with_panic_policy(&header, 64, false))); + + let mut ordinary = Vec::new(); + jpeg_encoder::Encoder::new(&mut ordinary, 90).encode(&[128], 1, 1, jpeg_encoder::ColorType::Luma).unwrap(); + validate_jpeg_rgba8_with_panic_policy(&ordinary, 1, true).unwrap(); + } + + #[test] + fn jpeg_sampling_guard_finds_frame_after_marker_padding() { + let header = progressive_frame_header(&[(1, 1), (1, 1), (1, 1), (2, 2)]); + // Exercise the shared header guard, without a pixel payload. + for split in [2, 8] { + let (before, after) = header.split_at(split); + for padding in [&[0][..], &[0x7F, 0][..], &[0xFF, 0][..], &[0xFF][..]] { + let padded = [before, padding, after].concat(); + assert!(first_component_subsampled(&padded), "offset {split}, padding {padding:?}"); + let got = validate_jpeg_rgba8_with_panic_policy(&padded, 64, true); + assert!(matches!(got, Err(CodecError::Malformed { message, .. }) if message.contains("frame maximum"))); + } + } + assert!(!first_component_subsampled(&[0xFF, 0xD8, 0, 0xFF])); + } + #[test] fn routing() { assert!(!uses_craft_jpeg(&[0xFF, 0xD8, 0xFF, 0xC0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0])); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index dc2ac29339..032289c7c1 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -45,6 +45,7 @@ pub use crate::cicp::ContentLightLevel; pub use crate::codecs::avif::{HDR_REFERENCE_WHITE_NITS, HdrTransfer, encode_avif_hdr, encode_avif_with_speed}; pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color}; pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES}; +pub use crate::codecs::jpeg::validate_jpeg_rgba8; pub use crate::codecs::png::{ PngDecodeRows, PngExtras, PngHeader, PngPalette, PngRowSink, PngRows, SharedBytes, encode_indexed as encode_png_indexed, encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, @@ -307,6 +308,15 @@ pub fn jpeg_info(bytes: &[u8]) -> Option { jpeg::info(bytes) } +/// Bytes of DCT coefficients to budget for a JPEG before decoding it: never less than +/// [`JpegInfo::held_coefficients`] nor than the whole-picture estimate of every progressive +/// frame header (SOF2, SOF6, SOF10, SOF14 at any precision, sampling clamped to 1..=4), and the +/// costliest frame at the first size read when the header can't be followed. 0 without a +/// readable frame. See the function body's rules for the precise charges. +pub fn jpeg_worst_case_coefficients(bytes: &[u8]) -> u64 { + jpeg::worst_case_coefficients(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) diff --git a/crates/image-codecs/src/png_probe.rs b/crates/image-codecs/src/png_probe.rs index 73f1199eb6..e7af74334b 100644 --- a/crates/image-codecs/src/png_probe.rs +++ b/crates/image-codecs/src/png_probe.rs @@ -136,6 +136,93 @@ pub fn color_chunks(b: &[u8]) -> Option { Some(result) } +/// Most chunks [`pixel_model`] walks before the image data; each chunk is at least 12 bytes. +const MAX_PROBE_CHUNKS: usize = 1 << 16; + +/// Pixel model of a PNG, from `IHDR` and the chunk headers before the first `IDAT`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PixelModel { + pub width: u32, + pub height: u32, + /// `IHDR` bit depth (1, 2, 4, 8 or 16). + pub bit_depth: u8, + /// `IHDR` colour type (0 grey, 2 RGB, 3 palette, 4 grey+alpha, 6 RGBA). + pub color_type: u8, + /// A `tRNS` chunk precedes the image data; it adds alpha to grey, RGB and palette images. + pub has_trns: bool, +} + +impl PixelModel { + /// Channels of the decoded buffer (palette expands to RGB; `tRNS` adds an alpha channel). + pub fn channels(&self) -> u8 { + let base = match self.color_type { + 0 => 1, + 2 | 3 => 3, + 4 => 2, + _ => 4, + }; + base + u8::from(self.has_trns && matches!(self.color_type, 0 | 2 | 3)) + } + + /// Bytes per pixel of the buffer a decoder that expands sub-byte samples to 8 bits gives: + /// `channels * (2 if bit_depth == 16 else 1)`. + pub fn bytes_per_pixel(&self) -> u8 { + self.channels() * if self.bit_depth == 16 { 2 } else { 1 } + } + + /// Whether the image has transparency (alpha colour type or `tRNS`). + pub fn has_alpha(&self) -> bool { + matches!(self.color_type, 4 | 6) || self.has_trns + } +} + +/// Dimensions, bit depth, colour type and `tRNS` presence without inflating anything (an `iCCP` +/// profile is skipped, not decompressed). Walks at most 65,536 chunk headers and stops at `IDAT`; +/// `IEND` or the end of the input before `IDAT` is an error. Does not validate CRCs. +/// A caller gets its `(width, height, bytes_per_pixel, alpha)` as +/// `(m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha())`. +pub fn pixel_model(b: &[u8]) -> Result { + if !b.starts_with(b"\x89PNG\r\n\x1a\n") { + return Err(err("bad signature")); + } + let be32 = |p: usize| b.get(p..p.checked_add(4)?).and_then(|v| <[u8; 4]>::try_from(v).ok()).map(u32::from_be_bytes); + if be32(8) != Some(13) || b.get(12..16) != Some(b"IHDR") { + return Err(err("missing IHDR")); + } + let ihdr = b.get(16..29).ok_or_else(|| err("truncated IHDR"))?; + let (width, height) = (be32(16).unwrap_or(0), be32(20).unwrap_or(0)); + let (bit_depth, color_type) = (ihdr[8], ihdr[9]); + if width == 0 || height == 0 || width > i32::MAX as u32 || height > i32::MAX as u32 { + return Err(err("dimensions out of range")); + } + let depth_ok = match color_type { + 0 => matches!(bit_depth, 1 | 2 | 4 | 8 | 16), + 3 => matches!(bit_depth, 1 | 2 | 4 | 8), + 2 | 4 | 6 => matches!(bit_depth, 8 | 16), + _ => false, + }; + if !depth_ok { + return Err(err("invalid IHDR")); + } + let mut has_trns = false; + let mut p = 8usize; + for _ in 0..MAX_PROBE_CHUNKS { + let len = be32(p).ok_or_else(|| err("truncated"))?; + let kind = p.checked_add(4).and_then(|k| b.get(k..k.checked_add(4)?)).ok_or_else(|| err("truncated"))?; + match kind { + b"IDAT" => return Ok(PixelModel { width, height, bit_depth, color_type, has_trns }), + b"IEND" => return Err(err("no image data")), + b"tRNS" => has_trns = true, + _ => {} + } + if len > i32::MAX as u32 { + return Err(err("chunk length out of range")); + } + p = p.checked_add(12).and_then(|q| q.checked_add(len as usize)).ok_or_else(|| err("truncated"))?; + } + Err(CodecError::LimitExceeded("PNG chunk count".into())) +} + #[cfg(test)] mod tests { use super::*; @@ -187,4 +274,140 @@ mod tests { assert!(!color.srgb); assert!(color_chunks(b"not png").is_none()); } + + /// WordCraft's `png_chunks` (crates/geom/src/picture.rs) as the differential oracle. + fn oracle(bytes: &[u8]) -> Option<(u32, u32, u64, bool)> { + let be = |at: usize| bytes.get(at..at.checked_add(4)?).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes); + if bytes.get(12..16) != Some(b"IHDR".as_slice()) { + return None; + } + let (width, height) = (be(16)?, be(20)?); + let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?); + let mut trns = false; + let mut at = 8usize; + loop { + let len = usize::try_from(be(at)?).ok()?; + match bytes.get(at.checked_add(4)?..at.checked_add(8)?)? { + b"IDAT" => break, + b"IEND" => return None, + b"tRNS" => trns = true, + _ => {} + } + at = at.checked_add(12)?.checked_add(len)?; + } + let (channels, alpha) = match color { + 0 => (1 + u64::from(trns), trns), + 2 | 3 => (3 + u64::from(trns), trns), + 4 => (2, true), + 6 => (4, true), + _ => return None, + }; + Some((width, height, channels * if depth == 16 { 2 } else { 1 }, alpha)) + } + + fn tuple(b: &[u8]) -> Option<(u32, u32, u64, bool)> { + pixel_model(b).ok().map(|m| (m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha())) + } + + fn png_with(depth: u8, color: u8, before_idat: &[(&[u8; 4], Vec)]) -> Vec { + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&5u32.to_be_bytes()); + ihdr.extend_from_slice(&7u32.to_be_bytes()); + ihdr.extend_from_slice(&[depth, color, 0, 0, 0]); + chunk(&mut bytes, b"IHDR", &ihdr); + for (k, d) in before_idat { + chunk(&mut bytes, k, d); + } + chunk(&mut bytes, b"IDAT", &[1, 2, 3]); + chunk(&mut bytes, b"IEND", &[]); + bytes + } + + #[test] + fn pixel_model_matches_oracle_for_every_color_type_depth_and_trns() { + let valid: [(u8, &[u8]); 5] = [(0, &[1, 2, 4, 8, 16]), (2, &[8, 16]), (3, &[1, 2, 4, 8]), (4, &[8, 16]), (6, &[8, 16])]; + for (color, depths) in valid { + for &depth in depths { + for trns in [false, true] { + let extra: Vec<(&[u8; 4], Vec)> = if trns { vec![(b"tRNS", vec![0, 0])] } else { vec![] }; + let bytes = png_with(depth, color, &extra); + assert!(tuple(&bytes).is_some(), "color {color} depth {depth}"); + assert_eq!(tuple(&bytes), oracle(&bytes), "color {color} depth {depth} trns {trns}"); + } + } + } + } + + #[test] + fn pixel_model_known_values() { + let m = pixel_model(&png_with(16, 2, &[(b"tRNS", vec![0; 6])])).unwrap(); + assert_eq!((m.width, m.height, m.channels(), m.bytes_per_pixel(), m.has_alpha()), (5, 7, 4, 8, true)); + let m = pixel_model(&png_with(4, 3, &[])).unwrap(); + assert_eq!((m.bytes_per_pixel(), m.has_alpha()), (3, false)); + } + + #[test] + fn pixel_model_skips_a_huge_iccp_without_inflating() { + let junk = vec![0xAB; 20 << 20]; + let bytes = png_with(8, 2, &[(b"iCCP", junk), (b"tRNS", vec![0; 6])]); + assert_eq!(tuple(&bytes), oracle(&bytes)); + assert_eq!(tuple(&bytes), Some((5, 7, 4, true))); + } + + #[test] + fn pixel_model_malformed_inputs_agree_with_oracle_and_never_panic() { + let full = png_with(8, 6, &[(b"tRNS", vec![0]), (b"gAMA", vec![0; 4])]); + for n in 0..=full.len() { + let cut = &full[..n]; + let got = tuple(cut); + // an Err where the oracle answers can only be a stricter header check + if got.is_some() { + assert_eq!(got, oracle(cut), "prefix {n}"); + } + } + assert!(pixel_model(&full[..33]).is_err()); + // missing IHDR + let mut bad = full.clone(); + bad[12..16].copy_from_slice(b"IHDX"); + assert!(pixel_model(&bad).is_err() && oracle(&bad).is_none()); + // chunk length overflow: a length past the input, then one past i32::MAX + for len in [u32::MAX, i32::MAX as u32, 0x7fff_fff0] { + let mut o = full.clone(); + o[33..37].copy_from_slice(&len.to_be_bytes()); + assert!(pixel_model(&o).is_err(), "len {len:#x}"); + assert_eq!(tuple(&o), oracle(&o)); + } + // IEND before IDAT, unknown colour type, zero size, bad signature + let mut iend = png_with(8, 2, &[]); + let at = iend.windows(4).position(|w| w == b"IDAT").unwrap(); + iend[at..at + 4].copy_from_slice(b"IEND"); + assert!(pixel_model(&iend).is_err() && oracle(&iend).is_none()); + assert!(pixel_model(&png_with(8, 5, &[])).is_err()); + let mut zero = png_with(8, 2, &[]); + zero[16..20].copy_from_slice(&0u32.to_be_bytes()); + assert!(pixel_model(&zero).is_err()); + assert!(pixel_model(b"not a png").is_err()); + // deterministic pseudo-random corruption + let mut s = 0x9e37_79b9u32; + for _ in 0..2000 { + let mut f = full.clone(); + for _ in 0..3 { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let i = (s >> 8) as usize % f.len(); + f[i] = (s >> 24) as u8; + } + let _ = pixel_model(&f); + } + } + + #[test] + fn pixel_model_many_tiny_chunks_and_the_chunk_cap() { + let many: Vec<(&[u8; 4], Vec)> = (0..10_000).map(|_| (b"tEXt", Vec::new())).chain([(b"tRNS", vec![0])]).collect(); + let bytes = png_with(8, 0, &many); + assert_eq!(tuple(&bytes), oracle(&bytes)); + assert_eq!(tuple(&bytes), Some((5, 7, 2, true))); + let over: Vec<(&[u8; 4], Vec)> = (0..MAX_PROBE_CHUNKS + 1).map(|_| (b"tEXt", Vec::new())).collect(); + assert!(matches!(pixel_model(&png_with(8, 0, &over)), Err(CodecError::LimitExceeded(_)))); + } } diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 4a31def009..1c22411dc0 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -32,6 +32,25 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { Ok((w, h, orientation)) } +/// Whether a WebP carries transparency, from the first chunk only (nothing is decoded): +/// `VP8X` flag bit 0x10, `VP8L` `alpha_is_used`, plain `VP8` never. +pub fn has_alpha(bytes: &[u8]) -> Result { + let err = |s: &str| CodecError::malformed(Format::WebP, s); + if bytes.get(..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WEBP") { + return Err(err("bad signature")); + } + match bytes.get(12..16) { + Some(b"VP8X") => Ok(bytes.get(20).ok_or_else(|| err("truncated VP8X"))? & 0x10 != 0), + // 0x2f signature byte, then 14+14 size bits, then the alpha_is_used bit (bit 28) + Some(b"VP8L") => match bytes.get(20..25) { + Some([0x2f, a, b, c, d]) => Ok(u32::from_le_bytes([*a, *b, *c, *d]) >> 28 & 1 != 0), + _ => Err(err("bad VP8L header")), + }, + Some(b"VP8 ") => Ok(false), + _ => Err(err("no image data")), + } +} + #[cfg(test)] mod tests { use super::*; @@ -71,4 +90,39 @@ mod tests { bytes.push(0); assert!(header(&bytes).is_err()); } + + #[test] + fn has_alpha_reads_vp8x_vp8l_and_plain_vp8() { + for (layout, want) in [(crate::ChannelLayout::Rgb, false), (crate::ChannelLayout::Rgba, true)] { + let n = layout.channels(); + let image = crate::Image::from_u8(2, 3, layout, vec![42; 6 * n]).unwrap(); + let bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + assert_eq!(has_alpha(&bytes).unwrap(), want); + } + let riff = |chunk: &[u8; 4], body: &[u8]| { + let mut v = b"RIFF\0\0\0\0WEBP".to_vec(); + v.extend_from_slice(chunk); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v + }; + let mut x = [0u8; 10]; + assert!(!has_alpha(&riff(b"VP8X", &x)).unwrap()); + x[0] = 0x10; + assert!(has_alpha(&riff(b"VP8X", &x)).unwrap()); + assert!(!has_alpha(&riff(b"VP8 ", &[0; 10])).unwrap()); + assert!(has_alpha(&riff(b"VP8L", &[0x2f, 0, 0, 0, 0x10])).unwrap()); + assert!(!has_alpha(&riff(b"VP8L", &[0x2f, 0, 0, 0, 0])).unwrap()); + } + + #[test] + fn has_alpha_rejects_malformed_prefixes() { + let full = [b"RIFF\0\0\0\0WEBPVP8X\x0a\0\0\0".as_slice(), &[0x10; 10]].concat(); + for n in 0..20 { + assert!(has_alpha(&full[..n]).is_err(), "prefix {n}"); + } + assert!(has_alpha(&full[..21]).is_ok()); + assert!(has_alpha(b"RIFF\0\0\0\0WEBPVP8L\x05\0\0\0\x2e").is_err()); + assert!(has_alpha(b"junk").is_err()); + } } diff --git a/crates/image-codecs/tests/it/malformed.rs b/crates/image-codecs/tests/it/malformed.rs index ec06109e00..b247bdfc6c 100644 --- a/crates/image-codecs/tests/it/malformed.rs +++ b/crates/image-codecs/tests/it/malformed.rs @@ -76,9 +76,11 @@ fn truncated_files_mostly_error() { #[test] fn bit_flips_never_panic() { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs 1/N of the flips. + let rounds = 150usize.div_ceil(craft_media_testkit::hostile::divisor()); let mut rng = common::Rng::new(42); for (f, bytes) in samples() { - for _ in 0..150 { + for _ in 0..rounds { let mut b = bytes.clone(); let flips = 1 + (rng.next_u64() % 4) as usize; for _ in 0..flips { @@ -92,8 +94,11 @@ fn bit_flips_never_panic() { #[test] fn byte_overwrites_in_header_never_panic() { - for (f, bytes) in samples() { - for i in 0..bytes.len().min(64) { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) overwrites every N-th byte, from a different offset + // for each sample, so the samples together still reach every header position. + let step = craft_media_testkit::hostile::divisor(); + for (k, (f, bytes)) in samples().into_iter().enumerate() { + for i in (0..bytes.len().min(64)).filter(|i| (i + k) % step == 0) { for v in [0x00, 0x7F, 0xFF] { let mut b = bytes.clone(); b[i] = v; diff --git a/crates/image-codecs/tests/it/tiff_pages.rs b/crates/image-codecs/tests/it/tiff_pages.rs index 7501be9365..7f6708f88f 100644 --- a/crates/image-codecs/tests/it/tiff_pages.rs +++ b/crates/image-codecs/tests/it/tiff_pages.rs @@ -820,15 +820,18 @@ fn poke(bytes: &[u8]) { #[test] fn zoo_decodes_and_never_panics_when_cut_or_corrupted() { - for f in zoo() { + // CRAFT_HOSTILE_DIVISOR=N (pull requests) runs every N-th cut and flip, from a different offset + // for each file, and 1/N of the random rounds. + let step = craft_media_testkit::hostile::divisor(); + for (k, f) in zoo().into_iter().enumerate() { let info = tiff_info(&f).unwrap(); for i in 0..info.pages.len() { decode_tiff_page(&f, i, &DecodeOptions::default()).unwrap(); } - for cut in 0..f.len() { + for cut in (0..f.len()).filter(|cut| (cut + k) % step == 0) { poke(&f[..cut]); } - for i in 0..f.len() { + for i in (0..f.len()).filter(|i| (i + k) % step == 0) { for flip in [0xffu8, 0x80, 0x01] { let mut g = f.clone(); g[i] ^= flip; @@ -836,7 +839,7 @@ fn zoo_decodes_and_never_panics_when_cut_or_corrupted() { } } let mut r = Rng::new(f.len() as u64); - for _ in 0..300 { + for _ in 0..300usize.div_ceil(step) { let mut g = f.clone(); for _ in 0..4 { let i = (r.next_u64() as usize) % g.len(); diff --git a/crates/java-class/Cargo.toml b/crates/java-class/Cargo.toml new file mode 100644 index 0000000000..1a5144fc39 --- /dev/null +++ b/crates/java-class/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name="craft-java-class" +description="Java class-file inspection and JVM bytecode decoding with retained bounds and partial reports" +version.workspace=true +edition.workspace=true +license.workspace=true +rust-version.workspace=true +repository.workspace=true +[lints] +workspace=true +[dependencies] +serde={workspace=true} +thiserror={workspace=true} +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/java-class/src/bytes.rs b/crates/java-class/src/bytes.rs new file mode 100644 index 0000000000..bc26aea19f --- /dev/null +++ b/crates/java-class/src/bytes.rs @@ -0,0 +1,51 @@ +//! 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 slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_be(&self, off: usize) -> Option { + self.arr(off).map(u16::from_be_bytes) + } + + pub fn u32_be(&self, off: usize) -> Option { + self.arr(off).map(u32::from_be_bytes) + } + + pub fn u64_be(&self, off: usize) -> Option { + self.arr(off).map(u64::from_be_bytes) + } +} + +/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves, +/// so a damaged sequence cannot hide valid text or borrow missing bytes. +pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) { + match bytes { + [a @ 0x00..=0x7f, ..] => (u16::from(*a), 1), + [0xc0, 0x80, ..] => (0, 2), + [a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2), + [a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => { + ((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3) + } + _ => (0xfffd, 1), + } +} diff --git a/crates/java-class/src/descriptor.rs b/crates/java-class/src/descriptor.rs new file mode 100644 index 0000000000..3f4b32bd79 --- /dev/null +++ b/crates/java-class/src/descriptor.rs @@ -0,0 +1,19 @@ +// Descriptor display helper retained from the source DEX reader. +pub fn java_name(desc: &str) -> String { + let dims = desc.chars().take_while(|&c| c == '[').count(); + let base = desc.get(dims..).unwrap_or(""); + let name = match base { + "V" => "void".to_string(), + "Z" => "boolean".to_string(), + "B" => "byte".to_string(), + "S" => "short".to_string(), + "C" => "char".to_string(), + "I" => "int".to_string(), + "J" => "long".to_string(), + "F" => "float".to_string(), + "D" => "double".to_string(), + b if b.starts_with('L') && b.ends_with(';') => b.get(1..b.len() - 1).unwrap_or("").replace('/', "."), + b => b.to_string(), + }; + format!("{name}{}", "[]".repeat(dims.min(255))) +} diff --git a/crates/java-class/src/java_class.rs b/crates/java-class/src/java_class.rs new file mode 100644 index 0000000000..4b751ec3ee --- /dev/null +++ b/crates/java-class/src/java_class.rs @@ -0,0 +1,1082 @@ +//! Java `.class` files (JVMS): the magic and version, the constant pool (every tag including +//! `MethodHandle`/`MethodType`/`Dynamic`/`InvokeDynamic`/`Module`/`Package`), access flags, the +//! this/super class and interfaces, fields and methods with their attributes (`Code` with its +//! exception table and line numbers, `ConstantValue`, `Exceptions`, `Signature`), and the +//! class-level `SourceFile`, `InnerClasses` and annotation attributes (type names, best-effort). +//! +//! Counts and lengths are checked against the file size, strings are decoded from modified UTF-8, +//! and every read is bounds-checked, so hostile input yields warnings, not panics. + +use crate::bytes::Reader; +use crate::java_ops::{self, Insn}; +use crate::{FormatError, descriptor as dex}; +use serde::Serialize; + +/// Most constant-pool entries, fields, methods, attributes or interfaces we read from one file. +const MAX_ITEMS: usize = 1 << 20; +/// Most attributes per element. +const MAX_ATTRS: usize = 64 * 1024; +/// Deepest annotation/element-value nesting we walk. +const MAX_ANNO_DEPTH: usize = 32; + +/// One constant-pool entry. Index 0 and the slot after a `Long`/`Double` are `Unusable`. +#[derive(Debug, Clone, PartialEq)] +pub enum Const { + Unusable, + Utf8(String), + Integer(i32), + Float(f32), + Long(i64), + Double(f64), + /// `name_index` → a Utf8 internal name. + Class(u16), + /// `string_index` → a Utf8. + String(u16), + /// `class_index`, `name_and_type_index`. + FieldRef(u16, u16), + MethodRef(u16, u16), + InterfaceMethodRef(u16, u16), + /// `name_index`, `descriptor_index`. + NameAndType(u16, u16), + /// `reference_kind`, `reference_index`. + MethodHandle(u8, u16), + /// `descriptor_index`. + MethodType(u16), + /// `bootstrap_method_attr_index`, `name_and_type_index`. + Dynamic(u16, u16), + InvokeDynamic(u16, u16), + Module(u16), + Package(u16), +} + +/// The class-file version. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct Version { + pub major: u16, + pub minor: u16, +} + +impl Version { + /// A friendly Java platform label (`Java 8`, `Java 17`, `Java 1.3`). + pub fn java_label(self) -> String { + match self.major { + 45..=48 => format!("Java 1.{}", self.major - 44), + m if m >= 49 => format!("Java {}", m - 44), + m => format!("pre-standard (major {m})"), + } + } +} + +/// An exception-table row of a `Code` attribute. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ExceptionEntry { + pub start_pc: u16, + pub end_pc: u16, + pub handler_pc: u16, + /// Dotted caught type; `None` is catch-all (a `finally` or `catch (Throwable)` with index 0). + pub catch_type: Option, +} + +/// A parsed `Code` attribute. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Code { + pub max_stack: u16, + pub max_locals: u16, + pub bytecode: Vec, + pub exceptions: Vec, + /// `(start_pc, line)` from the `LineNumberTable`. + pub line_numbers: Vec<(u16, u16)>, +} + +/// A field or method. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Member { + pub access: u16, + pub name: String, + pub descriptor: String, + /// The generic `Signature` attribute, if present. + pub signature: Option, + /// A field's `ConstantValue`, rendered to text. + pub constant_value: Option, + /// A method's declared `throws` types (dotted). + pub exceptions: Vec, + /// A method's code. + pub code: Option, + pub deprecated: bool, + /// The `Synthetic` attribute (separate from the access flag). + pub synthetic_attr: bool, +} + +/// An `InnerClasses` row. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct InnerClass { + pub inner: Option, + pub outer: Option, + /// Simple name; `None` for an anonymous class. + pub name: Option, + pub access: u16, +} + +/// A parsed class file. +#[derive(Debug, Clone)] +pub struct ClassFile { + pub version: Version, + pub access: u16, + /// Internal name of this class (`com/example/Main`). + pub this_class: String, + /// Internal name of the superclass; `None` only for `java/lang/Object` and modules. + pub super_class: Option, + /// Internal names of the implemented interfaces. + pub interfaces: Vec, + pub fields: Vec, + pub methods: Vec, + pub source_file: Option, + pub signature: Option, + pub inner_classes: Vec, + /// Class-level annotation types (dotted), with `(runtime)`/`(class)` visibility. + pub annotations: Vec, + /// Bootstrap method handle and static arguments, indexed by dynamic pool constants. + pub bootstrap_methods: Vec<(u16, Vec)>, + pub pool: Vec, + pub warnings: Vec, +} + +// --------------------------------------------------------------------------------------------- +// Names, descriptors and access flags + +/// `java/lang/String` → `java.lang.String`; `[Ljava/lang/String;` → `java.lang.String[]`. +pub fn internal_to_dotted(name: &str) -> String { + if name.starts_with('[') { dex::java_name(name) } else { name.replace('/', ".") } +} + +/// A field descriptor (`Ljava/lang/String;`, `[I`, `I`) as a Java type. +pub fn field_type(desc: &str) -> String { + dex::java_name(desc) +} + +/// Read parameter descriptors up to the closing parenthesis and return the remaining return descriptor. +fn split_types(s: &str) -> Option<(Vec, &str)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0usize; + while i < b.len() && out.len() < MAX_ITEMS { + if b.get(i) == Some(&b')') { + return Some((out, s.get(i + 1..)?)); + } + let start = i; + while b.get(i) == Some(&b'[') { + i += 1; + } + match b.get(i) { + Some(b'L') => match s.get(i..).and_then(|r| r.find(';')) { + Some(semi) => i = i + semi + 1, + None => i = b.len(), + }, + Some(_) => i += 1, + None => break, + } + match s.get(start..i) { + Some(t) if !t.is_empty() => out.push(t.to_string()), + _ => break, + } + } + None +} + +/// Parameter types and return type of a method descriptor (`(Ljava/lang/String;I)V`). +pub fn method_params(desc: &str) -> (Vec, String) { + let Some(rest) = desc.strip_prefix('(') else { return (Vec::new(), "?".into()) }; + let Some((params, ret)) = split_types(rest) else { return (Vec::new(), "?".into()) }; + (params.iter().map(|t| field_type(t)).collect(), field_type(ret)) +} + +/// What a set of access flags belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AccessKind { + Class, + Field, + Method, + InnerClass, +} + +/// Human names of the set access flags. +pub fn access_flags(flags: u16, kind: AccessKind) -> Vec<&'static str> { + let mut v = Vec::new(); + let common: &[(u16, &str)] = &[(0x0001, "public"), (0x0002, "private"), (0x0004, "protected"), (0x0008, "static"), (0x0010, "final")]; + for (bit, name) in common { + if flags & bit != 0 { + v.push(*name); + } + } + match kind { + AccessKind::Method => { + for (bit, name) in [ + (0x0020u16, "synchronized"), + (0x0040, "bridge"), + (0x0080, "varargs"), + (0x0100, "native"), + (0x0400, "abstract"), + (0x0800, "strictfp"), + (0x1000, "synthetic"), + ] { + if flags & bit != 0 { + v.push(name); + } + } + } + AccessKind::Field => { + for (bit, name) in [(0x0040u16, "volatile"), (0x0080, "transient"), (0x1000, "synthetic"), (0x4000, "enum")] { + if flags & bit != 0 { + v.push(name); + } + } + } + AccessKind::Class | AccessKind::InnerClass => { + for (bit, name) in [ + (0x0020u16, "super"), + (0x0200, "interface"), + (0x0400, "abstract"), + (0x1000, "synthetic"), + (0x2000, "annotation"), + (0x4000, "enum"), + (0x8000, "module"), + ] { + if flags & bit != 0 { + // "super" is an internal marker on classes; hide it unless it is the only flag of note. + if name == "super" && kind == AccessKind::Class { + continue; + } + v.push(name); + } + } + } + } + v +} + +/// A resolved reference to a field or method. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Ref { + /// Internal owner name (`java/lang/System`). + pub owner: String, + pub name: String, + pub descriptor: String, +} + +impl Ref { + /// `java.lang.System.out:java.io.PrintStream` style display. A field descriptor is shown as a + /// Java type; a method descriptor is left in its raw `(args)ret` form. + pub fn display(&self) -> String { + let ty = if self.descriptor.starts_with('(') { self.descriptor.clone() } else { field_type(&self.descriptor) }; + format!("{}.{}:{}", internal_to_dotted(&self.owner), self.name, ty) + } +} + +// --------------------------------------------------------------------------------------------- +// Modified UTF-8 + +/// Decode a modified-UTF-8 byte run (class-file `Utf8` content) to a String. +fn decode_mutf8(bytes: &[u8]) -> String { + let mut units: Vec = Vec::new(); + let mut i = 0usize; + while i < bytes.len() { + let (unit, consumed) = crate::bytes::mutf8_unit(bytes.get(i..).unwrap_or_default()); + units.push(unit); + i += consumed; + } + String::from_utf16_lossy(&units) +} + +// --------------------------------------------------------------------------------------------- +// Cursor + +struct Cursor<'a> { + r: Reader<'a>, + pos: usize, +} + +impl<'a> Cursor<'a> { + fn new(data: &'a [u8]) -> Self { + Cursor { r: Reader::new(data), pos: 0 } + } + fn u8(&mut self) -> Option { + let v = self.r.u8(self.pos)?; + self.pos += 1; + Some(v) + } + fn u16(&mut self) -> Option { + let v = self.r.u16_be(self.pos)?; + self.pos += 2; + Some(v) + } + fn u32(&mut self) -> Option { + let v = self.r.u32_be(self.pos)?; + self.pos += 4; + Some(v) + } + fn u64(&mut self) -> Option { + let v = self.r.u64_be(self.pos)?; + self.pos += 8; + Some(v) + } + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let s = self.r.slice(self.pos, n)?; + self.pos += n; + Some(s) + } +} + +// --------------------------------------------------------------------------------------------- +// Parsing + +/// True when the bytes begin a Java class file (0xCAFEBABE and a plausible major version). +/// A big-endian Mach-O fat binary shares the magic but has a small arch count where the version +/// is, so it fails the major-version check. +pub fn is_class(data: &[u8]) -> bool { + if !data.starts_with(&[0xca, 0xfe, 0xba, 0xbe]) { + return false; + } + let r = Reader::new(data); + matches!(r.u16_be(6), Some(major) if (45..=255).contains(&major)) +} + +fn utf8_of(pool: &[Const], idx: u16) -> &str { + match pool.get(idx as usize) { + Some(Const::Utf8(s)) => s.as_str(), + _ => "", + } +} + +/// Parse a class file. +pub fn parse(data: &[u8]) -> Result { + if !data.starts_with(&[0xca, 0xfe, 0xba, 0xbe]) { + return Err(FormatError::Malformed("not a Java class file (no 0xCAFEBABE magic)".into())); + } + let mut c = Cursor::new(data); + let mut warnings = Vec::new(); + let _magic = c.u32(); + let minor = c.u16().ok_or_else(|| FormatError::Truncated("version".into()))?; + let major = c.u16().ok_or_else(|| FormatError::Truncated("version".into()))?; + if major < 45 { + return Err(FormatError::Unsupported(format!("class major version {major} is below 45 (not a standard class file)"))); + } + let version = Version { major, minor }; + let cp_count = c.u16().ok_or_else(|| FormatError::Truncated("constant pool count".into()))?; + if cp_count == 0 { + return Err(FormatError::Malformed("constant pool count is zero".into())); + } + let pool = parse_pool(&mut c, cp_count, &mut warnings)?; + let access = c.u16().ok_or_else(|| FormatError::Truncated("access flags".into()))?; + let this_idx = c.u16().ok_or_else(|| FormatError::Truncated("this_class".into()))?; + let super_idx = c.u16().ok_or_else(|| FormatError::Truncated("super_class".into()))?; + let this_class = class_name_at(&pool, this_idx); + let super_class = if super_idx == 0 { None } else { Some(class_name_at(&pool, super_idx)) }; + // Interfaces + let n_iface = c.u16().ok_or_else(|| FormatError::Truncated("interfaces count".into()))? as usize; + let mut interfaces = Vec::new(); + for _ in 0..n_iface.min(MAX_ITEMS) { + let Some(i) = c.u16() else { + warnings.push("interface list ended early".into()); + break; + }; + interfaces.push(class_name_at(&pool, i)); + } + // Fields + let fields = parse_members(&mut c, &pool, &mut warnings, "field")?; + // Methods + let methods = parse_members(&mut c, &pool, &mut warnings, "method")?; + // Class attributes + let (attrs, complete) = read_attrs(&mut c, &pool); + if !complete { + warnings.push("class attribute table ended early".into()); + } + let mut source_file = None; + let mut signature = None; + let mut inner_classes = Vec::new(); + let mut annotations = Vec::new(); + let mut bootstrap_methods = Vec::new(); + for a in &attrs { + match a.name { + "SourceFile" => { + if let Some(i) = Reader::new(a.info).u16_be(0) { + source_file = Some(utf8_of(&pool, i).to_string()); + } + } + "Signature" => { + if let Some(i) = Reader::new(a.info).u16_be(0) { + signature = Some(utf8_of(&pool, i).to_string()); + } + } + "BootstrapMethods" => match bootstrap_table(a.info) { + Some(table) => bootstrap_methods = table, + None => warnings.push("invalid BootstrapMethods table".into()), + }, + "InnerClasses" => inner_classes = parse_inner_classes(a.info, &pool), + "RuntimeVisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "runtime")), + "RuntimeInvisibleAnnotations" => annotations.extend(parse_annotation_types(a.info, &pool, "class")), + _ => {} + } + } + Ok(ClassFile { + version, + access, + this_class, + super_class, + interfaces, + fields, + methods, + source_file, + signature, + inner_classes, + annotations, + bootstrap_methods, + pool, + warnings, + }) +} + +fn parse_pool(c: &mut Cursor<'_>, cp_count: u16, warnings: &mut Vec) -> Result, FormatError> { + let mut pool = vec![Const::Unusable]; // index 0 + let mut i = 1u16; + while i < cp_count { + let tag = c.u8().ok_or_else(|| FormatError::Truncated("constant pool entry".into()))?; + let entry = match tag { + 1 => { + let len = c.u16().ok_or_else(|| FormatError::Truncated("Utf8 length".into()))? as usize; + let bytes = c.take(len).ok_or_else(|| FormatError::Truncated("Utf8 bytes".into()))?; + Const::Utf8(decode_mutf8(bytes)) + } + 3 => Const::Integer(c.u32().ok_or_else(|| trunc("Integer"))? as i32), + 4 => Const::Float(f32::from_bits(c.u32().ok_or_else(|| trunc("Float"))?)), + 5 => Const::Long(c.u64().ok_or_else(|| trunc("Long"))? as i64), + 6 => Const::Double(f64::from_bits(c.u64().ok_or_else(|| trunc("Double"))?)), + 7 => Const::Class(c.u16().ok_or_else(|| trunc("Class"))?), + 8 => Const::String(c.u16().ok_or_else(|| trunc("String"))?), + 9 => Const::FieldRef(c.u16().ok_or_else(|| trunc("Fieldref"))?, c.u16().ok_or_else(|| trunc("Fieldref"))?), + 10 => Const::MethodRef(c.u16().ok_or_else(|| trunc("Methodref"))?, c.u16().ok_or_else(|| trunc("Methodref"))?), + 11 => Const::InterfaceMethodRef(c.u16().ok_or_else(|| trunc("InterfaceMethodref"))?, c.u16().ok_or_else(|| trunc("InterfaceMethodref"))?), + 12 => Const::NameAndType(c.u16().ok_or_else(|| trunc("NameAndType"))?, c.u16().ok_or_else(|| trunc("NameAndType"))?), + 15 => Const::MethodHandle(c.u8().ok_or_else(|| trunc("MethodHandle"))?, c.u16().ok_or_else(|| trunc("MethodHandle"))?), + 16 => Const::MethodType(c.u16().ok_or_else(|| trunc("MethodType"))?), + 17 => Const::Dynamic(c.u16().ok_or_else(|| trunc("Dynamic"))?, c.u16().ok_or_else(|| trunc("Dynamic"))?), + 18 => Const::InvokeDynamic(c.u16().ok_or_else(|| trunc("InvokeDynamic"))?, c.u16().ok_or_else(|| trunc("InvokeDynamic"))?), + 19 => Const::Module(c.u16().ok_or_else(|| trunc("Module"))?), + 20 => Const::Package(c.u16().ok_or_else(|| trunc("Package"))?), + other => { + return Err(FormatError::Malformed(format!("unknown constant pool tag {other} at index {i}"))); + } + }; + let wide = matches!(entry, Const::Long(_) | Const::Double(_)); + let next = i + .checked_add(if wide { 2 } else { 1 }) + .filter(|next| *next <= cp_count) + .ok_or_else(|| FormatError::Malformed(format!("constant pool entry {i} has no reserved second slot")))?; + pool.push(entry); + if wide { + pool.push(Const::Unusable); + } + i = next; + } + if pool.len() > MAX_ITEMS { + warnings.push("constant pool is unusually large".into()); + } + Ok(pool) +} + +fn trunc(what: &str) -> FormatError { + FormatError::Truncated(format!("constant pool {what}")) +} + +struct RawAttr<'a, 'p> { + // Many attributes can reference one long constant-pool name. The pool + // already owns it for the entire parse; a per-attribute copy amplifies it. + name: &'p str, + info: &'a [u8], +} + +/// Return the complete attributes in the readable prefix and whether the whole table was read. +fn read_attrs<'a, 'p>(c: &mut Cursor<'a>, pool: &'p [Const]) -> (Vec>, bool) { + let mut out = Vec::new(); + let Some(n) = c.u16().map(usize::from) else { return (out, false) }; + for _ in 0..n.min(MAX_ATTRS) { + let (Some(ni), Some(len)) = (c.u16(), c.u32()) else { return (out, false) }; + let Some(info) = c.take(len as usize) else { return (out, false) }; + out.push(RawAttr { name: utf8_of(pool, ni), info }); + } + (out, n <= MAX_ATTRS) +} + +fn bootstrap_table(data: &[u8]) -> Option)>> { + let mut cursor = Cursor::new(data); + let mut table = Vec::new(); + for _ in 0..cursor.u16()? { + let handle = cursor.u16()?; + let count = usize::from(cursor.u16()?); + let args = cursor.take(count * 2)?.as_chunks::<2>().0.iter().map(|b| u16::from_be_bytes(*b)).collect(); + table.push((handle, args)); + } + (cursor.pos == data.len()).then_some(table) +} + +fn parse_members(c: &mut Cursor<'_>, pool: &[Const], warnings: &mut Vec, what: &str) -> Result, FormatError> { + let n = c.u16().ok_or_else(|| FormatError::Truncated(format!("{what} count")))? as usize; + let mut out = Vec::new(); + for _ in 0..n.min(MAX_ITEMS) { + let (Some(access), Some(name_idx), Some(desc_idx)) = (c.u16(), c.u16(), c.u16()) else { + warnings.push(format!("{what} table ended early")); + break; + }; + let mut m = + Member { access, name: utf8_of(pool, name_idx).to_string(), descriptor: utf8_of(pool, desc_idx).to_string(), ..Default::default() }; + let (attrs, _) = read_attrs(c, pool); + for a in attrs { + match a.name { + "Code" => m.code = parse_code(a.info, pool), + "ConstantValue" => { + if let Some(i) = Reader::new(a.info).u16_be(0) { + m.constant_value = Some(const_display(pool, i)); + } + } + "Exceptions" => m.exceptions = parse_exceptions_attr(a.info, pool), + "Signature" => { + if let Some(i) = Reader::new(a.info).u16_be(0) { + m.signature = Some(utf8_of(pool, i).to_string()); + } + } + "Deprecated" => m.deprecated = true, + "Synthetic" => m.synthetic_attr = true, + _ => {} + } + } + out.push(m); + } + Ok(out) +} + +fn parse_code(info: &[u8], pool: &[Const]) -> Option { + let mut c = Cursor::new(info); + let max_stack = c.u16()?; + let max_locals = c.u16()?; + let code_len = c.u32()? as usize; + let bytecode = c.take(code_len)?.to_vec(); + let n_exc = c.u16()? as usize; + let mut exceptions = Vec::new(); + for _ in 0..n_exc.min(MAX_ITEMS) { + let (Some(start_pc), Some(end_pc), Some(handler_pc), Some(catch)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; + exceptions.push(ExceptionEntry { start_pc, end_pc, handler_pc, catch_type: (catch != 0).then(|| class_name_at(pool, catch)) }); + } + let mut line_numbers = Vec::new(); + let (attrs, _) = read_attrs(&mut c, pool); + for a in attrs { + if a.name == "LineNumberTable" { + let mut lc = Cursor::new(a.info); + let n = lc.u16().unwrap_or(0) as usize; + for _ in 0..n.min(MAX_ITEMS) { + let (Some(pc), Some(line)) = (lc.u16(), lc.u16()) else { break }; + line_numbers.push((pc, line)); + } + } + } + Some(Code { max_stack, max_locals, bytecode, exceptions, line_numbers }) +} + +fn parse_exceptions_attr(info: &[u8], pool: &[Const]) -> Vec { + let mut c = Cursor::new(info); + let n = c.u16().unwrap_or(0) as usize; + let mut out = Vec::new(); + for _ in 0..n.min(MAX_ITEMS) { + let Some(i) = c.u16() else { break }; + out.push(class_name_at(pool, i)); + } + out +} + +fn parse_inner_classes(info: &[u8], pool: &[Const]) -> Vec { + let mut c = Cursor::new(info); + let n = c.u16().unwrap_or(0) as usize; + let mut out = Vec::new(); + for _ in 0..n.min(MAX_ITEMS) { + let (Some(inner), Some(outer), Some(name), Some(access)) = (c.u16(), c.u16(), c.u16(), c.u16()) else { break }; + out.push(InnerClass { + inner: (inner != 0).then(|| class_name_at(pool, inner)), + outer: (outer != 0).then(|| class_name_at(pool, outer)), + name: (name != 0).then(|| utf8_of(pool, name).to_string()), + access, + }); + } + out +} + +/// Extract annotation type names (dotted) from a `Runtime*Annotations` attribute, best-effort. +fn parse_annotation_types(info: &[u8], pool: &[Const], visibility: &str) -> Vec { + let mut c = Cursor::new(info); + let n = c.u16().unwrap_or(0) as usize; + let mut out = Vec::new(); + for _ in 0..n.min(MAX_ITEMS) { + match read_annotation(&mut c, pool, 0) { + Some(t) => out.push(format!("{t} ({visibility})")), + None => break, + } + } + out +} + +/// Read one `annotation` structure, returning its (dotted) type name; advances past its values. +fn read_annotation(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option { + if depth > MAX_ANNO_DEPTH { + return None; + } + let type_idx = c.u16()?; + let n_pairs = c.u16()? as usize; + let type_name = field_type(utf8_of(pool, type_idx)); + for _ in 0..n_pairs.min(MAX_ITEMS) { + let _name_idx = c.u16()?; + skip_element_value(c, pool, depth + 1)?; + } + Some(type_name) +} + +fn skip_element_value(c: &mut Cursor<'_>, pool: &[Const], depth: usize) -> Option<()> { + if depth > MAX_ANNO_DEPTH { + return None; + } + let tag = c.u8()?; + match tag { + b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' | b's' | b'c' => { + c.u16()?; + } + b'e' => { + c.u16()?; + c.u16()?; + } + b'@' => { + read_annotation(c, pool, depth + 1)?; + } + b'[' => { + let n = c.u16()? as usize; + for _ in 0..n.min(MAX_ITEMS) { + skip_element_value(c, pool, depth + 1)?; + } + } + _ => return None, + } + Some(()) +} + +/// Internal class name at a `Class` constant index (`java/lang/String` or `[I`). +fn class_name_at(pool: &[Const], idx: u16) -> String { + match pool.get(idx as usize) { + Some(Const::Class(name_idx)) => utf8_of(pool, *name_idx).to_string(), + _ => format!(""), + } +} + +/// Render a loadable constant (for `ldc`/`ConstantValue`) to text. +fn const_display(pool: &[Const], idx: u16) -> String { + match pool.get(idx as usize) { + Some(Const::Integer(v)) => v.to_string(), + Some(Const::Float(v)) => format!("{v}f"), + Some(Const::Long(v)) => format!("{v}L"), + Some(Const::Double(v)) => v.to_string(), + Some(Const::String(s)) => format!("{:?}", utf8_of(pool, *s)), + Some(Const::Class(n)) => format!("{}.class", internal_to_dotted(utf8_of(pool, *n))), + Some(Const::MethodHandle(k, _)) => format!("MethodHandle(kind {k})"), + Some(Const::MethodType(d)) => format!("MethodType({})", utf8_of(pool, *d)), + _ => format!("#{idx}"), + } +} + +// --------------------------------------------------------------------------------------------- +// Resolution and formatting on a parsed class + +impl ClassFile { + /// The Utf8 at `idx`, or an empty string. + pub fn utf8(&self, idx: u16) -> &str { + utf8_of(&self.pool, idx) + } + + /// The dotted name of this class. + pub fn name_dotted(&self) -> String { + internal_to_dotted(&self.this_class) + } + + /// Resolve a `Fieldref`/`Methodref`/`InterfaceMethodref` index to owner, name and descriptor. + pub fn resolve_ref(&self, idx: u16) -> Option { + let (class_idx, nat_idx) = match self.pool.get(idx as usize)? { + Const::FieldRef(c, n) | Const::MethodRef(c, n) | Const::InterfaceMethodRef(c, n) => (*c, *n), + _ => return None, + }; + let owner = class_name_at(&self.pool, class_idx); + let (name, descriptor) = self.name_and_type(nat_idx); + Some(Ref { owner, name, descriptor }) + } + + /// Resolve a `NameAndType` index to (name, descriptor). + pub fn name_and_type(&self, idx: u16) -> (String, String) { + match self.pool.get(idx as usize) { + Some(Const::NameAndType(n, d)) => (self.utf8(*n).to_string(), self.utf8(*d).to_string()), + _ => (format!(""), String::new()), + } + } + + /// The (name, descriptor) of an `InvokeDynamic` (or `Dynamic`) constant's `NameAndType`. + pub fn name_and_type_of_indy(&self, idx: u16) -> Option<(String, String)> { + match self.pool.get(idx as usize)? { + Const::InvokeDynamic(_, nat) | Const::Dynamic(_, nat) => Some(self.name_and_type(*nat)), + _ => None, + } + } + + /// Dotted class name at a `Class` constant index. + pub fn class_dotted(&self, idx: u16) -> String { + internal_to_dotted(&class_name_at(&self.pool, idx)) + } + + /// A Java-style method signature (`public static void log(java.lang.String)`). + pub fn method_signature(&self, m: &Member) -> String { + let (params, ret) = method_params(&m.descriptor); + let flags = access_flags(m.access, AccessKind::Method).join(" "); + let params = params.join(", "); + if m.name == "" || m.name == "" { + format!("{}{}{}({params})", flags, if flags.is_empty() { "" } else { " " }, m.name).trim().to_string() + } else { + format!("{}{}{} {}({params})", flags, if flags.is_empty() { "" } else { " " }, ret, m.name).trim().to_string() + } + } + + /// Render one decoded instruction with its constant-pool reference resolved. + pub fn format_insn(&self, i: &Insn) -> String { + let mut operand = String::new(); + if let Some(cp) = i.cp_index { + operand = match i.opcode { + 0x12..=0x14 => const_display(&self.pool, cp), + 0xb2..=0xb5 => self.resolve_ref(cp).map(|r| r.display()).unwrap_or_else(|| format!("#{cp}")), + 0xb6..=0xb9 => self + .resolve_ref(cp) + .map(|r| format!("{}.{}{}", internal_to_dotted(&r.owner), r.name, r.descriptor)) + .unwrap_or_else(|| format!("#{cp}")), + 0xba => { + // invokedynamic: show the bootstrap name:descriptor + match self.pool.get(cp as usize) { + Some(Const::InvokeDynamic(_, nat)) => { + let (n, d) = self.name_and_type(*nat); + format!("{n}{d}") + } + _ => format!("#{cp}"), + } + } + 0xbb | 0xbd | 0xc0 | 0xc1 | 0xc5 => self.class_dotted(cp), + _ => format!("#{cp}"), + }; + } else if i.opcode == 0xbc { + // newarray + operand = java_ops::array_type(i.int.unwrap_or(0)).to_string(); + } else if i.opcode == 0x84 { + // iinc local, const + operand = format!("{}, {}", i.local.unwrap_or(0), i.int.unwrap_or(0)); + } else if let Some(l) = i.local { + operand = l.to_string(); + } else if let Some(v) = i.int { + operand = v.to_string(); + } else if let Some(b) = i.branch { + operand = format!("{b}"); + } + if i.opcode == 0xc5 { + // multianewarray class, dims + operand = format!("{}, {}", operand, i.int.unwrap_or(0)); + } + let mut s = if operand.is_empty() { i.name.to_string() } else { format!("{} {}", i.name, operand) }; + if let Some(sw) = &i.switch { + let cases: Vec = sw.pairs.iter().take(32).map(|(k, t)| format!("{k} -> {t}")).collect(); + s.push_str(&format!(" # default -> {}; {}", sw.default, cases.join(", "))); + } + s + } +} + +// --------------------------------------------------------------------------------------------- +// References + +/// One place a method's bytecode refers to a class, method or field. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Reference { + /// The calling method, `owner.name:descriptor`. + pub caller: String, + /// Byte offset in the caller's code. + pub pc: u32, + pub instruction: &'static str, + /// Direct member/type use or a method handle, method type or bootstrap linkage. + pub kind: &'static str, + pub target: String, +} + +fn class_component(name: &str) -> Option<&str> { + if name.starts_with('[') { name.trim_start_matches('[').strip_prefix('L')?.strip_suffix(';') } else { Some(name) } +} + +fn descriptor_mentions(mut descriptor: &str, owner: &str) -> bool { + while let Some((_, rest)) = descriptor.split_once('L') { + let Some((class, tail)) = rest.split_once(';') else { return false }; + if class == owner { + return true; + } + descriptor = tail; + } + false +} + +/// Resolve a loadable constant to its named dependency, retaining the linkage role. +fn constant_dependency(cf: &ClassFile, idx: u16, owner: &str, method: Option<&str>, bootstrap: bool) -> Option<(&'static str, String)> { + match cf.pool.get(usize::from(idx))? { + Const::Class(utf) if method.is_none() => { + let name = cf.utf8(*utf); + (class_component(name) == Some(owner)).then(|| ("type", internal_to_dotted(name))) + } + Const::MethodType(utf) if method.is_none() => { + let desc = cf.utf8(*utf); + descriptor_mentions(desc, owner).then(|| ("method-type", desc.to_owned())) + } + Const::MethodHandle(kind, target) => { + let member = cf.pool.get(usize::from(*target))?; + let valid = matches!( + (kind, member), + (1..=4, Const::FieldRef(..)) + | (5 | 8, Const::MethodRef(..)) + | (6 | 7, Const::MethodRef(..) | Const::InterfaceMethodRef(..)) + | (9, Const::InterfaceMethodRef(..)) + ); + let target = cf.resolve_ref(*target)?; + (valid && (!bootstrap || matches!(*kind, 6 | 8)) && target.owner == owner && method.is_none_or(|m| *kind >= 5 && target.name == m)) + .then(|| (if bootstrap { "bootstrap-method" } else { "method-handle" }, target.display())) + } + _ => None, + } +} + +/// Every instruction in `cf` that refers to the internal class `owner` (optionally only calls to +/// its methods named `method`). The bool is true when decoding or the reference limit stops a scan early. +pub fn references(cf: &ClassFile, owner: &str, method: Option<&str>, max: usize) -> (Vec, bool) { + let mut out = Vec::new(); + let mut incomplete = false; + // A single bootstrap record may be referenced by every instruction in a class. + let mut linkage_budget = 200_000usize; + for m in &cf.methods { + let Some(code) = &m.code else { continue }; + let caller = Ref { owner: cf.this_class.clone(), name: m.name.clone(), descriptor: m.descriptor.clone() }.display(); + let (insns, complete) = java_ops::decode(&code.bytecode, 200_000); + incomplete |= !complete; + for i in &insns { + let Some(cp) = i.cp_index else { continue }; + if matches!(i.opcode, 0x12..=0x14 | 0xba) { + let link = match (cf.pool.get(usize::from(cp)), i.opcode) { + (Some(Const::Dynamic(n, _)), 0x12..=0x14) | (Some(Const::InvokeDynamic(n, _)), 0xba) => Some(*n), + (Some(Const::Class(_) | Const::MethodType(_) | Const::MethodHandle(..)), 0x12 | 0x13) => None, + _ => continue, + }; + let record = link.and_then(|idx| cf.bootstrap_methods.get(usize::from(idx))); + let (handle, args): (u16, &[u16]) = record.map_or((cp, &[][..]), |(h, a)| (*h, a)); + let mut seen = std::collections::BTreeSet::new(); + for (index, &operand) in std::iter::once(&handle).chain(args).enumerate() { + let Some(left) = linkage_budget.checked_sub(1) else { return (out, true) }; + linkage_budget = left; + let is_bootstrap = index == 0 && record.is_some(); + if seen.insert((operand, is_bootstrap)) + && let Some((kind, target)) = constant_dependency(cf, operand, owner, method, is_bootstrap) + { + if out.len() >= max { + return (out, true); + } + out.push(Reference { caller: caller.clone(), pc: i.pc, instruction: i.name, kind, target }); + } + } + continue; + } + let hit = match i.opcode { + 0xb6..=0xb9 => { + cf.resolve_ref(cp).and_then(|r| (r.owner == owner && method.is_none_or(|n| r.name == n)).then(|| ("method", r.display()))) + } + 0xb2..=0xb5 if method.is_none() => cf.resolve_ref(cp).and_then(|r| (r.owner == owner).then(|| ("field", r.display()))), + 0xbb | 0xbd | 0xc0 | 0xc1 | 0xc5 if method.is_none() => { + let name = class_name_at(&cf.pool, cp); + (class_component(&name) == Some(owner)).then_some(("type", internal_to_dotted(&name))) + } + _ => None, + }; + if let Some((kind, target)) = hit { + if out.len() >= max { + return (out, true); + } + out.push(Reference { caller: caller.clone(), pc: i.pc, instruction: i.name, kind, target }); + } + } + } + (out, incomplete) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::java as fx; + + /// Two valid static methods: a one-dimensional allocation and a two-dimensional one. + fn array_reference_class(component: &str, array: &str) -> ClassFile { + let utf8 = |s: &str| { + let mut bytes = vec![1]; + bytes.extend_from_slice(&(s.len() as u16).to_be_bytes()); + bytes.extend_from_slice(s.as_bytes()); + bytes + }; + let pool = [ + utf8("sample/ArrayUses"), + vec![7, 0, 1], + utf8("java/lang/Object"), + vec![7, 0, 3], + utf8("Code"), + utf8("row"), + utf8(&format!("()[L{component};")), + utf8("grid"), + utf8(&format!("(){array}")), + utf8(component), + vec![7, 0, 10], + utf8(array), + vec![7, 0, 12], + ]; + let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52, 0, 14]; + bytes.extend(pool.into_iter().flatten()); + // public/super, this, super, no interfaces or fields, two methods. + bytes.extend_from_slice(&[0, 0x21, 0, 2, 0, 4, 0, 0, 0, 0, 0, 2]); + for (name, descriptor, code) in [(6u16, 7u16, vec![4, 0xbd, 0, 11, 0xb0]), (8, 9, vec![4, 4, 0xc5, 0, 13, 2, 0xb0])] { + for word in [9u16, name, descriptor, 1, 5] { + bytes.extend_from_slice(&word.to_be_bytes()); + } + bytes.extend_from_slice(&(12u32 + code.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&[0, 2, 0, 0]); // max_stack, max_locals + bytes.extend_from_slice(&(code.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&code); + bytes.extend_from_slice(&[0, 0, 0, 0]); // exception table and nested attributes + } + bytes.extend_from_slice(&[0, 0]); // class attributes + let cf = parse(&bytes).unwrap(); + assert!(cf.warnings.is_empty(), "{:?}", cf.warnings); + cf + } + + #[test] + fn parentheses_in_reference_types_are_part_of_the_class_name() { + let (params, result) = method_params("(Lpkg/A)B;[Lpkg/C(D;J)Lpkg/R)S;"); + assert_eq!(params, ["pkg.A)B", "pkg.C(D[]", "long"]); + assert_eq!(result, "pkg.R)S"); + } + + #[test] + fn object_arrays_reference_the_component_class() { + let cf = array_reference_class("java/lang/String", "[[Ljava/lang/String;"); + let (refs, more) = references(&cf, "java/lang/String", None, 10); + assert!(!more); + assert_eq!(refs.len(), 2, "{refs:?}"); + assert_eq!((refs[0].instruction, refs[0].pc), ("anewarray", 1)); + assert_eq!((refs[1].instruction, refs[1].pc), ("multianewarray", 2)); + assert_eq!(refs[1].target, "java.lang.String[][]"); + let (limited, more) = references(&cf, "java/lang/String", None, 1); + assert_eq!(limited, refs[..1]); + assert!(more); + assert_eq!(references(&cf, "java/lang/String", Some("grid"), 10), (Vec::new(), false)); + assert_eq!(references(&cf, "java/lang/Integer", None, 10), (Vec::new(), false)); + } + + #[test] + fn array_components_keep_class_names_beginning_with_l() { + for component in ["Leaf", "LLeaf"] { + let cf = array_reference_class(component, &format!("[[L{component};")); + let (refs, more) = references(&cf, component, None, 10); + assert_eq!(refs.len(), 2, "{component}: {refs:?}"); + assert!(!more); + } + } + + #[test] + fn primitive_arrays_do_not_reference_a_class_named_after_the_descriptor() { + let cf = array_reference_class("I", "[[I"); + let (refs, more) = references(&cf, "I", None, 10); + assert!(!more); + assert_eq!(refs.len(), 1, "{refs:?}"); + assert_eq!(refs[0].instruction, "anewarray"); + } + + #[test] + fn parses_fixture() { + let data = fx::hello_class(); + let cf = parse(&data).unwrap(); + assert!(cf.warnings.is_empty(), "{:?}", cf.warnings); + assert_eq!(cf.this_class, "com/example/Hello"); + assert_eq!(cf.super_class.as_deref(), Some("java/lang/Object")); + assert_eq!(cf.interfaces, vec!["java/lang/Runnable"]); + assert_eq!(cf.source_file.as_deref(), Some("Hello.java")); + assert!(cf.version.major >= 45); + // field + let f = cf.fields.iter().find(|f| f.name == "count").unwrap(); + assert_eq!(field_type(&f.descriptor), "int"); + // run() loads a string and calls println + let run = cf.methods.iter().find(|m| m.name == "run").unwrap(); + assert_eq!(cf.method_signature(run), "public void run()"); + let code = run.code.as_ref().unwrap(); + let (ins, complete) = java_ops::decode(&code.bytecode, 1000); + assert!(complete, "{ins:?}"); + let text: Vec = ins.iter().map(|i| cf.format_insn(i)).collect(); + assert!(text.iter().any(|t| t == "getstatic java.lang.System.out:java.io.PrintStream"), "{text:?}"); + assert!(text.iter().any(|t| t.starts_with("ldc \"Hello")), "{text:?}"); + assert!(text.iter().any(|t| t == "invokevirtual java.io.PrintStream.println(Ljava/lang/String;)V"), "{text:?}"); + // references to System from this class + let (refs, more) = references(&cf, "java/lang/System", None, 100); + assert!(!more); + assert!(refs.iter().any(|r| r.kind == "field" && r.target.contains("out")), "{refs:?}"); + } + + #[test] + fn helpers() { + assert_eq!(internal_to_dotted("java/lang/String"), "java.lang.String"); + assert_eq!(internal_to_dotted("[Ljava/lang/String;"), "java.lang.String[]"); + assert_eq!(method_params("(Ljava/lang/String;I)V"), (vec!["java.lang.String".to_string(), "int".to_string()], "void".to_string())); + assert_eq!(method_params("()I"), (Vec::new(), "int".to_string())); + assert_eq!(Version { major: 52, minor: 0 }.java_label(), "Java 8"); + assert_eq!(Version { major: 65, minor: 0 }.java_label(), "Java 21"); + assert_eq!(decode_mutf8(&[0xc0, 0x80, 0x41]), "\0A"); + } + + #[test] + fn hostile() { + let data = fx::hello_class(); + let walk = |cf: &ClassFile| { + let _ = cf.name_dotted(); + for m in cf.methods.iter().chain(&cf.fields) { + let _ = cf.method_signature(m); + if let Some(code) = &m.code { + let (ins, _) = java_ops::decode(&code.bytecode, 10_000); + for i in &ins { + let _ = cf.format_insn(i); + } + } + } + let _ = references(cf, "java/lang/System", None, 100); + }; + for m in crate::test_support::mutations(&data) { + if let Ok(cf) = parse(&m) { + walk(&cf); + } + } + for len in 0..data.len() { + if let Ok(cf) = parse(&data[..len]) { + walk(&cf); + } + } + for seed in 0..64 { + let mut n = crate::test_support::noise(seed, 2048); + n[..4].copy_from_slice(&[0xca, 0xfe, 0xba, 0xbe]); + n[6] = 0; + n[7] = 52; + if let Ok(cf) = parse(&n) { + walk(&cf); + } + } + } +} diff --git a/crates/java-class/src/java_ops.rs b/crates/java-class/src/java_ops.rs new file mode 100644 index 0000000000..46e5cdf30b --- /dev/null +++ b/crates/java-class/src/java_ops.rs @@ -0,0 +1,711 @@ +//! JVM bytecode: the opcode table (every defined opcode plus the `wide`, `tableswitch` and +//! `lookupswitch` variable-length forms) and a decoder for each instruction. Pure decoding; +//! constant-pool index operands are resolved by the caller (see [`crate::java_class`]). + +use serde::Serialize; + +/// The shape of an opcode's operands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub enum Operands { + /// No operands. + None, + /// One signed byte immediate (`bipush`). + Byte, + /// One signed short immediate (`sipush`). + Short, + /// A one-byte local-variable index. + Local, + /// `iinc`: a one-byte local index and a signed byte increment. + LocalConst, + /// A two-byte signed branch offset. + Branch2, + /// A four-byte signed branch offset (`goto_w`, `jsr_w`). + Branch4, + /// A one-byte constant-pool index (`ldc`). + Cp1, + /// A two-byte constant-pool index. + Cp2, + /// `newarray`: a one-byte primitive array type. + NewArray, + /// `invokeinterface`: a two-byte index, a count byte and a zero byte. + InvokeInterface, + /// `invokedynamic`: a two-byte index and two zero bytes. + InvokeDynamic, + /// `multianewarray`: a two-byte class index and a dimension byte. + MultiANewArray, + /// `tableswitch` (variable length, 4-byte aligned). + TableSwitch, + /// `lookupswitch` (variable length, 4-byte aligned). + LookupSwitch, + /// `wide`: a prefix that widens the following load/store/ret/iinc. + Wide, + /// A reserved or unknown opcode. + Reserved, +} + +/// One opcode slot. +#[derive(Debug, Clone, Copy)] +pub struct Op { + pub name: &'static str, + pub operands: Operands, +} + +const fn op(name: &'static str, operands: Operands) -> Op { + Op { name, operands } +} + +/// The opcode table entry for `b`. +pub fn opcode(b: u8) -> Op { + use Operands as O; + match b { + 0x00 => op("nop", O::None), + 0x01 => op("aconst_null", O::None), + 0x02 => op("iconst_m1", O::None), + 0x03 => op("iconst_0", O::None), + 0x04 => op("iconst_1", O::None), + 0x05 => op("iconst_2", O::None), + 0x06 => op("iconst_3", O::None), + 0x07 => op("iconst_4", O::None), + 0x08 => op("iconst_5", O::None), + 0x09 => op("lconst_0", O::None), + 0x0a => op("lconst_1", O::None), + 0x0b => op("fconst_0", O::None), + 0x0c => op("fconst_1", O::None), + 0x0d => op("fconst_2", O::None), + 0x0e => op("dconst_0", O::None), + 0x0f => op("dconst_1", O::None), + 0x10 => op("bipush", O::Byte), + 0x11 => op("sipush", O::Short), + 0x12 => op("ldc", O::Cp1), + 0x13 => op("ldc_w", O::Cp2), + 0x14 => op("ldc2_w", O::Cp2), + 0x15 => op("iload", O::Local), + 0x16 => op("lload", O::Local), + 0x17 => op("fload", O::Local), + 0x18 => op("dload", O::Local), + 0x19 => op("aload", O::Local), + 0x1a => op("iload_0", O::None), + 0x1b => op("iload_1", O::None), + 0x1c => op("iload_2", O::None), + 0x1d => op("iload_3", O::None), + 0x1e => op("lload_0", O::None), + 0x1f => op("lload_1", O::None), + 0x20 => op("lload_2", O::None), + 0x21 => op("lload_3", O::None), + 0x22 => op("fload_0", O::None), + 0x23 => op("fload_1", O::None), + 0x24 => op("fload_2", O::None), + 0x25 => op("fload_3", O::None), + 0x26 => op("dload_0", O::None), + 0x27 => op("dload_1", O::None), + 0x28 => op("dload_2", O::None), + 0x29 => op("dload_3", O::None), + 0x2a => op("aload_0", O::None), + 0x2b => op("aload_1", O::None), + 0x2c => op("aload_2", O::None), + 0x2d => op("aload_3", O::None), + 0x2e => op("iaload", O::None), + 0x2f => op("laload", O::None), + 0x30 => op("faload", O::None), + 0x31 => op("daload", O::None), + 0x32 => op("aaload", O::None), + 0x33 => op("baload", O::None), + 0x34 => op("caload", O::None), + 0x35 => op("saload", O::None), + 0x36 => op("istore", O::Local), + 0x37 => op("lstore", O::Local), + 0x38 => op("fstore", O::Local), + 0x39 => op("dstore", O::Local), + 0x3a => op("astore", O::Local), + 0x3b => op("istore_0", O::None), + 0x3c => op("istore_1", O::None), + 0x3d => op("istore_2", O::None), + 0x3e => op("istore_3", O::None), + 0x3f => op("lstore_0", O::None), + 0x40 => op("lstore_1", O::None), + 0x41 => op("lstore_2", O::None), + 0x42 => op("lstore_3", O::None), + 0x43 => op("fstore_0", O::None), + 0x44 => op("fstore_1", O::None), + 0x45 => op("fstore_2", O::None), + 0x46 => op("fstore_3", O::None), + 0x47 => op("dstore_0", O::None), + 0x48 => op("dstore_1", O::None), + 0x49 => op("dstore_2", O::None), + 0x4a => op("dstore_3", O::None), + 0x4b => op("astore_0", O::None), + 0x4c => op("astore_1", O::None), + 0x4d => op("astore_2", O::None), + 0x4e => op("astore_3", O::None), + 0x4f => op("iastore", O::None), + 0x50 => op("lastore", O::None), + 0x51 => op("fastore", O::None), + 0x52 => op("dastore", O::None), + 0x53 => op("aastore", O::None), + 0x54 => op("bastore", O::None), + 0x55 => op("castore", O::None), + 0x56 => op("sastore", O::None), + 0x57 => op("pop", O::None), + 0x58 => op("pop2", O::None), + 0x59 => op("dup", O::None), + 0x5a => op("dup_x1", O::None), + 0x5b => op("dup_x2", O::None), + 0x5c => op("dup2", O::None), + 0x5d => op("dup2_x1", O::None), + 0x5e => op("dup2_x2", O::None), + 0x5f => op("swap", O::None), + 0x60 => op("iadd", O::None), + 0x61 => op("ladd", O::None), + 0x62 => op("fadd", O::None), + 0x63 => op("dadd", O::None), + 0x64 => op("isub", O::None), + 0x65 => op("lsub", O::None), + 0x66 => op("fsub", O::None), + 0x67 => op("dsub", O::None), + 0x68 => op("imul", O::None), + 0x69 => op("lmul", O::None), + 0x6a => op("fmul", O::None), + 0x6b => op("dmul", O::None), + 0x6c => op("idiv", O::None), + 0x6d => op("ldiv", O::None), + 0x6e => op("fdiv", O::None), + 0x6f => op("ddiv", O::None), + 0x70 => op("irem", O::None), + 0x71 => op("lrem", O::None), + 0x72 => op("frem", O::None), + 0x73 => op("drem", O::None), + 0x74 => op("ineg", O::None), + 0x75 => op("lneg", O::None), + 0x76 => op("fneg", O::None), + 0x77 => op("dneg", O::None), + 0x78 => op("ishl", O::None), + 0x79 => op("lshl", O::None), + 0x7a => op("ishr", O::None), + 0x7b => op("lshr", O::None), + 0x7c => op("iushr", O::None), + 0x7d => op("lushr", O::None), + 0x7e => op("iand", O::None), + 0x7f => op("land", O::None), + 0x80 => op("ior", O::None), + 0x81 => op("lor", O::None), + 0x82 => op("ixor", O::None), + 0x83 => op("lxor", O::None), + 0x84 => op("iinc", O::LocalConst), + 0x85 => op("i2l", O::None), + 0x86 => op("i2f", O::None), + 0x87 => op("i2d", O::None), + 0x88 => op("l2i", O::None), + 0x89 => op("l2f", O::None), + 0x8a => op("l2d", O::None), + 0x8b => op("f2i", O::None), + 0x8c => op("f2l", O::None), + 0x8d => op("f2d", O::None), + 0x8e => op("d2i", O::None), + 0x8f => op("d2l", O::None), + 0x90 => op("d2f", O::None), + 0x91 => op("i2b", O::None), + 0x92 => op("i2c", O::None), + 0x93 => op("i2s", O::None), + 0x94 => op("lcmp", O::None), + 0x95 => op("fcmpl", O::None), + 0x96 => op("fcmpg", O::None), + 0x97 => op("dcmpl", O::None), + 0x98 => op("dcmpg", O::None), + 0x99 => op("ifeq", O::Branch2), + 0x9a => op("ifne", O::Branch2), + 0x9b => op("iflt", O::Branch2), + 0x9c => op("ifge", O::Branch2), + 0x9d => op("ifgt", O::Branch2), + 0x9e => op("ifle", O::Branch2), + 0x9f => op("if_icmpeq", O::Branch2), + 0xa0 => op("if_icmpne", O::Branch2), + 0xa1 => op("if_icmplt", O::Branch2), + 0xa2 => op("if_icmpge", O::Branch2), + 0xa3 => op("if_icmpgt", O::Branch2), + 0xa4 => op("if_icmple", O::Branch2), + 0xa5 => op("if_acmpeq", O::Branch2), + 0xa6 => op("if_acmpne", O::Branch2), + 0xa7 => op("goto", O::Branch2), + 0xa8 => op("jsr", O::Branch2), + 0xa9 => op("ret", O::Local), + 0xaa => op("tableswitch", O::TableSwitch), + 0xab => op("lookupswitch", O::LookupSwitch), + 0xac => op("ireturn", O::None), + 0xad => op("lreturn", O::None), + 0xae => op("freturn", O::None), + 0xaf => op("dreturn", O::None), + 0xb0 => op("areturn", O::None), + 0xb1 => op("return", O::None), + 0xb2 => op("getstatic", O::Cp2), + 0xb3 => op("putstatic", O::Cp2), + 0xb4 => op("getfield", O::Cp2), + 0xb5 => op("putfield", O::Cp2), + 0xb6 => op("invokevirtual", O::Cp2), + 0xb7 => op("invokespecial", O::Cp2), + 0xb8 => op("invokestatic", O::Cp2), + 0xb9 => op("invokeinterface", O::InvokeInterface), + 0xba => op("invokedynamic", O::InvokeDynamic), + 0xbb => op("new", O::Cp2), + 0xbc => op("newarray", O::NewArray), + 0xbd => op("anewarray", O::Cp2), + 0xbe => op("arraylength", O::None), + 0xbf => op("athrow", O::None), + 0xc0 => op("checkcast", O::Cp2), + 0xc1 => op("instanceof", O::Cp2), + 0xc2 => op("monitorenter", O::None), + 0xc3 => op("monitorexit", O::None), + 0xc4 => op("wide", O::Wide), + 0xc5 => op("multianewarray", O::MultiANewArray), + 0xc6 => op("ifnull", O::Branch2), + 0xc7 => op("ifnonnull", O::Branch2), + 0xc8 => op("goto_w", O::Branch4), + 0xc9 => op("jsr_w", O::Branch4), + 0xca => op("breakpoint", O::None), + 0xfe => op("impdep1", O::None), + 0xff => op("impdep2", O::None), + _ => op("unknown", O::Reserved), + } +} + +/// The primitive array type for a `newarray` atype operand. +pub fn array_type(atype: i32) -> &'static str { + match atype { + 4 => "boolean", + 5 => "char", + 6 => "float", + 7 => "double", + 8 => "byte", + 9 => "short", + 10 => "int", + 11 => "long", + _ => "?", + } +} + +/// A decoded `tableswitch`/`lookupswitch`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Switch { + /// Absolute byte offset of the default branch. + pub default: i64, + /// `(key, absolute target)` pairs in listing order. + pub pairs: Vec<(i32, i64)>, +} + +/// One decoded instruction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Insn { + /// Byte offset from the start of the method's code. + pub pc: u32, + pub opcode: u8, + pub name: &'static str, + /// Total length in bytes, including operands. + pub len: u32, + /// Local-variable index operand (load/store/ret/iinc). + #[serde(skip_serializing_if = "Option::is_none")] + pub local: Option, + /// Integer immediate (`bipush`/`sipush`/`iinc` increment/`newarray` type/`multianewarray` dims). + #[serde(skip_serializing_if = "Option::is_none")] + pub int: Option, + /// Constant-pool index operand (resolved by the caller). + #[serde(skip_serializing_if = "Option::is_none")] + pub cp_index: Option, + /// Absolute byte offset of a branch target. + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + /// A switch table when the opcode is `tableswitch`/`lookupswitch`. + #[serde(skip_serializing_if = "Option::is_none")] + pub switch: Option, + /// True when this instruction was prefixed by `wide`. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub wide: bool, +} + +/// Most entries decoded from one switch table. +const MAX_SWITCH: usize = 1 << 20; + +fn s8(code: &[u8], at: usize) -> Option { + code.get(at).map(|&b| i32::from(b as i8)) +} +fn u16b(code: &[u8], at: usize) -> Option { + Some(u16::from(*code.get(at)?) << 8 | u16::from(*code.get(at + 1)?)) +} +fn s16(code: &[u8], at: usize) -> Option { + u16b(code, at).map(|v| i32::from(v as i16)) +} +fn s32(code: &[u8], at: usize) -> Option { + Some(i32::from(*code.get(at)?) << 24 | i32::from(*code.get(at + 1)?) << 16 | i32::from(*code.get(at + 2)?) << 8 | i32::from(*code.get(at + 3)?)) +} + +fn base(pc: usize, opcode: u8, name: &'static str) -> Insn { + Insn { pc: pc as u32, opcode, name, len: 1, local: None, int: None, cp_index: None, branch: None, switch: None, wide: false } +} + +/// Decode one instruction at `pc`, or `None` for invalid or incomplete operands. +pub fn decode_one(code: &[u8], pc: usize) -> Option { + let b = *code.get(pc)?; + let o = opcode(b); + let mut insn = base(pc, b, o.name); + let rel = |d: i32| pc as i64 + i64::from(d); + match o.operands { + Operands::None | Operands::Reserved => {} + Operands::Byte => { + insn.int = Some(s8(code, pc + 1)?); + insn.len = 2; + } + Operands::Short => { + insn.int = Some(s16(code, pc + 1)?); + insn.len = 3; + } + Operands::Local => { + insn.local = Some(u16::from(*code.get(pc + 1)?)); + insn.len = 2; + } + Operands::LocalConst => { + insn.local = Some(u16::from(*code.get(pc + 1)?)); + insn.int = Some(s8(code, pc + 2)?); + insn.len = 3; + } + Operands::Branch2 => { + insn.branch = Some(rel(s16(code, pc + 1)?)); + insn.len = 3; + } + Operands::Branch4 => { + insn.branch = Some(rel(s32(code, pc + 1)?)); + insn.len = 5; + } + Operands::Cp1 => { + insn.cp_index = Some(u16::from(*code.get(pc + 1)?)); + insn.len = 2; + } + Operands::Cp2 => { + insn.cp_index = Some(u16b(code, pc + 1)?); + insn.len = 3; + } + Operands::NewArray => { + let atype = *code.get(pc + 1)?; + if !(4..=11).contains(&atype) { + return None; + } + insn.int = Some(i32::from(atype)); + insn.len = 2; + } + Operands::InvokeInterface => { + insn.cp_index = Some(u16b(code, pc + 1)?); + if *code.get(pc + 3)? == 0 || *code.get(pc + 4)? != 0 { + return None; + } + insn.len = 5; + } + Operands::InvokeDynamic => { + insn.cp_index = Some(u16b(code, pc + 1)?); + if *code.get(pc + 3)? != 0 || *code.get(pc + 4)? != 0 { + return None; + } + insn.len = 5; + } + Operands::MultiANewArray => { + insn.cp_index = Some(u16b(code, pc + 1)?); + let dimensions = *code.get(pc + 3)?; + if dimensions == 0 { + return None; + } + insn.int = Some(i32::from(dimensions)); + insn.len = 4; + } + Operands::Wide => return decode_wide(code, pc), + Operands::TableSwitch => return decode_tableswitch(code, pc), + Operands::LookupSwitch => return decode_lookupswitch(code, pc), + } + if pc.checked_add(insn.len as usize)? > code.len() { + return None; + } + Some(insn) +} + +fn decode_wide(code: &[u8], pc: usize) -> Option { + let real = *code.get(pc + 1)?; + if !matches!(real, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9) { + return None; + } + let o = opcode(real); + let mut insn = base(pc, real, o.name); + insn.wide = true; + if real == 0x84 { + // wide iinc: 2-byte local, 2-byte signed const + insn.local = Some(u16b(code, pc + 2)?); + insn.int = Some(s16(code, pc + 4)?); + insn.len = 6; + } else { + // wide load/store/ret: 2-byte local + insn.local = Some(u16b(code, pc + 2)?); + insn.len = 4; + } + if pc.checked_add(insn.len as usize)? > code.len() { + return None; + } + Some(insn) +} + +/// Padding so the operand word after a switch opcode is 4-byte aligned from the code start. +fn switch_pad(pc: usize) -> usize { + (4 - ((pc + 1) % 4)) % 4 +} + +fn decode_tableswitch(code: &[u8], pc: usize) -> Option { + let mut at = pc + 1 + switch_pad(pc); + let default = rel_i64(pc, s32(code, at)?); + let low = s32(code, at + 4)?; + let high = s32(code, at + 8)?; + at += 12; + if high < low { + return None; + } + let count = usize::try_from(i64::from(high) - i64::from(low) + 1).ok()?; + if count > MAX_SWITCH { + return None; + } + let end = at.checked_add(count.checked_mul(4)?)?; + code.get(at..end)?; + let mut pairs = Vec::with_capacity(count); + for i in 0..count { + let off = s32(code, at + i * 4)?; + pairs.push((low.wrapping_add(i as i32), rel_i64(pc, off))); + } + let mut insn = base(pc, 0xaa, "tableswitch"); + insn.switch = Some(Switch { default, pairs }); + insn.len = (end - pc) as u32; + Some(insn) +} + +fn decode_lookupswitch(code: &[u8], pc: usize) -> Option { + let mut at = pc + 1 + switch_pad(pc); + let default = rel_i64(pc, s32(code, at)?); + let npairs = s32(code, at + 4)?; + at += 8; + if npairs < 0 { + return None; + } + let count = npairs as usize; + if count > MAX_SWITCH { + return None; + } + let end = at.checked_add(count.checked_mul(8)?)?; + code.get(at..end)?; + let mut pairs = Vec::with_capacity(count); + let mut previous = None; + for i in 0..count { + let key = s32(code, at + i * 8)?; + if previous.is_some_and(|previous| key <= previous) { + return None; + } + previous = Some(key); + let off = s32(code, at + i * 8 + 4)?; + pairs.push((key, rel_i64(pc, off))); + } + let mut insn = base(pc, 0xab, "lookupswitch"); + insn.switch = Some(Switch { default, pairs }); + insn.len = (end - pc) as u32; + Some(insn) +} + +fn rel_i64(pc: usize, off: i32) -> i64 { + pc as i64 + i64::from(off) +} + +/// Decode a whole method body, stopping at `max` instructions. `complete` is false when a +/// instruction has invalid/incomplete operands or the cap was hit. +pub fn decode(code: &[u8], max: usize) -> (Vec, bool) { + let mut out = Vec::new(); + let mut pc = 0usize; + let mut complete = true; + while pc < code.len() { + if out.len() >= max { + complete = false; + break; + } + match decode_one(code, pc) { + Some(i) => { + pc += (i.len as usize).max(1); + out.push(i); + } + None => { + complete = false; + break; + } + } + } + (out, complete) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lookup(pc: usize, keys: &[i32]) -> Vec { + let mut code = vec![0; pc]; + code.push(0xab); + while !code.len().is_multiple_of(4) { + code.push(0); + } + code.extend_from_slice(&0i32.to_be_bytes()); + code.extend_from_slice(&(keys.len() as i32).to_be_bytes()); + for key in keys { + code.extend_from_slice(&key.to_be_bytes()); + code.extend_from_slice(&0i32.to_be_bytes()); + } + code + } + + #[test] + fn lookup_keys_must_increase_strictly() { + for keys in [&[1, 1][..], &[1, 0], &[0, -1], &[i32::MIN, i32::MAX, i32::MIN]] { + for pc in 0..4 { + let mut code = lookup(pc, keys); + code.push(0xb1); + assert!(decode_one(&code, pc).is_none(), "pc {pc}, keys {keys:?}"); + let (decoded, complete) = decode(&code, 100); + assert!(!complete); + assert_eq!(decoded.len(), pc, "preserve preceding nops, stop before the bad switch"); + } + } + } + + #[test] + fn lookup_keys_use_signed_order_at_every_alignment() { + for keys in [&[][..], &[i32::MIN, -1, 0, i32::MAX]] { + for pc in 0..4 { + let code = lookup(pc, keys); + let insn = decode_one(&code, pc).unwrap(); + assert_eq!(insn.len as usize, code.len() - pc); + let switch = insn.switch.unwrap(); + assert_eq!(switch.default, pc as i64); + assert_eq!(switch.pairs, keys.iter().map(|&key| (key, pc as i64)).collect::>()); + assert!(decode(&code, 100).1); + } + } + } + + #[test] + fn switch_payloads_must_be_complete() { + for pc in 0..4 { + let lookup = lookup(pc, &[-1, 1]); + let mut dense = vec![0; pc]; + dense.push(0xaa); + while !dense.len().is_multiple_of(4) { + dense.push(0); + } + for word in [0i32, i32::MAX - 1, i32::MAX, 0, 0] { + dense.extend_from_slice(&word.to_be_bytes()); + } + for code in [lookup, dense] { + assert!(decode_one(&code, pc).is_some()); + for end in pc + 1..code.len() { + assert!(decode_one(&code[..end], pc).is_none(), "pc {pc}, end {end}"); + } + } + } + } + + #[test] + fn switch_counts_cannot_reserve_an_absent_table() { + let mut lookup = lookup(0, &[]); + lookup[8..12].copy_from_slice(&(MAX_SWITCH as i32).to_be_bytes()); + assert!(decode_one(&lookup, 0).is_none()); + for (low, high) in [(0i32, MAX_SWITCH as i32 - 1), (i32::MIN, i32::MAX)] { + let mut dense = vec![0xaa, 0, 0, 0]; + for word in [0, low, high] { + dense.extend_from_slice(&word.to_be_bytes()); + } + assert!(decode_one(&dense, 0).is_none()); + } + } + + #[test] + fn table_covers_defined_opcodes() { + let mut named = 0; + for b in 0..=255u8 { + if opcode(b).name != "unknown" { + named += 1; + } + } + // 0x00..=0xca is 203 opcodes, plus impdep1/impdep2. + assert_eq!(named, 203 + 2); + assert_eq!(opcode(0xb6).name, "invokevirtual"); + assert_eq!(opcode(0x10).name, "bipush"); + assert_eq!(opcode(0xc4).name, "wide"); + } + + #[test] + fn decodes_core_formats() { + // iconst_1; bipush 7; istore_1; goto +3 ; (pad to reach len) return + let code = [0x04, 0x10, 0x07, 0x3c, 0xa7, 0x00, 0x03, 0xb1]; + let (ins, complete) = decode(&code, 100); + assert!(complete, "{ins:?}"); + assert_eq!(ins[0].name, "iconst_1"); + assert_eq!(ins[1].name, "bipush"); + assert_eq!(ins[1].int, Some(7)); + assert_eq!(ins[2].name, "istore_1"); + assert_eq!(ins[3].name, "goto"); + assert_eq!(ins[3].branch, Some(7)); // pc 4 + 3 + assert_eq!(ins[4].name, "return"); + } + + #[test] + fn decodes_invoke_and_wide() { + // invokevirtual #5 ; invokeinterface #6 count 2 ; wide iload 300 + let code = [0xb6, 0x00, 0x05, 0xb9, 0x00, 0x06, 0x02, 0x00, 0xc4, 0x15, 0x01, 0x2c]; + let (ins, complete) = decode(&code, 100); + assert!(complete); + assert_eq!(ins[0].name, "invokevirtual"); + assert_eq!(ins[0].cp_index, Some(5)); + assert_eq!(ins[0].len, 3); + assert_eq!(ins[1].name, "invokeinterface"); + assert_eq!(ins[1].cp_index, Some(6)); + assert_eq!(ins[1].len, 5); + assert_eq!(ins[2].name, "iload"); + assert!(ins[2].wide); + assert_eq!(ins[2].local, Some(300)); + assert_eq!(ins[2].len, 4); + } + + #[test] + fn decodes_switches() { + // tableswitch at pc 0: pad 3, default +40, low 1, high 2, offsets +10, +20 + let mut code = vec![0xaa, 0, 0, 0]; + code.extend_from_slice(&40i32.to_be_bytes()); + code.extend_from_slice(&1i32.to_be_bytes()); + code.extend_from_slice(&2i32.to_be_bytes()); + code.extend_from_slice(&10i32.to_be_bytes()); + code.extend_from_slice(&20i32.to_be_bytes()); + let i = decode_one(&code, 0).unwrap(); + assert_eq!(i.name, "tableswitch"); + let sw = i.switch.unwrap(); + assert_eq!(sw.default, 40); + assert_eq!(sw.pairs, vec![(1, 10), (2, 20)]); + assert_eq!(i.len as usize, code.len()); + + // lookupswitch at pc 0: pad 3, default +4, npairs 1, (key 99 -> +8) + let mut lk = vec![0xab, 0, 0, 0]; + lk.extend_from_slice(&4i32.to_be_bytes()); + lk.extend_from_slice(&1i32.to_be_bytes()); + lk.extend_from_slice(&99i32.to_be_bytes()); + lk.extend_from_slice(&8i32.to_be_bytes()); + let l = decode_one(&lk, 0).unwrap(); + let sw = l.switch.unwrap(); + assert_eq!(sw.default, 4); + assert_eq!(sw.pairs, vec![(99, 8)]); + } + + #[test] + fn hostile() { + for seed in 0..256 { + let n = crate::test_support::noise(seed, 512); + let _ = decode(&n, 10_000); + } + // truncated operands never panic + let _ = decode(&[0xb6, 0x00], 10); + let _ = decode(&[0xaa, 0, 0, 0, 0, 0, 0, 0], 10); + let _ = decode(&[0xab, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0xff, 0xff, 0xff], 10); + let _ = decode(&[0xc4], 10); + } +} diff --git a/crates/java-class/src/lib.rs b/crates/java-class/src/lib.rs new file mode 100644 index 0000000000..4d135e16b2 --- /dev/null +++ b/crates/java-class/src/lib.rs @@ -0,0 +1,50 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Java class-file inspection and JVM bytecode decoding. Never executes bytecode. +//! Retains source item, attribute and annotation-depth limits and partial reports. +mod bytes; +mod descriptor; +pub mod java_class; +pub mod java_ops; +pub use java_class::*; +#[cfg(test)] +mod test_support; +/// File admission errors; damaged optional structures retain partial-report warnings. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum JavaClassError { + #[error("the file ends early ({0})")] + Truncated(String), + #[error("the file is malformed ({0})")] + Malformed(String), + #[error("not supported: {0}")] + Unsupported(String), +} +use JavaClassError as FormatError; + +#[cfg(test)] +#[path = "regressions/java_array_operands.rs"] +mod java_array_operands; + +#[cfg(test)] +#[path = "regressions/java_attribute_names.rs"] +mod java_attribute_names; + +#[cfg(test)] +#[path = "regressions/java_constant_pool_slots.rs"] +mod java_constant_pool_slots; + +#[cfg(test)] +#[path = "regressions/java_invoke_operands.rs"] +mod java_invoke_operands; + +#[cfg(test)] +#[path = "regressions/java_linkage_references.rs"] +mod java_linkage_references; + +#[cfg(test)] +#[path = "regressions/java_truncated_attributes.rs"] +mod java_truncated_attributes; + +#[cfg(test)] +#[path = "regressions/java_wide_opcodes.rs"] +mod java_wide_opcodes; diff --git a/crates/java-class/src/regressions/java_array_operands.rs b/crates/java-class/src/regressions/java_array_operands.rs new file mode 100644 index 0000000000..b5867db52f --- /dev/null +++ b/crates/java-class/src/regressions/java_array_operands.rs @@ -0,0 +1,48 @@ +use crate::java_ops::{decode, decode_one}; + +#[test] +fn invalid_primitive_array_types_stop_before_the_allocation() { + for atype in (0..=u8::MAX).filter(|value| !(4..=11).contains(value)) { + assert!(decode_one(&[0xbc, atype], 0).is_none(), "atype {atype}"); + let (instructions, complete) = decode(&[0, 0xbc, atype, 0xb1], 100); + assert!(!complete, "atype {atype}"); + assert_eq!(instructions.len(), 1); + assert_eq!(instructions[0].name, "nop"); + } +} + +#[test] +fn zero_dimension_multidimensional_allocations_are_not_complete_bytecode() { + assert!(decode_one(&[0xc5, 0, 1, 0], 0).is_none()); + let (instructions, complete) = decode(&[0, 0xc5, 0, 1, 0, 0xb1], 100); + assert!(!complete); + assert_eq!(instructions.len(), 1); + assert_eq!(instructions[0].name, "nop"); +} + +#[test] +fn every_defined_primitive_type_and_nonzero_dimension_remains_decodable() { + for atype in 4..=11 { + let (instructions, complete) = decode(&[0xbc, atype, 0xb1], 100); + assert!(complete); + assert_eq!(instructions.len(), 2); + assert_eq!(instructions[0].int, Some(i32::from(atype))); + assert_eq!(instructions[0].len, 2); + } + for dimensions in 1..=u8::MAX { + let instruction = decode_one(&[0, 0xc5, 0x12, 0x34, dimensions], 1).unwrap(); + assert_eq!(instruction.pc, 1); + assert_eq!(instruction.cp_index, Some(0x1234)); + assert_eq!(instruction.int, Some(i32::from(dimensions))); + assert_eq!(instruction.len, 4); + } +} + +#[test] +fn incomplete_array_operands_remain_rejected() { + for instruction in [&[0xbc, 10][..], &[0xc5, 0, 1, 2][..]] { + for end in 1..instruction.len() { + assert!(decode_one(&instruction[..end], 0).is_none()); + } + } +} diff --git a/crates/java-class/src/regressions/java_attribute_names.rs b/crates/java-class/src/regressions/java_attribute_names.rs new file mode 100644 index 0000000000..c506ed0c9d --- /dev/null +++ b/crates/java-class/src/regressions/java_attribute_names.rs @@ -0,0 +1,132 @@ +use crate::java_class::{self, ClassFile, Const}; + +#[derive(Clone, Copy, Debug)] +enum Scope { + Class, + Field, + Method, + Code, +} + +fn u16b(out: &mut Vec, n: u16) { + out.extend_from_slice(&n.to_be_bytes()); +} + +fn u32b(out: &mut Vec, n: u32) { + out.extend_from_slice(&n.to_be_bytes()); +} + +fn utf8(out: &mut Vec, text: &str) { + out.push(1); + u16b(out, text.len() as u16); + out.extend_from_slice(text.as_bytes()); +} + +fn attr(name: u16, info: &[u8]) -> Vec { + let mut out = Vec::new(); + u16b(&mut out, name); + u32b(&mut out, info.len() as u32); + out.extend_from_slice(info); + out +} + +fn attributes(out: &mut Vec, repeated: u16, known: &[Vec]) { + u16b(out, repeated + known.len() as u16); + for _ in 0..repeated { + out.extend_from_slice(&attr(5, &[])); + } + for bytes in known { + out.extend_from_slice(bytes); + } +} + +// A valid shared CONSTANT_Utf8 is named by every unknown attribute. Known +// attributes follow it, so avoiding name copies must not discard their facts. +fn fixture(scope: Scope, repeated: u16) -> Vec { + let mut out = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52]; + u16b(&mut out, 17); + utf8(&mut out, "AttributeFixture"); // 1 + out.push(7); + u16b(&mut out, 1); // 2: this class + utf8(&mut out, "java/lang/Object"); // 3 + out.push(7); + u16b(&mut out, 3); // 4: superclass + utf8(&mut out, &format!("org.example.{}", "A".repeat(usize::from(u16::MAX) - 12))); // 5 + for text in ["SourceFile", "AttributeFixture.java", "field", "I"] { + utf8(&mut out, text); // 6..9 + } + out.push(3); + u32b(&mut out, 42); // 10 + for text in ["ConstantValue", "run", "()V", "Code", "LineNumberTable", "Deprecated"] { + utf8(&mut out, text); // 11..16 + } + for word in [0x0021, 2, 4, 0, 1, 0x0019, 8, 9] { + u16b(&mut out, word); + } + attributes(&mut out, if matches!(scope, Scope::Field) { repeated } else { 0 }, &[attr(11, &10u16.to_be_bytes()), attr(16, &[])]); + for word in [1, 0x0009, 12, 13] { + u16b(&mut out, word); + } + let mut code = vec![0, 0, 0, 0, 0, 0, 0, 1, 0xb1, 0, 0]; + attributes(&mut code, if matches!(scope, Scope::Code) { repeated } else { 0 }, &[attr(15, &[0, 1, 0, 0, 0, 7])]); + attributes(&mut out, if matches!(scope, Scope::Method) { repeated } else { 0 }, &[attr(14, &code)]); + attributes(&mut out, if matches!(scope, Scope::Class) { repeated } else { 0 }, &[attr(6, &7u16.to_be_bytes())]); + out +} + +fn check_facts(parsed: &ClassFile) { + assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings); + assert_eq!(parsed.this_class, "AttributeFixture"); + assert_eq!(parsed.super_class.as_deref(), Some("java/lang/Object")); + assert_eq!(parsed.source_file.as_deref(), Some("AttributeFixture.java")); + assert_eq!(parsed.fields.len(), 1); + assert_eq!(parsed.fields[0].name, "field"); + assert_eq!(parsed.fields[0].constant_value.as_deref(), Some("42")); + assert!(parsed.fields[0].deprecated); + assert_eq!(parsed.methods.len(), 1); + assert_eq!(parsed.methods[0].name, "run"); + let code = parsed.methods[0].code.as_ref().unwrap(); + assert_eq!(code.bytecode, [0xb1]); + assert_eq!(code.line_numbers, [(0, 7)]); + assert!(matches!(&parsed.pool[5], Const::Utf8(name) if name.len() == usize::from(u16::MAX))); +} + +#[test] +fn known_attributes_survive_repeated_unknown_names_at_every_scope() { + for scope in [Scope::Class, Scope::Field, Scope::Method, Scope::Code] { + check_facts(&java_class::parse(&fixture(scope, 64)).unwrap()); + } +} + +fn memory_case(scope: Scope) { + let bytes = fixture(scope, 4096); + assert!(bytes.len() < 100_000); + check_facts(&java_class::parse(&bytes).unwrap()); +} + +// Run each ignored case separately with a 128 MiB process address-space limit. +// The original parser copies 256 MiB of one attribute name; the fixture itself +// is under 100 KiB. These checks deliberately make no timing assertion. +#[test] +#[ignore = "run separately under a process memory limit"] +fn repeated_class_attribute_names_fit_in_bounded_memory() { + memory_case(Scope::Class); +} + +#[test] +#[ignore = "run separately under a process memory limit"] +fn repeated_field_attribute_names_fit_in_bounded_memory() { + memory_case(Scope::Field); +} + +#[test] +#[ignore = "run separately under a process memory limit"] +fn repeated_method_attribute_names_fit_in_bounded_memory() { + memory_case(Scope::Method); +} + +#[test] +#[ignore = "run separately under a process memory limit"] +fn repeated_code_attribute_names_fit_in_bounded_memory() { + memory_case(Scope::Code); +} diff --git a/crates/java-class/src/regressions/java_constant_pool_slots.rs b/crates/java-class/src/regressions/java_constant_pool_slots.rs new file mode 100644 index 0000000000..15ad885673 --- /dev/null +++ b/crates/java-class/src/regressions/java_constant_pool_slots.rs @@ -0,0 +1,53 @@ +use crate::{FormatError, java_class}; + +fn class_with_pool(count: u16, pool: &[u8]) -> Vec { + let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 52]; + bytes.extend_from_slice(&count.to_be_bytes()); + bytes.extend_from_slice(pool); + bytes.extend_from_slice(&[0; 14]); + bytes +} + +#[test] +fn a_wide_constant_needs_its_reserved_slot() { + for tag in [5, 6] { + let mut pool = vec![tag]; + pool.extend_from_slice(&[0; 8]); + let bytes = class_with_pool(2, &pool); + assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot"))); + } +} + +#[test] +fn the_largest_pool_cannot_overflow_on_a_trailing_wide_constant() { + for tag in [5, 6] { + let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(u16::MAX) - 2); + pool.push(tag); + pool.extend_from_slice(&[0; 8]); + let bytes = class_with_pool(u16::MAX, &pool); + assert!(matches!(java_class::parse(&bytes), Err(FormatError::Malformed(message)) if message.contains("second slot"))); + } +} + +#[test] +fn a_wide_constant_with_two_remaining_slots_is_retained() { + for tag in [5, 6] { + for count in [3, u16::MAX] { + let mut pool = [3, 0, 0, 0, 0].repeat(usize::from(count) - 3); + pool.push(tag); + pool.extend_from_slice(&[0; 8]); + let parsed = java_class::parse(&class_with_pool(count, &pool)).unwrap(); + assert_eq!(parsed.pool.len(), usize::from(count)); + assert!(matches!(parsed.pool.last(), Some(java_class::Const::Unusable))); + assert!(matches!(parsed.pool[usize::from(count) - 2], java_class::Const::Long(_) | java_class::Const::Double(_))); + } + } +} + +#[test] +fn ordinary_final_constants_and_existing_classes_still_parse() { + let parsed = java_class::parse(&class_with_pool(2, &[3, 0, 0, 0, 7])).unwrap(); + assert_eq!(parsed.pool, vec![java_class::Const::Unusable, java_class::Const::Integer(7)]); + let parsed = java_class::parse(&crate::test_support::java::hello_class()).unwrap(); + assert!(!parsed.methods.is_empty()); +} diff --git a/crates/java-class/src/regressions/java_invoke_operands.rs b/crates/java-class/src/regressions/java_invoke_operands.rs new file mode 100644 index 0000000000..a99d8803b0 --- /dev/null +++ b/crates/java-class/src/regressions/java_invoke_operands.rs @@ -0,0 +1,76 @@ +use crate::java_class; +use crate::java_ops::{decode, decode_one}; + +#[test] +fn invokeinterface_requires_a_count_and_zero_reserved_byte() { + for code in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xb9, 0, 1, 255, 255]] { + assert!(decode_one(&code, 0).is_none(), "{code:?}"); + assert!(!decode(&code, 16).1); + } +} + +#[test] +fn invokedynamic_requires_both_reserved_bytes_to_be_zero() { + for code in [[0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1], [0xba, 0, 1, 255, 255]] { + assert!(decode_one(&code, 0).is_none(), "{code:?}"); + assert!(!decode(&code, 16).1); + } +} + +#[test] +fn valid_and_truncated_invocations_keep_their_boundaries() { + for count in [1, 2, 255] { + let instruction = decode_one(&[0xb9, 0x12, 0x34, count, 0], 0).unwrap(); + assert_eq!(instruction.cp_index, Some(0x1234)); + assert_eq!(instruction.len, 5); + } + let instruction = decode_one(&[0xba, 0x12, 0x34, 0, 0], 0).unwrap(); + assert_eq!(instruction.cp_index, Some(0x1234)); + for code in [[0xb9, 0, 1, 1, 0], [0xba, 0, 1, 0, 0]] { + for len in 1..5 { + assert!(decode_one(&code[..len], 0).is_none()); + } + } + let (instructions, complete) = decode(&[0xb9, 0, 1, 1, 0, 0xba, 0, 2, 0, 0, 0xb1], 16); + assert!(complete); + assert_eq!(instructions.len(), 3); + assert_eq!(instructions[2].pc, 10); +} + +fn reference_class() -> java_class::ClassFile { + let mut class = java_class::parse(&crate::test_support::java::hello_class()).unwrap(); + class.methods.retain(|method| method.name == "run"); + class +} + +#[test] +fn malformed_invocations_mark_reference_scans_incomplete() { + let valid = reference_class(); + let (expected, incomplete) = java_class::references(&valid, "java/io/PrintStream", None, 10); + assert!(!incomplete); + assert_eq!(expected.len(), 1); + for invalid in [[0xb9, 0, 1, 0, 0], [0xb9, 0, 1, 1, 1], [0xba, 0, 1, 1, 0], [0xba, 0, 1, 0, 1]] { + let mut class = valid.clone(); + let code = &mut class.methods[0].code.as_mut().unwrap().bytecode; + let later_reference = code.clone(); + *code = invalid.to_vec(); + code.extend_from_slice(&later_reference); + let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10); + assert!(found.is_empty()); + assert!(incomplete, "invalid invocation must not hide an unfinished reference scan: {invalid:?}"); + } +} + +#[test] +fn incomplete_scans_keep_earlier_references_and_scan_other_methods() { + let mut class = reference_class(); + let mut later_method = class.methods[0].clone(); + later_method.name = "later".into(); + class.methods[0].code.as_mut().unwrap().bytecode.extend_from_slice(&[0xba, 0, 1, 1, 0]); + class.methods.push(later_method); + let (found, incomplete) = java_class::references(&class, "java/io/PrintStream", None, 10); + assert!(incomplete); + assert_eq!(found.len(), 2); + assert!(found[0].caller.contains(".run:(")); + assert!(found[1].caller.contains(".later:(")); +} diff --git a/crates/java-class/src/regressions/java_linkage_references.rs b/crates/java-class/src/regressions/java_linkage_references.rs new file mode 100644 index 0000000000..7c05abe949 --- /dev/null +++ b/crates/java-class/src/regressions/java_linkage_references.rs @@ -0,0 +1,97 @@ +use crate::java_class::{parse, references}; + +/// A method with a chosen load or call, plus a dynamic call site and a dynamic constant with distinct bootstrap signatures. +fn class(code: &[u8]) -> Vec { + fn utf(s: &str) -> Vec { + let mut b = vec![1]; + b.extend((s.len() as u16).to_be_bytes()); + b.extend(s.bytes()); + b + } + let pool = [ + utf("Uses"), + vec![7, 0, 1], + utf("java/lang/Object"), + vec![7, 0, 3], + utf("run"), + utf("()V"), + utf("Code"), + utf("BootstrapMethods"), + utf("Target"), + vec![7, 0, 9], + utf("apply"), + vec![12, 0, 11, 0, 6], + vec![10, 0, 10, 0, 12], + vec![15, 6, 0, 13], + utf("Factory"), + vec![7, 0, 15], + utf("boot"), + vec![12, 0, 17, 0, 28], + vec![10, 0, 16, 0, 18], + vec![15, 6, 0, 19], + utf("([LTarget;)V"), + vec![16, 0, 21], + vec![18, 0, 0, 0, 12], + utf("value"), + utf("I"), + vec![12, 0, 24, 0, 25], + vec![17, 0, 1, 0, 26], + utf( + "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;)Ljava/lang/invoke/CallSite;", + ), + utf("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)I"), + vec![12, 0, 17, 0, 29], + vec![10, 0, 16, 0, 30], + vec![15, 6, 0, 31], + ]; + let mut bytes = vec![0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 55]; + bytes.extend((pool.len() as u16 + 1).to_be_bytes()); + for e in pool { + bytes.extend(e); + } + bytes.extend([0, 0x21, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0, 9, 0, 5, 0, 6, 0, 1, 0, 7]); + bytes.extend(((12 + code.len()) as u32).to_be_bytes()); + bytes.extend([0, 3, 0, 0]); + bytes.extend((code.len() as u32).to_be_bytes()); + bytes.extend(code); + bytes.extend([0, 0, 0, 0]); + let boots = [0, 2, 0, 20, 0, 1, 0, 14, 0, 32, 0, 0]; + bytes.extend([0, 1, 0, 8]); + bytes.extend((boots.len() as u32).to_be_bytes()); + bytes.extend(boots); + bytes +} +fn kinds(code: &[u8], owner: &str, method: Option<&str>) -> Vec<&'static str> { + let cf = parse(&class(code)).unwrap(); + let (hits, partial) = references(&cf, owner, method, 10); + assert!(!partial); + hits.into_iter().map(|r| r.kind).collect() +} +#[test] +fn class_literal_has_a_use_site() { + assert_eq!(kinds(&[0x12, 10, 0x57, 0xb1], "Target", None), ["type"]); +} +#[test] +fn literal_method_handle_finds_its_member() { + assert_eq!(kinds(&[0x12, 14, 0x57, 0xb1], "Target", Some("apply")), ["method-handle"]); +} +#[test] +fn method_type_mentions_object_array_components() { + assert_eq!(kinds(&[0x12, 22, 0x57, 0xb1], "Target", None), ["method-type"]); +} +#[test] +fn dynamic_call_exposes_factory_dependency() { + assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]); +} +#[test] +fn dynamic_call_exposes_static_method_handle_argument() { + assert_eq!(kinds(&[0xba, 0, 23, 0, 0, 0xb1], "Target", Some("apply")), ["method-handle"]); +} +#[test] +fn dynamic_constant_exposes_bootstrap_dependency() { + assert_eq!(kinds(&[0x12, 27, 0x57, 0xb1], "Factory", Some("boot")), ["bootstrap-method"]); +} +#[test] +fn unused_bootstrap_does_not_introduce_a_reference() { + assert!(kinds(&[0xb1], "Factory", None).is_empty()); +} diff --git a/crates/java-class/src/regressions/java_truncated_attributes.rs b/crates/java-class/src/regressions/java_truncated_attributes.rs new file mode 100644 index 0000000000..700640f331 --- /dev/null +++ b/crates/java-class/src/regressions/java_truncated_attributes.rs @@ -0,0 +1,46 @@ +use crate::java_class::parse; +use crate::test_support::java::hello_class; + +/// The fixture ends in a class attribute count and a single two-byte SourceFile attribute. +const ATTRIBUTE_TABLE_BYTES: usize = 10; + +/// Every cut of the attribute count, header or body leaves a partial class report. +#[test] +fn incomplete_class_attribute_table_reports_a_warning() { + let data = hello_class(); + let start = data.len() - ATTRIBUTE_TABLE_BYTES; + for end in start..data.len() { + let class = parse(&data[..end]).unwrap(); + assert_eq!(class.methods.len(), 4); + assert!(class.source_file.is_none()); + assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table")), "cut at {}", end - start); + } +} + +/// A complete attribute stays available when a subsequent attribute is cut short. +#[test] +fn completed_class_attributes_survive_a_truncated_record() { + let mut data = hello_class(); + let start = data.len() - ATTRIBUTE_TABLE_BYTES; + data[start..start + 2].copy_from_slice(&2u16.to_be_bytes()); + data.extend_from_slice(&[0, 1, 0, 0, 0, 2, 0]); + let class = parse(&data).unwrap(); + assert_eq!(class.source_file.as_deref(), Some("Hello.java")); + assert!(class.warnings.iter().any(|warning| warning.contains("class attribute table"))); +} + +/// Complete, empty and unknown class attributes do not trigger a truncation warning. +#[test] +fn complete_class_attribute_tables_are_accepted() { + let mut data = hello_class(); + let start = data.len() - ATTRIBUTE_TABLE_BYTES; + let original = parse(&data).unwrap(); + assert_eq!(original.source_file.as_deref(), Some("Hello.java")); + assert!(original.warnings.is_empty()); + data[start..start + 2].copy_from_slice(&2u16.to_be_bytes()); + data.extend_from_slice(&[0, 1, 0, 0, 0, 1, 0]); + assert!(parse(&data).unwrap().warnings.is_empty()); + data.truncate(start + 2); + data[start..].fill(0); + assert!(parse(&data).unwrap().warnings.is_empty()); +} diff --git a/crates/java-class/src/regressions/java_wide_opcodes.rs b/crates/java-class/src/regressions/java_wide_opcodes.rs new file mode 100644 index 0000000000..85c03ffaae --- /dev/null +++ b/crates/java-class/src/regressions/java_wide_opcodes.rs @@ -0,0 +1,33 @@ +use crate::java_ops::{decode, decode_one}; + +#[test] +fn only_defined_wide_opcodes_are_accepted() { + for op in 0..=255u8 { + let valid = matches!(op, 0x15..=0x19 | 0x36..=0x3a | 0x84 | 0xa9); + let code = [0xc4, op, 0x01, 0x2c, 0xff, 0xfe]; + assert_eq!(decode_one(&code, 0).is_some(), valid, "opcode {op:#x}"); + } +} + +#[test] +fn invalid_wide_does_not_invent_a_method_body() { + let (instructions, complete) = decode(&[0x00, 0xc4, 0xb1, 0, 1, 0xb1], 32); + assert!(!complete); + assert_eq!(instructions.len(), 1); + assert_eq!(instructions[0].name, "nop"); +} + +#[test] +fn wide_locals_and_signed_increments_are_preserved() { + for op in [0x15, 0x16, 0x17, 0x18, 0x19, 0x36, 0x37, 0x38, 0x39, 0x3a, 0xa9] { + let instruction = decode_one(&[0xc4, op, 0xff, 0xff], 0).unwrap(); + assert_eq!(instruction.local, Some(u16::MAX)); + assert_eq!(instruction.len, 4); + assert!(instruction.wide); + } + let instruction = decode_one(&[0xc4, 0x84, 0x01, 0x2c, 0xff, 0xfe], 0).unwrap(); + assert_eq!(instruction.local, Some(300)); + assert_eq!(instruction.int, Some(-2)); + assert_eq!(instruction.len, 6); + assert!(decode_one(&[0xc4, 0x84, 0x00, 1], 0).is_none()); +} diff --git a/crates/java-class/src/test_support.rs b/crates/java-class/src/test_support.rs new file mode 100644 index 0000000000..e2e13ddbdd --- /dev/null +++ b/crates/java-class/src/test_support.rs @@ -0,0 +1,276 @@ +pub use craft_testkit::sample_damage::{mutations, noise}; + +pub mod java { + use std::collections::HashMap; + + /// A constant-pool builder that interns entries and tracks the double slot after `Long`/`Double`. + #[derive(Default)] + struct Pool { + items: Vec>, + /// Next free index (1-based; accounts for long/double taking two slots). + count: u16, + cache: HashMap, + } + + impl Pool { + fn new() -> Self { + Pool { items: Vec::new(), count: 1, cache: HashMap::new() } + } + fn add(&mut self, bytes: Vec, slots: u16) -> u16 { + let idx = self.count; + self.items.push(bytes); + self.count += slots; + idx + } + fn utf8(&mut self, s: &str) -> u16 { + let key = format!("u:{s}"); + if let Some(&i) = self.cache.get(&key) { + return i; + } + let mut b = vec![1u8]; + b.extend_from_slice(&(s.len() as u16).to_be_bytes()); + b.extend_from_slice(s.as_bytes()); + let i = self.add(b, 1); + self.cache.insert(key, i); + i + } + fn class(&mut self, name: &str) -> u16 { + let n = self.utf8(name); + let key = format!("c:{name}"); + if let Some(&i) = self.cache.get(&key) { + return i; + } + let mut b = vec![7u8]; + b.extend_from_slice(&n.to_be_bytes()); + let i = self.add(b, 1); + self.cache.insert(key, i); + i + } + fn string(&mut self, s: &str) -> u16 { + let u = self.utf8(s); + let mut b = vec![8u8]; + b.extend_from_slice(&u.to_be_bytes()); + self.add(b, 1) + } + fn nat(&mut self, name: &str, desc: &str) -> u16 { + let n = self.utf8(name); + let d = self.utf8(desc); + let mut b = vec![12u8]; + b.extend_from_slice(&n.to_be_bytes()); + b.extend_from_slice(&d.to_be_bytes()); + self.add(b, 1) + } + fn reff(&mut self, tag: u8, owner: &str, name: &str, desc: &str) -> u16 { + let c = self.class(owner); + let nt = self.nat(name, desc); + let mut b = vec![tag]; + b.extend_from_slice(&c.to_be_bytes()); + b.extend_from_slice(&nt.to_be_bytes()); + self.add(b, 1) + } + fn long(&mut self, v: i64) -> u16 { + let mut b = vec![5u8]; + b.extend_from_slice(&v.to_be_bytes()); + self.add(b, 2) + } + /// The serialized constant pool and the count field. + fn finish(&self) -> (Vec, u16) { + (self.items.concat(), self.count) + } + } + + fn u16b(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_be_bytes()); + } + fn u32b(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_be_bytes()); + } + + /// Build an attribute: name_index, length, body. + fn attr(name_idx: u16, body: Vec) -> Vec { + let mut v = Vec::new(); + u16b(&mut v, name_idx); + u32b(&mut v, body.len() as u32); + v.extend_from_slice(&body); + v + } + + /// A method's `Code` attribute body (max_stack, max_locals, code, exception table, no nested attrs). + fn code_body(max_stack: u16, max_locals: u16, code: &[u8], exc: &[(u16, u16, u16, u16)]) -> Vec { + let mut v = Vec::new(); + u16b(&mut v, max_stack); + u16b(&mut v, max_locals); + u32b(&mut v, code.len() as u32); + v.extend_from_slice(code); + u16b(&mut v, exc.len() as u16); + for (s, e, h, t) in exc { + u16b(&mut v, *s); + u16b(&mut v, *e); + u16b(&mut v, *h); + u16b(&mut v, *t); + } + u16b(&mut v, 0); // nested attributes count + v + } + + /// A method_info: access, name, descriptor, and one already-built Code attribute. + fn method(p: &mut Pool, access: u16, name: &str, desc: &str, code_attribute: Vec) -> Vec { + let name_idx = p.utf8(name); + let desc_idx = p.utf8(desc); + let mut v = Vec::new(); + u16b(&mut v, access); + u16b(&mut v, name_idx); + u16b(&mut v, desc_idx); + u16b(&mut v, 1); // one attribute + v.extend_from_slice(&code_attribute); + v + } + + /// Assemble a whole class from its parts. + #[allow(clippy::too_many_arguments)] + fn assemble( + pool: &Pool, + access: u16, + this_c: u16, + super_c: u16, + interfaces: &[u16], + fields: &[Vec], + methods: &[Vec], + class_attrs: &[Vec], + ) -> Vec { + let (cp, count) = pool.finish(); + let mut v = Vec::new(); + v.extend_from_slice(&[0xca, 0xfe, 0xba, 0xbe]); + u16b(&mut v, 0); // minor + u16b(&mut v, 52); // major (Java 8) + u16b(&mut v, count); + v.extend_from_slice(&cp); + u16b(&mut v, access); + u16b(&mut v, this_c); + u16b(&mut v, super_c); + u16b(&mut v, interfaces.len() as u16); + for i in interfaces { + u16b(&mut v, *i); + } + u16b(&mut v, fields.len() as u16); + for f in fields { + v.extend_from_slice(f); + } + u16b(&mut v, methods.len() as u16); + for m in methods { + v.extend_from_slice(m); + } + u16b(&mut v, class_attrs.len() as u16); + for a in class_attrs { + v.extend_from_slice(a); + } + v + } + + pub const HELLO: &str = "Hello, Craft!"; + + /// `public class com.example.Hello implements Runnable` with a `count` field, a `BIG` long + /// constant, ``, `run()` (System.out.println("Hello, Craft!")), `pick(int)` (a tableswitch) + /// and `guarded()` (a try/catch over the println call). + pub fn hello_class() -> Vec { + let mut p = Pool::new(); + let this_c = p.class("com/example/Hello"); + let obj_c = p.class("java/lang/Object"); + let runnable_c = p.class("java/lang/Runnable"); + let code_attr = p.utf8("Code"); + + // fields: int count; static final long BIG; + let count_name = p.utf8("count"); + let i_desc = p.utf8("I"); + let big_name = p.utf8("BIG"); + let j_desc = p.utf8("J"); + let constval_attr = p.utf8("ConstantValue"); + let big_val = p.long(0x1122_3344_5566_7788); + + // refs used by code + let obj_init = p.reff(10, "java/lang/Object", "", "()V"); + let sysout = p.reff(9, "java/lang/System", "out", "Ljava/io/PrintStream;"); + let hello = p.string(HELLO); + let println = p.reff(10, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); + let rt_exc = p.class("java/lang/RuntimeException"); + + // (): aload_0; invokespecial Object.; return + let mut init = vec![0x2a, 0xb7]; + init.extend_from_slice(&obj_init.to_be_bytes()); + init.push(0xb1); + let init_m = method(&mut p, 0x0001, "", "()V", attr(code_attr, code_body(1, 1, &init, &[]))); + + // run(): getstatic System.out; ldc "Hello"; invokevirtual println; return + let mut run = vec![0xb2]; + run.extend_from_slice(&sysout.to_be_bytes()); + run.push(0x12); + run.push(hello as u8); // ldc (1-byte index; pool is small) + run.push(0xb6); + run.extend_from_slice(&println.to_be_bytes()); + run.push(0xb1); + let run_m = method(&mut p, 0x0001, "run", "()V", attr(code_attr, code_body(2, 1, &run, &[]))); + + // pick(int): iload_0; tableswitch{0->L0,1->L1,default->Ldef}; L0: bipush 10; ireturn; L1: bipush 20; ireturn; Ldef: iconst_m1; ireturn + // offsets: iload_1@0; tableswitch@1 (pad 2) ends @24; L0@24; L1@27; Ldef@30 + let mut pick = vec![0x1b, 0xaa, 0x00, 0x00]; + u32b(&mut pick, 29); // default -> 1+29 = 30 + u32b(&mut pick, 0); // low + u32b(&mut pick, 1); // high + u32b(&mut pick, 23); // case 0 -> 1+23 = 24 + u32b(&mut pick, 26); // case 1 -> 1+26 = 27 + debug_assert_eq!(pick.len(), 24); + pick.extend_from_slice(&[0x10, 10, 0xac]); // @24: bipush 10; ireturn + pick.extend_from_slice(&[0x10, 20, 0xac]); // @27: bipush 20; ireturn + pick.extend_from_slice(&[0x02, 0xac]); // @30: iconst_m1; ireturn + let pick_m = method(&mut p, 0x0001, "pick", "(I)I", attr(code_attr, code_body(1, 1, &pick, &[]))); + + // guarded(): try { System.out.println("Hello"); } catch (RuntimeException e) {} (then return) + // 0: getstatic(3) ; 3: ldc(2) ; 5: invokevirtual(3) ; 8: goto +5 ->13 ; 11: astore_1 ; 12: return ; 13: return + let mut g = vec![0xb2]; + g.extend_from_slice(&sysout.to_be_bytes()); + g.push(0x12); + g.push(hello as u8); + g.push(0xb6); + g.extend_from_slice(&println.to_be_bytes()); + g.extend_from_slice(&[0xa7, 0x00, 0x05]); // @8 goto -> 13 + g.push(0x4c); // @11 astore_1 + g.push(0xb1); // @12 return + g.push(0xb1); // @13 return + let guarded_m = method(&mut p, 0x0001, "guarded", "()V", attr(code_attr, code_body(2, 2, &g, &[(0, 8, 11, rt_exc)]))); + + // field infos + let field = |p: &mut Pool, access: u16, name_idx: u16, desc_idx: u16, attrs: &[Vec]| -> Vec { + let _ = p; + let mut v = Vec::new(); + u16b(&mut v, access); + u16b(&mut v, name_idx); + u16b(&mut v, desc_idx); + u16b(&mut v, attrs.len() as u16); + for a in attrs { + v.extend_from_slice(a); + } + v + }; + let count_f = field(&mut p, 0x0002, count_name, i_desc, &[]); // private int count + let mut cv = Vec::new(); + u16b(&mut cv, big_val); + let big_f = field(&mut p, 0x0019, big_name, j_desc, &[attr(constval_attr, cv)]); // public static final long BIG + + let source_attr = p.utf8("SourceFile"); + let source_val = p.utf8("Hello.java"); + let mut sf = Vec::new(); + u16b(&mut sf, source_val); + let source = attr(source_attr, sf); + + assemble( + &p, + 0x0021, // public super + this_c, + obj_c, + &[runnable_c], + &[count_f, big_f], + &[init_m, run_m, pick_m, guarded_m], + &[source], + ) + } +} diff --git a/crates/jpeg/src/encode.rs b/crates/jpeg/src/encode.rs index 548f4c9f96..fb5fe183c2 100644 --- a/crates/jpeg/src/encode.rs +++ b/crates/jpeg/src/encode.rs @@ -419,6 +419,34 @@ pub fn encode_baseline( sub: ChromaSubsampling, app_segments: &[(u8, Vec)], ) -> Result, EncodeError> { + validate_encode(data, width, height, channels, app_segments)?; + Ok(encode(data, width, height, channels, quality, sub, app_segments)) +} + +/// Encode the same optimized baseline JPEG as [`encode_baseline`], trading a second DCT pass +/// for working memory independent of image height. This path is sequential even when the +/// `parallel` feature is enabled. It retains only one MCU row of conversion planes and writes +/// directly into the returned encoded buffer: no image-wide tokens or duplicate coded buffer. +/// +/// Scratch consists of at most `24 * width + 8` floats (odd-width 4:2:0), plus fixed-size coding tables. +/// The caller still owns the input pixels and the returned JPEG; this is not a cap on output +/// size or a replacement for the caller's image/admission budget. Geometry, quality, metadata, +/// Huffman tables and restart boundaries match [`encode_baseline`] byte for byte. +#[allow(clippy::too_many_arguments)] +pub fn encode_baseline_low_memory( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], +) -> Result, EncodeError> { + validate_encode(data, width, height, channels, app_segments)?; + Ok(encode_impl(data, width, height, channels, quality, sub, app_segments, true, true)) +} + +fn validate_encode(data: &[u8], width: usize, height: usize, channels: usize, app_segments: &[(u8, Vec)]) -> Result<(), EncodeError> { let fits = width.checked_mul(height).and_then(|n| n.checked_mul(channels)).is_some_and(|n| n <= data.len()); if !fits || width == 0 || height == 0 || width > 65_535 || height > 65_535 || !matches!(channels, 1 | 3 | 4) { return Err(EncodeError::InvalidInput(format!("{width}x{height}, {channels} channels, {} bytes", data.len()))); @@ -426,7 +454,7 @@ pub fn encode_baseline( if app_segments.iter().any(|(marker, payload)| !(0xE0..=0xEF).contains(marker) || payload.len() > 65_533) { return Err(EncodeError::InvalidInput("APP markers must be 0xE0..=0xEF with payloads no larger than 65533 bytes".into())); } - Ok(encode(data, width, height, channels, quality, sub, app_segments)) + Ok(()) } /// [`encode`], with optimized Huffman tables or (`optimize` false) the Annex K example tables. @@ -440,6 +468,21 @@ fn encode_with( sub: ChromaSubsampling, app_segments: &[(u8, Vec)], optimize: bool, +) -> Vec { + encode_impl(data, width, height, channels, quality, sub, app_segments, optimize, false) +} + +#[allow(clippy::too_many_arguments)] +fn encode_impl( + data: &[u8], + width: usize, + height: usize, + channels: usize, + quality: u8, + sub: ChromaSubsampling, + app_segments: &[(u8, Vec)], + optimize: bool, + low_memory: bool, ) -> Vec { // The public entry takes caller-sized dimensions: refuse (an empty output) what would size an allocation from // them or index past `data`, rather than panic or allocate for them. @@ -509,6 +552,8 @@ fn encode_with( planes.push(Plane { w: cw, h: crows.len(), data: cb }); planes.push(Plane { w: cw, h: crows.len(), data: cr }); } + #[cfg(test)] + low_memory_tests::record_planes(planes.iter().map(|p| p.data.len()).sum()); planes }; @@ -519,45 +564,58 @@ fn encode_with( let (mx, my) = (width.div_ceil(mcu_w), height.div_ceil(mcu_h)); // restart interval: whole MCU rows per band, ≤ 65535 MCUs, enough bands to keep all cores busy let rows_per_band = (my / 64).clamp(1, (65_535 / mx.max(1)).max(1)); - let bands: Vec = (0..my.div_ceil(rows_per_band)).collect(); + let num_bands = my.div_ceil(rows_per_band); + let bands: Vec = if low_memory { Vec::new() } else { (0..num_bands).collect() }; // first pass: each band's quantized blocks as symbols, with their counts per table (DC // prediction restarts per band, as the restart markers say) - let tokenize_band = |band: &usize| -> (Vec, [Freq; 4]) { + let visit_band = |band: &usize, emit: &mut dyn FnMut(&[i16; 64], &mut i32, bool)| { let (mut blk, mut q) = ([0f32; 64], [0i16; 64]); - let (mut tokens, mut freq) = (Vec::new(), [[0u64; 256]; 4]); let mut pred = [0i32; 3]; let (m0, m1) = (band * rows_per_band, ((band + 1) * rows_per_band).min(my)); - // the band's planes, its MCU row `m0` at their top (blocks past the image's bottom repeat its last row, - // which is the band's last row then) - let planes = convert(m0 * mcu_h..(m1 * mcu_h).min(height), m0 * 8..(m1 * 8).min(ch)); for mcu_y in m0..m1 { - let mcu_y = mcu_y - m0; + // Convert only the current MCU row. DC predictors still span the original band, + // so its symbols/restart decisions are identical to whole-band conversion. + let planes = convert(mcu_y * mcu_h..((mcu_y + 1) * mcu_h).min(height), mcu_y * 8..((mcu_y + 1) * 8).min(ch)); for mcu_x in 0..mx { for vy in 0..vs { for hx in 0..hs { - planes[0].block(mcu_x * hs + hx, mcu_y * vs + vy, &mut blk); + planes[0].block(mcu_x * hs + hx, vy, &mut blk); fdct_quant(&blk, &rl, &mut q); - tokenize_block(&q, &mut pred[0], false, &mut tokens, &mut freq); + emit(&q, &mut pred[0], false); } } if !gray { for (plane, pred) in planes.iter().zip(pred.iter_mut()).take(3).skip(1) { - plane.block(mcu_x, mcu_y, &mut blk); + plane.block(mcu_x, 0, &mut blk); fdct_quant(&blk, &rc, &mut q); - tokenize_block(&q, pred, true, &mut tokens, &mut freq); + emit(&q, pred, true); } } } } + }; + let tokenize_band = |band: &usize| -> (Vec, [Freq; 4]) { + let (mut tokens, mut freq) = (Vec::new(), [[0u64; 256]; 4]); + visit_band(band, &mut |q, pred, chroma| tokenize_block(q, pred, chroma, &mut tokens, &mut freq)); + #[cfg(test)] + low_memory_tests::record_tokens(tokens.len()); (tokens, freq) }; #[cfg(feature = "parallel")] - let tokenized: Vec<(Vec, [Freq; 4])> = bands.par_iter().map(tokenize_band).collect(); + let tokenized: Vec<(Vec, [Freq; 4])> = if low_memory { Vec::new() } else { bands.par_iter().map(tokenize_band).collect() }; #[cfg(not(feature = "parallel"))] - let tokenized: Vec<(Vec, [Freq; 4])> = bands.iter().map(tokenize_band).collect(); + let tokenized: Vec<(Vec, [Freq; 4])> = if low_memory { Vec::new() } else { bands.iter().map(tokenize_band).collect() }; // the tables: DC luma, AC luma, DC chroma, AC chroma let tables: [([u8; 16], Vec); 4] = if optimize { let mut total = [[0u64; 256]; 4]; + if low_memory { + for band in 0..num_bands { + visit_band(&band, &mut |q, pred, chroma| { + let base = if chroma { 2 } else { 0 }; + block_symbols(q, pred, |ac, symbol, _, _| total[base + ac as usize][symbol & 0xFF] += 1); + }); + } + } for (_, f) in &tokenized { for (t, f) in total.iter_mut().zip(f) { for (t, f) in t.iter_mut().zip(f) { @@ -577,9 +635,9 @@ fn encode_with( let huff = tables.each_ref().map(|(bits, vals)| Huff::new(bits, vals)); // second pass: code the symbols #[cfg(feature = "parallel")] - let coded: Vec> = tokenized.into_par_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + let coded: Vec> = if low_memory { Vec::new() } else { tokenized.into_par_iter().map(|(t, _)| write_tokens(&t, &huff)).collect() }; #[cfg(not(feature = "parallel"))] - let coded: Vec> = tokenized.into_iter().map(|(t, _)| write_tokens(&t, &huff)).collect(); + let coded: Vec> = if low_memory { Vec::new() } else { tokenized.into_iter().map(|(t, _)| write_tokens(&t, &huff)).collect() }; // headers let mut out = Vec::with_capacity(coded.iter().map(Vec::len).sum::() + 4096); @@ -617,7 +675,7 @@ fn encode_with( dht(&mut out, 0x11, acb, acv); } let interval = (rows_per_band * mx) as u16; - if coded.len() > 1 { + if num_bands > 1 { segment(&mut out, 0xDD, &interval.to_be_bytes()); } if gray { @@ -625,11 +683,32 @@ fn encode_with( } else { segment(&mut out, 0xDA, &[3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]); } - let last = coded.len().saturating_sub(1); - for (i, c) in coded.iter().enumerate() { - out.extend_from_slice(c); - if i < last { - out.extend_from_slice(&[0xFF, 0xD0 + (i % 8) as u8]); + if low_memory { + let last = num_bands.saturating_sub(1); + for i in 0..num_bands { + // Continue directly in the final buffer, resetting entropy bits at the same band + // boundaries as the retained-token path. Only the output grows with image height. + let mut bits = Bits { out, acc: 0, n: 0 }; + visit_band(&i, &mut |q, pred, chroma| { + let base = if chroma { 2 } else { 0 }; + block_symbols(q, pred, |ac, symbol, extra, n| { + let (code, len) = huff[base + ac as usize].code[symbol & 0xFF]; + bits.put(code as u32, len as u32); + bits.put(extra & 0xFFFF, n & 0xF); + }); + }); + out = bits.finish(); + if i < last { + out.extend_from_slice(&[0xFF, 0xD0 + (i % 8) as u8]); + } + } + } else { + let last = coded.len().saturating_sub(1); + for (i, c) in coded.iter().enumerate() { + out.extend_from_slice(c); + if i < last { + out.extend_from_slice(&[0xFF, 0xD0 + (i % 8) as u8]); + } } } out.extend_from_slice(&[0xFF, 0xD9]); @@ -877,3 +956,7 @@ mod tests { assert!(psnr(&src, &px) > 35.0); } } + +#[cfg(test)] +#[path = "encode_low_memory_tests.rs"] +mod low_memory_tests; diff --git a/crates/jpeg/src/encode_low_memory_tests.rs b/crates/jpeg/src/encode_low_memory_tests.rs new file mode 100644 index 0000000000..de45f8dfe0 --- /dev/null +++ b/crates/jpeg/src/encode_low_memory_tests.rs @@ -0,0 +1,155 @@ +use super::*; +use std::cell::Cell; + +thread_local! { + static STATS: Cell<(usize, usize)> = const { Cell::new((0, 0)) }; +} + +pub(super) fn record_planes(samples: usize) { + STATS.with(|s| { + let (peak, tokens) = s.get(); + s.set((peak.max(samples), tokens)); + }); +} +pub(super) fn record_tokens(count: usize) { + STATS.with(|s| { + let (peak, tokens) = s.get(); + s.set((peak, tokens + count)); + }); +} + +fn noise(len: usize) -> Vec { + let mut seed = 0x89ab_cdefu32; + (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed as u8 + }) + .collect() +} + +fn compare(src: &[u8], w: usize, h: usize, ch: usize, q: u8, sub: ChromaSubsampling, app: &[(u8, Vec)]) { + let expected = encode_baseline(src, w, h, ch, q, sub, app).unwrap(); + STATS.with(|s| s.set((0, 0))); + let actual = encode_baseline_low_memory(src, w, h, ch, q, sub, app).unwrap(); + assert_eq!(actual, expected, "{w}x{h} channels={ch} quality={q} subsampling={sub:?}"); + let (peak, tokens) = STATS.with(Cell::get); + assert!(peak <= 24 * w + 8, "MCU-row scratch exceeded: {peak}"); + assert_eq!(tokens, 0, "low-memory mode retained entropy tokens"); +} + +#[test] +fn all_sampling_and_channels_match_retained_tokens_byte_for_byte() { + for (w, h) in [(1, 1), (7, 9), (17, 31), (33, 65), (17, 1025)] { + for ch in [1, 3, 4] { + let src = noise(w * h * ch); + for sub in [ChromaSubsampling::S444, ChromaSubsampling::S422, ChromaSubsampling::S420] { + for q in [0, 1, 25, 50, 90, 100, 255] { + compare(&src, w, h, ch, q, sub, &[]); + } + } + } + } +} + +#[test] +fn high_entropy_hd_and_wide_frames_keep_only_one_mcu_row() { + for (w, h) in [(1920, 1080), (65_535, 1)] { + let src = noise(w * h * 3); + compare(&src, w, h, 3, 100, ChromaSubsampling::S444, &[]); + } +} + +#[test] +fn metadata_empty_tables_and_extra_source_bytes_keep_exact_output() { + let app = [(0xe0, b"custom density".to_vec()), (0xe2, vec![73; 65_533])]; + for ch in [1, 3, 4] { + let src = vec![127; 19 * 23 * ch + 5]; + compare(&src, 19, 23, ch, 75, ChromaSubsampling::S420, &app); + } +} + +#[test] +fn checked_admission_matches_original_without_panics() { + for (w, h, ch) in [(0, 1, 3), (1, 0, 3), (1, 1, 0), (1, 1, 2), (usize::MAX, 2, 4), (65_536, 1, 1), (1, 65_536, 1), (4, 4, 3)] { + let src = vec![0; if w == 65_536 || h == 65_536 { 65_536 } else { 8 }]; + let old = encode_baseline(&src, w, h, ch, 90, ChromaSubsampling::S444, &[]); + let new = encode_baseline_low_memory(&src, w, h, ch, 90, ChromaSubsampling::S444, &[]); + assert!(new.is_err()); + assert_eq!(new, old); + } + for app in [vec![(0xdf, vec![])], vec![(0xf0, vec![])], vec![(0xe1, vec![0; 65_534])]] { + assert_eq!( + encode_baseline_low_memory(&[0; 3], 1, 1, 3, 90, ChromaSubsampling::S444, &app), + encode_baseline(&[0; 3], 1, 1, 3, 90, ChromaSubsampling::S444, &app) + ); + } +} + +// Generated with the immutable pre-change encoder at craft-libs +// 937ac93c5cf3cd4b6a81e195b078fe161eb081b9, not the refactored token-retaining path. +// Odd chroma edges and 1025/2049-row inputs exercise multi-row restart bands. +#[test] +fn prechange_encoded_bytes_remain_pinned_across_band_boundaries() { + let cases = [ + (1, 1, 1, 1, 444, 159, 0xe3bd59145381ba57), + (1, 1, 1, 75, 422, 159, 0xcb2b103914bbdbd3), + (1, 1, 1, 100, 420, 160, 0xd9f640613efb6abf), + (1, 1, 3, 1, 444, 284, 0x61d2772b8fd9df17), + (1, 1, 3, 75, 422, 286, 0xa0e03ab7efa23296), + (1, 1, 3, 100, 420, 288, 0x5660667f1abd0a63), + (1, 1, 4, 1, 444, 284, 0x61d2772b8fd9df17), + (1, 1, 4, 75, 422, 286, 0xa0e03ab7efa23296), + (1, 1, 4, 100, 420, 288, 0x5660667f1abd0a63), + (17, 31, 1, 1, 444, 240, 0xf8d277e9499253d4), + (17, 31, 1, 75, 422, 515, 0xa6946d4f144bf243), + (17, 31, 1, 100, 420, 793, 0xbb3db259708d8951), + (17, 31, 3, 1, 444, 363, 0xff2b5b41ffb3f81b), + (17, 31, 3, 75, 422, 877, 0x0374ffb527378dfe), + (17, 31, 3, 100, 420, 1220, 0x2feeedfa90885737), + (17, 31, 4, 1, 444, 366, 0xde7f8d1330e436eb), + (17, 31, 4, 75, 422, 879, 0xb1559fbfc3ee0cf6), + (17, 31, 4, 100, 420, 1214, 0xaf5dcf12d28c8e88), + (33, 65, 1, 1, 444, 388, 0xbee80491e42c8fd2), + (33, 65, 1, 75, 422, 1470, 0x284f4eb78b785ca5), + (33, 65, 1, 100, 420, 2576, 0xa81cc94015f326dc), + (33, 65, 3, 1, 444, 526, 0xf75b4036acc30874), + (33, 65, 3, 75, 422, 2322, 0x6fbc56bd9a1eec70), + (33, 65, 3, 100, 420, 3796, 0xcad25051562ac816), + (33, 65, 4, 1, 444, 527, 0x4bfedc11153de4c1), + (33, 65, 4, 75, 422, 2309, 0x47bf11bf32bac6a4), + (33, 65, 4, 100, 420, 3775, 0x64c2303fde273cd1), + (17, 1025, 1, 1, 444, 2017, 0x242f4a95d8579612), + (17, 1025, 1, 75, 422, 10728, 0xfe49408f379bdffb), + (17, 1025, 1, 100, 420, 19686, 0x1355b995e38d6467), + (17, 1025, 3, 1, 444, 2137, 0x4e319440cb6946c2), + (17, 1025, 3, 75, 422, 17682, 0xf456c63b731dde8f), + (17, 1025, 3, 100, 420, 29015, 0x0631001154b128cf), + (17, 1025, 4, 1, 444, 2155, 0xa2de9c1d77e62aa6), + (17, 1025, 4, 75, 422, 17648, 0x7d85fbdf56061f0c), + (17, 1025, 4, 100, 420, 29010, 0x4848eeb93daf1df2), + (19, 2049, 1, 1, 444, 3531, 0x9b93cf219ff85796), + (19, 2049, 1, 75, 422, 26283, 0xb160523444397608), + (19, 2049, 1, 100, 420, 51883, 0xc5c26836c0a976c6), + (19, 2049, 3, 1, 444, 3303, 0x26eaac2272e1fdb8), + (19, 2049, 3, 75, 422, 42745, 0x38b9843fb54db698), + (19, 2049, 3, 100, 420, 79868, 0xd6a7917af19682f7), + (19, 2049, 4, 1, 444, 3343, 0x6bf577903528692f), + (19, 2049, 4, 75, 422, 42706, 0x0e62366274593a93), + (19, 2049, 4, 100, 420, 79804, 0x867d05cf9d944599), + ]; + for (w, h, ch, q, sampling, len, hash) in cases { + let sub = match sampling { + 444 => ChromaSubsampling::S444, + 422 => ChromaSubsampling::S422, + _ => ChromaSubsampling::S420, + }; + let src = noise(w * h * ch); + for actual in [encode_baseline(&src, w, h, ch, q, sub, &[]).unwrap(), encode_baseline_low_memory(&src, w, h, ch, q, sub, &[]).unwrap()] { + let actual_hash = actual.iter().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3)); + assert_eq!((actual.len(), actual_hash), (len, hash), "{w}x{h} channels={ch} quality={q} sampling={sampling}"); + } + } +} diff --git a/crates/jpeg/src/lib.rs b/crates/jpeg/src/lib.rs index 23434fdd01..ed2ee1988f 100644 --- a/crates/jpeg/src/lib.rs +++ b/crates/jpeg/src/lib.rs @@ -1705,7 +1705,7 @@ mod tests; /// Baseline JPEG encoder (8-bit, Huffman-coded sequential DCT). mod encode; -pub use encode::{ChromaSubsampling, EncodeError, encode_baseline}; +pub use encode::{ChromaSubsampling, EncodeError, encode_baseline, encode_baseline_low_memory}; mod app14; pub use app14::adobe_transform; diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md index 074a0ac447..2f69e68c93 100644 --- a/crates/mcmat/README.md +++ b/crates/mcmat/README.md @@ -1,17 +1,10 @@ # 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. +The MCMAT v3 portable material is a ZIP containing a version-only `material.json`, one +`source.sbs`, and the required source assets under `resources/`. The sole root-level +material graph in the SBS is the entry. Applications inspect its exposed controls and +cook its outputs through MaterialCraft. Texture maps and MaterialX documents are generated +by exporters. Earlier archives must be republished from their original projects. -`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. +`Material::open` checks archive entries and expansion budgets before returning source +files. `write` compresses the XML and version marker and preserves source asset bytes. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 75b8709ef3..ca3fa7641b 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -1,133 +1,150 @@ #![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; +//! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde::Deserializer; +use serde::de::{IgnoredAny, MapAccess, Visitor}; +use std::collections::{BTreeMap, BTreeSet}; -pub const FORMAT: &str = "craft-material"; +pub const VERSION: u32 = 3; pub const MANIFEST_ENTRY: &str = "material.json"; +pub const SOURCE_ENTRY: &str = "source.sbs"; +const MARKER: &[u8] = br#"{"version":3}"#; -/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - pub graph: String, - pub size: [u32; 2], - pub maps: Vec, - #[serde(default)] - pub parameters: Vec, - #[serde(default)] - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - pub usage: String, - pub file: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -/// All limits are supplied by the consumer, including the versions it understands. #[derive(Clone, Copy, Debug)] pub struct Limits { - pub min_version: u32, - pub max_version: u32, pub max_entries: u64, - pub max_maps: usize, pub max_manifest_bytes: u64, pub max_entry_bytes: u64, pub max_total_bytes: u64, } +impl Default for Limits { + fn default() -> Self { + Self { max_entries: 100_000, max_manifest_bytes: 64 << 20, max_entry_bytes: 256 << 20, max_total_bytes: 1 << 30 } + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("invalid portable material: {0}")] Invalid(String), - #[error("unsupported portable material version {0}")] + #[error("unsupported .mcmat version {0} (expected 3). Republish from the original authoring project")] 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. +/// File sniffing also recognizes old manifests so the reader can give republishing guidance. 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)) + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }).is_ok_and(|archive| 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, +fn valid_resource(name: &str) -> bool { + name.len() <= 4096 + && name.starts_with("resources/") + && !name.contains(['\\', ':']) + && !name.chars().any(char::is_control) + && name.split('/').all(|part| !matches!(part, "" | "." | "..")) } -impl<'a> Material<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { +#[derive(Debug)] +pub struct Material { + pub source: Vec, + /// Keys are paths relative to source.sbs, including the resources/ prefix. + pub resources: BTreeMap>, +} + +impl Material { + pub fn open(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; - if archive.has_duplicate_names() { - return Err(Error::Invalid("duplicate archive entries".into())); + if archive.has_duplicate_names() || archive.has_overlapping_files()? { + return Err(Error::Invalid("duplicate or overlapping 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))); + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; + struct Marker; + impl<'de> Visitor<'de> for Marker { + type Value = (u32, bool); + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a version object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut version = None; + let mut extra = false; + while let Some(key) = map.next_key::()? { + if key == "version" { + if version.is_some() { + return Err(serde::de::Error::duplicate_field("version")); + } + version = Some(map.next_value::()?); + } else { + map.next_value::()?; + extra = true; + } + } + Ok((version.ok_or_else(|| serde::de::Error::missing_field("version"))?, extra)) + } } - if !(limits.min_version..=limits.max_version).contains(&manifest.version) { - return Err(Error::Version(manifest.version)); + let mut deserializer = serde_json::Deserializer::from_slice(&json); + let (version, extra) = deserializer.deserialize_map(Marker).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + deserializer.end().map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if version != VERSION { + return Err(Error::Version(version)); } - if manifest.maps.len() > limits.max_maps { - return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + if extra { + return Err(Error::Invalid("material.json must contain only the version".into())); } - Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) - } - - /// Read one named member, charging it to the same budget as previous reads. - pub fn read(&mut self, name: &str) -> Result, Error> { - self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) - } - - pub fn read_source(&mut self) -> Result, Error> { - self.read(&self.manifest.source.clone()) + let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; + let mut resources = BTreeMap::new(); + let mut seen = BTreeSet::new(); + for index in 0..archive.len() { + let name = archive.entry_name(index)?.ok_or_else(|| Error::Invalid("invalid entry name".into()))?; + if name == SOURCE_ENTRY || name == MANIFEST_ENTRY { + continue; + } + if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + if archive.entry_sizes(index)? != Some((0, 0)) { + return Err(Error::Invalid("directory entries must have no payload".into())); + } + continue; + } + if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + let data = archive.read_index(index, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + resources.insert(name, data); + } + Ok(Self { source, resources }) } } -/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. -pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result, Error> { - // Flattened fields must not serialize a second copy of a known key. - const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; - if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) - || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) - { - return Err(Error::Invalid("an extra field duplicates a known field".into())); - } - let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; +/// Write one SBS document with its referenced source assets. +pub fn write<'a>(source: &[u8], resources: impl IntoIterator) -> Result, Error> { + let limits = Limits::default(); let mut writer = Writer::new(); - writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; - for (name, bytes) in maps { - writer.add(name, bytes, Compression::Stored)?; + let mut seen = BTreeSet::new(); + let mut total = (source.len() as u64).saturating_add(MARKER.len() as u64); + if source.len() as u64 > limits.max_entry_bytes { + return Err(Error::Invalid("source.sbs exceeds the entry limit".into())); + } + writer.add(MANIFEST_ENTRY, MARKER, Compression::Deflated)?; + writer.add(SOURCE_ENTRY, source, Compression::Deflated)?; + for (name, bytes) in resources { + if !valid_resource(name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + total = total.saturating_add(bytes.len() as u64); + if bytes.len() as u64 > limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { + return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); + } + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()); + let compression = match extension.as_deref() { + Some("png" | "jpg" | "jpeg" | "webp" | "gif" | "exr" | "woff" | "woff2") => Compression::Stored, + _ => Compression::Deflated, + }; + writer.add(name, bytes, compression)?; } - writer.add(&manifest.source, source, Compression::Stored)?; Ok(writer.finish()?) } @@ -135,82 +152,108 @@ pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> 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); + fn procedural_source_and_assets_round_trip_under_one_budget() { + let bytes = write(b"", [("resources/oak.png", b"image".as_slice())]).unwrap(); + let pkg = Material::open(&bytes, Limits::default()).unwrap(); + assert_eq!(pkg.source, b""); + assert_eq!(pkg.resources["resources/oak.png"], b"image"); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 3, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.read(MANIFEST_ENTRY, 32).unwrap().unwrap(), MARKER); + assert_eq!(archive.is_stored(SOURCE_ENTRY), Some(false)); + assert_eq!(archive.is_stored("resources/oak.png"), Some(true)); + for limits in [ + Limits { max_entries: 2, ..Default::default() }, + Limits { max_entry_bytes: 2, ..Default::default() }, + Limits { max_total_bytes: 24, ..Default::default() }, + ] { + assert!(Material::open(&bytes, limits).is_err()); } } #[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()); + fn marker_requires_an_object_and_complete_input() { + for marker in [b"[3]".as_slice(), b"[2]", b"null", b"3", br#"{"version":3} {}"#, br#"{"version":3,"version":3}"#] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + assert!(matches!(Material::open(&zip.finish().unwrap(), Limits::default()), Err(Error::Invalid(_)))); + } } #[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()); + fn directory_members_must_be_empty() { + for payload in [b"".as_slice(), b"hidden"] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + zip.add("resources/", payload, Compression::Stored).unwrap(); + assert_eq!(Material::open(&zip.finish().unwrap(), Limits::default()).is_ok(), payload.is_empty()); + } } #[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()); + fn legacy_encoded_resource_names_read_by_index_under_one_budget() { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"s", Compression::Stored).unwrap(); + zip.add("resources/a.bin", b"data", Compression::Stored).unwrap(); + let mut bytes = zip.finish().unwrap(); + // Same-length CP437 name in both headers: no UTF-8 flag, 0x82 decodes to é. + let offsets: Vec<_> = + bytes.windows(b"resources/a.bin".len()).enumerate().filter_map(|(i, n)| (n == b"resources/a.bin").then_some(i + 10)).collect(); + assert_eq!(offsets.len(), 2); + for offset in offsets { + bytes[offset] = 0x82; + } + let total = MARKER.len() as u64 + 1 + 4; + let limits = Limits { max_total_bytes: total, ..Default::default() }; + let material = Material::open(&bytes, limits).unwrap(); + assert_eq!(material.resources["resources/é.bin"], b"data"); + assert!(Material::open(&bytes, Limits { max_total_bytes: total - 1, ..limits }).is_err()); + } + + #[test] + fn compresses_unencoded_source_assets() { + let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 4, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.is_stored("resources/shape.svg"), Some(false)); + assert_eq!(archive.is_stored("resources/font.ttf"), Some(false)); + } + + #[test] + fn rejects_previous_versions_before_requiring_the_v3_layout() { + for version in [0, 1, 2, 4] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, format!(r#"{{"format":"craft-material","version":{version}}}"#).as_bytes(), Compression::Deflated).unwrap(); + let bytes = zip.finish().unwrap(); + assert!(is_material(&bytes, 2)); + assert!(matches!(Material::open(&bytes, Limits::default()), Err(Error::Version(v)) if v == version)); + } + } + + #[test] + fn v3_requires_source_and_a_version_only_marker() { + for (marker, source) in [(MARKER, None), (br#"{"version":3,"graph":"Other"}"#.as_slice(), Some(b"".as_slice()))] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Deflated).unwrap(); + if let Some(source) = source { + zip.add(SOURCE_ENTRY, source, Compression::Deflated).unwrap(); + } + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + } + + #[test] + fn rejects_ambiguous_or_nonlocal_resource_members() { + for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] { + assert!(write(b"x", [(name, &b"x"[..])]).is_err()); + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + zip.add(name, b"x", Compression::Stored).unwrap(); + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err()); } } diff --git a/crates/mcp-server/src/lib.rs b/crates/mcp-server/src/lib.rs index 17e6827c4a..66568fc05b 100644 --- a/crates/mcp-server/src/lib.rs +++ b/crates/mcp-server/src/lib.rs @@ -15,7 +15,7 @@ mod server; pub use content::{Contents, base64, image_result, text_result}; pub use schema::{Effect, check_arguments, object, string, tool}; -pub use server::{Incoming, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; +pub use server::{Incoming, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; #[cfg(test)] mod tests; diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs index b7ed050272..e0d064da5e 100644 --- a/crates/mcp-server/src/server.rs +++ b/crates/mcp-server/src/server.rs @@ -4,7 +4,7 @@ use std::io::{BufRead, Write}; use serde_json::{Value, json}; -use crate::content::Contents; +use crate::content::{Contents, text_result}; use crate::schema::{check_arguments, check_prompt_arguments}; /// The newest protocol revision we speak; offered when the client asks for one we don't know. @@ -88,9 +88,25 @@ pub struct Info { pub max_line: usize, } +/// Opt-in behaviour for apps with their own conventions; `Options::default()` is what [`Server::new`] +/// does. Set with [`Server::with_options`]. +#[derive(Clone, Debug, Default)] +pub struct Options { + /// Sent as `serverInfo.websiteUrl` at `initialize` (MCP 2025-06-18) when set. + pub website_url: Option, + /// Report a `tools/call` whose arguments fail the check against the tool's schema, or whose + /// tool is unknown, as a tool result with `isError: true` and the message as text, not as a + /// JSON-RPC -32602 error. For apps whose clients read every tool failure from the result. + pub tool_errors_as_results: bool, + /// Refuse a request whose `id` is neither a string nor a number (JSON-RPC 2.0) with -32600 and + /// a null id, instead of echoing the id back. + pub strict_request_ids: bool, +} + /// An MCP server over the app's [`Tools`]. pub struct Server { info: Info, + options: Options, tools: T, initialized: bool, } @@ -157,7 +173,13 @@ pub fn response(id: Value, result: Value) -> Value { impl Server { pub fn new(info: Info, tools: T) -> Self { - Self { info, tools, initialized: false } + Self { info, options: Options::default(), tools, initialized: false } + } + /// This server with `options` ([`Options`]) in place of the defaults. + #[must_use] + pub fn with_options(mut self, options: Options) -> Self { + self.options = options; + self } pub fn tools(&mut self) -> &mut T { &mut self.tools @@ -215,7 +237,11 @@ impl Server { if o.contains_key("result") || o.contains_key("error") { return None; } - return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); + let echoed = match id { + Some(id) if !self.options.strict_request_ids || id.is_string() || id.is_number() => id, + _ => Value::Null, + }; + return Some(error(echoed, INVALID_REQUEST, "missing `method`")); }; let params = o.get("params").cloned().unwrap_or(Value::Null); let Some(id) = id else { @@ -224,6 +250,9 @@ impl Server { } return None; }; + if self.options.strict_request_ids && !(id.is_string() || id.is_number()) { + return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number")); + } Some(match self.request(method, ¶ms) { Ok(r) => response(id, r), Err((code, m)) => error(id, code, m), @@ -236,10 +265,14 @@ impl Server { let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION }; let Info { name, title, version: server_version, .. } = self.info; + let mut server_info = json!({"name": name, "title": title, "version": server_version}); + if let Some(url) = &self.options.website_url { + server_info["websiteUrl"] = json!(url); + } Ok(json!({ "protocolVersion": version, "capabilities": self.capabilities(), - "serverInfo": {"name": name, "title": title, "version": server_version}, + "serverInfo": server_info, "instructions": self.tools.instructions(), })) } @@ -251,7 +284,9 @@ impl Server { None | Some(Value::Null) => json!({}), Some(a) => a.clone(), }; - check_arguments(&self.tools.list(), name, &args).map_err(|e| (INVALID_PARAMS, e))?; + if let Err(e) = check_arguments(&self.tools.list(), name, &args) { + return if self.options.tool_errors_as_results { Ok(text_result(e, true)) } else { Err((INVALID_PARAMS, e)) }; + } Ok(self.tools.call(name, &args)) } "resources/list" => Ok(json!({"resources": self.tools.resources()})), diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs index b687ee2e81..3f8f8d315f 100644 --- a/crates/mcp-server/src/tests.rs +++ b/crates/mcp-server/src/tests.rs @@ -1,7 +1,8 @@ use serde_json::{Value, json}; use crate::{ - Contents, Effect, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, tool, + Contents, Effect, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, + tool, }; /// One app's tools: `echo` and `level`, nothing behind them (no engine, no design). `log` records @@ -366,3 +367,131 @@ fn every_call_runs_right_after_its_listing() { reply(&mut s, &json!([call("level", json!({})), call("echo", json!({"text": "b"}))])); assert_eq!(s.tools().log, ["list", "list", "call echo", "list", "list", "call level", "list", "call echo"]); } + +fn with(options: Options) -> Server { + Server::new(info(), Echo::default()).with_options(options) +} + +fn call_msg(id: u64, name: &str, args: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": args}}) +} + +/// `websiteUrl` is sent only when set. +#[test] +fn website_url_is_sent_only_when_set() { + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}); + let off = reply(&mut with(Options::default()), &init).unwrap(); + assert!(off["result"]["serverInfo"].get("websiteUrl").is_none(), "{off}"); + let on = reply(&mut with(Options { website_url: Some("https://example.org/echo".into()), ..Options::default() }), &init).unwrap(); + assert_eq!(on["result"]["serverInfo"]["websiteUrl"], "https://example.org/echo"); + assert_eq!(on["result"]["serverInfo"]["name"], "echo"); +} + +/// With `tool_errors_as_results`, argument failures and unknown tools are `isError` results that +/// carry the message and never run the tool; other errors stay JSON-RPC errors. +#[test] +fn tool_errors_as_results_replaces_invalid_params() { + let mut s = with(Options { tool_errors_as_results: true, ..Options::default() }); + let bad = [ + call_msg(1, "echo", json!({})), + call_msg(2, "echo", json!({"text": 3})), + call_msg(3, "echo", json!({"text": "a", "loud": true})), + call_msg(4, "shout", json!({})), + call_msg(5, "echo", json!([])), + call_msg(6, "echo", json!("text")), + call_msg(7, "echo", json!(7)), + ]; + for msg in &bad { + let r = reply(&mut s, msg).unwrap(); + assert!(r.get("error").is_none(), "{r}"); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.is_empty()), "{r}"); + } + let r = reply(&mut s, &bad[0]).unwrap(); + assert_eq!(r["result"]["content"][0]["text"], "echo: missing required argument `text`"); + assert!(s.tools().calls.is_empty()); + let ok = reply(&mut s, &call_msg(8, "echo", json!({"text": "hi"}))).unwrap(); + assert_eq!(ok["result"], json!({"content": [{"type": "text", "text": "hi"}]})); + let nomethod = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 9, "method": "nope"})).unwrap(); + assert_eq!(nomethod["error"]["code"], -32601); + let noname = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 10, "method": "tools/call", "params": {}})).unwrap(); + assert_eq!(noname["error"]["code"], -32602); + // Unchanged with the option off. + let mut off = with(Options::default()); + for msg in &bad { + assert_eq!(reply(&mut off, msg).unwrap()["error"]["code"], -32602); + } +} + +/// With `strict_request_ids`, an id that is not a string or number is -32600 with a null id; the +/// tool never runs. Off, such ids are echoed as before. Notifications have no id and are unaffected. +#[test] +fn strict_request_ids_refuse_other_id_types() { + let odd = [json!(null), json!(true), json!({"a": 1}), json!([1])]; + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in &odd { + let msg = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "x"}}}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!(r["error"]["code"], -32600, "{id}: {r}"); + assert_eq!(r["id"], Value::Null); + let r = reply(&mut off, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["id"], *id); + assert_eq!(r["result"], json!({})); + } + assert!(on.tools().calls.is_empty()); + for id in [json!("a"), json!(1), json!(1.5), json!(-3)] { + let r = reply(&mut on, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["result"], json!({}), "{id}"); + } + assert!(reply(&mut on, ¬ification()).is_none()); +} + +/// The missing-`method` error follows the same id rule: strict mode echoes only string and number +/// ids and answers with a null id for the rest; off, ids are echoed as before. +#[test] +fn strict_request_ids_apply_to_the_missing_method_error() { + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in [json!(true), json!({"a": 1}), json!([1])] { + let msg = json!({"jsonrpc": "2.0", "id": id}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!((r["error"]["code"].clone(), r["id"].clone()), (json!(-32600), Value::Null), "{id}"); + assert_eq!(reply(&mut off, &msg).unwrap()["id"], id); + } + for id in [json!("a"), json!(7)] { + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0", "id": id})).unwrap()["id"], id); + } + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0"})).unwrap()["id"], Value::Null); +} + +/// Hostile input with every option on: oversized and non-UTF-8 lines, odd ids and wrongly typed +/// arguments are answered and serving goes on, and nothing panics. +#[test] +fn every_option_on_survives_hostile_input() { + let mut input = vec![b'x'; (1 << 16) + 10]; + input.push(b'\n'); + input.extend_from_slice(b"\xff\xfe\n"); + for id in ["null", "true", "{}", "[]", "\"s\"", "1e999"] { + input.extend_from_slice( + format!( + "{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/call\",\"params\":{{\"name\":\"echo\",\"arguments\":{{\"text\":{id}}}}}}}\n" + ) + .as_bytes(), + ); + } + for args in ["null", "1", "\"a\"", "[]", "{\"text\":[1]}", "{\"text\":{}}"] { + input.extend_from_slice( + format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"level\",\"arguments\":{args}}}}}\n").as_bytes(), + ); + } + input.extend_from_slice(json!({"jsonrpc": "2.0", "id": 9, "method": "ping"}).to_string().as_bytes()); + let mut output = Vec::new(); + let options = Options { website_url: Some("https://example.org".into()), tool_errors_as_results: true, strict_request_ids: true }; + with(options).serve(std::io::Cursor::new(input), &mut output).unwrap(); + let replies: Vec = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 2 + 6 + 6 + 1, "{replies:?}"); + assert_eq!(replies[0]["error"]["code"], -32600); + assert_eq!(replies[1]["error"]["code"], -32700); + assert_eq!(replies.last().map(|r| &r["result"]), Some(&json!({}))); +} diff --git a/crates/media-testkit/src/hostile.rs b/crates/media-testkit/src/hostile.rs index f40021986e..ddfc55f791 100644 --- a/crates/media-testkit/src/hostile.rs +++ b/crates/media-testkit/src/hostile.rs @@ -3,9 +3,9 @@ //! thread with a time limit for each case. [`Rng`], [`mutations`] and the other names here are //! `craft_testkit`'s. +pub use craft_testkit::hostile::{DIVISOR_VARIABLE, MAX_CASES, Mutation, Mutations, Rng, mutations}; #[cfg(not(target_arch = "wasm32"))] -pub use craft_testkit::hostile::{HammerConfig, HammerError}; -pub use craft_testkit::hostile::{MAX_CASES, Mutation, Mutations, Rng, mutations}; +pub use craft_testkit::hostile::{HammerConfig, HammerError, divisor}; /// The variable that multiplies [`hammer`]'s iterations. #[cfg(not(target_arch = "wasm32"))] @@ -17,8 +17,10 @@ const MULTIPLIER_VARIABLE: &str = "CRAFT_MEDIA_HOSTILE_MULT"; /// Panics on the first case that panics or does not finish, naming `name`, the case, its length and /// the panic's message. /// -/// `CRAFT_MEDIA_HOSTILE_MULT=10` runs ten times the iterations (soak runs). A value that is not a -/// whole number above zero panics, naming the variable, before `run` is called. +/// `CRAFT_MEDIA_HOSTILE_MULT=10` runs ten times the iterations (soak runs), and +/// `CRAFT_HOSTILE_DIVISOR=8` every eighth truncation and an eighth of the iterations (pull +/// requests). A value that is not a whole number above zero panics, naming the variable, before +/// `run` is called. #[cfg(not(target_arch = "wasm32"))] #[track_caller] pub fn hammer(name: &str, seed: &[u8], iters: usize, run: impl Fn(&[u8]) + Send + Sync + 'static) { diff --git a/crates/media-testkit/src/lib.rs b/crates/media-testkit/src/lib.rs index 3fa99c54f2..db4c844f9e 100644 --- a/crates/media-testkit/src/lib.rs +++ b/crates/media-testkit/src/lib.rs @@ -13,7 +13,8 @@ //! //! [`hostile::hammer`] runs a parser over every truncation and mutations of a valid input and fails //! on a panic or a case that does not finish in time; `CRAFT_MEDIA_HOSTILE_MULT=10` runs ten times -//! the iterations. It and [`with_deadline`] call `craft_testkit`. +//! the iterations and `CRAFT_HOSTILE_DIVISOR=8` an eighth of them. It and [`with_deadline`] call +//! `craft_testkit`. //! [`vmd`] writes Sierra VMD fixtures, which ffmpeg can read but not write. //! //! Failing loudly is what a test helper is for: a wrong `CRAFT_MEDIA_*` setting or an unwritable diff --git a/crates/media-testkit/tests/hostile.rs b/crates/media-testkit/tests/hostile.rs index 8e34cd5afe..5281f4a411 100644 --- a/crates/media-testkit/tests/hostile.rs +++ b/crates/media-testkit/tests/hostile.rs @@ -5,7 +5,7 @@ use std::process::Command; use std::sync::{Arc, Mutex}; use std::time::Duration; -use craft_media_testkit::hostile::hammer; +use craft_media_testkit::hostile::{divisor, hammer}; /// Set only in the child processes of `run_child`: the value names what `child_hammer` does. const CHILD_VARIABLE: &str = "CRAFT_MEDIA_TESTKIT_HOSTILE_CHILD"; @@ -60,10 +60,11 @@ fn a_bad_multiplier_names_the_variable() { #[test] fn a_panic_keeps_its_message() { - let payload = std::panic::catch_unwind(|| hammer("demo", &[9, 8, 7, 6], 0, |d| assert!(d.len() != 2, "boom at {}", d.len()))).unwrap_err(); + // Truncation to 0 runs under any CRAFT_HOSTILE_DIVISOR. + let payload = std::panic::catch_unwind(|| hammer("demo", &[9, 8, 7, 6], 0, |d| assert!(!d.is_empty(), "boom at {}", d.len()))).unwrap_err(); let message = payload.downcast_ref::().cloned().unwrap_or_default(); - assert!(message.starts_with("demo: truncation to 2 (len 2): the parser panicked: "), "{message}"); - assert!(message.contains("boom at 2"), "{message}"); + assert!(message.starts_with("demo: truncation to 0 (len 0): the parser panicked: "), "{message}"); + assert!(message.contains("boom at 0"), "{message}"); } #[test] @@ -74,8 +75,8 @@ fn every_truncation_of_a_large_seed_runs() { hammer("large", &seed, 0, move |d| { record.lock().unwrap().insert(d.len()); }); - // The seed and its 8,192 truncations. - assert_eq!(lengths.lock().unwrap().len(), 8_193); + // The seed and its 8,192 truncations, every N-th of them under CRAFT_HOSTILE_DIVISOR=N. + assert_eq!(lengths.lock().unwrap().len(), 1 + 8_192usize.div_ceil(divisor())); } #[test] diff --git a/crates/media/src/mxf/tests/hostile.rs b/crates/media/src/mxf/tests/hostile.rs index 015413881c..6ff89ed152 100644 --- a/crates/media/src/mxf/tests/hostile.rs +++ b/crates/media/src/mxf/tests/hostile.rs @@ -51,27 +51,53 @@ fn sync_before_on_an_empty_track() { } } -#[test] -fn hostile_input_never_panics() { +// Keep each deterministic hammer independent so test runners can schedule the seeds separately. +// The labels, mutation counts, every-truncation coverage and per-case watchdog stay unchanged. +fn hostile_seeds() -> [Vec; 3] { let (to, flags) = ipbb(); - let seeds = [build(7, |i| vec![i as u8; 100 + i], &to, &flags), build(5, prores_like, &to, &flags), build(4, prores_like, &[], &flags)]; - for (i, s) in seeds.iter().enumerate() { - craft_media_testkit::hostile::hammer(&format!("mxf seed {i}"), s, 6_000, exercise); - } - // The metadata sets and index segments, parsed directly. - let seed = &seeds[0]; + [build(7, |i| vec![i as u8; 100 + i], &to, &flags), build(5, prores_like, &to, &flags), build(4, prores_like, &[], &flags)] +} + +#[test] +fn hostile_input_seed_0_never_panics() { + craft_media_testkit::hostile::hammer("mxf seed 0", &hostile_seeds()[0], 6_000, exercise); +} + +#[test] +fn hostile_input_seed_1_never_panics() { + craft_media_testkit::hostile::hammer("mxf seed 1", &hostile_seeds()[1], 6_000, exercise); +} + +#[test] +fn hostile_input_seed_2_never_panics() { + craft_media_testkit::hostile::hammer("mxf seed 2", &hostile_seeds()[2], 6_000, exercise); +} + +#[test] +fn hostile_index_segment_never_panics() { + let seed = &hostile_seeds()[0]; let index_key = [0x06, 0x0E, 0x2B, 0x34, 0x02, 0x53, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x10, 0x01, 0x00]; if let Some(v) = value_of(seed, &index_key) { craft_media_testkit::hostile::hammer("mxf index segment", v, 30_000, |d| { let _ = IndexSegment::parse(d); }); } +} + +#[test] +fn hostile_primer_never_panics() { + let seed = &hostile_seeds()[0]; let primer_key = [0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00]; if let Some(v) = value_of(seed, &primer_key) { craft_media_testkit::hostile::hammer("mxf primer", v, 5_000, |d| { let _ = Primer::parse(d); }); } +} + +#[test] +fn hostile_set_never_panics() { + let seed = &hostile_seeds()[0]; let set = seed.windows(16).position(|w| w == set_key(0x18)).and_then(|at| value_of(&seed[at..], &set_key(0x18))); if let Some(v) = set { craft_media_testkit::hostile::hammer("mxf set", v, 20_000, |d| { diff --git a/crates/mesh/README.md b/crates/mesh/README.md index 8c0cdec000..df32e7a599 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -24,8 +24,9 @@ USD, Alembic and COLLADA are not here yet. - `Part`: the faces of a mesh that share a group name, a material and a smoothing group. A face is a polygon of three or more `Corner`s; each corner indexes a position and optionally a normal and a UV. Formats with separate indices (OBJ) are kept exactly, and polygons stay whole. - `Part::triangles()` fans them; `Mesh::unified()` gives one vertex per distinct corner as a - triangle list, which is what a renderer wants. + `Part::triangles_in(&mesh.positions)` triangulates them (a fan for a convex face, ear clipping + in the face's plane for a concave one; `Part::triangles()` only fans); `Mesh::unified()` gives + one vertex per distinct corner as a triangle list, which is what a renderer wants. - `Material`: metallic-roughness factors, alpha mode, double-sided, unlit, and five texture slots. A `TextureRef` names an `Image`, a UV set and wrap modes. An `Image` is a URI the caller resolves or the encoded bytes the file embedded; nothing here decodes images. diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index c92051b846..d074f1ed12 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -120,6 +120,16 @@ pub fn uri_decode(s: &str) -> String { String::from_utf8_lossy(&percent_decode(s)).into_owned() } +/// Percent-decode a URI, rejecting decoded bytes that are not UTF-8. +/// +/// As with [`uri_decode`], incomplete or non-hex escapes stay literal and `+` stays +/// `+`. This does not validate or confine a filesystem path; callers must retain +/// their own reference policy. Decoding is linear and output is no larger than input. +/// Use this instead of the lossy decoder when a resolver requires exact UTF-8 names. +pub fn uri_decode_strict(s: &str) -> Option { + String::from_utf8(percent_decode(s)).ok() +} + /// [`uri_decode`] as bytes, so escaped bytes that are not UTF-8 survive. fn percent_decode(s: &str) -> Vec { let b = s.as_bytes(); diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index 6017c8dd24..4808834fa4 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -47,6 +47,7 @@ pub mod ply; pub mod stl; #[cfg(feature = "threemf")] pub mod threemf; +mod triangulate; use std::collections::HashMap; use std::fmt; @@ -193,7 +194,8 @@ impl Part { }) } - /// The faces as triangles: a polygon becomes a fan from its first corner. + /// The faces as triangles: a polygon becomes a fan from its first corner, which is right + /// only for a convex face. [`Part::triangles_in`] triangulates concave faces too. pub fn triangles(&self) -> impl Iterator + '_ { self.faces().flat_map(|f| { let first = f.first().copied(); @@ -204,7 +206,19 @@ impl Part { }) } - /// Triangles the faces fan into. + /// The faces as triangles, with `positions` (the mesh's [`Mesh::positions`]) to see their + /// shape. A convex face becomes a fan from its first corner, as in [`Part::triangles`]; a + /// concave one is triangulated by ear clipping in its own plane, so no triangle covers a + /// notch. Each triangle keeps the face's winding. A face with a corner that has no position, + /// or with no area, keeps the fan. What is left of a face when no ear can be found (it + /// crosses itself) or the part's work budget (256 steps per corner) is spent is + /// fanned. Every face gives `corners − 2` triangles, as [`Part::triangle_count`] counts. + pub fn triangles_in<'a>(&'a self, positions: &'a [[f64; 3]]) -> impl Iterator + 'a { + let mut budget = triangulate::WORK_PER_CORNER.saturating_mul(self.corners.len()); + self.faces().flat_map(move |f| triangulate::face(f, positions, &mut budget)) + } + + /// Triangles the faces give: `corners − 2` each. pub fn triangle_count(&self) -> usize { if self.face_sizes.is_empty() { self.corners.len() / 3 } else { self.face_sizes.iter().map(|n| (*n as usize).saturating_sub(2)).sum() } } @@ -291,8 +305,8 @@ impl Mesh { Ok(()) } - /// The mesh as triangles with one vertex per distinct corner. Corners whose indices are out - /// of range are dropped with their triangle. + /// The mesh as triangles ([`Part::triangles_in`]) with one vertex per distinct corner. + /// Corners whose indices are out of range are dropped with their triangle. pub fn unified(&self) -> Unified { let mut out = Unified::default(); let all = |f: &dyn Fn(&Corner) -> bool| self.parts.iter().all(|p| p.corners.iter().all(f)); @@ -302,7 +316,7 @@ impl Mesh { let mut ids: HashMap = HashMap::new(); for part in &self.parts { let mut tris = Vec::with_capacity(part.triangle_count()); - 'tri: for t in part.triangles() { + 'tri: for t in part.triangles_in(&self.positions) { let mut tri = [0u32; 3]; for (slot, c) in tri.iter_mut().zip(t) { let key = Corner { diff --git a/crates/mesh/src/stl.rs b/crates/mesh/src/stl.rs index e60911a7ad..444db5f67b 100644 --- a/crates/mesh/src/stl.rs +++ b/crates/mesh/src/stl.rs @@ -238,7 +238,7 @@ fn ascii(bytes: &[u8], limits: &Limits) -> Result { fn triangles(scene: &Scene, limits: &Limits, mut each: impl FnMut([f64; 3], [[f64; 3]; 3])) -> Result<()> { for (index, world) in scene.instances(limits)? { let Some(mesh) = scene.meshes.get(index) else { continue }; - for t in mesh.parts.iter().flat_map(Part::triangles) { + for t in mesh.parts.iter().flat_map(|p| p.triangles_in(&mesh.positions)) { let p = t.map(|c| mesh.positions.get(c.position as usize).copied()); let [Some(a), Some(b), Some(c)] = p else { return Err(malformed(KIND, "a corner index is out of range")) }; // A mirrored placement turns the winding; turn it back so the facet faces out. diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index 160b5b3dcd..423732de80 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -14,6 +14,7 @@ mod ply; mod stl; #[cfg(feature = "threemf")] mod threemf; +mod triangulate; /// Every truncation of `good` and two mutations of every byte go through `read`: it may refuse /// them, it must not panic, and what it accepts must be a valid scene. diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 8892fe2414..c47b911df8 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -950,3 +950,32 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } + +#[test] +fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { + use crate::gltf::uri_decode_strict; + for (input, expected) in [ + ("", Some("")), + ("a+b", Some("a+b")), + ("a%20b", Some("a b")), + ("é/%E2%82%AC", Some("é/€")), + ("%", Some("%")), + ("%2", Some("%2")), + ("%GG", Some("%GG")), + ("%252e%252e", Some("%2e%2e")), + ("%2e%2e%2fmesh.bin", Some("../mesh.bin")), + ("%00", Some("\0")), + ("%FF", None), + ("%C0%AF", None), + ("%ED%A0%80", None), + ("%E2%82", None), + ] { + assert_eq!(uri_decode_strict(input).as_deref(), expected, "{input}"); + } + // Keep the existing API's replacement-character behavior unchanged. + assert_eq!(uri_decode("%FF"), "�"); + let input = "%41%GG+é".repeat(100_000); + let decoded = uri_decode_strict(&input).unwrap(); + assert_eq!(decoded, "A%GG+é".repeat(100_000)); + assert!(decoded.len() <= input.len()); +} diff --git a/crates/mesh/src/tests/triangulate.rs b/crates/mesh/src/tests/triangulate.rs new file mode 100644 index 0000000000..2bb0c3f6c4 --- /dev/null +++ b/crates/mesh/src/tests/triangulate.rs @@ -0,0 +1,147 @@ +//! Triangulating concave faces ([`Part::triangles_in`]). + +use super::*; + +/// A one-face part over corners `0..n`. +fn polygon(n: usize) -> Part { + Part { face_sizes: vec![n as u32], corners: (0..n as u32).map(Corner::at).collect(), ..Part::default() } +} + +/// Twice the signed area of a 2D triangle or of a closed 2D polygon. +fn area2(p: &[[f64; 2]]) -> f64 { + (0..p.len()).map(|i| p[i][0] * p[(i + 1) % p.len()][1] - p[(i + 1) % p.len()][0] * p[i][1]).sum() +} + +/// Whether `q` is strictly inside the 2D polygon `p`, by the even-odd rule. +fn inside(p: &[[f64; 2]], q: [f64; 2]) -> bool { + let mut odd = false; + for i in 0..p.len() { + let (a, b) = (p[i], p[(i + 1) % p.len()]); + if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]) { + odd = !odd; + } + } + odd +} + +/// Places the 2D outline on a tilted plane in 3D, so the triangulation has to find the plane. +fn lift(outline: &[[f64; 2]]) -> Vec<[f64; 3]> { + // An orthonormal basis of the plane through (1, 2, 3), its normal leaning on every axis. + let (u, v) = ([2.0 / 3.0, 2.0 / 3.0, -1.0 / 3.0], [-1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0]); + outline.iter().map(|p| [0, 1, 2].map(|k| [1.0, 2.0, 3.0][k] + p[0] * u[k] + p[1] * v[k])).collect() +} + +/// Triangulates `outline` as one face lifted into 3D, and checks the triangles tile it: one +/// fewer than two per corner, each wound as the outline is and lying inside it (three points +/// inside every triangle are inside the outline), and their areas adding up to the outline's. +fn assert_tiles(outline: &[[f64; 2]]) -> Vec<[u32; 3]> { + let positions = lift(outline); + let tris: Vec<[u32; 3]> = polygon(outline.len()).triangles_in(&positions).map(|t| t.map(|c| c.position)).collect(); + assert_eq!(tris.len(), outline.len() - 2, "{tris:?}"); + let whole = area2(outline); + let mut sum = 0.0; + for t in &tris { + let p = t.map(|i| outline[i as usize]); + let a = area2(&p); + assert!(a * whole.signum() > 0.0, "{t:?} is wound against the outline or has no area"); + sum += a.abs(); + for w in [[1.0, 1.0, 1.0], [4.0, 1.0, 1.0], [1.0, 4.0, 1.0], [1.0, 1.0, 4.0]] { + let n: f64 = w.iter().sum(); + let q = [0, 1].map(|k| (0..3).map(|j| p[j][k] * w[j]).sum::() / n); + assert!(inside(outline, q), "{t:?} leaves the outline at {q:?}"); + } + } + assert!((sum - whole.abs()).abs() < 1e-9 * whole.abs(), "areas {sum} and {whole}"); + tris +} + +#[test] +fn concave_faces_are_not_fanned_across_their_notch() { + // The issue's face: a fan from (0, 0) covers the notch between (2, 2), (1, 0.5) and (0, 2). + let notch = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [1.0, 0.5], [0.0, 2.0]]; + let fan: Vec<[u32; 3]> = polygon(5).triangles().map(|t| t.map(|c| c.position)).collect(); + assert_eq!(fan, [[0, 1, 2], [0, 2, 3], [0, 3, 4]]); + let tris = assert_tiles(¬ch); + assert_ne!(tris, fan); + // The same face wound the other way. + let mut cw = notch; + cw.reverse(); + assert_tiles(&cw); + // An L, a comb with nine teeth, a ten-pointed star and an arrow with straight corners. + assert_tiles(&[[0.0, 0.0], [3.0, 0.0], [3.0, 1.0], [1.0, 1.0], [1.0, 3.0], [0.0, 3.0]]); + let mut comb = vec![[0.0, 0.0], [18.0, 0.0]]; + for k in (0..9).rev() { + let x = 2.0 * k as f64; + comb.extend([[x + 2.0, 5.0], [x + 1.0, 5.0], [x + 1.0, 1.0]]); + } + comb.pop(); + assert_tiles(&comb); + let star: Vec<[f64; 2]> = (0..20) + .map(|k| { + let (r, a) = (if k % 2 == 0 { 3.0 } else { 1.0 }, k as f64 * std::f64::consts::PI / 10.0); + [r * a.cos(), r * a.sin()] + }) + .collect(); + assert_tiles(&star); + assert_tiles(&[[0.0, 1.0], [2.0, 1.0], [4.0, 1.0], [4.0, 0.0], [6.0, 2.0], [4.0, 4.0], [4.0, 3.0], [2.0, 3.0], [0.0, 3.0]]); +} + +#[test] +fn convex_faces_keep_their_fan() { + let hexagon: Vec<[f64; 2]> = (0..6).map(|k| [(k as f64).cos(), (k as f64).sin()]).collect(); + let positions = lift(&hexagon); + let part = polygon(6); + assert_eq!(part.triangles_in(&positions).collect::>(), part.triangles().collect::>()); + // A square with a straight corner on one side is still convex. + let square = lift(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]); + assert_eq!(polygon(5).triangles_in(&square).collect::>(), polygon(5).triangles().collect::>()); +} + +#[test] +fn faces_that_cannot_be_clipped_keep_their_triangle_count() { + // No positions, a face with no area, and a bow tie that crosses itself. + let bow = lift(&[[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 2.0]]); + let flat = lift(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]]); + for positions in [&[][..], &flat, &bow] { + assert_eq!(polygon(4).triangles_in(positions).count(), 2); + } + // A comb of 4000 teeth: the work stays bounded and every triangle is still given. + let mut comb = vec![[0.0, 0.0], [8000.0, 0.0]]; + for k in (0..4000).rev() { + let x = 2.0 * k as f64; + comb.extend([[x + 2.0, 5.0], [x + 1.0, 5.0], [x + 1.0, 1.0]]); + } + let positions = lift(&comb); + let part = polygon(comb.len()); + assert_eq!(part.triangles_in(&positions).count(), part.triangle_count()); +} + +#[test] +fn unified_and_stl_use_the_clipped_triangles() { + let notch = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [1.0, 0.5], [0.0, 2.0]]; + let mesh = Mesh { name: "Notch".into(), positions: lift(¬ch), parts: vec![polygon(5)], ..Mesh::default() }; + let expected: Vec<[u32; 3]> = mesh.parts[0].triangles_in(&mesh.positions).map(|t| t.map(|c| c.position)).collect(); + let u = mesh.unified(); + let got: Vec<[u32; 3]> = u.parts[0].iter().map(|t| t.map(|i| u.corners[i as usize].position)).collect(); + assert_eq!(got, expected); + #[cfg(feature = "stl")] + { + let scene = Scene::from_meshes(vec![mesh.clone()], vec![]); + let text = crate::stl::write_ascii(&scene, "n", &Limits::default()).unwrap(); + let back = crate::stl::read(text.as_bytes(), &Limits::default()).unwrap(); + // The facets' area is the face's, 2.5, not the fan's 3.5. + let m = &back.meshes[0]; + let area: f64 = m + .parts + .iter() + .flat_map(Part::triangles) + .map(|t| { + let p = t.map(|c| m.positions[c.position as usize]); + let (a, b) = ([0, 1, 2].map(|k| p[1][k] - p[0][k]), [0, 1, 2].map(|k| p[2][k] - p[0][k])); + let n = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt() / 2.0 + }) + .sum(); + assert!((area - 2.5).abs() < 1e-6, "{area}"); + } +} diff --git a/crates/mesh/src/triangulate.rs b/crates/mesh/src/triangulate.rs new file mode 100644 index 0000000000..84e3dd34a5 --- /dev/null +++ b/crates/mesh/src/triangulate.rs @@ -0,0 +1,226 @@ +//! Triangulating one polygon face: a fan for a convex face, ear clipping for a concave one. +//! +//! The face is projected onto the plane of its two minor axes (dropping the largest component +//! of its Newell normal) and clipped there. Work is charged to a budget the caller shares +//! between the faces of a part, so a crafted face cannot make it quadratic in the file's size; +//! when the budget runs out, or no ear can be found (a self-intersecting face), what is left of +//! the face is fanned. A face always gives `corners − 2` triangles, wound as the face is. + +use crate::Corner; + +/// Steps (ear checks, containment tests, looks for a straight corner) allowed per corner of a +/// part, shared by its faces. +pub(crate) const WORK_PER_CORNER: usize = 256; + +/// Relative tolerance under which a turn counts as straight. +const STRAIGHT: f64 = 1e-12; + +/// The triangles of one face. +pub(crate) enum FaceTriangles<'a> { + /// A fan from the first corner; `next` is the corner the next triangle starts its edge at. + Fan { face: &'a [Corner], next: usize }, + /// Triangles clipped from a concave face. + Ears(std::vec::IntoIter<[Corner; 3]>), +} + +impl Iterator for FaceTriangles<'_> { + type Item = [Corner; 3]; + + fn next(&mut self) -> Option<[Corner; 3]> { + match self { + FaceTriangles::Fan { face, next } => { + let t = [*face.first()?, *face.get(*next)?, *face.get(*next + 1)?]; + *next += 1; + Some(t) + } + FaceTriangles::Ears(it) => it.next(), + } + } +} + +/// Triangulates `face`, whose corners index `positions`, charging its work to `budget`. +pub(crate) fn face<'a>(face: &'a [Corner], positions: &[[f64; 3]], budget: &mut usize) -> FaceTriangles<'a> { + let fan = FaceTriangles::Fan { face, next: 1 }; + if face.len() <= 3 { + return fan; + } + let Some(pts) = project(face, positions) else { return fan }; + let area: f64 = (0..pts.len()).map(|i| cross(pts[i], pts[(i + 1) % pts.len()])).sum(); + if !area.is_finite() || area == 0.0 { + return fan; + } + let ring = Ring::new(pts, area.signum()); + if ring.is_convex() { + return fan; + } + FaceTriangles::Ears(ring.clip(face, budget).into_iter()) +} + +/// The face's corners in 2D, on the plane of the two axes its Newell normal leans on least; +/// `None` when a corner has no position or the face has no finite normal. +fn project(face: &[Corner], positions: &[[f64; 3]]) -> Option> { + let p: Vec<[f64; 3]> = face.iter().map(|c| positions.get(c.position as usize).copied()).collect::>()?; + let mut n = [0.0f64; 3]; + for (i, a) in p.iter().enumerate() { + let b = p[(i + 1) % p.len()]; + n[0] += (a[1] - b[1]) * (a[2] + b[2]); + n[1] += (a[2] - b[2]) * (a[0] + b[0]); + n[2] += (a[0] - b[0]) * (a[1] + b[1]); + } + let n = n.map(f64::abs); + if !n.iter().all(|x| x.is_finite()) { + return None; + } + // Drop the dominant axis, keeping the other two in cyclic order so the winding seen from the + // normal's side is kept; the sign of the projected area decides orientation anyway. + let (u, v) = if n[0] >= n[1] && n[0] >= n[2] { + (1, 2) + } else if n[1] >= n[2] { + (2, 0) + } else { + (0, 1) + }; + Some(p.iter().map(|q| [q[u], q[v]]).collect()) +} + +/// The z component of `a × b`. +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +/// Twice the signed area of triangle `a b c`. +fn orient(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 { + (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) +} + +/// A face's projected corners as a doubly linked ring that ears are clipped from. +struct Ring { + pts: Vec<[f64; 2]>, + /// The sign of the face's projected area: turns of this sign are convex. + sign: f64, + prev: Vec, + next: Vec, +} + +impl Ring { + fn new(pts: Vec<[f64; 2]>, sign: f64) -> Ring { + let n = pts.len(); + Ring { pts, sign, prev: (0..n).map(|i| (i + n - 1) % n).collect(), next: (0..n).map(|i| (i + 1) % n).collect() } + } + + /// The turn at corner `i`, positive when convex; and the tolerance under which it is straight. + fn turn(&self, i: usize) -> (f64, f64) { + let (a, b, c) = (self.pts[self.prev[i]], self.pts[i], self.pts[self.next[i]]); + let (e, f) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]); + (cross(e, f) * self.sign, STRAIGHT * e[0].hypot(e[1]) * f[0].hypot(f[1])) + } + + /// No corner turns the other way. A face that winds round more than once (a pentagram) + /// counts as convex too and keeps its fan. + fn is_convex(&self) -> bool { + (0..self.pts.len()).all(|i| { + let (t, tol) = self.turn(i); + t >= -tol + }) + } + + /// Whether the triangle at corner `i` is an ear: convex, and no corner that is not convex + /// lies in it or on its edges (corners at the same place as one of its own excepted). + /// `None` when `budget` runs out. + fn is_ear(&self, i: usize, reflex: &[usize], budget: &mut usize) -> Option { + *budget = budget.checked_sub(1)?; + let (t, tol) = self.turn(i); + if t <= tol { + return Some(false); + } + let (a, b, c) = (self.pts[self.prev[i]], self.pts[i], self.pts[self.next[i]]); + for &r in reflex { + *budget = budget.checked_sub(1)?; + let p = self.pts[r]; + let (turn, tol) = self.turn(r); + if p == a || p == b || p == c || turn > tol { + continue; + } + if self.left_of(a, b, p) && self.left_of(b, c, p) && self.left_of(c, a, p) { + return Some(false); + } + } + Some(true) + } + + /// Whether `p` lies on the inner side of edge `a b`, or on it within rounding (a corner on an + /// ear's edge, after the face is projected, may land a hair outside). + fn left_of(&self, a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> bool { + let l1 = |u: [f64; 2], v: [f64; 2]| (v[0] - u[0]).abs() + (v[1] - u[1]).abs(); + orient(a, b, p) * self.sign >= -STRAIGHT * l1(a, b) * l1(a, p) + } + + /// The first straight corner of the `left` corners from `from` on, charging each look to + /// `budget`. + fn straight(&self, from: usize, left: usize, budget: &mut usize) -> Option { + let mut j = from; + for _ in 0..left { + *budget = budget.checked_sub(1)?; + let (t, tol) = self.turn(j); + if t.abs() <= tol { + return Some(j); + } + j = self.next[j]; + } + None + } + + /// Unlinks corner `i`, returning its triangle. + fn cut(&mut self, i: usize, face: &[Corner]) -> [Corner; 3] { + let (a, c) = (self.prev[i], self.next[i]); + self.next[a] = c; + self.prev[c] = a; + [face[a], face[i], face[c]] + } + + /// Clips ears until a triangle is left. When a whole lap finds no ear, a straight corner is + /// cut instead (its triangle has no area); failing that, or when the budget runs out, the + /// rest is fanned. + fn clip(mut self, face: &[Corner], budget: &mut usize) -> Vec<[Corner; 3]> { + let mut out = Vec::with_capacity(face.len() - 2); + let mut removed = vec![false; face.len()]; + let mut reflex: Vec = (0..face.len()).filter(|&i| self.turn(i).0 <= self.turn(i).1).collect(); + let (mut left, mut i, mut stop) = (face.len(), 0, 0); + while left > 3 { + let ear = match self.is_ear(i, &reflex, budget) { + Some(true) => true, + Some(false) => { + i = self.next[i]; + if i != stop { + continue; + } + match self.straight(i, left, budget) { + Some(j) => { + i = j; + true + } + None => false, + } + } + None => false, + }; + if !ear { + break; + } + let c = self.next[i]; + out.push(self.cut(i, face)); + removed[i] = true; + reflex.retain(|&r| !removed[r]); + left -= 1; + (i, stop) = (c, c); + } + // Fan whatever is left from corner `i`. + let first = i; + let mut b = self.next[first]; + while self.next[b] != first { + out.push([face[first], face[b], face[self.next[b]]]); + b = self.next[b]; + } + out + } +} diff --git a/crates/pcap/Cargo.toml b/crates/pcap/Cargo.toml new file mode 100644 index 0000000000..ea644cdf39 --- /dev/null +++ b/crates/pcap/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-pcap" +description = "Read-only PCAP/PCAPNG and per-frame protocol inspection" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } +chrono = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/pcap/src/bytes.rs b/crates/pcap/src/bytes.rs new file mode 100644 index 0000000000..238b5b6b8b --- /dev/null +++ b/crates/pcap/src/bytes.rs @@ -0,0 +1,49 @@ +//! 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 slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + pub fn u64_le(&self, off: usize) -> Option { + self.arr(off).map(u64::from_le_bytes) + } + + pub fn u16_be(&self, off: usize) -> Option { + self.arr(off).map(u16::from_be_bytes) + } + + pub fn u32_be(&self, off: usize) -> Option { + self.arr(off).map(u32::from_be_bytes) + } + + pub fn u64_be(&self, off: usize) -> Option { + self.arr(off).map(u64::from_be_bytes) + } +} diff --git a/crates/pcap/src/lib.rs b/crates/pcap/src/lib.rs new file mode 100644 index 0000000000..bc05c1f77e --- /dev/null +++ b/crates/pcap/src/lib.rs @@ -0,0 +1,2183 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Saved packet captures: classic pcap (microsecond and nanosecond, either byte order) and pcapng +//! (section, interface, enhanced/simple/obsolete packet blocks). Frames are decoded from Ethernet +//! (with VLAN tags), raw IP, Linux cooked (SLL/SLL2) and BSD loopback links into IPv4/IPv6, +//! TCP/UDP/ICMP, and the application facts most people ask about: DNS questions and answers, +//! HTTP/1.x request and status lines with the Host header, and the TLS ClientHello server name +//! (SNI) and ALPN. Each frame is decoded on its own: no TCP reassembly, no decryption. Pure, no I/O, +//! every length checked. Input bytes remain caller-owned and must be admitted to a caller budget. +//! Packet, flow and inventory caps below are retained; they are not a total allocator-byte guarantee. + +mod bytes; +#[cfg(test)] +#[path = "../tests/support/mod.rs"] +mod test_support; + +/// Why capture inspection could not start or finish. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PcapError { + #[error("the file ends early ({0})")] + Truncated(String), + #[error("the file is malformed ({0})")] + Malformed(String), + #[error("not supported: {0}")] + Unsupported(String), +} + +use crate::PcapError as FormatError; +use crate::bytes::Reader; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt::Write as _; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +/// Most accepted and rejected packet records read from one capture. +pub const MAX_PACKETS: u64 = 5_000_000; +/// Most flows tracked; later flows are counted but get no id. +pub const MAX_FLOWS: usize = 100_000; +/// Most distinct values kept per inventory (endpoints, DNS names, hosts…). +pub const MAX_INVENTORY: usize = 10_000; + +const CLASSIC_US: u32 = 0xa1b2_c3d4; +const CLASSIC_NS: u32 = 0xa1b2_3c4d; +const NG_SHB: u32 = 0x0a0d_0d0a; +const NG_BOM: u32 = 0x1a2b_3c4d; + +/// One capture interface (a pcap file has exactly one). +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Interface { + pub link_type: u32, + pub link_name: &'static str, + pub snaplen: u32, + /// Timestamp units per second, as a power: (base 10 or 2, exponent). + #[serde(skip)] + tsresol: (u8, u8), + /// Signed offset in seconds added to timestamps on this interface (`if_tsoffset`). + #[serde(skip)] + tsoffset: i64, +} + +/// The plain name of a link-layer type. +pub fn link_name(link: u32) -> &'static str { + match link { + 0 => "BSD loopback", + 1 => "Ethernet", + 12 | 14 | 101 => "raw IP", + 108 => "OpenBSD loopback", + 113 => "Linux cooked (SLL)", + 228 => "raw IPv4", + 229 => "raw IPv6", + 276 => "Linux cooked v2 (SLL2)", + 105 => "IEEE 802.11", + 127 => "802.11 radiotap", + _ => "other", + } +} + +/// One captured frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame<'a> { + /// 1-based frame number, as capture tools show it. + pub number: u64, + /// Nanoseconds since the Unix epoch, when representable. + pub ts_ns: Option, + pub interface: usize, + pub link_type: u32, + pub original_len: u32, + pub data: &'a [u8], +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Classic { le: bool, nanos: bool }, + Ng { le: bool }, +} + +/// Walks the frames of a capture. Malformed data stops the walk with a warning, never a panic. +#[derive(Debug, Clone)] +pub struct Capture<'a> { + data: &'a [u8], + pos: usize, + kind: Kind, + /// Interfaces of the current pcapng section start here in `interfaces`. + section_base: usize, + pub format: &'static str, + pub version: String, + pub interfaces: Vec, + pub warnings: Vec, + /// The walk stopped at `MAX_PACKETS`. + pub truncated: bool, + count: u64, + rejected_simple_blocks: u64, + rejected_short_blocks: u64, + rejected_interfaces: u64, + invalid_fractions: u64, + warnings_reported: bool, +} + +fn rd_u16(r: &Reader<'_>, le: bool, off: usize) -> Option { + if le { r.u16_le(off) } else { r.u16_be(off) } +} + +fn rd_u32(r: &Reader<'_>, le: bool, off: usize) -> Option { + if le { r.u32_le(off) } else { r.u32_be(off) } +} + +fn rd_i64(r: &Reader<'_>, le: bool, off: usize) -> Option { + if le { r.u64_le(off) } else { r.u64_be(off) }.map(|v| v as i64) +} + +/// True when the bytes start like a pcap or pcapng file. +pub fn is_capture(data: &[u8]) -> bool { + let r = Reader::new(data); + matches!(r.u32_le(0), Some(CLASSIC_US | CLASSIC_NS | NG_SHB)) || matches!(r.u32_be(0), Some(CLASSIC_US | CLASSIC_NS)) +} + +impl<'a> Capture<'a> { + /// Read the file header. + pub fn new(data: &'a [u8]) -> Result { + let r = Reader::new(data); + let magic_le = r.u32_le(0).ok_or_else(|| FormatError::Truncated("no capture header".into()))?; + let magic_be = r.u32_be(0).unwrap_or(0); + let mut cap = Capture { + data, + pos: 0, + kind: Kind::Ng { le: true }, + section_base: 0, + format: "pcapng", + version: String::new(), + interfaces: Vec::new(), + warnings: Vec::new(), + truncated: false, + count: 0, + rejected_simple_blocks: 0, + rejected_short_blocks: 0, + rejected_interfaces: 0, + invalid_fractions: 0, + warnings_reported: false, + }; + let classic = |le: bool, nanos: bool| -> Result<(Kind, String, Interface), FormatError> { + let major = rd_u16(&r, le, 4).ok_or_else(|| FormatError::Truncated("pcap header".into()))?; + let minor = rd_u16(&r, le, 6).unwrap_or(0); + let snaplen = rd_u32(&r, le, 16).ok_or_else(|| FormatError::Truncated("pcap header".into()))?; + // Link type: bits 0–15; reserved: 16–25 and 27; FCS-present: 26; FCS length in 16-bit words: 28–31. + let link = rd_u32(&r, le, 20).ok_or_else(|| FormatError::Truncated("pcap header".into()))? & 0xffff; + let res = if nanos { (10, 9) } else { (10, 6) }; + let iface = Interface { link_type: link, link_name: link_name(link), snaplen, tsresol: res, tsoffset: 0 }; + Ok((Kind::Classic { le, nanos }, format!("{major}.{minor}"), iface)) + }; + match (magic_le, magic_be) { + (CLASSIC_US, _) | (_, CLASSIC_US) | (CLASSIC_NS, _) | (_, CLASSIC_NS) => { + let le = magic_le == CLASSIC_US || magic_le == CLASSIC_NS; + let nanos = (if le { magic_le } else { magic_be }) == CLASSIC_NS; + let (kind, version, iface) = classic(le, nanos)?; + cap.kind = kind; + cap.format = "pcap"; + cap.version = version; + cap.interfaces.push(iface); + cap.pos = 24; + } + (NG_SHB, _) => { + let le = match r.u32_le(8) { + Some(NG_BOM) => true, + _ if r.u32_be(8) == Some(NG_BOM) => false, + _ => return Err(FormatError::Malformed("pcapng section header without a byte-order mark".into())), + }; + cap.kind = Kind::Ng { le }; + cap.version = format!("{}.{}", rd_u16(&r, le, 12).unwrap_or(0), rd_u16(&r, le, 14).unwrap_or(0)); + } + _ => return Err(FormatError::Unsupported("not a pcap or pcapng capture".into())), + } + Ok(cap) + } + + fn stop(&mut self, why: impl Into) -> Option> { + self.warnings.push(why.into()); + self.pos = self.data.len(); + None + } + + fn packet_limit_reached(&mut self) -> bool { + if self.count + self.rejected_simple_blocks + self.rejected_short_blocks + self.rejected_interfaces < MAX_PACKETS { + return false; + } + if !self.truncated && self.pos < self.data.len() { + self.truncated = true; + self.warnings.push(format!("stopped after {MAX_PACKETS} packet records")); + } + true + } + + fn report_packet_warnings(&mut self) { + if self.warnings_reported { + return; + } + self.warnings_reported = true; + if self.rejected_short_blocks > 0 { + self.warnings.push(format!("skipped {} packet block(s) with captured data past the end", self.rejected_short_blocks)); + } + if self.rejected_interfaces > 0 { + self.warnings.push(format!("skipped {} packet block(s) naming an undeclared interface", self.rejected_interfaces)); + } + if self.invalid_fractions > 0 { + self.warnings.push(format!("ignored {} timestamp(s) with a fraction outside its second", self.invalid_fractions)); + } + if self.rejected_simple_blocks > 0 { + let n = self.rejected_simple_blocks; + let suffix = if n == 1 { "" } else { "s" }; + self.warnings.push(format!("skipped {n} simple packet block{suffix} with inconsistent captured lengths")); + } + } + + fn ts(&self, iface: usize, units: u64) -> Option { + let (base, exp) = self.interfaces.get(iface).map(|i| i.tsresol).unwrap_or((10, 6)); + let offset_s = self.interfaces.get(iface).map(|i| i.tsoffset).unwrap_or(0); + let ns = if base == 10 { + if exp <= 9 { + u128::from(units) * 10u128.pow(u32::from(9 - exp)) + } else { + 10u128.checked_pow(u32::from(exp - 9)).map_or(0, |scale| u128::from(units) / scale) + } + } else { + (u128::from(units) * 1_000_000_000) >> exp.min(127) + }; + let adjusted = i128::try_from(ns).ok()?.checked_add(i128::from(offset_s) * 1_000_000_000)?; + u64::try_from(adjusted).ok() + } + + fn frame(&mut self, iface: usize, ts_units: u64, data: &'a [u8], original_len: u32) -> Frame<'a> { + self.count += 1; + Frame { + number: self.count, + ts_ns: self.ts(iface, ts_units), + interface: iface, + link_type: self.interfaces.get(iface).map(|i| i.link_type).unwrap_or(u32::MAX), + original_len, + data, + } + } + + fn next_classic(&mut self, le: bool, nanos: bool) -> Option> { + let r = Reader::new(self.data); + let p = self.pos; + if p >= self.data.len() { + return None; + } + let (Some(sec), Some(frac), Some(incl), Some(orig)) = + (rd_u32(&r, le, p), rd_u32(&r, le, p + 4), rd_u32(&r, le, p + 8), rd_u32(&r, le, p + 12)) + else { + return self.stop(format!("record header at offset {p} is cut short")); + }; + let Some(body) = usize::try_from(incl).ok().and_then(|n| r.slice(p + 16, n)) else { + return self.stop(format!("record at offset {p} claims {incl} bytes past the end of the file")); + }; + self.pos = p + 16 + body.len(); + let per_second = if nanos { 1_000_000_000 } else { 1_000_000 }; + let units = u64::from(sec) * u64::from(per_second) + u64::from(frac); + let mut frame = self.frame(0, units, body, orig); + if frac >= per_second { + self.invalid_fractions += 1; + frame.ts_ns = None; + } + Some(frame) + } + + fn next_ng(&mut self, mut le: bool) -> Option> { + loop { + if self.packet_limit_reached() { + return None; + } + let r = Reader::new(self.data); + let p = self.pos; + if p >= self.data.len() { + return None; + } + let Some(btype) = rd_u32(&r, le, p) else { return self.stop(format!("block header at offset {p} is cut short")) }; + if btype == NG_SHB { + // A new section can switch byte order. + le = match r.u32_le(p + 8) { + Some(NG_BOM) => true, + _ if r.u32_be(p + 8) == Some(NG_BOM) => false, + _ => return self.stop(format!("section header at offset {p} has no byte-order mark")), + }; + } + let Some(blen) = rd_u32(&r, le, p + 4).and_then(|v| usize::try_from(v).ok()) else { + return self.stop(format!("block at offset {p} is cut short")); + }; + let minimum = match btype { + NG_SHB => 28, + 1 => 20, + 2 | 6 => 32, + 3 => 16, + _ => 12, + }; + if blen < minimum || blen % 4 != 0 || r.slice(p, blen).is_none() { + return self.stop(format!("block at offset {p} has an impossible length {blen}")); + } + if rd_u32(&r, le, p + blen - 4).and_then(|n| usize::try_from(n).ok()) != Some(blen) { + return self.stop(format!("block at offset {p} has an inconsistent trailing length")); + } + if btype == NG_SHB { + self.kind = Kind::Ng { le }; + self.section_base = self.interfaces.len(); + } + self.pos = p + blen; + let body = p + 8; + let body_end = p + blen - 4; + match btype { + 1 => { + let link = u32::from(rd_u16(&r, le, body).unwrap_or(u16::MAX)); + let snaplen = rd_u32(&r, le, body + 4).unwrap_or(0); + let mut tsresol = (10u8, 6u8); + let mut tsoffset = 0i64; + let mut o = body + 8; + while o + 4 <= body_end { + let (Some(code), Some(len)) = (rd_u16(&r, le, o), rd_u16(&r, le, o + 2)) else { break }; + if code == 0 { + break; + } + if code == 9 + && len == 1 + && o + 5 <= body_end + && let Some(v) = r.u8(o + 4) + { + tsresol = if v & 0x80 == 0 { (10, v) } else { (2, v & 0x7f) }; + } else if code == 14 + && len == 8 + && o + 12 <= body_end + && let Some(v) = rd_i64(&r, le, o + 4) + { + tsoffset = v; + } + o += 4 + usize::from(len).div_ceil(4) * 4; + } + self.interfaces.push(Interface { link_type: link, link_name: link_name(link), snaplen, tsresol, tsoffset }); + } + 6 | 2 => { + let (iface, hi, lo, cap, orig) = if btype == 6 { + ( + rd_u32(&r, le, body).map(|v| v as usize), + rd_u32(&r, le, body + 4), + rd_u32(&r, le, body + 8), + rd_u32(&r, le, body + 12), + rd_u32(&r, le, body + 16), + ) + } else { + ( + rd_u16(&r, le, body).map(usize::from), + rd_u32(&r, le, body + 4), + rd_u32(&r, le, body + 8), + rd_u32(&r, le, body + 12), + rd_u32(&r, le, body + 16), + ) + }; + let (Some(iface), Some(hi), Some(lo), Some(cap), Some(orig)) = (iface, hi, lo, cap, orig) else { continue }; + let Some(data) = usize::try_from(cap).ok().filter(|&c| c <= body_end - (body + 20)).and_then(|c| r.slice(body + 20, c)) else { + self.rejected_short_blocks += 1; + continue; + }; + let Some(iface) = self.section_base.checked_add(iface).filter(|&id| id < self.interfaces.len()) else { + self.rejected_interfaces += 1; + continue; + }; + return Some(self.frame(iface, (u64::from(hi) << 32) | u64::from(lo), data, orig)); + } + 3 => { + let Some(orig) = rd_u32(&r, le, body) else { continue }; + let iface = self.section_base; + let snap = self.interfaces.get(iface).map(|i| i.snaplen).filter(|&s| s > 0).unwrap_or(u32::MAX); + let room = body_end.saturating_sub(body + 4); + let cap = orig.min(snap) as usize; + if cap.checked_add(3).map(|n| n & !3) != Some(room) { + self.rejected_simple_blocks += 1; + continue; + } + let Some(data) = r.slice(body + 4, cap) else { continue }; + if iface >= self.interfaces.len() { + self.rejected_interfaces += 1; + continue; + } + // Simple packet blocks carry no timestamp. + self.count += 1; + return Some(Frame { + number: self.count, + ts_ns: None, + interface: iface, + link_type: self.interfaces.get(iface).map(|i| i.link_type).unwrap_or(u32::MAX), + original_len: orig, + data, + }); + } + _ => {} + } + } + } +} + +impl<'a> Iterator for Capture<'a> { + type Item = Frame<'a>; + + fn next(&mut self) -> Option> { + let frame = if self.packet_limit_reached() { + None + } else { + match self.kind { + Kind::Classic { le, nanos } => self.next_classic(le, nanos), + Kind::Ng { le } => self.next_ng(le), + } + }; + if frame.is_none() { + self.report_packet_warnings(); + } + frame + } +} + +// --------------------------------------------------------------------------------------------- +// Decoding + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct IpInfo { + pub version: u8, + pub src: IpAddr, + pub dst: IpAddr, + /// IP protocol number of the payload (6 TCP, 17 UDP, 1 ICMP, 58 ICMPv6…). + pub protocol: u8, + /// TTL or hop limit. + pub ttl: u8, + /// A non-first fragment: the transport header is in another frame. + pub fragment: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Transport { + /// tcp, udp, icmp, icmpv6 or other + pub protocol: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub src_port: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dst_port: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tcp_flags: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub seq: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ack: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub window: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub icmp_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub icmp_code: Option, + pub payload_len: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DnsQuestion { + pub name: String, + pub qtype: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct DnsAnswer { + pub name: String, + pub rtype: String, + pub ttl: u32, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Dns { + pub id: u16, + pub response: bool, + pub rcode: u8, + pub questions: Vec, + pub answers: Vec, + /// The message was cut short or malformed part-way. + pub incomplete: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Http { + /// request or response + pub kind: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + pub method: Option, + /// Request target with any user:password removed. + #[serde(skip_serializing_if = "Option::is_none")] + pub target: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + pub version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct TlsHello { + pub record_version: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub sni: Option, + pub alpn: Vec, + pub supported_versions: Vec, + /// The ClientHello continues in a later segment; extensions may be missing. + pub partial: bool, +} + +/// What one frame says. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Decoded { + /// Protocol stack, outermost first: eth, vlan, sll, ipv4, ipv6, arp, tcp, udp, icmp, dns, http, tls… + pub protocols: Vec<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub ip: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dns: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub http: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub tls: Option, + /// Where decoding stopped early, when it did. + #[serde(skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +impl Decoded { + /// The protocol stack joined with `:`. + pub fn stack(&self) -> String { + self.protocols.join(":") + } + + /// The direction-independent conversation this frame belongs to, and whether it travels a→b. + pub fn flow_key(&self) -> Option<(FlowKey, bool)> { + let ip = self.ip.as_ref()?; + let t = self.transport.as_ref(); + let sp = t.and_then(|t| t.src_port).unwrap_or(0); + let dp = t.and_then(|t| t.dst_port).unwrap_or(0); + let (s, d) = ((ip.src, sp), (ip.dst, dp)); + let forward = s <= d; + let (a, b) = if forward { (s, d) } else { (d, s) }; + Some((FlowKey { protocol: ip.protocol, a, b }, forward)) + } +} + +/// A conversation: IP protocol and the two (address, port) ends in sorted order. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct FlowKey { + pub protocol: u8, + pub a: (IpAddr, u16), + pub b: (IpAddr, u16), +} + +/// Decode one frame from its link layer up. +pub fn decode(link_type: u32, data: &[u8]) -> Decoded { + let mut d = Decoded::default(); + let r = Reader::new(data); + let (mut ethertype, mut off) = match link_type { + 1 => { + d.protocols.push("eth"); + (r.u16_be(12), 14usize) + } + 113 => { + d.protocols.push("sll"); + (r.u16_be(14), 16) + } + 276 => { + d.protocols.push("sll2"); + (r.u16_be(0), 20) + } + 0 | 108 => { + d.protocols.push("loopback"); + // The family is in the capturing host's byte order (NULL) or big-endian (LOOP). + let fam = if link_type == 108 { r.u32_be(0) } else { r.u32_le(0).filter(|&v| v < 256).or_else(|| r.u32_be(0)) }; + ( + fam.map(|f| { + if f == 2 { + 0x0800 + } else if matches!(f, 24 | 28 | 30) { + 0x86dd + } else { + 0 + } + }), + 4, + ) + } + 12 | 14 | 101 | 228 | 229 => { + d.protocols.push("raw"); + let ethertype = match link_type { + 228 => Some(0x0800), + 229 => Some(0x86dd), + _ => r.u8(0).map(|b| if b >> 4 == 6 { 0x86dd } else { 0x0800 }), + }; + (ethertype, 0) + } + _ => { + d.note = Some(format!("link type {link_type} ({}) is not decoded", link_name(link_type))); + return d; + } + }; + // Both Ethernet and Linux cooked headers carry an EtherType. Each VLAN + // tag supplies another EtherType after its tag-control field. + for _ in 0..2 { + if !matches!(ethertype, Some(0x8100 | 0x88a8)) { + break; + } + d.protocols.push("vlan"); + ethertype = r.u16_be(off + 2); + off += 4; + } + let payload = data.get(off..).unwrap_or(&[]); + match ethertype { + Some(0x0800) => ipv4(payload, &mut d), + Some(0x86dd) => ipv6(payload, &mut d), + Some(0x0806) => d.protocols.push("arp"), + Some(other) => d.note = Some(format!("ethertype {other:#06x} is not decoded")), + None => d.note = Some("frame too short for its link header".into()), + } + d +} + +fn ipv4(p: &[u8], d: &mut Decoded) { + let r = Reader::new(p); + let (Some(vihl), Some(total), Some(frag), Some(ttl), Some(proto)) = (r.u8(0), r.u16_be(2), r.u16_be(6), r.u8(8), r.u8(9)) else { + d.note = Some("IPv4 header cut short".into()); + return; + }; + let ihl = usize::from(vihl & 0x0f) * 4; + if vihl >> 4 != 4 || ihl < 20 || usize::from(total) < ihl { + d.note = Some("not a valid IPv4 header".into()); + return; + } + if r.slice(0, ihl).is_none() { + d.note = Some("IPv4 header cut short".into()); + return; + } + let (Some(src), Some(dst)) = (r.slice(12, 4), r.slice(16, 4)) else { return }; + d.protocols.push("ipv4"); + let ip4 = |b: &[u8]| { + IpAddr::V4(Ipv4Addr::new( + b.first().copied().unwrap_or(0), + b.get(1).copied().unwrap_or(0), + b.get(2).copied().unwrap_or(0), + b.get(3).copied().unwrap_or(0), + )) + }; + let fragment = frag & 0x1fff != 0; + d.ip = Some(IpInfo { version: 4, src: ip4(src), dst: ip4(dst), protocol: proto, ttl, fragment }); + let end = usize::from(total).min(p.len()); + let body = p.get(ihl..end).unwrap_or(&[]); + if fragment { + d.note = Some("IPv4 fragment (transport header is in the first fragment)".into()); + return; + } + transport(proto, body, d); +} + +fn ipv6(p: &[u8], d: &mut Decoded) { + let r = Reader::new(p); + let (Some(plen), Some(mut next), Some(hops), Some(src), Some(dst)) = (r.u16_be(4), r.u8(6), r.u8(7), r.slice(8, 16), r.slice(24, 16)) else { + d.note = Some("IPv6 header cut short".into()); + return; + }; + if r.u8(0).is_none_or(|version| version >> 4 != 6) { + d.note = Some("not a valid IPv6 header".into()); + return; + } + d.protocols.push("ipv6"); + let ip6 = |b: &[u8]| IpAddr::V6(Ipv6Addr::from(<[u8; 16]>::try_from(b).unwrap_or([0; 16]))); + let end = (40 + usize::from(plen)).min(p.len()); + let payload_reader = Reader::new(p.get(..end).unwrap_or(&[])); + let mut off = 40usize; + let mut fragment = false; + for _ in 0..8 { + match next { + 0 | 43 | 60 => { + let (Some(n), Some(l)) = (payload_reader.u8(off), payload_reader.u8(off + 1)) else { break }; + let len = (usize::from(l) + 1) * 8; + if off.checked_add(len).is_none_or(|next_off| next_off > end) { + break; + } + next = n; + off += len; + } + 44 => { + if off.checked_add(8).is_none_or(|next_off| next_off > end) { + break; + } + let (Some(n), Some(fo)) = (payload_reader.u8(off), payload_reader.u16_be(off + 2)) else { break }; + next = n; + fragment = fo & 0xfff8 != 0; + off += 8; + if fragment { + break; + } + } + 51 => { + let (Some(n), Some(l)) = (payload_reader.u8(off), payload_reader.u8(off + 1)) else { break }; + let len = (usize::from(l) + 2) * 4; + if off.checked_add(len).is_none_or(|next_off| next_off > end) { + break; + } + next = n; + off += len; + } + _ => break, + } + } + d.ip = Some(IpInfo { version: 6, src: ip6(src), dst: ip6(dst), protocol: next, ttl: hops, fragment }); + if fragment { + d.note = Some("IPv6 fragment (transport header is in the first fragment)".into()); + return; + } + // RFC 8200: No Next Header ends the chain even if the packet has trailing bytes. + if next != 59 { + transport(next, p.get(off..end).unwrap_or(&[]), d); + } +} + +fn tcp_flags(f: u8) -> String { + let names = [(0x02, "SYN"), (0x10, "ACK"), (0x01, "FIN"), (0x04, "RST"), (0x08, "PSH"), (0x20, "URG"), (0x40, "ECE"), (0x80, "CWR")]; + names.iter().filter(|(b, _)| f & b != 0).map(|(_, n)| *n).collect::>().join(",") +} + +fn transport(proto: u8, p: &[u8], d: &mut Decoded) { + let r = Reader::new(p); + let empty = Transport { + protocol: "other", + src_port: None, + dst_port: None, + tcp_flags: None, + seq: None, + ack: None, + window: None, + icmp_type: None, + icmp_code: None, + payload_len: 0, + }; + match proto { + 6 => { + let (Some(sp), Some(dp)) = (r.u16_be(0), r.u16_be(2)) else { + d.note = Some("TCP header cut short".into()); + return; + }; + d.protocols.push("tcp"); + let (seq, ack, off, flags, win) = (r.u32_be(4), r.u32_be(8), r.u8(12), r.u8(13), r.u16_be(14)); + let payload = match off.map(|off| usize::from(off >> 4) * 4) { + Some(length) if length < 20 => { + d.note = Some("TCP data offset is smaller than its header".into()); + &[][..] + } + Some(length) if length <= p.len() => p.get(length..).unwrap_or(&[]), + _ => { + d.note = Some("TCP header cut short".into()); + &[][..] + } + }; + d.transport = Some(Transport { + protocol: "tcp", + src_port: Some(sp), + dst_port: Some(dp), + tcp_flags: flags.map(tcp_flags), + seq, + ack, + window: win, + payload_len: payload.len(), + ..empty + }); + if (sp == 53 || dp == 53) && !payload.is_empty() { + let framed = Reader::new(payload); + match framed.u16_be(0) { + Some(length) if length < 12 => d.note = Some("DNS over TCP length is smaller than its header".into()), + Some(length) => { + if let Some(message) = framed.slice(2, usize::from(length)) { + dns(message, d, "dns", false); + } else { + d.note = Some("DNS over TCP message cut short".into()); + } + } + None => d.note = Some("DNS over TCP length prefix cut short".into()), + } + } else if !payload.is_empty() { + tcp_app(payload, d); + } + } + 17 => { + let (Some(sp), Some(dp)) = (r.u16_be(0), r.u16_be(2)) else { + d.note = Some("UDP header cut short".into()); + return; + }; + d.protocols.push("udp"); + let length = r.u16_be(4).map(usize::from).unwrap_or(0); + let payload = if p.len() < 8 { + d.note = Some("UDP header cut short".into()); + &[][..] + } else if length < 8 { + d.note = Some("UDP length is smaller than its header".into()); + &[][..] + } else { + if length > p.len() { + d.note = Some("UDP datagram cut short".into()); + } + p.get(8..length.min(p.len())).unwrap_or(&[]) + }; + d.transport = Some(Transport { protocol: "udp", src_port: Some(sp), dst_port: Some(dp), payload_len: payload.len(), ..empty }); + if sp == 53 || dp == 53 { + dns(payload, d, "dns", false); + } else if sp == 5353 || dp == 5353 { + dns(payload, d, "mdns", dp == 5353); + } + } + 1 | 58 => { + let name = if proto == 1 { "icmp" } else { "icmpv6" }; + d.protocols.push(name); + d.transport = Some(Transport { protocol: name, icmp_type: r.u8(0), icmp_code: r.u8(1), payload_len: p.len().saturating_sub(4), ..empty }); + } + _ => d.transport = Some(Transport { protocol: "other", payload_len: p.len(), ..empty }), + } +} + +pub fn qtype_name(t: u16) -> String { + match t { + 1 => "A".into(), + 2 => "NS".into(), + 5 => "CNAME".into(), + 6 => "SOA".into(), + 12 => "PTR".into(), + 15 => "MX".into(), + 16 => "TXT".into(), + 28 => "AAAA".into(), + 33 => "SRV".into(), + 35 => "NAPTR".into(), + 39 => "DNAME".into(), + 44 => "SSHFP".into(), + 52 => "TLSA".into(), + 256 => "URI".into(), + 64 => "SVCB".into(), + 65 => "HTTPS".into(), + 257 => "CAA".into(), + 255 => "ANY".into(), + n => format!("TYPE{n}"), + } +} + +fn dns_sd_service_label(label: &[u8]) -> bool { + let Some(name) = label.strip_prefix(b"_") else { return false }; + // RFC 6763 §7 / RFC 6335 §5.1, excluding the leading underscore. + (1..=15).contains(&name.len()) + && name.first().is_some_and(u8::is_ascii_alphanumeric) + && name.last().is_some_and(u8::is_ascii_alphanumeric) + && name.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-') + && name.iter().any(u8::is_ascii_alphabetic) + && !name.windows(2).any(|pair| pair == b"--") +} + +/// A DNS name, the offset after it, and whether its wire labels name a DNS-SD instance. +fn dns_name(msg: &[u8], mut off: usize, allow_compression: bool) -> Option<(String, usize, bool)> { + let mut out = String::new(); + // Count the expanded wire name, including label lengths and the terminating root. + let mut wire_len = 1usize; + let mut after: Option = None; + let mut labels = 0; + let mut service_instance = false; + for _ in 0..128 { + let len = *msg.get(off)?; + match len { + 0 => return Some((if out.is_empty() { ".".into() } else { out }, after.unwrap_or(off + 1), labels >= 4 && service_instance)), + l if allow_compression && l & 0xc0 == 0xc0 => { + let ptr = usize::from(u16::from_be_bytes([l & 0x3f, *msg.get(off + 1)?])); + after.get_or_insert(off + 2); + if ptr >= off { + return None; // only backward pointers, so no loops + } + off = ptr; + } + l if l < 64 => { + let label = msg.get(off + 1..off + 1 + usize::from(l))?; + wire_len += 1 + label.len(); + if wire_len > 255 { + return None; + } + // Match Instance / _service / _tcp|_udp / Domain before rendering: + // a literal dot inside one wire label is not a label boundary. + match labels { + 1 => service_instance = dns_sd_service_label(label), + 2 => service_instance &= label.eq_ignore_ascii_case(b"_tcp") || label.eq_ignore_ascii_case(b"_udp"), + _ => {} + } + labels += 1; + if !out.is_empty() { + out.push('.'); + } + for &c in label { + match c { + b'.' | b'\\' => { + out.push('\\'); + out.push(char::from(c)); + } + c if c.is_ascii_graphic() => out.push(char::from(c)), + _ => { + let _ = write!(out, "\\{c:03}"); + } + } + } + off += 1 + usize::from(l); + } + _ => return None, + } + } + None +} + +/// Decode discovery and authentication records whose domain names prohibit compression. +fn discovery_answer(kind: u16, rd: &[u8]) -> Option { + let r = Reader::new(rd); + let text = |b: &[u8]| b.iter().flat_map(|v| std::ascii::escape_default(*v)).map(char::from).collect::(); + let hex = |b: &[u8]| b.iter().map(|v| format!("{v:02x}")).collect::(); + match kind { + 39 => dns_name(rd, 0, false).filter(|(_, after, _)| *after == rd.len()).map(|(name, _, _)| name), + 44 => { + let (&algorithm, next) = rd.split_first()?; + let (&hash, digest) = next.split_first()?; + if digest.is_empty() || hash == 1 && digest.len() != 20 || hash == 2 && digest.len() != 32 { + return None; + } + Some(format!("{algorithm} {hash} {}", hex(digest))) + } + 52 => { + let [usage, selector, matching, cert @ ..] = rd else { return None }; + if cert.is_empty() || *matching == 1 && cert.len() != 32 || *matching == 2 && cert.len() != 64 { + return None; + } + Some(format!("{usage} {selector} {matching} {}", hex(cert))) + } + 256 => { + let target = rd.get(4..).filter(|s| !s.is_empty())?; + Some(format!("{} {} \"{}\"", r.u16_be(0)?, r.u16_be(2)?, strip_userinfo(&text(target)))) + } + 35 => { + let mut pos = 4; + let mut value = format!("{} {}", r.u16_be(0)?, r.u16_be(2)?); + for _ in 0..3 { + let len = usize::from(r.u8(pos)?); + value.push_str(&format!(" \"{}\"", text(r.slice(pos + 1, len)?))); + pos += 1 + len; + } + let (replacement, _, _) = dns_name(rd, pos, false).filter(|(_, after, _)| *after == rd.len())?; + Some(format!("{value} {replacement}")) + } + 64 | 65 => { + let priority = r.u16_be(0)?; + let (target, mut pos, _) = dns_name(rd, 2, false)?; + let mut value = format!("{priority} {target}"); + let mut previous = None; + while pos < rd.len() { + let key = r.u16_be(pos)?; + let len = usize::from(r.u16_be(pos + 2)?); + if key == u16::MAX || previous.is_some_and(|old| old >= key) { + return None; + } + let param = r.slice(pos + 4, len)?; + // Keep unknown keys lossless; interpreting them as text can fabricate an endpoint. + let field = match key { + 1 if priority != 0 => { + let mut remaining = param; + let mut ids = Vec::new(); + while let Some((&n, rest)) = remaining.split_first() { + if n == 0 { + return None; + } + let (id, tail) = rest.split_at_checked(usize::from(n))?; + ids.push(text(id).replace(',', "\\,")); + remaining = tail; + } + if ids.is_empty() { + return None; + } + format!("alpn={}", ids.join(",")) + } + 3 if priority != 0 => format!("port={}", u16::from_be_bytes(param.try_into().ok()?)), + 4 if priority != 0 => { + let (addresses, tail) = param.as_chunks::<4>(); + if addresses.is_empty() || !tail.is_empty() { + return None; + } + let hints: Vec<_> = addresses.iter().map(|ip| Ipv4Addr::from(*ip).to_string()).collect(); + format!("ipv4hint={}", hints.join(",")) + } + 6 if priority != 0 => { + let (addresses, tail) = param.as_chunks::<16>(); + if addresses.is_empty() || !tail.is_empty() { + return None; + } + let hints: Vec<_> = addresses.iter().map(|ip| Ipv6Addr::from(*ip).to_string()).collect(); + format!("ipv6hint={}", hints.join(",")) + } + _ => format!("key{key}=0x{}", hex(param)), + }; + value.push(' '); + value.push_str(&field); + previous = Some(key); + pos += len + 4; + } + Some(value) + } + _ => None, + } +} + +/// Decode a bounded set of DNS questions and answer/prerequisite records from one message. +/// Preserve complete entries before malformed data and mark the message incomplete. +fn dns(msg: &[u8], d: &mut Decoded, label: &'static str, mdns_wire_format: bool) { + let r = Reader::new(msg); + let (Some(id), Some(flags), Some(qd), Some(an)) = (r.u16_be(0), r.u16_be(2), r.u16_be(4), r.u16_be(6)) else { return }; + if msg.len() < 12 { + return; + } + let opcode = (flags >> 11) & 0xf; + // Sanity: opcode 0–6 and no absurd counts, so random payload on port 53 isn't misread. + if opcode > 6 || qd > 64 || qd == 0 && an == 0 { + return; + } + d.protocols.push(label); + let mut out = + Dns { id, response: flags & 0x8000 != 0, rcode: (flags & 0xf) as u8, questions: Vec::new(), answers: Vec::new(), incomplete: false }; + let mut off = 12usize; + for _ in 0..qd { + let Some((name, next, _)) = dns_name(msg, off, true) else { + out.incomplete = true; + break; + }; + // The class is not displayed, but both two-byte fields must be present. + let (Some(qt), Some(_class)) = (r.u16_be(next), r.u16_be(next + 2)) else { + out.incomplete = true; + break; + }; + out.questions.push(DnsQuestion { name, qtype: qtype_name(qt) }); + off = next + 4; + } + if !out.incomplete { + for _ in 0..an.min(64) { + let Some((name, next, service_instance)) = dns_name(msg, off, true) else { + out.incomplete = true; + break; + }; + let (Some(rt), Some(class), Some(ttl), Some(rdlen)) = (r.u16_be(next), r.u16_be(next + 2), r.u32_be(next + 4), r.u16_be(next + 8)) else { + out.incomplete = true; + break; + }; + let rd_off = next + 10; + let Some(rd) = r.slice(rd_off, usize::from(rdlen)) else { + out.incomplete = true; + break; + }; + let end = rd_off + rd.len(); + let within_record = msg.get(..end).unwrap_or(&[]); + let record_class = if mdns_wire_format { class & 0x7fff } else { class }; + let empty_prerequisite = rd.is_empty() && opcode == 5 && matches!(class, 254 | 255) && ttl == 0; + let value = match (rt, rd.len()) { + (1 | 28 | 6 | 33 | 35 | 39 | 44 | 52 | 64 | 65 | 256 | 257, 0) if empty_prerequisite => String::new(), + (1 | 28, _) if record_class != 1 => format!("<{} bytes>", rd.len()), + (1, 4) => Ipv4Addr::new( + rd.first().copied().unwrap_or(0), + rd.get(1).copied().unwrap_or(0), + rd.get(2).copied().unwrap_or(0), + rd.get(3).copied().unwrap_or(0), + ) + .to_string(), + (28, 16) => Ipv6Addr::from(<[u8; 16]>::try_from(rd).unwrap_or([0; 16])).to_string(), + (1 | 28, _) => { + out.incomplete = true; + break; + } + (33, _) => { + let fields = Reader::new(rd); + let Some((target, _, _)) = dns_name(within_record, rd_off + 6, mdns_wire_format).filter(|(_, after, _)| *after == end) else { + out.incomplete = true; + break; + }; + let (Some(priority), Some(weight), Some(port)) = (fields.u16_be(0), fields.u16_be(2), fields.u16_be(4)) else { + out.incomplete = true; + break; + }; + format!("{priority} {weight} {port} {target}") + } + (6, _) => { + let soa = dns_name(within_record, rd_off, true).and_then(|(primary, pos, _)| { + let (mailbox, pos, _) = dns_name(within_record, pos, true)?; + let (words, tail) = within_record.get(pos..)?.as_chunks::<4>(); + if !tail.is_empty() { + return None; + } + let words: &[[u8; 4]; 5] = words.try_into().ok()?; + let [serial, refresh, retry, expire, minimum] = words.map(u32::from_be_bytes); + Some(format!("{primary} {mailbox} {serial} {refresh} {retry} {expire} {minimum}")) + }); + let Some(soa) = soa else { + out.incomplete = true; + break; + }; + soa + } + (257, _) => { + let Some((&flags, rest)) = rd.split_first() else { + out.incomplete = true; + break; + }; + let caa = rest.split_first().and_then(|(&n, body)| body.split_at_checked(usize::from(n))).and_then(|(tag, value)| { + (!tag.is_empty() && tag.iter().all(u8::is_ascii_alphanumeric)).then(|| { + let value: String = value.iter().flat_map(|&byte| std::ascii::escape_default(byte)).map(char::from).collect(); + format!("{flags} {} {value}", String::from_utf8_lossy(tag)) + }) + }); + let Some(caa) = caa else { + out.incomplete = true; + break; + }; + caa + } + (2 | 5 | 12 | 15, _) => { + // RFC 2136 prerequisites can name an RRset without carrying its value. + if rd.is_empty() && opcode == 5 && matches!(class, 254 | 255) && ttl == 0 { + String::new() + } else { + let start = rd_off + if rt == 15 { 2 } else { 0 }; + // Keep earlier bytes available to compression pointers, but the encoded + // name itself must fit the record and account for all of its RDATA. + let Some((name, _, _)) = dns_name(within_record, start, true).filter(|(_, after, _)| *after == end) else { + out.incomplete = true; + break; + }; + name + } + } + (16, _) => { + // RFC 1035 §3.3.14: one TXT RDATA holds one or more + // length-prefixed character strings, and a zero-length + // string does not end the record. Consumers join them all + // (RFC 7208 §3.3), so keep every string instead of the + // first one and skip the rest of the RDATA. + let mut txt = String::new(); + let mut pos = 0; + // UPDATE's answer section holds prerequisites. ANY/NONE + // prerequisites use empty RDATA and zero TTL (RFC 2136 §2.4). + let empty_prerequisite = opcode == 5 && matches!(class, 254 | 255) && ttl == 0; + // DNS-SD receivers treat empty RDATA as an empty string + // (RFC 6763 §6.1), for both multicast and unicast DNS. + let empty_service_txt = opcode == 0 && service_instance; + out.incomplete |= rd.is_empty() && !empty_prerequisite && !empty_service_txt; + while let Some(&len) = rd.get(pos) { + let len = usize::from(len); + let end = pos + 1 + len; + let Some(part) = rd.get(pos + 1..end) else { + out.incomplete = true; + break; + }; + txt.push_str(&String::from_utf8_lossy(part)); + pos = end; + } + txt + } + (35 | 39 | 44 | 52 | 64 | 65 | 256, _) if record_class == 1 => { + let Some(value) = discovery_answer(rt, rd) else { + out.incomplete = true; + break; + }; + value + } + (_, n) => format!("<{n} bytes>"), + }; + if out.incomplete { + break; + } + out.answers.push(DnsAnswer { name, rtype: qtype_name(rt), ttl, value }); + off = rd_off + usize::from(rdlen); + } + } + out.incomplete |= flags & 0x0200 != 0; + d.dns = Some(out); +} + +/// HTTP method names are case-sensitive tokens, including extension methods. +fn http_method(method: &str) -> bool { + !method.is_empty() && method.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) +} + +/// Remove `user:password@` from an absolute request target. +pub fn strip_userinfo(target: &str) -> String { + if let Some((scheme, rest)) = target.split_once("://") { + let auth_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + if let Some(at) = rest.get(..auth_end).and_then(|a| a.rfind('@')) { + return format!("{scheme}://{}", rest.get(at + 1..).unwrap_or("")); + } + } + target.to_string() +} + +fn tcp_app(p: &[u8], d: &mut Decoded) { + let head = p.get(..p.len().min(16 << 10)).unwrap_or(p); + let Some(line_end) = head.windows(2).position(|w| w == b"\r\n") else { + tls(p, d); + return; + }; + let line = String::from_utf8_lossy(head.get(..line_end).unwrap_or(&[])); + let version = |v: &str| matches!(v.as_bytes(), [b'H', b'T', b'T', b'P', b'/', b'1', b'.', b'0'..=b'9']); + let mut parts = line.splitn(3, ' '); + let fields = (parts.next(), parts.next(), parts.next()); + if let (Some(v), Some(code), reason) = fields + && version(v) + && matches!(code.as_bytes(), [b'1'..=b'5', b'0'..=b'9', b'0'..=b'9']) + && reason.is_none_or(|text| text.bytes().all(|b| b == b'\t' || !b.is_ascii_control())) + { + d.protocols.push("http"); + d.http = Some(Http { kind: "response", method: None, target: None, status: code.parse().ok(), version: v.to_string(), host: None }); + return; + } + if let (Some(m), Some(t), Some(v)) = fields + && http_method(m) + && !t.is_empty() + && !t.bytes().any(|b| b.is_ascii_control()) + && version(v) + { + let mut remaining = head.get(line_end + 2..).unwrap_or(&[]); + let mut host = None; + while let Some(end) = remaining.windows(2).position(|w| w == b"\r\n") { + let field = remaining.get(..end).unwrap_or(&[]); + if field.is_empty() { + break; + } + if let Some(colon) = field.iter().position(|&b| b == b':') + && field.get(..colon).is_some_and(|name| name.eq_ignore_ascii_case(b"host")) + { + host = field.get(colon + 1..).map(|value| String::from_utf8_lossy(value).trim().to_string()); + break; + } + remaining = remaining.get(end + 2..).unwrap_or(&[]); + } + d.protocols.push("http"); + d.http = + Some(Http { kind: "request", method: Some(m.to_string()), target: Some(strip_userinfo(t)), status: None, version: v.to_string(), host }); + return; + } + tls(p, d); +} + +fn tls(p: &[u8], d: &mut Decoded) { + let r = Reader::new(p); + let (Some(ct), Some(major), Some(minor)) = (r.u8(0), r.u8(1), r.u8(2)) else { return }; + if !(20..=23).contains(&ct) || major != 3 || minor > 4 { + return; + } + d.protocols.push("tls"); + let Some(record_len) = r.u16_be(3) else { return }; + let record_end = 5 + usize::from(record_len); + let record_end_available = record_end.min(p.len()); + let record = Reader::new(p.get(..record_end_available).unwrap_or(&[])); + if ct != 22 || record.u8(5) != Some(1) { + return; + } + let ver = |v: u16| match v { + 0x0300 => "SSL 3.0".to_string(), + 0x0301 => "TLS 1.0".into(), + 0x0302 => "TLS 1.1".into(), + 0x0303 => "TLS 1.2".into(), + 0x0304 => "TLS 1.3".into(), + v if v & 0x0f0f == 0x0a0a && v >> 8 == v & 0xff => "GREASE".into(), + v => format!("{v:#06x}"), + }; + let mut hello = TlsHello { + record_version: ver(u16::from_be_bytes([major, minor])), + sni: None, + alpn: Vec::new(), + supported_versions: Vec::new(), + partial: record_end > p.len(), + }; + let Some(handshake_header) = record.u32_be(5) else { + hello.partial = true; + d.tls = Some(hello); + return; + }; + let handshake_end = 9 + (handshake_header & 0x00ff_ffff) as usize; + hello.partial |= handshake_end > record_end_available; + let hello_end = handshake_end.min(record_end_available); + let r = Reader::new(p.get(..hello_end).unwrap_or(&[])); + // Every variable-length field must fit inside this handshake, not merely the packet. + let skip8 = |off: usize, min: usize, max: usize| { + let n = usize::from(r.u8(off)?); + if !(min..=max).contains(&n) { + return None; + } + r.slice(off + 1, n)?; + Some(off + 1 + n) + }; + let cipher_suites_end = |off: usize| { + let n = usize::from(r.u16_be(off)?); + if n < 2 || n % 2 != 0 { + return None; + } + r.slice(off + 2, n)?; + Some(off + 2 + n) + }; + // Record header (5) + handshake header (4) + client_version (2) + random (32). + let Some(off) = skip8(5 + 4 + 2 + 32, 0, 32).and_then(cipher_suites_end).and_then(|p| skip8(p, 1, 255)) else { + hello.partial = true; + d.tls = Some(hello); + return; + }; + // Extensions are optional in a complete ClientHello through TLS 1.2. + if off == handshake_end && hello_end == handshake_end { + d.tls = Some(hello); + return; + } + let Some(ext_len) = r.u16_be(off) else { + hello.partial = true; + d.tls = Some(hello); + return; + }; + let declared_end = off + 2 + usize::from(ext_len); + hello.partial |= declared_end != handshake_end; + let end = declared_end.min(hello_end); + let extensions = Reader::new(p.get(..end).unwrap_or(&[])); + let mut seen_extensions = BTreeSet::new(); + let mut e = off + 2; + while e + 4 <= end { + let (Some(t), Some(l)) = (extensions.u16_be(e), extensions.u16_be(e + 2)) else { break }; + let body = e + 4; + let Some(data) = extensions.slice(body, usize::from(l)) else { + hello.partial = true; + break; + }; + if !seen_extensions.insert(t) { + hello.partial = true; + e = body + usize::from(l); + continue; + } + let dr = Reader::new(data); + match t { + 0 => { + if let Some(len) = dr.u16_be(0) { + let list_end = 2 + usize::from(len); + hello.partial |= len == 0 || list_end != data.len(); + let names = Reader::new(data.get(..list_end.min(data.len())).unwrap_or(&[])); + let mut a = 2; + while a < list_end.min(data.len()) { + let (Some(kind), Some(len)) = (names.u8(a), names.u16_be(a + 1)) else { + hello.partial = true; + break; + }; + let Some(name) = names.slice(a + 3, usize::from(len)) else { + hello.partial = true; + break; + }; + if kind == 0 { + if name.is_empty() || hello.sni.is_some() { + hello.partial = true; + } else { + hello.sni = Some(name.iter().map(|&c| if c.is_ascii_graphic() { char::from(c) } else { '?' }).collect()); + } + } + a += 3 + usize::from(len); + } + } else { + hello.partial = true; + } + } + 16 => { + if let Some(len) = dr.u16_be(0) { + let list_end = 2 + usize::from(len); + hello.partial |= len == 0 || list_end != data.len(); + let protocols = Reader::new(data.get(..list_end.min(data.len())).unwrap_or(&[])); + let mut a = 2usize; + while a < list_end.min(data.len()) { + let Some(n) = protocols.u8(a).filter(|&n| n > 0) else { + hello.partial = true; + break; + }; + let Some(proto) = protocols.slice(a + 1, usize::from(n)) else { + hello.partial = true; + break; + }; + if hello.alpn.len() < 16 { + hello.alpn.push(String::from_utf8_lossy(proto).into_owned()); + } + a += 1 + usize::from(n); + } + } else { + hello.partial = true; + } + } + 43 => { + if let Some(len) = dr.u8(0) { + let list_end = 1 + usize::from(len); + hello.partial |= len < 2 || list_end != data.len() || len % 2 != 0; + let versions = Reader::new(data.get(..list_end.min(data.len())).unwrap_or(&[])); + let mut a = 1usize; + while let Some(v) = versions.u16_be(a) { + let name = ver(v); + if name != "GREASE" { + hello.supported_versions.push(name); + } + a += 2; + if hello.supported_versions.len() >= 16 { + break; + } + } + } else { + hello.partial = true; + } + } + _ => {} + } + e = body + usize::from(l); + } + hello.partial |= e != end; + d.tls = Some(hello); +} + +// --------------------------------------------------------------------------------------------- +// Flows and summaries + +/// Assigns stable 1-based flow ids in order of first appearance. +#[derive(Debug, Default)] +pub struct FlowTable { + ids: HashMap, + /// Frames whose flow arrived after `MAX_FLOWS` and got no id. + pub untracked: u64, +} + +impl FlowTable { + /// The id of `key`, creating it when there is room. + pub fn id_for(&mut self, key: FlowKey) -> Option { + if let Some(&id) = self.ids.get(&key) { + return Some(id); + } + if self.ids.len() >= MAX_FLOWS { + self.untracked += 1; + return None; + } + let id = self.ids.len() + 1; + self.ids.insert(key, id); + Some(id) + } +} + +/// "addr:port", with brackets around IPv6 addresses; the port is omitted when zero. +pub fn endpoint((ip, port): (IpAddr, u16)) -> String { + match (ip, port) { + (IpAddr::V6(v6), 0) => v6.to_string(), + (IpAddr::V6(v6), p) => format!("[{v6}]:{p}"), + (v4, 0) => v4.to_string(), + (v4, p) => format!("{v4}:{p}"), + } +} + +pub fn ip_protocol_name(p: u8) -> &'static str { + match p { + 1 => "icmp", + 6 => "tcp", + 17 => "udp", + 58 => "icmpv6", + _ => "other", + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Flow { + pub id: usize, + pub protocol: &'static str, + pub a: String, + pub b: String, + pub packets: u64, + pub bytes: u64, + pub packets_a_to_b: u64, + pub packets_b_to_a: u64, + pub bytes_a_to_b: u64, + pub bytes_b_to_a: u64, + pub first_frame: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub first_ts_ns: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub last_ts_ns: Option, + /// Application protocols seen in it (dns, http, tls…). + pub applications: BTreeSet<&'static str>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Count { + pub value: String, + pub count: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub struct Summary { + pub format: &'static str, + pub version: String, + pub interfaces: Vec, + pub packets: u64, + pub bytes: u64, + pub first_ts_ns: Option, + pub last_ts_ns: Option, + /// Frames per protocol label. + pub protocols: Vec, + /// Frames per full protocol stack (eth:ipv4:udp:dns). + pub stacks: Vec, + /// Frames per IP address (source and destination each count once per frame). + pub endpoints: Vec, + pub flows: Vec, + pub flows_untracked_frames: u64, + /// "name (TYPE)" asked in DNS queries. + pub dns_queries: Vec, + /// "name TYPE value" from DNS responses. + pub dns_answers: Vec, + /// "question A|AAAA address" from DNS responses: each address answered, keyed by the response's first + /// question (so CNAME chains end at the name that was asked), or the record owner in a questionless reply. + pub dns_addresses: Vec, + /// "METHOD host target" from HTTP/1.x requests. + pub http_requests: Vec, + /// Server names from TLS ClientHellos. + pub tls_sni: Vec, + pub tls_alpn: Vec, + /// Frames whose network layer was not decoded (other link types, ARP, other ethertypes). + pub undecoded_frames: u64, + /// Inventories that hit `MAX_INVENTORY` distinct values. + pub capped_inventories: Vec<&'static str>, + pub truncated: bool, + pub warnings: Vec, +} + +#[derive(Default)] +struct Tally { + map: BTreeMap, + capped: bool, +} + +impl Tally { + fn add(&mut self, k: String) { + if let Some(v) = self.map.get_mut(&k) { + *v += 1; + } else if self.map.len() < MAX_INVENTORY { + self.map.insert(k, 1); + } else { + self.capped = true; + } + } + + fn done(self, name: &'static str, capped: &mut Vec<&'static str>) -> Vec { + if self.capped { + capped.push(name); + } + let mut v: Vec = self.map.into_iter().map(|(value, count)| Count { value, count }).collect(); + v.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.value.cmp(&b.value))); + v + } +} + +/// Read every frame once and summarize the capture. `cancelled` is polled every 4096 frames. +pub fn summarize(data: &[u8], cancelled: &dyn Fn() -> bool) -> Result { + let mut cap = Capture::new(data)?; + let mut s = Summary::default(); + let mut flows = FlowTable::default(); + let mut flow_rows: Vec = Vec::new(); + let (mut protocols, mut stacks, mut endpoints) = (Tally::default(), Tally::default(), Tally::default()); + let (mut queries, mut answers, mut http, mut sni, mut alpn) = + (Tally::default(), Tally::default(), Tally::default(), Tally::default(), Tally::default()); + let mut addresses = Tally::default(); + for f in cap.by_ref() { + if f.number % 4096 == 0 && cancelled() { + return Err(FormatError::Malformed("cancelled".into())); + } + s.packets += 1; + s.bytes += u64::from(f.original_len); + if let Some(t) = f.ts_ns { + s.first_ts_ns = Some(s.first_ts_ns.map_or(t, |x| x.min(t))); + s.last_ts_ns = Some(s.last_ts_ns.map_or(t, |x| x.max(t))); + } + let d = decode(f.link_type, f.data); + for (i, p) in d.protocols.iter().enumerate() { + if !d.protocols[..i].contains(p) { + protocols.add((*p).to_string()); + } + } + stacks.add(d.stack()); + let Some(ip) = &d.ip else { + s.undecoded_frames += 1; + continue; + }; + endpoints.add(ip.src.to_string()); + if ip.dst != ip.src { + endpoints.add(ip.dst.to_string()); + } + if let Some((key, forward)) = d.flow_key() + && let Some(id) = flows.id_for(key) + { + if id > flow_rows.len() { + flow_rows.push(Flow { + id, + protocol: ip_protocol_name(key.protocol), + a: endpoint(key.a), + b: endpoint(key.b), + packets: 0, + bytes: 0, + packets_a_to_b: 0, + packets_b_to_a: 0, + bytes_a_to_b: 0, + bytes_b_to_a: 0, + first_frame: f.number, + first_ts_ns: f.ts_ns, + last_ts_ns: f.ts_ns, + applications: BTreeSet::new(), + }); + } + if let Some(row) = flow_rows.get_mut(id - 1) { + row.packets += 1; + row.bytes += u64::from(f.original_len); + if forward { + row.packets_a_to_b += 1; + row.bytes_a_to_b += u64::from(f.original_len); + } else { + row.packets_b_to_a += 1; + row.bytes_b_to_a += u64::from(f.original_len); + } + if let Some(t) = f.ts_ns { + row.first_ts_ns = Some(row.first_ts_ns.map_or(t, |first| first.min(t))); + row.last_ts_ns = Some(row.last_ts_ns.map_or(t, |last| last.max(t))); + } + for app in d.protocols.iter().skip_while(|p| !matches!(**p, "tcp" | "udp")).skip(1) { + row.applications.insert(app); + } + } + } + if let Some(dns) = &d.dns { + if !dns.response { + for q in &dns.questions { + queries.add(format!("{} ({})", q.name, q.qtype)); + } + } + for a in &dns.answers { + answers.add(format!("{} {} {}", a.name, a.rtype, a.value)); + } + if dns.response { + for a in dns.answers.iter().filter(|a| matches!(a.rtype.as_str(), "A" | "AAAA") && a.value.parse::().is_ok()) { + // Questionless replies (including unsolicited mDNS) name the address in the answer. + let name = dns.questions.first().map_or(&a.name, |q| &q.name); + addresses.add(format!("{name} {} {}", a.rtype, a.value)); + } + } + } + if let Some(h) = &d.http + && h.kind == "request" + { + http.add(format!("{} {} {}", h.method.as_deref().unwrap_or("?"), h.host.as_deref().unwrap_or("-"), h.target.as_deref().unwrap_or(""))); + } + if let Some(t) = &d.tls { + if let Some(n) = &t.sni { + sni.add(n.clone()); + } + for a in &t.alpn { + alpn.add(a.clone()); + } + } + } + let mut capped = Vec::new(); + s.format = cap.format; + s.version = cap.version.clone(); + s.interfaces = cap.interfaces.clone(); + s.protocols = protocols.done("protocols", &mut capped); + s.stacks = stacks.done("stacks", &mut capped); + s.endpoints = endpoints.done("endpoints", &mut capped); + s.dns_queries = queries.done("dns_queries", &mut capped); + s.dns_answers = answers.done("dns_answers", &mut capped); + s.dns_addresses = addresses.done("dns_addresses", &mut capped); + s.http_requests = http.done("http_requests", &mut capped); + s.tls_sni = sni.done("tls_sni", &mut capped); + s.tls_alpn = alpn.done("tls_alpn", &mut capped); + s.capped_inventories = capped; + s.flows = flow_rows; + s.flows_untracked_frames = flows.untracked; + s.truncated = cap.truncated; + s.warnings = cap.warnings; + Ok(s) +} + +/// `YYYY-MM-DDThh:mm:ss.nnnnnnnnnZ` for nanoseconds since the Unix epoch. +pub fn iso8601(ns: u64) -> String { + // u64 nanoseconds span only 1970..2554, entirely within chrono's representable range. + chrono::DateTime::from_timestamp((ns / 1_000_000_000) as i64, (ns % 1_000_000_000) as u32) + .map(|time| time.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true)) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::{dns_query, eth, ipv4_pkt, pcap, pcapng, sample_frames, udp}; + + #[test] + fn rejected_simple_packets_count_toward_the_scan_limit() { + let mut data = pcapng(&[]); + let rejected = crate::test_support::block(3, &1u32.to_le_bytes()); + for _ in 0..3 { + data.extend(&rejected); + } + let mut cap = Capture::new(&data).unwrap(); + // Reach the boundary without allocating millions of preceding valid frames. + cap.count = MAX_PACKETS - 2; + assert!(cap.next().is_none()); + assert!(cap.truncated); + assert_eq!(cap.pos, data.len() - rejected.len()); + assert_eq!(cap.warnings.len(), 2); + assert!(cap.warnings.iter().any(|w| w.contains("2 simple packet blocks"))); + assert!(cap.next().is_none()); + assert_eq!(cap.warnings.len(), 2); + } + + #[test] + fn rejected_simple_packets_at_eof_do_not_report_a_truncated_scan() { + let mut data = pcapng(&[]); + let rejected = crate::test_support::block(3, &1u32.to_le_bytes()); + for _ in 0..2 { + data.extend(&rejected); + } + let mut cap = Capture::new(&data).unwrap(); + cap.count = MAX_PACKETS - 2; + assert!(cap.next().is_none()); + assert!(!cap.truncated); + assert_eq!(cap.warnings.len(), 1); + assert!(cap.warnings[0].contains("2 simple packet blocks")); + } + + #[test] + fn valid_and_rejected_simple_packets_share_the_scan_limit() { + let mut data = pcapng(&[]); + data.extend(crate::test_support::block(3, &1u32.to_le_bytes())); + let valid = crate::test_support::block(3, &0u32.to_le_bytes()); + data.extend(&valid); + data.extend(&valid); + let mut cap = Capture::new(&data).unwrap(); + cap.count = MAX_PACKETS - 2; + assert_eq!(cap.next().unwrap().number, MAX_PACKETS - 1); + assert!(cap.next().is_none()); + assert!(cap.truncated); + assert_eq!(cap.pos, data.len() - valid.len()); + } + + #[test] + fn malformed_packet_blocks_share_the_budget_and_report_each_reason_once() { + use crate::test_support::block; + let mut data = pcapng(&[]); + for kind in [2, 6] { + let mut body = [0; 20]; + body[12..16].copy_from_slice(&u32::MAX.to_le_bytes()); + data.extend(block(kind, &body)); + } + let mut body = [0; 20]; + body[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + data.extend(block(6, &body)); + let mut shb = pcapng(&[]); + shb.truncate(28); + data.extend(shb); + data.extend(block(3, &[0; 4])); // No interface in this section. + data.extend(block(3, &[0; 4])); + let mut cap = Capture::new(&data).unwrap(); + cap.count = MAX_PACKETS - 4; + assert!(cap.next().is_none()); + assert!(cap.truncated); + assert_eq!(cap.warnings.len(), 3); + assert!(cap.warnings.iter().any(|s| s.contains("2 packet block(s) naming"))); + assert!(cap.warnings.iter().any(|s| s.contains("2 packet block(s) with"))); + assert!(cap.next().is_none()); + assert_eq!(cap.warnings.len(), 3); + } + + #[test] + fn invalid_classic_fractions_do_not_move_the_capture_period() { + for (magic, scale) in [(CLASSIC_US, 1_000_000u32), (CLASSIC_NS, 1_000_000_000)] { + let mut data = pcap(&[vec![], vec![]]); + data[..4].copy_from_slice(&magic.to_le_bytes()); + data[28..32].copy_from_slice(&scale.to_le_bytes()); + data[44..48].copy_from_slice(&(scale - 1).to_le_bytes()); + let mut cap = Capture::new(&data).unwrap(); + assert_eq!(cap.next().unwrap().ts_ns, None); + assert!(cap.next().unwrap().ts_ns.is_some()); + assert!(cap.next().is_none()); + assert_eq!(cap.warnings.len(), 1); + } + } + + #[test] + fn subnanosecond_decimal_resolutions_keep_the_interface_offset() { + use crate::test_support::block; + let mut data = pcapng(&[]); + data.truncate(28); + let mut idb = vec![1, 0, 0, 0, 0, 0, 0, 0, 9, 0, 1, 0, 127, 0, 0, 0, 14, 0, 8, 0]; + idb.extend(2i64.to_le_bytes()); + data.extend(block(1, &idb)); + let mut epb = [0; 20]; + epb[4..12].fill(0xff); + data.extend(block(6, &epb)); + let frame = Capture::new(&data).unwrap().next().unwrap(); + assert_eq!(frame.ts_ns, Some(2_000_000_000)); + } + + #[test] + fn tcp_cut_inside_header_keeps_ports() { + // Ports sit in the first 4 bytes; a cut later in the header must not drop them (as UDP). + let mut tcp = Vec::new(); + tcp.extend(41000u16.to_be_bytes()); + tcp.extend(9000u16.to_be_bytes()); + tcp.extend([0, 0, 0, 1, 0, 0, 0, 0, 0x50, 0x18, 4, 0, 0, 0, 0, 0]); + let mut frame = eth(0x0800, &ipv4_pkt(6, [10, 0, 0, 1], [10, 0, 0, 2], &tcp)); + frame.truncate(14 + 20 + 11); + let d = decode(1, &frame); + let t = d.transport.unwrap(); + assert_eq!((t.src_port, t.dst_port), (Some(41000), Some(9000))); + assert_eq!(t.seq, Some(1)); + assert_eq!(t.ack, None); + assert_eq!(t.window, None); + assert!(d.protocols.contains(&"tcp")); + } + + /// One-answer DNS response for `example.com` with a TXT answer carrying `rdata`. + fn txt_response(rdata: &[u8]) -> Vec { + let mut m = vec![0x12, 0x34, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0]; + m.extend(b"\x07example\x03com\x00\x00\x01\x00\x01"); + m.extend([0xc0, 12, 0, 16, 0, 1, 0, 0, 0x00, 0x3c]); + m.extend((rdata.len() as u16).to_be_bytes()); + m.extend(rdata); + m + } + + #[test] + fn dns_txt_answer_keeps_every_character_string() { + // RFC 1035 §3.3.14: one TXT RDATA holds any number of length-prefixed + // character strings. Only the first used to survive (issue #330). + let rdata = [ + 5, b'f', b'i', b'r', b's', b't', // "first" + 6, b's', b'e', b'c', b'o', b'n', b'd', // "second" + ]; + let frame = eth(0x0800, &ipv4_pkt(17, [8, 8, 8, 8], [192, 168, 1, 10], &udp(53, 50000, &txt_response(&rdata)))); + let d = decode(1, &frame); + let dns = d.dns.unwrap(); + assert_eq!(dns.answers.len(), 1); + assert_eq!(dns.answers[0].rtype, "TXT"); + assert_eq!(dns.answers[0].value, "firstsecond"); + assert!(!dns.incomplete); + } + + #[test] + fn dns_txt_empty_first_string_keeps_later_content() { + // A zero-length character string does not end the record. + let rdata = [0, 6, b's', b'e', b'c', b'o', b'n', b'd']; + let frame = eth(0x0800, &ipv4_pkt(17, [8, 8, 8, 8], [192, 168, 1, 10], &udp(53, 50000, &txt_response(&rdata)))); + let d = decode(1, &frame); + let dns = d.dns.unwrap(); + assert_eq!(dns.answers.len(), 1); + assert_eq!(dns.answers[0].value, "second"); + assert!(!dns.incomplete); + } + + fn classic_link_word(link_word: u32, le: bool, nanos: bool, trailer: usize) { + let link = link_word & 0xffff; + let mut frame = sample_frames()[1].clone(); + if link == 101 { + frame.drain(..14); + } + frame.extend(vec![0xab; trailer]); + let word = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let short = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() }; + let mut data = word(if nanos { CLASSIC_NS } else { CLASSIC_US }).to_vec(); + data.extend(short(2)); + data.extend(short(4)); + data.extend([0; 8]); + data.extend(word(65535)); + data.extend(word(link_word)); + data.extend(word(1_700_000_000)); + data.extend(word(500)); + data.extend(word(frame.len() as u32)); + data.extend(word(frame.len() as u32)); + data.extend(&frame); + + let mut cap = Capture::new(&data).unwrap(); + assert_eq!(cap.interfaces[0].link_type, link); + assert_eq!(cap.interfaces[0].link_name, if link == 1 { "Ethernet" } else { "raw IP" }); + let packet = cap.next().unwrap(); + assert_eq!(packet.link_type, link); + assert_eq!(packet.data, frame); + assert_eq!(packet.ts_ns, Some(1_700_000_000_000_000_000 + if nanos { 500 } else { 500_000 })); + let d = decode(packet.link_type, packet.data); + assert_eq!(d.stack(), if link == 1 { "eth:ipv4:udp:dns" } else { "raw:ipv4:udp:dns" }); + let ip = d.ip.unwrap(); + assert_eq!(ip.src.to_string(), "8.8.8.8"); + assert_eq!(ip.dst.to_string(), "192.168.1.10"); + let dns = d.dns.unwrap(); + assert!(dns.response); + assert_eq!(dns.answers[0].value, "93.184.216.34"); + assert!(cap.next().is_none()); + + let s = summarize(&data, &|| false).unwrap(); + assert_eq!(s.packets, 1); + assert_eq!(s.undecoded_frames, 0); + assert_eq!(s.dns_answers[0].value, "example.com A 93.184.216.34"); + assert_eq!(s.flows[0].protocol, "udp"); + assert!(s.warnings.is_empty()); + } + + #[test] + fn fcs_bits_do_not_change_the_ethernet_link_type() { + classic_link_word(0x24000001, true, false, 4); + } + + #[test] + fn fcs_bits_are_masked_in_big_endian_files() { + classic_link_word(0x24000001, false, false, 4); + } + + #[test] + fn fcs_bits_are_masked_in_nanosecond_files() { + classic_link_word(0x24000001, true, true, 4); + } + + #[test] + fn fcs_bits_are_masked_in_big_endian_nanosecond_files() { + classic_link_word(0x24000001, false, true, 4); + classic_link_word(1, false, true, 0); + } + + #[test] + fn fcs_bits_do_not_change_big_endian_nanosecond_raw_ip() { + classic_link_word(0x24000065, false, true, 4); + classic_link_word(101, false, true, 0); + } + + #[test] + fn a_one_word_fcs_length_is_masked() { + classic_link_word(0x14000001, true, false, 2); + } + + #[test] + fn fcs_bits_do_not_change_the_raw_ip_link_type() { + classic_link_word(0x24000065, true, false, 4); + } + + #[test] + fn ethernet_without_fcs_bits_still_decodes() { + classic_link_word(1, true, false, 0); + } + + #[test] + fn raw_ip_without_fcs_bits_still_decodes() { + classic_link_word(101, true, false, 0); + } + + #[test] + fn linux_cooked_vlan_frames_reach_the_network_decoder() { + let ip = ipv4_pkt(17, [10, 0, 0, 1], [10, 0, 0, 2], &udp(123, 456, b"payload")); + for (link, header_len, protocol_at) in [(113, 16, 14), (276, 20, 0)] { + let mut frame = vec![0; header_len]; + frame[protocol_at..protocol_at + 2].copy_from_slice(&0x88a8_u16.to_be_bytes()); + frame.extend_from_slice(&[0, 1, 0x81, 0, 0, 2, 0x08, 0]); + frame.extend_from_slice(&ip); + let decoded = decode(link, &frame); + assert_eq!(decoded.protocols.iter().filter(|&&p| p == "vlan").count(), 2); + assert_eq!(decoded.transport.unwrap().dst_port, Some(456)); + assert!(decode(link, &frame[..header_len + 1]).ip.is_none()); + } + } + + #[test] + fn decodes_dns_tls_http() { + let frames = sample_frames(); + let d = decode(1, &frames[1]); + assert_eq!(d.stack(), "eth:ipv4:udp:dns"); + let dns = d.dns.unwrap(); + assert!(dns.response); + assert_eq!(dns.questions[0].name, "example.com"); + assert_eq!(dns.answers[0].value, "93.184.216.34"); + assert_eq!(dns.answers[0].ttl, 3600); + + let d = decode(1, &frames[4]); + assert_eq!(d.stack(), "eth:ipv4:tcp:tls"); + let t = d.tls.unwrap(); + assert_eq!(t.sni.as_deref(), Some("example.com")); + assert_eq!(t.alpn, vec!["h2", "http/1.1"]); + assert_eq!(t.supported_versions, vec!["TLS 1.3", "TLS 1.2"]); + assert!(!t.partial); + + let d = decode(1, &frames[5]); + let h = d.http.unwrap(); + assert_eq!(h.method.as_deref(), Some("GET")); + assert_eq!(h.host.as_deref(), Some("example.com")); + assert_eq!(h.target.as_deref(), Some("http://example.com/a?b=1")); + assert_eq!(decode(1, &frames[3]).transport.unwrap().tcp_flags.as_deref(), Some("SYN,ACK")); + assert_eq!(decode(1, &frames[6]).stack(), "eth:arp"); + } + + #[test] + fn summarizes_pcap_and_pcapng_alike() { + let frames = sample_frames(); + for data in [pcap(&frames), pcapng(&frames)] { + let s = summarize(&data, &|| false).unwrap(); + assert_eq!(s.packets, 7); + assert_eq!(s.flows.len(), 3, "{:?}", s.flows); + assert_eq!(s.flows[0].protocol, "udp"); + assert_eq!(s.flows[0].packets, 2); + assert_eq!((s.flows[0].packets_a_to_b, s.flows[0].packets_b_to_a), (1, 1)); + assert!(s.flows[1].applications.contains("tls")); + assert_eq!(s.dns_queries[0].value, "example.com (A)"); + assert_eq!(s.dns_answers[0].value, "example.com A 93.184.216.34"); + assert_eq!(s.tls_sni[0].value, "example.com"); + assert_eq!(s.http_requests[0].value, "GET example.com http://example.com/a?b=1"); + assert_eq!(s.undecoded_frames, 1); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + assert_eq!(s.interfaces[0].link_type, 1); + assert!(s.first_ts_ns.unwrap() >= 1_700_000_000_000_000_000); + } + assert_eq!(summarize(&pcap(&frames), &|| false).unwrap().format, "pcap"); + assert_eq!(iso8601(1_700_000_000_000_000_500), "2023-11-14T22:13:20.000000500Z"); + assert_eq!(iso8601(0), "1970-01-01T00:00:00.000000000Z"); + } + + #[test] + fn qinq_frames_count_vlan_once_per_frame() { + let mut payload = vec![0x00, 0x0a, 0x81, 0x00, 0x00, 0x14, 0x08, 0x00]; + payload.extend(ipv4_pkt(17, [10, 0, 0, 1], [10, 0, 0, 2], &udp(40000, 9999, b"ping"))); + let frame = eth(0x88a8, &payload); + let s = summarize(&pcap(&[frame.clone(), frame.clone(), frame]), &|| false).unwrap(); + let count = |name: &str| s.protocols.iter().find(|c| c.value == name).map(|c| c.count); + assert_eq!(s.stacks[0].value, "eth:vlan:vlan:ipv4:udp"); + assert_eq!(count("vlan"), Some(3)); + assert_eq!(count("eth"), Some(3)); + assert_eq!(count("ipv4"), Some(3)); + } + + #[test] + fn flows_count_bytes_per_direction() { + let req = eth(0x0800, &ipv4_pkt(17, [10, 0, 0, 1], [10, 0, 0, 2], &udp(40000, 9999, &[b'q'; 10]))); + let rep = eth(0x0800, &ipv4_pkt(17, [10, 0, 0, 2], [10, 0, 0, 1], &udp(9999, 40000, &[b'r'; 300]))); + let s = summarize(&pcap(&[req, rep]), &|| false).unwrap(); + let flow = serde_json::to_value(&s.flows[0]).unwrap(); + assert_eq!(flow["bytes"], 394); + assert_eq!(flow["bytes_a_to_b"], 52); + assert_eq!(flow["bytes_b_to_a"], 342); + } + + #[test] + fn pcapng_interface_tsoffset_adjusts_timestamps() { + let base = pcapng(&sample_frames()); + for offset_s in [3600i64, -50i64] { + let mut data = base[..52].to_vec(); + data.extend(14u16.to_le_bytes()); + data.extend(8u16.to_le_bytes()); + data.extend(offset_s.to_le_bytes()); + data.extend(&base[52..]); + data[32..36].copy_from_slice(&44u32.to_le_bytes()); + data[68..72].copy_from_slice(&44u32.to_le_bytes()); + let expected0 = (1_700_000_000_000_000_000i128 + i128::from(offset_s) * 1_000_000_000) as u64; + let frames: Vec<_> = Capture::new(&data).unwrap().collect(); + assert_eq!(frames[0].ts_ns, Some(expected0)); + let s = summarize(&data, &|| false).unwrap(); + assert_eq!((s.first_ts_ns, s.last_ts_ns), (Some(expected0), Some(expected0 + 6))); + assert_eq!((s.flows[0].first_ts_ns, s.flows[0].last_ts_ns), (Some(expected0), Some(expected0 + 1))); + } + } + + #[test] + fn ipv6_extension_outside_declared_payload_is_ignored() { + let mut v6 = vec![0x60, 0, 0, 0]; + v6.extend(0u16.to_be_bytes()); + v6.extend([60, 64]); + v6.extend([0u8; 32]); + v6.extend([17, 0, 0, 0, 0, 0, 0, 0]); + + let d = decode(101, &v6); + assert_eq!(d.ip.unwrap().protocol, 60); + } + + #[test] + fn ipv6_sll_and_raw_links() { + let mut v6 = vec![0x60, 0, 0, 0]; + let payload = udp(1000, 53, &dns_query()); + v6.extend((payload.len() as u16).to_be_bytes()); + v6.extend([17, 64]); + v6.extend([0x20, 0x01, 0x0d, 0xb8].iter().chain([0u8; 11].iter()).chain([1u8].iter())); + v6.extend([0x20, 0x01, 0x0d, 0xb8].iter().chain([0u8; 11].iter()).chain([2u8].iter())); + v6.extend(&payload); + let d = decode(101, &v6); + assert_eq!(d.stack(), "raw:ipv6:udp:dns"); + assert_eq!(d.ip.unwrap().src.to_string(), "2001:db8::1"); + let mut sll = vec![0u8; 14]; + sll.extend(0x86ddu16.to_be_bytes()); + sll.extend(&v6); + assert_eq!(decode(113, &sll).stack(), "sll:ipv6:udp:dns"); + assert!(decode(105, &v6).note.is_some()); + } + + #[test] + fn hostile_input_never_panics() { + assert!(Capture::new(b"").is_err()); + assert!(Capture::new(b"not a capture at all").is_err()); + let data = pcapng(&sample_frames()); + for cut in [0, 10, 28, 40, 100, data.len() / 2, data.len() - 3] { + let _ = summarize(data.get(..cut).unwrap(), &|| false); + } + let mut bad = pcap(&sample_frames()); + bad[32..36].copy_from_slice(&[0xff; 4]); // incl_len of the first record far past the end + let s = summarize(&bad, &|| false).unwrap(); + assert_eq!(s.packets, 0); + assert!(!s.warnings.is_empty()); + for seed in 0..200u64 { + let mut x = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise: Vec = (0..300) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect(); + for link in [0, 1, 101, 113, 276, 228] { + let _ = decode(link, &noise); + } + let mut f = sample_frames(); + f.push(noise); + let _ = summarize(&pcap(&f), &|| false); + } + // DNS compression loops are refused. + assert!(dns_name(&[0xc0, 0x00], 0, true).is_none()); + } +} + +#[cfg(test)] +mod timestamp_parity { + fn legacy_iso8601(ns: u64) -> String { + let secs = ns / 1_000_000_000; + let (days, rem) = (secs / 86_400, secs % 86_400); + // Civil-from-days (proleptic Gregorian), valid for every u64 day count we can reach. + let z = days as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:09}Z", rem / 3600, rem % 3600 / 60, rem % 60, ns % 1_000_000_000) + } + + #[test] + fn every_representable_day_and_boundaries_match_legacy() { + let day = 86_400_000_000_000u64; + for d in 0..=u64::MAX / day { + let ns = d * day; + assert_eq!(super::iso8601(ns), legacy_iso8601(ns)); + } + for ns in [0, 1, 999_999_999, 1_000_000_000, u64::MAX - 1, u64::MAX] { + assert_eq!(super::iso8601(ns), legacy_iso8601(ns)); + } + } +} diff --git a/crates/pcap/tests/dns_discovery_answers.rs b/crates/pcap/tests/dns_discovery_answers.rs new file mode 100644 index 0000000000..97d9dc0dca --- /dev/null +++ b/crates/pcap/tests/dns_discovery_answers.rs @@ -0,0 +1,60 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Dns, decode}; +use support::{dns_query, eth, ipv4_pkt, udp}; + +fn answer(kind: u16, rd: &[u8]) -> Dns { + let mut msg = dns_query(); + msg[2..4].copy_from_slice(&0x8180u16.to_be_bytes()); + msg[6..8].copy_from_slice(&1u16.to_be_bytes()); + msg.extend([0xc0, 12]); + msg.extend(kind.to_be_bytes()); + msg.extend([0, 1, 0, 0, 0, 60]); + msg.extend((rd.len() as u16).to_be_bytes()); + msg.extend(rd); + decode(1, ð(0x0800, &ipv4_pkt(17, [192, 0, 2, 2], [192, 0, 2, 1], &udp(53, 51000, &msg)))).dns.unwrap() +} + +#[test] +fn svc_binding_reports_target_and_port() { + for kind in [64, 65] { + let msg = answer(kind, b"\0\x01\x03api\0\0\x03\0\x02\x20\xfb"); + assert_eq!(msg.answers[0].value, "1 api port=8443"); + assert_eq!(answer(kind, b"\0\x01\0\0\x01\0\x03\x02h2\0\x04\0\x04\xc0\0\x02\x01").answers[0].value, "1 . alpn=h2 ipv4hint=192.0.2.1"); + assert!(answer(kind, b"\0\x01\0\0\x01\0\x01\x00").incomplete); + assert!(answer(kind, b"\0\x01\xc0\x0c").incomplete); + assert!(answer(kind, b"\0\x01\0\0\x03\0\x01\x00").incomplete); + } +} +#[test] +fn sshfp_preserves_algorithm_and_complete_digest() { + let mut d = vec![4, 2]; + d.extend([0x5a; 32]); + assert_eq!(answer(44, &d).answers[0].value, format!("4 2 {}", "5a".repeat(32))); + assert!(answer(44, &d[..15]).incomplete); +} +#[test] +fn tlsa_keeps_selector_and_certificate_association() { + let mut d = vec![3, 1, 1]; + d.extend([0xaa; 32]); + assert_eq!(answer(52, &d).answers[0].value, format!("3 1 1 {}", "aa".repeat(32))); + assert!(answer(52, &d[..4]).incomplete); +} +#[test] +fn naptr_keeps_order_preference_strings_and_replacement() { + let rd = b"\0\x0a\0\x02\x01s\x03sip\0\x03srv\0"; + assert_eq!(answer(35, rd).answers[0].value, r#"10 2 "s" "sip" "" srv"#); + assert!(answer(35, &rd[..rd.len() - 1]).incomplete); +} +#[test] +fn uri_keeps_priority_weight_and_target() { + assert_eq!(answer(256, b"\0\x02\0\x05https://x.test/s").answers[0].value, r#"2 5 "https://x.test/s""#); + assert!(answer(256, b"\0\x02\0\x05").incomplete); +} +#[test] +fn dname_only_accepts_a_complete_uncompressed_target() { + assert_eq!(answer(39, b"\x04host\0").answers[0].value, "host"); + assert!(answer(39, b"\xc0\x0c").incomplete); + assert!(answer(39, b"\x04host\0extra").incomplete); +} diff --git a/crates/pcap/tests/dns_question_class.rs b/crates/pcap/tests/dns_question_class.rs new file mode 100644 index 0000000000..b6583f7f3b --- /dev/null +++ b/crates/pcap/tests/dns_question_class.rs @@ -0,0 +1,58 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{decode, summarize}; +use support::{dns_query, eth, ipv4_pkt, pcap, udp}; + +fn packet(message: &[u8]) -> Vec { + eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 1], [192, 0, 2, 2], &udp(51000, 53, message))) +} + +/// Neither a missing class nor a one-byte class can complete a DNS question. +#[test] +fn a_question_missing_any_class_byte_is_incomplete() { + let complete = dns_query(); + for missing in [1, 2] { + let message = &complete[..complete.len() - missing]; + let dns = decode(1, &packet(message)).dns.unwrap(); + assert!(dns.incomplete, "missing {missing} class bytes"); + assert!(dns.questions.is_empty(), "a question needs both type and class"); + } +} + +#[test] +fn complete_questions_survive_before_a_truncated_question() { + let mut message = dns_query(); + message[4..6].copy_from_slice(&2u16.to_be_bytes()); + message.extend([0xc0, 12, 0, 28, 0]); // compressed name, AAAA, one class byte + + let dns = decode(1, &packet(&message)).dns.unwrap(); + assert!(dns.incomplete); + assert_eq!(dns.questions.len(), 1); + assert_eq!(dns.questions[0].name, "example.com"); + assert_eq!(dns.questions[0].qtype, "A"); +} + +#[test] +fn incomplete_questions_do_not_enter_the_query_inventory() { + let mut message = dns_query(); + message.pop(); + let summary = summarize(&pcap(&[packet(&message)]), &|| false).unwrap(); + assert_eq!(summary.packets, 1); + assert!(summary.dns_queries.is_empty()); +} + +/// Class validation requires both bytes without restricting valid class values. +#[test] +fn complete_class_fields_are_accepted() { + for class in [1u16, 3, 255] { + let mut message = dns_query(); + message.truncate(message.len() - 2); + message.extend(class.to_be_bytes()); + let dns = decode(1, &packet(&message)).dns.unwrap(); + assert!(!dns.incomplete); + assert_eq!(dns.questions.len(), 1); + assert_eq!(dns.questions[0].name, "example.com"); + assert_eq!(dns.questions[0].qtype, "A"); + } +} diff --git a/crates/pcap/tests/dns_rdata_names.rs b/crates/pcap/tests/dns_rdata_names.rs new file mode 100644 index 0000000000..7e8542a0af --- /dev/null +++ b/crates/pcap/tests/dns_rdata_names.rs @@ -0,0 +1,272 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{decode, summarize}; +use support::{dns_query, eth, ipv4_pkt, pcap, udp}; + +fn response(record_type: u16, rdata: &[u8], declared_length: usize) -> Vec { + let mut message = dns_query(); + message[2..4].copy_from_slice(&0x8180u16.to_be_bytes()); + message[6..8].copy_from_slice(&1u16.to_be_bytes()); + message.extend([0xc0, 12]); // owner points to the question's name + message.extend(record_type.to_be_bytes()); + message.extend(1u16.to_be_bytes()); + message.extend(60u32.to_be_bytes()); + message.extend((declared_length as u16).to_be_bytes()); + message.extend(rdata); + message +} + +fn packet(message: &[u8]) -> Vec { + eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 2], [192, 0, 2, 1], &udp(53, 51000, message))) +} + +/// Truncated literal names and compression pointers must stay inside RDLENGTH. +#[test] +fn answer_names_cannot_borrow_bytes_past_rdata() { + for record_type in [2, 5, 12, 15] { + for name in [b"\x04fake\x07example\x00".as_slice(), &[0xc0, 12]] { + let mut rdata = if record_type == 15 { vec![0, 10] } else { Vec::new() }; + let prefix = rdata.len(); + rdata.extend(name); + for declared in [prefix, prefix + name.len() - 1] { + let dns = decode(1, &packet(&response(record_type, &rdata, declared))).dns.unwrap(); + assert!(dns.incomplete, "type {record_type}, declared length {declared}"); + assert!(dns.answers.is_empty(), "a name must be wholly encoded in its record"); + } + } + } +} + +/// An incomplete pointer is malformed, rather than a successful empty answer. +#[test] +fn malformed_name_rdata_is_not_reported_as_an_empty_answer() { + for record_type in [2, 5, 12, 15] { + let rdata = if record_type == 15 { vec![0, 10, 0xc0] } else { vec![0xc0] }; + let dns = decode(1, &packet(&response(record_type, &rdata, rdata.len()))).dns.unwrap(); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +/// An MX name cannot borrow either of its required preference bytes from trailing data. +#[test] +fn an_mx_exchange_cannot_skip_a_missing_preference() { + for declared in [0, 1] { + let dns = decode(1, &packet(&response(15, &[0, 10, 0xc0, 12], declared))).dns.unwrap(); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +/// A terminator before the declared boundary must not hide unused RDATA bytes. +#[test] +fn a_name_must_account_for_all_of_its_rdata() { + for record_type in [2, 5, 12, 15] { + let rdata = if record_type == 15 { vec![0, 10, 0, 0xaa] } else { vec![0, 0xaa] }; + let dns = decode(1, &packet(&response(record_type, &rdata, rdata.len()))).dns.unwrap(); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +/// Literal, root, backward-pointer and label-plus-pointer names remain valid controls. +#[test] +fn complete_and_compressed_names_remain_supported() { + for record_type in [2, 5, 12, 15] { + for (name, expected) in [ + (b"\x04mail\x07example\x00".as_slice(), "mail.example"), + (&[0xc0, 12], "example.com"), + (b"\x03www\xc0\x0c".as_slice(), "www.example.com"), + (&[0], "."), + ] { + let mut rdata = if record_type == 15 { vec![0, 10] } else { Vec::new() }; + rdata.extend(name); + let dns = decode(1, &packet(&response(record_type, &rdata, rdata.len()))).dns.unwrap(); + assert!(!dns.incomplete, "type {record_type}, name {expected}"); + assert_eq!(dns.answers.len(), 1); + assert_eq!(dns.answers[0].value, expected); + } + } +} + +#[test] +fn names_outside_rdata_do_not_enter_the_answer_inventory() { + let message = response(5, b"\x04fake\x07example\x00", 0); + let summary = summarize(&pcap(&[packet(&message)]), &|| false).unwrap(); + assert_eq!(summary.packets, 1); + assert!(summary.dns_answers.is_empty()); +} + +#[test] +fn earlier_answers_survive_before_a_malformed_name() { + let mut message = response(1, &[192, 0, 2, 3], 4); + message[6..8].copy_from_slice(&2u16.to_be_bytes()); + let malformed = response(5, b"\x04fake\x07example\x00", 0); + message.extend(&malformed[dns_query().len()..]); + + let dns = decode(1, &packet(&message)).dns.unwrap(); + assert!(dns.incomplete); + assert_eq!(dns.answers.len(), 1); + assert_eq!(dns.answers[0].rtype, "A"); + assert_eq!(dns.answers[0].value, "192.0.2.3"); +} + +fn prerequisite_message(flags: u16, record_type: u16, class: u16, ttl: u32, rdata: &[u8]) -> Vec { + let mut message = vec![0, 1]; + message.extend(flags.to_be_bytes()); + message.extend([0, 1, 0, 2, 0, 0, 0, 0]); + message.extend(b"\x07example\x04test\0"); + message.extend([0, 6, 0, 1]); // One Zone record, SOA/IN. + message.extend(b"\x05first\xc0\x0c"); + message.extend(record_type.to_be_bytes()); + message.extend(class.to_be_bytes()); + message.extend(ttl.to_be_bytes()); + message.extend((rdata.len() as u16).to_be_bytes()); + message.extend(rdata); + // A different owner lets this value-dependent prerequisite coexist with CLASS NONE above. + message.extend(b"\x05after\xc0\x0c"); + message.extend([0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 192, 0, 2, 4]); + message +} + +#[test] +fn empty_update_name_prerequisites_preserve_the_following_record() { + for record_type in [2, 5, 12, 15] { + for class in [254, 255] { + let dns = decode(1, &packet(&prerequisite_message(0x2800, record_type, class, 0, &[]))).dns.unwrap(); + assert!(!dns.incomplete, "type {record_type}, class {class}"); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].value, ""); + assert_eq!(dns.answers[1].name, "after.example.test"); + assert_eq!(dns.answers[1].value, "192.0.2.4"); + } + } +} + +#[test] +fn empty_name_rdata_is_rejected_outside_legal_update_prerequisites() { + let cases = [(0x8180, 254, 0), (0x8180, 255, 0), (0x2000, 254, 0), (0x2000, 255, 0), (0x2800, 1, 0), (0x2800, 254, 1), (0x2800, 255, 1)]; + for record_type in [2, 5, 12, 15] { + for (flags, class, ttl) in cases { + let dns = decode(1, &packet(&prerequisite_message(flags, record_type, class, ttl, &[]))).dns.unwrap(); + assert!(dns.incomplete, "type {record_type}, flags {flags:#x}, class {class}, TTL {ttl}"); + assert!(dns.answers.is_empty()); + } + } +} + +#[test] +fn update_name_rdata_still_requires_complete_exact_encoding() { + for record_type in [2, 5, 12, 15] { + for class in [1, 254, 255] { + for name in [&[0xc0][..], &[0, 0xaa]] { + let mut rdata = if record_type == 15 { vec![0, 10] } else { Vec::new() }; + rdata.extend(name); + let dns = decode(1, &packet(&prerequisite_message(0x2800, record_type, class, 0, &rdata))).dns.unwrap(); + assert!(dns.incomplete, "type {record_type}, class {class}, name {name:?}"); + assert!(dns.answers.is_empty()); + } + } + } +} + +#[test] +fn value_dependent_update_name_prerequisites_keep_their_values() { + for record_type in [2, 5, 12, 15] { + for (name, expected) in [(&[0][..], "."), (&[0xc0, 12], "example.test")] { + let mut rdata = if record_type == 15 { vec![0, 0] } else { Vec::new() }; + rdata.extend(name); + let dns = decode(1, &packet(&prerequisite_message(0x2800, record_type, 1, 0, &rdata))).dns.unwrap(); + assert!(!dns.incomplete, "type {record_type}, name {expected}"); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].value, expected); + assert_eq!(dns.answers[1].value, "192.0.2.4"); + } + } +} + +#[test] +fn an_in_address_requires_the_right_wire_size_but_update_prerequisites_may_be_empty() { + for (kind, bad) in [(1, &[1, 2, 3][..]), (28, &[0; 15][..])] { + let mut msg = response(kind, bad, bad.len()); + assert!(decode(1, &packet(&msg)).dns.unwrap().incomplete); + msg = response(kind, &[], 0); + msg[2..4].copy_from_slice(&0x2800u16.to_be_bytes()); + let n = msg.len(); + msg[n - 8..n - 6].copy_from_slice(&255u16.to_be_bytes()); + msg[n - 6..n - 2].fill(0); + let dns = decode(1, &packet(&msg)).dns.unwrap(); + assert!(!dns.incomplete); + assert_eq!(dns.answers[0].value, ""); + } +} + +#[test] +fn questionless_announcements_and_truncated_responses_keep_their_address() { + let mut message = vec![0, 0, 0x86, 0, 0, 0, 0, 1, 0, 0, 0, 0]; + message.extend(b"\x04node\x05local\x00\x00\x01\x80\x01\x00\x00\x00\x3c\x00\x04\xc0\x00\x02\x04"); + let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [224, 0, 0, 251], &udp(5353, 5353, &message))); + let dns = decode(1, &frame).dns.unwrap(); + assert!(dns.incomplete); + assert_eq!(dns.answers.len(), 1); + assert_eq!(summarize(&pcap(&[frame]), &|| false).unwrap().dns_addresses[0].value, "node.local A 192.0.2.4"); + assert!(decode(1, &packet(&message[..8])).dns.is_none()); +} + +#[test] +fn service_records_report_their_fields_and_refuse_invalid_framing() { + let mut soa = vec![0xc0, 12, 0xc0, 12]; + for n in 1u32..=5 { + soa.extend(n.to_be_bytes()); + } + for (kind, data, expected) in [ + (33, &b"\x00\x01\x00\x02\x01\xbb\x03srv\x00"[..], "1 2 443 srv"), + (6, soa.as_slice(), "example.com example.com 1 2 3 4 5"), + (257, &b"\x80\x05issueca.test"[..], "128 issue ca.test"), + ] { + let dns = decode(1, &packet(&response(kind, data, data.len()))).dns.unwrap(); + assert!(!dns.incomplete); + assert_eq!(dns.answers[0].value, expected); + } + for (kind, bad) in [(33, &b"\x00\x01\x00\x02\x01\xbb\xc0\x0c"[..]), (6, &soa[..soa.len() - 1]), (257, &b"\x00\x06issue"[..])] { + let dns = decode(1, &packet(&response(kind, bad, bad.len()))).dns.unwrap(); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn mdns_srv_targets_can_be_compressed_except_in_legacy_replies() { + let data = [0, 1, 0, 2, 1, 187, 0xc0, 12]; + let msg = response(33, &data, data.len()); + for (port, legacy) in [(5353, false), (51000, true)] { + let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [192, 0, 2, 1], &udp(5353, port, &msg))); + let dns = decode(1, &frame).dns.unwrap(); + assert_eq!(dns.incomplete, legacy); + if !legacy { + assert_eq!(dns.answers[0].value, "1 2 443 example.com"); + } + } +} + +#[test] +fn caa_binary_values_remain_distinct_in_the_inventory() { + for (bytes, display) in [(&b"\xff"[..], r"\xff"), (b"\xfe", r"\xfe"), (br"\xff", r"\\xff")] { + let mut data = b"\x00\x01x".to_vec(); + data.extend(bytes); + let dns = decode(1, &packet(&response(257, &data, data.len()))).dns.unwrap(); + assert_eq!(dns.answers[0].value, format!("0 x {display}")); + } +} + +#[test] +fn only_mdns_masks_the_cache_flush_bit_in_an_address_class() { + let mut msg = response(1, &[192, 0, 2, 1], 4); + let class = msg.len() - 12; + msg[class..class + 2].copy_from_slice(&0x8001u16.to_be_bytes()); + for (port, expected) in [(53, "<4 bytes>"), (5353, "192.0.2.1")] { + let frame = eth(0x0800, &ipv4_pkt(17, [192, 0, 2, 4], [192, 0, 2, 1], &udp(port, port, &msg))); + assert_eq!(decode(1, &frame).dns.unwrap().answers[0].value, expected); + } +} diff --git a/crates/pcap/tests/pcap_dns_name_limit.rs b/crates/pcap/tests/pcap_dns_name_limit.rs new file mode 100644 index 0000000000..82fc4e9f06 --- /dev/null +++ b/crates/pcap/tests/pcap_dns_name_limit.rs @@ -0,0 +1,167 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Dns, decode}; +use support::{ipv4_pkt, udp}; + +fn query(last: usize, compressed: bool) -> Dns { + let mut msg = vec![0, 1, 1, 0, 0, if compressed { 2 } else { 1 }, 0, 0, 0, 0, 0, 0]; + for len in [63, 63, 63, last] { + msg.push(len as u8); + msg.extend(vec![b'a'; len]); + } + msg.extend([0, 0, 1, 0, 1]); + if compressed { + msg.extend([0xc0, 12, 0, 1, 0, 1]); + } + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(100, 53, &msg))).dns.unwrap() +} + +#[test] +fn label_lengths_and_the_root_octet_count_towards_the_dns_limit() { + for last in [62, 63] { + let dns = query(last, false); + assert!(dns.incomplete); + assert!(dns.questions.is_empty()); + } +} + +#[test] +fn a_255_octet_name_is_valid_in_plain_and_compressed_form() { + for compressed in [false, true] { + let dns = query(61, compressed); + assert!(!dns.incomplete); + assert_eq!(dns.questions.len(), if compressed { 2 } else { 1 }); + assert_eq!(dns.questions[0].name.len(), 253); + } +} + +fn prefixed_pointer(last: usize, answer_type: Option) -> Dns { + let mut msg = vec![0, 1, 0x81, 0x80, 0, if answer_type.is_some() { 1 } else { 2 }, 0, u8::from(answer_type.is_some()), 0, 0, 0, 0]; + for len in [63, 63, 63, last] { + msg.push(len as u8); + msg.extend(vec![b'a'; len]); + } + msg.extend([0, 0, 1, 0, 1]); + if let Some(rtype) = answer_type { + msg.extend([0xc0, 12]); + msg.extend(rtype.to_be_bytes()); + msg.extend([0, 1, 0, 0, 0, 0, 0, if rtype == 15 { 6 } else { 4 }]); + if rtype == 15 { + msg.extend([0, 10]); + } + } + msg.extend([1, b'x', 0xc0, 12]); + if answer_type.is_none() { + msg.extend([0, 1, 0, 1]); + } + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(100, 53, &msg))).dns.unwrap() +} + +#[test] +fn a_literal_prefix_and_pointer_cannot_exceed_the_question_name_limit() { + let dns = prefixed_pointer(61, None); + assert!(dns.incomplete); + assert_eq!(dns.questions.len(), 1); +} + +#[test] +fn invalid_name_rdata_is_incomplete_instead_of_an_empty_answer() { + for rtype in [2, 5, 12, 15] { + let dns = prefixed_pointer(61, Some(rtype)); + assert!(dns.incomplete, "record type {rtype}"); + assert_eq!(dns.questions.len(), 1); + assert!(dns.answers.is_empty(), "record type {rtype}"); + } +} + +#[test] +fn a_prefixed_pointer_at_255_octets_remains_valid() { + let dns = prefixed_pointer(59, None); + assert!(!dns.incomplete); + assert_eq!(dns.questions.len(), 2); + for rtype in [2, 5, 12, 15] { + let dns = prefixed_pointer(59, Some(rtype)); + assert!(!dns.incomplete, "record type {rtype}"); + assert_eq!(dns.answers.len(), 1); + assert_eq!(dns.answers[0].value.len(), 253); + } +} + +fn name_rdata_then_a(flags: u16, class: u16, ttl: u32, rtype: u16, rdata: &[u8]) -> Dns { + let mut msg = vec![0, 1]; + msg.extend(flags.to_be_bytes()); + msg.extend([0, 1, 0, 2, 0, 0, 0, 0]); + msg.extend(b"\x07example\x04test\0"); + msg.extend([0, 6, 0, 1]); // Zone: SOA/IN for UPDATE requests. + msg.extend([3, b'o', b'n', b'e', 0xc0, 12]); + msg.extend(rtype.to_be_bytes()); + msg.extend(class.to_be_bytes()); + msg.extend(ttl.to_be_bytes()); + msg.extend((rdata.len() as u16).to_be_bytes()); + msg.extend(rdata); + // A different owner keeps the two UPDATE prerequisites independent. + msg.extend([4, b'n', b'e', b'x', b't', 0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 203, 0, 113, 1]); + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(100, 53, &msg))).dns.unwrap() +} + +#[test] +fn empty_update_name_prerequisites_preserve_the_following_record() { + for rtype in [2, 5, 12, 15] { + for class in [254, 255] { + let dns = name_rdata_then_a(0x2800, class, 0, rtype, &[]); + assert!(!dns.incomplete, "type {rtype}, class {class}"); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].value, ""); + assert_eq!(dns.answers[1].value, "203.0.113.1"); + } + } +} + +#[test] +fn empty_name_rdata_is_rejected_outside_legal_update_prerequisites() { + let cases = [(0x8180, 254, 0), (0x8180, 255, 0), (0x2000, 254, 0), (0x2000, 255, 0), (0x2800, 1, 0), (0x2800, 254, 1), (0x2800, 255, 1)]; + for rtype in [2, 5, 12, 15] { + for (flags, class, ttl) in cases { + let dns = name_rdata_then_a(flags, class, ttl, rtype, &[]); + assert!(dns.incomplete, "type {rtype}, flags {flags:#x}, class {class}, TTL {ttl}"); + assert!(dns.answers.is_empty()); + } + } +} + +#[test] +fn a_cut_rdata_pointer_cannot_borrow_the_following_owner() { + for rtype in [2, 5, 12, 15] { + let mut rdata = if rtype == 15 { vec![0, 10] } else { Vec::new() }; + rdata.push(0xc0); // The next owner's length would complete a pointer to the header's zero byte. + let dns = name_rdata_then_a(0x8180, 1, 0, rtype, &rdata); + assert!(dns.incomplete, "type {rtype}"); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn root_name_rdata_remains_valid() { + for rtype in [2, 5, 12, 15] { + let rdata = if rtype == 15 { vec![0, 0, 0] } else { vec![0] }; + let dns = name_rdata_then_a(0x8180, 1, 0, rtype, &rdata); + assert!(!dns.incomplete, "type {rtype}"); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].value, "."); + assert_eq!(dns.answers[1].value, "203.0.113.1"); + } +} + +#[test] +fn dns_label_escapes_distinguish_wire_names_in_question_and_answer_owners() { + let mut message = vec![0, 1, 0x81, 0x80, 0, 2, 0, 1, 0, 0, 0, 0]; + message.extend(b"\x03a.b\x03\\\x00\xff\x00\x00\x01\x00\x01"); + message.extend(b"\x01a\x01b\x03\\\x00\xff\x00\x00\x01\x00\x01"); + message.extend([0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4]); + let dns = decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(53, 100, &message))).dns.unwrap(); + assert!(!dns.incomplete); + assert_eq!(dns.questions[0].name, r"a\.b.\\\000\255"); + assert_eq!(dns.questions[1].name, r"a.b.\\\000\255"); + assert_eq!(dns.answers[0].name, dns.questions[0].name); +} diff --git a/crates/pcap/tests/pcap_dns_txt_lengths.rs b/crates/pcap/tests/pcap_dns_txt_lengths.rs new file mode 100644 index 0000000000..56312df41a --- /dev/null +++ b/crates/pcap/tests/pcap_dns_txt_lengths.rs @@ -0,0 +1,199 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Dns, decode}; +use support::{ipv4_pkt, udp}; + +fn response(data: &[u8]) -> Dns { + let mut msg = vec![0, 1, 0x81, 0x80, 0, 0, 0, 1, 0, 0, 0, 0]; + msg.extend([0, 0, 16, 0, 1, 0, 0, 0, 60]); + msg.extend((data.len() as u16).to_be_bytes()); + msg.extend(data); + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(53, 100, &msg))).dns.unwrap() +} + +fn prerequisites(flags: u16, class: u16, ttl: u32, data: &[u8]) -> Dns { + let mut msg = vec![0, 1]; + msg.extend(flags.to_be_bytes()); + msg.extend([0, 1, 0, 2, 0, 0, 0, 0]); + // UPDATE's zone section has the question layout: example.test, SOA, IN. + msg.extend(b"\x07example\x04test\x00\x00\x06\x00\x01"); + msg.extend([0xc0, 12, 0, 16]); + msg.extend(class.to_be_bytes()); + msg.extend(ttl.to_be_bytes()); + msg.extend((data.len() as u16).to_be_bytes()); + msg.extend(data); + // Different owners let NONE and value-dependent prerequisites hold together. + // The following TXT record must also survive. + msg.extend(b"\x05after"); + msg.extend([0xc0, 12, 0, 16, 0, 1, 0, 0, 0, 0, 0, 3, 2, b'o', b'k']); + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(100, 53, &msg))).dns.unwrap() +} + +fn named_txt(owner: &[&[u8]], data: &[u8], port: u16, flags: u16, class: u16, ttl: u32, compressed: bool) -> Dns { + let mut name = Vec::new(); + for label in owner { + name.push(u8::try_from(label.len()).unwrap()); + name.extend(*label); + } + name.push(0); + let mut msg = vec![0, 1]; + msg.extend(flags.to_be_bytes()); + msg.extend([0, 1, 0, 2, 0, 0, 0, 0]); + msg.extend(&name); + msg.extend([0, 16, 0, 1]); + if compressed { + msg.extend([0xc0, 12]); + } else { + msg.extend(&name); + } + msg.extend([0, 16]); + msg.extend(class.to_be_bytes()); + msg.extend(ttl.to_be_bytes()); + msg.extend(u16::try_from(data.len()).unwrap().to_be_bytes()); + msg.extend(data); + // The next answer must survive an empty DNS-SD TXT record. + msg.extend([0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 127, 0, 0, 1]); + decode(101, &ipv4_pkt(17, [1; 4], [2; 4], &udp(port, 100, &msg))).dns.unwrap() +} + +fn assert_empty_txt_and_following_answer(dns: Dns) { + assert!(!dns.incomplete); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].rtype, "TXT"); + assert_eq!(dns.answers[0].value, ""); + assert_eq!(dns.answers[1].value, "127.0.0.1"); +} + +#[test] +fn empty_dns_sd_txt_preserves_following_answers() { + let multicast: &[&[u8]] = &[b"Printer", b"_ipp", b"_tcp", b"local"]; + let unicast: &[&[u8]] = &[b"Printer", b"_ipp", b"_tcp", b"example", b"test"]; + for (port, owner) in [(5353, multicast), (53, unicast)] { + assert_empty_txt_and_following_answer(named_txt(owner, &[], port, 0x8400, 1, 60, false)); + } +} + +#[test] +fn empty_dns_sd_txt_is_valid_in_mdns_known_answers_and_cache_flush_records() { + let owner: &[&[u8]] = &[b"Printer", b"_ipp", b"_tcp", b"local"]; + // Queries may contain known answers; the cache-flush bit belongs to CLASS. + for (flags, class) in [(0, 1), (0x8400, 0x8001)] { + assert_empty_txt_and_following_answer(named_txt(owner, &[], 5353, flags, class, 60, false)); + } +} + +#[test] +fn dns_sd_owner_preserves_wire_labels_case_and_compression() { + let owner: &[&[u8]] = &[b"Printer.with dots", b"_Ab-12", b"_UdP", b"example", b"test"]; + for compressed in [false, true] { + assert_empty_txt_and_following_answer(named_txt(owner, &[], 53, 0x8180, 1, 60, compressed)); + } +} + +#[test] +fn other_empty_txt_owners_are_not_dns_sd_instances() { + let owners: &[&[&[u8]]] = &[ + &[b"Printer", b"local"], + &[b"Printer._ipp._tcp", b"local"], + &[b"Printer", b"_ipp._tcp", b"_tcp", b"local"], + &[b"_ipp", b"_tcp", b"local"], + &[b"Printer", b"_ipp", b"_tcp"], + &[b"Printer", b"_ipp", b"_other", b"local"], + &[b"Printer", b"_123", b"_tcp", b"local"], + &[b"Printer", b"_bad--name", b"_tcp", b"local"], + ]; + for owner in owners { + let dns = named_txt(owner, &[], 5353, 0x8400, 1, 60, false); + assert!(dns.incomplete, "owner {owner:?}"); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn dns_sd_txt_still_rejects_truncated_nonempty_strings() { + let owner: &[&[u8]] = &[b"Printer", b"_ipp", b"_tcp", b"local"]; + for data in [&b"\x02x"[..], &b"\x00\x04x"[..]] { + let dns = named_txt(owner, data, 5353, 0x8400, 0x8001, 60, true); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn dns_sd_owner_does_not_relax_update_prerequisite_classes() { + let owner: &[&[u8]] = &[b"Printer", b"_ipp", b"_tcp", b"example", b"test"]; + let dns = named_txt(owner, &[], 53, 5 << 11, 1, 0, true); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + for class in [254, 255] { + assert_empty_txt_and_following_answer(named_txt(owner, &[], 53, 5 << 11, class, 0, true)); + } +} + +#[test] +fn empty_update_prerequisites_preserve_following_records() { + for class in [254, 255] { + let dns = prerequisites(5 << 11, class, 0, &[]); + assert!(!dns.incomplete, "class {class}"); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].name, "example.test"); + assert_eq!(dns.answers[0].value, ""); + assert_eq!(dns.answers[1].name, "after.example.test"); + assert_eq!(dns.answers[1].value, "ok"); + } +} + +#[test] +fn empty_txt_rdata_requires_update_and_a_prerequisite_class() { + assert!(response(&[]).incomplete); + for (flags, class, ttl) in [(0x8180, 254, 0), (0x8180, 255, 0), (5 << 11, 1, 0), (5 << 11, 254, 60), (5 << 11, 255, 60)] { + let dns = prerequisites(flags, class, ttl, &[]); + assert!(dns.incomplete, "flags {flags:#x}, class {class}, ttl {ttl}"); + assert!(dns.answers.is_empty()); + } + for opcode in [1, 2, 3, 4, 6] { + for class in [254, 255] { + let dns = prerequisites(opcode << 11, class, 0, &[]); + assert!(dns.incomplete, "opcode {opcode}, class {class}"); + assert!(dns.answers.is_empty()); + } + } +} + +#[test] +fn update_prerequisite_classes_do_not_allow_truncated_strings() { + for class in [254, 255] { + let dns = prerequisites(5 << 11, class, 0, b"\x02x"); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn truncated_txt_strings_are_not_complete_answers() { + for data in [&b"\x05abc"[..], &b"\x02ok\x04x"[..], &b"\x01"[..]] { + let dns = response(data); + assert!(dns.incomplete); + assert!(dns.answers.is_empty()); + } +} + +#[test] +fn empty_and_multiple_complete_strings_remain_valid() { + for (data, expected) in [(&b"\x00"[..], ""), (&b"\x00\x02ok\x01!"[..], "ok!")] { + let dns = response(data); + assert!(!dns.incomplete); + assert_eq!(dns.answers[0].value, expected); + } +} + +#[test] +fn value_dependent_update_accepts_an_empty_character_string() { + let dns = prerequisites(5 << 11, 1, 0, b"\x00"); + assert!(!dns.incomplete); + assert_eq!(dns.answers.len(), 2); + assert_eq!(dns.answers[0].value, ""); + assert_eq!(dns.answers[1].name, "after.example.test"); + assert_eq!(dns.answers[1].value, "ok"); +} diff --git a/crates/pcap/tests/pcap_flow_time_range.rs b/crates/pcap/tests/pcap_flow_time_range.rs new file mode 100644 index 0000000000..722121f4b7 --- /dev/null +++ b/crates/pcap/tests/pcap_flow_time_range.rs @@ -0,0 +1,39 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::summarize; +use support::{block, eth, ipv4_pkt, pcap, pcapng, udp}; + +fn frame() -> Vec { + eth(0x0800, &ipv4_pkt(17, [1; 4], [2; 4], &udp(100, 200, b"body"))) +} + +#[test] +fn out_of_order_flow_packets_keep_the_earliest_and_latest_timestamps() { + let f = frame(); + let mut capture = pcap(&[f.clone(), f.clone(), f.clone()]); + for (i, seconds) in [30u32, 10, 20].into_iter().enumerate() { + let at = 24 + i * (16 + f.len()); + capture[at..at + 4].copy_from_slice(&seconds.to_le_bytes()); + } + let summary = summarize(&capture, &|| false).unwrap(); + let flow = &summary.flows[0]; + assert_eq!(flow.first_ts_ns, summary.first_ts_ns); + assert_eq!(flow.last_ts_ns, summary.last_ts_ns); + assert_eq!(flow.first_frame, 1); +} + +#[test] +fn a_timestamped_packet_fills_a_flow_started_by_a_simple_packet() { + let f = frame(); + let headers = pcapng(&[]); + let mut simple = (f.len() as u32).to_le_bytes().to_vec(); + simple.extend(&f); + let mut capture = headers.clone(); + capture.extend(block(3, &simple)); + capture.extend(&pcapng(&[f])[headers.len()..]); + let summary = summarize(&capture, &|| false).unwrap(); + assert!(summary.first_ts_ns.is_some()); + assert_eq!(summary.flows[0].first_ts_ns, summary.first_ts_ns); + assert_eq!(summary.flows[0].last_ts_ns, summary.last_ts_ns); +} diff --git a/crates/pcap/tests/pcap_http_host_boundary.rs b/crates/pcap/tests/pcap_http_host_boundary.rs new file mode 100644 index 0000000000..5baa58feef --- /dev/null +++ b/crates/pcap/tests/pcap_http_host_boundary.rs @@ -0,0 +1,70 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Http, decode}; +use support::{ipv4_pkt, tcp}; + +fn request(data: &[u8]) -> Http { + decode(101, &ipv4_pkt(6, [1; 4], [2; 4], &tcp(100, 80, 0x18, data))).http.unwrap() +} + +#[test] +fn a_host_shaped_line_in_the_body_is_not_a_request_header() { + let http = request(b"POST / HTTP/1.1\r\nContent-Length: 22\r\n\r\nbody\r\nHost: forged.test\r\n"); + assert!(http.host.is_none()); +} + +#[test] +fn invalid_utf8_before_host_does_not_shift_header_byte_offsets() { + let http = request(b"GET / HTTP/1.1\r\nX-Data: \xff\r\nHoSt:\tReal.test \t\r\n\r\n"); + assert_eq!(http.host.as_deref(), Some("Real.test")); +} + +#[test] +fn host_requires_a_complete_header_line_and_keeps_its_spelling() { + assert!(request(b"GET / HTTP/1.1\r\nHost: cut").host.is_none()); + assert_eq!(request(b"GET / HTTP/1.1\r\nHost: Real.test\r\n\r\n").host.as_deref(), Some("Real.test")); +} + +#[test] +fn http_evidence_needs_a_complete_start_line() { + for input in [ + b"GET / HTTP/1.1".as_slice(), + b"GET / HTTP/1.1x\r\n", + b"GET / HTTP/1.1 extra\r\n", + b"GET HTTP/1.0\r\n", + b"GET /bad\tpath HTTP/1.1\r\n", + b"HTTP/1.garbage\r\n", + b"HTTP/1.1 20 OK\r\n", + b"HTTP/1.1 999 OK\r\n", + b"HTTP/1.1 200 OK", + b"HTTP/1.garbage 204\r\n\r\n", + b"HTTP/1.1 20\r\n\r\n", + b"HTTP/1.1 2040\r\n\r\n", + b"HTTP/1.1 999\r\n\r\n", + b"HTTP/1.1 2x4\r\n\r\n", + b"HTTP/1.1 204", + b"HTTP/1.1 204 bad\0reason\r\n\r\n", + ] { + assert!(decode(101, &ipv4_pkt(6, [1; 4], [2; 4], &tcp(100, 80, 0x18, input))).http.is_none(), "{input:?}"); + } + assert_eq!(request(b"GET / HTTP/1.0\r\n").version, "HTTP/1.0"); + assert_eq!(request(b"HTTP/1.1 204 \r\n").status, Some(204)); + assert_eq!(request(b"HTTP/1.1 403 Access denied\r\n").status, Some(403)); +} + +#[test] +fn responses_with_no_reason_phrase_still_keep_the_status_code() { + for (input, version, code) in + [(b"HTTP/1.1 204\r\n\r\n".as_slice(), "HTTP/1.1", 204), (b"HTTP/1.0 200\r\nContent-Length: 0\r\n\r\n".as_slice(), "HTTP/1.0", 200)] + { + let decoded = decode(101, &ipv4_pkt(6, [1; 4], [2; 4], &tcp(80, 100, 0x18, input))); + assert!(decoded.protocols.contains(&"http")); + let http = decoded.http.unwrap(); + assert_eq!(http.kind, "response"); + assert_eq!(http.version, version); + assert_eq!(http.status, Some(code)); + assert!(http.method.is_none()); + assert!(http.target.is_none()); + } +} diff --git a/crates/pcap/tests/pcap_http_methods.rs b/crates/pcap/tests/pcap_http_methods.rs new file mode 100644 index 0000000000..57eb4e5487 --- /dev/null +++ b/crates/pcap/tests/pcap_http_methods.rs @@ -0,0 +1,35 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::decode; +use support::{ipv4_pkt, tcp}; + +/// WebDAV and extension methods retain the same HTTP evidence as core methods. +#[test] +fn extension_methods_are_http_requests() { + for method in ["PROPFIND", "MKCOL", "LOCK", "REPORT", "M-SEARCH", "custom", "X!#$%&'*+-.^_`|~012"] { + let request = format!("{method} /collection/ HTTP/1.1\r\nHost: dav.example\r\n\r\n"); + let decoded = decode(101, &ipv4_pkt(6, [1; 4], [2; 4], &tcp(100, 80, 0x18, request.as_bytes()))); + let http = decoded.http.unwrap_or_else(|| panic!("missing HTTP: {method}")); + assert_eq!(http.method.as_deref(), Some(method)); + assert_eq!(http.target.as_deref(), Some("/collection/")); + assert_eq!(http.host.as_deref(), Some("dav.example")); + } +} + +/// A method still needs a nonempty ASCII token and a complete valid start line. +#[test] +fn invalid_extension_method_lines_are_not_http() { + for request in [ + " / HTTP/1.1\r\n", + "BAD:METHOD / HTTP/1.1\r\n", + "BAD/METHOD / HTTP/1.1\r\n", + "MÉTHOD / HTTP/1.1\r\n", + "BAD\tMETHOD / HTTP/1.1\r\n", + "PROPFIND / HTTP/1.1", + "PROPFIND / HTTP/no\r\n", + ] { + let decoded = decode(101, &ipv4_pkt(6, [1; 4], [2; 4], &tcp(100, 80, 0x18, request.as_bytes()))); + assert!(decoded.http.is_none(), "{request:?}"); + } +} diff --git a/crates/pcap/tests/pcap_ipv4_lengths.rs b/crates/pcap/tests/pcap_ipv4_lengths.rs new file mode 100644 index 0000000000..e1ea930a0a --- /dev/null +++ b/crates/pcap/tests/pcap_ipv4_lengths.rs @@ -0,0 +1,60 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::decode; +use support::{ipv4_pkt, udp}; + +#[test] +fn incomplete_ipv4_base_headers_explain_why_decoding_stopped() { + let packet = ipv4_pkt(17, [1; 4], [2; 4], &[]); + for captured in 10..20 { + let decoded = decode(101, &packet[..captured]); + assert!(decoded.ip.is_none(), "captured {captured} bytes"); + assert!(decoded.transport.is_none(), "captured {captured} bytes"); + assert_eq!(decoded.note.as_deref(), Some("IPv4 header cut short"), "captured {captured} bytes"); + } +} + +#[test] +fn an_ipv4_total_length_cannot_be_shorter_than_its_header() { + for total in [0u16, 19, 23] { + let mut packet = ipv4_pkt(17, [1, 2, 3, 4], [5, 6, 7, 8], &udp(100, 200, b"body")); + packet[0] = 0x46; + packet[2..4].copy_from_slice(&total.to_be_bytes()); + let decoded = decode(101, &packet); + assert!(decoded.ip.is_none()); + assert!(decoded.transport.is_none()); + assert!(decoded.note.is_some()); + } +} + +#[test] +fn missing_ipv4_options_do_not_form_a_complete_ip_header() { + let mut packet = ipv4_pkt(17, [1; 4], [2; 4], &[]); + packet[0] = 0x46; + packet[2..4].copy_from_slice(&24u16.to_be_bytes()); + let decoded = decode(101, &packet); + assert!(decoded.ip.is_none()); + assert!(decoded.note.is_some()); +} + +#[test] +fn complete_options_and_truncated_transport_keep_their_valid_fields() { + let body = udp(100, 200, b"body"); + let mut payload = vec![0; 4]; + payload.extend(body); + let mut packet = ipv4_pkt(17, [1; 4], [2; 4], &payload); + packet[0] = 0x46; + assert_eq!(decode(101, &packet).transport.unwrap().payload_len, 4); + packet.truncate(34); + let decoded = decode(101, &packet); + assert!(decoded.ip.is_some()); + let transport = decoded.transport.unwrap(); + assert_eq!(transport.src_port, Some(100)); + assert_eq!(transport.dst_port, Some(200)); + assert_eq!(transport.payload_len, 2); + packet.truncate(28); + let decoded = decode(101, &packet); + assert!(decoded.ip.is_some()); + assert_eq!(decoded.transport.unwrap().src_port, Some(100)); +} diff --git a/crates/pcap/tests/pcap_ipv6_fragments.rs b/crates/pcap/tests/pcap_ipv6_fragments.rs new file mode 100644 index 0000000000..1c413f4b38 --- /dev/null +++ b/crates/pcap/tests/pcap_ipv6_fragments.rs @@ -0,0 +1,43 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::decode; +use support::{eth, udp}; + +fn packet(offset: u16, next: u8, payload: &[u8]) -> Vec { + let mut ip = vec![0u8; 40]; + ip[0] = 0x60; + ip[4..6].copy_from_slice(&((8 + payload.len()) as u16).to_be_bytes()); + ip[6] = 44; + ip.extend([next, 0]); + ip.extend(offset.to_be_bytes()); + ip.extend([0; 4]); + ip.extend(payload); + eth(0x86dd, &ip) +} + +#[test] +fn a_noninitial_fragment_cannot_reset_its_offset_from_payload_bytes() { + let mut payload = vec![17, 0, 0, 0, 0, 0, 0, 0]; + payload.extend(udp(100, 200, b"body")); + let decoded = decode(1, &packet(8, 44, &payload)); + assert!(decoded.ip.unwrap().fragment); + assert!(decoded.transport.is_none()); + assert!(!decoded.protocols.contains(&"udp")); +} + +#[test] +fn noninitial_fragment_bytes_cannot_change_the_recorded_protocol() { + let decoded = decode(1, &packet(8, 60, &[17, 0, 0, 0, 0, 0, 0, 0])); + assert_eq!(decoded.ip.unwrap().protocol, 60); + assert!(decoded.transport.is_none()); +} + +#[test] +fn initial_and_atomic_fragments_still_decode_transport_headers() { + for offset in [0, 1] { + let decoded = decode(1, &packet(offset, 17, &udp(100, 200, b"body"))); + assert!(!decoded.ip.unwrap().fragment); + assert_eq!(decoded.transport.unwrap().payload_len, 4); + } +} diff --git a/crates/pcap/tests/pcap_ipv6_no_next_header.rs b/crates/pcap/tests/pcap_ipv6_no_next_header.rs new file mode 100644 index 0000000000..b008487680 --- /dev/null +++ b/crates/pcap/tests/pcap_ipv6_no_next_header.rs @@ -0,0 +1,40 @@ +use craft_pcap::decode; + +/// Build a raw IPv6 packet with the given payload and Next Header field. +fn packet(next: u8, payload: &[u8]) -> Vec { + let mut packet = vec![0; 40]; + packet[0] = 0x60; + packet[4..6].copy_from_slice(&u16::try_from(payload.len()).unwrap().to_be_bytes()); + packet[6] = next; + packet[7] = 64; + packet.extend_from_slice(payload); + packet +} + +/// Both an empty packet and bytes after No Next Header have no transport record. +#[test] +fn no_next_header_has_no_transport() { + for payload in [b"".as_slice(), b"padding"] { + let decoded = decode(229, &packet(59, payload)); + assert_eq!(decoded.ip.unwrap().protocol, 59); + assert_eq!(decoded.protocols, ["raw", "ipv6"]); + assert!(decoded.transport.is_none()); + } +} + +/// Destination Options can also end the header chain. +#[test] +fn no_next_header_after_an_extension() { + let decoded = decode(229, &packet(60, &[59, 0, 0, 0, 0, 0, 0, 0, 1, 2])); + assert_eq!(decoded.ip.unwrap().protocol, 59); + assert!(decoded.transport.is_none()); +} + +/// UDP after the same extension still yields its transport and payload. +#[test] +fn udp_after_an_extension_still_decodes() { + let decoded = decode(229, &packet(60, &[17, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 11, 0, 9, 0, 0, 42])); + let transport = decoded.transport.unwrap(); + assert_eq!(transport.protocol, "udp"); + assert_eq!((transport.src_port, transport.dst_port, transport.payload_len), (Some(10), Some(11), 1)); +} diff --git a/crates/pcap/tests/pcap_ipv6_version.rs b/crates/pcap/tests/pcap_ipv6_version.rs new file mode 100644 index 0000000000..f697663210 --- /dev/null +++ b/crates/pcap/tests/pcap_ipv6_version.rs @@ -0,0 +1,56 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::decode; +use support::{eth, ipv4_pkt}; + +fn raw_packets() -> (Vec, Vec) { + let ipv4 = ipv4_pkt(17, [1; 4], [2; 4], &[0; 20]); + let mut ipv6 = vec![0u8; 40]; + ipv6[0] = 0x60; + ipv6[6] = 59; + (ipv4, ipv6) +} + +#[test] +fn explicit_raw_link_types_reject_the_other_ip_version() { + let (ipv4, ipv6) = raw_packets(); + for (link_type, packet) in [(228, &ipv6), (229, &ipv4)] { + let decoded = decode(link_type, packet); + assert!(decoded.ip.is_none(), "link type {link_type}"); + assert!(decoded.transport.is_none(), "link type {link_type}"); + assert!(decoded.note.is_some(), "link type {link_type}"); + } +} + +#[test] +fn matching_raw_link_types_and_generic_raw_packets_remain_readable() { + let (ipv4, ipv6) = raw_packets(); + assert_eq!(decode(228, &ipv4).ip.unwrap().version, 4); + assert_eq!(decode(229, &ipv6).ip.unwrap().version, 6); + for link_type in [12, 14, 101] { + assert_eq!(decode(link_type, &ipv4).ip.unwrap().version, 4); + assert_eq!(decode(link_type, &ipv6).ip.unwrap().version, 6); + } +} + +#[test] +fn an_ethernet_type_does_not_replace_the_ipv6_version_check() { + for version in [0, 4, 5, 7, 15] { + let mut packet = [0u8; 40]; + packet[0] = version << 4; + packet[6] = 59; + let decoded = decode(1, ð(0x86dd, &packet)); + assert!(decoded.ip.is_none(), "version {version}"); + assert!(decoded.transport.is_none()); + assert!(decoded.note.is_some()); + } +} + +#[test] +fn ipv6_version_keeps_traffic_class_bits() { + let mut packet = [0u8; 40]; + packet[0] = 0x6f; + packet[6] = 59; + assert_eq!(decode(1, ð(0x86dd, &packet)).ip.unwrap().version, 6); +} diff --git a/crates/pcap/tests/pcap_tcp_ecn.rs b/crates/pcap/tests/pcap_tcp_ecn.rs new file mode 100644 index 0000000000..278fba8fe6 --- /dev/null +++ b/crates/pcap/tests/pcap_tcp_ecn.rs @@ -0,0 +1,33 @@ +use craft_pcap::decode; + +/// Decode a raw IPv4 packet with a TCP header and the specified control bits. +fn flags_on_wire(bits: u8) -> String { + let mut packet = [0u8; 40]; + packet[0] = 0x45; + packet[2..4].copy_from_slice(&40u16.to_be_bytes()); + packet[8] = 64; + packet[9] = 6; + packet[20..24].copy_from_slice(&[0xc0, 0, 0x01, 0xbb]); + packet[32] = 0x50; + packet[33] = bits; + decode(228, &packet).transport.unwrap().tcp_flags.unwrap() +} + +/// An ECN-capable SYN shows both classic ECN flags. +#[test] +fn reports_ecn_setup_on_syn() { + assert_eq!(flags_on_wire(0xc2), "SYN,ECE,CWR"); +} + +/// The receiver and sender can signal ECE and CWR independently on ACKs. +#[test] +fn distinguishes_ecn_echo_and_window_reduction() { + assert_eq!(flags_on_wire(0x50), "ACK,ECE"); + assert_eq!(flags_on_wire(0x90), "ACK,CWR"); +} + +/// Existing non-ECN packets keep their flag strings. +#[test] +fn keeps_ordinary_ack_flags() { + assert_eq!(flags_on_wire(0x12), "SYN,ACK"); +} diff --git a/crates/pcap/tests/pcapng_simple_payload.rs b/crates/pcap/tests/pcapng_simple_payload.rs new file mode 100644 index 0000000000..ee47430202 --- /dev/null +++ b/crates/pcap/tests/pcapng_simple_payload.rs @@ -0,0 +1,65 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::Capture; +use support::{block, pcapng}; + +fn capture(original: u32, snaplen: u32, payload: &[u8]) -> Vec { + let mut out = pcapng(&[]); + out[40..44].copy_from_slice(&snaplen.to_le_bytes()); + let mut body = original.to_le_bytes().to_vec(); + body.extend(payload); + out.extend(block(3, &body)); + out +} + +#[test] +fn a_simple_packet_cannot_silently_shorten_its_declared_capture() { + let data = capture(10, 0, &[1, 2, 3, 4]); + let mut cap = Capture::new(&data).unwrap(); + assert!(cap.next().is_none()); + assert!(!cap.warnings.is_empty()); +} + +#[test] +fn a_simple_packet_cannot_have_unexplained_extra_payload() { + let data = capture(1, 0, &[1; 8]); + let mut cap = Capture::new(&data).unwrap(); + assert!(cap.next().is_none()); + assert!(!cap.warnings.is_empty()); +} + +#[test] +fn snaplen_truncation_and_alignment_padding_are_preserved() { + for (original, snaplen) in [(3, 0), (10, 3)] { + let data = capture(original, snaplen, &[1, 2, 3]); + let mut cap = Capture::new(&data).unwrap(); + let packet = cap.next().unwrap(); + assert_eq!(packet.data, [1, 2, 3]); + assert_eq!(packet.original_len, original); + assert!(cap.next().is_none()); + assert!(cap.warnings.is_empty()); + } +} + +#[test] +fn rejected_simple_packets_share_one_warning_and_preserve_later_frames() { + let mut data = pcapng(&[]); + let rejected = block(3, &1u32.to_le_bytes()); + for _ in 0..128 { + data.extend(&rejected); + } + let mut valid = 3u32.to_le_bytes().to_vec(); + valid.extend([1, 2, 3]); + data.extend(block(3, &valid)); + let mut cap = Capture::new(&data).unwrap(); + let frame = cap.next().unwrap(); + assert_eq!(frame.number, 1); + assert_eq!(frame.data, [1, 2, 3]); + assert!(cap.next().is_none()); + assert!(!cap.truncated); + assert_eq!(cap.warnings.len(), 1); + assert!(cap.warnings[0].contains("128 simple packet blocks")); + assert!(cap.next().is_none()); + assert_eq!(cap.warnings.len(), 1); +} diff --git a/crates/pcap/tests/regression_pcapng_framing.rs b/crates/pcap/tests/regression_pcapng_framing.rs new file mode 100644 index 0000000000..1ba8d28788 --- /dev/null +++ b/crates/pcap/tests/regression_pcapng_framing.rs @@ -0,0 +1,80 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::summarize; +use support::{block, pcapng, sample_frames}; + +#[test] +fn mismatched_block_footers_stop_the_capture_with_a_warning() { + let original = pcapng(&sample_frames()); + for footer in [24, 56] { + let mut data = original.clone(); + data[footer..footer + 4].copy_from_slice(&12u32.to_le_bytes()); + let result = summarize(&data, &|| false).unwrap(); + assert!(!result.warnings.is_empty(), "footer at {footer}"); + assert_eq!(result.packets, 0); + } +} + +#[test] +fn fixed_block_headers_cannot_borrow_the_next_blocks_bytes() { + let header = pcapng(&[]); + for (kind, short_body) in [(1, vec![]), (2, vec![0; 16]), (6, vec![0; 16]), (3, vec![])] { + let mut data = header[..28].to_vec(); + if kind != 1 { + data.extend(&header[28..]); + } + data.extend(block(kind, &short_body)); + data.extend(&pcapng(&sample_frames())[28..]); + let result = summarize(&data, &|| false).unwrap(); + assert!(!result.warnings.is_empty(), "kind {kind}"); + assert_eq!(result.packets, 0, "kind {kind}"); + assert_eq!(result.interfaces.len(), usize::from(kind != 1), "kind {kind}"); + } +} + +#[test] +fn valid_blocks_and_unknown_blocks_still_work() { + let original = pcapng(&sample_frames()); + let mut data = original[..60].to_vec(); + data.extend(block(0x0000_1234, b"ignored")); + data.extend(&original[60..]); + let result = summarize(&data, &|| false).unwrap(); + assert_eq!(result.packets, 7); + assert!(result.warnings.is_empty()); + assert_eq!(result.interfaces.len(), 1); +} + +#[test] +fn big_endian_block_footers_use_the_sections_byte_order() { + let be_block = |kind: u32, body: &[u8]| { + let size = (body.len() + 12) as u32; + let mut out = kind.to_be_bytes().to_vec(); + out.extend(size.to_be_bytes()); + out.extend(body); + out.extend(size.to_be_bytes()); + out + }; + let mut section = 0x1a2b3c4du32.to_be_bytes().to_vec(); + section.extend([0, 1, 0, 0]); + section.extend((-1i64).to_be_bytes()); + let mut data = be_block(0x0a0d0d0a, §ion); + data.extend(be_block(1, &[0, 1, 0, 0, 0, 0, 0, 0])); + let result = summarize(&data, &|| false).unwrap(); + assert!(result.warnings.is_empty()); + assert_eq!(result.interfaces[0].link_type, 1); + let end = data.len(); + data[end - 4..].copy_from_slice(&20u32.to_le_bytes()); + assert!(!summarize(&data, &|| false).unwrap().warnings.is_empty()); +} + +#[test] +fn a_skipped_packet_before_the_first_interface_preserves_later_frames() { + let original = pcapng(&sample_frames()); + let mut data = original[..28].to_vec(); + data.extend(block(3, &[0; 4])); + data.extend(&original[28..]); + let summary = summarize(&data, &|| false).unwrap(); + assert_eq!(summary.packets, 7); + assert!(summary.warnings.iter().any(|w| w.contains("undeclared interface"))); +} diff --git a/crates/pcap/tests/regression_tcp_dns_framing.rs b/crates/pcap/tests/regression_tcp_dns_framing.rs new file mode 100644 index 0000000000..e85c987aa4 --- /dev/null +++ b/crates/pcap/tests/regression_tcp_dns_framing.rs @@ -0,0 +1,70 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Decoded, decode}; +use support::{dns_query, dns_response, ipv4_pkt, tcp}; + +fn decoded(payload: &[u8]) -> Decoded { + decode(101, &ipv4_pkt(6, [192, 0, 2, 1], [192, 0, 2, 2], &tcp(53, 51000, 0x18, payload))) +} + +fn framed(message: &[u8], declared: usize) -> Vec { + let mut payload = (declared as u16).to_be_bytes().to_vec(); + payload.extend(message); + payload +} + +#[test] +fn an_unfinished_dns_message_is_not_reported_complete() { + let message = dns_response(); + let result = decoded(&framed(&message, message.len() + 1)); + assert!(result.dns.is_none()); + assert!(result.note.is_some()); + assert_eq!(result.transport.unwrap().src_port, Some(53)); +} + +#[test] +fn dns_records_cannot_borrow_bytes_past_the_message_length() { + let result = decoded(&framed(&dns_response(), 12)); + let dns = result.dns.unwrap(); + assert!(dns.questions.is_empty() && dns.answers.is_empty()); + assert!(dns.incomplete); +} + +#[test] +fn a_length_smaller_than_the_dns_header_is_rejected() { + for length in 0..12 { + let result = decoded(&framed(&dns_response(), length)); + assert!(result.dns.is_none(), "length {length}"); + assert!(result.note.is_some(), "length {length}"); + } +} + +#[test] +fn a_partial_dns_length_prefix_is_reported() { + let result = decoded(&[0]); + assert!(result.dns.is_none()); + assert!(result.note.is_some()); +} + +#[test] +fn an_empty_tcp_ack_does_not_claim_a_missing_dns_message() { + let result = decoded(&[]); + assert!(result.dns.is_none()); + assert!(result.note.is_none()); + assert_eq!(result.transport.unwrap().payload_len, 0); +} + +#[test] +fn the_first_complete_dns_message_is_decoded_without_the_next_one() { + let first = dns_query(); + let second = dns_response(); + let mut payload = framed(&first, first.len()); + payload.extend(framed(&second, second.len())); + let result = decoded(&payload); + let dns = result.dns.unwrap(); + assert!(!dns.response && !dns.incomplete); + assert_eq!(dns.questions[0].name, "example.com"); + assert!(dns.answers.is_empty()); + assert!(result.note.is_none()); +} diff --git a/crates/pcap/tests/regression_tcp_header_length.rs b/crates/pcap/tests/regression_tcp_header_length.rs new file mode 100644 index 0000000000..d931f97b26 --- /dev/null +++ b/crates/pcap/tests/regression_tcp_header_length.rs @@ -0,0 +1,55 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Decoded, decode}; +use support::{ipv4_pkt, tcp}; + +fn decoded(segment: &[u8]) -> Decoded { + decode(101, &ipv4_pkt(6, [192, 0, 2, 1], [192, 0, 2, 2], segment)) +} + +#[test] +fn a_tcp_header_shorter_than_twenty_bytes_is_not_payload() { + for words in 0..5u8 { + let mut segment = tcp(51000, 80, 0x18, b"GET / HTTP/1.1\r\n\r\n"); + segment[12] = words << 4; + let result = decoded(&segment); + let transport = result.transport.unwrap(); + assert_eq!(transport.payload_len, 0, "offset {words}"); + assert_eq!((transport.src_port, transport.dst_port), (Some(51000), Some(80))); + assert!(result.http.is_none() && result.tls.is_none()); + assert!(result.note.is_some()); + } +} + +#[test] +fn a_cut_tcp_header_keeps_ports_but_reports_the_cut() { + let whole = tcp(51000, 80, 0x18, b"request"); + for end in 4..20 { + let result = decoded(&whole[..end]); + let transport = result.transport.unwrap(); + assert_eq!((transport.src_port, transport.dst_port), (Some(51000), Some(80))); + assert_eq!(transport.payload_len, 0); + assert!(result.note.is_some(), "cut at {end}"); + } + for words in 6..=15u8 { + let mut segment = tcp(51000, 80, 0x18, &[]); + segment[12] = words << 4; + let result = decoded(&segment); + assert_eq!(result.transport.unwrap().payload_len, 0); + assert!(result.note.is_some(), "missing options for offset {words}"); + } +} + +#[test] +fn a_valid_tcp_header_with_options_finds_its_payload() { + let mut segment = tcp(51000, 80, 0x18, &[]); + segment[12] = 7 << 4; + segment.extend([1; 8]); + let payload = b"GET /resource HTTP/1.1\r\nHost: example.test\r\n\r\n"; + segment.extend(payload); + let result = decoded(&segment); + assert_eq!(result.transport.unwrap().payload_len, payload.len()); + assert_eq!(result.http.unwrap().target.as_deref(), Some("/resource")); + assert!(result.note.is_none()); +} diff --git a/crates/pcap/tests/regression_tls_bounds.rs b/crates/pcap/tests/regression_tls_bounds.rs new file mode 100644 index 0000000000..92a710fc43 --- /dev/null +++ b/crates/pcap/tests/regression_tls_bounds.rs @@ -0,0 +1,176 @@ +#[path = "support/mod.rs"] +mod support; + +use craft_pcap::{Decoded, decode}; +use support::{client_hello, ipv4_pkt, tcp}; + +fn decoded(record: &[u8]) -> Decoded { + decode(101, &ipv4_pkt(6, [192, 0, 2, 1], [192, 0, 2, 2], &tcp(51000, 443, 0x18, record))) +} + +fn assert_no_complete_sni(record: &[u8]) { + let result = decoded(record); + assert!(result.protocols.contains(&"tls")); + assert!(result.tls.is_none_or(|hello| hello.sni.is_none() && hello.partial)); +} + +#[test] +fn a_client_hello_cannot_read_past_its_tls_record() { + let mut record = client_hello("example.test"); + record[3..5].copy_from_slice(&4u16.to_be_bytes()); + assert_no_complete_sni(&record); +} + +#[test] +fn a_client_hello_cannot_read_past_its_handshake() { + let mut record = client_hello("example.test"); + record[6..9].copy_from_slice(&[0, 0, 34]); + assert_no_complete_sni(&record); +} + +#[test] +fn extensions_cannot_read_past_the_declared_extension_list() { + let mut record = client_hello("example.test"); + record[50..52].copy_from_slice(&4u16.to_be_bytes()); + assert_no_complete_sni(&record); +} + +#[test] +fn a_truncated_record_reports_partial_even_when_the_hello_fields_fit() { + let mut record = client_hello("example.test"); + let larger = (record.len() + 20) as u16; + record[3..5].copy_from_slice(&larger.to_be_bytes()); + assert!(decoded(&record).tls.unwrap().partial); +} + +#[test] +fn server_names_stay_inside_the_name_list() { + let mut record = client_hello("example.test"); + record[56..58].copy_from_slice(&3u16.to_be_bytes()); + assert_no_complete_sni(&record); +} + +#[test] +fn alpn_names_stay_inside_the_protocol_list() { + let mut record = client_hello("example.test"); + let alpn_list = 52 + 4 + 5 + "example.test".len() + 4; + record[alpn_list..alpn_list + 2].copy_from_slice(&3u16.to_be_bytes()); + let hello = decoded(&record).tls.unwrap(); + assert_eq!(hello.alpn, ["h2"]); + assert!(hello.partial); +} + +#[test] +fn supported_versions_stay_inside_the_version_list() { + let mut record = client_hello("example.test"); + let versions = 52 + 4 + 5 + "example.test".len() + 4 + 14 + 4; + record[versions] = 2; + let hello = decoded(&record).tls.unwrap(); + assert_eq!(hello.supported_versions, ["TLS 1.3"]); + assert!(hello.partial); +} + +#[test] +fn a_complete_legacy_hello_can_omit_extensions() { + let mut record = client_hello("example.test"); + record.truncate(50); + record[3..5].copy_from_slice(&45u16.to_be_bytes()); + record[6..9].copy_from_slice(&[0, 0, 41]); + record[46..48].copy_from_slice(&0x002fu16.to_be_bytes()); + let hello = decoded(&record).tls.unwrap(); + assert!(hello.sni.is_none() && hello.alpn.is_empty() && hello.supported_versions.is_empty()); + assert!(!hello.partial); +} + +#[test] +fn a_following_handshake_does_not_extend_the_first_hello() { + let mut record = client_hello("example.test"); + record.extend([14, 0, 0, 0]); + let record_len = (record.len() - 5) as u16; + record[3..5].copy_from_slice(&record_len.to_be_bytes()); + let hello = decoded(&record).tls.unwrap(); + assert_eq!(hello.sni.as_deref(), Some("example.test")); + assert_eq!(hello.alpn, ["h2", "http/1.1"]); + assert!(!hello.partial); +} + +#[test] +fn complete_hello_metadata_is_unchanged() { + let record = client_hello("example.test"); + let hello = decoded(&record).tls.unwrap(); + assert_eq!(hello.sni.as_deref(), Some("example.test")); + assert_eq!(hello.alpn, ["h2", "http/1.1"]); + assert_eq!(hello.supported_versions, ["TLS 1.3", "TLS 1.2"]); + assert!(!hello.partial); +} + +fn hello_with_vectors(session: &[u8], suites: &[u8], compression: &[u8], extensions: &[(u16, &[u8])]) -> craft_pcap::TlsHello { + let mut record = client_hello("unused.test"); + record.truncate(43); + record.push(session.len() as u8); + record.extend(session); + record.extend((suites.len() as u16).to_be_bytes()); + record.extend(suites); + record.push(compression.len() as u8); + record.extend(compression); + let mut ext = Vec::new(); + for (kind, bytes) in extensions { + ext.extend(kind.to_be_bytes()); + ext.extend((bytes.len() as u16).to_be_bytes()); + ext.extend(*bytes); + } + record.extend((ext.len() as u16).to_be_bytes()); + record.extend(ext); + let len = record.len(); + record[3..5].copy_from_slice(&((len - 5) as u16).to_be_bytes()); + record[6..9].copy_from_slice(&((len - 9) as u32).to_be_bytes()[1..]); + decoded(&record).tls.unwrap() +} + +#[test] +fn hello_vectors_must_have_protocol_lengths() { + assert!(!hello_with_vectors(&[0; 32], &[0, 47], &[0], &[]).partial); + assert!(hello_with_vectors(&[0; 33], &[0, 47], &[0], &[]).partial); + for suites in [&[][..], &[0, 47, 0][..]] { + assert!(hello_with_vectors(&[], suites, &[0], &[]).partial); + } + assert!(hello_with_vectors(&[], &[0, 47], &[], &[]).partial); + for (kind, empty) in [(0, &[0, 0][..]), (16, &[0, 0][..]), (43, &[0][..])] { + assert!(hello_with_vectors(&[], &[0, 47], &[0], &[(kind, empty)]).partial); + } +} + +#[test] +fn only_registered_grease_patterns_are_removed() { + let hello = hello_with_vectors(&[], &[0, 47], &[0], &[(43, &[6, 0x1a, 0x2a, 0x4a, 0x4a, 3, 4])]); + assert!(!hello.partial); + assert_eq!(hello.supported_versions, ["0x1a2a", "TLS 1.3"]); +} + +#[test] +fn duplicate_extensions_and_repeated_host_names_are_incomplete() { + let hello = hello_with_vectors(&[], &[0, 47], &[0], &[(43, &[2, 3, 4]), (43, &[2, 3, 3])]); + assert!(hello.partial); + assert_eq!(hello.supported_versions, ["TLS 1.3"]); + let hello = hello_with_vectors(&[], &[0, 47], &[0], &[(0, &[0, 8, 0, 0, 1, b'a', 0, 0, 1, b'b'])]); + assert!(hello.partial); + assert_eq!(hello.sni.as_deref(), Some("a")); +} + +#[test] +fn the_alpn_display_limit_does_not_hide_a_damaged_tail() { + let mut protocols = vec![0, 33]; + for _ in 0..16 { + protocols.extend([1, b'x']); + } + protocols.push(3); + let hello = hello_with_vectors(&[], &[0, 47], &[0], &[(16, &protocols)]); + assert_eq!(hello.alpn.len(), 16); + assert!(hello.partial); + protocols[1] = 34; + protocols.pop(); + protocols.extend([1, b'y']); + let hello = hello_with_vectors(&[], &[0, 47], &[0], &[(16, &protocols)]); + assert_eq!(hello.alpn.len(), 16); + assert!(!hello.partial); +} diff --git a/crates/pcap/tests/support/mod.rs b/crates/pcap/tests/support/mod.rs new file mode 100644 index 0000000000..708864c837 --- /dev/null +++ b/crates/pcap/tests/support/mod.rs @@ -0,0 +1,173 @@ +#![allow(dead_code)] +//! Packet-capture fixtures: hand-built Ethernet/IPv4 frames (DNS, TCP handshake, TLS +//! ClientHello, HTTP request, ARP) written as classic pcap or pcapng. + +const CLASSIC_US: u32 = 0xa1b2_c3d4; +const NG_SHB: u32 = 0x0a0d_0d0a; +const NG_BOM: u32 = 0x1a2b_3c4d; + +pub fn eth(ethertype: u16, payload: &[u8]) -> Vec { + let mut f = vec![0xaa; 6]; + f.extend([0xbb; 6]); + f.extend(ethertype.to_be_bytes()); + f.extend(payload); + f +} + +pub fn ipv4_pkt(proto: u8, src: [u8; 4], dst: [u8; 4], payload: &[u8]) -> Vec { + let mut p = vec![0x45, 0, 0, 0, 0, 1, 0, 0, 64, proto, 0, 0]; + p.extend(src); + p.extend(dst); + let total = (20 + payload.len()) as u16; + p[2..4].copy_from_slice(&total.to_be_bytes()); + p.extend(payload); + p +} + +pub fn udp(sp: u16, dp: u16, payload: &[u8]) -> Vec { + let mut u = sp.to_be_bytes().to_vec(); + u.extend(dp.to_be_bytes()); + u.extend(((8 + payload.len()) as u16).to_be_bytes()); + u.extend([0, 0]); + u.extend(payload); + u +} + +pub fn tcp(sp: u16, dp: u16, flags: u8, payload: &[u8]) -> Vec { + let mut t = sp.to_be_bytes().to_vec(); + t.extend(dp.to_be_bytes()); + t.extend(1000u32.to_be_bytes()); + t.extend(0u32.to_be_bytes()); + t.extend([0x50, flags, 0xff, 0xff, 0, 0, 0, 0]); + t.extend(payload); + t +} + +/// DNS response for example.com A 93.184.216.34 (name compressed in the answer). +pub fn dns_response() -> Vec { + let mut m = vec![0x12, 0x34, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0]; + m.extend(b"\x07example\x03com\x00\x00\x01\x00\x01"); + m.extend([0xc0, 12, 0, 1, 0, 1, 0, 0, 0x0e, 0x10, 0, 4, 93, 184, 216, 34]); + m +} + +pub fn dns_query() -> Vec { + let mut m = vec![0x12, 0x34, 0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0]; + m.extend(b"\x07example\x03com\x00\x00\x01\x00\x01"); + m +} + +/// A TLS 1.3-style ClientHello naming `host` with ALPN h2 and http/1.1. +pub fn client_hello(host: &str) -> Vec { + let mut ext = Vec::new(); + let mut sni = vec![0u8]; + sni.extend((host.len() as u16).to_be_bytes()); + sni.extend(host.as_bytes()); + let mut sni_list = (sni.len() as u16).to_be_bytes().to_vec(); + sni_list.extend(sni); + ext.extend(0u16.to_be_bytes()); + ext.extend((sni_list.len() as u16).to_be_bytes()); + ext.extend(sni_list); + let alpn_list = b"\x02h2\x08http/1.1"; + ext.extend(16u16.to_be_bytes()); + ext.extend(((alpn_list.len() + 2) as u16).to_be_bytes()); + ext.extend((alpn_list.len() as u16).to_be_bytes()); + ext.extend(alpn_list); + ext.extend(43u16.to_be_bytes()); + ext.extend(5u16.to_be_bytes()); + ext.extend([4, 0x03, 0x04, 0x03, 0x03]); + let mut body = vec![3, 3]; + body.extend([7u8; 32]); + body.push(0); // session id + body.extend([0, 2, 0x13, 0x01]); // one cipher suite + body.extend([1, 0]); // compression + body.extend((ext.len() as u16).to_be_bytes()); + body.extend(ext); + let mut hs = vec![1]; + hs.extend(&(body.len() as u32).to_be_bytes()[1..]); + hs.extend(body); + let mut rec = vec![22, 3, 1]; + rec.extend((hs.len() as u16).to_be_bytes()); + rec.extend(hs); + rec +} + +/// Frames of a small conversation, as (link type 1) Ethernet frames. +pub fn sample_frames() -> Vec> { + let c = [192, 168, 1, 10]; + let dns_srv = [8, 8, 8, 8]; + let web = [93, 184, 216, 34]; + vec![ + eth(0x0800, &ipv4_pkt(17, c, dns_srv, &udp(50000, 53, &dns_query()))), + eth(0x0800, &ipv4_pkt(17, dns_srv, c, &udp(53, 50000, &dns_response()))), + eth(0x0800, &ipv4_pkt(6, c, web, &tcp(50001, 443, 0x02, &[]))), + eth(0x0800, &ipv4_pkt(6, web, c, &tcp(443, 50001, 0x12, &[]))), + eth(0x0800, &ipv4_pkt(6, c, web, &tcp(50001, 443, 0x18, &client_hello("example.com")))), + eth( + 0x0800, + &ipv4_pkt( + 6, + c, + web, + &tcp(50002, 80, 0x18, b"GET http://user:pw@example.com/a?b=1 HTTP/1.1\r\nHost: example.com\r\nUser-Agent: t\r\n\r\n"), + ), + ), + eth(0x0806, &[0u8; 28]), + ] +} + +/// A classic little-endian microsecond pcap of `frames`. +pub fn pcap(frames: &[Vec]) -> Vec { + let mut out = CLASSIC_US.to_le_bytes().to_vec(); + out.extend(2u16.to_le_bytes()); + out.extend(4u16.to_le_bytes()); + out.extend([0u8; 8]); + out.extend(65535u32.to_le_bytes()); + out.extend(1u32.to_le_bytes()); + for (i, f) in frames.iter().enumerate() { + out.extend((1_700_000_000u32 + i as u32).to_le_bytes()); + out.extend(500u32.to_le_bytes()); + out.extend((f.len() as u32).to_le_bytes()); + out.extend((f.len() as u32).to_le_bytes()); + out.extend(f); + } + out +} + +pub fn block(t: u32, body: &[u8]) -> Vec { + let mut body = body.to_vec(); + while !body.len().is_multiple_of(4) { + body.push(0); + } + let len = (body.len() + 12) as u32; + let mut b = t.to_le_bytes().to_vec(); + b.extend(len.to_le_bytes()); + b.extend(body); + b.extend(len.to_le_bytes()); + b +} + +/// A little-endian pcapng with one Ethernet interface at nanosecond resolution. +pub fn pcapng(frames: &[Vec]) -> Vec { + let mut shb = NG_BOM.to_le_bytes().to_vec(); + shb.extend(1u16.to_le_bytes()); + shb.extend(0u16.to_le_bytes()); + shb.extend((-1i64).to_le_bytes()); + let mut out = block(NG_SHB, &shb); + let mut idb = 1u16.to_le_bytes().to_vec(); + idb.extend([0, 0]); + idb.extend(0u32.to_le_bytes()); + idb.extend([9, 0, 1, 0, 9, 0, 0, 0, 0, 0, 0, 0]); // if_tsresol = 9, end of options + out.extend(block(1, &idb)); + for (i, f) in frames.iter().enumerate() { + let ts: u64 = 1_700_000_000_000_000_000 + i as u64; + let mut epb = 0u32.to_le_bytes().to_vec(); + epb.extend(((ts >> 32) as u32).to_le_bytes()); + epb.extend((ts as u32).to_le_bytes()); + epb.extend((f.len() as u32).to_le_bytes()); + epb.extend((f.len() as u32).to_le_bytes()); + epb.extend(f); + out.extend(block(6, &epb)); + } + out +} diff --git a/crates/pkcs7/src/revocation.rs b/crates/pkcs7/src/revocation.rs index 0aa9be9c6f..91d69730a4 100644 --- a/crates/pkcs7/src/revocation.rs +++ b/crates/pkcs7/src/revocation.rs @@ -63,6 +63,27 @@ pub struct CertificateList { pub revoked: Vec<(Vec, Time)>, } +/// Owned parsed components for adapters. This is not a signature or trust verdict. +/// Consuming conversion moves buffers without reparsing or cloning signed material. +pub struct CertificateListParts { + pub tbs: Vec, + pub sig_alg: Vec, + pub signature: Vec, + pub issuer_raw: Vec, + pub this_update: Time, + pub next_update: Option
"); + assert!(Document::parse(&accepted).is_ok()); + let rejected = format!("{xml} xmlns:extra='extra'/>
"); + assert!(Document::parse(&rejected).is_err()); + } + + #[test] + fn malformed_dtd_and_resource_limits_are_preserved() { + // Current shared XML rejects duplicate attributes, unlike the older app pin. + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse("").is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: true, nodes_limit: 8 }).is_ok()); + assert!(Document::parse_with_options("text", ParsingOptions { allow_dtd: false, nodes_limit: 1 }).is_err()); + assert!(Document::parse_with_options("", ParsingOptions { allow_dtd: false, nodes_limit: 0 }).is_err()); + let text = format!("{}{}", "".repeat(1025), "".repeat(1025)); + assert!(Document::parse(&text).is_err()); + assert!(Document::parse("").is_err()); + } +} diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml new file mode 100644 index 0000000000..9b1304d899 --- /dev/null +++ b/crates/xfdf/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-xfdf" +description = "Bounded XFDF field-value reader without PDF or form policy" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +craft-xml = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/xfdf/README.md b/crates/xfdf/README.md new file mode 100644 index 0000000000..ce8c2802e0 --- /dev/null +++ b/crates/xfdf/README.md @@ -0,0 +1,11 @@ +# craft-xfdf + +Scoped XFDF field-value reader extracted from PDFCraft #5937 refresh cb564fd82. Does not read FDF/PDF, parse annotations or apply field values. PDF application, permissions, calculations and password filtering stay caller-owned. + +Preserves local-name matching, duplicate field order, dotted names, empty leaf clearing and ignored rich-text-only fields, direct split text concatenation and source UTF-8 replacement policy. XML depth1024, field depth64,2million nodes and64MiB charged expanded names/text. Names and values are charged before copying; temporary parents and emitted name copies both count. XML input/tree memory remains governed by craft-xml defaults, not this output budget alone. + +Current strict craft-xml also rejects duplicate raw/expanded attributes and more than1024 active inherited namespace declarations; older app XML accepted those. These deliberate tighter admissions must be disclosed by consumers. No complete XFDF or corpus parity claim. + +Source history remains in PDFCraft. Shared move and preallocation budget reconciliation by Dylan M. Taylor, MIT OR Apache-2.0. No assets are imported. + +Retained source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs new file mode 100644 index 0000000000..0023761067 --- /dev/null +++ b/crates/xfdf/src/lib.rs @@ -0,0 +1,177 @@ +//! Bounded XFDF field values; PDF annotations and form application remain caller-owned. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +const MAX_NODES: u32 = 2_000_000; +const MAX_DEPTH: usize = 64; +const MAX_XML_DEPTH: usize = 1024; +const MAX_XFDF_TEXT: usize = 64 << 20; +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + #[error("this file isn't XFDF, FDF, XML or text form data")] + UnknownFormat, + #[error("the file can't be read: {0}")] + Malformed(String), +} +/// Read field names and values in file order. This does not apply values to a PDF. +/// UTF-8 replacement and leading BOM/space handling retain the source app policy. +pub fn read_fields(bytes: &[u8]) -> Result)>, Error> { + let text = String::from_utf8_lossy(bytes); + let text = text.trim_start_matches('\u{feff}').trim_start(); + check_form_xml_depth(text)?; + let root = parse_form_xml(text).map_err(|_| Error::UnknownFormat)?; + if root.local() != "xfdf" { + return Err(Error::UnknownFormat); + } + let mut values = Vec::new(); + if let Some(fields) = root.child(craft_xml::Local("fields")) { + walk_xfdf(fields, "", &mut values, 0, &mut 0)?; + } + Ok(values) +} +fn xml_nesting_depth(text: &str) -> usize { + fn find(hay: &[u8], from: usize, needle: &[u8]) -> Option { + (from..hay.len()).find(|&p| hay[p..].starts_with(needle)) + } + let b = text.as_bytes(); + let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize); + while i < b.len() { + if b[i] != b'<' { + i += 1; + } else if b[i..].starts_with(b"").map_or(b.len(), |p| p + 3); + } else if b[i..].starts_with(b"").map_or(b.len(), |p| p + 3); + } else if b[i..].starts_with(b"").map_or(b.len(), |p| p + 2); + } else if b[i..].starts_with(b"").map_or(b.len(), |p| p + 1); + } else if b[i..].starts_with(b"").map_or(b.len(), |p| p + 1); + } else { + depth += 1; + max = max.max(depth); + // Skip the rest of the start tag, over any quoted attribute value, and remember its last + // significant byte: a tag that ends in `/` closes itself, so it is one level deep while it + // is read rather than a level left open. + i += 1; + let mut quote = 0u8; + let mut last = 0u8; + while i < b.len() { + let c = b[i]; + if quote != 0 { + if c == quote { + quote = 0; + } + } else if c == b'"' || c == b'\'' { + quote = c; + } else if c == b'>' { + i += 1; + break; + } else if !c.is_ascii_whitespace() { + last = c; + } + i += 1; + } + if last == b'/' { + depth -= 1; + } + } + } + max +} + +fn check_form_xml_depth(text: &str) -> Result<(), Error> { + let depth = xml_nesting_depth(text); + if depth > MAX_XML_DEPTH { + return Err(Error::Malformed(format!("the file nests XML elements {depth} deep, past the {MAX_XML_DEPTH} the reader accepts"))); + } + Ok(()) +} + +fn parse_form_xml(text: &str) -> Result { + let mut opts = craft_xml::Options { strict: true, doctype: craft_xml::Doctype::Reject, ..Default::default() }; + opts.limits.max_nodes = MAX_NODES as usize; + opts.limits.max_depth = MAX_XML_DEPTH.max(1024); + opts.parse(text.as_bytes()) +} + +fn el_text(el: &craft_xml::El) -> String { + el.children + .iter() + .filter_map(|n| match n { + craft_xml::Node::Text(t) => Some(t.as_str()), + _ => None, + }) + .collect() +} + +fn walk_xfdf(node: &craft_xml::El, prefix: &str, out: &mut Vec<(String, Vec)>, depth: usize, bytes: &mut usize) -> Result<(), Error> { + if depth > MAX_DEPTH { + return Err(Error::Malformed(format!("XFDF fields nest more than {MAX_DEPTH} deep"))); + } + for f in node.children(craft_xml::Local("field")) { + let Some(name) = f.attr("name") else { continue }; + // Charge temporary parent names too, before allocation/recursion can amplify them. + let full_len = if prefix.is_empty() { name.len() } else { prefix.len().saturating_add(1).saturating_add(name.len()) }; + charge_xfdf_text(bytes, full_len)?; + let full = if prefix.is_empty() { name.to_string() } else { format!("{prefix}.{name}") }; + let mut vals = Vec::new(); + for value in f.children(craft_xml::Local("value")) { + let len = value + .children + .iter() + .filter_map(|n| match n { + craft_xml::Node::Text(t) => Some(t.len()), + _ => None, + }) + .fold(0, usize::saturating_add); + charge_xfdf_text(bytes, len)?; + vals.push(el_text(value)); + } + // A leaf with no `` is an empty field (the export writes one that way), so it + // clears the field like FDF's `/V ()`; a field with kids only names their parent. A + // leaf holding only `` is not read yet, so it leaves the field alone. + let names_kids_or_rich = f.elements().any(|c| matches!(c.local(), "field" | "value-richtext")); + if !vals.is_empty() || !names_kids_or_rich { + charge_xfdf_text(bytes, full.len())?; // The emitted name is a second owned copy. + out.push((full.clone(), vals)); + } + walk_xfdf(f, &full, out, depth + 1, bytes)?; + } + Ok(()) +} + +fn charge_xfdf_text(bytes: &mut usize, amount: usize) -> Result<(), Error> { + *bytes = bytes.saturating_add(amount); + if *bytes > MAX_XFDF_TEXT { + return Err(Error::Malformed(format!("the file expands to more than {} MiB of field names and values", MAX_XFDF_TEXT >> 20))); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn field_order_empty_rich_and_split_values() { + let xml = b"abcskiplast"; + assert_eq!( + read_fields(xml).unwrap(), + vec![("parent.child".into(), vec!["ab".into(), "c".into()]), ("empty".into(), vec![]), ("parent.child".into(), vec!["last".into()])] + ); + } + #[test] + fn bounds_and_strict_xml_hardening() { + assert_eq!(read_fields(b""), Err(Error::UnknownFormat)); + assert!(read_fields(b"").is_err()); + assert!(read_fields(b"").is_err()); + let text = format!("{}{}{}", "".repeat(65), "x", "".repeat(65)); + assert!(read_fields(text.as_bytes()).is_err()); + let fields = parse_form_xml("").unwrap(); + let mut out = Vec::new(); + assert!(walk_xfdf(&fields, "", &mut out, 0, &mut (MAX_XFDF_TEXT - 5)).is_err()); + assert!(out.is_empty()); + walk_xfdf(&fields, "", &mut out, 0, &mut (MAX_XFDF_TEXT - 6)).unwrap(); + } +} diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index fbcb3ecc2b..f89ec10fea 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -279,6 +279,7 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { // it from an empty EOCD-shaped record inside the preceding archive's comment. Keep it as a // last resort while searching for an older, structurally stronger candidate. let mut empty_sfx = None; + let mut measured_directory = None; let mut fallback = None; // Fake EOCD records in a comment can all describe the same large directory. Cache binary // directory jumps so checking each candidate does not rescan every entry. @@ -318,6 +319,21 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate) .filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps)) else { + // An overstated size is safe to ignore only when the recorded entries fill + // the byte range from the declared offset to this single-disk end record. + // The classic entry count is below MAX_ENTRIES, so the walk checks every entry. + if count != 0 + && u32_at(data, candidate + 4) == Some(0) + && u16_at(data, candidate + 8) == Some(count) + && let Ok(start) = usize::try_from(offset) + && let Some(measured) = candidate.checked_sub(start).and_then(|n| u32::try_from(n).ok()) + && measured < size + && directory_is_exact(data, start, measured.into(), count.into(), &mut directory_jumps) + { + // Keep scanning for a valid declared size. Among measured candidates, + // prefer the earliest record so a copy in its comment cannot hide it. + measured_directory = Some((count.into(), measured.into(), offset.into(), candidate)); + } continue; }; if count == 0 && shift > 0 { @@ -328,7 +344,13 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { eocd = Some(candidate); break; } - let eocd = eocd.or(empty_sfx).or(fallback).ok_or(ZipError::NotZip)?; + let eocd = eocd.or(empty_sfx); + if eocd.is_none() + && let Some(directory) = measured_directory + { + return Ok(directory); + } + let eocd = eocd.or(fallback).ok_or(ZipError::NotZip)?; let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 5ae0713ba0..6075e4e57f 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -108,6 +108,23 @@ fn damaged_archives_are_errors() { assert!(Archive::open(&z).is_err()); } +#[test] +fn reads_a_directory_with_an_overstated_size() { + let mut z = zip(&[("DOMDocument.xml", b"", true), ("LIBRARY/ball.xml", b"", false)]); + let end = z.len() - 22; + let size = u32_at(&z, end + 12).unwrap(); + z[end + 12..end + 16].copy_from_slice(&(size + 13).to_le_bytes()); + + let archive = Archive::open(&z).unwrap(); + assert_eq!(archive.counts().0, 2); + assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b""); + assert_eq!(archive.read("LIBRARY/ball.xml").unwrap().unwrap(), b""); + + // Keep the overstated end record but remove the last byte of the final entry's name. + z.remove(end - 1); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory is outside the archive"))); +} + #[test] fn a_truncated_central_directory_is_damaged() { let z = zip(&[("DOMDocument.xml", b"", true), ("b.xml", b"", true), ("c.xml", b"", false)]); @@ -306,6 +323,32 @@ fn nonempty_comment_eocd_candidate_does_not_mask_valid_archive() { assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); } +#[test] +fn overstated_comment_eocd_does_not_mask_valid_archive() { + let mut bytes = zip(&[("a.xml", b"x", false)]); + let end = bytes.len() - 22; + let size = u32_at(&bytes, end + 12).unwrap(); + let start = u32_at(&bytes, end + 16).unwrap() as usize; + let fake_start = bytes.len(); + + // Copy the directory and end record into the real comment, then corrupt the copies. + bytes.extend_from_within(start..); + let comment_len = u16::try_from(bytes.len() - fake_start).unwrap(); + bytes[end + 20..end + 22].copy_from_slice(&comment_len.to_le_bytes()); + bytes[fake_start + 42..fake_start + 46].copy_from_slice(&1u32.to_le_bytes()); + let fake_end = bytes.len() - 22; + bytes[fake_end + 12..fake_end + 16].copy_from_slice(&(size + 1).to_le_bytes()); + bytes[fake_end + 16..fake_end + 20].copy_from_slice(&u32::try_from(fake_start).unwrap().to_le_bytes()); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); + + // If both candidates need recovery, the record before the comment still wins. + bytes[end + 12..end + 16].copy_from_slice(&(size + 1).to_le_bytes()); + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + #[test] fn repeated_eocd_directory_candidates_reuse_entry_validation() { let entries = (0..1024).map(|index| Raw::new(&format!("entry-{index:04}.xml"), b"", false)).collect::>(); diff --git a/crates/zip/Cargo.toml b/crates/zip/Cargo.toml index 89cb2d1a73..cfdb333b40 100644 --- a/crates/zip/Cargo.toml +++ b/crates/zip/Cargo.toml @@ -35,7 +35,7 @@ lenient = ["dep:miniz_oxide"] lenient-bzip2 = ["lenient", "dep:bzip2-rs"] # Methods 14 (ZIP LZMA) and 95 (XZ). lenient-lzma = ["lenient", "dep:lzma-rs"] -# Method 93. +# Zstandard methods 20 (legacy) and 93. lenient-zstd = ["lenient", "dep:ruzstd"] serde = ["dep:serde"] diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 49da63585e..b9b3b3d802 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -108,6 +108,15 @@ impl<'a> Archive<'a> { Ok(Some(file.is_dir())) } + /// Declared decoded and compressed sizes at `index`, without name lookup. + pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + Ok(Some((file.size(), file.compressed_size()))) + } + /// Do two entries share a name? `zip` then keeps one of them, and which one a writer meant /// is not known: a format that must not guess refuses the archive. pub fn has_duplicate_names(&self) -> bool { @@ -178,6 +187,20 @@ impl<'a> Archive<'a> { /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.read_index_named(index, name, max) + } + + /// Read the entry at `index` under the same size, checksum and aggregate budget + /// rules as [`Self::read`], without repeating a decoded-name lookup. + pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); + self.read_index_named(index, &name, max) + } + + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); @@ -213,6 +236,32 @@ impl Archive<'static> { mod ownership_tests { use super::*; + #[test] + fn named_read_preserves_entry_error_for_a_corrupt_local_header() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + let mut bytes = writer.finish().unwrap(); + bytes[0] = 0; // The central directory remains valid; the local signature does not. + let mut archive = Archive::open(&bytes, Limits { max_entries: 1, max_total_bytes: 3 }).unwrap(); + assert!(matches!(archive.read("a", 3), Err(Error::Entry { name, .. }) if name == "a")); + assert_eq!(archive.budget().remaining(), 3); + } + + #[test] + fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + writer.add("b", b"def", crate::Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 2, max_total_bytes: 5 }).unwrap(); + assert!(archive.read_index(0, 2).is_err()); + assert_eq!(archive.read_index(0, 3).unwrap().unwrap(), b"abc"); + assert!(archive.read_index(1, 3).is_err()); + assert_eq!(archive.read_index(2, 3).unwrap(), None); + assert_eq!(archive.entry_sizes(0).unwrap(), Some((3, 3))); + assert_eq!(archive.entry_sizes(2).unwrap(), None); + } + #[test] fn owned_storage_lives_until_last_archive_clone_is_dropped() { let bytes = crate::Writer::new().finish().unwrap(); diff --git a/crates/zip/src/lenient.rs b/crates/zip/src/lenient.rs index c9bed3764d..20da277cdd 100644 --- a/crates/zip/src/lenient.rs +++ b/crates/zip/src/lenient.rs @@ -91,7 +91,7 @@ impl ZipEntry { 9 => "deflate64", 12 => "bzip2", 14 => "lzma", - 93 => "zstd", + 20 | 93 => "zstd", 95 => "xz", 99 => "aes", _ => "other", @@ -463,7 +463,7 @@ pub fn read_entry_unverified(data: &[u8], e: &ZipEntry, max_bytes: u64) -> Resul })?, 12 | 95 => decode_bzip2_or_xz(raw, e, max_bytes)?, 14 => decode_lzma(raw, e, max_bytes)?, - 93 => decode_zstd(raw, e, max_bytes)?, + 20 | 93 => decode_zstd(raw, e, max_bytes)?, m => return Err(ZipError::Unsupported(format!("compression method {m} ({}) for {}", e.method_name(), e.name))), }; if out.len() as u64 != e.uncompressed_size { diff --git a/crates/zip/src/lenient/tests.rs b/crates/zip/src/lenient/tests.rs index c2ca973940..ded7c0ecda 100644 --- a/crates/zip/src/lenient/tests.rs +++ b/crates/zip/src/lenient/tests.rs @@ -391,3 +391,40 @@ fn a_method_left_out_of_the_build_is_unsupported() { data[8..10].copy_from_slice(&93u16.to_le_bytes()); assert!(matches!(read_entry_unverified(&data, &entry, 100), Err(ZipError::Unsupported(m)) if m.contains("not built in"))); } + +// RRFZ, Craft Anything 29badae7: deprecated ZIP method 20 is Zstandard. +#[cfg(feature = "lenient-zstd")] +mod legacy_zstandard { + use crate::lenient as zip; + use crate::lenient::testkit::zip_stored; + + const BODY: &[u8] = b"zstandard payload"; + + /// Build a ZIP with one single-segment Zstandard frame containing a raw final block. + fn sample(method: u16) -> Vec { + let size = BODY.len() as u8; + let mut frame = vec![0x28, 0xb5, 0x2f, 0xfd, 0x20, size, (size << 3) | 1, 0, 0]; + frame.extend_from_slice(BODY); + let mut data = zip_stored(&[("a.txt", &frame)]); + let cd = 30 + "a.txt".len() + frame.len(); + data[8..10].copy_from_slice(&method.to_le_bytes()); + data[14..18].copy_from_slice(&zip::crc32(BODY).to_le_bytes()); + data[22..26].copy_from_slice(&u32::from(size).to_le_bytes()); + data[cd + 10..cd + 12].copy_from_slice(&method.to_le_bytes()); + data[cd + 16..cd + 20].copy_from_slice(&zip::crc32(BODY).to_le_bytes()); + data[cd + 24..cd + 28].copy_from_slice(&u32::from(size).to_le_bytes()); + data + } + + /// The deprecated and current method IDs both decode through the bounded ZIP reader. + #[test] + fn reads_zstandard_members_under_both_method_ids() { + for method in [93, 20] { + let data = sample(method); + let entry = zip::parse(&data, 1).unwrap().entries.remove(0); + assert_eq!(entry.method_name(), "zstd", "method {method}"); + assert_eq!(zip::read_entry(&data, &entry, 100).unwrap(), BODY); + assert!(matches!(zip::read_entry(&data, &entry, 2), Err(zip::ZipError::TooLarge(2)))); + } + } +} diff --git a/docs/full-validation.md b/docs/full-validation.md new file mode 100644 index 0000000000..dfa3d8a757 --- /dev/null +++ b/docs/full-validation.md @@ -0,0 +1,28 @@ +# Full validation + +The fast Workspace workflow intentionally samples hostile-input/proptest cases and primarily +runs all features. It is not evidence of full default-feature runtime or doctest coverage. + +Add the `full-validation` label to a pull request to start the separate Full validation workflow. +Keep it on the pull request so each new push receives full checks. The workflow checks the PR +merge ref using `pull_request`, never `pull_request_target`, and does not inherit secrets. +A workflow dispatch validates the selected repository ref; it is not evidence for another PR SHA. + +Before treating a candidate as fully validated, verify on its current head/merge ref: + +- All three `Full native / gate` checks actually ran and succeeded (Linux, Windows, macOS). +- Both workspace test configurations ran with `cargo test`: default and all features, including + their doctests and Cargo's ordinary example compilation/linking. Both clippy configurations + and formatting checks also pass. No hostile divisor or proptest case override is set. +- All three `Full PDF contracts / gate` checks ran and succeeded, including the Unicode fixture + cfg and the separate read-only-contract manifest. Linux-only generic tests do not replace them. +- The normal MSRV, WASM and applicable specialized workflow checks pass too. This optional + workflow does not replace those checks, Sonar analysis, independent review, or branch rules. + +An unlabelled PR's skipped Full validation jobs are not a full-validation pass. The label is an +opt-in mechanism, not a branch-protection change or a merge authorization. A new base/head may +need a fresh full run. Do not dispatch another copy when the matching run is already active. + +The existing fast path and nightly workflow are left unchanged. This workflow is separate from +platform-selection and lint/cache optimization work in #2113. Its native commands deliberately +retain the repository's `cargo test --workspace` pre-merge requirement. diff --git a/scripts/ci-format-workspace.py b/scripts/ci-format-workspace.py new file mode 100644 index 0000000000..32605af70b --- /dev/null +++ b/scripts/ci-format-workspace.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Check every workspace package separately to bound rustfmt's Windows argv.""" +import json +from pathlib import Path +import re +import subprocess + +ROOT = Path(__file__).resolve().parents[1] + + +def workspace_names(metadata): + members = metadata["workspace_members"] + packages = metadata["packages"] + if not members or len(members) != len(set(members)): + raise ValueError("workspace member inventory is empty or duplicated") + by_id = {package["id"]: package for package in packages} + if len(by_id) != len(packages): + raise ValueError("metadata contains duplicate package IDs") + names = [] + for member in members: + name = by_id[member]["name"] + # Package names are data, never command text or option fragments. + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", name): + raise ValueError("invalid workspace package name") + names.append(name) + if len(names) != len(set(names)): + raise ValueError("workspace package names are ambiguous") + return sorted(names) + + +def check_workspace(): + result = subprocess.run( + ["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"], + cwd=ROOT, check=True, stdout=subprocess.PIPE, text=True, encoding="utf-8", + ) + names = workspace_names(json.loads(result.stdout)) + # From this virtual workspace root, cargo fmt normally checks all workspace packages. + # Keep Cargo responsible for target kinds, editions and rustfmt configuration. + # One package per call retains all its targets without the workspace-sized argv. + print(f"Checking formatting for {len(names)} workspace packages", flush=True) + for name in names: + subprocess.run(["cargo", "fmt", "--check", "--package", name], cwd=ROOT, check=True) + + +if __name__ == "__main__": + check_workspace() diff --git a/scripts/ci-full-validation.sh b/scripts/ci-full-validation.sh new file mode 100644 index 0000000000..3b413ec886 --- /dev/null +++ b/scripts/ci-full-validation.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Restore both runtime feature configurations, docs and ordinary example linking, without fuzz caps. +set -euo pipefail +unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES +if [ "${RUNNER_OS:-}" = Windows ]; then + powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' +fi +# Windows cannot spawn one rustfmt command with every workspace target (#2200). +if [ "${RUNNER_OS:-}" = Windows ]; then + python scripts/ci-format-workspace.py +else + cargo fmt --check +fi +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +# cargo test includes docs and ordinary example linking, as required by AGENTS.md. +cargo test --workspace --locked +cargo test --workspace --all-features --locked diff --git a/scripts/ci-test-inputs.sh b/scripts/ci-test-inputs.sh new file mode 100755 index 0000000000..32af3ea773 --- /dev/null +++ b/scripts/ci-test-inputs.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# The test inputs the Workspace gate and the nightly full run fetch before their tests: the +# PhotoCraft test corpora (PSD, PSD tools, ATN, EXR, HEIF, PngSuite) at a pinned PhotoCraft commit, +# and the licensed PDF test fonts. Exports CRAFT_PSD_CORPUS and CRAFT_PDF_TEST_FONT_DIR through +# $GITHUB_ENV. Run from the repository root. +# +# A corpus already in .test-inputs/photocraft/corpus (restored from the CI cache, which is keyed on +# this file) is used as it is, without the PhotoCraft checkout and its xtask build. +set -euo pipefail + +# The PhotoCraft commit whose `cargo xtask corpus` pins the corpora. Changing it changes this file, +# which starts a new corpus cache entry. +photocraft=74330157cb601573ae4523a95bb9132822fc3918 +fetcher=.test-inputs/photocraft + +if [ -z "$(ls -A "$fetcher/corpus" 2>/dev/null)" ]; then + rm -rf "$fetcher" + mkdir -p "$fetcher" + git -C "$fetcher" init --quiet + git -C "$fetcher" remote add origin https://github.com/storytold/PhotoCraft.git + git -C "$fetcher" fetch --quiet --depth=1 origin "$photocraft" + git -C "$fetcher" checkout --quiet --detach FETCH_HEAD + (cd "$fetcher" && cargo xtask corpus --psd --psd-tools --atn --exr --heif --pngsuite) +fi +mkdir -p corpus +cp -a "$fetcher/corpus/." corpus/ + +python scripts/test-fetch-pdf-test-fonts.py +python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" + +printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$fetcher/corpus" >> "$GITHUB_ENV" +printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" diff --git a/scripts/test-full-validation.py b/scripts/test-full-validation.py new file mode 100644 index 0000000000..b37e979c8e --- /dev/null +++ b/scripts/test-full-validation.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Exercise the full gate's command sequence without building Rust locally.""" +import os +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts/ci-full-validation.sh" +# Actions uses Git Bash on Windows; Python's PATH search can instead select the WSL launcher. +BASH = (str(Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Git/bin/bash.exe") + if sys.platform == "win32" else "bash") +COMMANDS = [ + "fmt --check", + "clippy --workspace --all-targets --locked -- -D warnings", + "clippy --workspace --all-targets --all-features --locked -- -D warnings", + "test --workspace --locked", + "test --workspace --all-features --locked", +] + + +# Validate the real script, but execute only this fixed, reviewed command sequence. +# Repository-file bytes must never become bash -c source in a mock-only harness. +SOURCE = r""" +set -euo pipefail +unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES +if [ "${RUNNER_OS:-}" = Windows ]; then + powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' +fi +if [ "${RUNNER_OS:-}" = Windows ]; then + python scripts/ci-format-workspace.py +else + cargo fmt --check +fi +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +cargo test --workspace --locked +cargo test --workspace --all-features --locked +""" + + +def source_lines(text): + return [line.strip() for line in text.splitlines() + if line.strip() and not line.lstrip().startswith("#")] + + +def run(os_name, fail=""): + if source_lines(SCRIPT.read_text()) != source_lines(SOURCE): + raise AssertionError("full validation command sequence changed") + env = dict(os.environ, RUNNER_OS=os_name, FAIL=fail, + CRAFT_HOSTILE_DIVISOR="8", PROPTEST_CASES="64") + mock = r""" +cargo() { + test -z "${CRAFT_HOSTILE_DIVISOR+x}" && test -z "${PROPTEST_CASES+x}" || return 29 + printf '%s\n' "$*" + if [ "$*" = "$FAIL" ]; then return 17; fi +} +powershell.exe() { printf 'print-queue\n'; } +python() { test "$*" = "scripts/ci-format-workspace.py" || return 31; cargo fmt --check; } +""" + return subprocess.run([BASH, "-c", mock + SOURCE], env=env, + capture_output=True, text=True, check=False) + + +class FullValidation(unittest.TestCase): + def test_changed_source_is_rejected_without_execution(self): + for source in [ + SOURCE + "\necho injected", + SOURCE.replace("cargo fmt --check", "cargo fmt --check; echo injected"), + SOURCE.replace("cargo fmt --check", "cargo fmt $(echo injected) --check"), + SOURCE.replace("cargo test --workspace --locked", ""), + SOURCE + "\ncargo test --workspace --locked", + ]: + with self.subTest(source=source): + with patch.object(Path, "read_text", return_value=source), patch.object(subprocess, "run") as execute: + with self.assertRaises(AssertionError): + run("Linux") + execute.assert_not_called() + + def test_comments_and_blank_lines_do_not_change_commands(self): + with patch.object(Path, "read_text", return_value="# harmless comment\n\n" + SOURCE): + result = run("Linux") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(result.stdout.splitlines(), COMMANDS) + + def test_every_os_runs_both_full_configurations(self): + for name in ["Linux", "macOS", "Windows"]: + with self.subTest(os=name): + p = run(name) + self.assertEqual(p.returncode, 0, p.stdout + p.stderr) + self.assertEqual(p.stdout.splitlines(), + (["print-queue"] if name == "Windows" else []) + COMMANDS) + + def test_every_failure_stops_the_gate(self): + for name in ["Linux", "macOS", "Windows"]: + for i, command in enumerate(COMMANDS): + with self.subTest(os=name, command=command): + p = run(name, command) + self.assertEqual(p.returncode, 17, p.stdout + p.stderr) + self.assertEqual(p.stdout.splitlines(), + (["print-queue"] if name == "Windows" else []) + COMMANDS[:i + 1]) + + def test_workflow_preserves_fork_and_platform_boundaries(self): + text = (ROOT / ".github/workflows/full-validation.yml").read_text() + self.assertIn("os: '[\"ubuntu-latest\",\"windows-latest\",\"macos-latest\"]'", text) + self.assertIn("select-os: '[]'", text) + self.assertIn("contents: read", text) + self.assertNotIn("pull_request_target", text) + self.assertNotIn("secrets:", text) + self.assertIn("bash scripts/ci-full-validation.sh", text) + self.assertIn("github.event.label.name != 'full-validation' && github.run_id", text) + self.assertIn("github.event.action != 'labeled' || github.event.label.name == 'full-validation'", text) + self.assertNotIn("CRAFT_HOSTILE_DIVISOR=", text) + self.assertNotIn("PROPTEST_CASES=", text) + + def test_pdf_contracts_are_separate_and_uncapped(self): + text = (ROOT / ".github/workflows/full-validation.yml").read_text() + pdf = text.split(" pdf-contracts:", 1)[1] + self.assertIn("RUSTFLAGS=--cfg craft_pdf_unicode_fixtures", pdf) + self.assertIn("unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES", pdf) + self.assertIn("cargo test -p craft-pdf --all-features --locked", pdf) + self.assertIn("cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked", pdf) + self.assertIn("select-os: '[]'", pdf) + self.assertIn("windows-latest", pdf) + self.assertIn("macos-latest", pdf) + + + +class PackageFormatting(unittest.TestCase): + @staticmethod + def helper(): + import importlib.util + spec = importlib.util.spec_from_file_location("ci_format_workspace", ROOT / "scripts/ci-format-workspace.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + @staticmethod + def metadata(): + return {"workspace_members": ["id-b", "id-a"], "workspace_default_members": ["id-a"], + "packages": [{"id": "id-a", "name": "craft-a"}, + {"id": "id-b", "name": "craft-b"}, + {"id": "external", "name": "not-a-member"}]} + + def test_all_workspace_members_not_only_defaults_and_no_external_dependencies(self): + helper = self.helper() + self.assertEqual(helper.workspace_names(self.metadata()), ["craft-a", "craft-b"]) + + def test_new_package_automatically_included(self): + helper = self.helper() + data = self.metadata() + data["workspace_members"].append("id-new") + data["packages"].append({"id": "id-new", "name": "craft-new"}) + self.assertEqual(helper.workspace_names(data), ["craft-a", "craft-b", "craft-new"]) + + def test_bad_inventory_fails_closed(self): + helper = self.helper() + for members in ([], ["id-a", "id-a"], ["missing"]): + data = self.metadata() + data["workspace_members"] = members + with self.subTest(members=members), self.assertRaises((ValueError, KeyError)): + helper.workspace_names(data) + for name in ("--all", "craft-a;echo injected", "craft-a", ""): + data = self.metadata() + data["packages"][1]["name"] = name + with self.subTest(name=name), self.assertRaises(ValueError): + helper.workspace_names(data) + + def test_calls_cargo_with_one_package_and_no_shell(self): + import json + helper = self.helper() + result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata())) + with patch.object(helper.subprocess, "run", return_value=result) as execute: + helper.check_workspace() + self.assertEqual([call.args[0] for call in execute.call_args_list], [ + ["cargo", "metadata", "--no-deps", "--offline", "--locked", "--format-version", "1"], + ["cargo", "fmt", "--check", "--package", "craft-a"], + ["cargo", "fmt", "--check", "--package", "craft-b"], + ]) + self.assertEqual(execute.call_args_list[0].kwargs["encoding"], "utf-8") + for call in execute.call_args_list: + self.assertEqual(call.kwargs["cwd"], ROOT) + self.assertTrue(call.kwargs["check"]) + self.assertNotIn("shell", call.kwargs) + + def test_metadata_failure_prevents_formatting(self): + helper = self.helper() + failure = subprocess.CalledProcessError(17, ["cargo", "metadata"]) + with patch.object(helper.subprocess, "run", side_effect=failure) as execute: + with self.assertRaises(subprocess.CalledProcessError): + helper.check_workspace() + self.assertEqual(execute.call_count, 1) + + def test_first_format_failure_stops_later_packages(self): + import json + helper = self.helper() + result = subprocess.CompletedProcess([], 0, stdout=json.dumps(self.metadata())) + failure = subprocess.CalledProcessError(17, ["cargo", "fmt"]) + with patch.object(helper.subprocess, "run", side_effect=[result, failure]) as execute: + with self.assertRaises(subprocess.CalledProcessError): + helper.check_workspace() + self.assertEqual(execute.call_count, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/test-workspace-concurrency.py b/scripts/test-workspace-concurrency.py index 96bfae3047..db20031e9a 100644 --- a/scripts/test-workspace-concurrency.py +++ b/scripts/test-workspace-concurrency.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""Check the Workspace workflow's pull-request-only cancellation policy. +"""Check the Workspace workflow's cancellation policy: pull requests and pushes to main cancel the +run they supersede; release tags, manual runs and scheduled runs are never cancelled. The policy is the top-level `concurrency` block of .github/workflows/workspace.yml. This script reads those fields, requires the documented expression shapes, and checks which group each event @@ -21,16 +22,28 @@ except ImportError: yaml = None DEFAULT_WORKFLOW = Path(__file__).resolve().parent.parent / ".github" / "workflows" / "workspace.yml" -PULL_REQUEST, PUSH, DISPATCH = "pull_request", "push", "workflow_dispatch" +PULL_REQUEST, PUSH, DISPATCH, SCHEDULE = "pull_request", "push", "workflow_dispatch", "schedule" -# The two shapes this policy may use. GitHub reads `a && b || c` as "b, or c when a is false"; these -# patterns are the whole of that expression language this script understands, so a reworded policy -# has to be reworded here too, on purpose. github.ref, never github.head_ref or github.sha. +# The runs that share a group per ref and cancel the run they supersede. GitHub reads `a || b && c` +# as `a || (b && c)`, and `x && github.ref || github.run_id` as "github.ref, or the run id when x is +# false". This exact condition is the whole of the expression language this script understands, so +# a reworded policy has to be reworded here too, on purpose. github.ref, never github.head_ref or +# github.sha. +SUPERSEDED = "github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main'" GROUP_SHAPE = re.compile( - r"(?P[A-Za-z0-9._-]+)-\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*" + r"(?P[A-Za-z0-9._-]+)-\$\{\{\s*\(\s*(?P[^()]+?)\s*\)\s*" r"&&\s*github\.ref\s*\|\|\s*github\.run_id\s*\}\}" ) -CANCEL_SHAPE = re.compile(r"\$\{\{\s*github\.event_name\s*==\s*'(?P[a-z_]+)'\s*\}\}") +CANCEL_SHAPE = re.compile(r"\$\{\{\s*(?P[^{}]+?)\s*\}\}") + + +def normal(expression): + return re.sub(r"\s+", " ", expression).strip() + + +def superseded(event_name, ref): + """SUPERSEDED, evaluated.""" + return event_name == PULL_REQUEST or (event_name == PUSH and ref == "refs/heads/main") def read_concurrency(text): @@ -72,22 +85,25 @@ def other_run(event_name, ref, run_id): MAIN, TAG = ("refs/heads/main", "refs/tags/v1.2.3") SAME_GROUP = [ ("a newer commit on the same pull request", pull_request(1316, 43599251877), pull_request(1316, 43600899878)), - ("a rerun of one main run", other_run(PUSH, MAIN, 7001), other_run(PUSH, MAIN, 7001)), + ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), ] DIFFERENT_GROUPS = [ ("two pull requests", pull_request(1316, 1), pull_request(1317, 1)), ("the same branch name in two forks", pull_request(1316, 2), pull_request(1400, 2)), - ("two pushes to main", other_run(PUSH, MAIN, 3), other_run(PUSH, MAIN, 4)), ("two release tag runs", other_run(PUSH, TAG, 5), other_run(PUSH, TAG, 6)), ("two manual runs", other_run(DISPATCH, MAIN, 7), other_run(DISPATCH, MAIN, 8)), + ("two scheduled runs", other_run(SCHEDULE, MAIN, 15), other_run(SCHEDULE, MAIN, 16)), + ("a main push and a scheduled run", other_run(PUSH, MAIN, 17), other_run(SCHEDULE, MAIN, 17)), + ("a main push and a manual run of main", other_run(PUSH, MAIN, 18), other_run(DISPATCH, MAIN, 18)), ("a main push and a pull request", other_run(PUSH, MAIN, 9), pull_request(1316, 9)), ("a release tag and a pull request", other_run(PUSH, TAG, 10), pull_request(1316, 10)), ] CANCELLATION = [ ("a push supersedes the previous run of its pull request", pull_request(1316, 11), True), - ("a push to main is never cancelled", other_run(PUSH, MAIN, 12), False), + ("a push to main supersedes the previous main run", other_run(PUSH, MAIN, 12), True), ("a release tag run is never cancelled", other_run(PUSH, TAG, 13), False), ("a manual run is never cancelled", other_run(DISPATCH, MAIN, 14), False), + ("the scheduled run that saves the caches is never cancelled", other_run(SCHEDULE, MAIN, 19), False), ] @@ -103,17 +119,17 @@ class ConcurrencyTests(unittest.TestCase): if not cls.group_shape or not cls.cancel_shape: raise AssertionError(f"the concurrency fields are not the documented shapes: {cls.fields}") - def cancels(self, event_name): - return event_name == self.cancel_shape["event"] + def cancels(self, event_name, ref): + return superseded(event_name, ref) def group(self, event_name, ref, run_id): - return self.group_shape["prefix"] + "-" + (ref if event_name == self.group_shape["event"] else str(run_id)) + return self.group_shape["prefix"] + "-" + (ref if superseded(event_name, ref) else str(run_id)) def test_policy_is_the_two_documented_fields(self): self.assertEqual(sorted(self.fields), ["cancel-in-progress", "group"]) self.assertEqual(self.group_shape["prefix"], "workspace") - self.assertEqual(self.group_shape["event"], PULL_REQUEST) - self.assertEqual(self.cancel_shape["event"], PULL_REQUEST) + self.assertEqual(normal(self.group_shape["condition"]), SUPERSEDED) + self.assertEqual(normal(self.cancel_shape["condition"]), SUPERSEDED) def test_a_scalar_concurrency_value_is_not_read_as_a_mapping(self): cases = { @@ -133,10 +149,10 @@ class ConcurrencyTests(unittest.TestCase): with self.subTest(description): self.assertNotEqual(self.group(*first), self.group(*second), description) - def test_only_a_pull_request_cancels(self): + def test_only_pull_requests_and_main_pushes_cancel(self): for description, context, expected in CANCELLATION: with self.subTest(description): - self.assertEqual(self.cancels(context[0]), expected, description) + self.assertEqual(self.cancels(context[0], context[1]), expected, description) def test_pyyaml_reads_the_same_fields(self): if yaml is None: diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py new file mode 100644 index 0000000000..ac65da9c15 --- /dev/null +++ b/scripts/test-workspace-tests.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Exercise the native workflow's command selection without compiling Rust.""" +import os +import re +import subprocess +import tomllib +import unittest +from unittest.mock import patch +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +WORKFLOW = ROOT / ".github/workflows/workspace.yml" + + +def block(text, name): + match = re.search(r"^ " + re.escape(name) + r": \|\n((?: .*\n|\n)+)", text, re.M) + if match is None: + raise AssertionError(f"missing command block: {name}") + return "\n".join(line[8:] for line in match[1].splitlines()) + + +# Only these literal programs may be exercised. Workflow text is compared, never executed. +LINT_SOURCE = """ +if [ "$RUNNER_OS" = Linux ]; then + python3 scripts/test-workspace-concurrency.py + python3 scripts/test-workspace-tests.py +fi +if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check +fi +cargo clippy --workspace --all-targets --locked -- -D warnings +cargo clippy --workspace --all-targets --all-features --locked -- -D warnings +""" +TEST_SOURCE = """ +cargo nextest run --workspace --all-features --locked --profile ci +cargo test --workspace --doc --all-features --locked +cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci +""" +WINDOWS_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'""" +EXPECTED_SOURCE = { + "lint-command": LINT_SOURCE, + "command": TEST_SOURCE, + "windows-command": WINDOWS_SETUP + "\n" + TEST_SOURCE, +} + + +def source_lines(source): + return [line.strip() for line in source.splitlines() + if line.strip() and not line.lstrip().startswith("#")] + + +def validate_source(text, name): + if name not in EXPECTED_SOURCE: + raise AssertionError(f"unsupported command block: {name}") + if source_lines(block(text, name)) != source_lines(EXPECTED_SOURCE[name]): + raise AssertionError(f"unexpected command source: {name}") + + +# The child shell only receives this checked-in literal, never bytes read from the workflow. +HARNESS = """ +cargo() { + printf '%s\\n' "$*" + if [ -n "$FAIL" ] && [ "$*" = "$FAIL" ]; then return 17; fi +} +python3() { :; } +case "$BLOCK" in + lint-command) +""" + LINT_SOURCE + """ + ;; + command) +""" + TEST_SOURCE + """ + ;; + *) exit 29 ;; +esac +""" + + +def commands(os_name, fail="", name="command", source=None): + validate_source(WORKFLOW.read_text() if source is None else source, name) + return subprocess.run( + ["bash", "-euo", "pipefail", "-c", HARNESS], + env={**os.environ, "RUNNER_OS": os_name, "FAIL": fail, "BLOCK": name}, + text=True, capture_output=True, check=False, + ) + + +COMMON = [ + "fmt --check", + "clippy --workspace --all-targets --locked -- -D warnings", + "clippy --workspace --all-targets --all-features --locked -- -D warnings", +] +TESTS = [ + "nextest run --workspace --all-features --locked --profile ci", + "test --workspace --doc --all-features --locked", + "nextest run -p craft-image-codecs -p craft-text --locked --profile ci", +] + + +class WorkspaceTests(unittest.TestCase): + def test_every_leg_lints_with_both_feature_sets(self): + # Windows skips only rustfmt: one call with every source root of the workspace is longer + # than a Windows command line may be (os error 206), and Linux and macOS check the same + # formatting. + for os_name, expected in (("Linux", COMMON), ("macOS", COMMON), ("Windows", COMMON[1:])): + with self.subTest(os=os_name): + result = commands(os_name, name="lint-command") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), expected) + + def test_linux_and_macos_run_one_feature_set_with_doctests(self): + for os_name in ("Linux", "macOS"): + with self.subTest(os=os_name): + result = commands(os_name) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), TESTS) + + def test_each_stage_failure_remains_fatal(self): + for name, stages in (("lint-command", COMMON), ("command", TESTS)): + for index, command in enumerate(stages): + with self.subTest(block=name, command=command): + result = commands("Linux", command, name) + self.assertEqual(result.returncode, 17, result.stderr) + self.assertEqual(result.stdout.splitlines(), stages[:index + 1]) + + def test_windows_runs_the_same_tests(self): + validate_source(WORKFLOW.read_text(), "windows-command") + source = block(WORKFLOW.read_text(), "windows-command") + cargo = [line.strip() for line in source.splitlines() if line.strip().startswith("cargo ")] + self.assertEqual(cargo, ["cargo " + command for command in TESTS]) + + def test_workflow_source_is_rejected_before_starting_any_process(self): + source = WORKFLOW.read_text() + for payload in ("cargo fmt --check; echo injected", "cargo fmt $(echo injected)", + "cargo fmt --check | cat", "cargo fmt --check > injected", + "echo injected", "cargo fmt --check\n touch injected"): + with self.subTest(payload=payload), patch("subprocess.run") as child: + changed = source.replace("cargo fmt --check", payload, 1) + with self.assertRaisesRegex(AssertionError, "unexpected command source"): + commands("Linux", name="lint-command", source=changed) + child.assert_not_called() + + def test_added_or_missing_stage_is_rejected_before_execution(self): + source = WORKFLOW.read_text() + for replacement in ("", "cargo fmt --check\n cargo fmt --check"): + with self.subTest(replacement=replacement), patch("subprocess.run") as child: + with self.assertRaisesRegex(AssertionError, "unexpected command source"): + commands("Linux", name="lint-command", + source=source.replace("cargo fmt --check", replacement, 1)) + child.assert_not_called() + + def test_ci_profile_keeps_its_failure_policy_without_retries_or_filtering(self): + config = tomllib.loads((ROOT / ".config/nextest.toml").read_text()) + self.assertIs(config["profile"]["ci"]["fail-fast"], False) + for profile in config["profile"].values(): + self.assertNotIn("default-filter", profile) + self.assertNotIn("retries", profile) + self.assertEqual(config["profile"]["ci"]["slow-timeout"], {"period": "60s"}) + + def test_unix_resource_groups_are_serial_and_leave_windows_alone(self): + config = tomllib.loads((ROOT / ".config/nextest.toml").read_text()) + overrides = config["profile"]["ci"]["overrides"] + self.assertEqual(overrides, [ + {"platform": "cfg(unix)", + "filter": "package(craft-ui) | package(craft-keymap) | package(craft-update)", + "test-group": "gpu"}, + {"platform": "cfg(unix)", "filter": "package(craft-video) & kind(test)", + "test-group": "video-integration"}, + ]) + for override in overrides: + self.assertEqual(config["test-groups"][override["test-group"]]["max-threads"], 1) + + def test_workflow_stays_shared_and_keeps_platform_gates(self): + source = WORKFLOW.read_text() + self.assertIn("uses: storytold/craft-common-actions/.github/workflows/gate.yml@main", source) + self.assertIn('os: \'["ubuntu-latest","windows-latest","macos-latest"]\'', source) + self.assertIn(" msrv:", source) + self.assertIn(" wasm:", source) + self.assertIn("python3 scripts/test-workspace-tests.py", block(source, "lint-command")) + + +if __name__ == "__main__": + unittest.main() +